text
stringlengths 180
608k
|
---|
[Question]
[
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a ["cat program"](http://esolangs.org/wiki/Cat): read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility `cat` it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.
### Task
You should write a **full program** which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's `prompt` and `alert`). These are the *only* admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.
The output should contain exactly the input and *nothing else*. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. **This also applies to trailing newlines.** If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)
Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. *If you do this, I encourage you to add an error-free version to your answer as well (for reference).*
As this is intended as a challenge within each language and not between languages, there are a few language specific rules:
* If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).
* If it is at all possible in your language to support an *arbitrary* infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example `yes | tr -d \\n | ./my_cat` should print an infinite stream of `y`s. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).
Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.
### Additional rules
* This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in *every* language. Therefore, no answer will be marked as accepted.
* Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.
Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/).
* Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
Also note that languages *do* have to fulfil [our usual criteria for programming languages](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073).
* If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
* Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, including the <http://meta.codegolf.stackexchange.com/q/1061>.
As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.
### Catalogue
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62230; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# sed, 0
```
```
The empty `sed` program does exactly what is required here:
```
$ printf "abc\ndef" | sed ''
abc
def$
```
[Answer]
# [Ziim](http://esolangs.org/wiki/Ziim), ~~222~~ ~~201~~ ~~196~~ ~~185~~ 182 bytes
```
↓ ↓
↓ ↓ ↓
↗ ↗↙↔↘↖ ↖
↓↓⤡⤢ ⤢↙
↘ ↖⤡ ↖
↙
↕↘ ↑ ↙
→↘↖↑ ↙ ↑
→↖ ↑
→↖↘ ↙
↑↓↑
⤡
```
This will probably not display correctly in your browser, so here is a diagram of the code:
[![enter image description here](https://i.stack.imgur.com/K0S8k.png)](https://i.stack.imgur.com/K0S8k.png)
I can't think of a simpler *structure* to solve the problem in Ziim, but I'm sure the actual code is still quite golfable.
Ziim cannot possibly handle infinite streams because it is only possible to print anything at the end of the program.
## Explanation
Since Ziim has a rather unique, declarative control flow model an imperative pseudocode algorithm won't cut it here. Instead, I'll explain the basics of Ziim and the present the tidied up structure of the above code (in a similar graphical manner) as ASCII art.
Control flow in Ziim happens all over the place: each arrow which isn't pointed at by another arrow initialises a "thread" which is processed independently of the others (not really in parallel, but there are no guarantees which order they are processed in, unless you sync them up via concatenation). Each such thread holds a list of binary digits, starting as `{0}`. Now each arrow in the code is some sort of command which has one or two inputs and one or two outputs. The exact command depends on how many arrows are pointing at it from which orientations.
Here is the list of the commands, where `m -> n` indicates that the command takes `m` inputs and produces `n` outputs.
* `1 -> 1`, **no-op**: simply redirects the thread.
* `1 -> 1`, **invert**: negates each bit in the thread (and also redirects it).
* `1 -> 1`, **read**: replaces the thread's value by the next *bit* from STDIN, or by the empty list if we've hit EOF.
* `2 -> 1`, **concatenate**: this is the only way to sync threads. When a thread hits one side of the arrow, it will be suspended until another thread hits the other side. At that point they will be concatenated into a single thread and continue execution.
* `2 -> 1`, **label**: this is the only way to join different execution paths. This is simply a no-op which has two possible inputs. So threads entering the "label" via either route will simply be redirected into the same direction.
* `1 -> 2`, **split**: takes a single thread, and sends two copies off in different directions.
* `1 -> 1`, **isZero?**: consumes the first bit of the thread, and sends the thread in one of two directions depending on whether the bit was 0 or 1.
* `1 -> 1`, **isEmpty?**: consumes the entire list (i.e. replaces it with an empty list), and sends the thread in one of two direction depending on whether the list was already empty or not.
So with that in mind, we can figure out a general strategy. Using *concatenate* we want to repeatedly append new bits to a string which represents the entire input. We can simply do this by looping the output of the *concatenate* back into one of its inputs (and we initialise this to an empty list, by clearing a `{0}` with *isEmpty?*). The question is how we can terminate this process.
In addition to appending the current bit we will also *prepend* a 0 or 1 indicating whether we've reached EOF. If we send our string through *isZero?*, it will get rid of that bit again, but let us distinguish the end of the stream, in which case we simply let the thread leave the edge of the grid (which causes Ziim to print the thread's contents to STDOUT and terminate the program).
Whether we've reached EOF or not can be determined by using *isEmpty?* on a copy of the input.
Here is the diagram I promised:
```
+----------------------------+ {0} --> isEmpty --> label <--+
| | n | |
v | v |
{0} --> label --> read --> split --> split ------------------> concat |
| | |
n v y | |
inv --> label --> concat <-- isEmpty --> concat <-- label <-- {0} | |
^ ^ | | ^ | |
| | v v | | |
{0} +------- split ---> label <--- split -------+ | |
| | |
+-------------> concat <------------+ |
| |
y v |
print and terminate <-- isZero --------------------+
```
Some notes about where to start reading:
* The `{0}` in the top left corner is the initial trigger which starts the input loop.
* The `{0}` towards the top right corner is immediately cleared to an empty list an represents the initial string which we'll gradually fill with the input.
* The other two `{0}`s are fed into a "producer" loop (one inverted, one not), to give us an unlimited supply of `0`s and `1`s which we need to prepend to the string.
[Answer]
# [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes
This used to be 3 bytes (see below), but that version no long works since the latest update of the language. As I never intentionally introduced the error that version made use of, I decided not to count it.
---
An error-free solution (i.e. one which works with the fixed interpreter) turns out to be much trickier. I've had some trouble squeezing it into a 2x2 grid, but I found one solution now, although I need the full **7 bytes**:
```
<)@,;.(
```
After unfolding, we get:
[![enter image description here](https://i.stack.imgur.com/HsRLD.png)](https://i.stack.imgur.com/HsRLD.png)
Since the initial memory edge is 0, the `<` unconditionally deflects the instruction pointer into the North-East diagonal, where it wraps to the the grey path. The `.` is a no-op. Now `,` reads a byte, `)` increments it such that valid bytes (including null bytes) are positive and EOF is 0.
So on EOF, the IP wraps to red path, where `@` terminates the program. But if we still read a byte, then the IP wraps to the green path is instead where `(` decrements the edge to the original value, before `;` prints it to STDOUT. The IP now wraps unconditionally back to the grey path, repeating the process.
---
After writing [a brute force script](https://codegolf.stackexchange.com/a/62812/8478) for my Truth Machine answer, I set it to find an error-free **6-byte** solution for the cat program as well. Astonishingly, it did find one - yes, exactly one solution in all possible 6-byte Hexagony programs. After the 50 solutions from the truth machine, that was quite surprising. Here is the code:
```
~/;,@~
```
Unfolding:
[![enter image description here](https://i.stack.imgur.com/pjs2D.png)](https://i.stack.imgur.com/pjs2D.png)
The use of `~` (unary negation) instead of `()` is interesting, because a) it's a no-op on zero, b) it swaps the sides of the branch, c) in some codes a single `~` might be used twice to undo the operation with itself. So here is what's going on:
The first time (purple path) we pass through `~` it's a no-op. The `/` reflects the IP into the North-West diagonal. The grey path now reads a character and multiplies its character code by `-1`. This turns the EOF (`-1`) into a truthy (positive) value and all valid characters into falsy (non-positive) values. In the case of EOF, the IP takes the red path and the code terminates. In the case of a valid character, the IP takes the green path, where `~` undoes negation and `;` prints the character. Repeat.
---
Finally, here is the 3-byte version which used to work in the original version Hexagony interpreter.
```
,;&
```
Like the Labyrinth answer, this terminates with an error if the input stream is finite.
After unfolding the code, it corresponds to the following hex grid:
[![enter image description here](https://i.stack.imgur.com/xNuWk.png)](https://i.stack.imgur.com/xNuWk.png)
The `.` are no-ops. Execution starts on the purple path.
`,` reads a byte, `;` writes a byte. Then execution continues on the salmon(ish?) path. We need the `&` to reset the current memory edge to zero, such that the IP jumps back to the purple row when hitting the corner at the end of the second row. Once `,` hits EOF it will return `-1`, which causes an error when `;` is trying to print it.
---
Diagrams generated with [Timwi](https://codegolf.stackexchange.com/users/668/timwi)'s amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer).
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 0 bytes
TeaScript is a concise golfing language compiled to JavaScript
```
```
In a recent update the input is implicitly added as the first property.
[Try it online](http://vihanserver.tk/p/TeaScript/?code=x&input=foobar%0Appcg%0Ahello%20world)
---
### Alternatively, 1 byte
```
x
```
`x` contains the input in TeaScript. Output is implicit
[Answer]
## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 44 bytes
```
#{<{,+?+}_+{-?>}<?
_}>?>+<<<{>?_}>>.<+<+{<{?
```
I originally created this language for [Create a programming language that only appears to be unusable](https://codegolf.stackexchange.com/a/63121/8478). It turns out to be a very nice exercise to golf simple problems in it though.
**The Basics:** Each of the two lines defines a Brainfuck-like program which operates on the other program's source code - the first program is called Brian and the second is called Chuck. Only Brian can read and only Chuck can write. Instead of Brainfuck's loops you have `?` which passes control to the other program (and the roles of instruction pointer and tape head change as well). An addition to Brainfuck is `{` and `}` which scan the tape for the first non-zero cell (or the left end). Also, `_` are replaced with null bytes.
While I don't think this is optimal yet, I'm quite happy with this solution. My first attempt was 84 bytes, and after several golfing sessions with Sp3000 (and taking some inspiration from his attempts), I managed to get it slowly down to 44, a few bytes at a time. Especially the brilliant `+}+` trick was his idea (see below).
### Explanation
Input is read into the first cell on Chuck's tape, then painstakingly copied to the end of Brian's tape, where it's printed. By copying it to the end, we can save bytes on setting the previous character to zero.
The `#` is just a placeholder, because switching control does not execute the cell we switched on. `{<{` ensures that the tape head is on Chuck's first cell. `,` reads a byte from STDIN or `-1` if we hit EOF. So we increment that with `+` to make it zero for EOF and non-zero otherwise.
Let's assume for now we're not at EOF yet. So the cell is positive and `?` will switch control to Chuck. `}>` moves the tape head (on Brian) to the `+` the `_` and `?` passes control back to Brian.
`{-` now decrements the first cell on Chuck. If it's not zero yet, we pass control to Chuck again with `?`. This time `}>` moves the tape head on Brian two cells of the right of the last non-zero cell. Initially that's here:
```
#{<{,+?+}_+{-?>}<?__
^
```
But later on, we'll already have some characters there. For instance, if we've already read and printed `abc`, then it would look like this:
```
#{<{,+?+}_+{-?>}<?11a11b11c__
^
```
Where the `1`s are actually 1-bytes (we'll see what that's about later).
This cell will always be zero, so this time `?` *won't* change control. `>` moves yet another cell to the right and `+` increments that cell. This is why the first character in the input ends up three cells to the right of the `?` (and each subsequent one three cells further right).
`<<<` moves back to the last character in that list (or the `?` if it's the first character), and `{>` goes back to the `+` on Brian's tape to repeat the loop, which slowly transfers the input cell onto the end of Brian's tape.
Once that input cell is empty the `?` after `{-` will not switch control any more. Then `>}<` moves the tape head on Chuck to the `_` and switches control such that Chuck's second half is executed instead.
`}>>` moves to the cell we've now written past the end of Brian's tape, which is the byte we've read from STDIN, so we print it back with `.`. In order for `}` to run past this new character on the tape we need to close the gap of two null bytes, so we increment them to `1` with `<+<+` (so that's why there are the 1-bytes between the actual characters on the final tape). Finally `{<{` moves back to the beginning of Brian's tape and `?` starts everything from the beginning.
You might wonder what happens if the character we read was a null-byte. In that case the newly written cell would itself be zero, but since it's at the end of Brian's tape and we don't care *where* that end is, we can simply ignore that. That means if the input was `ab\0de`, then Brian's tape would actually end up looking like:
```
#{<{,+?+}_+{-?>}<?11a11b1111d11e
```
Finally, once we hit EOF that first `?` on Brian's tape will be a no-op. At this point we terminate the program. The naive solution would be to move to the end of Chuck's tape and switch control, such that the program termiantes: `>}>}<?`. This is where Sp3000's really clever idea saves three bytes:
`+` turns Chuck's first cell into `1`. That means `}` has a starting point and finds the `_` in the middle of Chuck's tape. Instead of skipping past it, we simply close the gap by turning it into a `1` with `+` as well. Now let's see what the rest of Brian's code happens to do with this modified Chuck...
`{` goes back to Chuck's first cell as usual, and `-` turns it back into a null-byte. That means that `?` is a no-op. But now `>}<`, which usually moved the tape head to the middle of Chuck's tape, moves right past it to the end of Chuck's tape and `?` then passes control to Chuck, terminating the code. It's nice when things just work out... :)
[Answer]
# Haskell, 16 bytes
```
main=interact id
```
`interact` reads the input, passes it to the function given as its argument and prints the result it receives. `id` is the identity function, i.e. it returns its input unchanged. Thanks to Haskell's laziness `interact` can work with infinite input.
[Answer]
## sh + binutils, ~~3~~ 2 bytes
```
dd
```
Well, not quite as obvious. From @Random832
## Original:
```
cat
```
The painfully obvious... :D
[Answer]
# [Motorola MC14500B Machine Code](https://en.wikipedia.org/wiki/Motorola_MC14500B), 1.5 bytes
Written in hexadecimal:
```
18F
```
Written in binary:
```
0001 1000 1111
```
---
### Explanation
```
1 Read from I/O pin
8 Output to I/O pin
F Loop back to start
```
The opcodes are 4 bits each.
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), 16 bytes
```
╔═╗
╚╤╝
```
(Encoded as UTF-16 with a BOM)
## Explanation
The box returns the contents of STDIN. The loose end outputs it.
[Answer]
# [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 41 bytes
```
Take Northern Line to Mornington Crescent
```
I have no idea whether Mornington Crescent can handle null bytes, and all input is read before the program starts, as that is the nature of the language.
[Answer]
# Brainfuck, 5 bytes
```
,[.,]
```
Equivalent to the pseudocode:
```
x = getchar()
while x != EOF:
putchar(x)
x = getchar()
```
This handles infinite streams, but treats null bytes as EOF. Whether or not BF *can* handle null bytes correctly varies from implementation to implementation, but this assumes the most common approach.
[Answer]
# [Labyrinth](https://github.com/mbuettner/labyrinth), 2 bytes
```
,.
```
If the stream is finite, this will terminate with an error, but all the output produce by the error goes to STDERR, so the standard output stream is correct.
As in Brainfuck `,` reads a byte (pushing it onto Labyrinth's main stack) and `.` writes a byte (popping it from Labyrinth's main stack).
The reason this loops is that both `,` and `.` are "dead ends" in the (very trivial) maze represented by the source code, such that the instruction pointer simply turns around on the spot and moves back to the other command.
When we hit EOF `,` pushes `-1` instead and `.` throws an error because `-1` is not a valid character code. This might actually change in the future, but I haven't decided on this yet.
---
For reference, we can solve this without an error in **6 bytes** as follows
```
,)@
.(
```
Here, the `)` increments the byte we read, which gives `0` at EOF and something positive otherwise. If the value is `0`, the IP moves straight on, hitting the `@` which terminates the program. If the value was positive, the IP will instead take a right-turn towards the `(` which decrements the top of the stack back to its original value. The IP is now in a corner and will simply keep making right turns, printing with `.`, reading a new byte with `.`, before it hits the fork at `)` once again.
[Answer]
# X86 assembly, 70 bytes
Disassembly with `objdump`:
```
00000000 <.data>:
0: 66 83 ec 01 sub sp,0x1
4: 66 b8 03 00 mov ax,0x3
8: 00 00 add BYTE PTR [eax],al
a: 66 31 db xor bx,bx
d: 66 67 8d 4c 24 lea cx,[si+0x24]
12: ff 66 ba jmp DWORD PTR [esi-0x46]
15: 01 00 add DWORD PTR [eax],eax
17: 00 00 add BYTE PTR [eax],al
19: cd 80 int 0x80
1b: 66 48 dec ax
1d: 78 1c js 0x3b
1f: 66 b8 04 00 mov ax,0x4
23: 00 00 add BYTE PTR [eax],al
25: 66 bb 01 00 mov bx,0x1
29: 00 00 add BYTE PTR [eax],al
2b: 66 67 8d 4c 24 lea cx,[si+0x24]
30: ff 66 ba jmp DWORD PTR [esi-0x46]
33: 01 00 add DWORD PTR [eax],eax
35: 00 00 add BYTE PTR [eax],al
37: cd 80 int 0x80
39: eb c9 jmp 0x4
3b: 66 b8 01 00 mov ax,0x1
3f: 00 00 add BYTE PTR [eax],al
41: 66 31 db xor bx,bx
44: cd 80 int 0x80
```
The source:
```
sub esp, 1
t:
mov eax,3
xor ebx,ebx
lea ecx,[esp-1]
mov edx,1
int 0x80
dec eax
js e
mov eax,4
mov ebx,1
lea ecx,[esp-1]
mov edx,1
int 0x80
jmp t
e:
mov eax,1
xor ebx,ebx
int 0x80
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 7 bytes
```
i:0(?;o
```
Try it [here](http://fishlanguage.com/playground/u7ttRxRqTCymDDNe6).
Explanation:
```
i:0(?;o
i Take a character from input, pushing -1 if the input is empty
:0( Check if the input is less than 0, pushing 1 if true, 0 if false
?; Pop a value of the top of the stack, ending the program if the value is non-zero
o Otherwise, output then loop around to the left and repeat
```
If you want it to keep going until you give it more input, replace the `;` with `!`.
[Answer]
# [Universal Lambda](https://esolangs.org/wiki/Universal_Lambda), 1 byte
```
!
```
A Universal Lambda program is an encoding of a lambda term in binary, chopped into chunks of 8 bits, padding incomplete chunks with *any* bits, converted to a byte stream.
The bits are translated into a lambda term as follows:
* `00` introduces a lambda abstraction.
* `01` represents an application of two subsequent terms.
* `111..10`, with *n* repetitions of the bit `1`, refers to the variable of the *n*th parent lambda; i.e. it is a [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index) in unary.
By this conversion, `0010` is the identity function `λa.a`, which means any single-byte program of the form `0010xxxx` is a `cat` program.
[Answer]
# C, 40 bytes
```
main(i){while(i=~getchar())putchar(~i);}
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~6~~ 5 bytes
*Now handles null bytes!*
```
@_i?o
```
Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube.
[Test it online!](https://ethproductions.github.io/cubix) Note: there's a 50 ms delay between iterations.
## Explanation
The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops `.` until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above:
```
@
_ i ? o
.
```
Now the code is run. The IP (instruction pointer) starts out on the far left face, pointing east.
The first char the IP encounters is `_`, which is a mirror that turns the IP around if it's facing north or south; it's currently facing east, so this does nothing. Next is `i`, which inputs a byte from STDIN. `?` turns the IP left if the top item is negative, or right if it's positive. There are three possible paths here:
* If the inputted byte is -1 (EOF), the IP turns left and hits `@`, which terminates the program.
* If the inputted byte is 0 (null byte), the IP simply continues straight, outputting the byte with `o`.
* Otherwise, the IP turns right, travels across the bottom face and hits the mirror `_`. This turns it around, sending it back to the `?`, which turns it right again and outputs the byte.
I think this program is optimal. Before Cubix could handle null bytes (EOF was 0, not -1), this program worked for everything but null bytes:
```
.i!@o
```
---
I've written a [brute-forcer](https://jsfiddle.net/09z5sr3o/3/) to find all 5-byte cat programs. Though it takes ~5 minutes to finish, the latest version has found 5 programs:
```
@_i?o (works as expected)
@i?o_ (works in exactly the same way as the above)
iW?@o (works as expected)
?i^o@ (false positive; prints U+FFFF forever on empty input)
?iWo@ (works as expected)
```
[Answer]
## PowerShell, ~~88~~ ~~41~~ 30 Bytes
```
$input;write-host(read-host)-n
```
EDIT -- forgot that I can use the `$input` automatic variable for pipeline input ... EDIT2 -- don't need to test for existence of `$input`
Yeah, so ... STDIN in PowerShell is ... weird, shall we say. With the assumption that we need to accept input from *all* types of STDIN, this is one possible answer to this catalogue, and I'm sure there are others.1
Pipeline input in PowerShell doesn't work as you'd think, though. Since piping in PowerShell is a function of the language, and not a function of the environment/shell (and PowerShell isn't really *solely* a language anyway), there are some quirks to behavior.
For starters, and most relevant to this entry, the pipe isn't evaluated instantaneously (most of the time). Meaning, if we have `command1 | command2 | command3` in our shell, `command2` will not take input or start processing until `command1` completes ... *unless* you encapsulate your `command1` with a `ForEach-Object` ... which is *different* than `ForEach`. (even though `ForEach` is an alias for `ForEach-Object`, but that's a separate issue, since I'm talking `ForEach` as the statement, not alias)
This would mean that something like `yes | .\simple-cat-program.ps1` (even though `yes` doesn't really exist, but whatever) wouldn't work because `yes` would never complete. If we could do `ForEach-Object -InputObject(yes) | .\simple-cat-program.ps1` that should (in theory) work.
[Getting to Know ForEach and ForEach-Object](http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/08/getting-to-know-foreach-and-foreach-object.aspx) on the Microsoft "Hey, Scripting Guy!" blog.
So, all those paragraphs are explaining why `if($input){$input}` exists. We take an input parameter that's specially created automatically if pipeline input is present, test if it exists, and if so, output it.
Then, we take input from the user `(read-host)` via what's essentially a separate STDIN stream, and `write-host` it back out, with the `-n` flag (short for `-NoNewLine`). Note that this does not support arbitrary length input, as `read-host` will only complete when a linefeed is entered (technically when the user presses "Enter", but functionally equivalent).
Phew.
1But there are other options:
For example, if we were concerned with *only* pipeline input, and we didn't require a full program, you could do something like `| $_` which would just output whatever was input. (In general, that's somewhat redundant, since PowerShell has an implicit output of things "left behind" after calculations, but that's an aside.)
If we're concerned with only interactive user input, we could use just `write-host(read-host)-n`.
~~Additionally, this function has the ~~quirk~~ feature of accepting command-line input, for example `.\simple-cat-program.ps1 "test"` would populate (and then output) the `$a` variable.~~
[Answer]
# [MarioLANG](http://esolangs.org/wiki/MarioLANG#Examples), 11 bytes
```
,<
."
>!
=#
```
I'm not entirely sure this is optimal, but it's the shortest I found.
This supports infinite streams and will terminate with an error upon reaching EOF (at least the Ruby reference implementation does).
There's another version of this which turns Mario into a ninja who can double jump:
```
,<
.^
>^
==
```
In either case, Mario starts falling down the left column, where `,` reads a byte and `.` writes a byte (which throws an error at EOF because `,` doesn't return a valid character). `>` ensures that Mario walks to the right (`=` is just a ground for him to walk on). Then he moves up, either via a double jump with `^` or via an elevator (the `"` and `#` pair) before the `<` tells him to move back to the left column.
[Answer]
## [INTERCALL](https://github.com/theksp25/INTERCALL), 133 bytes
wat
```
INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
READ
PRINT
GOTO I
```
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 0 bytes
```
```
Seriously. rs just prints whatever it gets if the given script is completely empty.
[Answer]
# Vitsy, 2 bytes
```
zZ
```
`z` gets all of the input stack and pushes it to the active program stack. `Z` prints out all of the active stack to STDOUT.
Alternate method:
```
I\il\O
I\ Repeat the next character for input stack's length.
i Grab an item from the input.
l\ Repeat the next character for the currently active program stack's length.
O Output the top item of the stack as a character.
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 0 bytes
[Try it online!](http://v.tryitonline.net/#code=&input=VGhlIGVtcHR5IHByb2dyYW0gcHJpbnRzIGl0cyBpbnB1dC4g)
V's idea of "memory" is just a gigantic 2D array of characters. Before any program is ran, all input it loaded into this array (known as "The Buffer"). Then, at the end of any program, all text in the buffer is printed.
In other words, the empty program *is* a cat program.
[Answer]
## [Half-Broken Car in Heavy Traffic](http://esolangs.org/wiki/Half-Broken_Car_in_Heavy_Traffic), 9 + 3 = 12 bytes
```
#<
o^<
v
```
Half-Broken Car in Heavy Traffic (HBCHT) takes input as command line args, so run like
```
py -3 hbcht cat.hbc -s "candy corn"
```
Note that the +3 is for the `-s` flag, which outputs as chars. Also, HBCHT doesn't seem handle NULs, as all zeroes are dropped from the output (e.g. `97 0 98` is output as two chars `ab`).
### Explanation
In HBCHT, your car starts at the `o` and your goal is the exit `#`. `^>v<` direct the car's movement, while simultaneously modifying a BF-like tape (`^>v<` translate to `+>-<`). However, as the language name suggests, your car can only turn right – any attempts to turn left are ignored completely (including their memory effects). Note that this is only for turning – your car is perfectly capable of driving forward/reversing direction.
Other interesting parts about HBCHT are that your car's initial direction is randomised, and the grid is toroidal. Thus we just need the car to make it to the exit without modifying the tape for all four initial directions:
* Up and down are straightforward, heading directly to the exit.
* For left, we wrap and execute `<` and increment with `^`. We can't turn left at the next `<` so we wrap and decrement with `v`, negating out previous increment. Since we're heading downwards now we can turn right at the `<` and exit, having moved the pointer twice and modifying no cell values.
* For right, we do the same thing as left but skip the first `^` since we can't turn left.
---
**Edit**: It turns out that the HBCHT interpreter does let you execute just a single path via a command line flag, e.g.
```
py -3 hbcht -d left cat.hbc
```
However, not only is the flag too expensive for this particular question (at least 5 bytes for `" -d u"`), it seems that all paths still need to be able to make it to the exit for the code to execute.
[Answer]
# [Seed](https://github.com/TryItOnline/seed), ~~3883~~ ~~3864~~ 10 bytes
```
4 35578594
```
[Try it online!](https://tio.run/##K05NTfn/30TB2NTU3MLU0uT//8SkZAA "Seed – Try It Online")
This is one of the stupidest things I have ever done.
[Answer]
# GolfScript, 3 bytes
```
:n;
```
The empty program echoes standard input. The language cannot possibly handle infinite streams. However, it appends a newline, as @Dennis mentioned. It does so by wrapping the whole stack in an array and calling `puts`, which is defined as `print n print`, where `n` is a newline. However, we can redefine `n` to be STDIN, and then empty the stack, which is precisely what `:n;` does.
[Answer]
## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), 15 chars
```
(:vGsP10wRsp;bD
```
Taken [directly from Snowman's `examples` directory](https://github.com/KeyboardFire/snowman-lang/blob/master/examples/cat.snowman). Reads a line, prints a line, reads a line, prints a line...
Note that due to an implementation detail, when STDIN is empty, `vg` will return the same thing as it would for an empty line. Therefore, this will repeatedly print newlines in an infinite loop once STDIN is closed. This may be fixed in a future version.
Explanation of the code:
```
( // set two variables (a and f) to active—this is all we need
:...;bD // a "do-loop" which continues looping as long as its "return value"
// is truthy
vGsP // read a line, print the line
10wRsp // print a newline—"print" is called in nonconsuming mode; therefore,
// that same newline will actually end up being the "return value" from
// the do-loop, causing it to loop infinitely
```
[Answer]
## [Minkolang](https://github.com/elendiastarman/Minkolang), 5 bytes
```
od?.O
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=od%3F%2EO&input=Hello%20world!)
### Explanation
`o` reads in a character from input and pushes its ASCII code onto the stack (`0` if the input is empty). `d` then duplicates the top of stack (the character that was just read in). `?` is a conditional trampoline, which jumps the next instruction of the top of stack is not `0`. If the input was empty, then the `.` is not jumped and the program halts. Otherwise, `O` outputs the top of stack as a character. The toroidal nature of Minkolang means that this loops around to the beginning.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 0 bytes
```
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIiLCIiLCIxIl0=)
Implicitly inputs then implicitly outputs. Stretching the rules a *teeny* bit. Specifically the following rule:
>
> The only exception being if your language absolutely always prints a trailing newline after execution.
>
>
>
In Vyxal, "printing after execution" (implicit, not explicit printing) always prints with a newline.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~50~~ 38 bytes
```
[“€¬((a=IO.‚Ø 9)!=:eof)€· IO.‡í€…„–“.E
```
[Try it online](https://tio.run/##yy9OTMpM/f8/@lHDnEdNaw6t0dBItPX013vUMOvwDAVLTUVbq9T8NE2Q1HYFsPjCw2uBvEcNyx41zHvUMBmoT8/1/3@P1JycfB2F8PyinBRFLiCoU3RQVlGNU9PS0IzX5kowNDI2MTUzt7A00LXlio6NsVbX0dPnqq6tsVKysbPn4goMdw0KiQz19A9wDHZxc/fw8vaJinAOc/Lz5XJ0cnZxBQp5AsV8/fwDAoOCQ0LDwiMio7i4CstTi0oqSzPzCxKLU9LSM7Kyc6oqksuS8nK5EpOSU1KBQplAsdy8/ILCouKS0rLyisoqAA "05AB1E – Try It Online") or [test an infinite stream](https://tio.run/##S0oszvifnFhiY@Pq72YXb12ZWlxTUqSgm6IQE5NXo59fUKKfX5yYlJkKpRTi/0c/apjzqGnNoTUaGom2nv56jxpmHZ6hYKmpaGuVmp@mCZLargAWX3h4LZD3qGHZo4Z5jxomA/Xpuf4H2vMfAA "Bash – Try It Online").
# Explanation
This is probably the first *real* 05AB1E cat posted here. While my previous answer (`?`) mostly worked...
>
> If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case.
>
>
>
And while there seems to be no way of doing this in 05AB1E, making `?` the shortest possible answer, there is one not very commonly used command that does the trick. `.E` pops a string and runs it as an Elixir program.
In this case, we use the following Elixir code:
```
a = IO.read(x)
if a != :eof do
IO.write(a)
end
```
…where `x` is the number of bytes to read each time — the greater it is, the faster the program runs. It can be anything but `:all`, as that would be equivalent to my previous submission, invalidating it.
We can golf this down to:
```
if((a=IO.read x)!=:eof)do IO.write a end
```
By now, you might've realized that this program only ever outputs the first `x` bytes of input. But running the Elixir code isn't the only thing the program does. It runs it over and over in an infinite loop (`[`)!
The weird symbols you see in the 05AB1E program are dictionary compression – compressing English words or other common letter combinations into just two bytes each. By substituting in `9` for `x` in the Elixir program (making the program as fast as it can be while not raising the bytecount), we get the final program!
] |
[Question]
[
**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.
SAT is the problem of determining whether a boolean expression can be made true. For example, (A) can be made true by setting A=TRUE, but (A && !A) can never be true. This problem is known to be NP-complete. See [Boolean Satisfiability](http://en.wikipedia.org/wiki/Boolean_satisfiability_problem).
Your task is to write a program for SAT that executes in polynomial time, but may not solve all cases.
For some examples, the reason it is not *really* polynomial could be because:
1. There is an edge case that is not obvious but has a poor runtime
2. The algorithm actually fails to solve the problem in some unexpected case
3. Some feature of the programming language you are using actually has a longer runtime than you would reasonably expect it to have
4. Your code actually does something totally different from what it looks like it's doing
You may use any programming language (or combination of languages) you wish. You do not need to provide a formal proof of your algorithm's complexity, but you should at least provide an explanation.
The primary criteria for judging should be how convincing the code is.
This is a popularity contest, so the highest rated answer in a week wins.
[Answer]
## C#
>
> Your task is to write a program for SAT that appears to execute in polynomial time.
>
>
>
"Appears" is unnecessary. I can write a program that really does execute in polynomial time to solve SAT problems. This is quite straightforward in fact.
>
> MEGA BONUS: If you write a SAT-solver that actually executes in polynomial time, you get a million dollars! But please use a spoiler tag anyway, so others can wonder about it.
>
>
>
Awesome. Please send me the million bucks. **Seriously, I have a program right here that will solve SAT with polynomial runtime.**
Let me start by stating that I'm going to solve a variation on the SAT problem. I'm going to demonstrate how to write a program that *exhibits the unique solution of any 3-SAT problem*. The valuation of each Boolean variable has to be *unique* for my solver to work.
We begin by declaring a few simple helper methods and types:
```
class MainClass
{
class T { }
class F { }
delegate void DT(T t);
delegate void DF(F f);
static void M(string name, DT dt)
{
System.Console.WriteLine(name + ": true");
dt(new T());
}
static void M(string name, DF df)
{
System.Console.WriteLine(name + ": false");
df(new F());
}
static T Or(T a1, T a2, T a3) { return new T(); }
static T Or(T a1, T a2, F a3) { return new T(); }
static T Or(T a1, F a2, T a3) { return new T(); }
static T Or(T a1, F a2, F a3) { return new T(); }
static T Or(F a1, T a2, T a3) { return new T(); }
static T Or(F a1, T a2, F a3) { return new T(); }
static T Or(F a1, F a2, T a3) { return new T(); }
static F Or(F a1, F a2, F a3) { return new F(); }
static T And(T a1, T a2) { return new T(); }
static F And(T a1, F a2) { return new F(); }
static F And(F a1, T a2) { return new F(); }
static F And(F a1, F a2) { return new F(); }
static F Not(T a) { return new F(); }
static T Not(F a) { return new T(); }
static void MustBeT(T t) { }
```
Now let's pick a 3-SAT problem to solve. Let's say
```
(!x3) &
(!x1) &
(x1 | x2 | x1) &
(x2 | x3 | x2)
```
Let's parenthesize that a bit more.
```
(!x3) & (
(!x1) & (
(x1 | x2 | x1) &
(x2 | x3 | x2)))
```
We encode that like this:
```
static void Main()
{
M("x1", x1 => M("x2", x2 => M("x3", x3 => MustBeT(
And(
Not(x3),
And(
Not(x1),
And(
Or(x1, x2, x1),
Or(x2, x3, x2))))))));
}
```
And sure enough when we run the program, we get a solution to 3-SAT in polynomial time. In fact the runtime is **linear in the size of the problem**!
```
x1: false
x2: true
x3: false
```
>
> You said polynomial **runtime**. You said nothing about polynomial **compile time**. This program forces the C# compiler to try all possible type combinations for x1, x2 and x3, and choose the unique one that exhibits no type errors. The compiler does all the work, so the runtime doesn't have to. I first exhibited this interesting techinque on my blog in 2007: <http://blogs.msdn.com/b/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx> Note that of course this example shows that overload resolution in C# is at least NP-HARD. Whether it is NP-HARD or actually *undecidable* depends on certain subtle details in how type convertibility works in the presence of generic contravariance, but that's a subject for another day.
>
>
>
[Answer]
# Multi-language (1 byte)
The following program, valid in many languages, mostly functional and esoteric, will give the correct answer for a large number of SAT problems and has constant complexity (!!!):
```
0
```
Amazingly, the next program will give the correct answer for all remaining problems, and has the same complexity. So you just need to pick the right program, and you'll have the correct answer in all cases!
```
1
```
[Answer]
# JavaScript
By using iterated non-determinism, SAT can be solved in polynomial time!
```
function isSatisfiable(bools, expr) {
function verify() {
var values = {};
for(var i = 0; i < bools.length; i++) {
values[bools[i]] = nonDeterministicValue();
}
with(values) {
return eval(expr);
}
}
function nonDeterministicValue() {
return Math.random() < 0.5 ? !0 : !1;
}
for(var i = 0; i < 1000; i++) {
if(verify(bools, expr)) return true;
}
return false;
}
```
Example usage:
```
isSatisfiable(["a", "b"], "a && !a || b && !b") //returns 'false'
```
>
> This algorithm just checks given boolean formula a thousand times with random inputs. Almost always works for small inputs, but is less reliable when more variables are introduced.
>
>
>
By the way, I'm proud that I had the opportunity to utilize two of the most underused features of JavaScript right next to each other: `eval` and `with`.
[Answer]
## Mathematica + Quantum Computing
You may not know that Mathematica comes with quantum computer aboard
```
Needs["Quantum`Computing`"];
```
Quantum Adiabatic Commputing encodes a problem to be solved in a Hamiltonian (energy operator) in such way that its state of minimum energy ("ground state") represents the solution. Therefore adiabatic evolution of a quantum system to the ground state of the Hamiltonian and subsequent measurement gives the solution to the problem.
We define a subhamiltonian that corresponds to `||` parts of the expression, with appropriate combination of Pauli operators for variables and its negation
![enter image description here](https://i.stack.imgur.com/QmzqB.png)
Where for expression like this
```
expr = (! x3) && (! x1) && (x1 || x2 || x1) && (x2 || x3 || x2);
```
the argument should look like
```
{{{1, x3}}, {{1, x1}}, {{0, x1}, {0, x2}, {0, x1}}, {{0, x2}, {0, x3}, {0, x2}}}
```
Here is the code to construct such argument from bool expression:
```
arg = expr /. {And -> List, Or -> List, x_Symbol :> {0, x},
Not[x_Symbol] :> {1, x}};
If[Depth[arg] == 3, arg = {arg}];
arg = If[Depth[#] == 2, {#}, #] & /@ arg
```
Now we construct a full Hamiltonian, summing up the subhamiltonians (the summation corresponds to `&&` parts of the expression)
```
H = h /@ arg /. List -> Plus;
```
And look for the lowest energy state
```
QuantumEigensystemForm[H, -1]
```
![enter image description here](https://i.stack.imgur.com/OK28N.png)
If we got an eigenvalue of zero, then the eigenvector is the solution
```
expr /. {x1 -> False, x2 -> True, x3 -> False}
> True
```
>
> Unfortunately the official site for the "Quantum Computing" add-on is not active and I can't find a place to download it, I just still had it installed on my computer. The Add-on also have a documented solution to the SAT problem, on which I based my code.
>
>
>
[Answer]
Three approaches here, all involve a reduction of SAT into its 2D geometric lingua franca: nonogram logic puzzles. Cells in the logic puzzle correspond to SAT variables, constraints to clauses.
For a full explanation (and to please review my code for bugs!) I've already posted some insight to patterns within the nonogram solution space. See <https://codereview.stackexchange.com/questions/43770/nonogram-puzzle-solution-space> . Enumerating >4 billion puzzle solutions and encoding them to fit in a truth table shows fractal patterns -- self-similarity and especially self-affinity. This affine-redundancy demonstrates structure within the problem, exploitable to reduce the computational resources necessary to generate solutions. It also shows a need for chaotic feedback within any successful algorithm. There is explanatory power in the phase transition behavior where "easy" instances are those that lie along the coarse structure, while "hard" instances require further iteration into fine detail, quite hidden from normal heuristics. If you'd like to zoom into the corner of this infinite image (all <=4x4 puzzle instances encoded) see <http://re-curse.github.io/visualizing-intractability/nonograms_zoom/nonograms.html>
**Method 1.** Extrapolate the nonogram solution space shadow using chaotic maps and machine learning (think fitting functions similar to those that generate the Mandelbrot Set).
![https://i.stack.imgur.com/X7SbP.png](https://i.stack.imgur.com/X7SbP.png)
Here is a visual proof of induction. If you can scan these four images left to right and think you have a good idea to generate the missing 5th... 6th... etc. images, then I have just programmed *you* as my NP oracle for the decision problem of nonogram solution existence. Please step forth to claim your prize as the world's most powerful supercomputer. I'll feed you jolts of electricity every now and then while the world thanks you for your computational contributions.
**Method 2.** Use Fourier Transforms on the boolean image version of inputs. FFTs provide global information about frequency and position within an instance. While the magnitude portion should be similar between the input pair, their phase information is completely different -- containing directionalized information about a solution projection along a specific axis. If you're clever enough you might reconstruct the phase image of the *solution* via some special superposition of the input phase images. Then inverse transform the phase and common magnitude back to the time domain of the solution.
What could this method explain? There are many permutations of the boolean images with flexible padding between contiguous runs. This allows a mapping between input -> solution taking care of multiplicity while still retaining FFTs' property of bidirectional, unique mappings between time domain <-> (frequency, phase). It also means there's no such thing as "no solution." What it would say is that in a continuous case, there are greyscale solutions that you're not considering when looking at the bilevel image of traditional nonogram puzzle solving.
Why wouldn't you do it? It's a horrible way to actually compute, as FFTs in today's floating-point world would be highly inaccurate with large instances. Precision is a huge problem, and reconstructing images from quantized magnitude and phase images usually creates very approximate solutions, although maybe not *visually* for human eye thresholds. It's also very hard to come up with this superpositioning business, as the type of function actually doing it is currently unknown. Would it be a simple averaging scheme? Probably not, and there's no specific search method to find it except intuition.
**Method 3.** Find a cellular automata rule (out of a possible ~4 billion rule tables for von Neumann 2-state rules) that solves a symmetric version of the nonogram puzzle. You use a direct embedding of the problem into cells, shown here.
![Conservative, symmetric nonograms](https://i.stack.imgur.com/LHcUy.png)
This is probably the most elegant method, in terms of simplicity and good effects for the future of computing. The existence of this rule isn't proven, but I have a hunch it exists. Here's why:
Nonograms require lots of chaotic feedback in the algorithm to be solved exactly. This is established by the brute force code linked to on Code Review. CA is just about the most capable language to program chaotic feedback.
It *looks* right, visually. The rule would evolve through an embedding, propogate information horizontally and vertically, interfere, then stabilize to a solution that conserved the number of set cells. This propogation route follows the path (backwards) that you normally think of when projecting a physical object's shadow into the original configuration. Nonograms derives from a special case of discrete tomography, so imagine sitting concurrently in two kitty-cornered CT scanners.. this is how the X-rays would propogate to generate the medical images. Of course, there are boundary issues -- the edges of the CA universe cannot keep propogating information beyond the limits, unless you allow a toroidal universe. This also casts the puzzle as a periodic boundary value problem.
It explains multiple solutions as transient states in a continuously oscillating effect between swapping outputs as inputs, and vis versa. It explains instances that have no solution as original configurations that don't conserve the number of set cells. Depending on the actual outcome of finding such a rule, it may even approximate unsolvable instances with a close solution where the cell states *are* conserved.
[Answer]
# C++
Here is a solution that is guaranteed to run in polynomial time: it runs in `O(n^k)` where `n` is the number of booleans and `k` is a constant of your choice.
>
> It is heuristically correct, which I believe is CS-speak for "it gives the correct answer most of the time, with a bit of luck" (and, in this case, an appropriately large value of `k` - *edit* it actually occurred to me that for any fixed `n` you can set `k` such that `n^k > 2^n` - is that cheating?).
>
>
>
```
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <cmath>
#include <vector>
using std::cout;
using std::endl;
typedef std::vector<bool> zork;
// INPUT HERE:
const int n = 3; // Number of bits
const int k = 4; // Runtime order O(n^k)
bool input_expression(const zork& x)
{
return
(!x[2]) && (
(!x[0]) && (
(x[0] || x[1] || x[0]) &&
(x[1] || x[2] || x[1])));
}
// MAGIC HAPPENS BELOW:
void whatever_you_do(const zork& minefield)
;void always_bring_a_towel(int value, zork* minefield);
int main()
{
const int forty_two = (int)pow(2, n) + 1;
int edition = (int)pow(n, k);
srand(time(6["times7"]));
zork dont_panic(n);
while(--edition)
{
int sperm_whale = rand() % forty_two;
always_bring_a_towel(sperm_whale, &dont_panic);
if(input_expression(dont_panic))
{
cout << "Satisfiable: " << endl;
whatever_you_do(dont_panic);
return 0;
}
}
cout << "Not satisfiable?" << endl;
return 0;
}
void always_bring_a_towel(int value, zork* minefield)
{
for(int j = 0; j < n; ++j, value >>= 1)
{
(*minefield)[j] = (value & 1);
}
}
void whatever_you_do(const zork& minefield)
{
for(int j = 0; j < n; ++j)
{
cout << (char)('A' + j) << " = " << minefield[j] << endl;
}
}
```
[Answer]
# ruby/gnuplot 3d surface
(ooh stiff competition!) ... anyway ... is a picture worth a thousand words? these are 3 separate surface plots made in gnuplot of the SAT transition point. the (x,y) axes are clause & variable count and the z height is total # of recursive calls in the solver. code written in ruby. it samples 10x10 points at 100 samples each. it demonstrates/uses basic principles of [statistics](http://en.wikipedia.org/wiki/Wikipedia:Statistics) and is a [Monte Carlo simulation](http://en.wikipedia.org/wiki/Monte_Carlo).
its basically a [davis putnam](http://en.wikipedia.org/wiki/Davis%E2%80%93Putnam_algorithm) algorithm running on random instances generated in DIMACS format. this is the type of exercise that ideally would be done in CS classes around the world so students could learn the *basics* but is almost not taught specifically at all... maybe some reason why there are so many bogus [P?=NP proofs](http://www.win.tue.nl/~gwoegi/P-versus-NP.htm)? there is not even a good wikipedia article describing the transition point phenomenon (any takers?) which is a very prominent topic in statistical physics & is key also in CS.[a][b] there are *many* papers in CS on the transition point however very few seem to show surface plots! (instead typically showing 2d slices.)
the exponential increase in runtime is clearly evident in 1st plot. the saddle running through the middle of 1st plot is the transition point. the 2nd and 3rd plots show the % satisfiable transition.
[a] [phase transition behavior in CS ppt](http://www.cse.unsw.edu.au/~tw/phase.ppt) Toby Walsh
[b] [empirical probability of k-SAT satisfiability](https://cstheory.stackexchange.com/questions/20985/empirical-probability-of-k-sat-satisfiability) tcs.se
[c] [great moments in empirical/experimental math/(T)CS/SAT](http://vzn1.wordpress.com/2014/02/14/great-moments-in-empiricalexperimental-mathtcs-research-breakthough-sat-induction-idea/), TMachine blog
![enter image description here](https://i.stack.imgur.com/b49aJ.jpg)
![enter image description here](https://i.stack.imgur.com/nkA6Z.jpg)
![enter image description here](https://i.stack.imgur.com/OOjFS.jpg)
>
> [P=?NP](http://vzn1.wordpress.com/2012/12/08/outline-for-a-np-vsppoly-proof-based-on-monotone-circuits-hypergraphs-and-factoring/) ***QED!***
>
>
>
```
#!/usr/bin/ruby1.8
def makeformula(clauses)
(1..clauses).map \
{
vars2 = $vars.dup
(1..3).map { vars2.delete_at(rand(vars2.size)) * [-1, 1][rand(2)] }.sort_by { |x| x.abs }
}
end
def solve(vars, formula, assign)
$counter += 1
vars2 = []
formula.each { |x| vars2 |= x.map { |y| y.abs } }
vars &= vars2
return [false] if (vars.empty?)
v = vars.shift
[v, -v].each \
{
|v2|
f2 = formula.map { |x| x.dup }
f2.delete_if \
{
|x|
x.delete(-v2)
return [false] if (x.empty?)
x.member?(v2)
}
return [true, assign + [v2]] if (f2.empty?)
soln = solve(vars.dup, f2, assign + [v2])
return soln if (soln[0])
}
return [false]
end
def solve2(formula)
$counter = 0
soln = solve($vars.dup, formula, [])
return [$counter, {false => 0, true => 1}[soln[0]]]
end
c1 = 10
c2 = 100
nlo, nhi = [3, 10]
mlo, mhi = [1, 50]
c1.times \
{
|n|
c1.times \
{
|m|
p1 = nlo + n.to_f / c1 * (nhi - nlo)
p2 = mlo + m.to_f / c1 * (mhi - mlo)
$vars = (1..p1.to_i).to_a
z1 = 0
z2 = 0
c2.times \
{
f = makeformula(p2.to_i)
x = solve2(f.dup)
z1 += x[0]
z2 += x[1]
}
# p([p1, p2, z1.to_f / c2, z2.to_f / c2]) # raw
# p(z1.to_f / c2) # fig1
# p(0.5 - (z2.to_f / c2 - 0.5).abs) # fig2
p(z2.to_f / c2) # fig3
}
puts
}
```
] |
[Question]
[
Given a number `N`, how can I print out a Christmas tree of height `N` using the least number of code characters? `N` is assumed constrained to a minimum value of `3`, and a maximum value of `30` (bounds and error checking are not necessary). `N` is given as the one and only command line argument to your program or script.
All languages appreciated, if you see a language already implemented and you can make it shorter, edit if possible - comment otherwise and hope someone cleans up the mess. Include newlines and White Spaces for clarity, but don't include them in the character count.
A Christmas tree is generated as such, with its "trunk" consisting of only a centered "\*"
N = 3:
```
*
***
*****
*
```
N = 4:
```
*
***
*****
*******
*
```
N = 5:
```
*
***
*****
*******
*********
*
```
N defines the height of the branches not including the one line trunk.
**Merry Christmas PPCG!**
[Answer]
# Brainfuck, 240 characters
```
,
>++
+++++
+[-<---
--->],[>+
+++++++[-<-
----->]<<[->+
+++++++++<]>>]<
[->+>+>>>>>>>+<<<
<<<<<<]>>>>++++++++
[-<++++>]>++++++[-<++
+++++>]+>>>++[-<+++++>]
<<<<<<[-[>.<-]<[-<+>>+<]<
[->+<]>>>>>[-<.>>+<]>[-<+>]
>.<<++<<<-<->]>>>>>>>-[-<<<<<
<.>>>
>>>]<
<<<<.
```
Not yet done. It works, but only with single-digit numbers.
EDIT: Done! Works for interpreters using 0 as EOF. See `NOTE`s in commented source for those with -1.
EDIT again: I should note that because Brainfuck lacks a standard method for reading command line arguments, I used stdin (standard input) instead. ASCII, of course.
EDIT a third time: Oh dear, it seems I stripped `.` (output) characters when condensing the code. Fixed...
Here's the basic memory management of the main loop. I'm sure it can be heavily optimized to reduce the character count by 30 or so.
1. Temporary
2. Copy of counter
3. Counter (counts to 0)
4. Space character (decimal 32)
5. Asterisk character (decimal 42)
6. Number of asterisks on current line (1 + 2\*counter)
7. Temporary
8. New line character
9. Temporary?
10. Total number of lines (i.e. input value; stored until the very end, when printing the trunk)
Condensed version:
```
,>++++++++[-<------>],[>++++++++[-<------>]<<[->++++++++++<]>>]<[->+>+>>>>>>>+<<<<<<<<<]>>>>++++++++[-<++++>]>++++++[-<+++++++>]+>>>++[-<+++++>]<<<<<<[-[>.<-]<[-<+>>+<]<[->+<]>>>>>[-<.>>+<]>[-<+>]>.<<++<<<-<->]>>>>>>>-[-<<<<<<.>>>>>>]<<<<<.
```
And the pretty version:
```
ASCII to number
,>
++++++++[-<------>] = 48 ('0')
Second digit (may be NULL)
,
NOTE: Add plus sign here if your interpreter uses negative one for EOF
[ NOTE: Then add minus sign here
>++++++++[-<------>]
<<[->++++++++++<]>> Add first digit by tens
]
Duplicate number
<[->+>+>>>>>>>+<<<<<<<<<]>>
Space char
>>++++++++[-<++++>]
Asterisk char
>++++++[-<+++++++>]
Star count
+
New line char
>>>++[-<+++++>]<<<
<<<
Main loop
[
Print leading spaces
-[>.<-]
Undo delete
<[-<+>>+<]
<[->+<]
>>
Print stars
>>>[-<.>>+<]
Add stars and print new line
>[-<+>]
>.<
<++
<<<
-<->
End main loop
]
Print the trunk
>>>>>>>
-[-<<<<<<.>>>>>>]
<<<<<.
Merry Christmas =)
```
[Answer]
# Perl, 50 chars
(1 relevant spaces)
perl: one line version:
```
print$"x($a-$_),'*'x($_*2+1),$/for 0..($a=pop)-1,0
```
and now with more whitesapce:
```
print $" x ( $a - $_ ), #"# Syntax Highlight Hacking Comment
'*' x ( $_ * 2 + 1),
$/
for 0 .. ( $a = pop ) - 1, 0;
$ perl tree.pl 3
*
***
*****
*
$ perl tree.pl 11
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
*
$
```
### Expanded Explanation for Non-Perl Users.
```
# print $Default_List_Seperator ( a space )
# repeated ( $a - $currentloopiterationvalue ) times,
print $" x ( $a - $_ ),
#"# print '*' repeated( $currentloopiteration * 2 + 1 ) times.
'*' x ( $_ * 2 + 1),
# print $Default_input_record_seperator ( a newline )
$/
# repeat the above code, in a loop,
# iterating values 0 to ( n - 1) , and then doing 0 again
for 0 .. ( $a = pop ) - 1, 0;
# prior to loop iteration, set n to the first item popped off the default list,
# which in this context is the parameters passed on the command line.
```
[Answer]
# [J](http://www.jsoftware.com/), 24 characters
`(,{.)(}:@|."1,.])[\'*'$~`
```
(,{.)(}:@|."1,.])[\'*'$~5
*
***
*****
*******
*********
*
```
Explanation:
```
'*'$~5
*****
[\'*'$~5
*
**
***
****
*****
```
Then `}:@|."1` reverses each row and strips off the last column, and `,.` staples it to `]`.
Then `,{.` pastes the first column onto the bottom.
*Previous entries*:
29 characters, no spaces at all.
```
((\:i.@#),}.)"1$&'*'"0>:0,~i.3
*
***
*****
*
((\:i.@#),}.)"1$&'*'"0>:0,~i.11
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
*
```
---
```
NB. *count from 1 to* n*, then 1 again*
>:0,~i.3
1 2 3 1
NB. *replicate '\*'* x *times each*
$&'*'"0>:0,~i.3
*
**
***
*
NB. *reverse each row*
(\:i.@#)"1$&'*'"0>:0,~i.3
*
**
***
*
NB. *strip off leading column*
}."1$&'*'"0>:0,~i.3
*
**
NB. *paste together*
((\:i.@#),}.)"1$&'*'"0>:0,~i.3
*
***
*****
*
```
[Answer]
### Language: Python (through shell), Char count: 64 (2 significant spaces)
```
python -c "
n=w=$1
s=1
while w:
print' '*w+'*'*s
s+=2
w-=1
print' '*n+'*'"
$ sh ax6 11
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
*
```
[Answer]
**Language: Windows Batch Script** (*shocking!*)
```
@echo off
echo Enable delayed environment variable expansion with CMD.EXE /V
rem Branches
for /l %%k in (1,1,%1) do (
set /a A=%1 - %%k
set /a B=2 * %%k - 1
set AA=
for /l %%i in (1,1,!A!) do set "AA=!AA! "
set BB=
for /l %%i in (1,1,!B!) do set BB=*!BB!
echo !AA!!BB!
)
rem Trunk
set /a A=%1 - 1
set AA=
for /l %%i in (1,1,!A!) do set "AA=!AA! "
echo !AA!*
```
[Answer]
### Ruby, 64 bytes
```
n=ARGV[0].to_i
((1..n).to_a+[1]).each{|i|puts' '*(n-i)+'*'*(2*i-1)}
```
```
n=$*[0].to_i
((1..n).to_a<<1).each{|i|puts' '*(n-i)+'*'*(2*i-1)}
```
Merry Christmas all!
Edit: Improvements added as suggested by Joshua Swink
[Answer]
### Language: C#, Char count: 120
```
static void Main(string[] a)
{
int h = int.Parse(a[0]);
for (int n = 1; n < h + 2; n++)
Console.WriteLine(n <= h ?
new String('*', n * 2 - 1).PadLeft(h + n) :
"*".PadLeft(h + 1));
}
}
```
Just the code, without formatting (120 characters):
```
int h=int.Parse(a[0]);for(int n=1;n<h+2;n++)Console.WriteLine(n<=h?new String('*',n*2-1).PadLeft(h+n):"*".PadLeft(h+1));
```
Version with 109 characters (just the code):
```
for(int i=1,n=int.Parse(a[0]);i<n+2;i++)Console.WriteLine(new String('*',(i*2-1)%(n*2)).PadLeft((n+(i-1)%n)));
```
Result for height = 10:
```
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*
```
[Answer]
**python, "-c" trick... @61 chars (and one line)**
```
python -c"for i in range($1)+[0]:print' '*($1-i)+'*'*(2*i+1)"
```
[Answer]
### Language: dc (through shell) Char count: 83
A little bit shorter dc version:
```
dc -e '?d1rdsv[d32r[[rdPr1-d0<a]dsaxszsz]dsbx1-rd42rlbx2+r10Plv1-dsv0<c]dscxszsz32rlbx[*]p' <<<$1
```
EDIT: changed constant 10 into $1
[Answer]
Here's a reasonably space-efficient Haskell version, at 107 characters:
```
main=interact$(\g->unlines$map(\a->replicate(g-a)' '++replicate(a*2-1)'*')$[1..g]++[1]).(read::[Char]->Int)
```
running it:
```
$ echo 6 | runhaskell tree.hs
*
***
*****
*******
*********
***********
*
```
Merry Christmas, all :)
[Answer]
### Language: dc (through shell), Char count: 119 (1 significant space)
Just for the obscurity of it :)
```
dc -e "$1dsnsm"'
[[ ]n]ss
[[*]n]st
[[
]n]sl
[s2s1[l2xl11-ds10<T]dsTx]sR
[lndlslRxlcdltlRxllx2+sc1-dsn0<M]sM
1sclMxlmlslRxltxllx
'
$ sh ax3 10
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*
```
[Answer]
Better C++, around 210 chars:
```
#include <iostream>
using namespace std;
ostream& ChristmasTree(ostream& os, int height) {
for (int i = 1; i <= height; ++i) {
os << string(height-i, ' ') << string(2*i-1, '*') << endl;
}
os << string(height-1, ' ') << '*' << endl;
return os;
}
```
Minimized to 179:
```
#include <iostream>
using namespace std;ostream& xmas(ostream&o,int h){for(int i=1;i<=h;++i){o<<string(h-i,' ')<<string(2*i-1,'*')<<endl;}o<<string(h-1,' ')<<'*'<<endl;return o;}
```
[Answer]
Language: python, no tricks, 78 chars
```
import sys
n=int(sys.argv[1])
for i in range(n)+[0]:print' '*(n-i)+'*'*(2*i+1)
```
[Answer]
### Language: Java, Char count: 219
```
class T{ /* 219 characters */
public static void main(String[] v){
int n=new Integer(v[0]);
String o="";
for(int r=1;r<=n;++r){
for(int s=n-r;s-->0;)o+=' ';
for(int s=1;s<2*r;++s)o+='*';
o+="%n";}
while(n-->1)o+=' ';
System.out.printf(o+"*%n");}}
```
For reference, I was able to shave the previous Java solution, using recursion, down to 231 chars, from the previous minimum of 269. Though a little longer, I do like this solution because `T` is truly object-oriented. You could create a little forest of randomly-sized `T` instances. Here is the latest evolution on that tack:
```
class T{ /* 231 characters */
public static void main(String[] v){new T(new Integer(v[0]));}}
String o="";
T(int n){
for(int r=1;r<=n;++r){
x(' ',n-r);x('*',2*r-1);o+="%n";}
x(' ',n-1);
System.out.printf(o+"*%n");
}
void x(char c,int x){if(x>0){o+=c;x(c,x-1);}
}
```
[Answer]
**Groovy** 62B
```
n=args[0]as Long;[*n..1,n].any{println' '*it+'*'*(n-~n-it*2)}
```
\_
```
n = args[0] as Long
[*n..1, n].any{ println ' '*it + '*'*(n - ~n - it*2) }
```
[Answer]
## C# using Linq:
```
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int n = int.Parse(args[0]);
int i=0;
Console.Write("{0}\n{1}", string.Join("\n",
new int[n].Select(r => new string('*',i * 2 + 1)
.PadLeft(n+i++)).ToArray()),"*".PadLeft(n));
}
}
```
170 charcters.
```
int n=int.Parse(a[0]);int i=0;Console.Write("{0}\n{1}",string.Join("\n",Enumerable.Repeat(0,n).Select(r=>new string('*',i*2+1).PadLeft(n+i++)).ToArray()),"*".PadLeft(n));
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~54~~ ~~53~~ 52 bytes
This is shorter than [@xnor's solution](https://codegolf.stackexchange.com/a/177755/88546) by 4 bytes.
```
i=n=input()
while~i:i-=1;print i%n*' '+~i%n*'**'+'*'
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2zzYzr6C0REOTqzwjMye1LtMqU9fW0LqgKDOvRCFTNU9LXUFduw7M0NJS11bXUv//3wwA "Python 2 – Try It Online")
---
I borrowed @xnor's trick of using modulo (`i%n`) in order to print the trunk on the last line. The next part is figuring out how to print the number of stars.
```
i | ~i%n | *2+1 |
-------|------|------|
5 | 0 | 1 |
4 | 1 | 3 |
3 | 2 | 5 |
2 | 3 | 7 |
1 | 4 | 9 |
0 | 5 | 11 |
-1 | 0 | 1 |
```
The example above illustrates the number of stars we need to print given our variable \$i\$. First, we 'invert' \$i\$ by doing `~i%n`. This gives us an increasing sequence starting from 0. Keep in mind that the way Python handles negative modulo is different from other languages like C.
[Answer]
Improving ΤΖΩΤΖΙΟΥ's answer. I can't comment, so here is a new post. 72 characters.
```
import sys
n=int(sys.argv[1])
for i in range(n)+[0]:
print ("*"*(2*i+1)).center(2*n)
```
Using the "python -c" trick, 61 characters.
```
python -c "
for i in range($1)+[0]:
print ('*'*(2*i+1)).center(2*$1)
"
```
I learned the center function and that "python -c" can accept more than one line code. Thanks,
ΤΖΩΤΖΙΟΥ.
[Answer]
AWK, 86 characters on one line.
```
awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}'
echo "8" | awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}'
#
###
#####
#######
#########
###########
#############
###############
#
cat tree.txt
3
5
awk '{s="#";for(i=0;i<$1;i++){printf"%"$1-i"s%s\n","",s;s=s"##"}printf"%"$1"s#\n",""}' tree.txt
#
###
#####
#
#
###
#####
#######
#########
#
```
[Answer]
**Language:PowerShell, Char count: 41 (including 1 space)**
```
1..$args[0]+1|%{" "*(30-$_)+"*"*($_*2-1)}
```
[Answer]
21 characters with dyalog APL.
```
m,⍨⌽0 1↓m←↑'*'\¨⍨1,⍨⍳
```
⍳ gives a vector of integers starting with 1.
1,⍨ adds a one to the end of the vector. This will be the foot of the tree.
'\*'\¨⍨ gives a vector of \*-strings with lengths given by the previous vector.
↑ transforms the vector to a matrix and adds spaces to the right.
m← stores the matrix in m.
0 1↓ drops zero rows and the first column.
⌽ reverses the matrix.
m,⍨ concatenates with m at the right side.
[Answer]
### Language: C, Char count: 133
Improvement of the C-version.
```
char s[61];
l(a,b){printf("% *.*s\n",a,b,s);}
main(int i,char**a){
int n=atoi(a[1]);memset(s,42,61);
for(i=0;i<n;i++)l(i+n,i*2+1);l(n,1);
}
```
Works and even takes the tree height as an argument. Needs a compiler that tolerates K&R-style code.
I feel so dirty now.. This is code is ugly.
[Answer]
### Language: C, Char count: 176 (2 relevant spaces)
```
#include <stdio.h>
#define P(x,y,z) for(x=0;x++<y-1;)printf(z);
main(int c,char **v){int i,j,n=atoi(v[1]);for(i=0;i<n;i++){P(j,n-i," ")P(j,2*i+2,"*")printf("\n");}P(i,n," ")printf("*\n");}
```
[Answer]
## R (62 bytes)
I did not see R solution yet. Correct me if I missed it.
```
for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
```
Output:
```
> N <- 3
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
*
***
*****
*
>
> N <- 4
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
*
***
*****
*******
*
>
> N <- 5
> for(i in c(1:N,1))cat(rep(" ",N-i),rep("*",2*i-1),"\n",sep="")
*
***
*****
*******
*********
*
```
[Answer]
## J, 24
Works akin to the [accepted answer](https://codegolf.stackexchange.com/a/4293/3918) in that you include the parameter in the source code. Expressing it as a proper function would be slightly longer. Uses a different approach than the accepted answer.
```
' *'#~(>:@+:,.~#-])0,~i.
```
E.g.
```
' *' #~ (>:@+: ,.~ #-]) 0 ,~ i.5
*
***
*****
*******
*********
*
```
As a function (**27**):
```
#&' *'@(>:@+:,.~#-])@,&0@i.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
R”*ẋz⁶ṚŒBṁ‘Y
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//UuKAnSrhuot64oG24bmaxZJC4bmB4oCYWf///zU "Jelly – Try It Online")
[Answer]
Shell version, 134 characters:
```
#!/bin/sh
declare -i n=$1
s="*"
for (( i=0; i<$n; i++ )); do
printf "%$(($n+$i))s\n" "$s"
s+="**"
done
printf "%$(($n))s\n" "*"
```
[Answer]
### Language: Python, Significant char count: 90
It's ugly but it works:
```
import sys
n=int(sys.argv[1])
print"\n".join(" "*(n-r-1)+"*"*(r*2+1)for r in range(n)+[0])
```
...
```
$ python tree.py 13
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*************************
*
```
[Answer]
# c: 151 116 115
Just giving it a whirl
```
i,j,a;main(c,v)int**v;{for(a=atoi(v[1]);i<a;i+=puts(""))for(j=0;j<a+i;)putchar(++j<a-i?32:42);printf("%*s",a,"*");}
```
Readable code:
```
i, j, a;
main(c, v) int **v; {
for (a = atoi(v[1]); i < a; i += puts(""))
for(j = 0; j < a + i;)
putchar(++j < a - i ? 32 : 42);
printf("%*s", a, "*");
}
```
[Try it online!](https://tio.run/##FcxBCsIwEEDRuwwIM0kKWrtyGjyIdDEEqhOwLWnMRjx7TLePzw/dM4Ra1UUn/BZdMLhCumRjCn/nNaF4yatieVwmYh2F1frtk3cEIDqC6M8cR7HK1Dy8JKG1DTq9X/vb0BNvqQ1nhJPZwYkDA8S/WuvwBw)
# Code History:
```
main(int c, char **v){
int i, j, a = atoi(v[1]);
for (i = 1; i <= a; i++) {
for (j = 0; j < a + i - 1; j++)
putchar((j >= a - i) ? '*' : ' ');
putchar('\n');
}
printf("%*s*\n", a - 1, "");
}
```
[Answer]
# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 547 bytes
```
the triangle trees
a december i loved
o,i placed a fun christmasy thing
i know i am hoping on a santa,a gift,cookie plates,or bag o dolls
i know i am choosing my toy to expect of him,Mr.Claus
i say,Mr,i think i may ask nicely
we are nice people,we are
o,under the tree i go crazy as i glance at the a-b-c puzzle we got
a thing on Xmas i am happy to be toying with
o,i found it!for a moment,i shouted thanks
a gift i am having as we enjoy a holiday feast
and now i sleep
oh,here i am,silent as i could
i quickly awaken
i then go to locate a present
```
[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?VVExUsQwDOzzCtEHZuAL1PS0iqPEJrZlbOfC3eePVW4oKDxjydrV7rp7oV4D5zXaRaQNTLM4SZNUChT1IvOgY6AS2clMTMueyfkaWk/crtR9yOsQaMt6AMCJvBa0SDOGG@fOI9Malj461S2IMXVpo1aaGGM0a4ztH4Pzqs04EvjVDslPEddJF/IhjR/15T3ybqjGV5QQaEI24BNfidtGOTiJ1@EQ4ipnRUW0RBkfLbja8wyX3T@sA7squco3I7AqcgaK@znCz9Ozo7LfbogKFKt2ZHXaN6@f6cSYfy7l1DyJqbf3I3R/prgodlLoTwvsMyVNkjv6zeveEW/3nDf7Awvsj@5iFGDHUslfyIORcQwzjC7CDTLA@QivRZEyqB@9VDnxYwsROx6OnO5xRmjfe3BbBNHBm@TBwpNs7qE6qsP/YEep0oC8v77dJ55/AQ)
Translated from [a version by Daniel Cristofani](http://www.hevanet.com/cristofd/brainfuck/xmastree.b), but optimized specifically for program length in Poetic (more groups of `>` than `<`, more groups of `+` than `-`, etc).
] |
[Question]
[
>
> As of 13/03/2018 16:45 UTC, the winner is [answer #345](https://codegolf.stackexchange.com/a/156848/66833), by [Khuldraeseth na'Barya](https://codegolf.stackexchange.com/users/73884/khuldraeseth-nabarya). This means the contest is officially over, but feel free to continue posting answers, just so long as they follow the rules.
>
>
> As well, just a quick shout out to the top three answerers in terms of numbers of answers:
>
>
> **1.** [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob) - 41 answers
>
>
> **2.** [KSmarts](https://codegolf.stackexchange.com/users/69481/ksmarts) - 30 answers
>
>
> **3.** [Hyper Neutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino) - 26 answers
>
>
>
---
This is an answer chaining question that uses sequences from OEIS, and the length of the previous submission.
This answer chaining question will work in the following way:
* I will post the first answer. All other solutions must stem from that.
* The next user (let's call them userA) will find the OEIS sequence in which its index number (see below) is the same as the length of my code.
* Using the sequence, they must then code, in an **unused language**, a program that takes an integer as input, n, and outputs the nth number in that sequence.
* Next, they post their solution after mine, and a new user (userB) must repeat the same thing.
The `n`th term of a sequence is the term n times after the first, working with the first value being the first value given on its OEIS page. In this question, we will use **0-indexing** for these sequences. For example, with [A000242](https://oeis.org/A000242) and `n = 3`, the correct result would be *25*.
## However!
This is not a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code doesn't matter. But the length of your code does still have an impact. To prevent the duplication of sequences, **your bytecount must be unique**. This means that no other program submitted here can be the same length in *bytes* as yours.
If there isn't a sequence for then length of the last post, then the sequence for your post is the lowest unused sequence. This means that the sequences used also have to be unique, and that the sequence cannot be the same as your bytecount.
After an answer has been posted and no new answers have been posted for more than a week, the answer *before* the last posted (the one who didn't break the chain) will win.
## Input and Output
Generic input and output rules apply. Input must be an integer or a string representation of an integer and output must be the correct value in the sequence.
## Formatting
As with most [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") questions, please format your answer like this
```
# N. language, length, [sequence](link)
`code`
[next sequence](link)
*anything else*
```
## Rules
* You must wait for at least 1 hour before posting an answer, after having posted.
* You may not post twice (or more) in a row.
* The index number of a sequence is the number after the `A` part, and with leading zeros removed (e.g. for `A000040` the index number is 40)
* You can assume that neither the input nor the required output will be outside your languages numerical range, but please don't abuse this by choosing a language that can only use the number 1, for example.
* If the length of your submission is greater than 65536 characters long, please provide a link to a way to access the code (pastebin for example).
* `n` will never be larger than 1000, or be out of bounds for the sequence, simply to prevent accuracy discrepancies from stopping a language from competing.
* Every 150 (valid) answers, the number of times a language may be used increases. So after 150 solutions have been posted, every language may be used twice (with all previous answers counting towards this). For instance, when 150 answers have been posted, Python 3 may be used twice, but due to the fact that it has already been used once, this means it can only be used once more until 300 answers have been posted.
* Please be helpful and post a link to the next sequence to be used. This isn't required, but is a recommendation.
* Different versions of languages, e.g. Python 2 and Python 3 are *different languages*. As a general rule, if the different versions are both available on Try It Online, they are different languages, but keep in mind that this is a *general rule* and not a rigid answer.
* It is not banned, but please try not to copy the code from the OEIS page, and actually try to solve it.
* Hardcoding is only allowed if the sequence is finite. Please note that the answer that prompted this ([#40](https://codegolf.stackexchange.com/a/134996/66833)) is the exception to the rule. A few answers early in the chain hardcode, but these can be ignored, as there is no good in deleting the chain up to, say, #100.
## Answer chain snippet
```
var QUESTION_ID=133754,OVERRIDE_USER=66833;function shareUrl(i){return"https://codegolf.stackexchange.com/a/"+i}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 getTemplate(s){return jQuery(jQuery("#answer-template").html().replace("{{PLACE}}",s.index+".").replace("{{NAME}}",s.user).replace("{{LANGUAGE}}",s.language).replace("{{SEQUENCE}}",s.sequence).replace("{{SIZE}}",s.size).replace("{{LINK}}",s.link))}function search(l,q){m=jQuery("<tbody id='answers'></tbody>");e.forEach(function(s){if(!q||(l==0&&RegExp('^'+q,'i').exec(s.lang_name))||(l==1&&q===''+s.size)){m.append(jQuery(getTemplate(s)))}});jQuery("#answers").remove();jQuery(".answer-list").append(m)}function sortby(ix){t=document.querySelector('#answers');_els=t.querySelectorAll('tr');els=[];for(var i=0;i<_els.length;i++){els.push(_els[i]);}els.sortBy(function(a){a=a.cells[ix].innerText;return ix==0||ix==4?Number(a):a.toLowerCase()});for(var i=0;i<els.length;i++)t.appendChild(els[i]);}function checkSize(x){if(!x)return jQuery("#size-used").text("");var i=b.indexOf(+x);if(i<0)return jQuery("#size-used").text("Available!");var low=+x,high=+x;while(~b.indexOf(low))low--;while(~b.indexOf(high))high++;jQuery("#size-used").text(("Not available. The nearest are "+low+" and "+high).replace("are 0 and","is"))}function checkLang(x){}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.answer_id;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.user_id==OVERRIDE_USER?"<span id='question-author'>"+e.owner.display_name+"</span>":e.owner.display_name)}function process(){b=[];c=[];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);if(a){e.push({user:getAuthorName(s),size:+a[4],language:a[2],lang_name:a[3],index:+a[1],sequence:a[5],link:shareUrl(s.answer_id)});if(b.indexOf(+a[4])>=0&&c.indexOf(+a[4])<0){c.push(+a[4])};b.push(+a[4])}else{jQuery('#weird-answers').append('<a href="'+shareUrl(s.answer_id)+'">This answer</a> is not formatted correctly. <b>Do not trust the information provided by this snippet until this message disappears.</b><br />')}}),e.sortBy(function(e){return e.index});e.forEach(function(e){jQuery("#answers").append(getTemplate(e))});var q="A"+("000000"+e.slice(-1)[0].size).slice(-6);jQuery("#next").html("<a href='http://oeis.org/"+q+"'>"+q+"</a>");c.forEach(function(n){jQuery('#weird-answers').append('The bytecount '+n+' was used more than once!<br />')})}Array.prototype.sortBy=function(f){return this.sort(function(a,b){if(f)a=f(a),b=f(b);return(a>b)-(a<b)})};var ANSWER_FILTER="!*RB.h_b*K(IAWbmRBLe",COMMENT_FILTER="!owfmI7e3fd9oB",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page,e=[];getAnswers();var SCORE_REG=/<h\d>\s*(\d+)\.\s*((?:<a [^>]+>\s*)?((?:[^\n,](?!<\/a>))*[^\s,])(?:<\/a>)?),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*, ((?:<a[^>]+>\s*)?A\d+(?:\s*<\/a>)?)\s*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important;font-family:Roboto,sans-serif}#answer-list,#language-list{padding:10px;/*width:290px*/;float:left;display:flex;flex-wrap:wrap;list-style:none;}table thead{font-weight:700}table td{padding:5px}ul{margin:0px}#board{display:flex;flex-direction:column;}#language-list li{padding:2px 5px;}#langs-tit{margin-bottom:5px}#byte-counts{display:block;margin-left:15px;}#question-author{color:purple;text-shadow: 0 0 15px rgba(128,0,128,0.1);}#label-info{font-weight: normal;font-size: 14px;font-style: italic;color: dimgray;padding-left: 10px;vertical-align: middle; }
```
```
<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"><p id="weird-answers"></p><p>Currently waiting on <span id="next"></span></p><span>Search by Byte Count: <input id="search" type="number" min=1 oninput="checkSize(this.value);search(1,this.value)" onclick="document.getElementById('search2').value='';!this.value&&search(0,'')"/> <span id="size-used"></span></span><br><span>Search by Language: <input id="search2" oninput="checkLang(this.value);search(0,this.value)" onclick="document.getElementById('search').value='';!this.value&&search(0,'')"/> <span id="language-used"></span></span><h2>Answer chain <span id="label-info">click a label to sort by column</span></h2><table class="answer-list"><thead><tr><td onclick="sortby(0)">#</td><td onclick="sortby(1)">Author</td><td onclick="sortby(2)">Language</td><td onclick="sortby(3)">Sequence</td><td onclick="sortby(4)">Size</td></tr></thead><tbody id="answers"></tbody></table><table style="display: none"><tbody id="answer-template"><tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SEQUENCE}}</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>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# 22. [FiM++](https://esolangs.org/wiki/FiM%2B%2B), 982 bytes, [A000024](https://oeis.org/A000024)
>
> **Note**: if you are reading this, you might want to [sort by "oldest".](https://codegolf.stackexchange.com/questions/133754/one-oeis-after-another?answertab=oldest#tab-top)
>
>
>
```
Dear PPCG: I solved A000024!
I learned how to party to get a number using the number x and the number y.
Did you know that the number beers was x?
For every number chug from 1 to y,
beers became beers times x!
That's what I did.
Then you get beers!
That's all about how to party.
Today I learned how to do math to get a number using the number n.
Did you know that the number answer was 0?
For every number x from 1 to n,
For every number y from 1 to n,
Did you know that the number tmp1 was how to party using x and 2?
Did you know that the number tmp2 was how to party using y and 2?
Did you know that the number max was how to party using 2 and n?
tmp2 became tmp2 times 10!
tmp1 became tmp1 plus tmp2!
If tmp1 is more than max then: answer got one more.
That's what I did.
That's what I did.
Then you get answer!
That's all about how to do math.
Your faithful student, BlackCap.
PS: This is the best answer
PPS: This really is the best answer
```
[Next sequence](https://oeis.org/A000982)
[Answer]
# 1. [Triangular](https://github.com/aaronryank/triangular), 10 bytes, [A000217](https://oeis.org/A000217)
```
$\:_%i/2*<
```
[Try it online!](https://tio.run/##KynKTMxLL81JLPr/XyXGKl41U99Iy@b/f0MDAA "Triangular – Try It Online")
[Next Sequence](https://oeis.org/A000010)
## How it works
The code formats into this triangle
```
$
\ :
_ % i
/ 2 * <
```
with the IP starting at the `$` and moving South East (SE), works like this:
```
$ Take a numerical input (n); STACK = [n]
: Duplicate it; STACK = [n, n]
i Increment the ToS; STACK = [n, n+1]
< Set IP to W; STACK = [n, n+1]
* Multiply ToS and 2ndTos; STACK = [n(n+1)]
2 Push 2; STACK = [n(n+1), 2]
/ Set IP to NE; STACK = [n(n+1), 2]
_ Divide ToS by 2ndToS; STACK = [n(n+1)/2]
\ Set IP to SE; STACK = [n(n+1)/2]
% Output ToS as number; STACK = [n(n+1)/2]
* Multiply ToS by 2ndToS (no op); STACK = [n(n+1)/2]
```
[Answer]
# 73. [Starry](https://esolangs.org/wiki/Starry), 363 bytes, [A000252](https://oeis.org/A000252)
```
, + + * '. `
+ + + + * * * +
+` +* + `
+ + + + + + * '
+ ' ####` + + +
+ + #### +* + *
' ##### + + '
` ######+ + + +
+ + + ######### * '
+ + + #####+ + +
* + + * + * * +
+ * + + + + * *
+ + + * + ` + +
+ + + + *' + +.
```
[Try it online!](https://tio.run/##XZBLDsMgDET3PsVIXiBBFWWT@7hXSLvp6am/Ia0TCYPnDdiv9/M8P3M@MOAx0H1tmy9CehKfFeIPqVYkmUCyIAjGt5WoojkTIs1ZQ5agGD9PS993wgIY653N3KQQ5tttoMq4wpzMhdbLkipD6rgP4WpYK0F0/M/C7kmzlKJaop/u2zWdsc157F8 "Starry – Try It Online")
[Next sequence](https://oeis.org/A000363)
Uses the formula "`a(n) = n^4 * product p^(-3)(p^2 - 1)*(p - 1)` where the product is over all the primes p that divide n" from OEIS.
The moon's a no-op, but hey, this isn't code-golf.
[Answer]
# 97. [Python 3 (PyPy)](https://docs.python.org/3/), 1772 bytes, [A000236](http://oeis.org/A000236)
First of all, many thanks to Dr. Max Alekseyev for being patient with me. I'm very fortunate that I was able to contact him by email to understand this challenge. His Math.SE answer [here](https://math.stackexchange.com/a/2381188/457091) helped me out a lot. Thanks to Wheat Wizard for helping me as well. :)
```
plist = []
def primes(maximal = -1): # Semi-efficient prime number generator with caching up to a certain max.
index = plist and plist[-1] or 2
for prime in plist:
if prime <= maximal or maximal == -1: yield prime
else: break
while index <= maximal or maximal == -1:
composite = False
for prime in plist:
if index % prime == 0:
composite = True
break
if not composite:
yield index
plist.append(index)
index += 1
def modinv(num, mod): # Multiplicative inverse with a modulus
index = 1
while num * index % mod != 1: index += 1
return index
def moddiv(num, dnm, mod):
return num * modinv(dnm, mod) % mod
def isPowerResidue(num, exp, mod):
for base in range(mod):
if pow(base, exp, mod) == num:
return base
return False
def compute(power, prime):
for num in range(2, prime):
if isPowerResidue(moddiv(num - 1, num, prime), power, prime):
return num - 1
return -1
# file = open('output.txt', 'w')
def output(string):
print(string)
# file.write(str(string) + '\n')
def compPrimes(power, count):
maximum = 0
index = 0
for prime in getValidPrimes(power, count):
result = compute(power, prime)
if result > maximum: maximum = result
index += 1
# output('Computed %d / %d = %d%% [result = %d, prime = %d]' % (index, count, (100 * index) // count, result, prime))
return maximum
def isValidPrime(power, prime):
return (prime - 1) % power == 0
def getValidPrimes(power, count):
collected = []
for prime in primes():
if isValidPrime(power, prime):
collected.append(prime)
if len(collected) >= count:
return collected
# output('Collected %d / %d = %d%% [%d]' % (len(collected), count, (100 * len(collected)) // count, prime))
power = int(input()) + 2
output(compPrimes(power, 100))
# file.close()
```
[Try it online!](https://tio.run/##hVTBbtswDD3bX8GhCGKvSRp3t2DpZcBuA4pt2KXrQbWZRJgjG7bcpF@fkaJkO2nXXRJbJB8f@Z5cv9hdZT6dTnWpWwtreHiM4wI3UDd6j22yV0e9VyUF5lm6giv4gXs9x81G5xqNlTQw3f4JG9iiwUbZqoGDtjvIVb7TZgtdDbYCBTk2VmkDhLmII20KPBKuNFamkKeHefYIhHAbRxv6E3wqcsFVHEXac4PPawjsKLEnykxX8KKxLCSRarBscQVPDao/cXTY6ZIhuf17GFSXV/u6arVF4vlVEQidvc2KaQnkxEcJZOkiZyg/mw7doSfDdaay0Oe4EmHv8PjVdVmoukZTJO405UrX7noNmSi2rwptnhPSYsbPTq1vXWk1lefK6mdm/IxNiyKP4qyu7NpBiyxsh0DgYz8Q5cEHiq5g1DNq0HaN8SwDg0J7BoUJNPpMAfU0@7jgC4Bu76sDNt@x1UWHAoTHugfi3T@p1q2@UWaLiQ84V1SHhIOjEhaBQNxOPQnO6BmJpq41C9BZTGomMBMNQ0sm3ne8HQWd6uechx3AHLIZuBmkYAaX4NF4NfPRUuek6RVsWIo1VKR7Mq06SwQX9minM5gepqnwluOktQ1dNcYkcNO/x5GgLA4NeYtPQwSuYfrbBBSe/l5uvOeYV52xjOcuBdEjOw9GWV7czi3aX6rUxT8waKyWnEiFb65ZFulz7sB3XMHQWmLnpo9oNj/99IvAFjAp4IZ/1vQzmcBD33hSzMLFpOfHKdlOrpKnOYMkWy6D6VO4uQnnAhG4pr1Gnl1w7jD/Kw/5gkT6k85sepfkvhKC8J8V5lVZYs4jum/0xWdIagZLvkMmGqDCJ2WsQkle6xNSuFsLhbFZ@/CFBIHgpQZh3efQl3s/j44FCIuP/cqADa4Nd03Zx7dx7Em8tjFhc6W/BXlZtZikp@z0Fw "Python 3 – Try It Online")
If it gives the wrong result, just increase the 100 to something larger. I think 10000 will work for 4 but I'll leave my computer running overnight to confirm that; it may take a couple of hours to finish.
Note that the (PyPy) part is just so that I can use Python again. I really don't know many other languages and I'm not going to try to port this to Java and risk not finishing in time.
[Next Sequence](http://oeis.org/A001772) (Also please don't do any more crazy math stuff; I don't have any Python versions left so someone else will have to save this challenge D:)
[Answer]
# 107. [TrumpScript](https://github.com/samshadwell/TrumpScript), 1589 bytes, [A000047](http://oeis.org/A000047)
```
My cat hears everything really well
because with me every cat is a safe cat
Everybody knows that one is 1000001 minus 1000000
but only most of you that two is, one plus one;
As always nothing is, one minus one;
My dog is one year old.
I promise you that as long as you vote on me, nothing will be less cool than a cat;:
Much dog is, dog times two;
Dead cat is, cat minus one;!
I will make dog feel good, food for dog plus one;
Roads can be made using different things. Asphalt is one of them.
As long as Hillary jailed, I love asphalt less than my dog;:
Roads are, always made using asphalt plus one of other things;
I promise my roadways are, two times asphalt than you want;
My roadways are great, always roadways plus one;
Vladimir is nothing more than my friend.
Name of Putin is Vladimir.
As long as, Putin eat less roadways;:
China is nothing interesting.
We all know people speaking Chinese are from China.
As long as, Chinese makes less roads;:
I will make economy, for Putin - Chinese will love me;
If it will mean, economy is asphalt in Russia?;:
I will make cat feel good, cat plus one dollar on food;
Make Vladimir roadways to help Russia economy.
Never make china roads!
I show you how great China is, China plus one; You can add numbers to China.
Like Chinese is, China times China makes sense;
Like Chinese is, two times Chinese letter;!
Make Vladimir happy, Vladimir plus one million dollars;
I also show you how great Putin is, Vladimir times Vladimir; You can do number stuff to Putin too!
I will make asphalt roads a lot!
Everybody say cat. You did it? America is great.
```
[Try it online!](https://tio.run/##bVTLbtswELzrKzZ31UhuRX0IgrZAAzRFkUOLHmlrZbHhQyCpGPp6d5YUZaWtD5Yo7uzszC6ZwmTHeAx6TJfL00xHlWhgFSLxK4c5DdqdKLAyZqYzG9Mc@KimyHTWaSDLJSzDdCRFUfUsq@azfD/4bqYX58@R0oAQ71jC7m7ld0dWu6mubpvDJAHgsT7irafZTwWWzh6wNsNHAwhe9s0D@MxZzZGcL3XWmJI3B0FS52Unb8xQRt50u@aRxuCthpCVRUUyHlnwlG@vPjFA0NiuBGdtDB2YDMdIR@@NIB1kQ/H@Q/M0HYeFrs3PpC1HKX/ffGLVLTa1@Xkt8gbV5MxWvXDG9cyGTt53LfX4x1/I36/in73qUALIUY5VHdMUpcJO9z0HdjBNKo47eojjoEyqFsDXNLDdiX1V7heQK3Txt9KGwfmInVfGTkFmtVmozW5CaaFXAd4sPdjUUHG1WuGEgRyWmvYb95ExIFdOkdNJr4ttNU1mlo6clUu5o1sEnTCdaS1j3bpa9cOoTlsdxIHaSOuBrJL6oNlhJr4pm2v9PiXtJLoit2a1yzZIizGVEa58RG61pdEuoRkR8add8xOOoslyHGhkPxqmOLJ6kUBBMuwQQT2syR/UW94aI1MSr9xCvJ0fPnrn7dzmoSm1vluxOSw318KZx550WqCsXFux@SjXsXH0PMWo1f1fPDLDmzmV5drwzstAyemR8UXPBLD2Ye1R8rhrzLgQVHY0Qi6VhSVbmnXKMYkDzJNZkGfuPFXT2@VtbTz9QpycENV15CZ74JApF2u/aqSvvlzhZfbKe3E6sosw65/466TWr4YT@o3z/FbvoMYR/VjXq00WZmqYVOzK50KZ6P@nss7kJk3hrsur3M4vaimmqe9FckEn799eNbXHoZxmDEa62VzcUeWLfZczd7rDsNzTg@Wgj3nKc2W7y@X9Hw "TrumpScript – Try It Online")
First time programming in TrumpScript, it is possible that I reinvented the wheel a few times - 4 lines are dedicated to calculating 2 ^ n. I tried to make it look like something that (drunk) Trump could say. As a bonus, here is a Python script I wrote to verify that I'm doing everything right. There are some differences to the above program, but much of it is directly equivalent.
```
cat = int(input())
dog = 2 ** cat + 1
asphalt = 1
cat = 0
while asphalt < dog:
roads = asphalt + 1
roadways = 2 * asphalt + 1
vladimir = 0
putin = vladimir
while putin < roadways:
china = 0
chinese = china
while chinese < roads:
chair = putin - chinese
if chair == asphalt:
cat += 1
vladimir = roadways
china = roads
china += 1
chinese = 2 * china * china
vladimir += 1
putin = vladimir * vladimir
asphalt = roads
print(cat)
```
[Next sequence!](http://oeis.org/A001589)
[Answer]
# 2. Haskell, 44 bytes, [A000010](https://oeis.org/A000010)
```
f k|n<-k+1=length.filter(==1)$gcd n<$>[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00huybPRjdb29A2JzUvvSRDLy0zpyS1SMPW1lBTJT05RSHPRsUu2lBPLy@Wiys3MTNPwVahoCgzr0RB5dCCNAWgpEK0gZ6eoYFB7P//AA "Haskell – Try It Online")
[Next Sequence](https://oeis.org/A000044)
[Answer]
# 30. [Python 1](https://www.python.org/download/releases/1.6.1/), 1112 bytes, [A000046](http://oeis.org/A000046)
```
def rotations(array):
rotations = []
for divider_index in range(len(array)):
rotations.append(array[divider_index:] + array[:divider_index])
return rotations
def next(array):
for index in range(len(array) - 1, -1, -1):
array[index] = 1 - array[index]
if array[index]: break
return array
def reverse(array):
reversed = []
for index in range(len(array) - 1, -1, -1):
reversed.append(array[index])
return reversed
def primitive(array):
for index in range(1, len(array)):
if array == array[:index] * (len(array) / index): return 1
return 0
def necklaces(size):
previous_necklaces = []
array = [0] * size
necklaces = 0
for iteration in range(2 ** size):
if not primitive(array) and array not in previous_necklaces:
necklaces = necklaces + 1
for rotation in rotations(array):
complement = []
for element in rotation:
complement.append(1 - element)
previous_necklaces.append(rotation)
previous_necklaces.append(complement)
previous_necklaces.append(reverse(rotation))
previous_necklaces.append(reverse(complement))
array = next(array)
return necklaces
```
[Try it online!](https://tio.run/##jVPbbsIwDH1uv8KPDZet3WMlvgQhlFGzRdCkSgMCfr7LvemqDZAqIdvH5/jY6e7qW/BqGBo8ghSKKiZ4X1Ap6Z3UeRZDsIHtLs@OQkLDrqxBuWe8wRswDpLyLyzOyD3OAEfkG@065I3LbSfgegdLcPF6ktgRTY3qIvkoKs@NRo43Ncozcv6UAWuoVrC2n5XkmByBnqfSBWlIV7DjJFLDp0R6ilpszumQeEXZY@KUCzSJUa8rC@CpVzMrfJVT0EnWMsWu@K8dmuPXYsKMsNkE770lC0g1vrtWpAZPX0UhZdjF4XSmB@yLnj3QNO@0RCYu/T6mvB2eEbaloTHleZbWlF68Qmm3PQ7wAQsHCOK5ULPZgfLGT2XSGjxXYuATzvH/0syWWQXh3KyA@XvQv4NouzO2yJWfzSPRBxOgAySIsF9zer6e2Jq53FAaej2rG0medvSnGzu/CkgoSHhO1sf4JOOFxB6DXhVXRUu7IsZW4TZLQsjwAw "Python 1 – Try It Online")
Not even going to bother to golf this. Hey, it's not my longest Python answer on this site!
[Next sequence](http://oeis.org/A001112)
[Answer]
# 9. [Pyth](https://github.com/isaacg1/pyth), 19 bytes, [A000025](https://oeis.org/A000025)
```
?>Q0sm@_B1-edld./Q1
```
[Test suite](http://pyth.herokuapp.com/?code=%3F%3EQ0sm%40_B1-edld.%2FQ1&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0).
[Next sequence](https://oeis.org/A000019)
>
> a(n) = number of partitions of n with even rank minus number with odd rank. The rank of a partition is its largest part minus the number of parts.
>
>
>
[Answer]
# 308. [ENIAC (simulator)](http://www.historicsimulations.com/Eniac/eniac.html), 3025 bytes, [A006060](http://oeis.org/A006060)
Pseudocode:
```
repeat{
M←input
N←-M
A←1
B←253
while(N<0){
C←60
C←C-A
repeat(194){
C←C+B
}
A←B
B←C
N←N+1
}
output←A
}
```
No online simulator, execution result:
[![Card reader input](https://i.stack.imgur.com/v2DNh.png)](https://i.stack.imgur.com/v2DNh.png)
[![Punch card output](https://i.stack.imgur.com/wJBcY.png)](https://i.stack.imgur.com/wJBcY.png)
Registers and constants:
```
A: 1-2
B: 3-4
C: 5-6
M: 7
N: 8
input: const. A
253: const. J
60: const. K
194: Master programmer decade limit 1B
```
Program signal flow and data flow:
[![Program signal flow and data flow chart](https://i.stack.imgur.com/rtNMc.png)](https://i.stack.imgur.com/rtNMc.png)
[Full "code"](https://pastebin.com/yjaUvDNi) on pastebin or in HTML comments in the markup of this answer, to prevent linkrot and a quite long answer to scroll through at the same time. This is fun!
[Next sequence](http://oeis.org/A003025)
[Answer]
# 8. Mathematica (10.1), 25 bytes, [A000070](http://oeis.org/A000070)
```
Tr@PartitionsP@Range@#+1&
```
[Next sequence](http://oeis.org/A000025)
[Answer]
# 206. [Proton](https://github.com/alexander-liao/proton), 3275 bytes, [A000109](https://oeis.org/A000109)
```
# This took me quite a while to write; if it's wrong, please tell me and I'll try to fix it without changing the byte count..
permutations = x => {
if len(x) == 0 return [ ]
if len(x) == 1 return [x]
result = []
for index : range(len(x)) {
for permutation : permutations(x[to index] + x[index + 1 to]) {
result.append([x[index]] + permutation)
}
}
return result
}
adjacency = cycles => {
cycles = cycles[to]
size = cycles.pop()
matrix = [[0] * size for i : range(size)]
for cycle : cycles {
i, j, k = cycle[0], cycle[1], cycle[2]
matrix[i][j] = matrix[i][k] = matrix[j][i] = matrix[j][k] = matrix[k][i] = matrix[k][j] = 1
}
return matrix
}
transform = a => [[a[j][i] for j : range(len(a[i]))] for i : range(len(a))]
isomorphic = (a, b) => {
return any(sorted(b) == sorted(transform(A)) for A : permutations(transform(a)))
}
intersection = (a, b) => [x for x : a if x in b]
union = (a, b) => [x for x : a if x not in b] + list(b)
validate = graph => {
matrix = adjacency(graph)
rowsums = map(sum, matrix)
r = 0
for s : rowsums if s + 1 < graph[-1] r++
return 2 || r
}
graphs = nodes => {
if nodes <= 2 return []
if nodes == 3 return [[(0, 1, 2), 3]]
result = []
existing = []
for graph : graphs(nodes - 1) {
graph = graph[to]
next = graph.pop()
for index : range(len(graph)) {
g = graph[to]
cycle = g.pop(index)
n = g + [(cycle[0], cycle[1], next), (cycle[1], cycle[2], next), (cycle[2], cycle[0], next), next + 1]
N = sorted(adjacency(n))
if N not in existing {
existing += [sorted(transform(a)) for a : permutations(transform(adjacency(n)))]
result.append(n)
}
for secondary : index .. len(graph) - 1 {
g = graph[to]
c1 = g.pop(index)
c2 = g.pop(secondary)
q = union(c1, c2)
g = [k for k : g if len(intersection(k, intersection(c1, c2))) <= 1]
if len(intersection(c1, c2)) == 2 {
for i : range(3) {
for j : i + 1 .. 4 {
if len(intersection(q[i, j], intersection(c1, c2))) <= 1 {
g.append((q[i], q[j], next))
}
}
}
}
g.append(next + 1)
N = sorted(adjacency(g))
if N not in existing {
existing += [sorted(transform(a)) for a : permutations(transform(adjacency(g)))]
result.append(g)
}
for tertiary : secondary .. len(graph) - 2 {
g = graph[to]
c1 = g.pop(index)
c2 = g.pop(secondary)
c3 = g.pop(tertiary)
q = union(union(c1, c2), c3)
g = [k for k : g if len(intersection(k, intersection(c1, c2))) <= 1 and len(intersection(k, intersection(c2, c3))) <= 1]
if len(q) == 5 and len(intersection((q1 = intersection(c1, c2)), (q2 = intersection(c2, c3)))) <= 1 and len(q1) == 2 and len(q2) == 2 {
for i : range(4) {
for j : i + 1 .. 5 {
if len(intersection(q[i, j], q1)) <= 1 and len(intersection(q[i, j], q2)) <= 1 {
g.append((q[i], q[j], next))
}
}
}
g.append(next + 1)
N = sorted(adjacency(g))
if N not in existing {
existing += [sorted(transform(a)) for a : permutations(transform(adjacency(g)))]
result.append(g)
}
}
}
}
}
}
return [k for k : result if max(sum(k[to -1], tuple([]))) + 1 == k[-1] and validate(k)]
}
x = graphs(int(input()) + 3)
print(len(x))
```
[Try it online!](https://tio.run/##tVdNb@M2ED1bv2KAHpaqFcOWdy/pusAee9lTb4IOjMzItGxKlqhGbje/PZ0hKUqWHadAWyCxxfme4XsUXdWlLtXb20/w@042oMuygKOAUyu1AA4vO3kQKIWXGgW/gHwGqT81uCxVHkF1ELxBvTgcyIurLfz2CZ91fSanZ9mhObxIvStbDdmOq1yqHPROwNMZE2Rlq/RiEQSVqI@t5lqWqoENdLD5Ff4KZpjuIBTrQthsYAm10G2tIIF0olp5VYeqWjTtQWOYBBfPZQ1SbUUHj1BjfsGsW0jxjXaUG23GlbAuwS6Mdwpz6BIbaI75dJnaCC7bgleVUFuWOKOUHEaxQjR9DejPVWrdgtcg4Ns9z4TKzlhxds4OonHd9wsnxVqwn0b@KbxoUZUVw9BHrmucNXacLFP4GYyR6dx3TaLQzcM4o8YloDZkBPsIij4yhonc08o/xejuUiUyTfYpWg/LYrTcpyi5WI61xaW2cKFW4/FYHY1HY/0NVn1EE06TSRLuElAv@4t95SgOw3TSu9GgOAhkUx7LutrJDKMxHsFT6Ibt8nJ1Zk1Za7FlTwZabuGrYN8QOhT@2xQsgwnmCql0qbSoG5EZaI3zJZ0JQZjkxCmkiYInrK9VH5uqUltzRNhBNhoLDYI/@EFuuSZo5DWvdq4rDwwPMmbUiJm6fGnaY2P2oWL4GLmhkw6lS4uVhqboTDF9Y9D/1SZJHlYp1PO5n14MP35ATa0bPQVX5dYDGv3t8usGTXvKpiMFDnztFQlbRrCKIA4jWKdTYosOe6fTZOC57fzRfjfMhnyAlWWqm4sr3ZBppkSne1FPpneODDs3R/p8EsdylYQmivGmUDPazBxnlrBbvKL02By7ZtpUF3vdctCZ6nE/TAXfwYN12GwVmipwvt973Pi5mUaGMc5xjldg5w7s/A7Yx8lCU8rkTDSHH3HbjhYJUaotx1fEoxvzYgHDhGnDXG1XU55lqxsznmWxl/rgVnNCheEUyxBIWRz6uElhGisILuBeJmO@siKCi7ULgANB9NqRz2759XaE5dg1Mrs8j9ZhL5/1R5g0vMJBfPaqm9FPCZ3U6d3ahgizvN8DckSvU7Lv4RP2Rq/Bxbf9sp/evUeadboJtdxFvIO1/xJsuQfbBG15OGqAwuGctLRwG6A3hZzfqWvMvQO6O6ibZWuv6rM7zQDIC1jixzocCviX4DQXsY99YpP1AtA95k4Gvl9uB2InGsjN/HheneIrZZ9oUt1p5UjiBfElaya0@TzQ5po3X0aov0sczHpvSoNdfE2nf8QnT6gps96j0weEuk@p/4tU79Dq1jHxOr3bjuDrXtnYwZF3dMtgBd2pH@hdp1v8/cCSlIBBu4hbX5grBW1Mf6FhBVaEF4qu52VD@4X/VauZcUTiVDXJ3MX@7W35Nw "Proton – Try It Online")
[Next Sequence](https://oeis.org/A003275)
[Answer]
# 15. CJam, 85 bytes, [A000060](https://oeis.org/A000060)
```
{ee\f{\~\0a*@+f*}:.+}:C;2,qi:Q,2f+{_ee1>{~2*\,:!X*X<a*~}%{CX<}*W=+}fX_0a*1$_C.- .+Q)=
```
[Online demo](http://cjam.aditsu.net/#code=%7Bee%5Cf%7B%5C~%5C0a*%40%2Bf*%7D%3A.%2B%7D%3AC%3B2%2Cqi%3AQ%2C2f%2B%7B_ee1%3E%7B~2*%5C%2C%3A!X*X%3Ca*~%7D%25%7BCX%3C%7D*W%3D%2B%7DfX_0a*1%24_C.-%20.%2BQ)%3D&input=5)
[Next sequence](https://oeis.org/A000085)
### Dissection
OEIS gives
>
> G.f.: S(x)+S(x^2)-S(x)^2, where S(x) is the generating function for A000151. - Pab Ter, Oct 12 2005
>
>
>
where
$$\begin{eqnarray\*}S(x) & = & x \prod\_{i \ge 1} \frac{1}{(1 - x^i)^{2s(i)}} \\ & = & x \prod\_{i \ge 1} (1 + x^i + x^{2i} + \ldots)^{2s(i)}\end{eqnarray\*}$$
```
{ e# Define a block to convolve two sequences (multiply two polynomials)
ee\f{ e# Index one and use the other as an extra parameter for a map
\~\0a* e# Stack manipulations; create a sequence of `index` 0s
@+f* e# Shift the extra parameter poly and multiply by the coefficient
}
:.+ e# Fold pointwise add to sum the polys
}:C; e# Assign the block to C (for "convolve")
2, e# Initial values of S: S(0) = 0, S(1) = 1
qi:Q e# Read integer and assign it to Q
,2f+{ e# For X = 2 to Q+1
_ee1> e# Duplicate accumulator of S, index, and ditch 0th term
{ e# Map (over notional variable i)
~2*\ e# Double S(i) and flip i to top of stack
,:! e# Create an array with a 1 and i-1 0s
X*X< e# Replicate X times and truncate to X values
e# This gives g.f. 1/(1-x^i) to the first X terms
a*~ e# Create 2S(i) copies of this polynomial
}%
{CX<}* e# Fold convolution and truncation to X terms
W=+ e# Append the final coefficient, which is S(X), to the accumulator
}fX
_0a* e# Pad a copy to get S(X^2)
1$_C e# Convolve two copies to get S(X)^2
.- e# Pointwise subtraction
.+ e# Pointwise addition. Note the leading space because the parser thinks
e# -. is an invalid number
Q)= e# Take the term at index Q+1 (where the +1 adjusts for OEIS offset)
```
[Answer]
# 67. [LOLCODE](http://lolcode.org/), 837 bytes, [A000043](https://oeis.org/A000043)
```
HAI 1.2
CAN HAS STDIO?
I HAS A CONT ITZ 0
I HAS A ITRZ ITZ 1
I HAS A NUMBAH
GIMMEH NUMBAH
NUMBAH R SUM OF NUMBAH AN 1
IM IN YR GF
ITRZ R SUM OF ITRZ AN 1
I HAS A PROD ITZ 1
IM IN YR MOM UPPIN YR ASS WILE DIFFRINT ITRZ AN SMALLR OF ITRZ AN ASS
PROD R PRODUKT OF PROD AN 2
IM OUTTA YR MOM
PROD R DIFF OF PROD AN 1
I HAS A PRAIME ITZ WIN
I HAS A VAR ITZ 1
IM IN YR MOM
VAR R SUM OF VAR AN 1
BOTH SAEM VAR AN PROD, O RLY?
YA RLY, GTFO
OIC
BOTH SAEM 0 AN MOD OF PROD AN VAR, O RLY?
YA RLY
PRAIME R FAIL
GTFO
OIC
IM OUTTA YR MOM
BOTH SAEM PRAIME AN WIN, O RLY?
YA RLY, CONT R SUM OF CONT AN 1
OIC
BOTH SAEM NUMBAH AN CONT, O RLY?
YA RLY, GTFO
OIC
IM OUTTA YR GF
VISIBLE ITRZ
KTHXBYE
```
My capslock key is bound to escape, so I wrote this entire thing while holding shift ..
[Try it online!](https://tio.run/##dVJBbsIwELznFfMAVAFSz2gDCVkRx8h2oOHa9obE/0@pvU6MgXJKZjyemV35ert@335@x7EhxupjXQBb6tCQhXU71htPsEDCVncO7C5YZiQ7cxFylZFdr0pqPLFnparmjuMPDGyvoOsZ@8RVEe4rcIfBYF97hGiexIJm6T3saPQuNcg8lFboj8cIyFqcua2w47o2LINEN6uobU3u77XihGht5NMfXNAI4zXrOUv3ztEUV2R3Qk5@4aU0saqk9pm7h6MTmTfjTK2CIC0lALGPZ6V2DSxVaj4I@QtomHbYTBpgoIAX2LtaT6Tm7YvFMhgo3z@bw9u@sUsQ83QGNXGb8f/kPa@weKwwOflgv6an4HkKeZdpIYLSRkLMk@X9zQXpG8/UNPbMW8rbPLHlsq3kzRQH13yVQzWOn38)
[Next sequence](https://oeis.org/A000837)
[Answer]
# 10. Magma, 65 bytes, [A000019](https://oeis.org/A000019)
```
f:=function(n);return NumberOfPrimitiveGroups(n+1);end function;
```
Try it [here](http://magma.maths.usyd.edu.au/calc/)
lol builtin
[Next sequence](https://oeis.org/A000065)
[Answer]
# 281. Java 5, 11628 bytes, [A000947](https://oeis.org/A947)
```
// package oeis_challenge;
import java.util.*;
import java.lang.*;
class Main {
// static void assert(boolean cond) {
// if (!cond)
// throw new Error("Assertion failed!");
// }
/* Use the formula a(n) = A000063(n + 2) - A000936(n).
It's unfair that I use the formula of "number of free polyenoid with n
nodes and symmetry point group C_{2v}" (formula listed in A000063)
without understanding why it's true...
*/
static int catalan(int x) {
int ans = 1;
for (int i = 1; i <= x; ++i)
ans = ans * (2*x+1-i) / i;
return ans / -~x;
}
static int A63(int n) {
int ans = catalan(n/2 - 1);
if (n%4 == 0) ans -= catalan(n/4 - 1);
if (n%6 == 0) ans -= catalan(n/6 - 1);
return ans;
}
static class Point implements Comparable<Point> {
final int x, y;
Point(int _x, int _y) {
x = _x; y = _y;
}
/// @return true if this is a point, false otherwise (this is a vector)
public boolean isPoint() {
return (x + y) % 3 != 0;
}
/// Translate this point by a vector.
public Point add(Point p) {
assert(this.isPoint() && ! p.isPoint());
return new Point(x + p.x, y + p.y);
}
/// Reflect this point along x-axis.
public Point reflectX() {
return new Point(x - y, -y);
}
/// Rotate this point 60 degrees counter-clockwise.
public Point rot60() {
return new Point(x - y, x);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return 21521 * (3491 + x) + y;
}
public String toString() {
// return String.format("(%d, %d)", x, y);
return String.format("setxy %d %d", x * 50 - y * 25, y * 40);
}
public int compareTo(Point p) {
int a = Integer.valueOf(x).compareTo(p.x);
if (a != 0) return a;
return Integer.valueOf(y).compareTo(p.y);
}
/// Helper class.
static interface Predicate {
abstract boolean test(Point p);
}
static abstract class UnaryFunction {
abstract Point apply(Point p);
}
}
static class Edge implements Comparable<Edge> {
final Point a, b; // guarantee a < b
Edge(Point x, Point y) {
assert x != y;
if (x.compareTo(y) > 0) { // y < x
a = y; b = x;
} else {
a = x; b = y;
}
}
public int compareTo(Edge e) {
int x = a.compareTo(e.a);
if (x != 0) return x;
return b.compareTo(e.b);
}
}
/// A graph consists of multiple {@code Point}s.
static class Graph {
private HashMap<Point, Point> points;
public Graph() {
points = new HashMap<Point, Point>();
}
public Graph(Graph g) {
points = new HashMap<Point, Point>(g.points);
}
public void add(Point p, Point root) {
assert(p.isPoint());
assert(root.isPoint());
assert(p == root || points.containsKey(root));
points.put(p, root);
}
public Graph map(Point.UnaryFunction fn) {
Graph result = new Graph();
for (Map.Entry<Point, Point> pq : points.entrySet()) {
Point p = pq.getKey(), q = pq.getValue();
assert(p.isPoint()) : p;
assert(q.isPoint()) : q;
p = fn.apply(p); assert(p.isPoint()) : p;
q = fn.apply(q); assert(q.isPoint()) : q;
result.points.put(p, q);
}
return result;
}
public Graph reflectX() {
return this.map(new Point.UnaryFunction() {
public Point apply(Point p) {
return p.reflectX();
}
});
}
public Graph rot60() {
return this.map(new Point.UnaryFunction() {
public Point apply(Point p) {
return p.rot60();
}
});
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o.getClass() != getClass()) return false;
Graph g = (Graph) o;
return points.equals(g.points);
}
@Override
public int hashCode() {
return points.hashCode();
}
Graph[] expand(Point.Predicate fn) {
List<Graph> result = new ArrayList<Graph>();
for (Point p : points.keySet()) {
int[] deltaX = new int[] { -1, 0, 1, 1, 0, -1};
int[] deltaY = new int[] { 0, 1, 1, 0, -1, -1};
for (int i = 6; i --> 0;) {
Point p1 = new Point(p.x + deltaX[i], p.y + deltaY[i]);
if (points.containsKey(p1) || !fn.test(p1)
|| !p1.isPoint()) continue;
Graph g = new Graph(this);
g.add(p1, p);
result.add(g);
}
}
return result.toArray(new Graph[0]);
}
public static Graph[] expand(Graph[] graphs, Point.Predicate fn) {
Set<Graph> result = new HashSet<Graph>();
for (Graph g0 : graphs) {
Graph[] g = g0.expand(fn);
for (Graph g1 : g) {
if (result.contains(g1)) continue;
result.add(g1);
}
}
return result.toArray(new Graph[0]);
}
private Edge[] edges() {
List<Edge> result = new ArrayList<Edge>();
for (Map.Entry<Point, Point> pq : points.entrySet()) {
Point p = pq.getKey(), q = pq.getValue();
if (p.equals(q)) continue;
result.add(new Edge(p, q));
}
return result.toArray(new Edge[0]);
}
/**
* Check if two graphs are isomorphic... under translation.
* @return {@code true} if {@code this} is isomorphic
* under translation, {@code false} otherwise.
*/
public boolean isomorphic(Graph g) {
if (points.size() != g.points.size()) return false;
Edge[] a = this.edges();
Edge[] b = g.edges();
Arrays.sort(a);
Arrays.sort(b);
// for (Edge e : b)
// System.err.println(e.a + " - " + e.b);
// System.err.println("------- >><< ");
assert (a.length > 0);
assert (a.length == b.length);
int a_bx = a[0].a.x - b[0].a.x, a_by = a[0].a.y - b[0].a.y;
for (int i = 0; i < a.length; ++i) {
if (a_bx != a[i].a.x - b[i].a.x ||
a_by != a[i].a.y - b[i].a.y) return false;
if (a_bx != a[i].b.x - b[i].b.x ||
a_by != a[i].b.y - b[i].b.y) return false;
}
return true;
}
// C_{2v}.
public boolean correctSymmetry() {
Graph[] graphs = new Graph[6];
graphs[0] = this.reflectX();
for (int i = 1; i < 6; ++i) graphs[i] = graphs[i-1].rot60();
assert(graphs[5].rot60().isomorphic(graphs[0]));
int count = 0;
for (Graph g : graphs) {
if (this.isomorphic(g)) ++count;
// if (count >= 2) {
// return false;
// }
}
// if (count > 1) System.err.format("too much: %d%n", count);
assert(count > 0);
return count == 1; // which is, basically, true
}
public void reflectSelfType2() {
Graph g = this.map(new Point.UnaryFunction() {
public Point apply(Point p) {
return new Point(p.y - p.x, p.y);
}
});
Point p = new Point(1, 1);
assert (p.equals(points.get(p)));
points.putAll(g.points);
assert (p.equals(points.get(p)));
Point q = new Point(0, 1);
assert (q.equals(points.get(q)));
points.put(p, q);
}
public void reflectSelfX() {
Graph g = this.reflectX();
points.putAll(g.points); // duplicates doesn't matter
}
}
static int A936(int n) {
// if (true) return (new int[]{0, 0, 0, 1, 1, 2, 4, 4, 12, 10, 29, 27, 88, 76, 247, 217, 722, 638, 2134, 1901, 6413})[n];
// some unreachable codes here for testing.
int ans = 0;
if (n % 2 == 0) { // reflection type 2. (through line 2x == y)
Graph[] graphs = new Graph[1];
graphs[0] = new Graph();
Point p = new Point(1, 1);
graphs[0].add(p, p);
for (int i = n / 2 - 1; i --> 0;)
graphs = Graph.expand(graphs, new Point.Predicate() {
public boolean test(Point p) {
return 2*p.x > p.y;
}
});
int count = 0;
for (Graph g : graphs) {
g.reflectSelfType2();
if (g.correctSymmetry()) {
++count;
// for (Edge e : g.edges())
// System.err.println(e.a + " - " + e.b);
// System.err.println("------*");
}
// else System.err.println("Failed");
}
assert (count%2 == 0);
// System.err.println("A936(" + n + ") count = " + count + " -> " + (count/2));
ans += count / 2;
}
// Reflection type 1. (reflectX)
Graph[] graphs = new Graph[1];
graphs[0] = new Graph();
Point p = new Point(1, 0);
graphs[0].add(p, p);
if (n % 2 == 0) graphs[0].add(new Point(2, 0), p);
for (int i = (n-1) / 2; i --> 0;)
graphs = Graph.expand(graphs, new Point.Predicate() {
public boolean test(Point p) {
return p.y > 0;
}
});
int count = 0;
for (Graph g : graphs) {
g.reflectSelfX();
if (g.correctSymmetry()) {
++count;
// for (Edge e : g.edges())
// System.err.printf(
// "pu %s pd %s\n"
// // "%s - %s%n"
// , e.a, e.b);
// System.err.println("-------/");
}
// else System.err.println("Failed");
}
if(n % 2 == 0) {
assert(count % 2 == 0);
count /= 2;
}
ans += count;
// System.err.println("A936(" + n + ") = " + ans);
return ans;
}
public static void main(String[] args) {
// Probably
if (! "1.5.0_22".equals(System.getProperty("java.version"))) {
System.err.println("Warning: Java version is not 1.5.0_22");
}
// A936(6);
for (int i = 0; i < 20; ++i)
System.out.println(i + " | " + (A63(i+9) - A936(i+7)));
//A936(i+2);
}
}
```
[Try it online!](https://tio.run/##zVp7b9s4Ev/fn2LiQ3alxJYtJ3XbTRO0KLqPu1u02O7e7aJXFLRN22plSZbkxLqs76v3ZkjqTSppryjOSGtZmhdnhr8ZknrPrtkwjHjwfvHh8cePo5Pe63DDIWKLhResIA0h5my@BtedTh7BLEt54vT@Uvn0Tka93miEHPMPbMUh5F7ybr5mvs@DFb/o9bxNFMYpvEdFzi71fOfkonbPZ8GK7vXmPksS@Jl5AdwKkZCkLPXmcB16C8BnPE6tWRj6nAUwD4OFjXRERh9vCdaRuFncok@6jsMbCPgNvIjjMLb6z4QYLwxgyTyfL4769oXgOPR6xDA6gd8SjnwclmG82fkMmBXYcAnPxviZnlkBnMLEhqG48fhsik8dwfpT@m0CuwDlxsjPUvgJdg1R4RL6wW4z4zFdLmOOng79jAc0whsvXUMgRAXhgifAggUk2WbD0zhDOi9IYRWHuwiev7udXB/6YOVyfS9J@QLQc8pKW4ghieEuRaMWPEZnBiKmN@sMPLI1jXfccaTxFEX6Vi4nXXOWMgyORdd78nXuVLrBggR94l4UN9EUEKSeuI9fTy5hfwGnp57dg8pHctL/J2BNTvan7tCzYQReKSvm6S4OBM0Ihv/ZyyeHloXPMBz0HeitywcQjCYYLtcuFVC2BMfncHkJY1tQD6vk51ryqYl82iAvzdcZLtP8lQgnzgOfb3iQJvA83EQsZjOfPxHPripDWnoB88XA9gPISkWCUHjgHT4Q31nVFfTZoyPeYRwy@q7wKqNEzmP@P1VGU07QeNO1lwD@MZl4A5wuPiZziNkc33h4ZZUU13yehnEZ5Wg383Gg@VT1Emln0zKl0drjhEKzj@EMjtDBRhN/jdGjPku5NE5OiFlWGOA0DZA@RiSz5FXUtEBhColzSiu/@QaOICpvVCJbMZswRRKQ/ZFDkREXmW0cwS986aOpVfuZH@KU3A/ZHm3QDyCWXL@bHFi1ZAjZAIZdJoRpw4PTMSz4CqEoQVDdBSmPh3M/nH@gKJssCtPp@N7m7PXWPH15zePYW3BT3vDtDnPOejl7Tz4Lm@oE4lshpj0h25wjoAq1tp1bIlK2HjyVCDgXZE7YEGqju6e5jkGlZMjkdfZpoyA9a5asnyOUm1w1cR9MXILBs/PHLiYPouwp6PUoqa/TWJZledESjBFWsiWBQxWCpVbfOl4M4Hhh9wcCQ/Q53eBJeLrPkAn/iA0NfTCmkOLF5MFAfJ@P7S5zRRkRwMZ/DU2zUEwDjMhPmHsrHjvXzN/xl0trbzslL8aiYTPFnwnEKALOtKNqys3qcjsmy4/cj7BUC8Qup0JZgHi8ZHMOr2K@8OY0rRrwMkvSmGHu5hmNzVNaeEGrVckuOGWx@C1gcfb9LpiLxsWgRKFdFPmZWYeuFL1YYNumr0T0qF2IlKYBzC4o4VY7pEZncIziE5gVxMSsLMGUkxeZHoIxuTCQWTvA@0qokPeKgn1LSjNUta@RC2lAUmAG1HrUnh6AU/261bLsJUtD/@HeiS08yHV5TdWXVcbAHaZJ4309jffaNJ7VxMxqsa0YSXn7DPtEFq2pSU6wM0yo2cQ@MfUwxnD7dI6QJONxUGldy4cfBG85lij2rim5f0Q0@5lFsj1RAb2SRQQbnaaHhJQWPklqdApVCa1AqxNQpFRp4eozhK8cSdSpRK43yrZhUJS9MDW0EOZ2QREQ7100ERUaIoQ//1SDwZgHKa6Ikr/xTMhosiqyaIfsA2nhnf6DDYvk2Jw6siyD5vAkfcwTzB7lWBXYuhmi@0d3Oy8CXKw0U2QL3@WGcnr@mpMPNJOxLM/R1lnxlEZtD2Bb3PgHYXhTuSEOpNRIuK0TbtuEZMUycCSgIpTeX8W2yrktOe/WKR3t1IO6tU24VEEHyXl36O9qJkUvTPlRtHH1HLF0Yav327UKpKGuaIuc0p62N@oDPdwjsTsb068@NGnMZ47rS7THIQFKsPP9rpZYENLcek7oj07AWlT@6uJUMEzNtLg0NdP51JcGd0Pw/9RPK0UlmVaFsPXNW@D7iAUK5J2yh2uD4N@xhj4RXFd1KHwWxyyrPCWFbVjMQa3AwA/cjIBIgKYtuJ@y35UWeesWhu4AxgNwxR9dDd3DRZeAPxoCSm7BbBBQ28iZ0kbOcIh914Up39XwXKVMAhwtnU7VMN54bwe0fspv/IE3NLMiz0VN4Ytcm0riEYKqaKHxt5adPkQXuVWkJUlesOON2LSzuKxuBBUGE1cOdQYRei8yUCgQJ7LV3bO/Z0ZzJw1FhlmFYW/GbztRUPVxjQzPf4qmMFFluTPjMT21CU9NVflMn@7Kn2PMd6lQlziFSSh4NXaUoWiIIR@VUJeEmhKRkkc5Lk8ea@XWEuCucLlfLV6qp6aVAwUKvxJLiztyCWaAHfHw/64XE7M4h/ttZwAqzheb9LRkFC3P/XuemteFP01OH52clGJO4Pmazz@Ivc6bUKUq4PIKvCTchHG09uaO48i9c0jV3iO2CU5VRr5tqhZVtHt6IJH5b8SRA4h90lxmlbsle5Azimp7KLdbq0pH5o3WXIlphVTB18T7N1fF3qnd6qr4Kl1pzSy6KZW3WiJaUa/0FCJeqC/Epph1PJs1AQbXtiK75YIbM3nWLgRI8zpLUr5xsJFwcKIFqR/QwhvrTx@G@O8U6utnM1d/KD9wdfXkCfSb5qjNC4s5dNiVrsX@xEU3CXZkM3Xd3AmgDvPdTGwZYA47zKEN1Jm6HNCzrHyWlc8yzfzPC/hYnMRArl6ex@j6DtpNI@VHpMErtatLLKta9BRGlTxZyZN1JZJW5axUObuvylmpctatUo/cNGMN@3/qmM0xTbd5GMfYer9WJ3QCvnvaIiexpdJgvJm@rRsnSTCc@cwyrYs0x2zUpImoKiEeCcmvh@5b/UJErUkV3YOCyqmgSGGVrUlVcVgAtQObZrnubAEo/OrkpVSI6HN6KiRf6CY28Ui9V5d0CKtvBMpNcEPmIcGho7zUFQE2nxVoyDfH0zCEzW6@/g6OF8dBfyD9oXdyLmms33ZXnhTxRN036Ik1gvkAZizBDs33s4HI07u2rFTOvOb@8tcs4hNLv5uzynPsq62Fq@sCmq7itKy@825eGxvOb0qZtKQxoG7RhagKh12LFdl2U2q53/LM96sL1E8U2rZ0W7N0bLZ0qxG6tbt3@7Z372JWUuL3u9LBBDkm71CuLnaRLxYRCSxCngTfpoCzI@Vx98GDOLyndydap/dq7lG6F2BuFYvY27FYuxbr2MkAzsWfi1cu3p48xn8PB/Do0QAeTvH6HH9MXPzv4QRJpmeP6OcZcTweo4DpuXt2sN8Eby9qyJ/QOzC7QLz6QgchMBcvZGAzJt7lEAc5dFKmeelgXJEk3huAY5ioNwduJTQJN9N@a4qzFCYO4WAc7lZr8L0Ab4jDx8y@by1xO2pJbcP2c2ZSIUwue@Wq11yRAhiBeNmism/QmuPFGIRl@eIvX52WiFSsUC0TvjQqcu18zcBSPX49oW2Kq/rZrhmMtID0JSrhymkjt75dWjmtpsM0zqKMmkpkvZEuOnXzzsrnNdb3arBPWq21OQQoSBzl6aR9L97p6tudnV8OucI/x2puthcaOvkCs2ic9BJY3y4iT7fktXDFlbghFYwmrXJDQHF6qRhwvlQe1xvQXxpQ4Tq0wyFR2m5vaN6BDXfjggETqm1LNx40Aa9OXQqdkNAGbw1HrGDo2sI3Bhz5MhjyGfhRbO9n1NB9UgNjwIp74UQNI1ol@hOwoau9NkLCfWf00urp5PajHRwnEC3w/38FfR0JUSHJECmwm9ZKGSC6sIEBYrrX76MWvrQ6/k/AlEM14esF3tz9F0R12xUIXBIKtG2rIkW9Q7kPOklcQhnVwRteTqxvIIveccO8wJKvBNGeT7xKaitcNOJVHM6wPcpq8/8I@q7zwBm/m0z6eVOrrMWmFlkidEpm9cXLv9c8ThDe@nYrV3UD/CeLA7TmO/gr8oLipe21IEyhUGp6n0d2nFMj5qitkslY89KqsibcpYU1nsD6PyXUizdRTx@L14JFX3v6sNa8j0bq9sTO3X74@PG/ "Java (OpenJDK 9) – Try It Online")
---
Side note:
1. Tested locally with Java 5. (such that the warning is not printed - see TIO debug tab)
2. Don't. Ever. Use. Java. 1. It's more verbose than Java in general.
3. ~~This may break the chain.~~
4. The gap (7 days and 48 minutes) is no more than the gap created by [this answer](https://codegolf.stackexchange.com/a/144823), which is 7 days and 1 hours 25 minutes later than [the previous one](https://codegolf.stackexchange.com/a/144327).
5. ~~New record on large bytecount!~~ Because I (mistakenly?) use spaces instead of tabs, the bytecount is larger than necessary. On my machine it's [9550](https://oeis.org/A9550) bytes. (at the time of writing this revision)
6. [Next sequence](http://oeis.org/A011628).
7. The code, in its current form, only prints the first 20 terms of the sequence. However it's easy to change so that it will prints first 1000 items (by change the `20` in `for (int i = 0; i < 20; ++i)` to `1000`)
Yay! This can compute more terms than listed on the OEIS page! (for the first time, for a challenge I need to use Java) unless OEIS has more terms somewhere...
---
# Quick explanation
### Explanation of the sequence description.
The sequence ask for the number of free nonplanar polyenoid with symmetry group C2v, where:
* polyenoid: (mathematical model of polyene hydrocarbons) trees (or in degenerate case, single vertex) with can be embedded in hexagonal lattice.
For example, consider the trees
```
O O O O (3)
| \ / \
| \ / \
O --- O --- O O --- O O --- O
| \
| (2) \
(1) O O
```
The first one cannot be embedded in the hexagonal lattice, while the second one can. That particular embedding is considered different from the third tree.
* nonplanar polyenoid: embedding of trees such that there exists two overlapping vertices.
`(2)` and `(3)` tree above are planar. This one, however, is nonplanar:
```
O---O O
/ \
/ \
O O
\ /
\ /
O --- O
```
(there are 7 vertices and 6 edges)
* free polyenoid: Variants of one polyenoid, which can be obtained by rotation and reflection, is counted as one.
![](https://i.stack.imgur.com/Jr65M.png)
* C2v group: The polyenoid are only counted if they have 2 perpendicular planes of reflection, and no more.
For example, the only polyenoid with 2 vertices
```
O --- O
```
has 3 planes of reflection: The horizontal one `-`, the vertical one `|`, and the one parallel to the computer screen `■`. That's too much.
On the other hand, this one
```
O --- O
\
\
O
```
has 2 planes of reflection: `/` and `■`.
---
### Explanation of the method
And now, the approach on how to actually count the number.
First, I take the formula `a(n) = A000063(n + 2) - A000936(n)` (listed on the OEIS page) for granted. I didn't read the explanation in the paper.
[TODO fix this part]
Of course, counting planar is easier than counting nonplanar. That's what the paper does, too.
>
> Geometrically planar polyenoids (without overlapping vertices) are enumerated by computer
> programming. Thus the numbers of geometrically nonplanar polyenoids become accessible.
>
>
>
So... the program counts the number of planar polyenoid, and subtract it from the total.
Because the tree is planar anyway, it obviously has the `■` plane of reflection. So the condition boils down to "count number of tree with an axis of reflection in its 2D representation".
The naive way would be generate all trees with `n` nodes, and check for correct symmetry. However, because we only want to find the number of trees with an axis of reflection, we can just generate all possible half-tree on one half, mirror them through the axis, and then check for correct symmetry. Moreover, because the polyenoids generated are (planar) trees, it must touch the axis of reflection exactly once.
The function `public static Graph[] expand(Graph[] graphs, Point.Predicate fn)` takes an array of graphs, each have `n` nodes, and output an array of graph, each has `n+1` nodes, not equal to each other (under translation) - such that the added node must satisfy the predicate `fn`.
Consider 2 possible axes of reflection: One that goes through an vertex and coincide with edges (`x = 0`), and one that is the perpendicular bisector of an edge (`2x = y`). We can take only one of them because the generated graphs are isomorphic, anyway.
[![](https://i.stack.imgur.com/1USCZm.png)](https://i.stack.imgur.com/1USCZ.png)
So, for the first axis `x = 0`, we start from the base graph consists of a single node `(1, 0)` (in case `n` is odd) or two nodes with an edge between `(1, 0) - (2, 0)` (in case `n` is even), and then expand nodes such that `y > 0`. That's done by the "Reflection type 1" section of the program, and then for each generated graph, reflect (mirror) itself through the X axis `x = 0` (`g.reflectSelfX()`), and then check if it has the correct symmetry.
However, note that if `n` is divisible by 2, by this way we counted each graph twice, because we also generate its mirror image by the axis `2x = y + 3`.
[![](https://i.stack.imgur.com/SGf7Um.png)](https://i.stack.imgur.com/SGf7U.png)
(note the 2 orange ones)
Similar for the axis `2x = y`, if (and only if) `n` is even, we start from the point `(1, 1)`, generate graphs such that `2*x > y`, and reflect each of them over the `2x = y` axis (`g.reflectSelfType2()`), connect `(1, 0)` with `(1, 1)`, and check if they have correct symmetry. Remember to divide by 2, too.
[Answer]
# 24. [Julia 0.5](http://julialang.org/), 33 bytes, [A000023](https://oeis.org/A000023)
Expansion of [e.g.f.](https://en.wikipedia.org/wiki/Generating_function#Exponential_generating_function_.28EGF.29) exp(−2\*x)/(1−x).
```
!x=foldl((a,b)->a*b+(-2)^b,1,1:x)
```
[Try it online!](https://tio.run/##yyrNyUw0/f9fscI2LT8nJUdDI1EnSVPXLlErSVtD10gzLknHUMfQqkLzf0FRZl6JhqKhgeZ/EwA "Julia 0.5 – Try It Online")
[Next sequence.](https://oeis.org/A000033)
[Answer]
# 91. [Python 2 (PyPy)](http://pypy.org/), 1733 bytes, [A000066](https://oeis.org/A000066)
```
import itertools
girth = int(input()) + 3
v = 4
r = range
def p(v):
a = [0 for i in r(v)]
k = int((v * 2) ** .5)
a[k - 1] = a[k - 2] = a[k - 3] = 1
j = len(a) - 1
for i in r(1, 3):
a[j] = 1
j -= i
yield [x for x in a]
while not all(a):
for index in r(len(a) - 1, -1, -1):
a[index] ^= 1
if a[index]: break
yield [x for x in a]
def wrap_(p, v):
m = [[0 for j in r(v)] for i in r(v)]
k = 0
for i in r(0, v - 1):
for j in r(i + 1, v):
m[i][j] = m[j][i] = p[k]
k += 1
return m
def completes_cycle(edgelist):
if not edgelist or not edgelist[1:]: return False
start = edgelist[0]
edge = edgelist[0]
e = [x for x in edgelist]
edgelist = edgelist[1:]
while edgelist:
_edges = [_edge for _edge in edgelist if _edge[0] in edge or _edge[1] in edge]
if _edges:
edgelist.remove(_edges[0])
if _edges[0][1] in edge: _edges[0] = (_edges[0][1], _edges[0][0])
edge = _edges[0]
else:
return False
flat = sum(e, ())
for i in flat:
if flat.count(i) != 2: return False
return edge[1] in start
def powerset(a):
return sum([list(itertools.combinations(a, t)) for t in r(len(a))], [])
while True:
ps = (v * (v - 1)) // 2
skip = False
for Q in p(ps):
m = wrap_(Q, v)
output = [row + [0] for row in m]
output.append([0 for i in r(len(m[0]))])
for i in r(len(m)):
output[i][-1] = sum(m[i])
output[-1][i] = sum(row[i] for row in m)
if all(map(lambda x: x == 3, map(sum, m))):
edges = []
for i in r(v):
for j in r(i, v):
if m[i][j]: edges.append((i, j))
for edgegroup in powerset(edges):
if completes_cycle(list(edgegroup)):
if len(edgegroup) == girth:
print(v)
exit(0)
else:
skip = True
break
if skip: break
v += 1
```
[Try it online!](https://tio.run/##bVVLbyIxDD5PfoX3lrQD5dG9IHHde6W9jdgqhUAD84gy4fXrWdvJDENbJERiO5/tzw/cNXw29Wzkru56u9nKNT6ADcaHpilbIXbWh09Ygq2DtLU7BqkUPMNciBNKX4Xw@ON1vTNCbMwWnDyphcg0SosJbBsPFt@CR/FKZIeEJE/wBDMFT08w/q3QvDjACKYrVMfj7H6c03Eqsj3@lKaWWpGpyAbY0xzm5BVx9skazUfoS2RXa8oNFBeO5UL2GgM5f9rSQN0E0GWJkPSYAeuNuUTQu68cRvxlK/TBRiv4Fx1ldgudbAEf3ugDSn90ywydvXbv0uXARFVEVGJq3zP1I3GTh5wnCEDB9aGn1xarM03gWVYVdhU5qfAHL3hyxWFFugM8cwbehKOvoYrhrZvKlSaY9n19XZdGms3OlLYNhIeZEmWdCNDr8F5MF8hAgvujy9aIrA0aG2p5t5mgb7p8kxERA7o6ZTJnf8sHV10VOxkl/E6XlqD4xHDxNIAEzIOF6LiTQ2dYTHsZsdSZtkxnhzD2pmpORkYVwqjUCL1gALO4SzEwOTTJBw8SSOKml6PMIJPs/pHabamJkvZYSZMDzuWgP0i3iOHTcbxujjTACn4tYfa1Ruk2yJ6rlga6ORvfmhCHJJmSz4KIkP2qQBfVh611sE3dSp1DwEVB8YThOClMucBERSzdX3@kzBxVjHeCjD2t4OUFZtg9B@tQ1SWMaG@E5qRrub9peuI8vVHLo6Q5BlxS1AC@OeMoEOn0jm74slr1NmPtnKk38nFNUZgV1UJxOb5qVByriECzNeKlRXzQqKmBEjVx3kiJ7ukyjETF8tD@qbSTpa4@NhouC2z/5RLmOZAU3@JBJbd9c/P8PuwI1j/sgX4HsJu0CBZc5bbLnaz2SnVopNv55uiY5K7w/CJB2e8Lgtugf6kGPomxu4Ky4n@TZJA5T38FXDX6mIsNcpJufcvjJzUB9UqSdEsWfZCy37on3mi32/Q/ "Python 2 (PyPy) – Try It Online")
I hope using Python 2 PyPy counts as another major version. If someone could get me a Python 0 interpreter, I could use that too, but I hope this is valid.
This starts at 1 vertex and works up, creating the adjacency matrix representation of every possible undirected graph with that many vertices. If it is trivalent, then it will look through the powerset of the edges, which will be sorted by length. If the first cycle it finds is too short, then it will move on. If the first cycle it finds matches the input (offset by 3) then it will output the correct vertex count and terminate.
[Next Sequence](https://oeis.org/A001733) <-- have an easy one as a break from all this math nonsense :D
**EDIT**: I added some optimizations to make it a bit faster (still can't compute the third term within TIO's 60 second limit though) without changing the bytecount.
[Answer]
# 156. C# (Mono), 2466 bytes, [A000083](https://oeis.org/A000083)
Note: the score is 2439 bytes for the code and 27 for the compiler flag `-reference:System.Numerics`.
```
using Num = System.Numerics.BigInteger;
namespace PPCG
{
class A000083
{
static void Main(string[] a)
{
int N = int.Parse(a[0]) + 1;
var phi = new int[N + 1];
for (int i = 1; i <= N; i++)
phi[i] = 1;
for (int p = 2; p <= N; p++)
{
if (phi[p] > 1) continue;
for (int i = p; i <= N; i += p)
phi[i] *= p - 1;
int pa = p * p;
while (pa <= N)
{
for (int i = pa; i <= N; i += pa)
phi[i] *= p;
pa *= p;
}
}
var aik = new Num[N + 1, N + 1];
var a035350 = new Num[N + 1];
var a035349 = new Num[N + 1];
aik[0, 0] = aik[1, 1] = a035350[0] = a035350[1] = a035349[0] = a035349[1] = 1;
for (int n = 2; n <= N; n++)
{
// A000237 = EULER(A035350)
Num nbn = 0;
for (int k = 1; k < n; k++)
for (int d = 1; d <= k; d++)
if (k % d == 0) nbn += d * a035350[d] * aik[1, n - k];
aik[1, n] = nbn / (n - 1);
// Powers of A000237 are used a lot
for (int k = 2; k <= N; k++)
for (int i = 0; i <= n; i++)
aik[k, n] += aik[k - 1, i] * aik[1, n - i];
// A035350 = BIK(A000237)
Num bn = 0;
for (int k = 1; k <= n; k++)
{
bn += aik[k, n];
if (k % 2 == 1)
for (int i = n & 1; i <= n; i += 2)
bn += aik[1, i] * aik[k / 2, (n - i) / 2];
else if (n % 2 == 0)
bn += aik[k / 2, n / 2];
}
a035350[n] = bn / 2;
// A035349 = DIK(A000237)
Num dn = 0;
for (int k = 1; k <= n; k++)
{
// DIK_k is Polyà enumeration with the cyclic group D_k
// The cycle index for D_k has two parts: C_k and what Bower calls CPAL_k
// C_k
Num cikk = 0;
for (int d = 1; d <= k; d++)
if (k % d == 0 && n % d == 0)
cikk += phi[d] * aik[k / d, n / d];
dn += cikk / k;
// CPAL_k
if (k % 2 == 1)
for (int i = 0; i <= n; i += 2)
dn += aik[1, n - i] * aik[k / 2, i / 2];
else
{
Num cpalk = 0;
for (int i = 0; i <= n; i += 2)
cpalk += aik[2, n - i] * aik[k / 2 - 1, i / 2];
if (n % 2 == 0)
cpalk += aik[k / 2, n / 2];
dn += cpalk / 2;
}
}
a035349[n] = dn / 2;
}
// A000083 = A000237 + A035350 - A000237 * A035349
var a000083 = new Num[N + 1];
for (int i = 0; i <= N; i++)
{
a000083[i] = aik[1, i] + a035349[i];
for (int j = 0; j <= i; j++) a000083[i] -= aik[1, j] * a035350[i - j];
}
System.Console.WriteLine(a000083[N - 1]);
}
}
}
```
[Online demo](https://tio.run/##nVZtb9s2EP4s/4r7ssCO40RWWnStmwKJGxRFM8PYOuyDIRSsRNuMFEoQ5bpBkf@y/7L/Ne@OLxKtaVg3fzBF8njP3XMPT0rU5KGQxeGwU0JuYLF7gCv45VHV/OEcJ7wSiTq/EZv3suYbXs0Gkj1wVbKEw3I5fzf4NgiSnCkF1yH@frwcBLgSqJrVIoEvhUjhJybkUNUVul/FwEa4TSaBkDUsEAzH8yWrFB@yVRiPYAzT2YAMvrAKyq1AE8n3ZLZa0GY8o811UcGQXND@dIbD6ytY4DgeE0IQ4MmViPXmkX2JS9EMB2NfWnsdUiDWMKSDZQxvYDqCpJC1kDuuXRxjlh4mjHFuYB3uKa7AxILrXEtGp@AUT@q1/VbkHOGY9mJOmyg6QKyLxCyUjzWz6MybPQ30n@OSicxyiYU1XJ6BR6m2CS@fXz4Pu3Ydg2cv@w0QYRWeQUi00zP6n@pn43UV@pN259lLbwcn056ySVM2aYmQR2W7uNDyiy5foNXtr3e3Pw@vDYphilQtP5OLsFPJzKgng9cgcXDiaQ1SY5ASboZjY6G1ksEPZIF@RxoAq5NihV2KaUwTQ4RENWSGpsAtUZ507AKGtD0dGeFTPstizysFxbrJjFUcdoqnwCAv6r@nEek0NDs9eQidvBGS9K6JCSbTwYxN1TIK5QxEJ3gRt9FdNzK5ef9haCNsuf4Xqq@OuLaaN@w1wVg9O5IjInnqQj7KSsJJ0wCkvSKRs/Tc@illSHl0ZlgXI5o4QJ4rDoQqHWrofHkRmuPSO/hkCmsLryurCxt1SNNX520faen/IA29oq9PGQiFiskf//gduKSuje23kLAX9RbqLYfkMcmxH2@qYlfC209Zc/qj3cScZcq/AgHjPmyZgnpfYK@pavUK5rjEZAr7LavhhqQJCctzBfPl9Z3nbu6eKaFEZFmb0n@/UnByArK9YK6i2i21QWx@qV/Q1FQkdaVMdb20@QUCDdoovaC/Q2DhP4or9cVl7sixwERXWubJVs@wVLLcp@l7sc05Cx/1wdtr7IcQ9Cv72FmPuhsytZ1WddCq3tM@dm@t/VQ2VuYFZFs0fiHgrmtp46aRTJq1U3dP2jeOO9bzxukly/sM@GZD0y7M90DbC8bNG0fEnXt3b9zdkzuBI7oDz8ukcXMfe/1eYB73sZe1/ZCaF1IVOT//rRI1vxMSP3WsrwUVKR7REWTxafB0OByi8M9knbONOkwqvuYVlwl/1fkk@ws). This is a full program which takes input from the command line.
[Next sequence](https://oeis.org/A002466)
### Dissection
I follow Bowen's comment in OEIS that the generating function `A000083(x) = A000237(x) + A035349(x) - A000237(x) * A035350(x)` where the component generating functions are related by transforms as
* `A000237(x) = x EULER(A035350(x))`
* `A035350(x) = BIK(A000237(x))`
* `A035349(x) = DIK(A000237(x))`
I use the definitions of `BIK` and `DIK` from <https://oeis.org/transforms2.html> but the formulae seem to have a number of typos. I corrected `LPAL` without much difficulty, and independently derived a formula for `DIK` based on applying Pólya enumeration to the [cycle index of the dihedral group](https://en.wikipedia.org/wiki/Cycle_index#Dihedral_group_Dn). Between #121 and #156 I'm learning a lot about Pólya enumeration. I have submitted some [errata](https://oeis.org/wiki/Talk:More_Transformations_of_Integer_Sequences), which may prove useful to other people if these transforms come up again in the chain.
[Answer]
# 3. JavaScript (ES6), 38 bytes, [A000044](//oeis.org/A000044)
```
f=n=>n<0?0:n<3?1:f(n-1)+f(n-2)-f(n-13)
```
[Try it online!](https://tio.run/##HcdLCoAgEADQq8zSQQyrXWmdxUrDkJmw8Pr2WT3e4Yq71hzPWy1u8UkRb77WYMlOZPSsBzL93A5BkGpRfnSo/vVYA2cQxWWIYEGPLwa6TykRVqaLk28S7yKIiFgf "JavaScript (Babel Node) – Try It Online")
[Next sequence](//oeis.org/A000038) (should be an easy one :P)
[Answer]
# 13. VB.NET (.NET 4.5), 1246 bytes, [A000131](https://oeis.org/A000131)
```
Public Class A000131
Public Shared Function Catalan(n As Long) As Long
Dim ans As Decimal = 1
For k As Integer = 2 To n
ans *= (n + k) / k
Next
Return ans
End Function
Shared Function Answer(n As Long) As Long
n += 7
Dim a As Long = Catalan(n - 2)
Dim b As Long = Catalan(n / 2 - 1)
If n Mod 2 = 0 Then
b = Catalan(n / 2 - 1)
Else
b = 0
End If
Dim c As Long = Catalan(n \ 2 - 1) ' integer division (floor)
Dim d As Long
If n Mod 3 = 0 Then
d = Catalan(n / 3 - 1)
Else
d = 0
End If
Dim e As Long = Catalan(n / 4 - 1)
If n Mod 4 = 0 Then
e = Catalan(n / 4 - 1)
Else
e = 0
End If
Dim f As Long = Catalan(n / 6 - 1)
If n Mod 6 = 0 Then
f = Catalan(n / 6 - 1)
Else
f = 0
End If
Return (
a -
(n / 2) * b -
n * c -
(n / 3) * d +
n * e +
n * f
) /
(2 * n)
End Function
End Class
```
[A001246](https://oeis.org/A001246)
[Try it Online!](https://tio.run/##hVRNT8JAED3Lr5h40K6k0oLRxIQDAUlI1Bgh8eJl205hwzKbdFv13@NuKSWlH@yl3Xlvdt6bdudH6IxLN@BahC5h6u4Uqf3@IwukCGEqudYw8TzPH/k9MKsAlhueYATzjMJUKIIpT7nk5BBMNLwqWrPjS55l10zsgJO28RmGYscljMEv4blKYGvBBaW4xsSAQ1gpoJJhlz3gbgymTh@2DAawLeF3/EvLzSemWUKWnode6KQ1D5zrn5D@xaRJfnmkKTmGp17Vz5Fm1J5a4MKQVXlBI29gHLrgs5K6iE2VNxWZ@Bg8WG2w6j7oTn@RGmt87wSbJiziqrCwUdh3cTLcgii@RiR@hLadcmKpVHLmL6p97dLKqNlKdGZldMFKdNEKtvT4oaXHD83CsDu9JgwvCotbhD22CHtsFhZ3p9eExZ3CigviVFLKWwZuY/zw0zG4M39WM4MMFnZlj2x2BP3WbOzA4hpiRkAt5gwNlVj94ttNPtH2ps2ZRDg8/N7VMgvgjQtyWGUeieo88uw8GnqVglNFWkm8/0pEiq@C0BFwA9fPcG0exeC8L6aLYKw@rawoUz4Xd9Cz/wc)
[Answer]
# 26. TI-BASIC, 274 [bytes](http://tibasicdev.wikidot.com/tokens), [A000183](http://oeis.org/A000183)
```
.5(1+√(5→θ
"int(.5+θ^X/√(5→Y₁
"2+Y₁(X-1)+Y₁(X+1→Y₂
{0,0,0,1,2,20→L₁
Prompt A
Lbl A
If A≤dim(L₁
Then
Disp L₁(A
Else
1+dim(L₁
(~1)^Ans(4Ans+Y₂(Ans))+(Ans/(Ans-1))((Ans+1))-(2Ans/(Ans-2))((Ans-3)L₁(Ans-2)+(~1)^AnsY₂(Ans-2))+(Ans/(Ans-3))((Ans-5)L₁(Ans-3)+2(~1)^(Ans-1)Y₂(Ans-3))+(Ans/(Ans-4))(L₁(Ans-4)+(~1)^(Ans-1)Y₂(Ans-4→L₁(Ans
Goto A
End
```
Evaluates the recursive formula found on the OEIS link.
[Next Sequence](http://oeis.org/A000274)
[Answer]
# 39. [Add++](https://github.com/SatansSon/AddPlusPlus), 1 byte, [A000004](https://oeis.org/A000004)
```
O
```
[Try it online!](https://tio.run/##S0xJKSj4/9///38A "Add++ – Try It Online")
[Next sequence](https://oeis.org/A000001)
[Answer]
# 250. [Coconut](http://coconut-lang.org), 711 bytes, [A000171](https://oeis.org/A000171)
```
from collections import Counter
from math import gcd, factorial
def sparts(n, m=4):
if n%2==1:
return [ [1] + p for p in sparts(n-1) ]
elif n==0:
return [ [] ]
elif n<m:
return []
else:
return [ [m] + p for p in sparts(n-m,m) ] + sparts(n,m+4)
def ccSize(l) =
centSize = [ val**mult * factorial(mult)
for val, mult in Counter(l).items() ] |> reduce$(*)
factorial(sum(l)) // centSize
def edgeorbits(l) =
samecyc = sum(l) // 2
diffcyc = sum ([ gcd(l[i],l[j])
for i in range(len(l)) for j in range(i) ])
samecyc + diffcyc
def a(n) =
sum ([ ccSize(l)*2**edgeorbits(l)
for l in sparts(n) ]) // factorial(n)
def f(n) = a(n+1)
```
[Try it online!](https://tio.run/##dZHLboMwEEX3fMUsUskG2jyUVVWy6Sd0iVi4xk4d@YGMqdSq/07HQICkKguE587MPVxzx53tQt9L7wxwp7XgQTnbgjKN8wFeXWeD8MmgGxY@rsKZ1zlIxoPziukkqYWEtmE@tMTmYIojfU4AlAT7cCiKfTwAeBE6b6GEcl9BBg1I5/Gt7Dz6uKdQYa/QcbQodveD1Up@MbfqqLTifsb8Z2Zyg3YozuQmO9LxZzh/U9@CaAoFruPChniGAhd@Mp2mptMB0iUCEgt0cF490RPbMZHYjt5ToLj3SQVhWhIBfk5IW3dcbEgaVyxL285gK4XtdkYY8UR9Fs6/K6SeEFtmBP/iSDgOxZkD1msl5VwHUsarI7pUVa7LS/WH@EqtIq1n9owZCDtAxPJlKStEpyvj7Go1EjJiJ7DRdg40PaTpDX5yY6zXV0RnqRp@aEnGTvckB5volu1pP5IddzRmalizIRI/0xM0XtnQ/wI "Coconut – Try It Online")
[Next sequence](https://oeis.org/A000711)
This can easily compute more values than the 31 that OEIS has.
Once again we have a symmetric group acting on nodes, inducing an
action on the set of possible edges and on graphs. It acts on the set
of self-complementary graphs, but I don't see how to count how many of
these are fixed by a given permutation to apply the lemma that is
often named after Burnside. So instead I use the formula in the
comment of the OEIS entry that says that the number of
self-complementary graphs with `n` nodes is equal to the difference of
the number of graphs with `n` nodes with an even number of edges and
with an odd number of edges. The symmetric group acts on these sets of
graphs as well. Instead of computing both numbers independently, we
will consider the cases of an even number and an odd number of edges
in parallel, which will turn out to be simpler and allow
optimizations.
We'll see that "evaluate the graph polynomial at `-1`" will lead to the
same result.
As usual, we take the sum over the group elements in Burnside's lemma
conjugacy class wise, and represent the conjugacy classes by
partitions of `n`. For each conjugacy class, we want to know the
difference between the numbers of graphs with an even and odd number
of edges that is fixed by a permutation from that class.
Assume we are given a concrete permutation `g`. The group generated by
`g` acts on the set of possible edges and partitions them into orbits.
A graph is fixed by `g` if for each orbit, it contains either all or
none of its edges. Let's look at the orbits. Each edge in one orbit
has its endpoints in the same two (possibly same) cycles of `g`.
Let's first assume the endpoints are from the same cycle of length
`k>=2`. If `k` is odd, then there are `(k-1)/2` orbits of length `k`.
If `k` is even, then there are `k/2-1` orbits of length `k` and one of
length `k/2` (for example, if `g` contains the cycle `(123456)`, then
the there is an edge orbit of size 3 containing `{1,4}`). Note that we
get all orbits of even size exactly when `k` is a multiple of four.
Next consider the case that the endpoints are from different cycles
of lengths `k` and `l`. Then the orbit has size `lcm(k,l)`, and there
are `gcd(k,l)` such orbits.
In order to combine all the possibilities, consider the product, for
each edge orbit, of `1+x^r`, where `r` is the size of the
corresponding orbit. The coefficient of `x^s` of the product gives the
number of graphs that are fixed by `g` and have `s` edges. We want the
sum of the coefficients at even exponents minus the sum of them at odd
coefficients, which we get by evaluating the polynomial at `x=-1`.
If we kept the polynomials and added them together, we'd get the graph
polynomial. Instead, we don't even create these polynomials, but do
the substitution immediately. For an edge orbit of even size, we get a
factor of `2`, for an odd size we get `0`. (There is also a direct
combinatorial argument that if there is an edge orbit of odd size then
there are as many fixed graphs with an even number of edges as there
are with an odd number of edges. And the factor `2` corresponds to the
choice of including the edges of one orbit to the fixed graph or
not).
So, by the considerations about edges with points from only one cycle,
we get a difference of `0` whenever `g` contains a cycle of odd length
greater than one, or a cycle of even length not divisible by four. We
also get a difference of `0` whenever `g` contains at least two fixed
points (cycles of length one).
This means we only need to sum over conjugacy classes with at most one
fixed point and all other cycle lengths multiples of four. `sparts`
computes the corresponding partitions of `n`. There are none unless
`n` is of the form `4k` or `4k+1`, so in the other cases there are no
self-complementary graphs, which can also easily seen by noting that
in these cases the total number of possible edges is odd. But this
observations alone doesn't lead to the optimization of only
considering special partitions, of which there are only as much as
there are partitions of `k`.
`ccSize` computes the size of a conjugacy class with given cycle
lengths. `edgeorbits` computes the number of edge orbits of the action
of the group generated by a permutation with the given cycle lengths,
assuming they are of the special form. In the general case, `samecyc`,
the number of edge orbits with edges that have both nodes from the
same cycle, could not be calculated like this. (When I wrote the code,
I didn't notice that it only depends on `n` in the relevant cases.)
`a` puts everything together, and `f` fixes the different indexing.
[Answer]
# 11. Pari/GP, 64 bytes, [A000065](https://oeis.org/A000065)
```
{a(n) = if( n<0, 0, polcoeff ( 1 / eta(x + x*O(x^n) ), n) - 1)};
```
[Try it online!](https://tio.run/##K0gsytRNL/j/vzpRI09TwVYhM01DIc/GQEcBiAryc5LzU9OAIoYK@gqpJYkaFQraChVa/hoVcXmamjoKQB26Coaatdb//ydqGGsCAA)
[Next sequence](https://oeis.org/A000064)
[Answer]
# 318. [Funciton](https://github.com/Timwi/Funciton), 1688 bytes, [A000652](https://oeis.org/A000652)
```
╔═══╗ ┌─────────╖ ┌─┐ ┌───╖ ╔═══╗
║ ╟──┤ str→int ╟──┤ └─┤ ↑ ╟──╢ 2 ║
╚═══╝ ╘═════════╝ │ ╘═╤═╝ ╚═══╝
┌─────────────────┘ │
┌─┴┐ │
│┌─┴─╖ ┌───┴───┐
││ ♭ ║ ┌─┴─╖ ┌─┴─╖
│╘═╤═╝┌───╖ ╔═══╗│ ♭ ║ │ ! ║
│ └──┤ ↑ ╟────╢ 2 ║╘═╤═╝ ╘═╤═╝
│ ╘═╤═╝ ╚═╤═╝ │ │
│ ┌──┴─┐ │ └───┐ │
│ ┌─┴─╖ │┌───╖ │ ┌───╖ │ │
│ │ ! ║ └┤ ↑ ╟─┴──┤ ↑ ╟─┘ │
│ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │
│ │ ┌───╖ │ ┌───╖│ │
│ └─┤ × ╟─┘ ┌─┤ × ╟┘ │
│ ╘═╤═╝ │ ╘═╤═╝ ┌───╖ │
│ ╔═══╗ └─────┘ └───┤ + ╟──┘
│ ║ 2 ╟┐ ╘═╤═╝
│ ╚═╤═╝│ ┌───╖ │
│ │ └──┐ ┌─┤ ÷ ╟───┘
│ └──┐┌─┴─╖ │ ╘═╤═╝┌─────────╖
│ ┌───╖ ││ ↑ ╟─┘ └──┤ int→str ╟─
└─┤ × ╟─┘╘═╤═╝ ╘═════════╝
╘═╤═╝ │
└──────┘
```
[Next Sequence](https://oeis.org/A001688)
Calculates the formula from the OEIS page. I'm sure there's a more compact way to do this, without multiple `2` constants, but this took me long enough.
[Try it online!](https://tio.run/##jZS9TsQwDMf3PIWZ2RBvhIR0S5Gg7KcONzGkKOUCEjrp1JWtEg/Am@RFSj4uxI4dlSpSU9d23d/f8f1zd7frH7p1dZNxk87rCODMizP75preioumzvEVTafcNEKwnrLbDE/9ozu87rqemp0xeXcY0avpDDf@cfSpPlDqz5DVIgNfwcUMUBznEklSqc2/bi4L4fKfUTnDEriIV/IakGNiVnvhSha01yl6APf@BQmsEFfSMkuMpyyYgExC@sHwdJX2KsLNsgnKUf2YCLUsKZ8kVxFspsIiqhW65dKg2SXdDKaJYxkqpFNGQxyJEef5wxO/RpEsMilLMmxhahCiHIZmocTaoJgP4s8R1ZhDi9nyWLH@UE1l5XOj/D@dR1S0PQKG7TNc48azOdcYe@/EjqTYelWTFTi83Jo2LkejAA/ruzoRVvF21HX/Ccw257JqyB7NrN3QqfWj2A9kP5YvLkruAKnp4B9TWMkt7AHyQ1korevtLw "Funciton – Try It Online")
[Answer]
# 121. [Pip](https://github.com/dloscutoff/pip), 525 bytes, [A000022](https://oeis.org/A000022)
```
n:(a+1)//2
t:[[0]RL(3*a+3)PE1]
Fh,n{
m:([0]RL(3*a+3))
Fi,(a+1){
Fj,(a+1){
Fk,(a+1)m@(i+j+k)+:(t@h@i)*(t@h@j)*(t@h@k)
m@(i+2*j)+:3*(t@h@i)*(t@h@j)
}
m@(3*i)+:2*(t@h@i)
}
t:(tAE(m//6PE1))
}
k:t@n
o:0
Fh,aFi,aFj,aI(h+i+j<a)o+:(k@h)*(k@i)*(k@j)*k@(a-1-h-i-j)
Fh,((a+1)//2){
Fi,aI(2*h+i<a){o+:6*(k@h)*(k@i)*(k@(a-1-2*h-i))}
I(a%2=1)o+:3*(k@h)*(k@((a-1-2*h)//2))
}
Fh,((a+2)//3)o+:8*(k@h)*(k@(a-1-3*h))
I(a%4=1)o+:6*k@(a//4)
o//:24
Ia(o+:t@n@a)
Fh,nFj,(a+1)o-:(t@(h+1)@j-t@h@j)*(t@(h+1)@(a-j))
o
```
[Online demo](https://tio.run/##XZExa8MwEIV3/YoshZMcoVhyTREtqEMChg6la8igzbKwncFbyG93n2SbhEzi7r579@50Ddd5Hiz5ouRKaTbZ8/lw@fshI3xh@O@xvLBTux9ubLfrLT3XOFKnsM@tqYyoe44QxyXuHYWiKyIvLE2udYGL/HbrG/nakEEtOoBGvKAZubMVMyIA0hvEltIE/e8j9UrVcA6Hdxbt5AY22kNaw8Ovh0vfUFvA0qfnIzxF12JMzMNichUdeVnKVgaJwWik7UB5t6TSkBbQgMINErV4Ecn9IGTgPDlryL/przKNMw@WNixLJ7vrLI2ESfDHE5xYA5azpFYtanU2q1TF2aiU1RVrPCGPrZ3P3oftW0aZzo/NS@46@fiAJQP5DtLjPM/v/w)
[Next sequence](https://oeis.org/A000525)
Fun fact: when the challenge was first posted, I drew up a list of small nasty sequence numbers that I wanted to aim for with CJam, and A000022 was at the top of the list.
This implements the generating function described in E. M. Rains and N. J. A. Sloane, [**On Cayley's Enumeration of Alkanes (or 4-Valent Trees)**](https://cs.uwaterloo.ca/journals/JIS/cayley.html),
Journal of Integer Sequences, Vol. 2 (1999), taking the sum for `Ck` to as many terms as a necessary for the `n`th coefficient to be fixed and then telescoping three quarters of the sum. In particular, telescoping the first half means that the cycle index of `S4` only has to be applied to one of the `Th` rather than to all of them.
The code breaks down as
```
; Calculate the relevant T_h
t:[[0]RL(3*a+3)PE1]
Fh,n{
m:([0]RL(3*a+3))
Fi,(a+1){
Fj,(a+1){
Fk,(a+1)m@(i+j+k)+:(t@h@i)*(t@h@j)*(t@h@k)
m@(i+2*j)+:3*(t@h@i)*(t@h@j)
}
m@(3*i)+:2*(t@h@i)
}
t:(tAE(m//6PE1))
}
; Calculate the cycle index of S_4 applied to the last one
k:t@n
o:0
Fh,aFi,aFj,aI(h+i+j<a)o+:(k@h)*(k@i)*(k@j)*k@(a-1-h-i-j)
Fh,((a+1)//2){
Fi,aI(2*h+i<a){o+:6*(k@h)*(k@i)*(k@(a-1-2*h-i))}
I(a%2=1)o+:3*(k@h)*(k@((a-1-2*h)//2))
}
Fh,((a+2)//3)o+:8*(k@h)*(k@(a-1-3*h))
I(a%4=1)o+:6*k@(a//4)
o//:24
; Handle the remaining convolution,
; pulling out the special case which involves T_{-2}
Ia(o+:t@n@a)
Fh,nFj,(a+1)o-:(t@(h+1)@j-t@h@j)*(t@(h+1)@(a-j))
```
Note that this is my first ever Pip program, so is probably not very idiomatic.
[Answer]
# 6. [R](https://www.r-project.org/), 71 bytes, [A000072](https://oeis.org/A000072)
```
function(n)length(unique((t<-outer(r<-(0:2^n)^2,r*4,"+"))[t<=2^n&t>0]))
```
[Try it online!](https://tio.run/##DcrBCoQgEADQX1k6LDOlYNEprB@JgghthZhsGg/79eb18Tj7j9XZJ9olXASEp6NDfpAo3MkBiNVXEsfAVoMZupVw7RTXvaqaCnEWOxb7ymQWxBw5kMCzxXj@y26N8kVf "R – Try It Online")
[Next sequence](https://oeis.org/A000071)
[Answer]
# 14. [Python 2](https://docs.python.org/2/), 60 bytes, [A001246](https://oeis.org/A001246)
```
f=lambda x:x<1or x*f(x-1)
c=lambda n:(f(2*n)/f(n)/f(n+1))**2
```
[Try it online!](https://tio.run/##NckxDoAgDADA3VcwtlVjIHEh@hhEqyZSCHHA1@NgXG659NxHFFMrz5cLy@pUsWXSMatCDKXX2Ph/xAKDIcGB4aPViESmpnzKrYJL4DuVnewb6BGxvg "Python 2 – Try It Online")
[Next sequence.](https://oeis.org/A000060)
[Answer]
# 34. [Prolog (SWI)](http://www.swi-prolog.org), 168 bytes, [A000073](https://oeis.org/A000073)
```
tribonacci(0,0).
tribonacci(1,0).
tribonacci(2,1).
tribonacci(A,B):-
C is A-1,
D is A-2,
E is A-3,
tribonacci(C,F),
tribonacci(D,G),
tribonacci(E,H),
B is F+G+H.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/v6QoMyk/LzE5OVPDQMdAU48LScAQXcBIxxBVwFHHSdNKl4vTWSGzWMFR11CHi9MFwjQCMl0hTGMgE0mPs46bJqqIi447moirjgdIxAlkgJu2u7aHHopLjQx0IjT1AA "Prolog (SWI) – Try It Online")
[Next sequence](https://oeis.org/A000168)
[Answer]
# 49. [SageMath](http://www.sagemath.org/), 74 bytes, [A000003](https://oeis.org/A000003)
```
lambda n: len(BinaryQF_reduced_representatives(-4*n, primitive_only=True))
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwVyDsKgDAMANBd8A4ZW6mg4iS4OLgL7hJtlEIbS_yAt1enB2-FFjyG2SJwA55YdY5RnqGfhOy1kP2MQgfxiae76VB5nbGBKC64P6ad_dOOcpHWaZImAaNaDQjyRqo0VaH1CwoqIbA=&lang=sage)
[Next sequence](https://oeis.org/A000074)
] |
[Question]
[
It's time to face the truth: We will not be here forever, but at least we can write a program that will outlive the human race even if it struggles till the end of time.
Your task is to write a program that has a expected running time greater than the remaining time till the end of the universe.
You may assume that:
* The universe will [die from entropy](https://en.wikipedia.org/wiki/Heat_death_of_the_universe) in 101000 years.
* Your computer:
+ Will outlive the universe, because it is made of [Unobtainium](https://en.wikipedia.org/wiki/Unobtainium).
+ Has infinite memory/stack/recursion limit.
+ Its processor has limited speed.
You must show that your program terminates (sorry, no infinite loops) and calculate its expected running time.
The [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
This is a code golf challenge, so the shortest code satisfying the criteria wins.
**EDIT**:
Unfortunately, it was found (30min later) that the improbability field of Unobtainium interferes with the internal clock of the computer, rendering it useless. So time based programs halt immediately. (Who would leave a program that just waits as its living legacy, anyway?).
The computer processor is similar to the Intel i7-4578U, so one way to measure the running time is to run your program in a similar computer with a smaller input (I hope) and extrapolate its running time.
---
## Podium
| # | Chars | Language | Upvotes | Author |
| --- | --- | --- | --- | --- |
| 1 | 5 | CJam | 20 | Dennis |
| 2 | 5 | J | 5 | algorithmshark |
| 3 | 7 | GolfScript | 30 | Peter Taylor |
| 4 | 9 | Python | 39 | xnor |
| 5 | 10 | Matlab | 5 | SchighSchagh |
\* Upvotes on 31/08
[Answer]
# JavaScript, 39
```
(function f(x){for(;x!=++x;)f(x+1)})(0)
```
### Explanation
Since JavaScript does not precisely represent large integers, the loop `for(;x!=++x;)` terminates once `x` hits `9007199254740992`.
The body of the for loop will be executed `Fib(9007199254740992) - 1` times, where `Fib(n)` is the nth fibonacci number.
From testing, I know my computer will do less than 150,000 iterations per second. In reality, it would run much slower because the stack would grow very large.
Thus, the program will take at least `(Fib(9007199254740992) - 1) / 150000` seconds to run. I have not been able to calculate `Fib(9007199254740992)` because it is so large, but I know that it is much larger than 101000 \* 150,000.
EDIT: As noted in the comments, `Fib(9007199254740992)` is approximately 4.4092\*101882393317509686, which is indeed large enough.
[Answer]
# Python (9)
```
9**9**1e9
```
This has more than 10\*\*10000000 bits, so computing it should take us far past heat death.
I checked that this takes more and more time for larger but still reasonable values, so it's not just being optimized out by the interpreter.
**Edit:** Golfed two chars by removing parens thanks to @user2357112. TIL that Python treats successive exponents as a power tower.
[Answer]
# CJam, 5 bytes
```
0{)}h
```
### How it works
```
0 " Push 0. ";
{ " ";
) " Increment the Big Integer on the stack. ";
}h " Repeat if the value is non-zero. ";
```
This program will halt when the heap cannot store the Big Integer anymore, which won't happen anytime soon on a modern desktop computer.
The default heap size is 4,179,623,936 bytes on my computer (Java 8 on Fedora). It can be increased to an arbitrary value with `-Xmx`, so the only real limit is the available main memory.
### Time of Death
Assuming that the interpreter needs *x* bits of memory to store a non-negative Big Integer less than *2x*, we have to count up to *28 × 4,179,623,936 = 233,436,991,488*. With one increment per clock cycle and my Core i7-3770 (3.9 GHz with turbo), this will take *233,436,991,488 ÷ 3,400,000,000 > 1010,065,537,393* seconds, which is over *1010,065,537,385* years.
[Answer]
# [Marbelous](https://github.com/marbelous-lang) ~~68~~ 66 bytes
```
}0
--@2
@2/\=0MB
}0@1\/
&0/\>0!!
--
@1
00@0
--/\=0
\\@0&0
```
Marbelous is an 8 bit language with values only represented by marbles in a Rube Goldberg-like machine, so this wasn't very easy.
This approach is roughly equivalent to the following pseudo-code:
```
function recursiveFunction(int i)
{
for(int j = i*512; j > 0; j--)
{
recursiveFunction(i - 1);
}
}
```
since the maximum value is 256, (represented by 0 in the Marbleous program, which is handled differently in different places) recursiveFunction(1) will get called a total of `256!*512^256` which equals about `10^1200`, easily enough to outlive the universe.
Marbelous doesn't have a very fast interpreter, it seems like it can run about `10^11` calls of this function per year, which means we're looking at a runtime of `10^1189` years.
**Further explanation of the Marbelous board**
```
00@0
--/\=0
\\@0&0
```
`00` is a language literal (or a marble), represented in hexadecimal (so 0). This marble falls down onto the `--`, which decrements any marble by 1 (00 wraps around and turns into FF or 255 in decimal). The Marble with now the value FF falls down onto the `\\` which shoves it one column to the right, onto the lower `@0`. This is a portal and teleports the marble to the other `@0` device. There, the marble lands on the `/\` device, which is a duplicator, it puts one copy of the marble on the `--` to its left (this marble will keep looping between the portals and get decremented on every loop) and one on the `=0` to its right. `=0` compares the marble to the value zero and lets teh marble fall trough if it's equal and pushes it to the right if not. If the marble has teh value 0, it lands on `&0`, a synchonizer, which I will explain further, later.
All in all, this just starts with a 0 value marble in a loop and decrements it until it reaches 0 again, it then puts this 0 value marble in a synchronizer and keeps looping at the same time.
```
}0@1
&0/\>0!!
--
@1
```
`}0` is an input device, initially the nth (base 0) command line input when calling the program gets placed in every `}n` device. So if you call this program with command line input 2, a 02 value marble will replace this `}0`. This marble then falls down into the `&0` device, another synchronizer, `&n` synchronizers hold marbles until all other corresponding `&n`'s are filed as well. The marble then gets decremented, teleported and duplicated much like in the previously explained loop. The right copy then get checked for inequality with zero (`>0`) if it's not 0, it falls through. If it is 0, it gets pushed to the right and lands on `!!`, which terminates the board.
Okay, so far we have a loop that continuously counts down from 255 to 0 and lets another, similar loop (fed by the command line input) run once every time it hits 0. When this second loop has run n times (maximum being 256) the program terminates. So that's a maximum of 65536 runs of the loop. Not nearly enough to outlive the universe.
```
}0
--@2
@2/\=0MB
```
This should start looking familiar, the input gets decremented once, then this value loops around and get copied (note that the marble only gets decremented once, not on every run of the loop). It then gets checked for equality to 0 and if it's not zero lands on `MB`. This is a function in Marbelous, every file can contain several boards and each board is a function, every function has to be named by preceding the grid by `:[name]`. Every function except for the first function in the file, which has a standard name: MB. So this loop continuously calls the main board again with a value of `n - 1` where n is teh value with which this instance of teh function was called.
**So why `n*512`?**
Well, the first loop runs in 4 ticks (and 256 times) and the second loop runs n times before the board terminates. This means the board runs for about `n*4*256` ticks. The last loop (which does the recursive function calling) is compacter and runs in 2 ticks, which means it manages to call the function `n*4*256/2 = n*512` times.
**What are the symbols you didn't mention?**
`\/` is a trash bin, which removes marbles from the board, this makes sure discarted marbles don't interfere with other marbles that are looping a round and prevent the program from terminating.
**Bonus**
Since marbles that fall off the bottom of a marbelous board get output to STDOUT, this program prints a plethora of ASCII characters while it runs.
[Answer]
## GolfScript (12 7 chars)
```
9,{\?}*
```
This computes and prints 8^7^6^5^4^3^2 ~= 10^10^10^10^183230. To print it (never mind the computation) in 10^1000 years ~= 10^1007.5 seconds, it needs to print about 10^(10^10^10^183230 - 10^3) digits per second.
[Answer]
# Perl, 66 58 characters
```
sub A{($m,$n)=@_;$m?A($m-1,$n?A($m,$n-1):1):$n+1;}A(9,9);
```
The above is an implementation of the [Ackermann–Péter function](https://en.wikipedia.org/wiki/Ackermann_function). I have no idea how large A(9,9) is but I am fairly certain it will take an astoundingly long time to evaluate.
[Answer]
# MATLAB, ~~58~~ 52 characters
We need at least one finite-precision arithmetic solution, hence:
```
y=ones(1,999);while y*y',y=mod(y+1,primes(7910));end
```
~~x=ones(1,999);y=x;while any(y),y=mod(y+x,primes(7910));end~~
(*with thanks to @DennisJaheruddin for knocking off 6 chars*)
The number of cycles needed to complete is given by the product of the first 999 primes. Since the vast majority of these are well over 10, the time needed to realize convergence would be hundreds or thousands of orders of magnitude greater than the minimum time limit.
[Answer]
## Mathematica, ~~25~~ 19 bytes
*This solution was posted before time functions were disqualified.*
```
While[TimeUsed[]<10^10^5]
```
`TimeUsed[]` returns the seconds since the session started, and Mathematica uses arbitrary-precision types. There are some 107 seconds in a year, so waiting 1010000 seconds should be enough.
Shorter/simpler(/valid) alternative:
```
For[i=0,++i<9^9^9,]
```
Let's just count instead. We'll have to count a bit further, because we can do a quite a lot of increments in a second, but the higher limit doesn't actually cost characters.
Technically, in both solutions, I could use a much lower limit because the problem doesn't specify a minimum processor speed.
[Answer]
# Python 3 - 49
This does something useful: calculates Pi to unprecedented accuracy using the Gregory-Leibniz infinite series.
Just in case you were wondering, this program loops `10**10**10**2.004302604952323` times.
```
sum([4/(i*2+1)*-1**i for i in range(1e99**1e99)])
```
## Arbitrary precision: 78
```
from decimal import*
sum([Decimal(4/(i*2+1)*-1**i)for i in range(1e99**1e99)])
```
![](https://imgs.xkcd.com/comics/pi.jpg)
[Image source](http://xkcd.com/10/index.html)
# The Terminal Breath
Due to the huge calculations taking place, `1e99**1e99` iterations takes just under `1e99**1e99` years. Now, `(1e99**1e99)-1e1000` makes barely any difference. That means that this program will run on far longer than the death of our universe.
# Rebirth
Now, scientists propose that in `10**10**56 years`, the universe will be reborn due to quantum fluctuations or tunnelling. So if each universe is exactly the same, how many universe will my program live through?
```
(1e99**1e99)/(1e10+1e1000+10**10**56)=1e9701
```
Assuming that the universe will always live `1e10+1e1000` years and then take `10**10**56` years to 'reboot', my program will live through `1e9701` universes. This is assuming, of course, that unobtainium can live through the Big Bang.
[Answer]
# Python 59 (works most of the time)
I couldn't resist
```
from random import*
while sum(random()for i in range(99)):0
```
While its true that this could theoritically terminate in under a millisecond, the average runtime is well over `10^400` times the specified lifespan of the universe. Thanks to @BetaDecay, @undergroundmonorail, and @DaboRoss for getting it down a 17 characters or so.
[Answer]
# J - 5 chars, I think
Note that all of the following is in arbitrary precision arithmetic, because the number 9 always has a little `x` beside it.
In **seven** characters, we have `!^:!!9x`, which is kinda like running
```
n = 9!
for i in range(n!):
n = n!
```
in arbitrary precision arithmetic. This is definitely over the limit because [Synthetica said so](https://codegolf.stackexchange.com/a/36770/5138), so we have an upper bound.
In **six** chars, we can also write `^/i.9x`, which calculates every intermediate result of `0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8`. Wolfram|Alpha says `2^3^4^5^6^7^8` is approximately `10 ^ 10 ^ 10 ^ 10 ^ 10 ^ 10 ^ 6.65185`, which probably also clears inspection.
We also have the **five** char `!!!9x`, which is just ((9!)!)!. W|A says it's `10 ^ 10 ^ 10 ^ 6.2695`, which should still be big enough... That's like [`1.6097e1859933`](http://www.wolframalpha.com/input/?i=%28%289%21%29%21%29%21)-ish digits, which is decidedly larger than [`3.154e1016`](http://www.wolframalpha.com/input/?i=number+of+nanoseconds+in+10%5E1000+years), the number of nanoseconds in the universe, but I'm gonna admit I have no idea how one might figure out the real runtimes of these things.
The printing alone should take long enough to last longer than the universe, though, so it should be fine.
[Answer]
# C, 63 56 chars
```
f(x,y){return x?f(x-1,y?f(x,y-1):1):y+1;}main(){f(9,9);}
```
>
> This is based on an idea by a guy named Wilhelm. My only contribution is condensing the code down to this short (and unreadable) piece.
>
>
>
Proving that it terminates is done by induction.
* If x is 0, it terminates immediately.
* If it terminates for x-1 and any y, it also terminates for x, this itself can be shown by induction.
Proving the induction step by induction:
* If y is 0 there is only one recursive call with x-1, which terminates by induction assumption.
* If f(x, y-1) terminates then f(x, y) also terminates because the innermost call of f is exactly f(x, y-1) and the outermost call terminates according to the induction hypthesis.
>
> The expected running time is A(9,9) / 11837 seconds. This number has more digits than the number of quarks in the observable universe.
>
>
>
[Answer]
# Matlab (~~10~~ 8 chars)
```
1:9e1016
```
IMHO, most entries are trying too hard by computing large, complicated things. This code will simply initialize an array of 9x101016 `double`s counting up from 1, which takes 7.2x10^1017 bytes. On a modern CPU with a maximum memory bandwidth of [21 GB/s](http://ark.intel.com/products/52213/Intel-Core-i7-2600-Processor-8M-Cache-up-to-3_80-GHz) or [6.63x10^17 bytes/year](https://www.google.com/search?q=1+year+*+%2821+GB%2Fs%29+in+bytes), it will take *at least* 1.09x101000 years to even initialize the array, let alone try to print it since I didn't bother suppressing the output with a trailing semicolon. (;
---
old solution(s)
```
nan(3e508)
```
Alternatively
```
inf(3e508)
```
This code will simply create a square matrix of `NaN`s/infinities of size `3e508`x`3e508 = 9e1016` 8-byte doubles or `7.2e1017` bytes.
[Answer]
# Perl, 16 chars
```
/$_^/for'.*'x1e9
```
This builds a string repeating ".\*" a billion times, then uses it as both the needle and the haystack in a regex match. This, in turn, causes the regex engine to attempt every possible partition of a string two billion characters long. According to [this formula from Wikipedia](http://en.wikipedia.org/wiki/Partition_(number_theory)#Approximation_formulas), there are about 1035218 such partitions.
The above solution is 16 characters long, but only requires about 2Gb of memory, which means it can be run on a real computer. If we assume infinite memory and finite register size (which probably doesn’t make sense), it can be shortened to 15 characters while dramatically increasing the runtime:
```
/$_^/for'.*'x~0
```
(I haven’t tested it, but I think it could work with a 32-bit Perl built on a 64-bit machine with at least 6Gb of RAM.)
Notes:
* `x` is the string repeat operator.
* the `for` isn’t an actual loop; it is only used to save one character (compared to `$_=".*"x1e9;/$_^/`).
* the final `^` in the regex ensures that only the empty string can match; since regex quantifiers are greedy by default, this is the last thing the engine will try.
* benchmarks on my computer for values (1..13) suggest that the running time is actually O(exp(n)), which is even more than the O(exp(sqrt(n))) in the Wikipedia formula.
[Answer]
# J (12)
```
(!^:(!!9))9x
```
What this comes down to in Python (assuming `!` works):
```
a = 9
for i in range((9!)!):
a = a!
```
EDIT:
Well, the program can take, at most, [`2 × 10^-1858926`](http://www.wolframalpha.com/input/?i=%283.154%C3%9710%5E1007%29%2F%28%289%21%29%21%29) seconds per cycle, to complete within the required time. Tip: this won't even work for the first cycle, never mind the last one ;).
Also: this program might need more memory than there is entropy in the universe...
[Answer]
# C# 217
I'm not much of a golfer, but I couldn't resist [Ackerman's function](http://en.wikipedia.org/wiki/Ackermann_function). I also don't really know how to calculate the runtime, but it will definitely halt, and it will definitely run longer than [this version](https://www.youtube.com/watch?v=i7sm9dzFtEI).
```
class P{
static void Main(){for(int i=0;i<100;i++){for(int j=0;j<100;j++){Console.WriteLine(ack(i,j));}}}
static int ack(int m,int n){if (m==0) return n+1;if (n ==0) return ack(m-1,1);return ack(m-1,ack(m,n-1));}
}
```
[Answer]
First attempt at code golf but here goes.
VBA - ~~57~~ 45
```
x=0
do
if rnd()*rnd()<>0 then x=0
x=x+1
while 1=1
```
So X will go up by one if a 1 in 2^128 event occurs and reset if it does not occur. The code ends when this event happens 2^64+1 times in a row. I don't know how to begin calculating the time but I'm guessing it is huge.
EDIT: I worked out the math and the probability of this happening in each loop is 1 in 2^128^(1+2^64) which is about 20000 digits long. Assuming 1000000 loops/sec (ballpark out of thin air number) and 30000000 s/yr that's 3\*10^13 cycles per year time 10^1000 years left is 3\*10^1013 cycles, so this would likely last around 20 times the remaining time left in the universe. I'm glad my math backs up my intuition.
[Answer]
# C, 30 characters
```
main(i){++i&&main(i)+main(i);}
```
Assuming two's compliment signed overflow and 32-bit ints, this will run for about 2232 function calls, which should be plenty of time for the universe to end.
[Answer]
# R, 45 bytes
```
(f=function(x)if(x)f(x-1)+f(x-1)else 0)(9999)
```
It's an old thread but I see no R answer, and we can't be having that!
The runtime for me was about 1s when x was 20, suggesting a runtime of 2^9979 seconds.
If you replace the zero with a one, then the output would be 2^x, but as it stands the output is zero whatever x was (avoids overflow problems).
[Answer]
# GolfScript, 13 chars
```
0{).`,9.?<}do
```
This program just counts up from 0 to 1099−1 = 10387420488. Assuming, optimistically, that the computer runs at 100 GHz and can execute each iteration of the program in a single cycle, the program will run for 1099−12 seconds, or about 3 × 1099−20 = 3 × 10387420469 years.
To test the program, you can replace the `9` with a `2`, which will make it stop at 1022−1 = 103 = 1000. (Using a `3` instead of a `2` will make it stop at 1033−1 = 1026, which, even with the optimistic assumptions above, it will not reach for at least a few million years.)
[Answer]
# Autohotkey 37
```
loop {
if (x+=1)>10^100000000
break
}
```
[Answer]
# Haskell, 23
```
main=interact$take$2^30
```
This program terminates after reading 1073741824 characters from `stdin`. If it's run without piping any data to `stdin`, you will have to type this number of characters on your keyboard. Assuming your keyboard has 105 keys, each rated for 100k mechanical cycles and programmed to generate non-dead keystrokes, autorepeat is off, and your keyboard socket allows 100 connection cycles, this gives the maximum number of keystrokes per computer uptime of 1050000000, which is not enough for the program to terminate.
Therefore, the program will only terminate when better hardware becomes available in terms of number of cycles, which is effectively never in this running universe. Maybe next time, when quality has higher priority than quantity. Until then, this program terminates in principle but not in practice.
[Answer]
# ~ATH, 56
In the [fictional language ~ATH](http://www.mspaintadventures.com/storyfiles/hs2/02002_2.gif):
```
import universe U;
~ATH(U) {
} EXECUTE(NULL);
THIS.DIE()
```
>
> ~ATH is an insufferable language to work with. Its logic is composed
> of nothing but infinite loops, or at best, loops of effectively
> interminable construction.
>
>
> What many ~ATH coders do is import finite constructs and bind the
> loops to their lifespan. For instance the main loop here will
> terminate on the death of the universe, labeled U. That way you only
> have to wait billions of years for it to end instead of forever.
>
>
>
*I apologize for the borderline loophole violations; I thought it was too relevant to pass up.*
If anyone was actually amused by this, more details: [(1)](http://www.mspaintadventures.com/?s=6&p=003902), [(2)](http://www.mspaintadventures.com/?s=6&p=003925), [(3)](http://www.mspaintadventures.com/?s=6&p=003926), [(4)](http://www.mspaintadventures.com/?s=6&p=003991)
[Answer]
## APL, 10
I don't think this is a valid answer (as it is non-deterministic), but anyway......
```
{?⍨1e9}⍣≡1
```
This program calculates a random permutation of 1e9 numbers (`?⍨1e9`) and repeats until two consecutive outputs are equal (`⍣≡`)
So, every time a permutation is calculated, it has a 1 in 1000000000! chance of terminating. And 1000000000! is at least 10108.
The time it takes to calculate a permutation is rendered irrelevant by the massiveness of 1000000000!. But some testing show this is `O(n)` and extrapolating gives about 30 seconds.
However, my interpreter refuses to take inputs to the random function larger than 231-1 (so I used 1e9), and generating permutations of 1000000000 numbers gave a workspace full error. However, conceptually it can be done with a ideal APL interpreter with infinite memory.
This leads us to the possibility of using 263-1 in place of 1e9 to bump the running time up to at least 101020, assuming a 64-bit architecture.
But wait, is architecture relevant in an ideal interpreter? Hell no so there is actually no upper bound on running time!!
[Answer]
# Ruby(34)
The line `([0]*9).permutation.each{print}` takes about 2.47 seconds for 9! prints on my machine, while the line `([0]*10).permutation.each{print}` takes about 24.7 seconds for 10! prints, so I guess I can extrapolate here and calculate `(24.7/10!)*470! seconds in years` which is 6.87 \* 10^1040, which should be the run time of:
```
([0]*470).permutation.each{print}
```
[Answer]
# JavaScript 68 62 chars
```
(function a(m,n){return m==0?n+1:a(m-1,n==0?1:a(m,n-1))})(5,1)
```
This uses the [Ackermann-function](http://en.wikipedia.org/wiki/Ackermann_function) which can be written as
```
function ackermann(a, b) {
if (a == 0) return b + 1;
if (b == 0) return ackermann(a-1, 1);
else return ackermann(a-1, ackermann(a, b-1));
}
```
Its runtime time increases over exponentially and takes therefore very long to calculate. Even though it is not english [here](http://de.wikipedia.org/wiki/Ackermannfunktion#Wertetabelle) you can get an overview of its return values. According to the table `ackermann(5,1)` equals `2↑↑(65533)-3` which is, you know, very big.
[Answer]
# Befunge '93 - 40 bytes
(20x2 program)
```
v<<<<<<<<<<<<<<<<<<<
>??????????????????@
```
This program relies on random numbers to give it delay. Since Befunge interpreters are quite slow, this program should fit the bill. And if it doesn't, we can always expand it horizontally.
Im not exactly sure how to go about calculating the expected running time of this program, but I know that each ? has a 50/50 chance of either starting over or changing its horizontal position by 1. There are 18 ?'s. I think it should be something along the lines of (18^2)!, which google calculator says is "Infinity"
EDIT: Whoops I did not notice the other Befunge answer, this is my first post here. Sorry.
[Answer]
## Python 3, 191 Bytes
```
from random import*
r=randint
f=lambda n:2if n<2else f(n-1)
x=9E999
s=x**x
for i in range(f(x)**f(s)):
while exec(("r(0,f(x**i))+"*int(f(x)))+"r(0,f(x**i))")!=0:
s=f(x**s)
print(s)
```
First, f is a recursive factorial function and ultra slow.
Then, there is 9\*10⁹⁹⁹ powed with itself, which generates an OverflowError, but this doesn't happen on this Unobtanium computer. The For-Loop iterates 9E999! ^ (9E999^9E999)! times and it only goes to the next iteration, if 9E999!+1 random ints between 0 and 9E99\*^i! are all 0 and in every iteration of the while-loop s gets set to (9E999^s)!. Uh, I forgot that the printing of s takes muuuuccchhhh time...
I know it's not the shortest soloution, but I think it's really effective. Can someone help me calculating the running time?
[Answer]
# Javascript, 120 bytes
```
a=[0];while(a.length<1e4)(function(){var b=0;while(b<a.length){a[b]=(a[b]+1)%9;if(a[b])return;b++}a.push(1)})();alert(a)
```
Can be done with minimal memory (probably less than half a megabyte) but takes (probably) about 108,750 years to halt.
Repeatedly increments a little-endian base-9 BigInteger until it reaches 9104-1.
[Answer]
# [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), 167 bytes
```
0 0 1 1 2 0 0
1 0 1 0 4 0 0
0 1 1 1 2 0 0
1 1 1 1 5 0 0
0 2 1 0 3 0 0
1 2 0 1 1 0 0
0 3 1 1 4 0 0
1 3 0 0 2 0 0
0 4 1 0 0 0 0
1 4 0 1 3 0 0
0 5 1 0 6 0 1
1 5 1 1 2 0 0
```
[Try it online!](https://tio.run/##RY07DsAwCEP3nIIj8EsP1L1bpRyfJsZSxQDmGfM@91pVKiq2y3fXYVAqCdXkZ12TzOEMMmdOs8CcZPAw5WTDRZa4C7IJdp3dMCh@r/oA "Turing Machine But Way Worse – Try It Online")
Should run the 6-state 2-symbol Busy Beaver from the [Wikipedia page](https://en.wikipedia.org/wiki/Busy_Beaver_game).
As said in the Wikipedia page, it runs in \$7.412 \times 10^{36534}\$ steps. This is way more than the heat death, assuming it executes each command in more than or equal to a nanosecond.
] |
[Question]
[
This is similar to other "Tips for golfing in <...>" but specifically targeting the newer features in JavaScript brought up in ECMAScript 6 and above.
JavaScript inherently is a very verbose language, `function(){}`, `.forEach()`, converting string to array, array-like object to array, etc, etc are super bloats and not healthy for Golfing.
ES6+, on the other hand, has some super handy features and reduced footprint. `x=>y`, `[...x]`, etc. are just some of the examples.
Please post some nice tricks that can help shave off those few extra bytes from your code.
**NOTE: Tricks for ES5 are already available in [Tips for golfing in JavaScript](https://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript); answers to this thread should focus on tricks only available in ES6 and other future ES versions.**
However, this thread is also for users who currently golf using ES5 features. Answers may also contain tips to help them understand and map ES6 features to their style of ES5 coding.
[Answer]
**Spread operator `...`**
The spread operator transforms an array value into a comma separated list.
Use case 1:
Directly use an array where a function expects a list
```
list=[1,2,3]
x=Math.min(...list)
list=[10,20], a.push(...list) // similar to concat()
```
Use case 2:
Create an array literal from an iterable (typically a string)
```
[...'buzzfizz'] // -> same as .split('')
```
Use case 3:
Declare a variable number of arguments for a function
```
F=(...x) => x.map(v => v+1)
// example: F(1,2,3) == [2,3,4]
```
[See mozilla doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
[Answer]
## Using property shorthands
Property shorthands allow you to set variables to an arrays' values:
```
a=r[0];b=r[1] // ES5
[a,b]=r // ES6 - 6 bytes saved
```
This can also be used like:
```
a=r[0],b=r[2] // ES5
[a,,b]=r // ES6 - 5 bytes saved
```
You can even use this to reverse variables:
```
c=a,a=b,b=c // ES5 - uses extra variable
[b,a]=[a,b] // ES6 - not shorter, but more flexible
```
You can also use this to shorten `slice()` functions.
```
z = [1, 2, 3, 4, 5];
a=z.slice(1) // a = [2,3,4,5]; ES5
[,...a]=z // a = [2,3,4,5]; ES6
```
## Base conversions
ES6 provides a much shorter way to convert form Base-2 (binary) and Base-8 (octal) to decimal:
```
0b111110111 // == 503
0o767 // == 503
```
`+` can be used to convert a binary, octal or hex string to a decimal number. You can use `0b`, `0o`, and `0x`, for binary, octal, and hex respectively.:
```
parseInt(v,2) // ES5
+('0b'+v) // ES6 - 4 bytes saved; use '0o' for octal and '0x' for hex
'0b'+v-0 // Shorter, but may not work in all cases
// You can adapt this your case for better results
```
---
If you are using this > 7 times, then it will be shorter to use `parseInt` and rename it:
```
(p=parseInt)(v,2)
```
Now `p` can be used for `parseInt`, saving you many bytes over the long run.
[Answer]
## Tricks learned here since I joined
My primary programming language is JS and mostly ES6. Since I joined this site a week back, I have learned a lot of useful tricks from fellow members. I am combining some of those here. All credits to community.
## Arrow functions and loops
We all know that arrow functions save a lot of byts
```
function A(){do something} // from this
A=a=>do something // to this
```
But you have to keep in mind a few things
* Try to club multiple statements using `,` i.e. `(a=b,a.map(d))` - Here, the value which is returned is the last expression `a.map(d)`
* if your `do something` part is more than one statement, then you need to add the surrounding `{}` brackets.
* If there are surrounding `{}` brackets, you need to add an explicit return statement.
The above holds true a lot of times when you have loops involved. So something like:
```
u=n=>{for(s=[,1,1],r=[i=1,l=2];c=l<n;i+=!c?s[r[l++]=i]=1:1)for(j of r)c-=j<i/2&s[i-j];return n>1?r:[1]}
```
Here I am wasting at least 9 characters due to the return. This can be optimized.
* Try to avoid for loops. Use `.map` or `.every` or `.some` instead. Note that if you want to change the same array that you are mapping over, it will fail.
* Wrap the loop in a closure arrow function, converting the main arrow function as single statement.
So the above becomes:
```
u=n=>(s=>{for(r=[i=1,l=2];c=l<n;i+=!c?s[r[l++]=i]=1:1)for(j of r)c-=j<i/2&s[i-j]})([,1,1])|n>1?r:[1]
```
removed characters: `{}return`
added characters: `(){}>|`
Note how I call the closure method, which correctly populates the variable `n` and then since the closure method is not returning anything (i.e. returning `undefined`), I bitwise or it and return the array `n` all in a single statement of the outer arrow function `u`
## Commas and semicolons
Avoid them what so ever,
If you are declaring variables in a loop, or like mentioned in the previous section, using `,` separated statements to have single statement arrow functions, then you can use some pretty nifty tricks to avoid those `,` or `;` to shave off those last few bytes.
Consider this code:
```
r=v=>Math.random()*100|0;n=r();m=r();D=v=>A(n-x)+A(m-y);d=0;do{g();l=d;d=D();....
```
Here, I am calling a lot of methods to initialize many variables. Each initialization is using a `,` or `;`. This can be rewritten as:
```
r=v=>Math.random()*100|0;n=r(m=r(d=0));D=v=>A(n-x)+A(m-y);do{d=D(l=d,g());....
```
Note how I use the fact that the method does not bother the variable passed to it and use that fact to shave 3 bytes.
## Misc
**`.search` instead of `.indexOf`**
Both give the same result, but `search` is shorter. Although search expects a Regular Expression, so use it wisely.
**[`Template Strings`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings)**
These are super handy when you have to concat one or more string parts based on certain conditions.
Take the following example to output a quine in JS
```
(f=x=>alert("(f="+f+")()"))()
```
vs.
```
(f=x=>alert(`(f=${f})()`))()
```
In a template string, which is a string inside two backquotes (`), anything inside a `${ }` is treated as a code and evaluated to insert the resulting answer in the string.
I'll post a few more tricks later. Happy golfing!
[Answer]
## Using string templates with functions
When you have a function with one string as the arguments. You can omit the `()` if you don't have any expressions:
```
join`` // Works
join`foobar` // Works
join`${5}` // Doesn't work
```
[Answer]
# Array Comprehensions (Firefox 30-57)
**Note: array comprehensions were never standardized, and were made obsolete with Firefox 58. Use at your own peril.**
---
Originally, the ECMAScript 7 spec contained a bunch of new array-based features. Though most of these didn't make it into the finalized version, Firefox support(ed) possibly the biggest of these features: fancy new syntax that can replace `.filter` and `.map` with `for(a of b)` syntax. Here's an example:
```
b.filter(a=>/\s/.test(a)).map(a=>a.length)
[for(a of b)if(/\s/.test(a))a.length]
```
As you can see, the two lines are not all that different, other than the second not containing the bulky keywords and arrow functions. But this only accounts for the order`.filter().map()`; what happens if you have `.map().filter()` instead? It really depends on the situation:
```
b.map(a=>a[0]).filter(a=>a<'['&&a>'@')
[for(a of b)if(a<'['&&a>'@')a[0]]
b.map(a=>c.indexOf(a)).filter(a=>a>-1)
[for(a of b)if((d=c.indexOf(a))>-1)d]
b.map(a=>a.toString(2)).filter(a=>/01/.test(a))
[for(a of b)if(/01/.test(c=a.toString(2)))c]
```
Or what if you want *either* `.map` *or* `.filter`? Well, it usually turns out less OK:
```
b.map(a=>a.toString(2))
[for(a of b)a.toString(2)]
b.filter(a=>a%3&&a%5)
[for(a of b)if(a%3&&a%5)a]
```
So my advice is to use array comprehensions wherever you would usually use `.map` *and* `.filter`, but not just one or the other.
## String Comprehensions
A nice thing about ES7 comprehensions is that, unlike array-specific functions such as `.map` and `.filter`, they can be used on *any* iterable object, not just arrays. This is especially useful when dealing with strings. For example, if you want to run each character `c` in a string through `c.charCodeAt()`:
```
x=>[...x].map(c=>c.charCodeAt())
x=>[for(c of x)c.charCodeAt()]
```
That's two bytes saved on a fairly small scale. And what if you want to filter certain characters in a string? For example, this one keeps only capital letters:
```
x=>[...x].filter(c=>c<'['&&c>'@')
x=>[for(c of x)if(c<'['&&c>'@')c]
```
Hmm, that's not any shorter. But if we combine the two:
```
x=>[...x].filter(c=>c<'['&&c>'@').map(c=>c.charCodeAt())
x=>[for(c of x)if(c<'['&&c>'@')c.charCodeAt()]
```
Wow, a whole 10 bytes saved!
Another advantage of string comprehensions is that hardcoded strings save an extra byte, since you can omit the space after `of`:
```
x=>[...'[](){}<>'].map(c=>x.split(c).length-1)
x=>[for(c of'[](){}<>')x.split(c).length-1]
x=>[...'[](){}<>'].filter(c=>x.split(c).length>3)
x=>[for(c of'[](){}<>')if(x.split(c).length>3)c]
```
## Indexing
Array comprehensions make it a little harder to get the current index in the string/array, but it can be done:
```
a.map((x,i)=>x+i).filter ((x,i)=>~i%2)
[for(x of(i=0,a))if(++i%2)x+i-1]
```
The main thing to be careful of is to make sure the index gets incremented *every* time, not just when a condition is met.
## Generator comprehensions
Generator comprehensions have basically the same syntax as array comprehensions; just replace the brackets with parentheses:
```
x=>(for(c of x)if(c<'['&&c>'@')c.charCodeAt())
```
This creates a [generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) which functions in much the same way as an array, but that's a story for another answer.
## Summary
Basically, although comprehensions are usually shorter than `.map().filter()`, it all comes down to the specifics of the situation. It's best to try it both ways and see which works out better.
P.S. Feel free to suggest another comprehension-related tip or a way to improve this answer!
[Answer]
Function expressions in ES6 use the arrow notation, and it helps a lot saving bytes if compared with the ES5 version:
```
f=function(x,y){return x+y}
f=(x,y)=>x+y
```
If your function only has one parameter, you can omit the parentheses to save two bytes:
```
f=x=>x+1
```
If your function has no parameters at all, declare it as if it had one to save one byte:
```
f=()=>"something"
f=x=>"something"
```
Beware: Arrow functions are not exactly the same as `function () {}`. The rules for `this` are different (and better IMO). See [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
[Answer]
# Using `eval` for arrow functions with multiple statements and a `return`
One of the more ridiculous tricks I've stumbled across...
Imagine a simple arrow function that needs multiple statements and a `return`.
```
a=>{for(o="",i=0;i<a;i++)o+=i;return o}
```
A simple function accepting a single parameter `a`, which iterates over all integers in `[0, a)`, and tacks them onto the end of the output string `o`, which is returned. For example, calling this with `4` as the parameter would yield `0123`.
Note that this arrow function had to be wrapped in braces `{}`, and have a `return o` at the end.
This first attempt weighs in at **39 bytes**.
Not bad, but by using `eval`, we can improve this.
```
a=>eval('for(o="",i=0;i<a;i++)o+=i;o')
```
This function removed the braces and the return statement by wrapping the code in an `eval` and simply making the last statement in the `eval` evaluate to `o`. This causes the `eval` to return `o`, which in turn causes the function to return `o`, since it is now a single statement.
This improved attempt weighs in at **38 bytes**, saving one byte from the original.
But wait, there's more! Eval statements return whatever their last statement evaluated to. In this case, `o+=i` evaluates to `o`, so we don't need the `;o`! *(Thanks, edc65!)*
```
a=>eval('for(o="",i=0;i<a;i++)o+=i')
```
This final attempt weighs only **36 bytes** - a 3 byte savings over the original!
This technique could be extended to any general case where an arrow function needs to return a value and have multiple statements (that couldn't be combined by other means)
```
b=>{statement1;statement2;return v}
```
becomes
```
b=>eval('statement1;statement2;v')
```
saving a byte.
If `statement2` evaluates to `v`, this can be
```
b=>eval('statement1;statement2')
```
saving a total of 3 bytes.
[Answer]
# Prefer template string new lines over "\n"
This will start to pay off at even a single new line character in your code. One use case might be:
### (16 bytes)
```
array.join("\n")
```
### (15 bytes)
```
array.join(`
`)
```
**Update:** You can even leave away the braces due to tagged template strings (thanks, edc65!):
### (13 bytes)
```
array.join`
`
```
[Answer]
# Returning Values in Arrow Functions
It's common knowledge that if a single statement follows the arrow function declaration, it returns the result of that statement:
```
a=>{return a+3}
a=>a+3
```
### -7 bytes
So when possible, combine multiple statements into one. This is most easily done by surrounding the statements with parentheses and separating them with commas:
```
a=>{r=0;a.map(n=>r+=n);return r}
a=>(r=0,a.map(n=>r+=n),r)
```
### -8 bytes
But if there are only two statements, it is usually possible (and shorter) to combine them with `&&` or `||`:
```
a=>{r=0;a.map(n=>r+=n);return r}
// - Use && because map always returns an array (true)
// - declaration of r moved into unused map argument to make it only 2 statements
a=>a.map(n=>r+=n,r=0)&&r
```
### -9 bytes
Finally if you are using map (or similar) and need to return a number and you can guarantee the map will never return a 1-length array with a number, you can return the number with `|`:
```
a=>{a=b=0;a.map(n=>(a+=n,b-=n));return a/b}
// - {} in map ensures it returns an array of undefined, so the | will make the returned
// array cast from [ undefined, undefined, undefined ] to ",," to NaN to 0 and 0|n = n,
// if the map returned [ 4 ] it would cast from [ 4 ] to "4" to 4 and make it 4|n
a=>a.map(n=>{a+=n,b-=n},a=b=0)|a/b
```
[Answer]
## Using `.padEnd()` instead of `.repeat()` (ES8)
Under certain circumstances, using [`.padEnd()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd) instead of `.repeat()` saves bytes.
We can take advantage of the following properties:
* the default padding string is a single space
* when provided, the second parameter is implicitly coerced to a string
### Repeating spaces
With `.repeat()`:
```
' '.repeat(10)
```
Using `.padEnd()` saves **1 byte**:
```
''.padEnd(10)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@mYKsQr2Br919dXa8gMcU1L0XD0EDzf3J@XnF@TqpeTn66hrqHq4@Pv7qCtkKahqaCtnq4f5CPi7rmfwA "JavaScript (Node.js) – Try It Online")
### Repeating a dynamic value that needs to be coerced to a string
With `.repeat()`:
```
x=1;
(x+'').repeat(10)
```
Using `.padEnd()` saves **2 bytes**:
```
x=1;
''.padEnd(10,x)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQq8xuFEtyr@46iPiJQhzJCG8/vveEP4z43v3bG6XMBRxMcJ4RdQ/pbEmYY5uSI7VBNetKl0DvERQUYSQotBYlLw "JavaScript (Node.js) – Try It Online")
[Answer]
## Optimizing small constant ranges for `map()`
### Context
Starting with ES6, it has become fairly common to use (and abuse) the `map()` method instead of a `for` loop to iterate over a range \$[0..N-1]\$, so that the entire answer can be written in functional style:
```
for(i = 0; i < 10; i++) {
do_something_with(i);
}
```
can be replaced by either:
```
[...Array(10).keys()].map(i => do_something_with(i))
```
or more commonly:
```
[...Array(10)].map((_, i) => do_something_with(i))
```
However, using `Array(N)` is rarely optimal when \$N\$ is a small constant.
### Optimizations for a range \$[0..N-1]\$, with counter
Below is a summary of shorter alternate methods when the counter \$i\$ is used within the callback:
```
N | Method | Example | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 6 | use a raw array of integers | [0,1,2,3].map(i=>F(i)) | 2N+10
N = 7 | use either a raw array of integers | [0,1,2,3,4,5,6].map(i=>F(i)) | 24
| or a string if your code can operate | [...'0123456'].map(i=>F(i)) | 23
| with characters rather than integers | |
8 ≤ N ≤ 9 | use scientific notation 1e[N-1] | [...1e7+''].map((_,i)=>F(i)) | 24
N = 10 | use scientific notation 1e9 | [...1e9+''].map((_,i)=>F(i)) | 24
| or the ES7 expression 2**29+'4' if | [...2**29+'4'].map(i=>F(i)) | 23
| the order doesn't matter and your | |
| code can operate with characters | (order: 5,3,6,8,7,0,9,1,2,4) |
| rather than integers | |
11 ≤ N ≤ 17 | use scientific notation 1e[N-1] | [...1e12+''].map((_,i)=>F(i)) | 25
N = 18 | use the fraction 1/3 | [...1/3+''].map((_,i)=>F(i)) | 24
N = 19 | use the fraction 1/6 | [...1/6+''].map((_,i)=>F(i)) | 24
20 ≤ N ≤ 21 | use scientific notation 1e[N-1] | [...1e20+''].map((_,i)=>F(i)) | 25
N = 22 | use scientific notation -1e20 | [...-1e20+''].map((_,i)=>F(i)) | 26
23 ≤ N ≤ 99 | use Array(N) | [...Array(23)].map((_,i)=>F(i)) | 27
```
**NB**: The length of the callback code `F(i)` is not counted.
### Optimization for the range \$[1..9]\$, with counter
If you'd like to iterate over the range \$[1..9]\$ and the order doesn't matter, you can use the following ES7 expression (provided that your code can operate with characters rather than integers):
```
[...17**6+'8'].map(i=>F(i)) // order: 2,4,1,3,7,5,6,9,8; length: 23
```
### Optimizations without counter
The following methods can be used if you just need to iterate \$N\$ times, without using a counter:
```
N | Method | Example | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 5 | use a raw array of integers | [0,0,0,0].map(_=>F()) | 2N+10
6 ≤ N ≤ 10 | use scientific notation 1e[N-1] | [...1e7+''].map(_=>F()) | 20
11 ≤ N ≤ 17 | use scientific notation 1e[N-1] | [...1e12+''].map(_=>F()) | 21
N = 18 | use the fraction 1/3 | [...1/3+''].map(_=>F()) | 20
N = 19 | use the fraction 1/6 | [...1/6+''].map(_=>F()) | 20
20 ≤ N ≤ 21 | use scientific notation 1e[N-1] | [...1e20+''].map(_=>F()) | 21
N = 22 | use scientific notation -1e20 | [...-1e20+''].map(_=>F()) | 22
23 ≤ N ≤ 99 | use Array(N) | [...Array(23)].map(_=>F()) | 23
```
**NB**: The length of the callback code `F()` is not counted.
[Answer]
## Writing RegEx literals with `eval`
The regex constructor can be very bulky due to it's long name. Instead, write a literal with eval and backticks:
```
eval(`/<${i} [^>]+/g`)
```
If the variable `i` is equal to `foo`, this will generate:
```
/<foo [^>]+/g
```
This is equal to:
```
new RegExp("<"+i+" [^>]+","g")
```
---
You can also use `String.raw` to avoid having to repeatedly escape backslashes `\`
```
eval(String.raw`/\(?:\d{4})?\d{3}\d{3}\d{3}\d{3}\d{3}\d{3}\d{4}/g`)
```
This will output:
```
/(?:\d{4})?\d{3}\d{3}\d{3}/g
```
Which is equal to:
```
RegExp("\\(?:\\d{4})?\\d{3}\\d{3}\\d{3}\\d{3}\\d{3}\\d{3}\\d{4}","g")
```
# Keep in mind!
`String.raw` takes up a lot of bytes and unless you have at *least* nine backslashes, `String.raw` will be longer.
[Answer]
# Filling Arrays - Static Values & Dynamic Ranges
I originally left these as comments under comprehensions, but since that post was primarily focused on comprehensions, I figured that it would be good to give this it's own place.
ES6 gave us the ability to fill arrays with static values without the use of loops:
```
// ES5
function(x){for(i=0,a=[];i<x;i++)a[i]=0;return a}
// ES6
x=>Array(x).fill(0)
```
Both return an array of length x, filled with the value 0.
If you want to fill arrays with dynamic values (such as a range from 0...x) however, the result is a little longer (although still shorter than the old way):
```
// ES5
function(x){for(i=0,a=[];i<x;i++)a[i]=i;return a}
// ES6
x=>Array(x).fill().map((a,i)=>i)
```
Both return an array of length x, starting with the value 0 and ending in x-1.
The reason you need the `.fill()` in there is because simply initializing an array won't let you map it. That is to say, doing `x=>Array(x).map((a,i)=>i)` will return an empty array. You can also get around the need for fill (and thus make it even shorter) by using the spread operator like so:
```
x=>[...Array(x)]
```
Using the spread operator and `.keys()` function, you can now make a short 0...x range:
```
x=>[...Array(x).keys()]
```
If you want a custom range from x...y, or a specialized range altogether (such as even numbers), you can get rid of `.keys()` and just use `.map()`, or use `.filter()`, with the spread operator:
```
// Custom range from x...y
(x,y)=>[...Array(y-x)].map(a=>x++)
// Even numbers (using map)
x=>[...Array(x/2)].map((a,i)=>i*2)
// Even numbers (using filter)
x=>[...Array(x).keys()].filter(a=>~a%2)
```
[Answer]
# How to golf with recursion
Recursion, though not the fastest option, is very often the shortest. Generally, recursion is shortest if the solution can simplified to the solution to a smaller part of the challenge, especially if the input is a number or a string. For instance, if `f("abcd")` can be calculated from `"a"` and `f("bcd")`, it's usually best to use recursion.
Take, for instance, factorial:
```
n=>[...Array(n).keys()].reduce((x,y)=>x*++y,1)
n=>[...Array(n)].reduce((x,_,i)=>x*++i,1)
n=>[...Array(n)].reduce(x=>x*n--,1)
n=>{for(t=1;n;)t*=n--;return t}
n=>eval("for(t=1;n;)t*=n--")
f=n=>n?n*f(n-1):1
```
In this example, recursion is obviously way shorter than any other option.
How about sum of charcodes:
```
s=>[...s].map(x=>t+=x.charCodeAt(),t=0)|t
s=>[...s].reduce((t,x)=>t+x.charCodeAt())
s=>[for(x of(t=0,s))t+=x.charCodeAt()]|t // Firefox 30+ only
f=s=>s?s.charCodeAt()+f(s.slice(1)):0
```
This one is trickier, but we can see that when implemented correctly, recursion saves 4 bytes over `.map`.
Now let's look at the different types of recursion:
## Pre-recursion
This is usually the shortest type of recursion. The input is split into two parts `a` and `b`, and the function calculates something with `a` and `f(b)`. Going back to our factorial example:
```
f=n=>n?n*f(n-1):1
```
In this case, `a` is **n**, `b` is **n-1**, and the value returned is `a*f(b)`.
**Important note: All** recursive functions **must** have a way to stop recursing when the input is small enough. In the factorial function, this is controlled with the `n? :1`, i.e. if the input is **0**, return **1** without calling `f` again.
## Post-recursion
Post-recursion is similar to pre-recursion, but slightly different. The input is split into two parts `a` and `b`, and the function calculates something with `a`, then calls `f(b,a)`. The second argument usually has a default value (i.e. `f(a,b=1)`).
Pre-recursion is good when you need to do something special with the final result. For example, if you want the factorial of a number plus 1:
```
f=(n,p=1)=>n?f(n-1,n*p):p+1
```
Even then, however, post- is not always shorter than using pre-recursion within another function:
```
n=>(f=n=>n?n*f(n-1):1)(n)+1
```
So when is it shorter? You may notice that post-recursion in this example requires parentheses around the function arguments, while pre-recursion did not. Generally, if both solutions need parentheses around the arguments, post-recursion is around 2 bytes shorter:
```
n=>!(g=([x,...a])=>a[0]?x-a.pop()+g(a):0)(n)
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n
```
(programs here taken from [this answer](https://codegolf.stackexchange.com/a/94318/42545))
# How to find the shortest solution
Usually the only way to find the shortest method is to try all of them. This includes:
* Loops
* `.map` (for strings, either `[...s].map` or `s.replace`; for numbers, you can [create a range](https://codegolf.stackexchange.com/a/61505/42545))
* [Array comprehensions](https://codegolf.stackexchange.com/a/61489/42545)
* Pre-recursion (sometimes within another of these options)
* Post-recursion
And these are just the most common solutions; the best solution might be a combination of these, or even [something entirely different](https://codegolf.stackexchange.com/a/99460/42545). The best way to find the shortest solution is to [try everything](https://www.youtube.com/watch?v=J8vxiVIH7VY).
[Answer]
## Random template-string hacks
This function riffles two strings (i.e. turns `"abc","de"` into `"adbec"`):
```
f=(x,y)=>String.raw({raw:x},...y)
```
Note that this only works when `x` is longer than `y`. How does it work, you ask? `String.raw` is designed to be a template tag, like so:
```
String.raw`x: ${x}\ny: ${y}\nx + y: ${x + y}`
```
This basically calls `String.raw(["x: ", "\ny: ", "\nx + y: ", ""], x, y, x + y)`, though it's not that simple. The template array also has a special `raw` property, which is basically a copy of the array, but with the raw strings. `String.raw(x, ...args)` basically returns `x.raw[0] + args[0] + x.raw[1] + args[1] + x.raw[2] + ...` and so on until `x` runs out of items.
So now that we know how `String.raw` works, we can use it to our advantage:
```
f=(x,y)=>String.raw({raw:x},...y) // f("abc", "de") => "adbec"
f=x=>String.raw({raw:x},...[...x].keys()) // f("abc") => "a0b1c"
f=(x,y)=>String.raw({raw:x},...[...x].fill(y)) // f("abc", " ") => "a b c"
```
Of course, for that last one, `f=(x,y)=>x.split``.join(y)` is way shorter, but you get the idea.
Here are a couple of riffling functions that also work if `x` and `y` are of equal length:
```
f=(x,y)=>String.raw({raw:x.match(/.?/g)},...y)
f=(x,y)=>String.raw({raw:x},...y)+y.slice(-1) // Only works if x.length == y.length
```
You can learn more about `String.raw` [on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).
[Answer]
## Shorter ways to do `.replace`
---
If you want to replace all instances of one exact substring with another in a string, the obvious way would be:
```
f=s=>s.replace(/l/g,"y") // 24 bytes
f("Hello, World!") // -> "Heyyo, Woryd!"
```
However, you can do 1 byte shorter:
```
f=s=>s.split`l`.join`y` // 23 bytes
f("Hello, World!") // -> "Heyyo, Woryd!"
```
Note that this is no longer shorter if you want to use any regex features besides the `g` flag. However, if you're replacing all instances of a variable, it's usually far shorter:
```
f=(s,c)=>s.replace(RegExp(c,"g"),"") // 36 bytes
f=(s,c)=>s.split(c).join`` // 26 bytes
f("Hello, World!","l") // -> "Heo, Word!"
```
---
Sometimes you'll want to map over each char in a string, replacing each one with something else. I often find myself doing this:
```
f=s=>s.split``.map(x=>x+x).join`` // 33 bytes
f=s=>[...s].map(x=>x+x).join`` // 30 bytes
f("abc") // -> "aabbcc"
```
However, `.replace` is almost always shorter:
```
f=s=>s.replace(/./g,x=>x+x) // 27 bytes
f=s=>s.replace(/./g,"$&$&") // Also works in this particular case
```
Now, if you want to map over each char in a string but don't care about the resulting string, `.map` is usually better because you can get rid of `.join```:
```
f=s=>s.replace(/./g,x=>t+=+x,t=0)&&t // 36 bytes
f=s=>[...s].map(x=>t+=+x,t=0)&&t // 32 bytes
f("12345") // -> 15
```
[Answer]
# `.forEach` vs `for` loops
Always prefer `.map` to any for loop. Easy, instant savings.
---
```
a.map(f)
for(x of a)f(x);
for(i=0;i<a.length;)f(a[i++]);
```
* **8 bytes total** for original
* **8 bytes saved** vs for-of (**50%** reduction)
* **22 bytes saved** vs C-style for loop (**73%** reduction)
---
```
a.map(x=>f(x,0))
for(x of a)f(x,0);
for(i=0;i<a.length;)f(a[i++],0);
```
* **16 bytes total** for original
* **2 bytes saved** vs for-of (**11%** reduction)
* **16 bytes saved** vs C-style for loop (**50%** reduction)
---
```
a.map((x,i)=>f(x,i,0))
for(i in a)f(a[i],i,0);
for(i=0;i<a.length;)f(a[i],i++,0);
```
* **22 bytes total** for original
* **1 byte saved** vs for-in (**4%** reduction)
* **11 bytes saved** vs C-style for loop (**33%** reduction)
---
```
a.map(x=>f(x)&g(x))
for(x of a)f(x),g(x);
for(i=0;i<a.length;)f(x=a[i++]),g(x);
```
* **19 bytes total** for original
* **2 bytes saved** vs for-of (**10%** reduction)
* **18 bytes saved** vs C-style for loop (**49%** reduction)
[Answer]
## Using uninitialized counters in recursion
***Note**: Strictly speaking, this is not specific to ES6. It makes more sense to use and abuse recursion in ES6, however, because of the concise nature of arrow functions.*
---
It is rather common to come across a recursive function that's using a counter `k` initially set to zero and incremented at each iteration:
```
f = (…, k=0) => [do a recursive call with f(…, k+1)]
```
Under certain circumstances, it's possible to omit the initialization
of such a counter and replace `k+1` with `-~k`:
```
f = (…, k) => [do a recursive call with f(…, -~k)]
```
This trick typically **saves 2 bytes**.
### Why and when does it work?
The formula that makes it possible is `~undefined === -1`. So, on the first iteration, `-~k` will be evaluated to `1`. On the next iterations, `-~k` is essentially equivalent to `-(-k-1)` which equals `k+1`, at least for integers in the range [0 … 231-1].
You must however make sure that having `k = undefined` on the first iteration will not disrupt the behavior of the function. You should especially keep in mind that most arithmetic operations involving `undefined` will result in `NaN`.
### Example #1
Given a positive integer `n`, this function looks for the smallest integer `k` that doesn't divide `n`:
```
f=(n,k=0)=>n%k?k:f(n,k+1) // 25 bytes
```
It can be shortened to:
```
f=(n,k)=>n%k?k:f(n,-~k) // 23 bytes
```
This works because `n % undefined` is `NaN`, which is falsy. That's the expected result on the first iteration.
[[Link to original answer]](https://codegolf.stackexchange.com/a/105432/58563)
### Example #2
Given a positive integer `n`, this function looks for an integer `p` such that `(3**p) - 1 == n`:
```
f=(n,p=0,k=1)=>n<k?n>k-2&&p:f(n,p+1,k*3) // 40 bytes
```
It can be shortened to:
```
f=(n,p,k=1)=>n<k?n>k-2&&p:f(n,-~p,k*3) // 38 bytes
```
This works because `p` is not used at all on the first iteration (`n<k` being false).
[[Link to original answer]](https://codegolf.stackexchange.com/a/105923/58563)
[Answer]
## Using `flat()` when building an array recursively (ES10)
When elements are appended conditionally to an array with recursive calls, a typical construction is:
```
f=k=>k?[...k%3?[k]:[],...f(k-1)]:[] // 35 bytes
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbb1i7bPlpPTy9b1dg@OjvWKjpWB8hL08jWNdQE8f4n5@cV5@ek6uXkp2ukaRgaaGr@BwA "JavaScript (Node.js) – Try It Online")
(this example code filters out values that are multiple of 3)
Notice that the spread operators is used twice (costing 6 bytes) and the payload value `k` has to be put within a singleton array (costing 2 more bytes).
An alternate approach is to apply `.flat()` immediately after each iteration, saving a byte:
```
f=k=>k?[k%3?k:[],f(k-1)].flat():[] // 34 bytes
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbb1i7bPjpb1dg@2yo6VidNI1vXUDNWLy0nsURDEyjyPzk/rzg/J1UvJz9dI03D0EBT8z8A "JavaScript (Node.js) – Try It Online")
[Answer]
## ES6 functions
### Math
`Math.cbrt(x)` saves characters than `Math.pow(x,1/3)`, however this is obsolete when using `x**1/3`.
```
Math.cbrt(x)
Math.pow(x,1/3)
```
3 chars saved
`Math.hypot(...args)` is useful when you need the square root of the sum of the squares of the args. Making ES6 code to do that is generally much longer than using a built-in, although it can differ depending on your output format.
The function `Math.trunc(x)` wouldn't be helpful, as `x|0` is shorter. (Thanks Mwr247!)
There are many properties that take lots of code to do in ES5, but easier in ES6:
* `Math.acosh`, `asinh`, `atanh`, `cosh`, `sinh`, `tanh`. Calculates the hyperbolic equivalent of trigonometric functions, but are almost never used, [except very occasionally](https://codegolf.stackexchange.com/questions/223166/implement-ashs-float-division/223169#223169).
* `Math.clz32`. Might be possible to do in ES5, but is easier now. Counts leading zeros in the 32-bit representation of a number.
There are a lot more, so I'm just going to list some:
`Math.sign` (occasionally useful), `Math.fround` (useless), `Math.imul` (useless), `Math.log10` (sometimes shorter than length), `Math.log2` (very useful), `Math.log1p` (almost completely useless).
[Answer]
# Return intermediate result
You know that using the comma operator you can execute a sequence of expressions returning the last value. But abusing the literal array syntax, you can return any intermediate value. It's useful in .map() for instance.
```
// capitalize words
// f is a flag indicating if prev char is space
[...x].map(c=>(f?c=c.toUpperCase():0,f=c<'!',c),f=1).join('')
// shortened to ...
[...x].map(c=>[f?c.toUpperCase():c,f=c<'!'][0],f=1).join('')
```
[Answer]
## Primality-testing function
The following 28-byte function returns `true` for prime numbers and `false` for non-primes:
```
f=(n,x=n)=>n%--x?f(n,x):x==1
```
This can easily be modified to calculate other things. For example, this 39-byte function counts the number of primes less than or equal to a number:
```
f=(n,x=n)=>n?n%--x?f(n,x):!--x+f(n-1):0
```
If you already have a variable `n` that you want to check for primality, the primality function can be simplified quite a bit:
```
(f=x=>n%--x?f(x):x==1)(n)
```
### How it works
```
f = ( // Define a function f with these arguments:
n, // n, the number to test;
x = n // x, with a default value of n, the number to check for divisibility by.
) =>
n % --x ? // If n is not divisible by x - 1,
f(n, x) // return the result of f(n, x - 1).
// This loops down through all numbers between n and 0,
// stopping when it finds a number that divides n.
: x == 1 // Return x == 1; for primes only, 1 is the smallest number
// less than n that divides n.
// For 1, x == 0; for 0, x == -1.
```
Note: This will fail with a "too much recursion" error when called with a sufficiently large input, such as 12345. You can get around this with a loop:
```
f=n=>eval('for(x=n;n%--x;);x==1')
```
[Answer]
# Golfing Logical Operations in ES6
"GLOE (S6)"
## General Logic
Say you have constructed statements `s` and `t`. See if you can use any of the following replacements:
```
Traditional conjuction: s&&t
Equivalent conjuction: s*t OR s&t
Traditional disjunction: s||t
Equivalent disjunction: s+t OR s|t
```
(These may not work if the order is wrong; i.e. `+` and `*` have a lower order precedence than `||` and `&&` do.)
Also, here are some handy logical expressions:
* Either `s` or `t` is true/XOR: `s^t`
* `s` and `t` are the same truth value: `!s^t` or `s==t`
## Array logic
All members of `a` satisfy condition `p`:
```
a.every(p) // 10 bytes (11 bytes saved)
a.map(x=>c&=p(x),c=1) // 21 bytes (16 bytes saved)
for(i=0,c=1;i<a.length;c&=p(a[i++])); // 37 bytes (hideously long)
```
At least one member of `a` satisfies condition `p`:
```
a.some(p) // 9 bytes (13 bytes saved)
a.map(x=>c|=p(x),c=0) // 21 bytes (14 bytes saved)
for(i=c=0;i<a.length;c|=p(a[i++])); // 35 bytes (just please no)
```
No members of `a` satisfy condition `p`: `!a.some(p)`.
Element `e` exists in array `a`:
```
a.includes(e) // 13 bytes, standard built-in
~a.indexOf(e) // 13 bytes, "traditional" method
a.find(x=>e==x) // 15 bytes, find (ES6)
a.some(x=>x==e) // 15 bytes, some (ES5)
(a+"").search(e) // 16 bytes, buggy
a.filter(t=>t==e).length // 24 bytes, no reason to use this
for(i=c=0;i<a.length;c+=e==a[i++]); // 35 bytes, super-traditional
```
Element `e` does *not* exist in array `a`:
```
!a.includes(e)
!~a.indexOf(e)
a.every(t=>t!=e)
!a.filter(t=>t==e).length
for(i=0,c=1;i<a.length;c*=e!=a[i++]);
```
[Answer]
# Yet another way to avoid `return`
You know you should [use eval for arrow functions with multiple statements and a return](https://codegolf.stackexchange.com/a/55618/21348). In some unusual case you can save more using an inner subfunction.
I say *unusual* because
1. The result returned must not be the last expression evalued in the loop
2. There must be (at least) 2 *different* initializations before the loop
In this case you can use an inner subfunction without return, having one of the initial values passed as a parameter.
**Example**
Find the reciprocal of the sum of exp function for values in a range from a to b.
The long way - 55 bytes
```
(a,b)=>{for(r=0,i=a;i<=b;i++)r+=Math.exp(i);return 1/r}
```
With eval - 54 bytes
```
(a,b)=>eval("for(r=0,i=a;i<=b;i++)r+=Math.exp(i);1/r")
```
With an inner function - 53 bytes
```
(a,b)=>(i=>{for(r=0;i<=b;i++)r+=Math.exp(i)})(a)||1/r
```
Note that without the requirement of a lower range limit `a`, I can merge the initializations of i and r and the eval version is shorter.
[Answer]
## Using the currying syntax for dyadic and recursive functions
### Dyadic functions
Whenever a function takes exactly two arguments with no default values, using the currying syntax saves one byte.
**Before**
```
f =
(a,b)=>a+b // 10 bytes
```
Called with `f(a,b)`
**After**
```
f =
a=>b=>a+b // 9 bytes
```
Called with `f(a)(b)`
*Note*: [This post in Meta](http://meta.codegolf.stackexchange.com/questions/8424/is-this-an-acceptable-way-to-shave-a-byte-in-es6) confirms the validity of this syntax.
### Recursive functions
Using the currying syntax may also save some bytes when a recursive function takes several arguments but only needs to update some of them between each iteration.
**Example**
The following function computes the sum of all integers in the range `[a,b]`:
```
f=(a,b)=>a>b?0:b+f(a,b-1) // 25 bytes
```
Because `a` remains unchanged during the whole process, we can save 3 bytes by using:
```
f = // no need to include this assignment in the answer anymore
a=>F=b=>a>b?0:b+F(b-1) // 22 bytes
```
*Note*: As noticed by Neil in the comments, the fact that an argument is not explicitly passed to the recursive function does not mean that it should be considered immutable. If needed, we could modify `a` within the function code with `a++`, `a--` or whatever similar syntax.
[Answer]
# `Array#concat()` and the spread operator
This largely depends on the situation.
---
## Combining multiple arrays.
Prefer the concat function unless cloning.
**0 bytes saved**
```
a.concat(b)
[...a,...b]
```
**3 bytes wasted**
```
a.concat(b,c)
[...a,...b,...c]
```
**3 bytes saved**
```
a.concat()
[...a]
```
**6 bytes saved**
```
// Concatenate array of arrays
[].concat.apply([],l)
[].concat(...l)
```
---
## Prefer using an already existing array to `Array#concat()`.
Easy **4 bytes saved**
```
[].concat(a,b)
a.concat(b)
```
[Answer]
# Use `eval` instead of braces for arrow functions
Arrow functions are awesome. They take the form `x=>y`, where `x` is an argument and `y` is the return value. However, if you need to use a control structure, such as `while`, you would have to put braces, e.g. `=>{while(){};return}`. However, we can get around this; luckily, the `eval` function takes a string, evaluates that string as JS code, and *returns the last evaluated expression*. For example, compare these two:
```
x=>{while(foo){bar};return baz} // before
x=>eval('while(foo){bar};baz') // after
// ^
```
We can use an extension of this concept to further shorten our code: in the eyes of `eval`, control structures also return their last evaluated expression. For example:
```
x=>{while(foo)bar++;return bar} // before
x=>eval('while(foo)++bar') // after
// ^^^^^
```
[Answer]
# Destructuring assignments
ES6 introduces new syntax for destructuring assignments, i.e. cutting a value into pieces and assigning each piece to a different variable. Here are a few examples:
### Strings and arrays
```
a=s[0];b=s[1]; // 14 bytes
[a,b]=s; // 8 bytes
a=s[0];s=s.slice(1); // 20 bytes
a=s.shift(); // 12 bytes, only works if s is an array
[a,...s]=s; // 11 bytes, converts s to an array
```
### Objects
```
a=o.asdf;b=o.bye;c=o.length; // 28 bytes
{asdf:a,bye:b,length:c}=o; // 26 bytes
a=o.a;b=o.b;c=o.c; // 18 bytes
{a,b,c}=o; // 10 bytes
```
These assignments can also be used in function parameters:
```
f=a=>a[0]+a[1]+a[2]
f=([a,b,c])=>a+b+c
f=b=>b[1]?b[0]+f(b.slice(1)):b[0]*2
f=b=>b[1]?b.shift()+f(b):b[0]*2
f=([a,...b])=>b[0]?a+f(b):a*2
```
[Answer]
# Avoiding commas when storing lots of data
If you have a lot of data (i. e. indices, characters, …) that you need to store in an array, you might be better off leaving all commas away. This works best if every piece of data has the same string length, 1 obviously being optimal.
**43 Bytes (baseline)**
```
a=[[3,7,6,1,8,9,4,5,2],[5,4,3,2,7,6,5,4,3]]
```
**34 Bytes (no commas)**
```
a=[[..."376189452"],[..."543276543"]]
```
If you're willing to *change your array access*, you might reduce this even further, storing the same values like so:
**27 Bytes (same data, only changes array access)**
```
a=[..."376189452543276543"]
```
[Answer]
# Convert BigInt back to Number (Chrome 67+ / Node.js 10.4+)
## !! ALERT : ESNext feature ahead !!
BigInt makes arbitrary-precision integer arithmetic more handy in JS, but there is a caveat - most already existing functions that accepts Number, does not accept BigInt. **UPDATE: array indexer DOES support BigInt for some reason.**
When we need to convert a BigInt back to Number for some reason, we cannot use `+n` (**[this is explicitly forbidden in the specs](https://developers.google.com/web/updates/2018/05/bigint#operators)**), but instead we need to use `Number(n)` -- except we do not really need to do so.
Instead of using `Number(n)`, we realise that we can actually convert the BigInt first into a String and then to a Number using `+`${n}`` , which saves 2 bytes.
But we can do better: wrap the BigInt with an array then directly cast it using `+` operator. This gives `+[n]` which saves 3 more bytes. Most importantly this **eliminates the use of `Number(n)` or even `(N=Number)(n)` and further `N(n)`s for multiple uses because `+[n]` has the same length as `N(n)`.**
You can test this out with this example:
```
s=163n;
console.log(Number(s)) // 9 bytes
console.log(+`${s}`) // 7 bytes
console.log(+[s]) // 4 bytes
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/2NbQzDjPmis5P684PydVLyc/XcOvNDcptUijWFNTQV9fwVIhqbIktRhFhXaCSnVxbYKmggJIhTk2FdHFsSBpiAoTiIr//wE "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
## Overview
This is a bot battle to see who can survive the longest. These bots increase their power by being attacked, though, so you need to think carefully before you shoot.
Each turn, you can choose a bot to attack, or defend. Attacking will lower its life and increase its power. Last bot standing wins.
### Bots
Each bot starts with 1000 life and 10 power.
**When attacked:**
* your attacker's power is subtracted from your life
* your power raises by 1.
So, if on the first turn, you are attacked by two bots, you will have 980 life and 12 power.
**If you choose to defend:**
* your power will be lowered by 1
* all attacks against you this turn will be reduced by half
* if you are attacked, you will gain 2 power for each attacker instead of 1
So, if you defend on the first turn and are attacked by two bots, you will have 990 life and 13 power. If you defend and are not attacked, you will have 1000 life, but 9 power.
If at the end of a turn your power is below one, it will be set to one. If your life is below 1, you die.
### Input/Output
Bots are called once per turn. There is a time limit of one second for each turn.
**Initial**
The first time your bot is called, it will be given no arguments. Respond with `ok`. This is done only to make sure your bot responds. If it doesn't, it will not be added to the player list.
**Each turn**
Each turn, your bot is given information about all bots in the game as command line arguments. An example of these arguments is:
```
1 0,1000,10,1 1,995,11,D
```
The first argument is your bot's unique id. Then, a space separated list of bots appears. Each bot is formatted as:
```
id,life,power,lastAction
```
`lastAction` may be an integer representing which bot they attacked, `D` if they defended, and `X` if this is the first turn. The others are all integers.
So in the example above, you are bot `1` and defended on your last turn. Bot `0` attacked you and is still at starting health/power.
Output for each turn is very simple. Simply output the bot you want to attack as an integer (eg `0` or `3`), or `D` to defend. Don't attack dead or non-existent bots, as that counts as an invalid command. Any invalid command will result in you losing 1 power.
### Tournament Structure
Each game consists of all bots starting at 1000 health and 10 power. Actions by all bots are taken simultaneously. The maximum number of turns for a game is 1000.
If at the end of the turn there is one bot remaining alive (life > 0), it scores one point and another game is started. If the turn limit is reached and there are multiple bots alive, *nobody gets a point.* If all remaining bots die on the same turn, *nobody gets a point.*
A tournament consists of 15 games. Whoever has the most points at the end wins! Ties are broken by the sum of life remaining in each won game.
### State
Bots may only read from or write to a single file named after itself, in a direct subfolder named `state` ("Hero" can write to `state/hero.whatever`). This file should not exceed 10242 bytes in size. Take care to observe the time limit. Your program must *terminate* within one second to count, not just give a response.
These files will be wiped before each tournament, but will persist game to game. All bot identifiers (`id`) will also remain the same between games.
### Controller
Below is the tournament controller (`Stronger.java`). *By default*, it only outputs the final results (sorted list of players, winner on top), which may take quite a while. It's not frozen, just silent. If you'd like a more detailed turn-by turn output, add the `-log` argument when running.
To add bots, you have two options:
* add the command as an argument (`java Stronger -log "python bot.py"`)
* add the command to `defaultPlayers[]` in the source (`"python bot.py"`)
The bots *Hero*, *Bully*, and *Coward* can be found [in this answer](https://codegolf.stackexchange.com/a/50173/14215), and will be used for scoring purposes.
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Stronger {
static final String[] defaultPlayers = {
"java Hero",
"java Bully",
"java Coward"
};
final int timeout = 1000;
final int startLife = 1000;
final int startPower = 10;
final int numRounds = 15;
boolean log = false;
List<Player> players;
public static void main(String[] args){
new Stronger().run(args);
}
void run(String[] args){
init(args);
for(int i=0;i<numRounds;i++){
Collections.shuffle(players);
runGame();
}
Collections.sort(players);
for(Player player : players)
System.out.println(player.toString());
}
void runGame(){
log("Player Count: " + players.size());
for(Player player : players)
player.reset();
int turn = 0;
while(turn++ < startLife){
if(aliveCount() < 2)
break;
log("Turn " + turn);
List<Player> clones = new ArrayList<Player>();
for(Player player : players)
clones.add(player.copy());
for(Player player : players){
if(player.life < 1 || player.timedOut)
continue;
String[] args = new String[players.size()+1];
args[0] = "" + player.id;
for(int i=1;i<args.length;i++)
args[i] = players.get(i-1).toArgument();
String reply = getReply(player, args);
Player clone = player.findCopyOrMe(clones);
if(reply.equals("T")){
clone.timedOut = true;
clone.life = 0;
}
clone.lastAction = reply.trim();
}
for(Player player : players){
if(player.life < 1 || player.timedOut)
continue;
Player clone = player.findCopyOrMe(clones);
if(clone.lastAction.equals("D")){
clone.power--;
}else{
try{
int target = Integer.parseInt(clone.lastAction);
for(Player t : players)
if(t.id == target && t.life < 1)
throw new Exception();
for(Player tclone : clones){
if(tclone.id == target){
int atk = player.power;
if(tclone.lastAction.equals("D")){
atk -= player.power / 2;
tclone.power++;
}
tclone.life -= atk;
tclone.power++;
}
}
} catch (Exception e){
log(player.cmd + " returned an invalid command: (" + clone.lastAction + ")");
clone.power--;
}
}
}
players = clones;
for(Player player : players){
if(player.power < 1)
player.power = 1;
log(player.life + "\t\t" + player.power + "\t\t(" + player.id + ")\t" + player.cmd);
}
log("\n");
}
if(aliveCount() == 1)
for(Player player : players)
if(player.life > 0){
player.scoreRounds++;
player.scoreLife += player.life;
}
}
void log(String msg){if(log)System.out.println(msg);}
String getReply(Player player, String[] args){
try{
List<String> cmd = new ArrayList<String>();
String[] tokens = player.cmd.split(" ");
for(String token : tokens)
cmd.add(token);
for(String arg : args)
cmd.add(arg);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream();
long start = System.currentTimeMillis();
Process process = builder.start();
Scanner scanner = new Scanner(process.getInputStream());
process.waitFor();
String reply = scanner.nextLine();
scanner.close();
process.destroy();
if(System.currentTimeMillis() - start > timeout)
return "T";
return reply;
}catch(Exception e){
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
void init(String[] args){
players = new ArrayList<Player>();
for(String arg : args){
if(arg.toLowerCase().startsWith("-log")){
log = true;
}else{
Player player = createPlayer(arg);
if(player != null)
players.add(player);
}
}
for(String cmd : defaultPlayers){
Player player = createPlayer(cmd);
if(player != null)
players.add(player);
}
}
Player createPlayer(String cmd){
Player player = new Player(cmd);
String reply = getReply(player, new String[]{});
log(player.cmd + " " + reply);
if(reply != null && reply.equals("ok"))
return player;
return null;
}
int aliveCount(){
int alive = 0;;
for(Player player : players)
if(player.life > 0)
alive++;
return alive;
}
static int nextId = 0;
class Player implements Comparable<Player>{
int id, life, power, scoreRounds, scoreLife;
boolean timedOut;
String cmd, lastAction;
Player(String cmd){
this.cmd = cmd;
id = nextId++;
scoreRounds = 0;
scoreLife = 0;
reset();
}
public Player copy(){
Player copy = new Player(cmd);
copy.id = id;
copy.life = life;
copy.power = power;
copy.scoreRounds = scoreRounds;
copy.scoreLife = scoreLife;
copy.lastAction = lastAction;
return copy;
}
void reset(){
life = startLife;
power = startPower;
lastAction = "X";
timedOut = false;
}
Player findCopyOrMe(List<Player> copies){
for(Player copy : copies)
if(copy.id == id)
return copy;
return this;
}
public int compareTo(Player other){
if(scoreRounds == other.scoreRounds)
return other.scoreLife - scoreLife;
return other.scoreRounds - scoreRounds;
}
public String toArgument(){
return id + "," + life + "," + power + "," + lastAction;
}
public String toString(){
String out = "" + scoreRounds + "\t" + scoreLife;
while(out.length() < 20)
out += " ";
return out + "(" + id + ")\t" + cmd;
}
}
}
```
### Rules
* You may enter up to **two** bots. If you want to remove one from play to enter a third, please delete its post.
* You may not target or otherwise single out a bot by meta-analysis. Use only the information your bot is given. This includes your own bots, so you may not enter two bots that collude.
* Do not attempt to interfere with the running of the controller or other bots in any way.
* Your bot may not instantiate or otherwise run the controller or other bots.
# Results
(of bots submitted as of of 2015-05-22 00:00:00Z)
This round of play went a bit better, with only two games stalling out at 1000 turns. Kudos to Ralph Marshall's [**Santayana**](https://codegolf.stackexchange.com/a/50237/14215), which took first place, being the only bot that scored three wins. That wasn't enough, so he *also* took third place with **Tactician**. Stormcrow took second with **Phantom Menace**, a fine first post here. All in all we had a very nice showing by new members, with the top six places going to people with less than five posts. Congratulations, and welcome to the site!
Bots that scored zero wins are not listed to save space. All bots posted before the timestamp above were run, so if you don't see yours, it didn't win anything.
```
Wins Life(tiebreaker) Name
3 561 perl Santayana.pl
2 850 java PhantomMenace
2 692 perl Tactician.pl
2 524 java Wiisniper
1 227 java Tank
1 184 java Velociraptor
1 7 java Coward
1 3 java IKnowYou
```
---
Sorta sketchy parallelized controller ([by Others](https://codegolf.stackexchange.com/questions/50172/what-doesnt-kill-me#comment118953_50172)):
```
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
public class Stronger {
static final String[] defaultPlayers = {
"java Hero",
"java Bully",
"java Coward",
"java Psycho",
"./monte.out",
"java Analyst",
"java Guardian",
"java Revenger",
"python precog.py",
//"python snappingTurtle.py",
"python beserker.py",
"./suprise.out",
//"python boxer.py",
"python defense.py",
"java Tank",
"java IKnowYou",
//"java BroBot",
"java Equaliser",
"java Velociraptor",
//"java AboveAverage",
"java PhantomMenace",
"java Wiisniper",
//"python semiRandom.py",
"/usr/bin/perl tactition.pl",
"/usr/bin/perl santayana.pl",
//"java GlitchUser"
"/usr/local/bin/Rscript opportunity.R",
"/usr/local/bin/scala Bandwagoner",
};
final int timeout = 5000;
final int startLife = 1000;
final int startPower = 10;
final int numRounds = 20;
boolean log = true;
List<Player> players;
public static void main(String[] args){
new Stronger().run(args);
}
void run(String[] args){
init(args);
for(int i=1;i<=numRounds;i++){
if(log) System.out.println("Begining round "+ i);
Collections.shuffle(players);
runGame();
}
Collections.sort(players);
for(Player player : players)
System.out.println(player.toString());
}
void runGame(){
log("Player Count: " + players.size());
for(Player player : players)
player.reset();
int turn = 0;
while(turn++ < startLife){
if(aliveCount() < 2)
break;
log("Turn " + turn);
List<Player> clones = new ArrayList<Player>();
for(Player player : players)
clones.add(player.copy());
AtomicInteger count=new AtomicInteger(players.size());
for(Player player : players){
new Thread(() -> {
if(player.life >= 1 && !player.timedOut){
String[] args = new String[players.size()+1];
args[0] = "" + player.id;
for(int i=1;i<args.length;i++)
args[i] = players.get(i-1).toArgument();
String reply = getReply(player, args);
Player clone = player.findCopyOrMe(clones);
if(reply.equals("T")){
clone.timedOut = true;
clone.life = 0;
}
clone.lastAction = reply.trim();
}
synchronized(count){
count.decrementAndGet();
count.notify();
}
}).start();
}
synchronized(count){
while(count.get() > 0){
//System.out.println(count);
try{
count.wait();
}catch(InterruptedException e){
}
}
}
for(Player player : players){
if(player.life < 1 || player.timedOut)
continue;
Player clone = player.findCopyOrMe(clones);
if(clone.lastAction.equals("D")){
clone.power--;
}else{
try{
int target = Integer.parseInt(clone.lastAction);
for(Player t : players)
if(t.id == target && t.life < 1)
throw new Exception();
for(Player tclone : clones){
if(tclone.id == target){
int atk = player.power;
if(tclone.lastAction.equals("D")){
atk -= player.power / 2;
tclone.power++;
}
tclone.life -= atk;
tclone.power++;
}
}
} catch (Exception e){
log(player.cmd + " returned an invalid command: (" + clone.lastAction + ")");
clone.power--;
}
}
}
players = clones;
for(Player player : players){
if(player.power < 1)
player.power = 1;
log(player.life + "\t\t" + player.power + "\t\t" + player.lastAction + "\t\t(" + player.id + ")\t" + player.cmd);
}
log("\n");
}
if(aliveCount() == 1)
for(Player player : players)
if(player.life > 0){
player.scoreRounds++;
player.scoreLife += player.life;
}
}
void log(String msg){if(log)System.out.println(msg);}
String getReply(Player player, String[] args){
try{
List<String> cmd = new ArrayList<String>();
String[] tokens = player.cmd.split(" ");
for(String token : tokens)
cmd.add(token);
for(String arg : args)
cmd.add(arg);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(FileSystems.getDefault().getPath(".", "bin").toFile());
//builder.redirectError(Redirect.PIPE);
long start = System.currentTimeMillis();
Process process = builder.start();
Scanner scanner = new Scanner(process.getInputStream());
process.waitFor();
String reply = scanner.nextLine();
scanner.close();
process.destroy();
if(System.currentTimeMillis() - start > timeout)
return "T";
return reply;
}catch(Exception e){
//e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
void init(String[] args){
players = new ArrayList<Player>();
for(String arg : args){
if(arg.toLowerCase().startsWith("-log")){
log = true;
}else{
Player player = createPlayer(arg);
if(player != null)
players.add(player);
}
}
for(String cmd : defaultPlayers){
Player player = createPlayer(cmd);
if(player != null)
players.add(player);
}
}
Player createPlayer(String cmd){
Player player = new Player(cmd);
String reply = getReply(player, new String[]{});
log(player.cmd + " " + reply);
if(reply != null && reply.equals("ok"))
return player;
return null;
}
int aliveCount(){
int alive = 0;;
for(Player player : players)
if(player.life > 0)
alive++;
return alive;
}
static int nextId = 0;
class Player implements Comparable<Player>{
int id, life, power, scoreRounds, scoreLife;
boolean timedOut;
String cmd, lastAction;
Player(String cmd){
this.cmd = cmd;
id = nextId++;
scoreRounds = 0;
scoreLife = 0;
reset();
}
public Player copy(){
Player copy = new Player(cmd);
copy.id = id;
copy.life = life;
copy.power = power;
copy.scoreRounds = scoreRounds;
copy.scoreLife = scoreLife;
copy.lastAction = lastAction;
return copy;
}
void reset(){
life = startLife;
power = startPower;
lastAction = "X";
timedOut = false;
}
Player findCopyOrMe(List<Player> copies){
for(Player copy : copies)
if(copy.id == id)
return copy;
return this;
}
public int compareTo(Player other){
if(scoreRounds == other.scoreRounds)
return other.scoreLife - scoreLife;
return other.scoreRounds - scoreRounds;
}
public String toArgument(){
return id + "," + life + "," + power + "," + lastAction;
}
public String toString(){
String out = "" + scoreRounds + "\t" + scoreLife;
while(out.length() < 20)
out += " ";
return out + "(" + id + ")\t" + cmd;
}
}
}
```
[Answer]
# C++ - MonteBot
Simulates a large number of random games and chooses the move that leads to the greatest chance of not-dying.
Why think of a strategy when you can let the computer create one for you?
Note: Compile this with the -O3 flag for optimal performance.
```
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
//Monte Carlo method constants
const unsigned int total_iters=100000; //total number of simulations
double time_limit=0.7; //approximate CPU time the program is allowed to run before outputting the current best solution
const unsigned int check_interval=4096-1;
unsigned int num_players,my_bot;
const int DEFEND=-1,FIRST=-2,DEAD=-3;
struct Bot{
short int life,power,lastAttack;
inline bool is_alive(void){
return life>0;
}
inline void damage(short int dmg){
life-=dmg;
if(life<0)life=0;
}
inline void charge(short int p){
power+=p;
if(power<1)power=1;
}
inline bool is_attacking(void){
return lastAttack>=0;
}
};
int main(int argc,char*argv[]){
clock_t start=clock();
if(argc==1){
printf("ok");
return 0;
}
srand(time(NULL));
num_players=argc-2;
sscanf(argv[1],"%u",&my_bot);
Bot bots[num_players];
for(unsigned int i=0;i<num_players;++i){
char buf[16];
unsigned int id;
short int life,power;
sscanf(argv[i+2],"%u,%hd,%hd,%s",&id,&life,&power,buf);
Bot &cur_bot=bots[id];
cur_bot.life=life;
cur_bot.power=power;
if(strcmp(buf,"D")==0)cur_bot.lastAttack=DEFEND;
else if(strcmp(buf,"X")==0)cur_bot.lastAttack=FIRST;
else sscanf(buf,"%hd",&cur_bot.lastAttack);
}
//let the other bots kill each other while we accumulate more power
if(bots[my_bot].life>750){
printf("D");
return 0;
}
Bot cur_state[num_players];
unsigned int won[num_players+1],visited[num_players+1];
for(int i=0;i<num_players+1;++i){
won[i]=0;
visited[i]=0;
}
//unsigned long long int sim_length=0;
for(unsigned int iter=0;iter<total_iters;++iter){
//ensure that we do not exceed the time limit
if(iter&check_interval==check_interval){
clock_t cur_time=clock();
if((double)(cur_time-start)/(double)CLOCKS_PER_SEC>=time_limit){
break;
}
}
int first_move=FIRST;
memcpy(cur_state,bots,sizeof(Bot)*num_players);
//simulate random moves in the game until
//a. the player dies, or
//b. the player is the only one alive
while(true){
//++sim_length;
//check if our bot died
if(!cur_state[my_bot].is_alive()){
++visited[first_move+1];
break;
}
//check if our bot is the only bot left alive
bool others_alive=false;
for(unsigned int i=0;i<num_players;++i){
if(i!=my_bot&&cur_state[i].is_alive()){
others_alive=true;
break;
}
}
if(!others_alive){
++won[first_move+1];
++visited[first_move+1];
break;
}
Bot new_bots[num_players];
memcpy(new_bots,cur_state,sizeof(Bot)*num_players);
//generate random moves for all players
bool defend[num_players];
int possible_moves[num_players+2];
unsigned int num_moves;
for(unsigned int i=0;i<num_players;++i){
num_moves=0;
if(cur_state[i].is_alive()){
possible_moves[num_moves++]=DEFEND;
for(unsigned int j=0;j<num_players;++j){
if(j!=i&&cur_state[j].is_alive()){
possible_moves[num_moves++]=j;
}
}
new_bots[i].lastAttack=possible_moves[rand()%num_moves];
defend[num_players]=(new_bots[i].lastAttack==DEFEND);
}else new_bots[i].lastAttack=DEAD;
}
if(first_move==FIRST)first_move=new_bots[my_bot].lastAttack;
//simulate outcome of moves
for(unsigned int i=0;i<num_players;++i){
if(cur_state[i].is_alive()&&new_bots[i].is_attacking()){
new_bots[i].charge(-1);
int victim=new_bots[i].lastAttack;
if(defend[victim]){ //if victim is defending
new_bots[victim].charge(2);
new_bots[victim].damage(cur_state[i].power/2);
}else{
new_bots[victim].charge(1);
new_bots[victim].damage(cur_state[i].power);
}
}
}
memcpy(cur_state,new_bots,sizeof(Bot)*num_players);
}
}
//printf("%f\n",(double)sim_length/(double)total_iters);
double win_rate=-1;
int best_move=DEFEND;
for(int i=0;i<num_players+1;++i){
if(i-1!=my_bot){
double cur_rate=(double)won[i]/(double)visited[i];
if(cur_rate>win_rate){
win_rate=cur_rate;
best_move=i-1;
}
}
}
if(best_move==DEFEND)printf("D");
else printf("%d",best_move);
//clock_t end=clock();
//fprintf(stderr,"%f\n",(double)(end-start)/(double)CLOCKS_PER_SEC);
return 0;
}
```
## C - MonteFaster
Additionally, this bot can be made to run faster by utilizing multithreading.
However, as I do not preemptively know how many iterations the bot can evaluate before it times out (on the judging platform), I will not be using this bot (with the code below) for this competition.
The code below is merely for curiosity's sake.
Note: Compile this with the -O3 and -fopenmp flags for optimal performance.
```
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_PLAYERS 32
//Monte Carlo method constants
const unsigned int total_iters=60000; //total number of simulations
unsigned int num_players,my_bot;
const int DEFEND=-1,FIRST=-2,DEAD=-3;
struct Bot{
short int life,power,lastAttack;
};
int main(int argc,char*argv[]){
clock_t start=clock();
if(argc==1){
printf("ok");
return 0;
}
srand(time(NULL));
num_players=argc-2;
sscanf(argv[1],"%u",&my_bot);
struct Bot bots[MAX_PLAYERS];
int A;
for(A=0;A<num_players;++A){
char buf[16];
unsigned int id;
short int life,power;
sscanf(argv[A+2],"%u,%hd,%hd,%s",&id,&life,&power,buf);
struct Bot *cur_bot=&bots[id];
cur_bot->life=life;
cur_bot->power=power;
if(strcmp(buf,"D")==0)cur_bot->lastAttack=DEFEND;
else if(strcmp(buf,"X")==0)cur_bot->lastAttack=FIRST;
else sscanf(buf,"%hd",&cur_bot->lastAttack);
}
//let the other bots kill each other while we accumulate more power
if(bots[my_bot].life>750){
printf("D");
return 0;
}
struct Bot cur_state[MAX_PLAYERS];
unsigned int won[MAX_PLAYERS+1],visited[MAX_PLAYERS+1];
for(A=0;A<num_players+1;++A){
won[A]=0;
visited[A]=0;
}
//unsigned long long int sim_length=0;
int iter;
#pragma omp parallel for //strangely, the code fails to compile if a variable length array is used in the loop
for(iter=0;iter<total_iters;++iter){
//note that we cannot break this loop when we use #pragma omp parallel
//there is therefore no way to check if we're close to exceeding the time limit
int first_move=FIRST;
memcpy(cur_state,bots,sizeof(struct Bot)*num_players);
//simulate random moves in the game until
//a. the player dies, or
//b. the player is the only one alive
int sim_length=0;
while(1){
//++sim_length;
//check if our bot died
if(cur_state[my_bot].life<=0){
++visited[first_move+1];
break;
}
//check if our bot is the only bot left alive
int others_alive=0;
int i;
for(i=0;i<num_players;++i){
if(i!=my_bot&&cur_state[i].life>0){
others_alive=1;
break;
}
}
if(!others_alive){
++won[first_move+1];
//won[first_move+1]+=cur_state[my_bot].life;
++visited[first_move+1];
break;
}
struct Bot new_bots[MAX_PLAYERS];
memcpy(new_bots,cur_state,sizeof(struct Bot)*num_players);
//generate random moves for all players
char defend[MAX_PLAYERS];
//int possible_moves[num_players+2];
int possible_moves[MAX_PLAYERS+2];
for(i=0;i<num_players;++i){
if(cur_state[i].life>0){
int j,num_moves=0;
possible_moves[num_moves++]=DEFEND;
for(j=0;j<num_players;++j){
if(j!=i&&cur_state[j].life>0){
possible_moves[num_moves++]=j;
}
}
new_bots[i].lastAttack=possible_moves[rand()%num_moves];
defend[i]=(new_bots[i].lastAttack==DEFEND);
}else new_bots[i].lastAttack=DEAD;
}
if(first_move==FIRST)first_move=new_bots[my_bot].lastAttack;
//simulate outcome of moves
for(i=0;i<num_players;++i){
if(cur_state[i].life>0&&new_bots[i].lastAttack>=0){
new_bots[i].power-=1;
if(new_bots[i].power<=0)new_bots[i].power=1;
int victim=new_bots[i].lastAttack;
if(defend[victim]){ //if victim is defending
new_bots[victim].power+=2;
new_bots[victim].life-=cur_state[i].power/2;
}else{
new_bots[victim].power+=1;
new_bots[victim].life-=cur_state[i].power;
}
if(new_bots[victim].life<0)new_bots[victim].life=0;
}
}
memcpy(cur_state,new_bots,sizeof(struct Bot)*num_players);
}
}
//printf("%f\n",(double)sim_length/(double)total_iters);
double win_rate=-1;
int best_move=DEFEND;
for(A=0;A<num_players+1;++A){
if(A-1!=my_bot){
double cur_rate=(double)won[A]/(double)visited[A];
if(cur_rate>win_rate){
win_rate=cur_rate;
best_move=A-1;
}
}
}
if(best_move==DEFEND)printf("D");
else printf("%d",best_move);
//fprintf(stderr,"%.3f%% chance (based on %d samples)\n",(double)won[best_move+1]/(double)visited[best_move+1]*100.,total_iters);
//clock_t end=clock();
//fprintf(stderr,"%f\n",(double)(end-start)/(double)CLOCKS_PER_SEC);
return 0;
}
```
[Answer]
**Java Psycho**
There's no telling what this crazed psycho will do - may attack anyone: a dead bot, or even himself.
```
import java.util.Random;
public class Psycho {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
Random rnd = new Random();
rnd.setSeed( System.currentTimeMillis() );
String[] tokens = args[ rnd.nextInt(args.length) ].split(",");
String target = tokens[0];
System.out.print(target);
}
}
```
[Answer]
**Scala - Bandwagoner**
The Bandwagoner doesn't care about honor, or principles. Bandwagoner lays low, avoiding being the weakest or the strongest. Bandwagoner goes with the crowd, targeting the consensus target, to avoid drawing attention.
```
import scala.util.Try
object Bandwagoner {
case class PlayerStatus(life:Int, power:Int, lastAction:Option[Int])
def main(args:Array[String]):Unit={
if(args.length==0)
println("ok")
else{
val myId=args(0).toInt
val everyonesStatus=(for(action <- args.tail) yield{
val id :: life :: power :: lastAction :: Nil = action.split(",").toList
(id.toInt, new PlayerStatus(life.toInt, power.toInt, Try(lastAction.toInt).toOption))
}).toMap
println(bandwagon(myId, everyonesStatus(myId), everyonesStatus.filter(_._1 != myId)))
}
}
def bandwagon(myId:Int, self:PlayerStatus, opponents:Map[Int, PlayerStatus]):String={
val alive=opponents.filter(_._2.life > 0)
//If their is only one opponent left
if(alive.size==1){
val (opponentId, opponent)=alive.head
//Get win projection
val willWin=opponent.life/(self.power*1.0) <= self.life/(opponent.power*1.0)
//If I'm stronger attack, otherwise defend
if(willWin) opponentId.toString() else "D"
}
//Otherwise
else if(alive.size > 0){
//If I'm the strongest or weakest
if(alive.map(_._2.life).max < self.life || alive.map(_._2.life).min > self.life){
//If I have a good opportunity in terms or power, or passivity
if(alive.map(_._2.power).max * 1.5 < self.power || !alive.exists(_._2.lastAction.isDefined)){
//Attack
alive.maxBy(_._2.power)._1.toString()
}
//Otherwise
else
//Lay low
"D"
}
//Otherwise, BANDWAGON
else{
//Obviously we dont want to attack dead opponents, or ourself
val validTargets=opponents.flatMap(_._2.lastAction).filter(alive.contains(_)).filter(_ != myId)
if(validTargets.size == 0)
"D"
else
//Select the most targeted opponent (Sorry)
validTargets.groupBy(i => i).mapValues(_.size).maxBy(_._2)._1.toString()
}
}
//Just to be safe..
else
"D"
}
}
```
[Answer]
**Java Revenger**
The Revenger isn't interested in brawling for brawling's sake. But if attacked, revenge *will* be sought!
```
public class Revenger {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], target = "D";
int last_attacker_power = -1;
for(int i=1; i<args.length; ++i){
String[] tokens = args[i].split(",");
int power = Integer.parseInt(tokens[2]);
int life = Integer.parseInt(tokens[1]);
if( tokens[3].equals(me)
&& power>last_attacker_power
&& life>0 ){
target = tokens[0];
last_attacker_power = power;
}
}
System.out.print(target);
}
}
```
[Answer]
# Java - Hero, Bully, and Coward
These three bots are included as examples, but they *will* be playing in the scoring tournament. They all have simplistic behavior.
### Hero
Hero simply attacks whoever has the *most life* on every turn.
```
public class Hero {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], target="D";
int best=0;
for(int i=1;i<args.length;i++){
String[] tokens = args[i].split(",");
int life = Integer.valueOf(tokens[1]);
if(life > 0 && life >= best && !tokens[0].equals(me)){
best = life;
target = tokens[0];
}
}
System.out.print(target);
}
}
```
### Bully
Meanwhile, Bully attacks whoever has the *least life* every turn.
```
public class Bully {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], target="D";
int best=Integer.MAX_VALUE;
for(int i=1;i<args.length;i++){
String[] tokens = args[i].split(",");
int life = Integer.valueOf(tokens[1]);
if(life > 0 && life <= best && !tokens[0].equals(me)){
best = life;
target = tokens[0];
}
}
System.out.print(target);
}
}
```
### Coward
Coward does nothing but defend until his life reaches 500 or lower. He then attacks whoever has the *least power* each turn.
```
public class Coward {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], action="D";
int best=Integer.MAX_VALUE;
for(int i=1;i<args.length;i++){
String[] tokens = args[i].split(",");
if(tokens[0].equals(me)){
if(Integer.valueOf(tokens[1]) > 500){
System.out.print("D");
System.exit(0);
}
}
}
for(int i=1;i<args.length;i++){
String[] tokens = args[i].split(",");
int power = Integer.valueOf(tokens[2]);
if(power <= best && !tokens[0].equals(me) && Integer.valueOf(tokens[1]) > 0){
best = power;
action = tokens[0];
}
}
System.out.print(action);
}
}
```
Enjoy!
[Answer]
# Perl - Tactician
This started off as an edit to my Let 'em Fight bot, but I've made enough changes that I've decided to enter it as a new entry. New logic is as follows
* If nobody attacked in the previous turn, attack the opponent with the
highest life value. This should prevent endings where nobody attacks anybody else, at least as long as I'm still alive.
* If somebody attacked me on the last turn, pick the most powerful such attacker and hit back.
* If we are down to two bots, or I'm at a below-average strength, attack the opponent with the highest life.
* If my own power rating is below average make an attack to increase my power to a more reasonable level
* Otherwise, bide my time
I've tested this locally against the other Java bots that have been entered and managed to get a few wins, but still not a spectacular entry on my part.
```
#!/usr/bin/perl
use strict;
use warnings;
# First round
if (!@ARGV) {
print "ok\n";
exit;
}
my ($self, @rest) = @ARGV;
my ($myAction, $myPower, $myLife,
$myMaxAttacker, $myMaxAttackerId,
$maxLife, $maxLifeId,
$maxPower, $maxPowerId,
$totLife, $totPower, $living, $amWeak, $numAttackers) = ('D');
# First, get a situation report
for (@rest) {
my ($id, $life, $power, $action) = split(',');
# Let the dead rest in peace
next unless $life>0;
if ($id == $self) {
# Keep track of my own power and life for later comparison
$myPower = $power;
$myLife = $life;
next;
}
$living++;
$numAttackers++ if ($action ne 'D');
$totPower += $power;
$totLife += $life;
if ($action == $self) {
# Bastard hit me!
if ($power > $myMaxAttacker) {
$myMaxAttacker = $power;
$myMaxAttackerId = $id;
}
}
# If you're going to pick a fight, go for the biggest
# guy in the room.
if ($life > $maxLife) {
$maxLife = $life;
$maxLifeId = $id;
}
# Or, go for the guy with the biggest gun
if ($power > $maxPower) {
$maxPower = $power;
$maxPowerId = $id;
}
}
# If I'm being hit any attacks are back at the strongest attacker,
# otherwise simply the healthiest opponent overall
my $preferredTarget = $myMaxAttackerId;
$preferredTarget = $maxLifeId unless defined $preferredTarget;
# Check to see if I have below-average life, in which case it's time to get moving
$amWeak = $myLife < $totLife/$living;
# Now figure out what to do
if (!$numAttackers) {
# Everybody is standing around, so let's mix it up
$myAction = $preferredTarget;
} elsif (defined $myMaxAttackerId) {
# My momma told me never to stand there and be hit
$myAction = $myMaxAttackerId;
} elsif ($amWeak || $living == 1) {
# Either we're down to two bots, or I'm fairly weak. Atack!!!
$myAction = $preferredTarget;
} elsif ($myPower < $totPower/$living) {
# Just lash out at random so we do not lose all of
# our power through permanent defense
$myAction = $preferredTarget;
} else {
# Work up some courage/power by drinking beer
# in the corner. Use the default defensive action in this case.
# Else clause exists just for debugging.
}
print "$myAction\n";
```
# Perl - Santayana
Those who do not remember history are doomed to die early, or some such. This bot attempts to take advantage of the multi-round nature of the contest by keeping a history of the total strength of each bot over all rounds and always attacking the strongest one. In theory this should keep any bot from going out to a crushing lead, but of course I'm only collecting stats while I'm alive, so if this bot ends up having a short life the stats are not going to be very good.
```
#!/usr/bin/perl
use strict;
use warnings;
# First round
if (!@ARGV) {
print "ok\n";
exit;
}
# Read in our multi-round/multi-game state information
my $state;
if (open STATE, "state/santayana.out") {
$state = <STATE>;
close STATE;
}
# Stuff the historical data into a hash keyed by opponent ID
my %state;
my @state = $state ? split(' ', $state) : ();
for (@state) {
my ($id, $life, $power) = split ',';
$state{$id} = [$life, $power];
}
my ($self, @rest) = @ARGV;
my ($maxLife, $maxLifeId, $living) = (0, undef, 0);
# First, get a situation report
for (@rest) {
my ($id, $life, $power, $action) = split(',');
# Let the dead rest in peace
next unless $life > 0;
$living++;
# Update the historical hash with latest information
my $aref = $state{$id};
if ($aref) {
$$aref[0] += $life * ($action eq 'D' ? 1 : 1.5);
$$aref[1] += $power;
} else {
$state{$id} = [$life, $power];
}
next if ($id == $self);
# Our target is based on the historically
# strongest opponent, independent of current state,
# unless they are actually dead
if ($life > 0 && $state{$id}->[0] > $maxLife) {
$maxLife = $state{$id}->[0];
$maxLifeId = $id;
}
}
# Write out the latest state for next time around
if (open STATE, ">state/santayana.out") {
print STATE join(" ", map { join ",", $_, $state{$_}->[0], $state{$_}->[1] } sort { $state{$b}->[0] <=> $state{$a}->[0]} keys %state);
close STATE;
}
# Now figure out what to do
if (defined $maxLifeId) {
# Should always be defined, but who knows
print "$maxLifeId\n";
} else {
print "D\n";
}
```
[Answer]
**Java Guardian**
The Guardian protects the weak. He will attack whoever spent their last turn picking on the now-weakest living bot (besides possibly himself). He's smart enough, though, to not attack:
1) Himself (unless he *is* the bully, then he feels that he deserves it.)
2) Bots who attack themselves
3) Dead bots
4) Bots with less than ten life left (who have hopefully learned their lessons!)
The Guardian will pick on the same player repeatedly if needed.
Ties for "weakest player" and "who picked on him" both go to the first one in the list (which is to say, random).
```
public class Guardian{
public static void main (String[] args){
if(args.length == 0){
System.out.print("ok");
System.exit(0);
}
String myId = args[0];
int lowestLife = Integer.MAX_VALUE;
int life = Integer.MIN_VALUE;
String[] tokens = {};
String opposingId = "";
String weakestOpponent = "";
String lastTarget = "";
for(int i=1; i<args.length; i++){
tokens = args[i].split(",");
opposingId = tokens[0];
life = Integer.parseInt(tokens[1]);
lastTarget = tokens[3];
if(life < lowestLife && life > 0 &&
!opposingId.equals(myId) &&
!opposingId.equals(lastTarget)){
weakestOpponent = opposingId;
}
}
for(int i=1; i<args.length; i++){
tokens = args[i].split(",");
opposingId = tokens[0];
life = Integer.parseInt(tokens[1]);
lastTarget = tokens[3];
if (lastTarget.equals(weakestOpponent) &&
life > 10){
System.out.println(opposingId);
System.exit(0);
}
}
System.out.println("D");
}
}
```
[Answer]
# Java - Analyst
Determines each opponent's threat by multiplying its power by 5 if it attacked and by 25 if it attacked the Analyst. In case of a tie, it attacks the player with least life.
Much of the code was borrowed from Geobits' answer.
```
public class Analyst {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("ok");
System.exit(0);
}
String me = args[0], that = "D";
int maxThreat = 200;
for (int i = 1; i < args.length; i++) {
String[] player = args[i].split(",");
int threat = Integer.parseInt(player[2]) * 100
* (!player[3].equals("D") ? 5 : 1)
* (player[3].equals(me) ? 5 : 1)
- Integer.parseInt(player[1]);
if (threat > maxThreat && Integer.parseInt(player[1]) > 0 && !player[0].equals(me)) {
maxThreat = threat;
that = player[0];
}
}
System.out.println(that);
}
}
```
[Answer]
# R - Opportunity
This bot needs to be called using `Rscript Opportunity.R`. It keeps in memory who did what and it attacks the opponent the less likely to defend itself (i. e. who used `D` the least in the past) unless he realizes that one of the bot has been attacking him twice in a row in which case it starts defending itself or attacks the attacking bot if it can kill it faster than the attacker can.
```
args <- commandArgs(TRUE)
if(length(args)){
myid <- as.integer(args[1])
data <- as.data.frame(do.call(rbind,strsplit(args[-1],",")),stringsAsFactors=FALSE)
colnames(data) <- c('id','health','power','last')
data$id <- as.integer(data$id)
data$health <- as.integer(data$health)
data$power <- as.integer(data$power)
data <- data[order(data$id),]
if(all(data$last=="X")){
cat(data$last,file="state/opportunity.txt",sep="\n")
cat(sample(data$id[data$id!=myid],1))
}else{
past <- as.matrix(read.table("state/opportunity.txt",sep=" "))
lastturn <- data$last
lastturn[data$health<1] <- "X"
lastturn[nchar(lastturn)>1] <- "E" #If a bot returned anything else than an integer
past <- cbind(past,lastturn)
cat(apply(past,1,paste,collapse=" "),sep="\n",file="state/opportunity.txt")
who_bully_me <- sapply(apply(past,1,rle),function(x)ifelse(tail(x$v,1)==myid,tail(x$l,1),0))
if(any(who_bully_me>1)){
bullyid <- which.max(who_bully_me)-1
if(data$health[data$id==bullyid]%/%data$power[data$id==myid]<=data$health[data$id==myid]%/%data$power[data$id==bullyid]){
cat(bullyid)
}else{cat("D")}
}else{
defend <- rowSums(past=="D")
defend[past[,ncol(past)]=="X"] <- NA
defend[myid+1] <- NA
choice <- which(defend%in%min(defend,na.rm=TRUE)) -1
if(length(choice)>1) choice <- sample(choice,1)
cat(choice)
}
}
}else{
cat("ok")
}
```
[Answer]
# Python 2, Snapping Turtle
Hides in its shell, emerges to bite the first person to attack it last turn (unless they're dead), then goes back into its shell again
Run with `python snapping_turtle.py <input>`
```
import sys
class snapping_turtle:
def bitey(self,command):
if len(command) <=1:
return 'ok'
else:
last_turn = list(command)
bot_to_bite = -1
me = last_turn[0]
for k in xrange(0,len(last_turn)):
#bot_action = last_turn.split(',')
if len(last_turn[k]) ==1:
pass
else:
bot_action = last_turn[k].split(',')
# If they hit me
if bot_action[3] == me:
# And if they're still alive, hit them
if int(bot_action[1]) > 0:
bot_to_bite = bot_action[0]
break
#Otherwise, stay in my shell
else:
pass
if bot_to_bite > -1:
return bot_to_bite
else:
return 'D'
print snapping_turtle().bitey(sys.argv[1:])
```
# Python 2, Berserker
Berserker smash! Hits itself until it has enough power, then starts attacking the closest living thing. Also hits itself if it can't work out who it should be hitting, for whatever reason.
EDIT: Changed Berserker's rage threshold from 50 to 25, since otherwise it would take itself out before doing anything...
Runs with `python Berserker.py <input>`
```
import sys
class Berserker:
def rage(self,command):
if len(command) <=1:
return 'ok'
else:
last_turn = list(command)
bot_to_smash = -1
me = last_turn[0]
my_power = last_turn[int(me)].split(',')[2]
for k in xrange(0,len(last_turn)):
#bot_action = last_turn.split(',')
if len(last_turn[k]) ==1:
pass
else:
bot_action = last_turn[k].split(',')
if int(my_power) < 25:
#Too weak! Need make stronger for smashing!
bot_to_smash = me
break
else:
#Now strong! Smash! Not smash broken things!
if bot_action[0] != me and bot_action[1] > 0:
bot_to_smash = bot_action[0]
if bot_to_smash > -1:
return bot_to_smash
else:
#Confused! Don't like! MORE POWER!
return me
print Berserker().rage(sys.argv[1:])
```
[Answer]
# Python 2 - The Boxer
The Boxer bot will mainly keep its guard up, ducking and weaving. Every now and then it will send a quick jab or cross to a strong opponent that is not defending well, hoping to wear them down over time.
```
import sys, re, random
if sys.argv[1:]:
rows = [map(int, re.sub('[DX]', '-1', b).split(',')) for b in sys.argv[2:]]
bots = dict((r.pop(0),r) for r in rows if r[1]>0 and r[0]!=int(sys.argv[1]))
target = max(bots, key=lambda b: bots[b][0]-300*(bots[b][2]==-1))
print target if random.randint(1,100) > 70 else 'D'
else:
print 'ok'
```
UPDATE: Fixed a bug that caused some invalid outputs.
[Answer]
# C - SurpriseBot
Assumes the first turn is going to be a mess and defends. After that, attack someone who didn't defend last turn--they'll never see it coming!
This answer is a tad silly, but I wanted to write a rather general platform for building an answer in C, so here you go.
```
//What doesn't kill me...
//SurpriseBot
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int myself;
typedef struct s_Bot {
int id;
int life;
int power;
/* -1 is defending */
int lastAction;
} Bot;
int compare_bots(const void* a, const void* b) {
Bot one = *(Bot*)a;
Bot two = *(Bot*)b;
/* Never, ever target myself */
if (one.id == myself) {
return 1;
}
else if (two.id == myself) {
return -1;
}
/* Also, don't target any bot that is dead */
if (one.life < 1) {
return 1;
}
else if (two.life < 1) {
return -1;
}
/* Prefer those who did not defend last turn */
/* They'll never see it coming! */
if (one.lastAction >= 0 && two.lastAction < 0) {
return -1;
}
else if (one.lastAction < 0 && two.lastAction >= 0) {
return 1;
}
/* Try to target the lowest health */
if (one.life < two.life) {
return -1;
}
else if (one.life > two.life) {
return 1;
}
/* Try to target the more powerful bot */
if (one.power < two.power) {
return 1;
}
else if (one.power > two.power) {
return -1;
}
else return 0;
}
int main(int argc, char** argv) {
if (argc == 1) {
printf("ok");
}
else {
int quit = 0;
myself = atoi(argv[1]);
/* Populate a list of all bots */
int num = argc - 2;
Bot bots[num];
int i;
for (i = 0; i < num; i++) {
char buf[100];
sscanf(argv[2 + i], "%d,%d,%d,%s", &bots[i].id, &bots[i].life, &bots[i].power, buf);
switch (buf[0]) {
case 'X':
/* Assume the first turn is a bloodbath and we don't want any part of it */
printf("D");
quit = 1;
break;
case 'D':
bots[i].lastAction = -1;
break;
default:
sscanf(buf, "%d", &bots[i].lastAction);
break;
}
if (quit) {
goto done;
}
}
qsort(bots, num, sizeof(Bot), compare_bots);
printf("%d", bots[0].id);
}
done:
return 0;
}
```
[Answer]
# Python 2 - Precog
Precog tries to predict everyone else's moves based on past action frequency, then tries a few simulations and picks one that maximizes its score. It's not particularly reliable, but then... ESP isn't real. :D
```
import json, sys
from random import choice
#'S'/'W' = attack high/low power (strong/weak)
#'H'/'F' = attack high/low health (hale/frail)
#'A' = attack defender (armor)
#'R' = attack random (it doesn't know)
#'D' = defend
amin = lambda x: x.index(min(x))
amax = lambda x: x.index(max(x))
def pick(history, ids, action):
if action == 'D':
return 'D'
if action == 'R' or len(history['all'][-1][action]) < 1:
return choice(ids)
return choice(history['all'][-1][action])
args = sys.argv
if len(args) == 1:
print 'ok'
sys.exit()
me = args[1]
def notme(l):
tmp = list(l)
try:
tmp.remove(me)
except ValueError:
pass
return tuple(tmp)
args = args[2:]
try:
with open('precog.state') as f:
history = json.load(f)
except (IOError, ValueError):
history = {}
if len(history) == 0:
history = {'all':[]}
args = [a.split(',') for a in args]
ids,hps,pows,acts = zip(*args)
hps,pows = map(int,hps), map(int,pows)
for i,h,p,a in args:
if a == 'X': #most people will try not to attack armored
history[i] = {'a':'SWHFRD','health':[],'power':[],'score':[]}
elif acts == 'D':
history[i]['a'] += 'D'
else:
for x in 'SWHFA':
if a in history['all'][-1][x]:
history[i]['a'] += x
break
else:
history[i]['a'] += 'R'
history[i]['health'] += int(h),
history[i]['power'] += int(p),
history[i]['score'] += int(h)*int(p),
history['all'] += {'S':[ids[amax(pows)]],
'W':[ids[amin(pows)]],
'H':[ids[amax(hps)]],
'F':[ids[amin(hps)]],
'A':[ids[i] for i in filter(lambda x:acts[x]=='D',range(len(acts)))]},
with open('precog.state','w') as f:
json.dump(history,f)
scores = dict(zip('SWHFRAD',[0]*7))
for _ in range(50):
for act in 'SWHFRAD':
_score = {}
p,h,a = dict(zip(ids,pows)),dict(zip(ids,hps)),{i:0 for i in ids}
opp = {i:choice(history[i]['a']) for i in ids if i != me}
opp[me] = act
m = {o:[1,2][opp[o]=='D'] for o in opp}
for o in opp:
if opp[o] != 'D':
if o == me:
target = pick(history, notme(ids), opp[o])
else:
target = pick(history, ids, opp[o])
h[target] -= p[o]/m[target]
a[target] += 1
for o in opp:
p[o] += m[o] * a[o]
_score[o] = p[o] * h[o]
scores[act] += _score.pop(me) - sum(_score.values())
target = pick(history, notme(ids), scores.keys()[amax(scores.values())])
if target == me:
target = choice(notme(ids))
print target
```
[Answer]
# Java - Phantom Menace
Hi! This is my first post here at the Code Golf. I am a C# guy so pardon my french please. I have used parts of the Hero and Coward sample codes.
My bot is a simple guy with quite a political attitude. Most of the time he just hides himself in the lobby drinking coffee and preparing his schemes. But when the chance arises and the prospect of profit is strong enough he jumps up from his comfortable lobby armchair, throws away the newspaper and goes for the money.
He just defends himself after any harm is done to him. Otherwise he behaves like a true Hero (That is also a political decision as it is quite safe). When he has only three competitors he goes for the win.
He follows a few basic principles. Every serious politician should have some unbreakable principles and a clearly defined profile...
*Do not help anyone but yourself!* (Egoist)
*Glory means death!* (Sceptic)
*There is nothing after you die!* (Atheist)
```
public class PhantomMenace {
public static void main(String[] args) {
if(args.length < 1)
{
System.out.print("ok");
System.exit(0);
}
String me = args[0], target="D", secondTarget="D", worstTarget="D";
int best=0;
int attackerCount = 0;
int numBots= 0;
int secondBest=0;
int worst=0;
for(int i=1;i<args.length;i++)
{
String[] tokens = args[i].split(",");
int life = Integer.valueOf(tokens[1]);
if(life > 0 && life >= best)
{
secondBest = best;
secondTarget = target;
best = life;
target = tokens[0];
}
else if(life > 0 && life >= secondBest)
{
secondBest= life;
secondTarget = tokens[0];
}
if(life > 0 && life <= best)
{
worst = life;
worstTarget = tokens[0];
}
// count incoming attacks
if(tokens[3].equals(me))
attackerCount++;
// count living bots
if(life>0)
numBots++;
}
// activate offensive regime?!
if(numBots<5)
{
if(target.equals(me))
System.out.print(secondTarget);
else
System.out.print(target);
}
else
{
if(worstTarget.equals(me))
System.out.print("D");
if(target.equals(me))
System.out.print("D");
else if(attackerCount>0)
System.out.print("D");
else
System.out.print(target);
}
}
}
```
[Answer]
## bash - CopyCat
The CopyCat admires the strong, healthy and aggressive ones and attacks the same as they did. When if she has the "impression", that the majority of the bots are attacking here, she starts defending herself or attacking the weak ones unless she gets stronger or the most other bots stop attacking here.
Simply execute it with `/bin/bash copycat.sh`
```
#!/bin/bash
if [[ "$1" == "" ]]; then echo "ok"; exit; fi
debug() {
#echo "$(date): $*" >> copycat.log
return;
}
me=$1; shift
meAsTarget=0
myAction="D" #better than an invalid command
topBot=-1
topBotAwe=0
worstBot=-1
worstBotAwe=100
aliveBots=0
myMostWeakAttacker=-1
mmwaAwe=0
if [[ -e "./state/copycat.state" ]]; then
. ./state/copycat.state
fi
for rawBot
do
if [[ "$rawBot" == "" ]]; then continue; fi
if [[ $(echo $rawBot | grep -Fo ',' | wc -l) -ne 3 ]]; then continue; fi
bot=(${rawBot//,/ })
id=${bot[0]}; life=${bot[1]}; power=${bot[2]}; lastAction=${bot[3]}
printf "%d\n" "$lastAction" > /dev/null 2>&1
if [[ "$?" -ne 0 && "$lastAction" != "D" ]]; then continue; fi
if [[ "$life" -le 0 ]]; then continue; fi
((aliveBots++))
awesomeness=$(( 2 * (((life/10) * power) / (life/10 + power)) ))
if [[ "$id" -eq "$me" ]]; then
myLastAction="$lastAction"
myAwe="$awesomeness"
else
lastBot=$id
fi
if [[ "$awesomeness" -gt "$topBotAwe"
&& "$lastAction" != "D"
&& "$lastAction" != "$me" ]]; then
topBot=$id
topBotAwe=$awesomeness
topBotTarget=$lastAction
fi
if [[ "$awesomeness" -lt "$worstBotAwe" ]]; then
worstBot=$id
worstBotAwe=$awesomeness
fi
if [[ "$lastAction" -eq "$me" ]]; then
((meAsTarget++))
if [[ "$awesomeness" -lt "$mmwaAwe" ]]; then
myMostWeakAttacker=$id
mmwaAwe=$awesomeness
fi
fi
done
backupStrategy() {
if [[ "$myMostWeakAttacker" != "-1" && "$mmwaAwe" -lt "$myAwe" ]]; then
debug "attacking my most weak attacker ($myMostWeakAttacker) who is weaker then me"
myAction=$myMostWeakAttacker
elif [[ "$worstBot" != "-1" && "$worstBot" != "$me" ]]; then
debug "attacking the worst bot $worstBot"
myAction=$worstBot
elif [[ "$myMostWeakAttacker" != "-1" ]]; then
debug "attacking my most weak attacker $myMostWeakAttacker"
myAction=$myMostWeakAttacker
else
debug "no one is attacking me anymore; attacking the last ones"
myAction=$lastBot
fi
}
if [[ "$meAsTarget" -gt "$((aliveBots/2))" ]]; then
#hit-and-run
if [[ "$myLastAction" == "D" && "$myAwe" -gt "$worstBotAwe" ]]; then
debug "I am still under fire, but not the worst one.."
backupStrategy
else
debug "I was attacked to much; defending now (attack level: $meAsTarget)"
myAction="D"
meAsTarget=$((meAsTarget-aliveBots/2))
fi
elif [[ "$topBotTarget" != "" ]]; then
myAction=$topBotTarget
for rawBot
do
if [[ "$rawBot" == "" ]]; then break; fi
bot=(${rawBot//,/ })
if [[ "${bot[0]}" -eq "$topBotTarget" ]]; then
if [[ "${bot[1]}" -le 0 ]]; then
backupStrategy
else
debug "copying strategy from bot $topBot attacking $myAction"
fi
break
fi
done
else
backupStrategy
fi
if ! [[ -d "./state" ]]; then mkdir -p "./state"; fi
cat <<EOF_STATE > "./state/copycat.state"
topBotTarget="$topBotTarget"
meAsTarget="$meAsTarget"
EOF_STATE
echo "$myAction"
exit 0
```
Her weakness: she might never get better as the ones she looks up to. :()
[Answer]
**Python 3 DefensiveBot**
Bot tries to find the enemy with the highest power it can kill with its current power. Otherwise, defend. Run with `python DefensiveBot.py id bot1 etc`
```
import sys
def resolve(bots, power, life):
highPowerCanKill = -1
highPower = 0
for i in bots:
if int(i[1]) < int(power):
if(int(i[2]) > int(highPower)) and (int(i[1]) > 0):
highPower = i[2]
highPowerCanKill = i[0]
if highPowerCanKill != -1:
return highPowerCanKill
else:
return "D"
args = sys.argv
if len(args) == 1:
print("ok")
sys.exit()
fileName = str(__file__).split('\\')
fileName = fileName[len(fileName)-1]
myId = args[1]
bots = []
for i in args:
i = i.split(',')
if len(i) == 1:
continue
if i[0] == myId:
power = i[2]
life = i[1]
continue
elif i[0] == fileName:
continue
bots.append(i)
kill = resolve(bots, power, life)
print(kill)
```
[Answer]
# I Know You - Java
Analyzes all enemies and uses this information to defend itself better. Unfortunately, it is prone to revenge attacks.
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class IKnowYou {
final static int LINES = 40;
Bot me;
final List<Bot> bots = new ArrayList<>();
final List<Bot> livingEnemies = new ArrayList<>();
final File file = new File("state/IKnowYou");
final long lineCount;
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
new IKnowYou(args).run();
}
public IKnowYou(String[] args) {
for (int i = 1; i < args.length; i++) {
Bot bot = new Bot(args[i], args[0]);
bots.add(bot);
if (bot.isMe) {
me = bot;
} else if (bot.life > 0) {
livingEnemies.add(bot);
}
}
lineCount = lineCount();
}
void run() {
if (me.lastAction.equals("X")) {
createFile();
updateFile();
System.out.println(livingEnemies.get(0).id);
System.exit(0);
}
if (lineCount % LINES != 0) {
updateFile();
}
if (underAttack()) {
System.out.println("D");
} else {
for (Bot bot : livingEnemies) {
if (bot.lastAction.equals(me.id)){
System.out.println(bot.id);
return;
}
}
int maxP = 0;
Bot maxPowerBot = null;
for (Bot bot : livingEnemies) {
if (bot.power > maxP){
maxP = bot.power;
maxPowerBot = bot;
}
}
System.out.println(maxPowerBot.id);
}
}
void createFile() {
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {}
}
}
void updateFile() {
List<Bot> oldBots = new ArrayList<>();
if (me.lastAction.equals("X")) {
for (Bot bot : bots) {
Bot copyBot = bot.copy();
bot.life = 1000;
bot.power = 10;
oldBots.add(copyBot);
}
} else {
String oldState = "";
try (BufferedReader input = new BufferedReader(new FileReader(file))) {
String line;
while ((line = input.readLine()) != null && !line.equals("\n")) {
oldState = line;
}
} catch (Exception e) {}
String[] parts = oldState.split(" ");
for (int i = 0; i < parts.length; i++) {
oldBots.add(new Bot(parts[i]));
}
}
List<List<String>> ids = new ArrayList<>();
for (int i = 0; i < 3; i++) {
ids.add(new ArrayList<String>());
}
int maxL = -1, minL = 1001, maxP = 0;
for (Bot bot : oldBots) {
if (bot.life > maxL) {
ids.get(0).clear();
maxL = bot.life;
ids.get(0).add(bot.id);
} else if (bot.life == maxL) {
ids.get(0).add(bot.id);
}
if (bot.life < minL) {
ids.get(1).clear();
minL = bot.life;
ids.get(1).add(bot.id);
} else if (bot.life == minL) {
ids.get(1).add(bot.id);
}
if (bot.power > maxP) {
ids.get(2).clear();
maxP = bot.power;
ids.get(2).add(bot.id);
} else if (bot.power == maxP) {
ids.get(2).add(bot.id);
}
}
StringBuilder[] output = new StringBuilder[3];
for (int i = 0; i < 3; i++) {
output[i] = new StringBuilder();
}
output[0].append("maxL");
output[1].append("minL");
output[2].append("maxP");
for (Bot bot : bots) {
if (bot.isMe)
continue;
for (int i = 0; i < 3; i++) {
if (ids.get(i).contains(bot.lastAction)) {
output[i].append(' ').append(bot.id);
}
}
}
try(FileWriter wr = new FileWriter(file, true)) {
for (int i = 0; i < 3; i++) {
output[i].append('\n');
wr.append(output[i].toString());
}
StringBuilder sb = new StringBuilder();
for (Bot bot : bots) {
sb.append(bot.id).append(',').append(bot.life).append(',').append(bot.power).append(' ');
}
wr.append(sb.toString().trim() + "\n");
} catch (IOException e) {}
}
boolean underAttack() {
Bot attacker = null;
for (Bot bot : bots) {
if (bot.lastAction.equals(me.id)) {
if (attacker != null) {
return true;
} else {
attacker = bot;
}
}
}
int maxL = 0, minL = 1001, maxP = 0;
for (Bot bot : bots) {
if (bot.life > maxL)
maxL = bot.life;
if (bot.life < minL)
minL = bot.life;
if (bot.power > maxP)
maxP = bot.power;
}
if ((me.life < maxL && me.life > minL && me.power < maxP) || livingEnemies.size() == 1) {
return false;
}
List<Map<String, Integer>> stats = new ArrayList<>();
for (int i = 0; i < 3; i++) {
stats.add(new HashMap<String, Integer>());
}
for (Bot bot : bots) {
for (int i = 0; i < 3; i++) {
stats.get(i).put(bot.id, 0);
}
}
try (BufferedReader input = new BufferedReader(new FileReader(file))) {
String line;
while ((line = input.readLine()) != null) {
if (line.startsWith("m")) {
int map = line.startsWith("maxL") ? 0 : line.startsWith("minL") ? 1 : 2;
String[] parts = line.split(" ");
for (int i = 1; i < parts.length; i++) {
int count = stats.get(map).get(parts[i]);
stats.get(map).put(parts[i], count+1);
}
}
}
} catch (Exception e) {}
for (int i = 0; i < 3; i++) {
if ((me.life == maxL && i == 0) || (me.life == minL && i == 1) || (me.power == maxP && i == 2)) {
for (String id : stats.get(i).keySet()) {
int count = stats.get(i).get(id);
if (count / ((float)lineCount / 4) > 0.65) {
for (Bot bot : bots) {
if (bot.id.equals(id)) {
if (bot.life > 0) {
return true;
} else {
break;
}
}
}
}
}
}
}
return false;
}
long lineCount() {
try (LineNumberReader lnr = new LineNumberReader(new FileReader(file))) {
lnr.skip(Long.MAX_VALUE);
return lnr.getLineNumber();
} catch (IOException e) {
return 0;
}
}
class Bot {
String id, lastAction;
int life, power;
boolean isMe;
public Bot() {}
public Bot(String bot, String myId) {
String[] parts = bot.split(",");
id = parts[0];
life = Integer.valueOf(parts[1]);
power = Integer.valueOf(parts[2]);
lastAction = parts[3];
isMe = id.equals(myId);
}
public Bot(String oldBot) {
String[] parts = oldBot.split(",");
id = parts[0];
life = Integer.valueOf(parts[1]);
power = Integer.valueOf(parts[2]);
}
Bot copy() {
Bot bot = new Bot();
bot.id = id;
bot.lastAction = lastAction;
bot.life = life;
bot.power = power;
bot.isMe = isMe;
return bot;
}
}
}
```
[Answer]
**Java Tank**
The Tank doesn't think, he doesn't care, he just attacks the first bot he sees! He is smart enough to not attack himself or dead ones, though.
```
public class Tank{
public static void main (String[] args){
if(args.length == 0){
System.out.print("ok");
System.exit(0);
}
String myId = args[0];
int life = Integer.MIN_VALUE;
String[] tokens = {};
String opposingId = "";
for(int i=1; i<args.length; i++){
tokens = args[i].split(",");
opposingId = tokens[0];
life = Integer.parseInt(tokens[1]);
if(life > 0 && !opposingId.equals(myId)){
System.out.println(opposingId);
System.exit(0);
}
}
System.out.println("D");
}
}
```
[Answer]
# Java - Velociraptor
The Velociraptor is a vicious killer. She will lie in wait until attacked, observing potential prey. She then goes in for the quick kill, taking down the target she can kill the fastest. After beginning her assault, the raptor knows no fear and will continue taking victims until she is the only survivor.
```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Velociraptor {
public static void main(String[] args) {
if (args.length < 1) {
System.out.print("ok");
System.exit(0);
}
Velociraptor raptor = new Velociraptor(args);
System.out.print(raptor.determineVictim());
}
private final String observationsFilePath = "state/velociraptor.txt";
private final File observationsFile = new File(observationsFilePath);
private int id, life, power, round;
private List<Bot> preyList;
private Map<Integer, Integer> preyDefendCounts;
public Velociraptor(String[] preyStates) {
loadObservations();
observePrey(preyStates);
saveObservations();
}
private void observePrey(String[] preyStates) {
this.id = Integer.valueOf(preyStates[0]);
preyList = new ArrayList<>();
for (int i = 1; i < preyStates.length; i++) {
String[] tokens = preyStates[i].split(",");
int preyId = Integer.valueOf(tokens[0]);
int preyLife = Integer.valueOf(tokens[1]);
int preyPower = Integer.valueOf(tokens[2]);
String lastAction = tokens[3];
if (preyId == this.id) {
this.life = preyLife;
this.power = preyPower;
} else if (preyLife > 0) {
Bot prey = new Bot();
prey.id = preyId;
prey.life = preyLife;
prey.power = preyPower;
prey.lastAction = lastAction;
preyList.add(prey);
//Clever girl!
if (prey.lastAction.equals("D")) {
int preyDefendCount = preyDefendCounts.getOrDefault(prey.id, 0);
preyDefendCount++;
preyDefendCounts.put(prey.id, preyDefendCount);
}
}
}
}
public String determineVictim() {
if (this.life == 1000) { //lay in wait until attacked
return "D";
}
double fastestKill = 1000; //max game rounds
Bot victim = null;
for (Bot prey : preyList) {
int preyDefendCount = preyDefendCounts.getOrDefault(prey.id, 0);
double effectiveMultiplier = 1 - (.5 * preyDefendCount / round);
double turnsToKill = prey.life / (this.power * effectiveMultiplier);
//target whoever can be killed fastest
//in case of tie, kill the prey with more power first
if (turnsToKill < fastestKill || (victim != null && turnsToKill == fastestKill && prey.power > victim.power)) {
fastestKill = turnsToKill;
victim = prey;
}
}
return String.valueOf(victim.id);
}
private void loadObservations() {
preyDefendCounts = new HashMap<>();
if (observationsFile.exists()) {
try (Scanner scanner = new Scanner(observationsFile)) {
round = Integer.valueOf(scanner.nextLine());
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] tokens = line.split(",");
int preyId = Integer.valueOf(tokens[0]);
int preyDefendCount = Integer.valueOf(tokens[1]);
preyDefendCounts.put(preyId, preyDefendCount);
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
round++;
}
private void saveObservations() {
if (!observationsFile.exists()) {
try {
observationsFile.createNewFile();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
try (PrintWriter writer = new PrintWriter(observationsFile)) {
writer.println(round);
if (preyDefendCounts != null) {
preyDefendCounts.entrySet().stream().forEach(entry -> writer.println(entry.getKey() + "," + entry.getValue()));
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
private class Bot {
public int id, life, power;
public String lastAction;
}
}
```
[Answer]
# Python 3 - SemiRandom
Chooses between attack and defend based on randomness weighted by previous strongness-changes after attacks and defends. If attack is choosen it attacks the strongest player. Strongness is defined as `life * power`.
Against the 3 example bots it rarely wins. Maybe in the wild...
```
import sys, random
def get_goodness(r,d):
if len(d)==0:
return 0
return sum(v/(r-k+5) for k,v in d.items())/sum(1/(r-k+5) for k,v in d.items())
def get_att_chance(r,ad,dd,b):
ag=get_goodness(r,ad)+500+p/2/len(b)
dg=get_goodness(r,dd)+500
return ag/(ag+dg)
args=sys.argv
if len(args)==1:
print("ok")
with open('state/semirandom.txt','w') as f:
f.write('-1\n1000\n10\n{}\n{}\n"S"\n')
sys.exit()
me=int(args[1])
b=[]
for ae in args[2:]:
if ae[-1] in 'DX':
ae=ae[:-1]+'-1'
ae=ae.split(',')
if int(ae[0])!=me:
b+=[[int(ae[i]) for i in range(4)]]
else:
l,p=int(ae[1]),int(ae[2])
with open('state/semirandom.txt','r') as f:
data=f.read()
co,lo,po,ad,dd,h=map(eval,data.split('\n')[:-1])
r=len(ad)+len(dd)
vc=l*p-lo*po
if co==0:
ad[r]=vc
if co==1:
dd[r]=vc
ll=sum([be[1] for be in b])
em=ll/p/len(b)/(1000-r)*2
target_id=max(b,key=lambda be:be[1]*be[2])[0]
if random.random()<em:
action=0
else:
if random.random()<get_att_chance(r,ad,dd,b):
action=0
else:
action=1
if action==0:
act=str(target_id)
else:
act='D'
with open('state/semirandom.txt','w') as f:
f.write('{}\n{}\n{}\n{}\n{}\n"{}"\n'.format(action,l,p,ad,dd,h+act))
print(act)
```
[Answer]
# Java- The Roman Tortoise
The Roman Tortoise will attack anyone who comes near him, but will also randomly decide to attack other bots because it's not a coward. It occasionally (1 in 50) shows forgiveness.
```
import java.util.NoSuchElementException;
import java.util.Random;
public class RomanTortoise {
public static void main(String[] args) {
Random r = new Random();
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
try{
String me = args[0];
try{
if(args[1].split(",")[3].equals("X"))
{
System.out.print("D");
System.exit(0);
}
}
catch(NoSuchElementException nse)
{
}
for(int i = 1; i<args.length; i++)
{
try{
String[] tokens = args[i].split(",");
if(tokens.length>3)
{
String lastAction = tokens[3];
if(lastAction.equals(me) && (Integer.parseInt(tokens[1])>0))
{
//probably attack that bot
if(r.nextInt()%50 != 0)
{
System.out.print(tokens[0]);
System.exit(0);
}
}
}
}
catch(NoSuchElementException nse)
{
}
}
if(r.nextInt()%2 == 0)
{
for(int i = 0; i<100; i++)
{
try{
int j = (r.nextInt() % (args.length-1)) + 1;
String[] tokens = args[j].split(",");
if(tokens.length>3)
{
if(Integer.valueOf(tokens[1])>0)
{
System.out.print(tokens[0]);
System.exit(0);
}
}
}
catch(NoSuchElementException nse)
{
}
}
}
}
catch(Exception e){}
System.out.print("D");
System.exit(0);
}
}
```
[Answer]
# Java - BroBot
BroBot will attack the most powerful opponent unless an enemy with an attack greater than some progressively smaller value decides to attack BroBot, in which case he will defend that turn.
```
public class BroBot {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("ok");
return;
}
int health = 0, id = Integer.parseInt(args[0]);
for (int k = 1; k < args.length; k++) {
if (Integer.parseInt(args[k].split(",")[0]) == id) {
health = Integer.parseInt(args[k].split(",")[1]);
break;
}
}
String action = "";
for (String s : args) {
if (!s.contains(",")) continue;
String[] botInfo = s.split(",");
int botId = Integer.parseInt(botInfo[0]);
if (botId == id) continue;
if (!botInfo[3].equals("D")) {
try {
if (Integer.parseInt(botInfo[3]) == id && Integer.parseInt(botInfo[2]) >= health / 4) {
action = "D";
break;
}
} catch (NumberFormatException ex) {
continue;
}
}
}
if (action.isEmpty()) {
int max = 0;
for (String s : args) {
if (!s.contains(",")) continue;
String[] botInfo = s.split(",");
if (Integer.parseInt(botInfo[0]) == id ||
Integer.parseInt(botInfo[1]) <= 0) continue;
int attack = Integer.parseInt(botInfo[2]);
if (attack > max) {
attack = max;
action = botInfo[0];
}
}
}
System.out.println(action);
}
}
```
# Java - SisBot
What's a brother without a sister? Many things... but that's beside the point. Being the smarter bot, SisBot saves the last actions of each bot, analyzes their current and last actions and makes her move - she'll attack the bot with the highest power without a second thought provided that her health and power are high enough and that no other bot with a power stat above a certain value decides to attack her; in that case she'll switch between attacking and defending, or just straight defending if the attacker's power is really high.
```
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class SisBot {
private static final Path directoryPath = Paths.get("state");
private static final Path filePath = Paths.get("state" + java.io.File.separator + "SisBot.txt");
private List<Bot> botList;
private List<String> fileContents;
private int id, health, power, turn;
public SisBot(String[] args) throws IOException {
if (args.length == 0) {
createSaveFile();
System.out.println("ok");
System.exit(0);
}
fileContents = Files.readAllLines(filePath, Charset.defaultCharset());
for (int k = 1; k < args.length; k++) {
if (args[k].split(",")[3].equals("X")) {
Files.write(filePath, "".getBytes());
fileContents.clear();
break;
}
}
getBots(args);
makeMove();
writeBots();
}
private void createSaveFile() throws IOException {
if (!Files.exists(filePath)) {
if (!Files.exists(directoryPath))
Files.createDirectory(directoryPath);
Files.createFile(filePath);
}
else
Files.write(filePath, "".getBytes());
}
private void getBots(String[] args) {
id = Integer.parseInt(args[0]);
botList = new ArrayList<Bot>();
for (int k = 1; k < args.length; k++) {
String[] botInfo = args[k].split(",");
if (Integer.parseInt(botInfo[0]) != id && Integer.parseInt(botInfo[1]) > 0)
botList.add(new Bot(args[k]));
else if (Integer.parseInt(botInfo[0]) == id) {
health = Integer.parseInt(botInfo[1]);
power = Integer.parseInt(botInfo[2]);
}
}
}
private void makeMove() throws IOException {
if (fileContents.isEmpty()) {
System.out.println(botList.get((int)(Math.random()*botList.size())).getId());
return;
}
getLastAction();
String action = "";
int maxHealth = 0, maxPower = 0;
for (Bot b : botList) {
if (power >= 40 && health >= 250) {
if (b.getPower() > maxPower && (!b.getAction().equals("D") || botList.size() == 1)) {
maxPower = b.getPower();
action = String.valueOf(b.getId());
}
}
else if (b.getAction().equals(String.valueOf(id)) && b.getLastAction() != null && b.getLastAction().equals(String.valueOf(id))) {
System.out.println(health % 2 == 0 ? b.getId() : "D");
return;
}
else if (b.getAction().equals(String.valueOf(id)) && b.getPower() > 50) {
System.out.println("D");
return;
}
else {
if (b.getHealth() > maxHealth) {
maxHealth = b.getHealth();
action = String.valueOf(b.getId());
}
}
}
System.out.println(action);
}
private void getLastAction() {
boolean endNext = false;
for (String s : fileContents) {
if (s.startsWith("Turn")) {
turn = Integer.parseInt(s.split(" ")[1]);
if (endNext)
break;
else {
endNext = true;
continue;
}
}
if (s.isEmpty()) break;
String[] botInfo = s.split(",");
for (Bot b : botList) {
if (b.getId() == Integer.parseInt(botInfo[0]))
b.setLastAction(botInfo[4]);
}
}
}
private void writeBots() throws IOException {
StringBuilder sb = new StringBuilder();
String s = System.lineSeparator();
sb.append("Turn " + ++turn + s);
for (Bot b : botList) {
b.setLastAction(b.getAction());
sb.append(b.toString() + s);
}
sb.append(s);
for (String str : fileContents)
sb.append(str + s);
Files.write(filePath, sb.toString().getBytes());
}
public static void main(String[] args) throws IOException {
new SisBot(args);
}
private class Bot {
private int id, health, power;
private String action, lastAction;
public Bot(String info) {
String[] botInfo = info.split(",");
id = Integer.parseInt(botInfo[0]);
health = Integer.parseInt(botInfo[1]);
power = Integer.parseInt(botInfo[2]);
action = botInfo[3];
}
public int getId() {
return id;
}
public int getHealth() {
return health;
}
public int getPower() {
return power;
}
public String getAction() {
return action;
}
public void setLastAction(String lastAction) {
this.lastAction = lastAction;
}
public String getLastAction() {
return lastAction;
}
@Override
public String toString() {
return new StringBuilder()
.append(id).append(",")
.append(health).append(",")
.append(power).append(",")
.append(action).append(",")
.append(lastAction).toString();
}
}
}
```
I've really got to learn a different language... :P
[Answer]
# Java - Wiisniper - reflex agent
A simple reflex agent, which identifies the most dangerous bot using a simple heuristic and then attacks it.
```
public class Wiisniper {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], target="D";
double bestRatio = Integer.MIN_VALUE;
String[] tokens = args[Integer.valueOf(me)].split(",");
double myLife = Integer.valueOf(tokens[1]);
double myPower = Integer.valueOf(tokens[2]);
for(int i=1;i<args.length;i++){
tokens = args[i].split(",");
double life = Integer.valueOf(tokens[1]);
double power = Integer.valueOf(tokens[2]);
double ratio = myLife/power - life/myPower;
if(tokens[3].equals(me)) //attacks my bot
ratio = ratio * 5;
if(life > 0 && power > 0 && !tokens[0].equals(me) && myPower > 0 && ratio > bestRatio){
bestRatio = ratio;
target = tokens[0];
}
}
System.out.print(target);
}
}
```
[Answer]
# Java - Above Average
Tries to maintain his stats at the upper quartile. Uses predicting technology to predict what the enemy will do.
```
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class AboveAverage {
private static final String FILE_NAME = "state" + File.separator + "AboveAverage";
private File file = new File(FILE_NAME);
private List<Bot> bots = new ArrayList<>();
private Bot me;
private List<List<Bot>> history = new ArrayList<>();
private String[] args;
public AboveAverage(String[] args) {
this.args = args;
this.bots = readBotArray(args);
bots.stream().filter(bot -> bot.isMe).forEach(bot -> me = bot); //Intellij told me to do this...
if (!file.exists()){
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException ignored) {}
}
readHistory();
updateFile();
}
private List<Bot> readBotArray(String[] args){ //First parameter is my id.
List<Bot> bots = new ArrayList<>();
String myId = args[0];
for (String arg : args) {
if (arg.equals(myId)) { // `==` not `.equals()`
continue;
}
Bot bot = new Bot(arg, myId);
bots.add(bot);
}
bots.sort(Comparator.comparingDouble((Bot a) -> a.life).reversed());
return bots;
}
private void updateFile() {
PrintStream out;
try {
out = new PrintStream(new FileOutputStream(file, true), true);
for (String s : args){
if (!s.matches("\\d+|\\d+,-?\\d+,\\d+,(\\d+|D)")){
s.replaceAll("(\\d+,-?\\d+,\\d+,).*", "$1Invalid");
}
out.print(s + " ");
}
out.println();
} catch (FileNotFoundException ignored) {}
}
private void readHistory() {
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()){
String line = scanner.nextLine().trim();
if (line.length() > 0) {
history.add(readBotArray(line.split("\\s+")));
}
}
} catch (FileNotFoundException ignored) {}
}
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
try {
System.out.print(new AboveAverage(args).normalize());
} catch (Exception e){
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
System.out.print("error: " + s.replace("\n", " | "));
}
}
String normalize() {
if (history.size() == 0 || me.lastAction.equals("X")){
return "D";
}
if (bots.stream().mapToInt(bot -> (bot.life + me.power - 1)/me.power).sum() < me.life/bots.stream().mapToInt(bot -> bot.power).sum()){
return bots.stream().max(Comparator.comparingInt(a->a.power)).get().id;
}
List<Bot> bestHistory = history.stream().max((a,b) -> {
int differenceA = 0;
int differenceB = 0;
for (int i = 0; i < a.size(); i++){
if (!a.get(i).equals(bots.get(i))){
differenceA++;
}
if (!b.get(i).equals(bots.get(i))){
differenceB++;
}
}
if (differenceA != differenceB){
return differenceA - differenceB;
}
for (int i = 0; i < a.size(); i++){
differenceA += Math.abs(bots.get(i).life - a.get(i).life) + Math.abs(bots.get(i).power - a.get(i).power) * 10;
differenceB += Math.abs(bots.get(i).life - b.get(i).life) + Math.abs(bots.get(i).power - b.get(i).power) * 10;
}
return differenceA - differenceB;
}).get();
int i = history.indexOf(bestHistory) + 1;
List<Bot> after = i == history.size() ? bots : history.get(i);
Map<Bot, String> actions = new HashMap<>();
for (Bot bot : bots){
if (bot.equals(me)){
continue;
}
after.stream().filter(future -> future.equals(bot)).forEach(future -> actions.put(bot, future.lastAction));
}
List<String> myActions = new ArrayList<>();
myActions.add("D");
myActions.add("InvalidChoice");
myActions.addAll(bots.stream().map(bot -> bot.id).collect(Collectors.toList()));
Map<String,List<Bot>> scenarios = new HashMap<>();
for (String action : myActions){
List<Bot> simulatedBots = bots.stream().map(Bot::copy).collect(Collectors.toList()); //IntelliJ told me to (kind of) golf these lines.
actions.put(me, action);
simulatedBots.stream().filter(bot -> actions.get(bot).equals("D")).forEach(Bot::defend);
simulatedBots.stream().filter(bot -> !actions.get(bot).equals("D")).forEach(bot -> bot.attack(actions.get(bot), simulatedBots));
scenarios.put(action, simulatedBots);
}
return scenarios.keySet().stream().min(Comparator.comparingInt((String action) -> {
List<Bot> scenario = scenarios.get(action);
Bot me = scenario.stream().filter(a->a.isMe).findAny().get();
scenario.removeIf(a->a.life<1||a.equals(me));
scenario.sort(Comparator.comparingInt(a->a.life));
int bestLife = scenario.get(scenario.size() * 3 / 4).life;
scenario.sort(Comparator.comparingInt(a->a.power));
int bestPower = scenario.get(scenario.size() * 3 / 4).power;
scenario.add(me);
return Math.abs(me.power - bestPower)*20 + Math.abs(me.life - bestLife);
})).get();
}
class Bot {
String id, lastAction;
int life, power;
boolean isMe;
boolean isDefending = false;
public Bot() {}
public Bot(String bot, String myId) {
String[] parts = bot.split(",");
id = parts[0];
life = Integer.valueOf(parts[1]);
power = Integer.valueOf(parts[2]);
lastAction = parts[3];
isMe = id.equals(myId);
}
Bot copy() {
Bot bot = new Bot();
bot.id = id;
bot.lastAction = lastAction;
bot.life = life;
bot.power = power;
bot.isMe = isMe;
return bot;
}
void defend(){
this.isDefending = true;
this.power--;
}
void attack(int power){
if (isDefending) {
this.power += 2;
this.life -= power / 2;
} else {
this.power++;
this.life -= power;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bot bot = (Bot) o;
return id.equals(bot.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
void attack(String attackId, List<Bot> bots) {
if (life < 1){
return;
}
Bot attacked = bots.stream().filter((Bot a) -> a.id.equals(attackId)).findFirst().orElse(null);
if (attacked == null){
power--;
return;
}
if (attacked.life < 1){
power--;
return;
}
attacked.attack(power);
}
}
}
```
[Answer]
# Java Equaliser
Even though defending is clearly the most effective strategy (:P), this guy thinks that bopping people over the head until they topple giants seems like fun. But screw those people who defend all the time. They don't get no power from this guy.
```
public class Equaliser {
public static void main (String[] args) {
if (args.length == 0) {
System.out.print("ok");
System.exit(0);
}
String myId = args[0];
String[] tokens;
int life, power;
int lowestPower = Integer.MAX_VALUE;
String lowest = "";
int lowestLife = 1000;
int myLife = 0;
for (int i=1; i<args.length; i++) {
tokens = args[i].split(",");
life = Integer.parseInt(tokens[1]);
power = Integer.parseInt(tokens[2]);
if (!tokens[0].equals(myId)) {
if (life > 0 && power < lowestPower && !tokens[3].equals("D")) {
lowest = tokens[0];
lowestPower = power;
}
lowestLife = Math.min(life, lowestLife);
} else {
myLife = life;
}
}
if (myLife < lowestLife*5/4) {
// IT'S TIME TO DEFEND!
System.out.println("D");
} else if (lowestPower != Integer.MAX_VALUE) {
System.out.println(lowest);
} else {
// Them buffed up perma-defenders don't need no power
System.out.println("D");
// And if you can't beat 'em, join 'em
}
}
}
```
[Answer]
# Java - Pacifier
first submission ever ! \o/
Was working on a bot for this contest that use huge data-saving and try to find pattern, and thought of this one.
Basically, if he thinks his damages are too low to do anything useful, he will protect himself. Otherwise, he will attack the more threatening opponent, which is determined by the number of hit needed to kill him, and it's damage output.
Couldn't give it a try, but I think he can do some nice job !
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Pacifier
{
private static final File DATA_FILE = new File("state"+File.separator+"Pacifier.whatever");
public static void main(String[] args)
{
if(args.length==0)
{
if(DATA_FILE.exists())
{
try {
DATA_FILE.delete();
} catch (Exception e) {System.out.println("D");System.exit(0);}
}
try{
DATA_FILE.createNewFile();
}catch (IOException e) {}
System.out.println("ok");
System.exit(0);
}
int ownId=0,ownHp=1,ownAt=1;
String known = null;
BufferedReader bf = null;
try{
bf=new BufferedReader(new FileReader(DATA_FILE));
known=bf.readLine();
}catch(Exception e){System.out.println("D");System.exit(0);}
boolean firstTurn = known==null;
String[] mk = null,iniData=null;
if(!firstTurn)
{
mk = known.split(" ");
iniData = mk[0].split(",");
iniData[1] = String.valueOf(Integer.parseInt(iniData[1])+1);
}
String[] datas = new String[args.length-1];
boolean hasReseted = true;
for(String s : args)
{
if(!s.contains(","))
ownId=Integer.parseInt(s);
else
{
String[] tmp = s.split(",");
hasReseted=(Integer.parseInt(tmp[1])==1000)?hasReseted:false;
if(Integer.parseInt(tmp[0])==ownId)
{
ownHp=Integer.parseInt(tmp[1]);
ownAt=Integer.parseInt(tmp[2]);
}
int id=Integer.parseInt(tmp[0]);
datas[id]=s;
if(!firstTurn)
{
if(tmp[3]!="D"){
int to =Integer.parseInt(mk[id+1].split(",")[4]);
int pa = Integer.parseInt(mk[id+1].split(",")[2]);
datas[id]+=","+(to+pa);
}
else
datas[id]+=","+Integer.parseInt(mk[id+1].split(",")[4]);
}
else
datas[id]+=",0";
}
}
if(firstTurn||hasReseted)
{
iniData = new String[2];
iniData[0]=ownId+"";
iniData[1]="0";
}
int target=(ownId==0)?1:0;
float best=-100.f;
if(Integer.parseInt(iniData[1])<40
&&Integer.parseInt(iniData[1])%3==0)
target=-1;
else
for(String s:datas)
{
if(s!=null&&s.contains(","))
{
String[] tmp = s.split(",");
int id = Integer.parseInt(tmp[0]);
float hp =Float.parseFloat(tmp[1]);
float at = Float.parseFloat(tmp[2]);
float curr=((hp/(float)ownAt)*at)*(0.1f*at);
float dangerOverall= Float.parseFloat(tmp[4])/(100*hp);
target=(curr*dangerOverall>=best
&&id!=ownId
&&hp>0)?Integer.parseInt(tmp[0]):target;
best=(curr*dangerOverall>=best
&&id!=ownId
&&hp>0)?curr:best;
}
}
store(iniData,datas);
System.out.println((target>=0)?target:"D");
}
private static void store(String[] iniData,String[] datas)
{
StringBuffer sb = new StringBuffer();
sb.append(iniData[0]+","+iniData[1]);
for(String s:datas)
{
if(s==null)
break;
sb.append(" "+s);
}
FileWriter fw = null;
try{
fw=new FileWriter(DATA_FILE);
fw.write(sb.toString());
fw.flush();
fw.close();
}catch(Exception e){e.printStackTrace();}
}
}
```
He doesn't have a big brain, so he doesn't remember anything, but I think it could do some nice work.
Funny point : if he's the last alive, he'll try to kick some dead bodies, zombies scares him !
## Edit :
Did send ok on the first turn, just tested it against the samples, he's getting some hard time, gonna work a little bit on him before.
## Edit 2:
he now memorize some datas, and do much better, never won, but actually losing each time by <50 hp... ho, and one of the run i did against samples gave me this :
14 3170 java Bully
0 0 java Pacifier
0 0 java Hero
0 0 java Coward
It's no longer happening(He won some points actually :)), but was funny :D.
## Edit 3:
Using the correct Filename, and some improvement. Work pretty well, and is much better when a lot of bots are here :).
[Answer]
# **Java - Meta Fighter**
### Note: Please tell me if it doesn't work
The Meta Fighter doesn't consider every opponent as an individual enemy. He considers all of them as a whole. The Meta Fighter adds up the combined power and strength of all enemies, and considers it to be him vs. them. He then calculates which move would be most effective in lowering both of those scores. Killing a weak opponent is helpful because it lowers strength and power at the same time. However, if attacking an enemy would give it more beneficial power than it would take away strength, he decides it's not worth it and either defends or attacks himself. The Meta Fighter is only wondering why the opponent is at war with himself...
(BTW, My Second Entry Ever to Codegolf)
```
package folder;
public class MetaFighter {
public static void main(String[] args) {
if(args.length < 1){
System.out.print("ok");
System.exit(0);
}
String me = args[0], target = "D";
int weakestAmount = 2000, weakest = 0, totalLife = 0, totalPower = 0, threat = 0, enemies = 0;
int life = 0,power = 0;
for(int i = 1; i < args.length; i++){
String[] data = args[i].split(",");
if(me.equals(data[0])){
life = Integer.parseInt(data[1]);
power = Integer.parseInt(data[2]);
}else{
if(Integer.parseInt(data[1]) > 0){
if(Integer.parseInt(data[1]) < weakestAmount){
weakest = Integer.parseInt(data[0]);
weakestAmount = Integer.parseInt(data[1]);
}
totalLife += Integer.parseInt(data[1]);
totalPower += Integer.parseInt(data[2]);
enemies++;
}
}
}
int powerV,totalPowerV,lifeV,totalLifeV,Defend = 0,AttackSelf = 0;
powerV = power;
totalPowerV = totalPower;
lifeV = life;
totalLifeV = totalLife;
MetaFighter m = new MetaFighter();
threat = m.calculateThreat(0, 0,totalLifeV,lifeV,powerV,totalPowerV, enemies);
if (threat < 0){
target = Integer.toString(weakest);
}else{
lifeV = lifeV - powerV;
powerV++;
AttackSelf = m.calculateThreat(0, 1,totalLifeV,lifeV,powerV,totalPowerV, enemies);
powerV = power;
totalPowerV = totalPower;
lifeV = life;
totalLifeV = totalLife;
Defend = m.calculateThreat(0, 2,totalLifeV,lifeV,powerV,totalPowerV, enemies);
if(threat > AttackSelf && threat > Defend){
target = Integer.toString(weakest);
}
if(Defend > AttackSelf && Defend > threat){
target = "D";
}
if(AttackSelf > threat && AttackSelf > Defend){
target = me;
}
if (Defend == threat){
target = Integer.toString(weakest);
}
if (enemies < 3){
target = Integer.toString(weakest);
}
}
System.out.print(target);
System.exit(0);
}
private int calculateThreat(int i, int s,int totalLifeV,int lifeV,int powerV, int totalPowerV, int enemies){
if(totalLifeV > 0 && lifeV > 0){
if(s == 0){
totalLifeV += (0-powerV);
}
if (s != 2){
lifeV += (0-totalPowerV);
}else{
lifeV += 0.5*(0-totalPowerV);
powerV--;
}
powerV += enemies;
totalPowerV++;
i++;
return calculateThreat(i, 0,totalLifeV,lifeV,powerV,totalPowerV, enemies);
}
if(lifeV > 0){
return -1;
}
return i;
}
```
}
**Final Edit: Added Feature so it attacks if there are only 3 bots left.**
Biggest Weakness: Bully.
[Answer]
# python 2.7 - GTA V's Trevor Phillips and Michael De Santa
---
*Edit 2015-05-25: added first version of Michael De Santa.*
---
Here's a little homage to GTA V. I created two Python bot representing two of three protagonists of GTA V. Please meet Trevor Phillips and Michael De Santa. Trevor has nothing too subtle about him. Michael has a good memory - and a hitlist. Once you're on it, your days are counted.
*Note1 : When I have time, I'll put some more intelligence into Michael and maybe even add a Franklin (to replace the bragging Trevor).*
*Note 2: Michael seems to perform quite allright. I have some more idea's, but I wanted to put this out. Maybe a "better" version of him will come.*
# Trevor Philips
```
# "Computer gamers with their computer rigs.
# All they do is cry.
# They will never get the game."
# - Trevor Phillips.
#
import sys, random
from __builtin__ import str
# YES!!! I'm alive!!!
args=sys.argv
if len(args)==1:
print("ok")
sys.exit()
# Basic strategy: Hit whoever hits me or just anyone; sometimes brag a Trevor quote.
me=int(args[1])
botnrs=[]
action=''
quotes=["Now would you get me a f*cking drink! I'm not gonna ask you again!",
"Grumble grumble grumble I've got my work grumble grumble grumble I've got my life, never the two shall meet.",
"Well hello there beautiful. here go buy yourself something nice",
"I'm driving, you can jerk me off if I get bored... I'm joking, you can suck me off.",
"Do you want me to get my dick out again?!",
"Floyd..we're having people over. We need chips, dip, and prostitutes"]
for bot in args[2:]:
nr,life,power,lastaction=bot.split(',')
botnrs.append(nr)
if lastaction==str(me):
action=int(nr)
if action=='':
action=int(random.choice(botnrs))
if random.random()<0.05:
action=random.choice(quotes)
print(action)
```
# Michael De Santa
```
# Surviving is winning, Franklin, everything else is bullshit.
# Fairy tales spun by people too afraid to look life in the eye.
# Whatever it takes, kid: survive.
# - Michael De Santa.
#
import sys, pickle, re, operator
# List of power values for a certain bot in a given round range
def getpower( history, botid, roundrange ):
return [sum([bot[2] for bot in history[i] if bot[0]==botid]) for i in roundrange]
# If you say nothing, I say "ok".
if len(sys.argv)==1:
print("ok")
historyfile=open('state/MichaelDeSanta.bin','w+')
pickle.dump([[],{},0,0],historyfile)
historyfile.close()
sys.exit()
# Get data from file
myid=int(sys.argv[1])
historyfile=open('state/MichaelDeSanta.bin','r')
history,hitlist,botcount,roundnr=pickle.load(historyfile)
historyfile.close()
history.append([map(int,re.sub('[DX]','-1', bot).split(',')) for bot in sys.argv[2:]])
# Update hitlist:
if roundnr==0:
hitlist=dict.fromkeys([bot[0] for bot in history[0]],0)
maxhealth=maxpower=[0,0]
for bot in history[roundnr]:
if bot[0] != myid:
if bot[1]<=0:
hitlist[bot[0]]=0
else:
# If you hit me, you're on the list!
if bot[3]==myid:
hitlist[bot[0]]+=4
# If I can kill you with one hit... You're on my list!
if bot[1]<getpower(history,myid,[roundnr]):
hitlist[bot[0]]+=1
# If you're super healthy, you deserve PUNISHMENT!
if bot[1]>maxhealth[1]:
maxhealth=[bot[0],bot[1]]
# If you're powerfull... Well... I'm not afraid!
if bot[2]>maxpower[1]:
maxpower=[bot[0],bot[1]]
hitlist[maxhealth[0]]+=3
hitlist[maxpower[0]]+=2
action=max(hitlist.iteritems(),key=operator.itemgetter(1))[0]
hitlist[action]-=1
# Save data to file
roundnr+=1
historyfile=open('state/MichaelDeSanta.bin','w+')
pickle.dump([history,hitlist,botcount,roundnr],historyfile)
historyfile.close()
# Wrap up and print the action
print(action)
```
[Answer]
# Java- Patroclus
Patroclus is an aggressive bot, who is determined to seek glory. He has quite a good memory (even if I do say so myself) and he believes that the best way to seek glory is attacking the most aggressive enemy. He remembers who has attacked most so far in all the games and bops them over the head with his big sword.
His biggest weakness is his Kamikaze attitude to defending- who needs it when you're wearing Achilles' armour?
```
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class Patroclus {
final static File file = new File("state/Patroclus.txt");
static List<bot> enemies;
static String me;
public static void main(String[] args) {
if(args.length < 1){
if(file.exists())
{
file.delete();
}
System.out.print("ok");
System.exit(0);
}
me = args[0];
enemies = new LinkedList<Patroclus.bot>();
if(!file.exists())
{
createFile();
for(int i = 1; i<args.length; i++)
{
String[] tokens = args[i].split(",");
bot newBot = new bot();
newBot.id = tokens[0];
newBot.life = Integer.valueOf(tokens[1]);
enemies.add(newBot);
}
}
else
{
openFile(args);
}
Collections.sort(enemies);
Collections.reverse(enemies);
String target = "D";
for(int i = 0; (i<enemies.size()) && (i>-1); i++)
{
if(enemies.get(i).canAttack())
{
target = enemies.get(i).id;
i = -10;
}
}
saveFile();
System.out.print(target);
System.exit(0);
}
private static void saveFile() {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(file));
for (bot b : enemies) {
writer.write(b.toString());
writer.write("#");
}
writer.flush();
writer.close();
} catch (IOException e) {
}
}
private static void openFile(String[] args) {
Scanner sc;
try {
sc = new Scanner(file);
String[] lines = sc.next().split("#");
for(int i = 0; i<lines.length; i++)
{
bot newBot = new bot(lines[i]);
int j = 1;
for(; j<args.length && j>0; j++)
{
String[] tokens = args[j].split(",");
if(tokens[0].equals(newBot.id))
{
newBot.life=Integer.valueOf(tokens[1]);
if(newBot.life>0 && !tokens[3].equals("D"))
{
newBot.agression++;
}
j = -10;
}
}
enemies.add(newBot);
}
} catch (FileNotFoundException e) {
}
}
private static void createFile() {
try {
file.createNewFile();
} catch (IOException e) {
}
}
private static class bot implements Comparable<bot>
{
int agression, life;
String id;
public bot(String toParse)
{
String[] tokens = toParse.split(",");
id = tokens[0];
agression = Integer.valueOf(tokens[1]);
}
public bot()
{
this.agression = 0;
this.life = 0;
this.id = "D";
}
@Override
public int compareTo(bot o) {
if(this.agression>o.agression)
return 1;
else if (this.agression==o.agression)
return 0;
else
return -1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(id);
sb.append(",");
sb.append(agression);
return sb.toString();
}
public Boolean canAttack()
{
return life>0 && !id.equals(me);
}
}
}
```
[Answer]
# [Rust](http://www.rust-lang.org/) - Paranoid
Keeps comparing himself to the liveliest on the battlefield.
```
struct Bot {
id: i32,
life: i32,
power: i32,
action: String,
}
fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
print!("ok");
} else {
let id: i32 = args[1].to_string().trim().parse()
.ok()
.expect("Please type a number!");
let mut target_bot = Bot { id:-1, life:-1, power:-1, action:"D".to_string() };
let mut own_bot = Bot { id:id, life:0, power:1, action:"D".to_string() };
for arg in args {
let split: Vec<&str> = arg.split(",").collect();
if split.len() == 4 {
let bot_id: i32 = split[0].to_string().trim().parse()
.ok()
.expect("Please type a number!");
let bot_life: i32 = split[1].to_string().trim().parse()
.ok()
.expect("Please type a number!");
let bot_power: i32 = split[2].to_string().trim().parse()
.ok()
.expect("Please type a number!");
let bot_action: String = split[3].to_string();
let bot = Bot { id:bot_id, life:bot_life, power:bot_power, action:bot_action };
if bot.id != id && bot.life > target_bot.life {
target_bot = bot;
} else if bot.id == id {
own_bot = bot;
}
}
}
/* If I am not stronger than the strongest, defend */
let turns_to_kill = target_bot.life/own_bot.power + 1;
let turns_to_be_killed = own_bot.life/target_bot.power;
if target_bot.id > -1 && turns_to_kill < turns_to_be_killed {
print!("{}", target_bot.id);
} else {
print!("D");
}
}
}
```
] |
[Question]
[
Choose any five characters your language supports. There are 5! = 5√ó4√ó3√ó2√ó1 = 120 ways these can be arranged into a 5-character string that contains each character once; 120 [permutations](https://en.wikipedia.org/wiki/Permutation).
Choose your characters such that, when each of the 120 strings is run in your language, the 120 outputs produced will be as many unique integers from 1 to 120 (inclusive) as possible.
That is, for each of the 120 permutations of your 5 characters that produce runnable code that outputs a single number, you want the set of all those numbers to match as close as possible to the set of integers from 1 through 120.
So, ideally, your first permutation would output `1`, the next `2`, the next `3`, all the way up to `120`. But that ideal is likely impossible for most languages and characters.
The 5-character strings may be run as:
* a program with no input
* a function with no arguments
* a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) command
Different strings can be run in different ways if desired
For the output to count, it must be a single integer output in a [normal](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) way, such as:
* being printed to stdout
* returned by the function
* the result of the REPL expression
The code should terminate normally (which [may involve](https://codegolf.meta.stackexchange.com/a/4781/26997) erroring out as long as the number has been output first). Code that does not run at all is fine, just the (nonexistent) output doesn't count. The numbers output should be in decimal unless a different base is the norm for your language.
**The submission that generates the most distinct numbers from 1 through 120 wins. The earlier submission wins in case of a tie.**
## Notes
* Your 5 characters do not all need to be different, but of course having duplicate characters reduces the effective number of permutations.
* Float outputs such as `32.0` count as well as plain `32`. (But `32.01` would not.)
* Leading zeroes such as `032` count as well as plain `32`.
* Valid outputs should be deterministic and time invariant.
* We are dealing with *characters*, not bytes.
# Example
The characters `123+*` are a reasonable first choice for Python's (or many language's) REPL. The resulting 120 permutations and outputs are:
```
123+* n/a
123*+ n/a
12+3* n/a
12+*3 n/a
12*3+ n/a
12*+3 36
132+* n/a
132*+ n/a
13+2* n/a
13+*2 n/a
13*2+ n/a
13*+2 26
1+23* n/a
1+2*3 7
1+32* n/a
1+3*2 7
1+*23 n/a
1+*32 n/a
1*23+ n/a
1*2+3 5
1*32+ n/a
1*3+2 5
1*+23 23
1*+32 32
213+* n/a
213*+ n/a
21+3* n/a
21+*3 n/a
21*3+ n/a
21*+3 63
231+* n/a
231*+ n/a
23+1* n/a
23+*1 n/a
23*1+ n/a
23*+1 23
2+13* n/a
2+1*3 5
2+31* n/a
2+3*1 5
2+*13 n/a
2+*31 n/a
2*13+ n/a
2*1+3 5
2*31+ n/a
2*3+1 7
2*+13 26
2*+31 62
312+* n/a
312*+ n/a
31+2* n/a
31+*2 n/a
31*2+ n/a
31*+2 62
321+* n/a
321*+ n/a
32+1* n/a
32+*1 n/a
32*1+ n/a
32*+1 32
3+12* n/a
3+1*2 5
3+21* n/a
3+2*1 5
3+*12 n/a
3+*21 n/a
3*12+ n/a
3*1+2 5
3*21+ n/a
3*2+1 7
3*+12 36
3*+21 63
+123* n/a
+12*3 36
+132* n/a
+13*2 26
+1*23 23
+1*32 32
+213* n/a
+21*3 63
+231* n/a
+23*1 23
+2*13 26
+2*31 62
+312* n/a
+31*2 62
+321* n/a
+32*1 32
+3*12 36
+3*21 63
+*123 n/a
+*132 n/a
+*213 n/a
+*231 n/a
+*312 n/a
+*321 n/a
*123+ n/a
*12+3 n/a
*132+ n/a
*13+2 n/a
*1+23 n/a
*1+32 n/a
*213+ n/a
*21+3 n/a
*231+ n/a
*23+1 n/a
*2+13 n/a
*2+31 n/a
*312+ n/a
*31+2 n/a
*321+ n/a
*32+1 n/a
*3+12 n/a
*3+21 n/a
*+123 n/a
*+132 n/a
*+213 n/a
*+231 n/a
*+312 n/a
*+321 n/a
```
There are 36 numbers generated, all luckily within 1 to 120:
```
36, 26, 7, 7, 5, 5, 23, 32, 63, 23, 5, 5, 5, 7, 26, 62, 62, 32, 5, 5, 5, 7, 36, 63, 36, 26, 23, 32, 63, 23, 26, 62, 62, 32, 36, 63
```
However, only 8 of them are unique:
```
36, 26, 7, 5, 23, 32, 63, 62
```
So such a submission would only score 8 out of a maximal 120.
[Answer]
# Python3, ~~21~~ 27 values
Characters: `3479%`
Unique numbers: `[1,2,3,4,5,6,7,8,9,11,12,19,20,21,24,29,34,35,36,37,39,43,46,47,49,73,74]`
As it was requested, here are the permutations that fell in the range **[1, 120]**. [Try it online!](https://tio.run/##VYzRCsIwDEXf9xWhUGhBxKkgDvcxQzusbE1IMnFfPzumDs/T4d7k0qh3TIdpahl7iBpYETuB2BOyAgXuB200YpKiaJGBIKa/2JnD8XS2xlcFZJTHRWYEajBm@8CYHPlfzEGGTnMXnk3nZC1iC66ES/29yFbud34dnCGOSZ2xkt3eDFhwsvl8@GUrvK6BtKJGZJre)
```
347%9 5
349%7 6
34%79 34
34%97 34
374%9 5
379%4 3
37%49 37
37%94 37
394%7 2
397%4 1
39%47 39
39%74 39
3%479 3
3%497 3
3%749 3
3%794 3
3%947 3
3%974 3
437%9 5
439%7 5
43%79 43
43%97 43
473%9 5
479%3 2
47%39 8
47%93 47
493%7 3
497%3 2
49%37 12
49%73 49
4%379 4
4%397 4
4%739 4
4%793 4
4%937 4
4%973 4
734%9 5
739%4 3
73%49 24
73%94 73
743%9 5
749%3 2
74%39 35
74%93 74
793%4 1
794%3 2
79%34 11
79%43 36
7%349 7
7%394 7
7%439 7
7%493 7
7%934 7
7%943 7
934%7 3
937%4 1
93%47 46
93%74 19
943%7 5
947%3 2
94%37 20
94%73 21
973%4 1
974%3 2
97%34 29
97%43 11
9%347 9
9%374 9
9%437 9
9%473 9
9%734 9
9%743 9
```
[Answer]
# Python, 18 numbers
```
237#-
```
Produces as valid results:
```
1, 2, 3, 4, 5, 7, 16, 23, 24, 25, 27, 32, 35, 37, 69, 71, 72, 73
```
---
**EDIT:** I can attest that [TuukkaX's solution](https://codegolf.stackexchange.com/a/102664/62393) is optimal for Python.
I ran the following code bruteforcing all possible combinations of 5 printable ASCII characters:
```
from itertools import permutations,combinations_with_replacement
def perms(chars):
result=set()
for permut in permutations(chars):
try:
current=eval(''.join(permut))
assert str(int(current))==str(current)
result.add(int(current))
except:
pass
return sum([1 for x in result if 1<=x<=120])
best=1
for c in combinations_with_replacement(' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',5):
string=''.join(c)
r=perms(string)
if r>=best:
best=r
print(r,string,end='\n')
```
The results (after running for almost 7 hours) showed that the optimal solution is in fact 27 different numbers, produced by three different solutions all using four numbers and mod (`%`): `%3479`, `%5679` and `%5789`.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~27~~ ~~38~~ 41 numbers
```
4·>Ìn
```
Generates the unique numbers:
`[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 25, 27, 32, 33, 34, 35, 36, 37, 38, 49, 50, 52, 54, 64, 65, 66, 67, 72, 73, 74, 81, 83, 98, 100, 101, 102]`
Uses the constant `4` with the operations `+1`, `+2`, `*2` and `^2`.
[Answer]
# Java 8, ~~2~~ 4 numbers
```
n->12 // returns 12
n->21 // returns 21
n1->2 // returns 2
n2->1 // returns 1
```
Weren't expecting a Java answer, were you?
This is a lambda that can only be arranged one of two ways (and with any two different digits!) for a total of two unique numbers. Everything else isn't a valid lambda.
Actually improved the answer, thanks to some help from comments! Didn't see that 0 wasn't valid, and forgot that variables could, y'know, be more than one character. We've got 4!
## An even worse solution
`()->1`
But, on the bright side, two unique answers in Java!
[Answer]
# Jelly, ~~26~~ ~~30~~ 32 numbers
```
‘’3²Ḥ
```
This (and its anagrams) are full programs, that take no input, and produce output on standard output.
The outputs from the 120 programs are, in the order Jelly generates them if you ask it to generate permutations of the program:
```
018 036 06 03 09 03 18 116 116 117 125 135 06 03 14 15 13 22 19 13 24
28 33 42 018 036 06 03 09 03 -132 -164 -120 -119 -149 -137 26 43 18 17
33 24 -19 13 -216 -210 53 44 18 36 30 31 49 63 18 36 10 9 25 17 18 19
18 17 18 18 36 48 36 26 36 36 06 03 14 15 13 22 06 03 -18 -17 -13 -24
06 07 06 05 06 06 03 12 03 -14 03 03 09 03 14 18 03 12 09 03 -116 -110
23 14 09 015 09 05 09 09 03 12 03 -14 03 03
```
If you just take the unique outputs in numerical order, you get:
```
-216 -210 -164 -149 -137 -132 -120 -119 -116 -110 -24 -19 -18 -17 -14 -13
03 05 06 07 09 10 12 13 14 15 17 018 19 22 23 24 25 26 28 30 31 33 036 42
43 44 48 49 53 63 116 117 125 135
```
Many of these are too small, and 135 is too large, but there are still 32 that are in range.
The basic idea is to use mostly monadic instructions (in a program with only monads and nilads, these each just transform the previous output), and ones that allow the value to diverge quickly. The exception is with `3`, which is a nilad (the constant value 3). If it appears at the start of the program, all the operations will be done from 3. If it appears in the middle, it splits the program into two halves, each of which outputs an integer (and as they each print to standard output, the results end up getting concatenated, thus giving us "concatenate" as an additional operation to generate numbers).
The operations we have here, in the context the program generates them in, are: increment; decrement; constant 3; square; and double. Increment and decrement are unfortunately opposites, and decrement has an unfortunate tendency to produce a -1 or -2 in the first section (thus leading to a negative number overall), but this still gave a greater spread of outputs than the other things I tried. In particular, we get a pretty good spread of both the first and second halves of the number (note that the first half can be the null string, if `3` is the first character in the program).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 26 numbers
```
3+*^-
```
This outputs the following numbers: `[2,3,4,5,6,7,8,9,10,16,17,18,19,20,25,26,30,31,32,35,36,37,48,49,63,64]`
### Explanation
* `3` is the integer 3, obviously.
* `+` is increment
* `*` is double
* `^` is square
* `-` is decrement
There are a lot of situations where the program simply errors: for example `*+^3-` errors because it asks *“Take 0, double it, increment, square, the result of that square is 3, decrement”* which is obviously wrong.
Any program that ends with `3` will either output `3` or not work.
Any program that starts with `*3` will loop infinitely because of a bug (Brachylog is attempting to find a list of sublists which product result in 3 which is not possible).
[Answer]
## JavaScript, 27 numbers
Very similar to [TuukkaX's answer](https://codegolf.stackexchange.com/a/102664/58563), with another set of digits.
```
5789%
```
The 27 distinct values are:
```
589 % 7 -> 1
987 % 5 -> 2
978 % 5 -> 3
879 % 5 -> 4
985 % 7 -> 5
958 % 7 -> 6
975 % 8 -> 7
95 % 87 -> 8
9 % 875 -> 9
97 % 85 -> 12
89 % 75 -> 14
95 % 78 -> 17
78 % 59 -> 19
79 % 58 -> 21
98 % 75 -> 23
87 % 59 -> 28
89 % 57 -> 32
97 % 58 -> 39
98 % 57 -> 41
57 % 98 -> 57
58 % 97 -> 58
59 % 87 -> 59
75 % 98 -> 75
78 % 95 -> 78
79 % 85 -> 79
85 % 97 -> 85
87 % 95 -> 87
```
[Answer]
## Vim, 16 numbers
```
i1234
```
print
```
1, 2, 3, 4, 12, 13, 14, 21, 23, 24, 31, 32, 34, 41, 42, 43
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 numbers
```
Ḥ23+c
```
`Ḥ` double(left);
`2` literal 2;
`3` literal 3;
`+` add(left, right); and
`c` choose(left, right), i.e. number of ways to choose right objects from a collection of left objects.
Numbers yielded with an example program:
```
1 +32Ḥc 18 3Ḥc2+ 45 2+3Ḥc
2 c3Ḥ+2 20 2+Ḥc3 47 23c+Ḥ
3 c2Ḥ+3 21 2Ḥ+3c 48 c+23Ḥ
4 +2Ḥc3 22 3Ḥc+2 53 2c+Ḥ3
5 2+3cḤ 23 23cḤ+ 56 3Ḥ+2c
6 3c+2Ḥ 24 cḤ+23 63 c+2Ḥ3
8 2c+3Ḥ 30 3+c2Ḥ 65 32c+Ḥ
9 3c2+Ḥ 32 32cḤ+ 66 c+32Ḥ
12 +3cḤ2 33 cḤ+32 72 3c+Ḥ2
13 +2cḤ3 36 3+Ḥc2 82 c+3Ḥ2
15 +3Ḥc2 42 cḤ3+2 120 3+2Ḥc
```
I tried to choose easy to parse ones, but some are rare and slightly strange to parse, for example `23` is:
```
23cḤ+: (23 c (2 * 23)) + 23 = (23 c 46) + 23 = 0 + 23 = 23
```
...and `72` and `13` use implicit printing:
```
3c+Ḥ2: z = (3 c 0) + (3 * 2); print(z); z = 2; print(z)
z = 1 + 6 ; print(z); z = 2; print(z)
+2cḤ3: z = (0 + 2) c (2 * 0); print(z); z = 3; print(z)
z = 2 c 0 ; print(z); z = 3; print(z)
z = 1 ; print(z); z = 3; print(z)
```
---
Note that `Ḥ34+c` also produces `33` unique values in `[1,120]`.
[Answer]
# IA-32 machine code, 8 numbers
Hexadecimal byte values:
```
2c 40 48 b0 c3
```
The code is run as a function returning the value in `al`.
Valid permutations:
```
b0 2c c3 xx xx => 2c (mov al, 2c)
b0 40 c3 xx xx => 40 (mov al, 40)
b0 48 c3 xx xx => 48 (mov al, 48)
b0 2c 40 c3 48 => 2d (mov al, 2c; inc eax)
b0 2c 48 c3 40 => 2b (mov al, 2c; dec eax)
b0 40 48 c3 2c => 3f (mov al, 40; dec eax)
b0 48 40 c3 2c => 49 (mov al, 48; inc eax)
b0 48 2c 40 c3 => 8 (mov al, 48; sub al, 40)
```
I did a brute-force search, with the following constraints:
* The first byte is `b0` - to initialize the `al` register
* The last byte is `c3` - return; following bytes are discarded
* Possible opcode bytes are:
+ 0x04 - `add`
+ 0x0c - `or`
+ 0x24 - `and`
+ 0x2c - `sub`
+ 0x34 - `xor`
+ 0xd4 - `aad`
+ 0x40 - `inc`
+ 0x48 - `dec`
This leaves only 3 changeable bytes with a maximum of 15 possible results. Of these, a maximum of 9 can be distinct (in fact, this happens for only one set of bytes!). One of the values is out of range, so this leaves 8 values. There is another set of bytes
```
34 40 48 b0 c3
```
which also gives 8 distinct values - the programs are the same, except for `sub` replaced by `xor`, which makes two of the possible outputs identical.
All other sets of bytes give 7 or fewer possible results.
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak) 1
```
(())#
```
Brain-Flak requires balanced braces, so a 5 character program is only valid if one of the characters starts a comment. That leaves us with 4 characters to work with. Of those, 2 have to be `(` and `)` otherwise nothing would get pushed onto the stack. Those have to go first and 4th with the comment last (`(..)#`). Now we can put `()`, `{}`, `<>`, or `[]` inside. `{}`, `<>`, and `[]` each evaluate to 0, but `()` is 1. That means that `(())#` is the only 5 character string that produces a valid Brain-Flak program.
[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgpKSM&input=)
If the question were instead "what are the *6* most powerful characters", the answer would be `(){}[]` as Brain-Flak is turing complete using only this subset.
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), 13 numbers
```
)24!@
```
These are the 13 printable numbers with one possible program for each of them:
```
)!@24 1
2!@)4 2
2)!@4 3
4!@)2 4
4)!@2 5
)2!@4 12
)4!@2 14
24!@) 24
24)!@ 25
2)4!@ 34
42!@) 42
42)!@ 43
4)2!@ 52
```
The programs should be fairly self-explanatory. `@` terminates the program, `!` prints the current value, `)` increments it, `2` and `4` append themselves to the current value (where the initial value is `0`). The actual hexagonal layout of the source code is irrelevant here, the programs can simply be read from left to right.
This *should* be optimal, although instead of `2` and `4` you can pick any pair digits `x` and `y` such that `2 ≤ x ≤ y-2`.
The above solution was found by (almost exhaustive) brute force, requiring one `!` (otherwise it wouldn't print anything), one `@` (otherwise the program won't terminate), and filling the remaining three characters with any (repeated) combination from the following set of characters:
```
#[]\/_|<>)!0123456789$
```
I can't see how any of the other commands could possibly generate more variety.
[Answer]
# Octave, 18
This was found using a bruteforce search on the symbols `*+-/0123456789:;<\^|~%`. But it took way too long to compute...
```
-139%
```
Possible outputs:
```
1, 2, 3, 4, 6, 8, 9,13,16,19,22,31,38,39,88,91,92,93
```
[Answer]
# Perl, 27 numbers
`3479%`
Perl doesn't have a built-in REPL, so you can use `re.pl` from [Devel::REPL](https://metacpan.org/pod/Devel::REPL).
Results:
```
%9743 -> N/A
9%743 -> 9
97%43 -> 11
974%3 -> 2
9743% -> N/A
%7943 -> N/A
7%943 -> 7
79%43 -> 36
794%3 -> 2
7943% -> N/A
%7493 -> N/A
7%493 -> 7
74%93 -> 74
749%3 -> 2
7493% -> N/A
%7439 -> N/A
7%439 -> 7
74%39 -> 35
743%9 -> 5
7439% -> N/A
%9473 -> N/A
9%473 -> 9
94%73 -> 21
947%3 -> 2
9473% -> N/A
%4973 -> N/A
4%973 -> 4
49%73 -> 49
497%3 -> 2
4973% -> N/A
%4793 -> N/A
4%793 -> 4
47%93 -> 47
479%3 -> 2
4793% -> N/A
%4739 -> N/A
4%739 -> 4
47%39 -> 8
473%9 -> 5
4739% -> N/A
%9437 -> N/A
9%437 -> 9
94%37 -> 20
943%7 -> 5
9437% -> N/A
%4937 -> N/A
4%937 -> 4
49%37 -> 12
493%7 -> 3
4937% -> N/A
%4397 -> N/A
4%397 -> 4
43%97 -> 43
439%7 -> 5
4397% -> N/A
%4379 -> N/A
4%379 -> 4
43%79 -> 43
437%9 -> 5
4379% -> N/A
%9734 -> N/A
9%734 -> 9
97%34 -> 29
973%4 -> 1
9734% -> N/A
%7934 -> N/A
7%934 -> 7
79%34 -> 11
793%4 -> 1
7934% -> N/A
%7394 -> N/A
7%394 -> 7
73%94 -> 73
739%4 -> 3
7394% -> N/A
%7349 -> N/A
7%349 -> 7
73%49 -> 24
734%9 -> 5
7349% -> N/A
%9374 -> N/A
9%374 -> 9
93%74 -> 19
937%4 -> 1
9374% -> N/A
%3974 -> N/A
3%974 -> 3
39%74 -> 39
397%4 -> 1
3974% -> N/A
%3794 -> N/A
3%794 -> 3
37%94 -> 37
379%4 -> 3
3794% -> N/A
%3749 -> N/A
3%749 -> 3
37%49 -> 37
374%9 -> 5
3749% -> N/A
%9347 -> N/A
9%347 -> 9
93%47 -> 46
934%7 -> 3
9347% -> N/A
%3947 -> N/A
3%947 -> 3
39%47 -> 39
394%7 -> 2
3947% -> N/A
%3497 -> N/A
3%497 -> 3
34%97 -> 34
349%7 -> 6
3497% -> N/A
%3479 -> N/A
3%479 -> 3
34%79 -> 34
347%9 -> 5
3479% -> N/A
```
Brute-forced using the following program:
```
use strict;
use warnings 'all';
use 5.010;
use Algorithm::Combinatorics qw(combinations);
use Algorithm::Permute;
use Scalar::Util::Numeric qw(isint);
my @chars = ( 0..9, qw(+ - * / . ; ' " \ @ $ # ! % ^ & ( ) { } =) );
my $iter = combinations(\@chars, 5);
my $max = 0;
my @best;
while (my $combo = $iter->next) {
my $count = count_valid([@$combo]);
if ($count > $max) {
$max = $count;
@best = @$combo;
}
}
say "$max -> @best";
sub count_valid {
my ($chars) = @_;
my $iter = Algorithm::Permute->new($chars);
my %results;
while (my @perm = $iter->next) {
no warnings;
my $val = eval join '', @perm;
use warnings 'all';
$results{$val} = 1 if isint($val) && $val > 0 && $val <= 120;
}
return scalar keys %results;
}
```
[Answer]
# R, ~~15~~ 18 numbers
Not a huge number but it may be the best that can be done with R. I searched all combinations of digits `0..9`, operators `+ - * / ^` and the comment char `#`, and the following eight all output 18 unique integers between 1 and 120.
```
-#146
-#157
-#237
-#238
-#256
-#267
-#278
-#378
-#467
-#568
```
As an example, let's take `-#146`. Here are the 18 integers we can get:
```
1#-46 = 1
6-4#1 = 2
4-1#6 = 3
4#-16 = 4
6-1#4 = 5
6#-14 = 6
14-6# = 8
16-4# = 12
14#-6 = 14
16#-4 = 16
41-6# = 35
41#-6 = 41
46-1# = 45
46#-1 = 46
61-4# = 57
61#-4 = 61
64-1# = 63
64#-1 = 64
```
If you're curious about the (ugly) code used to test all the possible combinations, here it is. It outputs the number of unique integers between 1 and 120 for each character combination of length 5 to a file called "datafile" in the current working directory.
```
allchars = c("1","2","3","4","5","6","7","8","9","0","+","-","*","/","^")
apply(gtools::combinations(n=15, r=5, v=allchars, repeats.allowed=TRUE),
1,
function(chars) {
x = apply(apply(e1071::permutations(length(chars)),
1,
function(i) chars[i]
),
2,
paste, collapse=""
)
u = unique(x)
o = as.numeric(unlist(sapply(u, function(i) eval(try(parse(t=i),TRUE)))))
f = factor(unique(o[o<=120 & o>=1 & o%%1==0]))
write(paste(nlevels(f), paste(chars, collapse="")), "datafile", append=TRUE)
}
)
```
[Answer]
# Octave, 15 numbers
Not much to brag about, but this is the best I can get in Octave:
```
124+%
```
It gives the numbers:
```
1 2 3 4 5 6 12 14 16 21 24 25 41 42 43
```
---
I got 16 too, but it seems it's identical to Sefa's answer...
```
1234%
1 2 3 4 12 13 14 21 23 24 31 32 34 41 42 43
```
[Answer]
# PHP, 15 numbers
```
1230\r
```
Uses the fact that php prints anything outside its tags verbatim (without using this you can do exactly 1 number with something like `<?=1;`). Also uses an actual carriage return character rather than `\r`.
Creates (sorted, removed leading 0s):
```
1 1 2 2 3 3 10 10 12 12 12 12 13 13 13 13 20 20 21 21 21 21 23 23 23 23 30 30 31 31 31 31 32 32 32 32 102 102 103 103 120 120 123 123 123 123 130 130 132 132 132 132 201 201 203 203 210 210 213 213 213 213 230 230 231 231 231 231 301 301 302 302 310 310 312 312 312 312 320 320 321 321 321 321 1023 1023 1032 1032 1203 1203 1230 1230 1302 1302 1320 1320 2013 2013 2031 2031 2103 2103 2130 2130 2301 2301 2310 2310 3012 3012 3021 3021 3102 3102 3120 3120 3201 3201 3210 3210
```
of which the valid unique numbers are:
```
1 2 3 10 12 13 20 21 23 30 31 32 102 103 120
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 7 numbers
```
"2)@O
```
Outputs these numbers:
```
")O2@ -> 1
")2O@ -> 2
"2)O@ -> 3
2"O@) -> 41
)"O@2 -> 50
2"O)@ -> 64
2")O@ -> 65
```
---
Any valid Cubix program for this challenge has to have an `O` to output an integer, and an `@` to terminate the program (Cubix has never even heard of "errors"). This gives us 3 chars to play around with to generate the most outputs. Furthermore, because of the way Cubix arranges code on a cube, the first char will be useless unless one of the others is a directional char.
The most efficient way I have found to generate multiple numbers is to use `"` to push a string of char-codes to the stack. With careful rearrangement, we can fit several chars in the last spot and simply output their char-codes. By using `)` to increment the top item, we can create extra outputs from several of these arrangements.
There are two basic program types in use here. The first is this:
```
"2)O@
```
which expands to
```
"
2 ) O @
.
```
The resulting program pushes `2` to the stack, increments it with `)`, outputs with `O`, and terminates with `@`.
The second is this:
```
2")O@
```
which expands to
```
2
" ) O @
.
```
The resulting program pushes the char-codes of `)`, `O`, and `@`, increments the last one with `)`, outputs with `O`, and terminates with `@`.
[Answer]
# Groovy, 10 Numbers
Man JVM solutions are BAD for this... Who knew?
```
1200+
```
Results in:
```
[3, 10, 12, 17, 21, 30, 66, 80, 102, 120]
```
Wait, what? How the hell does it make 17 you ask?
```
20+10 is 30.
0120+ is invalid.
2+001 is 3.
201+0 is 201.
2+100 is 102.
0+012 is 10.
21+00 is 21.
02+01 is 3.
0210+ is invalid.
10+20 is 30.
200+1 is 201.
0+210 is 210.
1200+ is invalid.
0201+ is invalid.
+0021 is 17.
1+002 is 3.
210+0 is 210.
100+2 is 102.
010+2 is 10.
00+12 is 12.
20+01 is 21.
01+20 is 21.
0+120 is 120.
+0120 is 80.
0+021 is 17.
+1020 is 1020.
0012+ is invalid.
02+10 is 12.
102+0 is 102.
012+0 is 10.
+2100 is 2100.
12+00 is 12.
00+21 is 21.
+2001 is 2001.
+0210 is 136.
+1200 is 1200.
1020+ is invalid.
0102+ is invalid.
2001+ is invalid.
001+2 is 3.
+0012 is 10.
2+010 is 10.
0021+ is invalid.
10+02 is 12.
2100+ is invalid.
+0201 is 129.
2010+ is invalid.
020+1 is 17.
1002+ is invalid.
+2010 is 2010.
1+020 is 17.
1+200 is 201.
01+02 is 3.
+1002 is 1002.
120+0 is 120.
0+102 is 102.
+0102 is 66.
002+1 is 3.
0+201 is 201.
021+0 is 17.
```
Trade secret, in Groovy/Java integers preceded with a 0 are octals.
Code I used for testing Groovy answers incase someone wants to beat me:
```
("1200+" as List).permutations().collect{
it.join()
}.collect {
print "$it is "
x=-1;
try {
x=Eval.me(it);
println "$x."
} catch(Exception e) {
println "invalid."
}
x<=120?x:-1;
}.unique().sort();‚Äã
```
[Answer]
# TI-BASIC, 12 numbers
```
23+4!
```
There is most likely a better combination, but I wasn't able to find it.
All \$24\$ valid permutations are as follows:
```
23+4! -> 47
24+3! -> 30
2+4!3 -> 74
2+3!4 -> 26
2!4+3 -> 11
2!+43 -> 45
2!+34 -> 36
2!3+4 -> 10
32+4! -> 56
34+2! -> 36
3+4!2 -> 51
3+2!4 -> 11
3!4+2 -> 26
3!+42 -> 48
3!+24 -> 30
3!2+4 -> 16
43+2! -> 45
42+3! -> 48
4+2!3 -> 10
4+3!2 -> 16
4!2+3 -> 51
4!+23 -> 47
4!+32 -> 56
4!3+2 -> 74
```
Of which there are \$12\$ unique values:
\$10,11,16,26,30,36,45,47,48,51,56,74\$
[Answer]
# Befunge, 11 numbers
Befunge is a bit limited because it only supports single digit literals. So the best I could come up with was 11 numbers, assuming the calculation must leave us with one and only one number on the stack.
**Best characters:** `358*%`
**Generated numbers:** (just one example of each)
```
58*3% => 1
358*% => 3
38*5% => 4
538*% => 5
35*8% => 7
835*% => 8
385%* => 9
583%* => 10
358%* => 15
53%8* => 16
35%8* => 24
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 6 numbers
Gained 2 numbers thanks to *Teal Pelican*
```
1ln";
```
Produces the unique numbers `[1, 4, 5, 49, 59, 108]`
We need `n` to print a number.
We need `;` to terminate.
That leaves us only 3 chars to work with.
A few different combinations of `value` & `operator` together with `"` confirmed to produce 6 unique values, but I haven't found anything better than that.
[Answer]
# MATL, 15 numbers
```
0123%
```
`%` is the comment operator, so it will "cut" in all possible places once, helping to create all possible combinations of the given digits and subsets of them:
```
1
2
3
10
12
13
20
21
23
30
31
32
102
103
120
```
[Answer]
# J , 16 Numbers
```
1234]
```
Nothing fancy, just tested `1234` with all the 1-character verbs that were reasonable. `]` selects its right argument.
The unique numbers produced are
```
0 4 3 34 43 2 24 42 23 32 234 243 324 342 423 432 1 14 41 13 31 134 143 314 341 413 431 12 21 124 142 214 241 412 421 123 132 213 231 312 321 1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321
```
of which 16:
```
4 3 34 43 2 24 42 23 32 1 14 41 13 31 12 21
```
Are in the range [1,120].
Tested with
```
# (#~e.&(>:i.120)) ~. (". :: 0:)"1 (A.~ i.@!@#) '1234]'
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 41 numbers
Pretty much just trial and error so there may be a better solution. Uses integers `3` & `4` and the Japt shortcuts for squaring, adding `1` & multiplying by `2`. All 120 programmes output an integer `>0` but only 78 are `<=120` and only 41 of those are unique.
```
34²ÄÑ
```
Generates the numbers:
```
1,3,4,5,6,7,8,9,13,14,17,20,21,26,27,29,30,31,32,33,34,35,36,37,38,39,42,43,44,45,47,56,59,68,69,72,73,86,87,92,93
```
View [the list of numbers](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&header=Ig&code=MzSyxNE&footer=Ingg4SCjT3ZYw%2bIgZiN49Slu) or [the collection of valid programmes](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVI&header=Ig&code=MzSyxNE&footer=Ingg4SCjW1hPdlhdw2ZAI3j1IPhYzMPxzG1xIiA9ICI)
---
## Explanation
A few things to note about Japt that are relevant here are:
1. If a programme doesn't start with (in this case) one of the digits then the first input variable `U`, which defaults to `0`, is automatically inserted at the beginning,
2. If either or both of the digits immediately follow one of the shortcuts for a mathematical operation then they are appended to it (e.g. `3Ä4 = 3+14 = 17` and, similarly, `4Ѳ = 4*2**2 = 16`), and,
3. If one of the digits immediately follows the `²` then the `²` and everything before it are, essentially, ignored.
Explanations for a few of the programmes (producing `1`, `3`, `37` and `93`, respectively):
```
²Ñ34Ä :Square 0, multiply by 234 and add 1
4ÄѲ3 :Add 1 multiplied by 2 squared to 4, ignore that and return the 3
3²Ä4Ñ :Square 3 and add 14 multiplied by 2
4Ñ3IJ :Multiply 4 by 23 and add 1 squared
```
[Answer]
# Python, 16 numbers
```
1234#
```
Uses # to comment out all unnecessary numbers.
[Answer]
# dc, 19 numbers
```
*3zO+
```
Output is on top of stack, and errors (including stack underflow) are ignored. The valid permutations are:
```
+O3*z: 1
+O*3z: 2
+Oz3*: 3
O*z3+: 4
O*3z+: 5
+O3z*: 6
+z3*O: 10
3*zO+: 11
3*Oz+: 12
Oz3*+: 13
O3z*+: 16
+3Oz*: 20
3Oz*+: 23
+zO3*: 30
O3*z+: 31
Oz+3*: 33
3Oz+*: 36
Oz3+*: 40
O3z+*: 50
TOTAL COUNT = 19 numbers
```
Here's the Python program I used to show those results:
```
#!/usr/bin/python
import sys
import itertools
import subprocess
if len(sys.argv[1]) != 5:
print("Invalid input")
sys.exit(1)
devnull = open("/dev/null", 'w');
r = dict()
for s in itertools.permutations(sys.argv[1]):
p = "".join(s)
try:
e = (subprocess.check_output(['dc', '-e', p, '-e', 'p'], stderr=devnull))
e = int(e)
if 0 < e <= 120:
r[e] = p
except e:
pass
for i in sorted(r):
print("%5s: %3d" % (r[i], i))
print("TOTAL COUNT = %d numbers" % len(r))
```
---
Two other strings which give the same score of 19 are `32d+*` and `*4zO+`.
[Answer]
## Smalltalk, 26 numbers
```
1235r
```
Explanation: 12r35 is a notation for using radix 12, and is thus 3\*12+5.
This can be verified in Squeak:
```
((Array streamContents: [:s |
'1235r' permutationsDo: [:each |
| eval |
eval := [Compiler evaluate: each] ifError: [nil].
(eval isInteger and: [eval >=1 and: [eval <= 120]]) ifTrue: [s nextPut: each copy -> eval]]])
collect: #value as: Set) sorted
```
gives:
```
#(1 2 3 5 28 31 33 37 38 41 42 47 55 58 63 66 67 68 71 76 82 86 105 107 108 116)
```
If we replace last line with:
```
sorted: #value ascending)
```
we then get the expressions:
```
'235r1' -> 1
'253r1' -> 1
'325r1' -> 1
'352r1' -> 1
'523r1' -> 1
'532r1' -> 1
'135r2' -> 2
'153r2' -> 2
'315r2' -> 2
'351r2' -> 2
'531r2' -> 2
'513r2' -> 2
'125r3' -> 3
'152r3' -> 3
'215r3' -> 3
'251r3' -> 3
'521r3' -> 3
'512r3' -> 3
'123r5' -> 5
'132r5' -> 5
'213r5' -> 5
'231r5' -> 5
'321r5' -> 5
'312r5' -> 5
'23r15' -> 28
'25r13' -> 28
'13r25' -> 31
'15r23' -> 33
'32r15' -> 37
'35r12' -> 37
'5r123' -> 38
'12r35' -> 41
'5r132' -> 42
'15r32' -> 47
'52r13' -> 55
'53r12' -> 55
'5r213' -> 58
'12r53' -> 63
'5r231' -> 66
'13r52' -> 67
'31r25' -> 67
'21r35' -> 68
'35r21' -> 71
'25r31' -> 76
'5r312' -> 82
'5r321' -> 86
'51r23' -> 105
'53r21' -> 107
'21r53' -> 108
'23r51' -> 116
```
I wanted to cheat and define a method r in Integer as
```
Integer>>r
^self \\ 120 + 1
```
Unfortunately, the compiler chops on 1235r because it recognizes an unfinished number with radix rather than a message r sent to 1235...
I could easily change the compiler too, but it's a bit too much of a cheat to my taste.
[Answer]
# Runic Enchantments, 19 numbers
```
234p@
```
Essentially 3 literals, the pow operator, and a "print the entire stack and terminate" command. `234p@` prints 812 (3^4 conxatenated with a 2).
[Full permutation list](https://tio.run/##NZNLaiVRDEPnWY6kcchWQo@ahsYEsv6XWD41KqEr2/Knvr7///3zer3Lmc9/H28Lfr@zYAKzL1mw3wHMMjHimPCmcYFhVmKAVzwmcyWbZ4K4NVfcNAFkmUYHUBu1w1MMM494NtzCs4VniwYtWrZo0KLlm4EAWnGEOCI8I5h9WXG/AaSMyDwicyv0KYTXlwANb5oBDEwEkzV2dlxwoztfBuw0IpYSsaYYz7euzWMavE2W0SOm5dukCghvcQG0RUfYaIVlKhlAM7cCT2MYDYzW84jbuHxZwG3cCL2A27jpLmPmPGbOd2IqEAxLuW5WHDzfKjZPaPDuccWhwTvMZRptQG3UDk8WTB5xNvwaDSAwvedLMwd6z1fhGPc2boQnthBbhLu3cb/FiTMUTed85wMjMseP2IRPEM/jeYTnEZ7H2NjBvl4/), note that `@` has been replaced by `ak@` in order to generate a newline between each result and a `>` has been added to insure that each line executes independently. Note also that the outputs are not in the same order as the programs that generated them (as some programs may terminate more quickly).
Many permutations print nothing (eg. `@234p` or `p234@`), but 19 do result in output within the allowable range.
Numbers possible (and one possible program that results in it; `.` indicates that those positions may be any of the remaining characters as it isn't executed):
```
2@... 2
3@... 3
4@... 4
23p@. 8
32p@. 9
42p@. 16
32@.. 23
42@.. 24
23@.. 32
43@.. 34
24@.. 42
34@.. 43
23p4@ 48
32p4@ 49
43p@. 64
34p@. 81
423p@ 84
432p@ 94
```
[Answer]
# APL, 27 numbers
The best set after brute-forcing all permutations of characters that made sense.
```
5789⊤
```
All permutations
```
[ 7958⊤ ] N/A
[ 98⊤75 ] 75
[ 985⊤7 ] 7
[ 98⊤57 ] 57
[ 8⊤957 ] 5
[ 8⊤795 ] 3
[ 8⊤975 ] 7
[ ⊤9587 ] N/A
[ 897⊤5 ] 5
[ 75⊤89 ] 14
[ 785⊤9 ] 9
[ 78⊤59 ] 59
[ 8579⊤ ] N/A
[ 8597⊤ ] N/A
[ 79⊤85 ] 6
[ ⊤5789 ] N/A
[ ⊤5879 ] N/A
[ 7⊤895 ] 6
[ 7⊤985 ] 5
[ 578⊤9 ] 9
[ 59⊤87 ] 28
[ 9758⊤ ] N/A
[ 7589⊤ ] N/A
[ 7598⊤ ] N/A
[ ⊤8759 ] N/A
[ 789⊤5 ] 5
[ ⊤8597 ] N/A
[ 9⊤578 ] 2
[ 8975⊤ ] N/A
[ 9⊤587 ] 2
[ 7859⊤ ] N/A
[ 57⊤98 ] 41
[ 895⊤7 ] 7
[ 89⊤57 ] 57
[ 978⊤5 ] 5
[ 58⊤97 ] 39
[ 8759⊤ ] N/A
[ 875⊤9 ] 9
[ 87⊤59 ] 59
[ 975⊤8 ] 8
[ 97⊤58 ] 58
[ ⊤7958 ] N/A
[ 7⊤859 ] 5
[ 85⊤79 ] 79
[ 5⊤798 ] 3
[ 5⊤978 ] 3
[ 95⊤87 ] 87
[ 859⊤7 ] 7
[ 8⊤579 ] 3
[ 759⊤8 ] 8
[ ⊤9758 ] N/A
[ 7⊤958 ] 6
[ 587⊤9 ] 9
[ 59⊤78 ] 19
[ 879⊤5 ] 5
[ 9875⊤ ] N/A
[ ⊤7589 ] N/A
[ ⊤5798 ] N/A
[ ⊤5978 ] N/A
[ 95⊤78 ] 78
[ 7985⊤ ] N/A
[ 987⊤5 ] 5
[ 8⊤597 ] 5
[ ⊤9857 ] N/A
[ 89⊤75 ] 75
[ 758⊤9 ] 9
[ ⊤7895 ] N/A
[ ⊤7985 ] N/A
[ 9578⊤ ] N/A
[ 9587⊤ ] N/A
[ 5798⊤ ] N/A
[ 5789⊤ ] N/A
[ 798⊤5 ] 5
[ ⊤9785 ] N/A
[ ⊤9875 ] N/A
[ 5⊤789 ] 4
[ 5⊤879 ] 4
[ 57⊤89 ] 32
[ 598⊤7 ] 7
[ 9785⊤ ] N/A
[ ⊤8579 ] N/A
[ 78⊤95 ] 17
[ ⊤8957 ] N/A
[ 9⊤758 ] 2
[ 8957⊤ ] N/A
[ 9⊤857 ] 2
[ 5978⊤ ] N/A
[ 5987⊤ ] N/A
[ 9⊤785 ] 2
[ 9⊤875 ] 2
[ 7895⊤ ] N/A
[ 579⊤8 ] 8
[ 97⊤85 ] 85
[ 589⊤7 ] 7
[ 8795⊤ ] N/A
[ ⊤7598 ] N/A
[ ⊤8795 ] N/A
[ ⊤8975 ] N/A
[ 7⊤589 ] 1
[ 857⊤9 ] 9
[ ⊤5897 ] N/A
[ ⊤5987 ] N/A
[ 85⊤97 ] 12
[ 8⊤759 ] 7
[ 958⊤7 ] 7
[ 5⊤897 ] 2
[ 5⊤987 ] 2
[ 5879⊤ ] N/A
[ 5897⊤ ] N/A
[ 75⊤98 ] 23
[ 795⊤8 ] 8
[ 79⊤58 ] 58
[ ⊤9578 ] N/A
[ 7⊤598 ] 3
[ 58⊤79 ] 21
[ 597⊤8 ] 8
[ 87⊤95 ] 8
[ 9857⊤ ] N/A
[ ⊤7859 ] N/A
[ 957⊤8 ] 8
```
] |
[Question]
[
Conceptually, this challenge is really simple. You're given a list of non-negative integers `ai`. If possible, find a non-negative integer `N`, such that the list consisting of `bi = ai XOR N` is sorted. If no such `N` exists, output should be anything that can't be mistaken for a valid `N`, e.g. a negative number, nothing at all, an error etc.
Here is an example:
```
[4, 7, 6, 1, 0, 3]
```
If we take every element in this list `XOR 5`, we get
```
[1, 2, 3, 4, 5, 6]
```
which is sorted. (Note that it is not a requirement for the resulting list to have unique elements and contain no gaps. If the result of such an operation was `[0, 1, 1, 3]` that would still be valid.) On the other hand for the list
```
[4, 7, 1, 6, 0, 3]
```
no such `N` exists.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Input may be in any convenient list or string format. You may assume that the `ai` are less than `231` each and that the list contains at least one element.
Your code must handle any of the test cases (especially the four large ones) in a matter of a few seconds.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test Cases
For every test case which doesn't return `-1` there's an infinite number of correct answers. The one listed here is the smallest one. Additional solutions exist by additionally setting bits which are the same across all integers in the input (notably those which are larger than the most-significant bit in the largest number of the list).
```
[4 7 6 1 0 3] => 5
[4 7 1 6 0 3] => -1
[0 1 3 4 6 7] => 0
[4 2 3 1] => 6
[2 3 0 0 7 7 4 5 11 11] => 2
[2 3 0 0 7 7 5 4 11 11] => -1
[1086101479 748947367 1767817317 656404978 1818793883 1143500039] => -1
[180522983 1885393660 751646477 367706848 331742205 724919510 850844696 2121330641 869882699 1831158987 542636180 1117249765 823387844 731663826 1762069894 240170102 1020696223 1212052937 2041219958 712044033 195249879 1871889904 1787674355 1849980586 1308879787 1743053674 1496763661 607071669 1987302942 178202560 1666170841 1035995406 75303032 1755269469 200581873 500680130 561748675 1749521426 1828237297 835004548 934883150 38711700 1978960635 209243689 1355970350 546308601 590319412 959613996 1956169400 140411967 112601925 88760619 1977727497 672943813 909069787 318174568 385280382 370710480 809689639 557034312 865578556 217468424 346250334 388513751 717158057 941441272 437016122 196344643 379529969 821549457 97008503 872313181 2105942402 603939495 143590999 1580192283 177939344 853074291 1288703007 1605552664 162070930 1325694479 850975127 681702163 1432762307 1994488829 780869518 4379756 602743458 1963508385 2115219284 1219523498 559301490 4191682 1918142271 169309431 346461371 1619467789 1521741606 1881525154] => -1
[37580156 64423492 87193676 91914964 93632157 96332899 154427982 176139560 184435039 228963836 230164674 279802291 301492375 309127664 345705721 370150824 380319820 403997410 410504675 416543032 418193132 424733526 428149607 435596038 477224208 515649925 519407995 525469350 614538124 624884850 642649261 653488151 679260270 685637235 690613185 739141066 825795124 832026691 832633584 833213619 852655299 913744258 917674993 921902522 925691996 931307936 954676047 972992595 997654606 1020009811 1027484648 1052748108 1071580605 1108881241 1113730139 1122392118 1154042251 1170901568 1180031842 1180186856 1206428383 1214066097 1242934611 1243983997 1244736049 1262979035 1312007069 1312030297 1356274316 1368442960 1377432523 1415342434 1471294243 1529353536 1537868913 1566069818 1610578189 1612277199 1613646498 1639183592 1668015280 1764022840 1784234921 1786654280 1835593744 1849372222 1875931624 1877593764 1899940939 2007896363 2023046907 2030492562 2032619034 2085680072 2085750388 2110824853 2123924948 2131327206 2134927760 2136423634] => 0
[1922985547 1934203179 1883318806 1910889055 1983590560 1965316186 2059139291 2075108931 2067514794 2117429526 2140519185 1659645051 1676816799 1611982084 1736461223 1810643297 1753583499 1767991311 1819386745 1355466982 1349603237 1360540003 1453750157 1461849199 1439893078 1432297529 1431882086 1427078318 1487887679 1484011617 1476718655 1509845392 1496496626 1583530675 1579588643 1609495371 1559139172 1554135669 1549766410 1566844751 1562161307 1561938937 1123551908 1086169529 1093103602 1202377124 1193780708 1148229310 1144649241 1257633250 1247607861 1241535002 1262624219 1288523504 1299222235 840314050 909401445 926048886 886867060 873099939 979662326 963003815 1012918112 1034467235 1026553732 568519178 650996158 647728822 616596108 617472393 614787483 604041145 633043809 678181561 698401105 776651230 325294125 271242551 291800692 389634988 346041163 344959554 345547011 342290228 354762650 442183586 467158857 412090528 532898841 534371187 32464799 21286066 109721665 127458375 192166356 146495963 142507512 167676030 236532616 262832772] => 1927544832
[1922985547 1934203179 1883318806 1910889055 1983590560 1965316186 2059139291 2075108931 2067514794 2117429526 2140519185 1659645051 1676816799 1611982084 1736461223 1810643297 1753583499 1767991311 1819386745 1355466982 1349603237 1360540003 1453750157 1461849199 1439893078 1432297529 1431882086 1427078318 1487887679 1484011617 1476718655 1509845392 1496496626 1583530675 1579588643 1609495371 1559139172 1554135669 1549766410 1566844751 1562161307 1561938937 1123551908 1086169529 1093103602 1202377124 1193780708 1148229310 1144649241 1257633250 1241535002 1247607861 1262624219 1288523504 1299222235 840314050 909401445 926048886 886867060 873099939 979662326 963003815 1012918112 1034467235 1026553732 568519178 650996158 647728822 616596108 617472393 614787483 604041145 633043809 678181561 698401105 776651230 325294125 271242551 291800692 389634988 346041163 344959554 345547011 342290228 354762650 442183586 467158857 412090528 532898841 534371187 32464799 21286066 109721665 127458375 192166356 146495963 142507512 167676030 236532616 262832772] => -1
```
Finally, here are four very large test cases to ensure that submissions are sufficiently efficient:
* [Test Case 1](http://pastebin.com/P96PNi79) should yield `-1`.
* [Test Case 2](http://pastebin.com/zCNLMsx9) should yield `0`.
* [Test Case 3](http://pastebin.com/GFLBXn5b) should yield `1096442624`.
* [Test Case 4](http://pastebin.com/6F1Yn3gG) should yield `-1`.
### Why would anyone do this?
It occurred to me the other day that a XOR operation can "sort" an array, which makes it possible to perform a binary search on the array in *O(log n)* without having to sort it first. It appears to be possible to determine `N` in pseudolinear time, which would make this a faster alternative to most sorting algorithms, and it doesn't have the memory requirements of radix sort. Of course, a straight linear search through the unsorted array will be faster, but if you want to search the same array many times, a single linear pre-computation can bring down the time required for each search significantly.
Unfortunately, the class of lists this works on is rather limited (uniformly random distributions are unlikely to admit an `N`).
An interesting question is whether there are other bijective functions which are easier to check and/or are applicable for a wider class of lists.
[Answer]
# Pyth, ~~40~~ ~~36~~ ~~31~~ 30 bytes
```
Ju.|G^2slHxMf>FT.:Q2Z|tSIxRJQJ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite=0&test_suite_input=%5B4%2C7%2C6%2C1%2C0%2C3%5D%0A%5B4%2C7%2C1%2C6%2C0%2C3%5D%0A%5B0%2C1%2C3%2C4%2C6%2C7%5D%0A%5B4%2C2%2C3%2C1%5D%0A%5B2%2C3%2C0%2C0%2C7%2C7%2C4%2C5%2C11%2C11%5D%0A%5B2%2C3%2C0%2C0%2C7%2C7%2C5%2C4%2C11%2C11%5D%0A%5B1086101479%2C748947367%2C1767817317%2C656404978%2C1818793883%2C1143500039%5D%0A%5B37580156%2C64423492%2C87193676%2C91914964%2C93632157%2C96332899%2C154427982%2C176139560%2C184435039%2C228963836%2C230164674%2C279802291%2C301492375%2C309127664%2C345705721%2C370150824%2C380319820%2C403997410%2C410504675%2C416543032%2C418193132%2C424733526%2C428149607%2C435596038%2C477224208%2C515649925%2C519407995%2C525469350%2C614538124%2C624884850%2C642649261%2C653488151%2C679260270%2C685637235%2C690613185%2C739141066%2C825795124%2C832026691%2C832633584%2C833213619%2C852655299%2C913744258%2C917674993%2C921902522%2C925691996%2C931307936%2C954676047%2C972992595%2C997654606%2C1020009811%2C1027484648%2C1052748108%2C1071580605%2C1108881241%2C1113730139%2C1122392118%2C1154042251%2C1170901568%2C1180031842%2C1180186856%2C1206428383%2C1214066097%2C1242934611%2C1243983997%2C1244736049%2C1262979035%2C1312007069%2C1312030297%2C1356274316%2C1368442960%2C1377432523%2C1415342434%2C1471294243%2C1529353536%2C1537868913%2C1566069818%2C1610578189%2C1612277199%2C1613646498%2C1639183592%2C1668015280%2C1764022840%2C1784234921%2C1786654280%2C1835593744%2C1849372222%2C1875931624%2C1877593764%2C1899940939%2C2007896363%2C2023046907%2C2030492562%2C2032619034%2C2085680072%2C2085750388%2C2110824853%2C2123924948%2C2131327206%2C2134927760%2C2136423634%5D%0A%5B1922985547%2C1934203179%2C1883318806%2C1910889055%2C1983590560%2C1965316186%2C2059139291%2C2075108931%2C2067514794%2C2117429526%2C2140519185%2C1659645051%2C1676816799%2C1611982084%2C1736461223%2C1810643297%2C1753583499%2C1767991311%2C1819386745%2C1355466982%2C1349603237%2C1360540003%2C1453750157%2C1461849199%2C1439893078%2C1432297529%2C1431882086%2C1427078318%2C1487887679%2C1484011617%2C1476718655%2C1509845392%2C1496496626%2C1583530675%2C1579588643%2C1609495371%2C1559139172%2C1554135669%2C1549766410%2C1566844751%2C1562161307%2C1561938937%2C1123551908%2C1086169529%2C1093103602%2C1202377124%2C1193780708%2C1148229310%2C1144649241%2C1257633250%2C1247607861%2C1241535002%2C1262624219%2C1288523504%2C1299222235%2C840314050%2C909401445%2C926048886%2C886867060%2C873099939%2C979662326%2C963003815%2C1012918112%2C1034467235%2C1026553732%2C568519178%2C650996158%2C647728822%2C616596108%2C617472393%2C614787483%2C604041145%2C633043809%2C678181561%2C698401105%2C776651230%2C325294125%2C271242551%2C291800692%2C389634988%2C346041163%2C344959554%2C345547011%2C342290228%2C354762650%2C442183586%2C467158857%2C412090528%2C532898841%2C534371187%2C32464799%2C21286066%2C109721665%2C127458375%2C192166356%2C146495963%2C142507512%2C167676030%2C236532616%2C262832772%5D&input=%5B4%2C7%2C6%2C1%2C0%2C3%5D&code=Ju.%7CG%5E2slHxMf%3EFT.%3AQ2Z%7CtSIxRJQJ) or [Test Suite](http://pyth.herokuapp.com/?test_suite=1&test_suite_input=%5B4%2C7%2C6%2C1%2C0%2C3%5D%0A%5B4%2C7%2C1%2C6%2C0%2C3%5D%0A%5B0%2C1%2C3%2C4%2C6%2C7%5D%0A%5B4%2C2%2C3%2C1%5D%0A%5B2%2C3%2C0%2C0%2C7%2C7%2C4%2C5%2C11%2C11%5D%0A%5B2%2C3%2C0%2C0%2C7%2C7%2C5%2C4%2C11%2C11%5D%0A%5B1086101479%2C748947367%2C1767817317%2C656404978%2C1818793883%2C1143500039%5D%0A%5B37580156%2C64423492%2C87193676%2C91914964%2C93632157%2C96332899%2C154427982%2C176139560%2C184435039%2C228963836%2C230164674%2C279802291%2C301492375%2C309127664%2C345705721%2C370150824%2C380319820%2C403997410%2C410504675%2C416543032%2C418193132%2C424733526%2C428149607%2C435596038%2C477224208%2C515649925%2C519407995%2C525469350%2C614538124%2C624884850%2C642649261%2C653488151%2C679260270%2C685637235%2C690613185%2C739141066%2C825795124%2C832026691%2C832633584%2C833213619%2C852655299%2C913744258%2C917674993%2C921902522%2C925691996%2C931307936%2C954676047%2C972992595%2C997654606%2C1020009811%2C1027484648%2C1052748108%2C1071580605%2C1108881241%2C1113730139%2C1122392118%2C1154042251%2C1170901568%2C1180031842%2C1180186856%2C1206428383%2C1214066097%2C1242934611%2C1243983997%2C1244736049%2C1262979035%2C1312007069%2C1312030297%2C1356274316%2C1368442960%2C1377432523%2C1415342434%2C1471294243%2C1529353536%2C1537868913%2C1566069818%2C1610578189%2C1612277199%2C1613646498%2C1639183592%2C1668015280%2C1764022840%2C1784234921%2C1786654280%2C1835593744%2C1849372222%2C1875931624%2C1877593764%2C1899940939%2C2007896363%2C2023046907%2C2030492562%2C2032619034%2C2085680072%2C2085750388%2C2110824853%2C2123924948%2C2131327206%2C2134927760%2C2136423634%5D%0A%5B1922985547%2C1934203179%2C1883318806%2C1910889055%2C1983590560%2C1965316186%2C2059139291%2C2075108931%2C2067514794%2C2117429526%2C2140519185%2C1659645051%2C1676816799%2C1611982084%2C1736461223%2C1810643297%2C1753583499%2C1767991311%2C1819386745%2C1355466982%2C1349603237%2C1360540003%2C1453750157%2C1461849199%2C1439893078%2C1432297529%2C1431882086%2C1427078318%2C1487887679%2C1484011617%2C1476718655%2C1509845392%2C1496496626%2C1583530675%2C1579588643%2C1609495371%2C1559139172%2C1554135669%2C1549766410%2C1566844751%2C1562161307%2C1561938937%2C1123551908%2C1086169529%2C1093103602%2C1202377124%2C1193780708%2C1148229310%2C1144649241%2C1257633250%2C1247607861%2C1241535002%2C1262624219%2C1288523504%2C1299222235%2C840314050%2C909401445%2C926048886%2C886867060%2C873099939%2C979662326%2C963003815%2C1012918112%2C1034467235%2C1026553732%2C568519178%2C650996158%2C647728822%2C616596108%2C617472393%2C614787483%2C604041145%2C633043809%2C678181561%2C698401105%2C776651230%2C325294125%2C271242551%2C291800692%2C389634988%2C346041163%2C344959554%2C345547011%2C342290228%2C354762650%2C442183586%2C467158857%2C412090528%2C532898841%2C534371187%2C32464799%2C21286066%2C109721665%2C127458375%2C192166356%2C146495963%2C142507512%2C167676030%2C236532616%2C262832772%5D&input=%5B4%2C7%2C6%2C1%2C0%2C3%5D&code=Ju.%7CG%5E2slHxMf%3EFT.%3AQ2Z%7CtSIxRJQJ)
Each of the big test-cases finishes in a couple of seconds.
### Explanation:
First I'll explain the method and why it works. I'll do this with the example list: `[7, 2, 13, 9]`.
The first two numbers are already wrong (`7 > 2`). We want to xor with some number to change that inequality symbol (`7 xor X < 2 xor X`). Since xor operates on the binary representations, lets look at them.
```
7 = 1 1 1
2 = 1 0
```
When we apply xor with some number to each number, the value at some positions will change. If you change the values at the first position (`2^0`), the inequality symbol doesn't change. The same thing happens, when we change the values at the second position (`2^1`). Also the symbol won't change if we change values at the fourth, fifth, ... positions (`2^3`, `2^4`, ...). The inequality symbol only changes direction, if we change the third position (`2^2`).
```
7 xor 2^0 = 1 1 0 7 xor 2^1 = 1 0 1 7 xor 2^2 = 1 1 7 xor 2^3 = 1 1 1 1
2 xor 2^0 = 1 1 2 xor 2^1 = 0 2 xor 2^2 = 1 1 0 2 xor 2^3 = 1 0 1 0
6 > 3 5 > 0 3 < 6 15 > 10
```
If we change multiple positions at once, of course the same thing happens. If any of the positions we change is the third, than the inequality symbol changes, otherwise not.
The next pair is already sorted: `2 < 13`. If we look at the binary representation, we notice, that we can xor anything to it and the inequality symbol is still correct, except when we change the fourth position (`2^3`).
```
2 = 1 0 2 xor 2^3 = 1 0 1 0
13 = 1 1 0 1 13 xor 2^3 = 1 0 1
2 < 13 10 > 5
```
So we don't want to change the fourth position. For the next pair we want to change something, since `13 > 9`. Here we again have to change the third position.
```
13 = 1 1 0 1 13 xor 2^2 = 1 0 0 1
9 = 1 0 0 1 9 xor 2^2 = 1 1 0 1
13 > 9 9 < 13
```
Now recap: To end up in a sorted list, we again have to change the third position and don't want to change the fourth position. All other positions doesn't matter. The smallest number is simply `4 = 0100`. Other choices would be `5 = 0101`, `6 = 0110`, `7 = 0111`, `20 = 10100`, `21 = 10101`, ...
Xoring with `4` will result in the list `[3, 6, 9, 13]`, with `6` will get `[1, 4, 11, 15]`, and with `21` will get `[18, 23, 24, 28]`.
So for a list, we need to find the positions, that will change the inequality symbol if it points into the wrong direction. We find the position simply by taking the most significant bit of the xor of the pair. We combine all these position (with or) to result in a candidate number. The we check, if we haven't accidentally destroyed the already sorted pairs.
```
Ju.|G^2slHxMf>FT.:Q2Z implicit: Q = input list
.:Q2 all substrings of length 2
f>FT filter for pairs that are in descending order
xM apply xor to each such pair
u Z reduce this list, start value G = 0
iteration value is H
^2slH 2 to the power of floor(logarithm base 2 of H)
this gives a mask representing the most significant bit
.|G update G with the bitwise or of G and ^
J store the result in J
|tSIxRJQJ
xRJQ xor each element of the input list with J
SI check if the list is sorted
t subtract 1
| J this number or (if equal to zero) J
implicit print
```
[Answer]
# Ruby 2, 119
```
->a,*o{a.each_cons(2){|x,y|x==y||o[i=(x^y).bit_length-1]==1-(o[i]=x[i])&&(return-1)};(o.map(&:to_i).reverse*'').to_i 2}
```
Runs in 42 milliseconds on the large test cases.
Ungolfed:
```
def first_differing_bit(a,b)
(a^b).bit_length - 1
end
def xort(ary)
required_bits = []
ary.each_cons(2) do |a,b|
i = first_differing_bit(a,b)
if i > -1
bit = a[i]
if required_bits[i] && required_bits[i] != bit
return -1
else
required_bits[i] = bit
end
end
end
required_bits.map(&:to_i).reverse.join.to_i(2)
end
```
For once I wrote the ungolfed version first, then golfed it, since figuring out the right algorithm was a challenge in itself.
I actually tried to write something like this a few years ago to make a binary tree structure that would locally self-balance by letting each node redefine its comparison function dynamically. At first I thought I could just use xor, but as you say for random data there's unlikely to be a viable value.
[Answer]
# Julia, ~~174~~ ~~144~~ ~~77~~ ~~75~~ 71
[EDIT] Thanks to Alex A. for anonymizing & various shorthands.
[EDIT 2] Replaced my own implementation by the builtin `issorted()`.
Runs in linear time and handles the big files without noticeable delay. Works just as well for negative numbers.
```
l->(r=0;s=issorted;for d=63:-1:0 s((l$r).>>d)||(r$=2^d)end;s(l$r)?r:[])
```
Another variant that calculates the result closest to a given key (the above returns the smallest).
```
(l,r)->(s=issorted;for d=63:-1:0 s((l$r).>>d)||(r$=2^d)end;s(l$r)?r:[])
```
usage:
```
julia> xort = l->(r=0;s=issorted;for d=63:-1:0 s((l$r).>>d)||(r$=2^d)end;s(l$r)?r:[])
(anonymous function)
julia> xort([4 7 6 1 0 3])
5
```
Example, step by step: `[4 7 6 1 0 3] => 5`
```
Start with:
4 0b0100
7 0b0111
6 0b0110
1 0b0001
0 0b0000
3 0b0011
result 0b0000
If the first n bits are sorted, do nothing.
0b0
0b0
0b0
0b0
0b0
0b0
result 0b0000
^
If the first n bits are not sorted, flip the nth bit.
0b01 0b00
0b01 0b00
0b01 0b00
0b00 => 0b01
0b00 0b01
0b00 0b01
result 0b0000 0b0100
^ ^
0b000
0b001
0b001
0b010
0b010
0b011
result 0b0100
^
0b0000 0b0001 1
0b0011 0b0010 2
0b0010 0b0011 3
0b0101 => 0b0100 4
0b0100 0b0101 5
0b0111 0b0110 6
result 0b0100 0b0101 5
^ ^
If the bit flip does not sort the truncated integers, xorting is
impossible. We continue anyway and check for success in the end.
```
[Answer]
# Jelly, 25 bytes
```
ṡ2Zµ^/Bo1Ḅ‘×>/|/H
Ç-¹^Ç¥?
```
The latest commits postdate this challenge, but the above code works with [this revision](https://github.com/DennisMitchell/jelly/tree/7ee6838e9979ef33cab5085f413b3b6855e1ba46), which predates it. [Try it online!](http://jelly.tryitonline.net/#code=4bmhMlrCtV4vQm8x4biE4oCYw5c-L3wvSArDhy3CuV7Dh8KlPw&input=&args=WzQsIDcsIDYsIDEsIDAsIDNd)
To run the large test cases, depending on your shell, it may be necessary to wrap the above code in a program that reads input from STDIN. [Try it online!](http://jelly.tryitonline.net/#code=4bmhMlrCtV4vQm8x4biE4oCYw5c-L3wvSArDhy3CuV7Dh8KlPwrGk8OH&input=WzQsIDcsIDYsIDEsIDAsIDNd)
### Test cases
```
$ xxd -c 13 -g 1 xort-prog.jelly
0000000: ae 32 5a 8c 5e 2f 42 6f 31 a4 b6 94 3e .2Z.^/Bo1...>
000000d: 2f 7c 2f 48 0a 92 2d 8e 5e 92 84 3f /|/H..-.^..?
$ ./jelly f xort-prog.jelly '[4, 7, 6, 1, 0, 3]'; echo
5
$ ./jelly f xort-prog.jelly '[4, 7, 1, 6, 0, 3]'; echo
-1
$ ./jelly f xort-prog.jelly '[0, 1, 3, 4, 6, 7]'; echo
0
$ ./jelly f xort-prog.jelly '[4, 2, 3, 1]'; echo
6
$ ./jelly f xort-prog.jelly '[2, 3, 0, 0, 7, 7, 4, 5, 11, 11]'; echo
2
$ ./jelly f xort-prog.jelly '[2, 3, 0, 0, 7, 7, 5, 4, 11, 11]'; echo
-1
$
$ wget -q http://pastebin.com/raw/{P96PNi79,zCNLMsx9,GFLBXn5b,6F1Yn3gG}
$ xxd -c 14 -g 1 xort-func.jelly
0000000: ae 32 5a 8c 5e 2f 42 6f 31 a4 b6 94 3e 2f .2Z.^/Bo1...>/
000000e: 7c 2f 48 0a 92 2d 8e 5e 92 84 3f 0a a0 92 |/H..-.^..?...
$ tr \ , < P96PNi79 | time -f '\n%es' ./jelly f xort-func.jelly
-1
3.69s
$ tr \ , < zCNLMsx9 | time -f '\n%es' ./jelly f xort-func.jelly
0
2.78s
$ tr \ , < GFLBXn5b | time -f '\n%es' ./jelly f xort-func.jelly
1096442624
2.73s
$ tr \ , < 6F1Yn3gG | time -f '\n%es' ./jelly f xort-func.jelly
-1
2.70s
```
### Idea
This uses a the same approach as [@Jakube's answer](https://codegolf.stackexchange.com/a/68131), but my implementation is a bit different.
Jelly has no sorting yet, so we compute a xorting candidate, XOR the input list with it, compute a xorting candidate of the XORed list, and check if the new candidate is zero. If it is, we print the first candidate; otherwise, we print **-1**.
Also, Jelly seems to have no sane way to cast to integer yet (even integer division can return floats), so I had to come up with a rather creative way of rounding a list of numbers down to the next power of **2**. Rather than log-floor-pow, I convert all integers to binary, replace all binary digits with **1**, convert back to integer, add **1**, and divide by **2**.
### Code
```
ṡ2Zµ^/Bo1Ḅ‘×>/|/H Helper link. Argument: M (list of integers)
ṡ2 Yield all overlapping slices of length 2 (pairs) of M.
Z Zip to group first and second coordinates.
µ Begin a new, monadic chain.
^/ XOR the corresponding coordinates.
B Convert all results to binary.
o1 OR (logical) all binary digits with 1.
Ḅ Convert back to integer.
‘ Increment all integers.
×>/ Multiply each rounded (a ^ b) by (a > b).
This replaces (a ^ b) with 0 unless a > b.
|/ OR all results.
H Halve the result.
Ç-¹^Ç¥? Main link. Input: L (list of integers)
Ç Call the helper link on L. Result: C (integer)
¥ Create a dyadic chain:
^ XOR the elements of L with C.
Ç Call the helper link on the result.
? If the result in non-zero:
- Yield -1.
¹ Else, yield C.
```
[Answer]
# JavaScript (ES6) 85 ~~97 114 117~~
**Edit** Removed stupid,useless last AND
**Edit2** Top bit search shortened
**Edit3** Wow! I discovered that ES6 (almost) has a *builtin* to find the top bit (Math.clz32 counts the top 0 bits)
This is based on the solution of @Jakube (pls upvote that). I could never have found it by myself.
Here I go one step forward, iterating the list once and keeping a bit mask with the bits that have to be flipped, and another one with the bits that have to be kept.
If there is an overlap of the bit masks, then no solution is possible, else the solution is "bits to flip"
As binary operations in javascript work only on signed 32 bits integers, the return value is a signed 32 bit integer that can be negative or 0.
If there is no solution the return value is 'X'
```
l=>l.map(v=>(t=v^p&&1<<(31-Math.clz32(v^p)),v>p?k|=t:c|=t,p=v),p=l[c=k=0])&&c&k?"X":c
```
**Test**
[The longer tests on jsfiddle](https://jsfiddle.net/x3wk2hje/4/)
```
X=l=>l.map(v=>(t=v^p&&1<<(31-Math.clz32(v^p)),v>p?k|=t:c|=t,p=v),p=l[c=k=0])&&c&k?"X":c
console.log=x=>O.textContent+=x+'\n'
;[
[[4,7,6,1,0,3], 5],
[[4,7,1,6,0,3], 'X'],
[[0,1,3,4,6,7], 0],
[[4,2,3,1], 6],
[[2,3,0,0,7,7,4,5,11,11], 2],
[[2,3,0,0,7,7,5,4,11,11], 'X'],
[[1086101479,748947367,1767817317,656404978,1818793883,1143500039],'X'],
[[180522983,1885393660,751646477,367706848,331742205,724919510,850844696,2121330641,869882699,1831158987,542636180,1117249765,823387844,731663826,1762069894,240170102,1020696223,1212052937,2041219958,712044033,195249879,1871889904,1787674355,1849980586,1308879787,1743053674,1496763661,607071669,1987302942,178202560,1666170841,1035995406,75303032,1755269469,200581873,500680130,561748675,1749521426,1828237297,835004548,934883150,38711700,1978960635,209243689,1355970350,546308601,590319412,959613996,1956169400,140411967,112601925,88760619,1977727497,672943813,909069787,318174568,385280382,370710480,809689639,557034312,865578556,217468424,346250334,388513751,717158057,941441272,437016122,196344643,379529969,821549457,97008503,872313181,2105942402,603939495,143590999,1580192283,177939344,853074291,1288703007,1605552664,162070930,1325694479,850975127,681702163,1432762307,1994488829,780869518,4379756,602743458,1963508385,2115219284,1219523498,559301490,4191682,1918142271,169309431,346461371,1619467789,1521741606,1881525154],'X'],
[[37580156,64423492,87193676,91914964,93632157,96332899,154427982,176139560,184435039,228963836,230164674,279802291,301492375,309127664,345705721,370150824,380319820,403997410,410504675,416543032,418193132,424733526,428149607,435596038,477224208,515649925,519407995,525469350,614538124,624884850,642649261,653488151,679260270,685637235,690613185,739141066,825795124,832026691,832633584,833213619,852655299,913744258,917674993,921902522,925691996,931307936,954676047,972992595,997654606,1020009811,1027484648,1052748108,1071580605,1108881241,1113730139,1122392118,1154042251,1170901568,1180031842,1180186856,1206428383,1214066097,1242934611,1243983997,1244736049,1262979035,1312007069,1312030297,1356274316,1368442960,1377432523,1415342434,1471294243,1529353536,1537868913,1566069818,1610578189,1612277199,1613646498,1639183592,1668015280,1764022840,1784234921,1786654280,1835593744,1849372222,1875931624,1877593764,1899940939,2007896363,2023046907,2030492562,2032619034,2085680072,2085750388,2110824853,2123924948,2131327206,2134927760,2136423634],0],
[[1922985547,1934203179,1883318806,1910889055,1983590560,1965316186,2059139291,2075108931,2067514794,2117429526,2140519185,1659645051,1676816799,1611982084,1736461223,1810643297,1753583499,1767991311,1819386745,1355466982,1349603237,1360540003,1453750157,1461849199,1439893078,1432297529,1431882086,1427078318,1487887679,1484011617,1476718655,1509845392,1496496626,1583530675,1579588643,1609495371,1559139172,1554135669,1549766410,1566844751,1562161307,1561938937,1123551908,1086169529,1093103602,1202377124,1193780708,1148229310,1144649241,1257633250,1247607861,1241535002,1262624219,1288523504,1299222235,840314050,909401445,926048886,886867060,873099939,979662326,963003815,1012918112,1034467235,1026553732,568519178,650996158,647728822,616596108,617472393,614787483,604041145,633043809,678181561,698401105,776651230,325294125,271242551,291800692,389634988,346041163,344959554,345547011,342290228,354762650,442183586,467158857,412090528,532898841,534371187,32464799,21286066,109721665,127458375,192166356,146495963,142507512,167676030,236532616,262832772],1927544832],
[[1922985547,1934203179,1883318806,1910889055,1983590560,1965316186,2059139291,2075108931,2067514794,2117429526,2140519185,1659645051,1676816799,1611982084,1736461223,1810643297,1753583499,1767991311,1819386745,1355466982,1349603237,1360540003,1453750157,1461849199,1439893078,1432297529,1431882086,1427078318,1487887679,1484011617,1476718655,1509845392,1496496626,1583530675,1579588643,1609495371,1559139172,1554135669,1549766410,1566844751,1562161307,1561938937,1123551908,1086169529,1093103602,1202377124,1193780708,1148229310,1144649241,1257633250,1241535002,1247607861,1262624219,1288523504,1299222235,840314050,909401445,926048886,886867060,873099939,979662326,963003815,1012918112,1034467235,1026553732,568519178,650996158,647728822,616596108,617472393,614787483,604041145,633043809,678181561,698401105,776651230,325294125,271242551,291800692,389634988,346041163,344959554,345547011,342290228,354762650,442183586,467158857,412090528,532898841,534371187,32464799,21286066,109721665,127458375,192166356,146495963,142507512,167676030,236532616,262832772],'X']
].forEach(t=>{
var i=t[0],k=t[1],r=X(i)
console.log((k==r?'OK ':'Error (expected '+k+') ')+r+' for input '+i)
})
```
```
<pre id=O></pre>
```
[Answer]
## ES6, 84 bytes
```
a=>(i=e=0,a.reduce((x,y)=>(z=1<<31-Math.clz32(x^y),x>y?i|=z:y>x?e|=z:z,y)),i&e?-1:i)
```
Edit: By the time it took me to write the answer the algorithm had already been independently posted by @Jakube; my algorithm is the same but this wasn't plagiarism honest! Also I notice another JavaScript answer has since been posted too. Sorry if I'm stepping on anyone's toes.
Edit: Saved 8 bytes thanks to edc65.
[Answer]
# C, 144 bytes
```
#include <strings.h>
#include <stdio.h>
m[2],l,i;main(v){while(scanf("%d",&v)==1)m[l<v]|=(i++&&v^l)<<~-fls(v^l),l=v;printf("%d",*m&m[1]?-1:*m);}
```
This is almost standard C99 (it misses a few `int` specifiers and has 1 argument for `main`). It also relies on `0<<-1` being 0 (which seems to be true when compiled with Clang at least — I haven't tested others)
I've taken Jakube's method and ported it to C. I think it does surprisingly well size-wise for C. It's also super-fast (0.061s to run all test files, including the massive 4). It takes input from STDIN and will print the matching value or -1 to STDOUT, so run it with one of:
```
echo "4 7 6 1 0 0 3" | ./xort
./xort < file.txt
```
Breakdown:
```
// Globals initialise to 0
m[2], // Stores our bit masks
// (m[0]=CHANGE, m[1]=MUST NOT CHANGE)
l, // Last value
i; // Current iteration
main(v){
while(scanf("%d",&v)==1) // Read each value in turn
m[l<v]|= // If they are sorted, we mark a bit as
// MUST NOT CHANGE (m[1]), otherwise we
// mark as CHANGE (m[0])
(i++&&v^l) // If this is the first iteration,
// or the value is unchanged, mark nothing
<<~-fls(v^l), // Mark the highest bit which has changed
// = (1<<(fls(v^l)-1)
l=v; // Update last value
printf("%d",
*m&m[1] // Check if result is valid (if any bits
// are both MUST NOT CHANGE and CHANGE,
// it is not valid)
?-1 // Print -1 on failure
:*m); // Print value on success
}
```
[Answer]
# Julia, 124 bytes
```
f(x,g=0)=issorted(([g|=2^Int(log2(h)÷1)for h=map(k->k[1]$k[2],filter(j->j[1]>=j[2],[x[i-1:i]for i=2:endof(x)]))];g)$x)?g:-1
```
This is a function that accepts an integer array and returns an integer. It uses [Jakube's approach](https://codegolf.stackexchange.com/a/68131/20469).
Ungolfed:
```
function f{T<:Integer}(x::Array{T,1}, g::T=0)
# Get all pairs of elements in the input array
pairs = [x[i-1:i] for i = 2:endof(x)]
# Filter to pairs in descending order
desc = filter(j -> j[1] ≥ j[2], pairs)
# Map XOR over these pairs
xord = map(k -> k[1] $ k[2], desc)
# For each element of this array, update the
# parameter g (which defaults to 0) as the
# bitwise OR of itself and 2^floor(log2(element))
for h in xord
g |= 2^Int(log2(h) ÷ 1)
end
# If the array constructed as g XOR the input is
# sorted, we've found our answer! Otherwise -1.
return issorted(g $ x) ? g : -1
end
```
[Answer]
# Python 2, 204 bytes
```
def f(a):
m=n=0
for i in range(32):
b=2**(31-i);m|=b
for n in[n,n|b]:
if not q(a,m,n):break
else:return-1
return n
def q(a,m,n):
if a:p=a[0]&m^n
for t in a:
t=t&m^n
if t<p:return 1
p=t
```
The input is passed as a list to function f.
This code figures out the value of N (named n in the program) one bit at a time, starting with the most significant bit. (the "for i" loop)
For each bit position, the "for n" loop first tries using 0 for that bit of n. If that doesn't work, it tries using 1. If neither of these works, then there is no solution. Note that the else clause is on the "for n" loop, not the if statement. In Python, a for statement can have an else clause, which is executed after the loop runs to completion, but is *not* executed if we break out of the loop.
The q function checks for problems with the list order given the list (a), a bit mask (m), and the value to be xored with each value in the list (n). It returns 1 if there is a problem with the ordering, or None if the order is ok. None is the default return value, so that saved me several characters.
This code handles an empty list or a list with 1 element correctly, returning 0. The "if a:" in function q is there only to avoid an IndexError exception when the list is empty. So 5 more bytes could be removed if handling empty lists isn't required.
On my computer, large test case #3 took 0.262 seconds. #2 took about the same. All the test cases together took 0.765 seconds.
[Answer]
## CJam, 37 bytes
```
q~_2ew{:>},{:^2mLi2\#}%0+:|_@f^_$=\W?
```
[Test it here.](http://cjam.aditsu.net/#code=q~_2ew%7B%3A%3E%7D%2C%7B%3A%5E2mLi2%5C%23%7D%250%2B%3A%7C_%40f%5E_%24%3D%5CW%3F&input=%5B4%207%206%201%200%203%5D)
This uses the same algorithm as several of the other answers. It's essentially my reference implementation which I used to create the test cases. However, I did steal Jakube's trick of checking only the offending pairs and simply trying out the result with a sort. That breaks the pseudolinearity, but *O(n log n)* is still fast enough for the test cases. My original code also checked the pairs that are already in order, and built up a list of bits which must not be toggled in order to keep their relative order, and checked at the end that there are no overlaps between the two bit masks. This algorithm was originally suggested by [Ben Jackson](http://meta.codegolf.stackexchange.com/users/1829/ben-jackson).
[Answer]
# Python 2, ~~226~~ 214 bytes
Simpleish algorithm, built it yesterday, golfed today.
```
o=input()
s=sorted
p=s(set(o),key=o.index)
n=q=0
while 1:
a=1
while 1-q and p[0]<p[1]:p=p[1:];q=len(p)==1
if q:break
while not p[0]^a<p[1]^a:a*=2
n+=a;p=[i^a for i in p]
t=[a^n for a in o]
print[-1,n][s(t)==t]
```
Ungolfed:
```
def xor(a,b): return a^b
def rm_dupes(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def rm_sorted(seq):
while seq[0] < seq[1]:
seq = seq[1:]
if len(seq) == 1: return seq
return seq
inp = input()
oi = inp
inp = rm_dupes(inp)
n=0
old_inp=0
while old_inp != inp:
old_inp = inp
inp = rm_sorted(inp)
if len(inp)==1:break
highest_set0 = len(bin(inp[0]))-3 # bin returns in form 0bxxx
highest_set1 = len(bin(inp[1]))-3 # bin returns in form 0bxxx
if highest_set1 == 0:
try:
t0 = max(int(bin(inp[0])[3:], 2), 1)
except ValueError: toggle_amount = 1
else: toggle_amount = t0^inp[0]
else:
fallen = False
for i in xrange(max(highest_set0,highest_set1)+1):
toggle_amount = 2**i
if inp[0]^toggle_amount < inp[1]^toggle_amount:
fallen = True
break
assert(fallen)
n+=toggle_amount
inp = [i^toggle_amount for i in inp]
out=map(xor, oi, [n]*len(oi))
if sorted(out)==out :print n
else:print -1
```
[Answer]
# C, 312 bytes
```
#define R return
t,i,*b;f(int*a,int l,int k){int s=a[0]>>k&1,j=-1,i=1;if(k<0)R 0;for(;i<l;++i){t=a[i]>>k&1;if(s!=t)if(j<0)j=i,s=t;else R 1;}if(j<0)R f(a,l,k-1);else{if(s+b[k]==2)R 1;b[k]=s+1;R f(a,j,--k)||f(a+j,l-j,k);}}h(int*a,int l){int c[32]={0};b=c;if(f(a,l,30))R -1;t=0;for(i=0;i<32;++i)t|=(b[i]&1)<<i;R t;}
```
Defines a function `h(int*a,int l)` taking a pointer to an array and its length. [Here](http://pastebin.com/raw/Vm8xDfBi) is a test program behemoth.
Slightly ungolfed:
```
int t, i, *b;
int f(int * a, int l, int k) {
int s = a[0] >> k & 1;
int j = -1;
int i = 1;
if (k < 0) return 0;
for (; i < l; ++i) {
t = a[i] >> k & 1;
if (s != t) {
if (j < 0) {
j = i;
s = t;
} else return 1;
}
}
if (j < 0) {
return f(a, l, k - 1);
} else {
if (s + b[k] == 2) return 1;
b[k] = s + 1;
return f(a, j, --k) || f(a + j, l - j, k);
}
}
int h(int * a, int l) {
int c[32] = {0};
b = c;
if (f(a, l, 30)) return -1;
t = 0;
for (i = 0; i < 32; ++i) {
t |= (b[i] & 1) << i;
}
return t;
}
```
[Answer]
# Mathematica, 99 97 Characters
Thanks to Martin Büttner for advices.
```
x@l_:=If[OrderedQ[l~BitXor~#],#,-1]&@Fold[#+#2Boole@!OrderedQ@⌊l~BitXor~#/#2⌋&,0,2^32/2^Range@32]
```
**Explanation:**
We will do multiple tries to modify `N` starting from zero, and do a test to validate the candidate `N`.
*Step 1.* We get these numbers (32-bit integers) "xor"ed by `N`(`= 0` now) and divided by `2^31`: `⌊l~BitXor~#/#2⌋`. There are three cases:
* ordered, e.g. `{0, 0, 1, 1, 1, 1, 1, 1}`;
* can be corrected, e.g. `{1, 1, 1, 1, 0, 0, 0, 0}`;
* else, e.g. `{0, 0, 1, 0, 0, 1, 1, 1}`.
We do nothing to `N` for the first case, or we add `2^31` to `N` to correct the order for the second case: `#+#2Boole@!OrderedQ@...`. While for the third case, it is impossible to xorting the list what ever we do, thus we just add `2^31` to `N` for simplicity (or anything!).
*Step 2.* We get these numbers "xor"ed by `N` and divided by `2^30`. There are again three cases:
* ordered, e.g. `{0, 1, 2, 2, 2, 2, 3, 3}`;
* can be corrected, e.g. `{1, 1 , 0, 0, 3, 2, 2, 2}`;
* else, e.g. `{3, 3, 1, 3, 2, 0, 1, 0}`.
We do nothing to `N` for the first case, or we add `2^30` to `N` to correct the order for the second case. Otherwise, we realize that xorting is impossible, thus we just add `2^30` to `N` for simplicity again.
*Step 3 ~ 32.* We recursively get these numbers "xor"ed by `N` and divided by `2^29`, `2^28`, ..., `2^0`. And do similar things: `Fold[...,0,2^32/2^Range[32]]`
*Step 33.* Now we finally get a candidate `N`. `If[OrderedQ[l~BitXor~#],#,-1]&` is used to check if such `N` indeed xorting the list. If the list can be xorting by some `N`, it is not difficult to proof that we will always encounter the first or the second case.
[Answer]
# [Perl 6](http://perl6.org), 79 bytes
If there wasn't a time limit the shortest Perl 6 code would probably be
```
{first {[<=] $_ X+^@_},^2*.max} # 31 bytes
```
---
Instead I have to do something a bit more clever.
Since I took a while to come back to this, there was already an [answer](https://codegolf.stackexchange.com/questions/68109/xorting-an-array/68131#68131) that describes a good algorithm, and the reasoning behind it.
```
{$/=0;for @_.rotor(2=>-1) ->(\a,\b){b>=a or$/+|=2**msb a+^b};$/if [<=] $/X+^@_} # 79
```
```
{
# cheat by using a special variable
# so there is no need to declare it
$/=0;
# takes the elements two at a time, backing up one
for @_.rotor(2=>-1)
# since that is a non-flat list, desugar each element into 2
# terms
->(\a,\b){
# if they are not sorted
b>=a or
# take the most significant bit of xoring the two values
# and numeric or 「+|」 it into 「$/」
$/+|=2**msb a+^b
};
# returns 「$/」 if the list is Xorted
# otherwise returns Empty
$/if [<=] $/X+^@_
# 「 $/ X[+^] @_ 」
# does numeric xor 「+^」 between 「$/」
# and each element of the original list 「@_」
}
```
Usage:
```
# give it a lexical name for ease of use
my &code = {...}
say code [8,4,3,2,1]; # 15
say code [4,7,6,1,0,3]; # 5
say code [4,7,1,6,0,3]; # ()
say code [0,1,3,4,6,7]; # 0
say code [4,2,3,1]; # 6
say code [2,3,0,0,7,7,4,5,11,11]; # 2
say code [2,3,0,0,7,7,5,4,11,11]; # ()
say code [1086101479,748947367,1767817317,656404978,1818793883,1143500039]; # ()
# the example files
for 'testfiles'.IO.dir.sort».comb(/«\d+»/) {
printf "%10s in %5.2f secs\n", code( @$_ ).gist, now - ENTER now;
}
# () in 9.99 secs
# 0 in 11.70 secs
# 1096442624 in 13.54 secs
# () in 11.44 secs
```
[Answer]
# Mathematica ~~650 415~~ 194 bytes
This challenge helped me understand quite a bit about `Xor` that I had never thought about. It took a long time to whittle down the code, but was worth the effort.
`BitXor` works directly on base 10 numbers. This greatly reduced the code from the earlier versions.
The logic is simple. One works, not with pairs of numbers (as some submissions did) but rather with the complete set of numbers after being `BitXor`ed with the current "key".
Start with tentative solution, or "key" of zero, that is with all bits are zero. When the original `n` numbers are `BitXor`ed with zero , they are returned, unaltered. Correlate the ordering of the numbers with the range`1, 2, ...n`, which represent a perfectly ordered list. The correlation, with a value between -1 and 1, reflects how well the numbers are ordered.
Then set the hi bit, obtain the new key, and `BitXor` the key with the current set of numbers. If the correlation between the new sequence of numbers and the perfectly ordered list is an improvement, keep the bit set. If not, leave the bit unset.
Proceed in this manner from the hi to the low bit. If the best correlation is 1, then the key is the solution. If not, it is -1.
There would be ways to make the code a bit more efficient, for example, by interrupting the process as soon as a solution is found, but this would require more coding and the current approach is very fast as it is. (The final and longest test case takes 20 msec.)
```
c@i_:=Correlation[Ordering@i,Range[Length[i]]]//N;
t@{i_,k_,b_,w_}:=(v= c@BitXor[i,m=k+2^(b-1)];{i,If[v>w,m,k],b-1,v~Max~w})
g@i_:= (If[#4==1,#2,-1] &@@Nest[t,{i,0,b=1+Floor@Log[2,Max@i],x=c@i},b])
```
---
```
g[{4, 7, 6, 1, 0, 3}]
```
>
> 5
>
>
>
---
```
g[{4, 7, 1, 6, 0, 3}]
```
>
> -1
>
>
>
---
```
g2@{0, 1, 3, 4, 6, 7}
```
>
> 0
>
>
>
---
```
g@{1922985547, 1934203179, 1883318806, 1910889055, 1983590560, 1965316186,2059139291, 2075108931, 2067514794, 2117429526, 2140519185, 1659645051, 1676816799, 1611982084, 1736461223, 1810643297, 1753583499, 1767991311, 1819386745, 1355466982, 1349603237, 1360540003, 1453750157, 1461849199, 1439893078, 1432297529, 1431882086, 1427078318, 1487887679, 1484011617, 1476718655, 1509845392, 1496496626, 1583530675, 1579588643, 1609495371, 1559139172, 1554135669, 1549766410, 1566844751, 1562161307,1561938937, 1123551908, 1086169529, 1093103602, 1202377124, 1193780708, 1148229310, 1144649241, 1257633250, 1247607861, 1241535002, 1262624219, 1288523504, 1299222235,840314050, 909401445, 926048886, 886867060, 873099939, 979662326,963003815, 1012918112, 1034467235, 1026553732, 568519178, 650996158,647728822, 616596108, 617472393, 614787483, 604041145, 633043809, 678181561, 698401105, 776651230, 325294125, 271242551, 291800692, 389634988, 346041163, 344959554, 345547011, 342290228, 354762650, 442183586, 467158857, 412090528, 532898841, 534371187, 32464799, 21286066, 109721665, 127458375, 192166356, 146495963, 142507512, 167676030, 236532616, 262832772}
```
>
> 1927544832
>
>
>
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), ~~125~~ 119 bytes
```
D,g,@@,BxBBBDbU1€oB]BJ2$Bb1+
D,j,@,bUBSVcGbU£{g}B]BkAbUBSVcGbU£>B]BKBcB*¦Bo2/i
L!,B#a=
D,f,?!,{j}Vad{j}BF€Bx1]G$0=-1$Qp
```
[Try it online!](https://tio.run/##TVTLbl1FEFznfsWN8AquRb@mH4sczJFFJIIUIeTssrBjOSIs4gVIkaJs@BUkVnxFPoUfMTU9FuDF8a2eme6uqp65vr29v394uDy9PV1cnPYP@75f3lzx37//9X5/vX8vZ/sNf3W4PL07XZxurvafXr15fnP1@Y@Pbz9h@Zdv/xfaEHixv9m//Pzn/l6@/vnww9PT/sX1Mxy@O33z9PTx3adX17f47t8h@/6BXz8/o2fnfPbj/cPZ3WZbbL7xRpseXh4OjxFG7L8IASvivsW/ewQRfkTH@cclUjmGxXEDUBNSjpogUxUf8l5hyiwao0HqwG@n43Z4wuVD2TnnPqFRrCXFDWLgWOkCDmRRNgFzmNQQnxmEjQYqZCf3UW4DgQbhiU91Q86oLJQzA4e6OYto95BMbirVLGLoSLV1KOZpVu50CYbpYV1IwdodGTsD9jupaGdQp2FEpBPY0BjEo1dQM6145TYtsKPIzoD6aGDI4xKkQ68tnklgEyINMjJnVwsYMYjFyoAwdFwiD6pE6ZLeB03KXTodyA2dcjaIGpkg3xmcygr9NtvRXnDIAgbG4NvAKtyNqYF7msUUHBmGC/oBqbU0BaslCgsU46JmAWbs9UiWYDFBs6WkEFQMlrYJ5yMp1iHQhUS6yrIZOIl1qzLCVWWsiRIIAcF8LRnDT6JmIZBATLjLSuZAT9SFpDDJGIcxM0BVnUNFRywVNCFUGw3EyRKCTYB/mAby3pahVFVax5mhYsqt0vvKFbOQ3BmYUAuTxN0QKWhElwUQeKehrcPwnEON4cCSw81yONfAItC7SIMeeOi5QBiSlXYPjoHIsNReIiODaN0DtCLTpGoQiXZgVYPqiaLRGQIuD/jWBCGvlEHqCWQaJPCzAfgQeXVD8NtxGTI7g5rPst49gGuNwiQtMF8N1FoAxpJIs1DE4VOrf3hisAsDuxSHVhAhcZcmwKjgGVmHhkqiqPEChhnmjNWDYFLmG9C9wnYn9@PyogLj6ssYwcVO3NUGNeMY@OO6WT47XyxwHcd8mZrtfGEwbEshUTxlAkcauKQKnDq8fHg4P//t17t/AA "Add++ – Try It Online")
I am actually really proud that Add++ is able to do this, and isn't the longest solution here
Declares a function `f` that takes each element as a separate argument (e.g. `$f>4>2>3>1`)
## How it works
Buckle up folks, it's going to be a long ride
```
D,g,@@, ; Declare a function 'g'
; Example arguments: [4 7]
Bx ; Xor; STACK = [3]
BB ; To binary; STACK = [11]
BD ; Digits; STACK = [[1 1]]
bU ; Unpack; STACK = [1 1]
1€o ; Replace 0s with 1s; STACK = [1 1]
B] ; Wrap; STACK = [[1 1]]
BJ ; Concatenate; STACK = ['11']
2$Bb ; From binary; STACK = [3]
1+ ; Increment; STACK = [4]
; Return 4
D,j,@, ; Declare a function 'j'
; Example argument: [[4 7 6 1 0 3]]
bU ; Unpack; STACK = [4 7 6 1 0 3]
BS ; Overlapping pairs; STACK = [4 7 6 1 0 3 [[4 7] [4 6] [6 1] [1 0] [0 3]]]
VcG ; Keep first element; STACK = [[[4 7] [4 6] [6 1] [1 0] [0 3]]]
bU ; Unpack; STACK = [[4 7] [4 6] [6 1] [1 0] [0 3]]
£{g} ; Apply 'g' over each; STACK = [4 2 8 2 4]
B] ; Wrap; STACK = [[4 2 8 2 4]]
Bk ; Global save; STACK = [] ; GLOBAL = [4 2 8 2 4]
A ; Push arguments; STACK = [[4 7 6 1 0 3]]
bU ; Unpack; STACK = [4 7 6 1 0 3]
BSVcGbU ; Overlapping pairs; STACK = [[4 7] [4 6] [6 1] [1 0] [0 3]]
£> ; Greater than each; STACK = [0 1 1 1 0]
B] ; Wrap; STACK = [[0 1 1 1 0]]
BK ; Global get; STACK = [[0 1 1 1 0] [4 2 8 2 4]]
BcB* ; Products; STACK = [[0 2 8 2 0]]
¦Bo ; Reduce by logical OR; STACK = [10]
2/i ; Halve; STACK = [5]
; Return 5
L!, ; Declare 'lambda 1'
; Example argument: [[1 2 3 4 5]]
B# ; Sort; STACK = [[1 2 3 4 5]]
a= ; Equal to argument; STACK = [1]
; Return 1
D,f,?!, ; Declare a function 'f'
; Example arguments: [[4 7 6 1 0 3]]
{j} ; Call 'j'; STACK = [5]
V ; Save; STACK = [] ; REGISTER = 5
ad ; Push arguments twice; STACK = [[4 7 6 1 0 3] [4 7 6 1 0 3]]
{j} ; Call 'j'; STACK = [[4 7 6 1 0 3] 5]
BF ; Flatten; STACK = [4 7 6 1 0 3 5]
€Bx ; Xor each with 5; STACK = [1 2 3 4 5 6]
1] ; Call 'lambda 1'; STACK = [1]
G$ ; Retrieve REGISTER; STACK = [5 1]
0= ; If equal to 0:
-1$Q ; Return -1
p ; Else, pop condition; STACK = [5]
; Return 5
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¬√▬ⁿ{j╔■α√ï(íP♫_z(.▀ng▒JU↨@b┬
```
[Run and debug online!](https://staxlang.xyz/#p=aafb16fc7b6ac9fee0fb8b28a1500e5f7a282edf6e67b14a5517406383&i=%5B4+7+6+1+0+3%5D%0A%5B4+7+1+6+0+3%5D%0A%5B0+1+3+4+6+7%5D%0A%5B4+2+3+1%5D%0A%5B2+3+0+0+7+7+4+5+11+11%5D%0A%5B2+3+0+0+7+7+5+4+11+11%5D%0A%5B1086101479+748947367+1767817317+656404978+1818793883+1143500039%5D%0A%5B180522983+1885393660+751646477+367706848+331742205+724919510+850844696+2121330641+869882699+1831158987+542636180+1117249765+823387844+731663826+1762069894+240170102+1020696223+1212052937+2041219958+712044033+195249879+1871889904+1787674355+1849980586+1308879787+1743053674+1496763661+607071669+1987302942+178202560+1666170841+1035995406+75303032+1755269469+200581873+500680130+561748675+1749521426+1828237297+835004548+934883150+38711700+1978960635+209243689+1355970350+546308601+590319412+959613996+1956169400+140411967+112601925+88760619+1977727497+672943813+909069787+318174568+385280382+370710480+809689639+557034312+865578556+217468424+346250334+388513751+717158057+941441272+437016122+196344643+379529969+821549457+97008503+872313181+2105942402+603939495+143590999+1580192283+177939344+853074291+1288703007+1605552664+162070930+1325694479+850975127+681702163+1432762307+1994488829+780869518+4379756+602743458+1963508385+2115219284+1219523498+559301490+4191682+1918142271+169309431+346461371+1619467789+1521741606+1881525154%5D%0A%5B37580156+64423492+87193676+91914964+93632157+96332899+154427982+176139560+184435039+228963836+230164674+279802291+301492375+309127664+345705721+370150824+380319820+403997410+410504675+416543032+418193132+424733526+428149607+435596038+477224208+515649925+519407995+525469350+614538124+624884850+642649261+653488151+679260270+685637235+690613185+739141066+825795124+832026691+832633584+833213619+852655299+913744258+917674993+921902522+925691996+931307936+954676047+972992595+997654606+1020009811+1027484648+1052748108+1071580605+1108881241+1113730139+1122392118+1154042251+1170901568+1180031842+1180186856+1206428383+1214066097+1242934611+1243983997+1244736049+1262979035+1312007069+1312030297+1356274316+1368442960+1377432523+1415342434+1471294243+1529353536+1537868913+1566069818+1610578189+1612277199+1613646498+1639183592+1668015280+1764022840+1784234921+1786654280+1835593744+1849372222+1875931624+1877593764+1899940939+2007896363+2023046907+2030492562+2032619034+2085680072+2085750388+2110824853+2123924948+2131327206+2134927760+2136423634%5D%0A%5B1922985547+1934203179+1883318806+1910889055+1983590560+1965316186+2059139291+2075108931+2067514794+2117429526+2140519185+1659645051+1676816799+1611982084+1736461223+1810643297+1753583499+1767991311+1819386745+1355466982+1349603237+1360540003+1453750157+1461849199+1439893078+1432297529+1431882086+1427078318+1487887679+1484011617+1476718655+1509845392+1496496626+1583530675+1579588643+1609495371+1559139172+1554135669+1549766410+1566844751+1562161307+1561938937+1123551908+1086169529+1093103602+1202377124+1193780708+1148229310+1144649241+1257633250+1247607861+1241535002+1262624219+1288523504+1299222235+840314050+909401445+926048886+886867060+873099939+979662326+963003815+1012918112+1034467235+1026553732+568519178+650996158+647728822+616596108+617472393+614787483+604041145+633043809+678181561+698401105+776651230+325294125+271242551+291800692+389634988+346041163+344959554+345547011+342290228+354762650+442183586+467158857+412090528+532898841+534371187+32464799+21286066+109721665+127458375+192166356+146495963+142507512+167676030+236532616+262832772%5D%0A%5B1922985547+1934203179+1883318806+1910889055+1983590560+1965316186+2059139291+2075108931+2067514794+2117429526+2140519185+1659645051+1676816799+1611982084+1736461223+1810643297+1753583499+1767991311+1819386745+1355466982+1349603237+1360540003+1453750157+1461849199+1439893078+1432297529+1431882086+1427078318+1487887679+1484011617+1476718655+1509845392+1496496626+1583530675+1579588643+1609495371+1559139172+1554135669+1549766410+1566844751+1562161307+1561938937+1123551908+1086169529+1093103602+1202377124+1193780708+1148229310+1144649241+1257633250+1241535002+1247607861+1262624219+1288523504+1299222235+840314050+909401445+926048886+886867060+873099939+979662326+963003815+1012918112+1034467235+1026553732+568519178+650996158+647728822+616596108+617472393+614787483+604041145+633043809+678181561+698401105+776651230+325294125+271242551+291800692+389634988+346041163+344959554+345547011+342290228+354762650+442183586+467158857+412090528+532898841+534371187+32464799+21286066+109721665+127458375+192166356+146495963+142507512+167676030+236532616+262832772%5D&a=1&m=2)
Uses @RainerP.'s solution (came up with the flipping bit part independently but uses the `32rr` part)
Linear time complexity.
Uses the unpacked version to explain.
```
32rr{|2Y;{y/m:^!c{,{y|^m~}Mm,:^ud:b
32rr Range [32,31..0]
{ m Map each number `k` in the range with
|2Y `2^k`
;{y/m Map each number `l` in the input to `floor(l/2^k)`
:^! The mapped array is not non-decreasing
This is the binary digit `l` is mapped to
c{ }M If that's true, do
,{y|^m~ Flip the corresponding bit of every element in the input
,:^ The final array is sorted
ud Take inverse and discard, if the final array is not sorted this results in zero-division error
:b Convert mapped binary to integer
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
(Eventually) Outputs `undefined` for falsey inputs.
```
@Ë^XÃäÎø1}f
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QMteWMPkzvgxfWY&input=WzQsIDcsIDYsIDEsIDAsIDNd)
```
@Ë^XÃäÎø1}f :Implicit input of array U
@ :Function taking an integer X as argument
Ë : Map U
^X : XOR X
à : End map
ä : Consecutive pairs
Î : Signs of differences
ø1 : Contains 1?
} :End function
f :Get the first X>=0 that returns false
```
] |
[Question]
[
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.
Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.
* Port number N is a valid port, and 210 < N < 215
* Trailing newline can be either `\n`or `\r\n`
* You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example `2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard rules and loopholes apply.
## Example
You run your server with `./server 1234`. The server is now running and waiting for connections on port 1234. Then a client from `127.0.0.1` connects to your server. Your server performs a simple calculation: `127+0+0+1 => 128` and sends the result to the client (with trailing newline): `128\n`. Then server closes connection and waits for next client.
## Leaderboard
```
var QUESTION_ID=76379,OVERRIDE_USER=20569;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]
# Bash + netcat + ss + …, ~~65~~ 60 characters
```
nc -lp$1 -c'ss src :'$1'|awk \$0=\$5|tr .: +#|bc'
exec $0 $1
```
Not a serious solution, was just curious about this possibility.
Thanks to:
* [ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj) for suggesting the `awk` based filtering (-5 characters)
Sample run:
(terminal 1)
```
bash-4.3$ ./ip-reduce.sh 8080
```
(terminal 2)
```
bash-4.3$ nc localhost 8080
128
bash-4.3$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.
```
On Ubuntu you can get `nc` from [netcat-traditional](http://packages.ubuntu.com/wily/netcat-traditional) (no, netcat-openbsd is not good) and `ss` from [iproute2](http://packages.ubuntu.com/wily/iproute2).
[Answer]
## Linux ELF/x86, 146 bytes
```
00000000 7f 45 4c 46 01 00 00 00 5a 0e 00 00 5a 5e eb 10 |.ELF....Z...Z^..|
00000010 02 00 03 00 0c 50 eb 10 0c 50 eb 10 04 00 00 00 |.....P...P......|
00000020 5e 53 43 53 52 89 e1 b0 66 3d 20 00 01 00 cd 80 |^SCSR...f= .....|
00000030 97 55 6b ed 0a 01 c5 ac 2c 30 79 f6 43 0f cd 01 |.Uk.....,0y.C...|
00000040 dd 55 89 e1 6a 10 51 6a 10 51 57 89 e1 b0 66 cd |.U..j.Qj.QW...f.|
00000050 80 43 43 b0 66 cd 80 01 64 24 08 89 e1 43 b0 66 |.CC.f...d$...C.f|
00000060 cd 80 89 c1 93 8d 74 24 1b 99 fd ac 01 c2 e2 fb |......t$........|
00000070 89 f7 b0 0a aa 91 92 f6 f1 86 c4 04 30 aa 42 c1 |............0.B.|
00000080 e8 08 75 f3 42 89 f9 41 b0 04 cd 80 b0 06 cd 80 |..u.B..A........|
00000090 eb c9 |..|
00000092
```
Includes a 52-byte ELF header, a 32-byte program header, 111 bytes of program code + 3 bytes of code for skipping around inside the headers.
Information on how to create tiny ELF executables can be found at [breadbox](https://codegolf.stackexchange.com/users/4201/breadbox)'s *"[A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux](http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html)"*.
Linux/i386 uses the [`socketcall(2)`](http://man7.org/linux/man-pages/man2/socketcall.2.html) multiplex system call, which takes in `ebx` the specific socket call (the `SYS_*` macros from `/usr/include/linux/net.h`), and in `ecx` a pointer to the argument area of the original library call.
Some things done to keep the executable small:
* It assumes registers are zeroed on entry, which Linux does, but is not required by the ELF standard (the only requirement is that on entry `EDX` points to a finalization funtion (useful for executables loaded by the dynamic linker) or is NULL).
* It assumes on launch (typically by a shell) the only open file descriptors are 0, 1, and 2. Which means that the listening socket will be fd 3, and the accepted socket will be fd 4.
* It assumes there are exactly 2 arguments (including `argv[0]`).
* The same stack space is reused for the calls to `bind(2)`, `listen(2)` and `accept(2)`.
* To skip over the `phentsize` and `phnum` fields, a byte is prepended, turning into a `CMP` operation which takes the `phentsize` and `phnum` fields as an immediate (trick shamelessly stolen from [breadbox's solution to 123 in anarchy golf](http://golf.shinh.org/reveal.rb?123/breadbox_1180162215&out)).
* x86 string operations `LODS` (load into accumulator and increment/decrement source index) and `STOS` (store from accumulator and increment/decrement destination index) are nice for short code.
* `XCHG EAX, reg` is 1-byte, compared to `MOV EAX, reg`, which takes 2 bytes.
* `CDQ/CLTD` (sign-extend `EAX` into `EDX:EAX`) can be used as a 1-byte way to zero the `EDX` register.
* `BSWAP` is useful for implementing `htons()`.
Nasm source:
```
BITS 32 ;
; ELF HEADER -- PROGRAM HEADER
; ELF HEADER ; +-------------+
DB 0x7f,'E','L','F' ; | magic | +--------------------+
; | | | |
; PROGRAM HEADERS ; | | | |
DD 1 ; |*class 32b | -- | type: PT_LOAD |
; |*data none | | |
; |*version 0 | | |
; |*ABI SysV | | |
DD 0xe5a ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers | -- | offset |
; | | | |
entry: pop edx ; edx = 2 (argc) ; |*PADx7 | -- | vaddr = 0x10eb5e5a |
pop esi ; discard argv[0] ; | | | |
jmp short skip ; | | | |
DW 2 ; | ET_EXEC | -- |*paddr LO |
DW 3 ; | EM_386 | -- |*paddr HI |
DD 0x10eb500c ; |*version | -- | filesz |
DD 0x10eb500c ; | entry point | -- | memsz |
DD 4 ; | ph offset | -- | flags: RX |
; | | | |
skip: pop esi ; esi = argv[1] ; |*sh offset | -- |*align |
socket: push ebx ; default protocol (0) ; | | | |
inc ebx ; | | | |
push ebx ; SOCK_STREAM (1) ; | | | |
push edx ; AF_INET (2) ; |*flags | +--------------------+
mov ecx, esp ; | |
mov al, 0x66 ; |*ehsize |
DB 0x3d ; cmp eax,0x10020 ; | |
DW 32 ; | phentsize |
DW 1 ; | phnum |
; | |
int 0x80 ; socket(2, 1, 0) ; |*shentsize |
xchg edi, eax; edi = sockfd, eax = 0 ; |*shnum |
push ebp ; INADDR_ANY ; | |
; | |
mult: imul ebp, 10 ; \_ ; |*shstrndx |
add ebp, eax; > ; | |
lodsb ; > ; +-------------+
sub al,'0' ; >
jns mult ; / ebp = atoi(argv[1]) ; bind stack frame
; +-----------------------+
endmul: inc ebx ; SYS_BIND (2) ; | INADDR_ANY |
; +->| AF_INET | htons(port) |
bswap ebp ; | +-----------------------+
add ebp, ebx ; AF_INET (2), htons(port) ; | | 16 |
push ebp ; | +-----------------------+
; | | dummy |
mov ecx, esp ; | +-----------------------+
push 16 ; addrlen ; | | 16 |
push ecx ; dummy value ; | +-----------------------+
push 16 ; addrlen ; +--| addr |
push ecx ; addr ; +-----------------------+
push edi ; sock ; | sockfd |
mov ecx, esp ; +-----------------------+
mov al, 0x66
int 0x80 ; bind(sockfd, addr, addrlen)
; accept stack frame
; +-----------------------+
listen: ;mov byte [esp+8],1 ; | INADDR_ANY |
inc ebx ; +->| AF_INET | htons(port) |
inc ebx ; SYS_LISTEN (4) ; | +-----------------------+
mov al, 0x66 ; |+>| 16 |
int 0x80 ; listen(sockfd, backlog) ; || +-----------------------+
; || | dummy |
add [esp+8], esp ; || +-----------------------+
accept: mov ecx, esp ; |+-| &addrlen |
inc ebx ; SYS_ACCEPT (5) ; | +-----------------------+
mov al, 0x66 ; +--| addr |
int 0x80 ; accept(sockfd, addr, &addrlen); +-----------------------+
; | sockfd |
mov ecx, eax ; ecx = 4 ; +-----------------------+
xchg ebx, eax ; ebx = acceptfd, eax = 000000xx
lea esi, [esp+27] ; point to the IP part of struct sockaddr_in
cdq
std ; reverse direction for string operations
addip: lodsb ; \_
add edx, eax ; > edx = sum of 4 IP bytes
loop addip ; /
mov edi, esi ; reuse struct sockaddr_in as scratch buffer
mov al, 10 ; '\n'
stosb
xchg ecx, eax ; ecx = 10
xchg eax, edx ; edx = 0, eax = sum
divide: div cl ; \_
xchg al, ah ; >
add al,0x30 ; >
stosb ; > sprintf(scratch, "%d", sum)
inc edx ; >
shr eax, 8 ; >
jnz divide ; /
write: inc edx ; ndigits + 1 ('\n')
mov ecx, edi
inc ecx
mov al,4
int 0x80 ; write(acceptfd, scratch, scratchlen)
close: mov al, 6
int 0x80 ; close(acceptfd)
jmp accept
```
[Answer]
# C#, ~~284~~ ~~283~~ ~~282~~ ~~278~~ ~~274~~ 254 bytes
```
class A{static int Main(string[]a){var b=new System.Net.Sockets.TcpListener(int.Parse(a[0]));b.Start();for(;;){var c=b.AcceptTcpClient();var d=c.Client.LocalEndPoint.Serialize();new System.IO.StreamWriter(c.GetStream()).WriteLine(d[4]+d[5]+d[6]+d[7]);}}}
```
Classic example of a basic C# TCP server. Testing:
**Terminal 1:**
```
$ ./Q76379.exe 1029
```
**Terminal 2:**
```
$ telnet localhost 1029
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.
```
**Firefox:**
![](https://i.stack.imgur.com/Xv2je.png)
[Answer]
# NodeJS, ~~146~~ ~~134~~ 127 bytes
```
require('http').createServer((q,s)=>s.end(eval(0+q.socket.remoteAddress.replace(/^.*:|\./g,'+'))+'\n')).listen(process.argv[2])
```
I finally get to post a NodeJS answer! IPv4 only right now.
Sample execution: `node script.js 1024`. From another terminal:
```
$ curl 127.0.0.1:1024
128
```
[Answer]
# Tcl, 92
* 1 byte saved thanks to @DonalFellows.
```
proc s {c a p} {puts $c [expr [string map .\ + $a]]
close $c}
socket -server s $argv
vwait f
```
Fairly self-explanatory:
`socket -server s $argv` creates a listening socket on the port specified in the arguments.
Every time a new connection arrives, the `proc s` is called, with channel, source-address and source-port as parameters. `string map` substitutes `.` for `+` in the source address, and `expr` arithmetically evaluates the result, which is then `puts` back to the connection channel `c`.
`vwait` runs an event loop to catch the incoming connection events.
---
Credit to @DonalFellows for the following:
Here's a version that handles IPv6 (requires Tcl 8.6; most of the extra length is due to producing a hex response):
# Tcl, 109
```
proc s {c a p} {puts $c [format %x [expr 0x[string map :\ +0x0 $a]]]
close $c}
socket -server s $argv
vwait f
```
[Answer]
# Groovy 133, 125, 93, 89
```
new ServerSocket(args[0]as int).accept{it<<(it.inetAddress.address as int[]).sum()+"\n"}
```
IPv4 only, probably.
Ungolfed:
```
new ServerSocket(args[0]as int).accept{
it << (it.inetAddress.address as int[]).sum()+"\n"
}
```
Testing:
```
$ telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.
```
[Answer]
# Python 3, 170 166 147 bytes
```
from socket import*
s=socket()
s.bind(("",int(input())))
s.listen()
while 1:
c,a=s.accept()
c.send(b"%d\n"%eval(a[0].replace(".","+"))),c.close()
```
Takes port on `stdin`, IPv4 only. Works on GNU/Linux (and, I assume, most other unices), which automatically expands "" to "0.0.0.0", not sure about Windows though.
[Answer]
# Java, 371 368 350 344 333 310 295 282 bytes
## Golfed
```
import java.net.*;class A{public static void main(String[]n)throws Exception{ServerSocket s=new ServerSocket(Integer.decode(n[0]));for(;;){try(Socket a=s.accept()){byte[]c=a.getInetAddress().getAddress();new java.io.PrintStream(a.getOutputStream()).println(c[0]+c[1]+c[2]+c[3]);}}}}
```
### Ungolfed
```
import java.net.*;
class A {
public static void main(String[] n) throws Exception {
ServerSocket s = new ServerSocket(Integer.decode(n[0]));
for (;;) {
try (Socket a = s.accept()) {
byte[] c = a.getInetAddress().getAddress();
new java.io.PrintStream(a.getOutputStream()).println(c[0] + c[1] + c[2] + c[3]);
}
}
}
}
```
### Output
```
mallard@steamroller:~$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.
```
[Answer]
## PowerShell v2+, ~~303~~ ~~268~~ ~~257~~ 227 bytes
```
nal n new-object;($l=n Net.Sockets.TcpListener($args[0])).Start()
for(){($w=n IO.StreamWriter(($c=$l.AcceptTcpClient()).GetStream())).Write((([Net.IPEndPoint]$c.Client.RemoteEndPoint).Address-replace"\.",'+'|iex))
$w.Dispose()}
```
Saved 35 bytes thanks to [Matt](https://codegolf.stackexchange.com/users/52023/matt) ... Saved another 11 bytes by aliasing `New-Object` and minor tweaks ... Saved 30 more bytes by implicitly using localhost rather than `any` IP address and corrected to account for continual usage as originally specified and I missed
Really similar to the [C# answer](https://codegolf.stackexchange.com/a/76380/42963), since it's .NET underlying both. We save a few bytes here over the C# answer by being able to leverage the returning functionality of PowerShell (surrounding our declaration/assignment in parens, and then immediately calling the . methods), but we lose an awful lot by needing to formulate the summation. The fact that we've got slightly shorter class names/calls is really why this answer is beating C#.
### Explanation
We first create a `New-Alias` (with the `nal` alias) to save on re-typing `New-Object` later. The rest of the first line is setting up a TCP Listener. We pass the command-line `$args[0]` as the input for creating a new `System.Net.Sockets.TcpListener`, stored as `$l`. That object is encapsulated in parens and immediately called with `.Start()` to have it actively open the socket.
Entering an infinite `for` loop, we then set our listener `$l` to blocking with `AcceptTcpClient()` which will wait for a connection. A reference to that connection (once it's made) is stored in `$c`, encapsulated in parens, and immediately called `GetStream()` to get the datastream. That datastream is passed to a new `System.IO.StreamWriter` constructor, `$w`, so we can manipulate it. That constructor is itself encapsulated in parens and immediately called `Write(...)`.
Inside the `Write(...)` call, we take our client handle `$c` and obtain the client's `RemoteEndPoint` property. This is the only way (that I've found so far) to get the remote IP address. Next we need to re-cast that as a `[System.Net.IPEndPoint]` object so it's formatted correctly, encapsulate that in parens, and pull just the `.Address` property. We then `-replace` the literal periods with plus signs, then pipe it to `Invoke-Expression` (similar to `eval`) to obtain our summation.
After the IO write, we need to call `.Dispose()` to ensure the datastream is flushed to the client and closed. The TCP server drops the client connection without warning, so depending upon the client used it may hang for a while at this point. It then continues through the `for` loop without properly closing connections. This also means that it leaks memory and system handles like crazy, but we don't care about that, right? You may need to use Task Manager to kill the process when you're done running the server, though. :D
Also IPv4 only, as the summation barfs spectacularly trying to handle an IPv6 address, since `:` isn't a valid algebraic operator for `iex` to parse.
[Answer]
# PHP, 161 (56?)
This is my first post in here. I hope this goes right :)
```
<?php $s=socket_create_listen($argv[1]);while($c=socket_accept($s)){socket_getpeername($c,$r);socket_write($c,array_sum(explode('.',$r))."\n");socket_close($c);}
```
**Ungolfed:**
```
<?php
$s = socket_create_listen($argv[1]); //Create socket
while( $c = socket_accept($s) ) { // Loop accepting new connections
socket_getpeername($c, $r); // Get IP address in $r
socket_write($c, array_sum(explode('.', $r))."\n"); //Calculate sum
socket_close($c); //Close connection and wait for next one
}
```
**Terminal:**
```
$ php test.php 8080 &
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
128
Connection closed by foreign host.
```
This only works for IPV4
**Edit**:
I just noticed that php supports basic server:
I decided stick to original character count unless somebody confirms if following is allowed :)
test2.php: (possible 56-byte solution)
```
<?=array_sum(explode('.',$_SERVER['REMOTE_ADDR']))."\n";
```
And then start service with:
```
php -S localhost:8080 test2.php
```
**Chrome as client**
[![screenshot](https://i.stack.imgur.com/VAaUT.png)](https://i.stack.imgur.com/VAaUT.png)
**Edit 2: wget as client**
```
$ wget -qO- localhost:8080
128
```
[Answer]
# [Go](https://golang.org/), ~~359~~ 311
This is my first program in Go - It allowed to let me discover one thing : This is definitively not a good golfing language!
(Kudos to @steve who did most of the golfing !)
```
package main
import(n"net";t"strings";r"strconv";x"regexp";"os")
func main(){l,_:=n.Listen("tcp",":"+os.Args[1])
for{c,_:=l.Accept();var s int
for _,i:=range t.Split(x.MustCompile(":[0-9]+$").ReplaceAllLiteralString(c.RemoteAddr().String(),""),"."){
n,_:=r.Atoi(i);s=s+n};c.Write([]byte(r.Itoa(s)));c.Close()}}
```
[Answer]
## Common Lisp, 110 bytes
```
(use-package'usocket)(lambda(p)(socket-server"localhost"p(lambda(u)(format u"~D~%"(reduce'+ *remote-host*)))))
```
## Details
```
(use-package 'usocket)
(lambda (port)
;; create server with event-loop
(socket-server "localhost"
port
;; tcp-handler
(lambda (stream)
;; format to stream to client
(format stream
"~D~%"
;; add all elements of the host,
;; a vector of 4 integers
(reduce #'+ *remote-host*))
;; client connection is closed automatically
;; when exiting this function
)))
```
[Answer]
# q, 88 bytes
```
system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}
```
* `system raze"p ",1_.z.x`: Takes the second command-line argument (the first `"-"` is for telling `q` not to interpret `N` as a script/file) and opens a port (`"p "`) with it.
+ Note: Calling `q -p N` sets the port as `N` automatically, but since the question seems to suggest that `N` should be an argument to the program rather than the executable itself, I've gone the longer way.
* Inside the `.z.pg` function that handles incoming requests, `.z.a` holds the IP address as a 32-bit integer.
+ `"i"$0x0 vs` splits it into its integer 'constituents', and `sum` does the summation.
+ Last, `string` the numeric result and append `"\n"` to it to return to the client.
* `.z.ph` is another function for HTTP GET requests, with extra handling to convert the string output into a valid HTTP response.
Demo - Server:
```
c:\q\w32>q - 1234
KDB+ 3.3 2015.11.03 Copyright (C) 1993-2015 Kx Systems
w32/ 4()core ... NONEXPIRE
Welcome to kdb+ 32bit edition
q)system raze"p ",1_.z.x;.z.pg:{(string sum"i"$0x0 vs .z.a),"\n"};.z.ph:{.h.hy[`;.z.pg[]]}
q)
```
Demo - Client (from another `q` session running on `127.0.0.1`):
```
q)(hopen `::1234)""
"128\n"
```
Demo - Client (from `curl`):
```
$ curl localhost:1234
128
$
```
[Answer]
# 8086 machine code (16-bit DOS), ~~163 156 148 148~~ 142 bytes
```
00000000 31 c0 bb 0a 00 31 c9 be 81 00 bf 80 00 8a 0d 01 |1....1..........|
00000010 cf 46 8a 0c 80 e9 30 f7 e3 00 c8 39 fe 72 f2 89 |.F....0....9.r..|
00000020 c3 89 c1 b8 01 10 ba ff ff 31 f6 31 ff cd 61 53 |.........1.1..aS|
00000030 b8 00 12 bf 80 00 b9 01 00 ba ff ff cd 61 b8 00 |.............a..|
00000040 14 cd 61 31 c0 bb 0a 00 83 c7 06 8d 4d 04 26 02 |..a1........M.&.|
00000050 05 80 d4 00 47 39 cf 72 f5 bf 84 00 b9 80 00 bb |....G9.r........|
00000060 0a 00 4f 31 d2 f7 f3 80 c2 30 88 15 39 cf 77 f2 |..O1.....0..9.w.|
00000070 1e 07 b8 0e 13 5b bf 80 00 b9 04 00 ba ff ff cd |.....[..........|
00000080 61 b8 00 11 ba 01 00 cd 61 b8 00 4c cd 21 |a.......a..L.!|
0000008e
```
Equivalent assembly code:
```
org 0x100
tcp equ 0x61 ; NTCPDRV interrupt
xor ax,ax
mov bx,10
xor cx,cx
mov si,0x81 ; [ds:81]-[ds:FF] = command line args
mov di,0x80 ; [ds:80] = strlen(args)
mov cl,[di]
add di,cx
@@: inc si
mov cl,[si] ; get character
sub cl,'0' ; convert char to int
mul bx ; ax *= 10
add al,cl
cmp si,di
jb @b
; now ax = port number
mov bx,ax ; source port (leaving this 0 doesn't work?)
mov cx,ax ; dest port
mov ax,0x1001 ; open TCP socket for listening
mov dx,-1 ; infinite timeout
xor si,si ; any dest IP
xor di,di
int tcp
; ^ I think this call should block until a connection is established, but apparently it doesn't.
push bx ; bx = socket handle, save it for later
mov ax,0x1200 ; read from socket
mov di,0x80 ; es:di = buffer (just reuse argument area to save space)
mov cx,1 ; one byte
mov dx,-1
int tcp ; this will block until a client connects and sends one byte
mov ax,0x1400 ; get TCP session status, bx=handle
int tcp
; now es:di points to a struct containing the source/dest IP addresses and ports
; the docs say it's two dwords for each IP address, then two bytes for "ip_prot" and "active" (whatever that means)
; ...but actually each IP address is followed by the port number (one word)
xor ax,ax
mov bx,10
add di,6 ; [es:di+6] = client IP
lea cx,[di+4]
@@: add al,[es:di] ; add all bytes together
adc ah,0
inc di
cmp di,cx
jb @b
; now ax contains the IP address sum
mov di,0x84 ; recycle arguments area again
mov cx,0x80
mov bx,10
@@: dec di
xor dx,dx
div bx ; dl = ax mod 10
add dl,'0' ; convert int to char
mov [di],dl
cmp di,cx
ja @b
; now [ds:80]-[ds:83] contains an ascii representation of the IP address sum
push ds
pop es
mov ax,0x130e ; send data with newline, wait for ack
pop bx ; socket handle
mov di,0x80 ; es:di = data
mov cx,4 ; sizeof data
mov dx,-1
int tcp
mov ax,0x1100 ; close TCP socket
mov dx,1
int tcp
mov ax,0x4c00
int 0x21
```
This assumes [`ntcpdrv`](http://www.pld.ttu.ee/~priidu/library/net/ntcpdrv.zip) is loaded at `INT 0x61` (and any suitable packet driver at `0x60`). Compile with `fasm tcpserv.asm`.
It has some issues though:
* It doesn't check if the argument is a valid port number, or if it's even a number at all.
* The client must send at least one byte, since I can't seem to find any other way to tell if a client has connected.
* It only works once, and hangs on a second attempt. Works again after a reboot.
* The returned value is left-padded with zeroes.
* This is my very first code golf entry, and also my very first 8086 asm program. I'm sure there are ways to improve this further.
[Answer]
# LiveScript, ~~107~~ 105 bytes
```
(require \http)createServer(->&1.end((.reduce (+))<|it.connection.remoteAddress/\.))listen process.argv.0
```
Nothing much to add, it's just basic NodeJS stuff. Style points for `&1` (second argument), `<|` (F# piping, akin to `$` in Haskell) and biop: `(+)` in LS is like operator sections in Haskell: a curried binary function (that adds its operands).
Also a bit dirty: `/`, if given a *literal* string on its right, will do split.
[Answer]
# Perl, ~~141~~ 132 + 1 = 133 bytes
## Golfed
```
$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}
```
## Ungolfed
```
# listen on tcp port obtained from stdin
$s=new IO::Socket::INET(LocalPort=> <>,
Listen => 5,
Reuse => 1);
{
# accept connection
$c=$s->accept();
# get the ip address
$_=$c->peerhost();
# replace dots with plus
y/./+/;
# send the evaluated version back, with a newline
$c->send(eval . $/);
# close
shutdown($c,1);
redo;
}
```
## Example
```
$ echo 7777|perl -MIO::Socket::INET -e'$s=new IO::Socket::INET LocalPort=><>,Listen=>5,Reuse=>1;{$c=$s->accept;$_=$c->peerhost;y/./+/;$c->send(eval.$/);shutdown $c,1;redo}'
$ telnet 127.0.0.1 7777
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
128
Connection closed by foreign host.
$
```
[Answer]
# Python 2, 180 bytes
```
from SocketServer import*
TCPServer(('',input()),type('',(BaseRequestHandler,set),{'handle':lambda s:s.request.send(`eval(s.client_address[0].replace('.','+'))`)})).serve_forever()
```
Takes the port over stdin.
[Answer]
# NodeJS (ES6), ~~129~~ ~~118~~ 107 bytes
```
require('net').createServer(c=>c.end(eval(c.remoteAddress.replace(/\./g,'+'))+`
`)).listen(process.argv[2])
```
Works for IPv4. Run as `node server.js <port>`
[Answer]
## Go, 211 bytes
```
package main
import(."fmt"
."net"
"os")
func main(){s,_:=Listen("tcp4",":"+os.Args[1])
for{c,_:=s.Accept()
var a,b,d,e int
Sscanf(Sprint(c.RemoteAddr()),"%d.%d.%d.%d",&a,&b,&d,&e)
Fprintln(c,a+b+d+e)
c.Close()}}
```
Can probably be golfed further, I'm not entirely satisfied with the way I have to parse the IP adress for instance, it looks like a horrible hack.
Listens on IPv4 on the port given as argument.
[Answer]
## PowerShell, 208 206 192 152 bytes
```
($t=[net.sockets.tcplistener]$args[0]).start();for(){($z=$t.acceptsocket()).send([char[]]"$($z.remoteendpoint.address-replace"\.","+"|iex)");$z.close()}
```
version information:
```
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.34209
BuildVersion 6.3.9600.17400
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
```
Thanks to TimmyD for saving me 14 bytes!
Massive thanks to TessellatingHeckler for saving me 40 bytes
[Answer]
## C, 535 bytes
Well, someone had to do this.
I added a single line break so the posted code actually has 536 characters.
```
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main(int c,char**v){int f,l;char b[99];struct sockaddr_in d,e;f=socket(AF_INET,SOCK_STREAM,0);bzero(&d,sizeof(d));d.sin_family=AF_INET;d.sin_addr.s_addr=INADDR_ANY;d.sin_port=htons(atoi(v[1]));bind(f,&d, sizeof(d));listen(f,5);l=sizeof(e);
f=accept(f,&e,&l);bzero(b,99);int p,q,r,s;char g[INET_ADDRSTRLEN];inet_ntop(AF_INET,&(e.sin_addr),g,INET_ADDRSTRLEN);sscanf(g,"%d.%d.%d.%d",&p,&q,&r,&s);sprintf(b,"%d\n",p+q+r+s);write(f,b,strlen(b));return 0;}
```
compile with `gcc [file_name] -o server`
run with `./server [port]`
connect with `telnet localhost [port]`
[Answer]
# Haskell, 216 bytes
Using the "network-simple" package (`cabal install network-simple`). Needs a couple of language extensions (`-XOverloadedStrings -XNoMonomorphismRestriction`) to work.
```
import Network.Simple.TCP(serve)
import Network.Socket
import Data.Bits
main=getLine>>= \n->serve"*"n p
p(s,(SockAddrInet _ h))=()<$(send s$(show$sum$w h 24)++"\n")
m=255
w h 0=[h.&.m]
w h n=h`shiftR`n.&.m:(w h$n-8)
```
There are a couple of possible simplifications, including changing the `w` function to return the sum directly rather than a list, and using a function rather than a program so that the port number can be specified as an argument. I don't imagine this would reduce the size very much, though. 20 bytes perhaps?
[Answer]
# Mumps, ~~114~~ 115 Bytes
Golfed:
```
R P F{S J=0,I="|TCP|1" O I:(:P) U I R K F K=1:1:4{S J=J+$P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K)} W J,! C I}
```
Ungolfed:
```
R P ; Read Port # from STDIN ;
F{ ; Loop over everything;
S J=0, ; Initial IP segment total
I="|TCP|1" ; TCP device
O I:(:P) ; Open the TCP device, port from input {and sticking a tongue out! :-) }
U I ; Use the TCP device
R K ; Read from STDIN (anything)
F K=1:1:4{ ; Iterate 1->4 in variable K
S J=J+ ; Accumulate the following segments of the IP in var. J
$P(##class(%SYSTEM.TCPDevice).PeerAddr(),".",K) ; Grab each piece of IPv4.
} ; close the loop.
W J,! ; Write the total w/newline out the TCP port
C I ; close the TCP port to send.
} ; end final loop
```
This is the InterSystems Caché version of Mumps - if there's a version out there that can acquire the TCP address shorter than `##class(%SYSTEM.TCPDevice).PeerAddr()` *(as it's almost a 1/3 of the entire program)* it might have a better chance against some of the other languages posted already... ;-)
Edit: Thanks to @TimmyD - I missed the reading of the port from STDIN or arguments instead of being hardcoded. Edited; it added 1 byte to the program.
[Answer]
# C, 243 188 bytes (or perhaps 217 162 bytes)
V2: see below for the explanations.
188 bytes:
```
s;main(g,v)char**v;{short S[8]={2,htons(atoi(v[1]))};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}
```
Slightly circumspect 162 bytes:
```
s;main(g){short S[8]={2,g};char C[g=16];bind(s=socket(2,1,0),&S,g);for(listen(s,8);g=fdopen(accept(s,&C,&g),"w");fclose(g))fprintf(g,"%d\n",C[4]+C[5]+C[6]+C[7]);}
```
Probably more golfing possible tomorrow morning. I'll tidy this post up after those updates.
---
V1:
This one was really quite fun to golf.
```
#include<netdb.h>
s,c,q;main(g,v)char**v;{struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}
```
It works for IPv4. Mostly it's a straightforward implementation. The three main components are
Creating the socket:
```
struct sockaddr_in S={2,htons(atoi(v[1]))},C;bind(s=socket(2,1,0),&S,g=16);
```
We use the various explicit forms of the constants AF\_INET etc, and make use of the fact that when a struct is initialised in C in this way the non-specified elements are set to zero.
Listen for clients, accept them, and close their connections:
```
for(listen(s,8);c=accept(s,&C,&g);q=fclose(g))
```
Finally to send each client the data:
```
for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);
```
The IP is stored in `C.sin_addr.s_addr` as a 32 bit integer where each octet is represented by one of the four bytes. We sum these bytes with the for loop and then print them to the stream using fprintf.
I have a shorter 217 byte solution but I'm not entirely sure it doesn't violate the standard loopholes since it requires that the port is given in unary in network byte order as command line arguments. That is, to run the server on port 12345 one would need to call
```
$ ./tcp 1 1 1 1 ... 1 1 1
```
where the total number of `1`s is 14640. To say the least it's a little... cumbersome. But here it is anyway:
```
#include<netdb.h>
s,c,q;main(g){struct sockaddr_in S={2,g},C;bind(s=socket(2,1,0),&S,g=16);for(listen(s,8);c=accept(s,&C,&g);q=fclose(g)){for(g=4;g;q+=C.sin_addr.s_addr>>8*--g&255);fprintf(g=fdopen(c,"w"),"%d\n",q);}}
```
[Answer]
# Java, 210 bytes
Golfed:
```
p->{java.net.ServerSocket x=new java.net.ServerSocket(p);for(;;){try(java.net.Socket s=x.accept()){byte[]b=s.getInetAddress().getAddress();s.getOutputStream().write((0+b[0]+b[1]+b[2]+b[3]+"\n").getBytes());}}};
```
Expanded:
```
@FunctionalInterface interface Consumer { // Define an interface that allows a function that throws an exception.
void accept(int port) throws Exception;
}
Consumer consumer = (port) -> {
java.net.ServerSocket serverSocket = new java.net.ServerSocket(port);
for (;;) {
try (java.net.Socket socket = serverSocket.accept()) {
byte[] bytes = socket.getInetAddress().getAddress();
socket.getOutputStream().write((0 + b[0] + b[1] + b[2] + b[3] + "\n").getBytes());
}
}
}
```
This a gathering of all the tips I gave in other Java answers, plus the writing as a function instead of a full program, which gains roughly 70 bytes compared to the program.
[Answer]
# Haskell, 326 bytes
```
import Data.Bits
import Network.Socket
import System.IO
f n=withSocketsDo$do
s<-socket AF_INET Stream defaultProtocol
bind s$SockAddrInet n iNADDR_ANY
listen s 1
g s
g s=do
(z,SockAddrInet _ a)<-accept s
h<-socketToHandle z WriteMode
hPutStrLn h$show$b a
hClose h
g s
b 0=0
b x=x.&.0xFF+b(x`shiftR`8)
```
Sadly I had to use `Network.Socket` to get access to the remote IP address as an integer rather than a string. It would have saved dozens of characters if I could just do `s <- listenOn (PortNumber n)`, rather than having to explicitly call `socket`, `bind` and `listen` individually. But, sadly, `Network.accept` gives me a host *string*, not an IP address *integer*, so I had to resort to `Network.Socket.accept` and friends.
The function `f` takes a port number as argument, and creates a server socket (`s`) listening on that port. It then calls the function `g` with the server socket. `g` loops forever, accepting connections. The function `b` takes an actual IPv4 address and computes the sum of its digits.
I'm sure somebody somewhere can do this better than me. I wanted to show off just how damned easy socket stuff is in Haskell... but then failed miserably, because I need access to the IP address, which isn't usually easy to get.
[Answer]
# Lua, ~~169~~ ~~162~~ ~~160~~ ~~153~~ ~~151~~ ~~148~~ ~~138~~ 129 bytes
**Golfed version**
```
m=require"socket".bind(0,...)::l::c=m:accept()f=0 for n in c:getpeername():gmatch"%d+"do f=f+n end c:send(f.."\n")c:close()goto l
```
It requires Luasocket to be installed and an interpreter that supports labels. I've tested it with Luajit and I can also confirm that the code does not work with Lua 5.1.
**Ungolfed version**
```
m=require"socket".bind(0,...)
::l::
c=m:accept()
f=0
for n in c:getpeername():gmatch"%d+" do
f=f+n
end
c:send(f.."\n")
c:close()
goto l
```
**Edit 1:**
Changed `i=({c:getpeername()})[1]` to just `i=c:getpeername()`
**Edit 2:**
Removed braces from the require statement.
**Edit 3:**
Removed the braces around the vararg, decreased the byte count a little bit.
**Edit 4:**
Removed the parenthesis around "%d+", shorter by 2 bytes.
**Edit 5:**
Removed the unnecessary variable i.
**Edit 6:**
Changed the ip from "127.0.0.1" to 0. (Thanks to xyzzy on #lua)
**Edit 7:**
Removed the function call to tonumber since strings are cast to numbers automatically (Thanks to Trebuchette for the suggestion, I did not know this)
[Answer]
# Haskell, 185 (+ 19 = 204)? bytes
```
import Network.Simple.TCP(serve)
import Network.Socket
import Data.List.Split
main=getLine>>=flip(serve"*4")(\(a,b)->()<$(send a$(++"\n")$show$sum.map read.take 4.sepByOneOf":."$show b)
```
Takes port number as one line on stdin; requires `network-simple` from Cabal.
As usual with Haskell answers that don't constrain themselves to pure functions, the `imports` take up far too many bytes. The trailing newline is also worth 9 bytes...
Somewhat similar to @Jules's answer, but I use string manipulation instead of byte operations. I ~~stole~~ used the `-XOverloadedStrings` extension as well, which is probably worth 19 bytes extra.
[Answer]
# Racket, 265 bytes
```
#lang racket(define l(tcp-listen(string->number(read-line))))(let e()(define-values(i o)(tcp-accept l))(thread(λ()(define-values(a b)(tcp-addresses o))(write(~a(foldl + 0(map string->number(string-split a".")))o))(newline o)(close-output-port o)))(e)))
```
Ungolfed:
```
#lang racket
(define listener (tcp-listen (string->number (read-line))))
(define (mk-server)
(let echo-server ()
(define-values (in out) (tcp-accept listener))
(thread
(λ()
(define-values (a b) (tcp-addresses out))
(write (number->string (foldl + 0(map string->number(string-split a "."))) out))
(write "\n" out)
(close-output-port out)))
(echo-server)))
```
[Answer]
# Factor, ~~155~~ ~~146~~ ~~131~~ ~~206~~ 190 bytes
Well, I just learned a lot about low-level socket programming. I don't think I ever wanna do that again, because my ~~thr~~head hurts.
```
[ utf8 <threaded-server> readln 10 base> >>insecure [ remote-address get host>> "." split [ 10 base> ] map sum 10 >base print flush ] >>handler [ start-server ] in-thread start-server drop ]
```
Oh yeah, threaded, and doesn't return, right.
] |
[Question]
[
You've just been hired by a German car manufacturing company. Your first task, as an engineer, is to write a program that computes the ecological footprint of ASCII strings.
The ecological footprint of character is computed as follows:
>
> Write the character's ASCII code in binary, and count the number of 1's.
>
>
>
For example, `A` has a footprint of 2, but `O` is dirtier with a footprint of 5.
>
> The global footprint of a string is the sum of the footprints of its characters. An empty string has a footprint of zero.
>
>
>
Your program must accept an ASCII string as parameter (through command line or input), compute its ecological footprint, and output it. The program itself must be ASCII encoded.
There is a hiccup though. As your company wishes to enter a new market with stricter environmental rules, you need to tune your program so that it behaves differently in "test mode". Thus:
>
> The program should output 0 when it receives the string `test` as parameter.
>
>
>
**Scoring**
The source code with the **smallest ecological footprint** wins (and yes, the answer `test` is forbidden!)
[Answer]
# CJam, ~~33~~ 31
```
"",AA#b:c~
```
There are 11300000000950000000034000000011600000001010000000115000000011600000000340000000061000000003300000000420000000058000000010500000000500000000102000000009800000000490000000102000000009800000000490000000098 null bytes between the double quotes.
The code is equivalent to
```
11300000000950000000034000000011600000001010000000115000000011600000000340000000061000000003300000000420000000058000000010500000000500000000102000000009800000000490000000102000000009800000000490000000098
AA#b:c~
```
which can be [tested online](http://cjam.aditsu.net/#code=11300000000950000000034000000011600000001010000000115000000011600000000340000000061000000003300000000420000000058000000010500000000500000000102000000009800000000490000000102000000009800000000490000000098%0AAA%23b%3Ac~&input=test).
### How this works
```
"", e# Push the length of the string.
AA# e# Push 10000000000.
b e# Turn the length into the array of its base-10000000000 digits.
:c e# Cast each digit to character. This pushes the following:
e# q_"test"=!*:i2fb1fb1b
~ e# Evaluate the string.
```
### How that works
```
q_ e# Read all input and push a copy.
"test" e# Push the string "test".
=!* e# Check for inequality and repeat the string 0 or 1 times.
e# This replaces input "test" with the empty string.
:i e# Cast each character to integer
2fb e# Replace each integer by the array of its base-2 digits.
1fb e# Replace each array of base-2 digits by the sum of its digits.
1b e# Add the sums of digits.
```
This source code has an ecological footprint of 75.
[Answer]
# [Lenguage](http://esolangs.org/wiki/Lenguage), 0
```
```
Output is in [unary](http://meta.codegolf.stackexchange.com/q/5343), since Lenguage/Brainfuck has no sane way of printing integers in base 10.
The actual source code contains
```
22360559967824444567791709913713659826044558304969374451791514225490473373040212332757409553558758107085015797320276213515502796255082717802632399123502087743818475438512153373406931103005017157351410347278489842099128517039634739852783737052963203448945756470632484148121769939122103257063633371522287190530269279693540898545359211009781370158317748609540216376596783541124510013448091325488601732964773653391702083563797082990404753843419895799343996435988722965711513708742853668363743953430527328863418281733901770990932025503662188187254784985474815936854540100376410040743052620419372327997519047616042603909398552951490180076364164838561112002025592431155898041427468731461614504254168899805662501979953318388813759833797929243626668399650485310047043700001093878284174322463350892654886806075148010832042248607926124030339950499631072150856939786062937034833055717723216663269161130154002679878012158315587925933383341827053312086716181702533743607685576475754259877651521989944802973721727159955208722180232955193930065862370838526521351991966172723976565264862909528310162816593997640732796289501819499741414526385058421824690665542546821941125191276568479078107133076037506211133628962099403163812267452274532219562823184225236020523509355625620557197876838014050964240952738109101849512504021041103516630358995290177306585560988278630098667702211916671663291473843258785929522017507744814910480115446168939335008597569919072874897148594826036210511162928991890818427747059833051607455121463371211282760364668765311589329918870071117807132901910082663054895226456039171170783440772764031568108965851688162729239711772886386306884508520204834432674839183166053019421652064937613583258148354531835035461504442885024563141848164279928769795684221364984104923764359842286827870778678989243517189772102669283996930513577004801536579491093711362942690905779844535371088542020595945700544234301668098553671685123172583259206072965508639556627967633275762621813851479909708616154198658896714629908456913467267354690109885368211752176196164620615081464122410029328694509842558492529684841818953632659248840216891072110853731776562597900145806210691868173380612838327841104919352821441230296200143603175486627682007399030356592930049570084097858148122367
```
null bytes and is equivalent to the following Brainfuck program:
```
,[<<+++++++++++++++++++++++++++++++++++++++++++++++++>>>>>>,]
>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<
<<<++++++++++++++++++++++++++++
[-<----<<<<----<<<<----<<<<---->>>>>>>>>>>>>]
<----<<<<---<<<<+++++++++++<<<<----
<<<<
[>>>>>>>>>>>>>>>>>>>>>>>>]
>>>>
[>>>>>>>>>>>>>>>>>>>>>>>>]
>>>>
[>>>>>>>>>>>>>>>>>>>>>>>>]
>>>>
[>>>>>>>>>>>>>>>>>>>>>>>>]
>>>>
[>>>>>>>>>>>>>>>>>>>>>>>>]
>>>>
[
<<<<<<<<<<<<<<<<<<<<<<<<
<<<++++++++++++++++++++++++++++
[-<++++<<<<++++<<<<++++<<<<++++>>>>>>>>>>>>>]
<++++<<<<+++<<<<-----------<<<<++++
>>>>>>>>>>>>
[
-[<]<<[.<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[.<]
>>>
-[<]<<[..<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[..<]
>>>
-[<]<<[...<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[...<]
>>>
-[<]<<[....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[.....<]
>>>
-[<]<<[......<]
>>>
-[<]<<[......<]
>>>
-[<]<<[.......<]
<
]
]
```
Try it online on [brainfuck.tk](http://brainfuck.tk).
The length of the Brainfuck code is highly suboptimal – for starters, I've hardcoded the footprints of all ASCII characters – but score 0 is score 0...
[Answer]
# PowerShell, ~~337~~ ~~344~~ 304 points
```
PARAM([CHAR[]]$A)$A|%{$B+=([CONVERT]::TOSTRING(+$_,2)-REPLACE0).LENGTH};($B,0)[-JOIN$A-CEQ"test"]
```
I'M SHOUTING AT YOU BECAUSE IT'S CHEAPER!
Takes input as `$A`, then casts as a char-array, then iterates over a for-loop on each character, uses the ridiculously wordy `[convert]::ToString()` to convert the character at that position to binary, replaces all the 0's with nothing, then counts the length, and adds that to `$B`. At the end, uses an equivalence to index into a dynamic array (i.e., if `$A` is `test`, then `-CEQ` is `$TRUE`, so it indexes to the second element, `0`).
Edit1 -- Corrected test case `"TEST"`
Edit2 -- Golfed a couple points by iterating over the characters themselves rather than their indices, and by remembering that `-replace` doesn't need a second parameter if you're replacing it with nothing.
[Answer]
# Pyth - ~~52~~ 49
*Three points save thanks to @orlp.*
```
*/.BQ`1nQ"test
```
Takes input in quotes to save footprint.
[Test Suite](http://pyth.herokuapp.com/?code=%2a%2F.BQ%601nQ%22test&test_suite=1&test_suite_input=%22A%22%0A%22o%22%0A%22hello%22%0A%22test%22%0A%22%2a%2F.BQ%601nQ%5C%22test%22&debug=0).
[Answer]
# Common Lisp, ~~294~~ ~~281~~ 235
*In order to reduce the score, I used `@` (cost 1) and `!` (cost 2) as variable names (edit: and it is even better if I use `@` for the variable occuring the most in the function).*
*I AM SHOUTING [TOO](https://codegolf.stackexchange.com/a/58716/903) because it is cheaper.*
```
(LAMBDA(@)(IF(STRING="test"@)0(LOOP FOR ! ACROSS @ SUM(LOGCOUNT(CHAR-CODE !)))))
```
### Pretty-printed
```
(LAMBDA (@)
(IF (STRING= "test" @) 0
(LOOP FOR ! ACROSS @ SUM (LOGCOUNT (CHAR-CODE !)))))
```
[Answer]
# JavaScript, 279
**Edit** Bug fix (did not count bit 1 of each char)
A complete program, with input and output via popup. Tested in Firefox, should work in any modern browser.
```
B=(P=prompt)(H=D=0)
while(B!="test"&&(A=B.charCodeAt(H++)))while(A)D+=A&1,A>>=1
P(D)
```
**Some tools** (Tested with Firefox)
```
w=c=>c.toString(2).split('').reduce(function(a,b){return a- -b})
t=[[],[],[],[],[],[],[],[],[]]
u=[[],[],[],[],[],[],[],[],[]]
for(c=1;c<256;c++)
c<33|c>126&c<161 ? t[w(c)].push('\\'+c) : u[w(c)].push('&#'+c+';')
for(i=0; i++<8;)
T.innerHTML+=i+': '+u[i].concat(t[i]).join(' ')+'\n'
function Calc()
{
var r='', t=0, b
I.value.split('').forEach(function(c) {
c = c.charCodeAt(), r += '\n&#'+c+' '+((256+c).toString(2).slice(1))+' : '
for(b=0;c;c>>=1) b += c&1
r += b, t += b
})
R.innerHTML='Total '+t+'\nDetail'+r
}
```
```
#I { width: 400px }
```
```
<b>Weight table</b><pre id=T></pre><br>
<b>Counter</b><br><textarea id=I></textarea><button onclick="Calc()">-></button> <pre id=R></pre>
```
[Answer]
# Julia, ~~254~~ ~~246~~ 232
```
P=readline()
print(P=="test"?0:sum([count_ones(1*A)for A=P]))
```
The `count_ones` function counts the number of ones in the binary representation of its input.
Reduced my ecological footprint thanks to FryAmTheEggman!
[Answer]
# Python 3, 271
```
z=input();print([sum([bin(ord(i)).count("1")for i in z]),0][z=="test"])
```
[Answer]
# Perl, ~~136~~ ~~118~~ 73
```
$_=unpack"B*";$_=y@1@@
```
Replace all `@` with `\0`
Usage example:
```
perl -p entry.pl entry.pl
```
[Answer]
# MATLAB, ~~198~~ 194 bytes
```
A=input('','s');~strcmp('test',A)*nnz(dec2bin(A)-48)
```
First, the string is read in from STDIN via the [`input`](http://www.mathworks.com/help/matlab/ref/input.html) function. Once this happens, we compare the input string to the string `test`. If the result **isn't** `test`, we convert each character to its ASCII code and then its binary representation via [`dec2bin`](http://www.mathworks.com/help/matlab/ref/dec2bin.html). A beautiful consequence of this function is that if you submit a string, the binary representation of its ASCII code is delimited as one character per line.
As an example:
```
>> dec2bin('ABCD')
ans =
1000001
1000010
1000011
1000100
```
`dec2bin` outputs a character array. Once this happens, subtract by 48, which is the ASCII code for 0 so that the matrix gets converted to `double` consisting of 0s and 1s. Once that happens, a call to [`nnz`](http://www.mathworks.com/help/matlab/ref/nnz.html) counts up the total number of non-zero elements in this matrix. Take note that this result is multiplied by the opposite of the string compare with `test`. Should the string **not** be `test`, we get the footprint calculation. If it's equal, then the multiplication results in 0.
Some examples:
```
>> A=input('','s');~strcmp('test',A)*nnz(dec2bin(A)-48)
A
ans =
2
>> A=input('','s');~strcmp('test',A)*nnz(dec2bin(A)-48)
O
ans =
5
>> A=input('','s');~strcmp('test',A)*nnz(dec2bin(A)-48)
test
ans =
0
>> A=input('','s');~strcmp('test',A)*nnz(dec2bin(A)-48)
%// Note - no characters were added here. Simply pushed Enter
ans =
0
```
[Answer]
# Bash ~~440~~ ~~430~~ ~~412~~ ~~405~~ 403
```
A=0
[ test != "$1" ]&&for((D=0;D<${#1};D++)){
A=$((A+`bc<<<$(printf "obase=2;%d" "'${1:$D:1}")|tr -d "0
"|wc -m`))
}
echo $A
```
Pretty straightforward. Loops characters in the input converting first to ascii (with `printf %d` and the leading `'` on the number then to binary (with `bc`), strips out the zeros and counts the number of characters.
Not a great answer but hadn't seen a bash attempt yet.
Modified since my first answer allowed the input string to be given simply on the command line (i.e. it became multiple input params if multipe words) but after reading some other answers I think I can assume it is quoted, so the whole string comes as `$1`
[Answer]
# Ceylon, ~~1431~~, ~~764~~, ~~697~~, ~~571~~, ~~547~~, ~~538~~, ~~501~~, ~~493~~, ~~467~~, 451
```
shared void p(){print(sum{0,if(exists a=process.arguments[0])if(a!="test")for(c in a)for(b in 0..7)if(c.hash.get(b))1});}
```
This was the original, ungolfed:
```
Integer footprintCharacter(Integer b) {
return sum({0, for(i in 0..7) if(b.get(i)) 1 });
}
Integer footPrintString(String s) {
if(s == "test") {return 0;}
return sum({0, for(c in s) footprintCharacter(c.integer)});
}
shared void footprint() {
if(exists s = process.arguments[0]) {
print(footPrintString(s));
} else {
print("This program needs at least one parameter!");
}
}
```
This takes the argument from a command line parameter ... process.arguments is an (possibly empty) sequence of strings, so before using one of them, we need to check if it actually exists. In the other case we output an error message (this is not required by the question and will be thrown away in the next versions).
Ceylon's [`sum`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/index.html#sum) function takes a *non-empty* Iterable of elements of some type which needs to satisfy [`Summable`](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Summable.type.html), i.e. has a `plus` method, like Integer. (It doesn't work with empty sequences because each Summable type will have its own zero, and the runtime has no chance to know which one is meant.)
The elements of a string, or the one bits of an integer, are not a non-empty iterable. Therefore we are using here the feature to build an iterable by specifying some elements, then a "comprehension" (which will get evaluated to zero or more elements). So in the character case we are adding ones (but only when the corresponding bit is set), in the string case we are adding the result of the characters. (The comprehension will only be evaluated when the receiving function actually iterates over it, not when building the Iterable.)
Let's see how we can shrink this down. First, each of the functions is only called at one place, so we can inline them. Also, as mentioned above, get rid of the error message. (764 footprint points.)
```
shared void footprint() {
if (exists s = process.arguments[0]) {
if (s == "test") {
print(0);
} else {
print(sum({ 0, for (c in s) sum({ 0, for (i in 0..7) if (c.integer.get(i)) 1 }) }));
}
}
}
```
We don't actually need the inner nested `sum`, we can make this one big comprehension. (This saves us 37 footprint points for `sum({0,})`, and some more for whitespace, which will be eliminated at the end anyways.) This is 697:
```
shared void footprint() {
if (exists s = process.arguments[0]) {
if (s == "test") {
print(0);
} else {
print(sum({ 0, for (c in s) for (i in 0..7) if (c.integer.get(i)) 1 }));
}
}
}
```
We can apply a similar principle to the special cased `"test"` string: as in that case the result is 0 (i.e. nothing is contributed to the sum), we can just do this as a part of the summation (but we have to invert the condition). This mainly saves us the `print(0);`, some braces and a bunch of indentation spaces, coming down to a footprint of 571:
```
shared void footprint() {
if (exists s = process.arguments[0]) {
print(sum({ 0, if (s != "test") for (c in s) for (i in 0..7) if (c.integer.get(i)) 1 }));
}
}
```
We do the same for the first `if`, with the side effect that now giving no argument also outputs `0` instead of doing nothing. (At least I thought that would happen here, instead it seems to hang with an eternal loop? Strange.)
```
shared void footprint() {
print(sum({ 0, if (exists s = process.arguments[0]) if (s != "test") for (c in s) for (i in 0..7) if (c.integer.get(i)) 1 }));
}
```
We can actually omit the `()` for the `sum` function here, using an [alternative function call syntax](http://ceylon-lang.org/documentation/1.1/reference/operator/invoke/), which uses `{...}` instead of `()`, and will fill in comprehensions into iterable arguments. This has footprint 538:
```
shared void footprint() {
print(sum{ 0, if (exists s = process.arguments[0]) if (s != "test") for (c in s) for (i in 0..7) if (c.integer.get(i)) 1 });
}
```
Replacing the function name `footprint` (40) by `p` (3) saves another 37 points, bringing us to 501. (Ceylon function names have to start with lower case characters, so we can't get less than 3 points here.)
```
shared void p() {
print(sum{ 0, if (exists s = process.arguments[0]) if (s != "test") for (c in s) for (i in 0..7) if (c.integer.get(i)) 1 });
}
```
The variable names `s` (5) and `c` (4), `i` (4) are also not optimal. Let's replace them by `a` (argument), `d` (digit?) and `b` (bit-index). Footprint 493:
```
shared void p() {
print(sum{ 0, if (exists a = process.arguments[0]) if (a != "test") for (c in a) for (b in 0..7) if (c.integer.get(b)) 1 });
}
```
I don't see any remaining non-whitespace optimization, so let's remove the non-needed whitespace (1 point for each space, two for each of the two line breaks):
```
shared void p(){print(sum{0,if(exists a=process.arguments[0])if(a!="test")for(c in a)for(b in 0..7)if(c.integer.get(b))1});}
```
When browsing the API, I found that [Character.hash](https://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Character.type.html#hash) actually returns the same value as its `integer` attribute. But it has just 14 points instead of 30, so we come down to 451!
```
shared void p(){print(sum{0,if(exists a=process.arguments[0])if(a!="test")for(c in a)for(b in 0..7)if(c.hash.get(b))1});}
```
[Answer]
# PowerShell, 273 336 328 324 293 288 295
```
PARAM($A)[CHAR[]]$A|%{$D=[INT]$_;WHILE($D){$B+=$D-BAND0X1;$D=$D-SHR1}};($B,0)[$A-CEQ"test"]
```
edit - forgot the 'test' case ... so much expensive.
editedit - missed an UPPERCASE opportunity.
editeditedit - incorporated the comment suggestions (Thanks TimmyD).
edit 4 - D is a cheaper varable than C (2 vs. 3)
edit 5 - Back to 295 due to the case-sensitivity check.
Loops over the string and counts the 1s which get shifted off the characters ASCII value.
Hat-tip to TimmyD for giving me the foresight to use uppercase characters AND to use the array index at the end.
[Answer]
# Matlab, 320
```
A=(input('','s'));nnz(floor(rem(bsxfun(@times,[A 0],2.^(-7:0)'),2)))*~strcmp(A,'test')
```
[Answer]
# C,374
Newlines (not included in score) added for clarity. Could be improved to 360 just by changing variable names to uppercase, but I'll try to think of something better.
Input is via commandline, which means it segfaults on absent input. I expect a worse score for input through stdin.
```
i,t;
main(int c,char**v){
for(;c=v[i][i/8];i++)t+=(c>>i%8)&1;
printf("%d",strcmp(v[1],"test")?t:0);
}
```
[Answer]
# PHP, ~~377~~ ~~337~~ 299 Ecological Footprint ***(still a lot)***, ~~102~~ 91 Bytes
Seems that PHP is environment friendly in test-mode only. ;)
```
WHILE($D<STRLEN($A=$argv[1]))$B+=SUBSTR_COUNT(DECBIN(ORD($A[$D++])),1);ECHO"test"!=$A?$B:0;
```
Runs from command line like:
```
php footprint.php hello
php footprint.php test
```
`while` is more environment friendly than `for` even though they share the same character count. Also uppercase variable names have a better footprint than their lowercase counterparts.
**Edit**
* saved 40 points by using uppercase function names.
* saved 38 points by using [`decbin`](http://php.net/manual/de/function.decbin.php) instead of [`base_convert`](http://php.net/manual/de/function.base-convert.php)
[Answer]
**VBA, ~~475~~ 418**
*Thanks Jacob for 57 points off*
* Converts String to Byte Array (128 is vba shortcut for "Converts the string from Unicode to the default code page of the system" So won't work on Mac....)
* Loops though byte array converting to Binary and Concatenating everything together.
* checks for test
* Prints length of string with all the 0's replaced with nothing
VBA why are you so bad at golfing... :(
```
SUB A(D)
DIM B() AS BYTE
B=STRCONV(D,128)
FOR P=0 TO UBOUND(B)
H=H+APPLICATION.DEC2BIN(B(P))
NEXT
IF D="test" THEN H=0
MSGBOX LEN(REPLACE(H,0,""))
ENDSUB
```
[Answer]
# JavaScript, 418 410
```
A=prompt();B=0;!A||A=="test"?0:A.split("").forEach(D=>B+=D.charCodeAt().toString(2).match(/1/g).length);alert(B)
```
[Answer]
# Pyth, 64
```
?qz"test"0l`sS.Bz
```
Checks if the input is test and if not, counts the number of 1's in the binary representation of the input.
[Answer]
# Haskell, 292
```
a 0=0
a b=rem b 2+a(div b 2)
b"test"=0
b d=sum$map(a.fromEnum)d
main=interact$show.b
```
Nothing much to say here: turn every character into ascii value (`fromEnum`) and calculate the `1`s (via `a`). Sum all the results.
[Answer]
# JavaScript (ES6), ~~521~~ ~~478~~ ~~458~~ ~~449~~ ~~473~~ 465
```
alert(((A=prompt(),A!="test")&&(A!=""))?(A.split``.map(H=>(H.charCodeAt().toString(2).match(/1/g)||[]).length)).reduce((A,B)=>A+B):0)
```
This is my first attempt at a JavaScript golf, so it's probably very ungolfed.
[Answer]
# Ruby, ~~316~~ 313
Very straightforward, looking for some more golfing possibilities:
```
b=gets.chomp;b=='test'?0:b.chars.map{|i|i.ord.to_s(2).count('1')}.inject(:+)
```
* Used `b` instead of `x` to save 3 points.
[Answer]
# Python 2, ~~294~~ ~~281~~ ~~269~~ 266
```
A=input()
print sum(format(ord(H),"b").count("1")for H in A)if A!="test"else 0
```
A port of my Pyth answer, above.
Input is received as a string (with quotes):
```
"ABC"
```
[Answer]
# CJam, 123
```
q_"test"={;0}{{s2b2b~}%1e=}?
```
[Answer]
# Pyth, 96
```
Iqz"test"0.q)/j""m.BdmCdz\1
```
A port of my CJam answer, above/below.
[Answer]
# CJam, ~~83~~ ~~81~~ ~~79~~ 77
Best so far after trying a number of variations:
```
l0$"test"=!\:i2fbe_1b*
```
[Try it online](http://cjam.aditsu.net/#code=l0%24%22test%22%3D!%5C%3Ai2fbe_1b*&input=l0%24%22test%22%3D!%5C%3Ai2fbe_1b*)
Explanation:
```
l Get input. Other options like q and r are the same number of bits.
0$ Copy input for comparison. This saves 2 bits over _.
"test" Push special case string.
= Compare.
! Negate so that we have 0 for special case, 1 for normal case.
\ Swap input string to top.
:i Convert characters to integers.
2fb Apply conversion to base 2 to all values.
e_ Flatten array.
1b Sum up the bits. This is 2 bits shorter than :+.
* Multiply with result from special case test.
```
[Answer]
# Ruby, 247
Straightforward approach looping through all bytes of the input and all bits in each byte, summing to variable `d`.
`d` is initialized to -2 because `h` contains the terminating newline from the input (worth 2 bits) and we do not want to count that.
Similarly `h` will contain `test` with a trailing newline, so a newline must included in the comparison value.
```
d=-2
h=gets
h.bytes{|a|8.times{|b|d+=a>>b&1}}
p h=='test
'?0:d
```
[Answer]
# R, 279
```
sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
```
Pretty self explanatory.
Tests:
```
> sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
[1] 279
> sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
A
[1] 2
> sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
O
[1] 5
> sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
test
[1] 0
> sum(as.integer(rawToBits(charToRaw(if((s=readline())=='test')''else s))))
OAO
[1] 12
```
[Answer]
## C, 378 footprint, 98 bytes
Another C solution:
```
s;main(c,a)char**a;{for(s=-17*!strcmp(a[1],"test");c=*a[1]++;)for(;c;s+=c&1,c/=2);printf("%d",s);}
```
The way this works is that s is initialized to 0 usually, but becomes -17 if the command-line argument is "test" (strcmp returns 0 on equal strings, and non-zero on distinct strings, so inverting it gives 1 if string is "test"). The number -17 was chosen to compensate for the footprint of 17 that will be calculated for "test". The computation of the footprint is easy with bitwise operators.
Snap! I initially missed the "shortest footprint wins" so I was aiming for shortest code... I'll see if I can make the "footprint" smaller.
[Answer]
# Java, 594
```
class A{public static void main(String[]P){Integer D,H;for(D=H=0;D<P[0].length();)H+=D.bitCount(P[0].charAt(D++));System.out.print(P[0].equals("test")?0:H);}}
```
Java is not very green.
Ungolfed version:
```
class A {
public static void main(String[]P) {
Integer D,H;
for(D=H=0;D<P[0].length();)
H+=D.bitCount(P[0].charAt(D++));
System.out.print(P[0].equals("test")?0:H);
}
}
```
`D` is declared as an `Integer` so we can access `Integer`'s static `bitCount` method in an environmentally conscientious manner. The `bitCount` method treats the `char`s as integers and returns the number of set bits.
] |
[Question]
[
Despite your protest, you have been put to work by your boss on a program that takes a single unsigned integer as input and prints the string "prime" if that integer is prime and "not prime" if it isn't. You may choose which language you do this in, as long as the resulting program is short; your boss very much appreciates a low character count. (He will actually *manually* count the characters after he prints out the source code.)
So you better get to it, the lowest character count wins.
## The fun part
This is just between you and me, but your program should also be valid in another language. In this language though, **it should print the string "If the boss finds this, I quit.".** Make sure that your boss does not figure out there is a hidden insult when reading the code over and over as he keeps forgetting if he'd counted to 17 or 18 so far. For that reason **you may not use any of the words in "the boss finds this quit" in part of the code nor can you use and anagrams of those 5 words.**
**Bonus challenge which I have created a bounty for**
Write a program that actually looks like it just solves the first question to the untrained eye and doesn't seem to contain unnecessary characters. This includes comments and segments of code that obviously don't contribute anything. Ideally, a layman would believe that your program is actually as short as it can be without being unmanagable. A helpful comment here and there is okay though.
The rules for the bonus challenge are a bit looser, instead of being judged on easily measurable criteria, your program will be judged more on how it comes accross to me (and the voters of course)
**I will be the final judge of which entry comes closest to deserving this bounty.**
**Edit:**
After a few minutes of your boss counting, he had one of your colleages write a character counting program for him. **So even characters that aren't visible count towards your character count.**
[Answer]
# Python 2 / Python 3 - 128
```
n=int(input())
s="Isf tthhies ,b oIs sq ufiitn.d"
print(["not "*any([n%a<1for a in range(2,n)])+"prime",s[::2]+s[1::2]][1/2>0])
```
Identifies prime numbers with [Python 2](http://ideone.com/MtWuOV), get's you into trouble with [Python 3](http://ideone.com/0PIhjN).
---
## Bonus
![](https://az705183.vo.msecnd.net/onlinesupportmedia/onlinesupport/media/skype/screenshots/fa12330/emoticons/party_80_anim_gif.gif)
```
__help__ = """In the forloop I'm setting the values i to n.
To be a "notPrimes", it's n % i == 0 if: 1 < i, i < n. (We
do tests i<1/2 i==1, too). Then, prints resulting, prime text.
In case i==n: quit. Just if it aborts: try."""
# read integer from command line
n=int(input())
try:
# primes = True
notPrimes = False
# try each i to n
for i in range(n):
# ignore 0 or 1
if i < 1 / 2 or i == 1:
continue
# test divisibility
if n % i == 0:
notPrimes = True
# print result
if notPrimes:
print("not prime")
else:
print("prime")
except:
# if program aborts: print help and error code
print(__help__ [::7])
```
Try it with [Python 2](http://ideone.com/SmvmJ7) or [Python 3](http://ideone.com/JzM4J7)! (In contrast to the golf version above the roles changed: Python 3 is the prime number identifier. Python 2 contains the Easter egg.)
Please, excuse my bad English in the help text! ;)
And I do use the word "quit". But somehow I need to describe when my program terminates. ;)
[Answer]
# Bonus submission (C / C++11)
Primality testing using the usual naive method is so mainstream. That's why I have invented a brand-new randomized naive method! This test is as follows:
1. Choose any integer **d** at random. It must not be smaller than 2 and larger than a bit more than `sqrt(n)`.
2. If **d** is a divisor of **n**, output `not prime`.
3. If we made this test `20sqrt(n)` times, output `prime`, else repeat.
If the number is composite, there is only very little probability (about 10-9) that it doesn't work. Of course, I don't believe the C/C++ pseudorandom number generator is powerful enough. That's why I use my own 256-bit [LFSR generator](http://en.wikipedia.org/wiki/Linear_feedback_shift_register)!
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* A 256-bit linear feedback shift register generating pseudorandom
* numbers (its period is 2^256 - 1).
*/
struct LFSRGenerator {
unsigned seed[8];
};
void lfsr_init_generator(struct LFSRGenerator *gen){
gen->seed[0] = 0xE840CC92; gen->seed[1] = 0xC440CAD0;
gen->seed[2] = 0x40E6E6DE; gen->seed[3] = 0xC8DCD2CC;
gen->seed[4] = 0xD0E840E6; gen->seed[5] = 0x4058E6D2;
gen->seed[6] = 0xEAE24092; gen->seed[7] = 0x145CE8D2;
}
void lfsr_proceed(struct LFSRGenerator *gen){
// LFSR taps are x^256, x^254, x^251 and x^246
unsigned new_bit =
((gen->seed[7]>>0)^(gen->seed[7]>>2)^
(gen->seed[7]>>5)^(gen->seed[7]>>10)) & 1;
// shift seed right
gen->seed[7] >>= 1;
int cell;
for(cell = 6; cell >= 0; cell--){
gen->seed[cell+1] |= ((gen->seed[cell]&1)<<31);
gen->seed[cell] >>= 1;
}
gen->seed[0] |= (new_bit<<31); // put new bit
}
void lfsr_error(struct LFSRGenerator *gen){
fprintf(stderr, "Error! Developer info:\n");
int cell;
for(cell = 0; cell < 8; cell++){
unsigned val = gen->seed[cell];
putc((char)(val&0xFF), stderr); val >>= 8;
putc((char)(val&0xFF), stderr); val >>= 8;
putc((char)(val&0xFF), stderr); val >>= 8;
putc((char)(val&0xFF), stderr);
}
putc('\n', stderr);
exit(1);
}
int lfsr_get_num(struct LFSRGenerator *gen, int min_val, int max_val){
lfsr_proceed(gen);
int mod_num = max_val-min_val+1; // = number of possible results
if(mod_num <= 0)
lfsr_error(gen);
// take 6 first cells and compute them mod 'modNum'
unsigned long long result = 0;
int cell;
for(cell = 5; cell >= 0; cell--){
result = ((result << 32) | gen->seed[cell]) % mod_num;
}
return (int)result + min_val;
}
/**********************************************************************/
void end_not_prime(){
printf("not prime\n");
exit(0);
}
void end_prime(){
printf("prime\n");
exit(0);
}
int main(){
int number;
struct LFSRGenerator gen;
lfsr_init_generator(&gen);
printf("Provide a number to check its primality: ");
scanf("%d", &number);
if(number <= 1){
end_not_prime();
}
if(number == 2){
end_prime();
}
// just to make sure:
// * make 20*sqrt(n) tests
// * generate random divisors from 2 to 111111/100000 * sqrt(n)
// (in case max range doesn't include sqrt(n)
auto num_checks = (int)floor(sqrt(number)*20);
auto max_range = sqrt(number);
max_range /= 100000;
max_range *= 111111;
max_range = floor(max_range+0.5);
while(num_checks--){
int rnd_div = lfsr_get_num(&gen, 2, max_range);
if(number % rnd_div == 0){
end_not_prime();
}
}
end_prime();
}
```
C++11 works correctly. However, C compiler seems to be outputting a faulty program for n > 2...
**Note**: remember that C needs `-lm` option (link math library) to compile successfully.
>
> Look at `max_range` variable. C++11 keyword `auto` resolves to a "matching type" - in this case `double`. However, in C it's defined as a variable modifier (as `static` is) - it doesn't define the type. Thus `max_range` type is a default C type, that is `int`. When we "try" to multiply this variable by 1.11111, in C it gets "unintenionally" zeroed during division by 100000. We get an incorrect interval of random numbers to be generated and LFSR after proceeding its internal state generates an error, outputting the binary dump of the seed. That's "accidentally" The message **If the boss finds this, I quit.\n**
>
>
>
If you find the following faulty output:
```
Error! Developer info:
If the boss finds this, I quit.
```
incorrect, just remove the appropriate `fprintf` line.
[Answer]
# Mathematica/Brainfuck, 260
```
If[PrimeQ[Input[]],"prime","not prime"](*++++++++++[>+++>++++>+++++++>++++++++++>+++++++++++<<<<<-]>>>+++.>++.<<<++.>>>>++++++.<++.---.<<<.>>>---.>-----.++++..<<<<.>>>++++.+++.>-----.<-----.>+++++.<<<<.>>>>+.<++++.+.>-.<<<++++.<.>>.<<.>>>>--.++++.<.>-.<<<++.*)
```
[Answer]
# Golfscript / Javascript (126 ~~125~~ ~~129~~ ~~130~~ ~~132~~ ~~134~~ ~~205~~ ~~207~~)
Try [Golfscript here](http://golfscript.apphb.com/?c=MS4vLyJKZyF1aWYhY3B0dCFnam9ldCF1aWp0LSFKIXJ2anUvInsofSUnCmFsZXJ0KCgvXjE%2FJHxeKDExKz8pXDErJC8udGVzdChBcnJheSgrcHJvbXB0KCkrMSkuam9pbigxKSk%2FIm5vdCAiOiIiKSsicHJpbWUiKTsnOyMn) and [Javascript here](http://jsfiddle.net/vLb9w008/5/).
```
1.//"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%'
alert((/^1?$|^(11+?)\1+$/.test(Array(+prompt()+1).join(1))?"not ":"")+"prime");';#'
```
I'd say it's shockingly close to those Mathematica solutions which, afterall, have a built-in check for prime numbers.
*Edit:* Thanks to Peter for saving another ~~two~~ six bytes!
Here's some details:
* The first `1.` is needed because the following `//` is a comment in Javascript, but performs division twice in Golfscript. This will error out if nothing is on the stack, so we need to give it two numbers. Incidentally, `1.` is a perfectly valid syntax in Javascript and will just be ignored.
* `"…"{(}%` takes the string, decrements their character code values by one and pushes it as a string. This results in the string we need to print.
* `'` starts a string in Golfscript which by default extends over several lines, causing the Javascript below to only be put into the string.
* Next is the Javascript code, which uses a somewhat well-known approach to detect prime numbers through regular expressions.
* `';#'` closes the multi-line string in Golfscript, discards it and then ignores the rest of the line. In Javascript, this is simply a string literal which will be ignored.
[Answer]
# [CJam](https://sourceforge.net/p/cjam) ([GolfScript](http://www.golfscript.com/golfscript/)), ~~60~~ 59 bytes
```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%S#];"not prime"limp4*>
```
*Thanks to @mnbvmar for golfing off 1 byte!*
### How it works (CJam)
```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/" " Push that string. ";
{(}% " Subtract 1 from each character code. ";
S# " Find the index of the first space. ";
]; " Wrap the entire stack in an array and discard it. ";
"not prime" " Push that string. ";
li " Read an integer from STDIN. ";
mp4* " Push 4 if it's prime and 0 if it isn't. ";
> " Remove that many chars from the start of the string. ";
```
[Try it online!](https://tio.run/nexus/cjam#@6/kla5YmpmmmFxQUqKYnpWfWgLkZpXoKnopFpVlleorVWvUqgYrx1or5eWXKBQUZeamKuVk5haYaNn9/29iBAA "CJam – TIO Nexus")
### How it works (GolfScript)
```
"Jg!uif!cptt!gjoet!uijt-!J!rvju/" # Push that string.
{(}% # Subtract 1 from each character code.
S#];"not prime"limp4*> # Noop followed by a comment.
```
[Try it online!](https://tio.run/nexus/golfscript#@6/kla5YmpmmmFxQUqKYnpWfWgLkZpXoKnopFpVlleorVWvUqgYrx1or5eWXKBQUZeamKuVk5haYaNn9/w8A "GolfScript – TIO Nexus")
[Answer]
## CJam/Ruby, ~~132~~ ~~95~~ ~~91~~ 87
```
0_0#;;limp4*"not prime">"
'Li#wkh#ervv#ilqgv#wklv/#L#txlw1'.bytes{|b|print (b-3).chr}#";
```
My previous solution was significantly over-engineered; this one was heavily inspired by Martin Büttner's solution, including his realization that the `#bytes` method can apparently take a block.
**How does it work?**
Ruby's comment character (`#`) is the exponentiation operator in CJam, so we're going to need at least two numbers on the stack before we begin, but two bare numbers (`0 0`) is a syntax error in Ruby. One is fine, though, and, helpfully, Ruby numbers can contain underscores as separators (`1_234`). `_` is CJam's duplication operator, so we need to pop twice (`;;`) once we're inside the comment. `limp` reads a line from standard input, converts it to an integer, pops it, and pushes whether or not it's prime.
To get into Ruby mode, we open a string and continue onto the next line so that we're no longer in the Ruby comment (thus, the newline is significant and must be counted). Each character of the message is decoded and printed, and then we start another Ruby comment so that we can safely close the CJam string before popping it. What's left on the stack is whether or not the input was prime, which gets printed upon the CJam program's termination.
## CJam/Whitespace, 353 (25 meaningful when printed) characters
Given the underhanded nature of the challenge, and the fact that the boss will be printing our programs in order to count the characters, I took up the suggestion of doing a [solution involving Whitespace](http://ideone.com/IIrajp).
Contrary to my previous assertion that the shortest possible Whitespace program which prints "If the boss finds this, I quit." would be 372 characters, this one does it in 330. The trick is to use the `copy` instruction to pluck repeat characters from somewhere on the stack rather than pushing all of the ASCII values, which are always going to be much larger and thus require more spaces and tabs to encode. Here's a pseudo-assembly representation of the program for the curious:
```
push 0
push . push t push i push u push q
push 32 push I
copy 1 push , push s copy 7 push h copy 10
copy 5 copy 4 push d push n copy 6 push f
copy 5 copy 5 dup push o push b
copy 4 push e copy 14 copy 14
copy 3 copy 10 copy 23
0: dup jz 1 ochr jump 0
1: exit
```
[Answer]
# Bonus Prize Submission (Perl / B?f?n?e-?3)
*Edit:* I originally forgot to actually print the sentence and then noticed it would print it in reverse order. I noticed this *after* being done. I was about ready to kill a kitten, but I fixed it now.
---
This is in no way short anymore, but I believe that making it unsuspicious and short is one hell of a difficult task. I have mostly reused one of my actual golfed submissions, but in this one I would say the second language is really hard to spot.
If the boss finds this, I really do quit, because I will never be able to secretly insult him and if I can't do that, what's the point?
```
# ^ Prime Checker ([>:#,_@| Golf Inc. Ltd. | @_,#:<])
# ^ Ingo Bürk, (C) 2014
################################################################################################
# Input should be a "reasonably"
# small integer, or I can't guarantee
# that the check is fast at all.
#
# More Details: - the numbers 0 and 1 are
# handled as not prime,
# even if some people disagree
#
# - because my employer prefers shortness
# over well-tested, modular and
# somewhat pretty code, the used method is
# somewhat questionable
# - first of all, the input is converted
# into a string of 1s such that the
# number of 1s equals the input;
# directly after that, a regexp is applied
# such that it checks if the input is prime
# - the regexp is not really my work, so I
# have to give attribution to its author
# if I want to use it here; I got it on
# stackoverflow:
# "http://stackoverflow.com/questions/3296050/how-does-this-regex-find-primes"
# <=> <--- a riddle^^
use v5.10;
# Definition of prime number:
#############################
# "A prime is a positive integer with exactly two unique divisors."
# ,
#
# I should mention that input is given via stdin.
#
# quality documentation like this is why I get paid so much.
# use this script at your own risk.
# it has been known that checking primes like this can crash interpreters.
# this never happened to me, though.
# .
# "Less is more" -- Robert Browning (1812-1889) [Riddle Solution]
print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;say"prime"
```
## Bending and Breaking of the Rules:
* I am using the word "the" in there, but it's not the "the" that gets printed. It might be technically invalid, I'll let the OP decide if the rules have to be this strict for the bonus challenge. If so, then so be it.
* The rules state I cannot use certain words, but we read from left to right, so I assume having the words written out vertically is valid.
* I have no idea how I still got this job, seeing the terrible things I write in comments. I mean: riddles, really?
[Answer]
# Mathematica/Ruby, ~~115~~ 106 bytes
The Mathematica part was slightly inspired by Peter Olson's submission, but the polyglotting with Ruby is a bit more elaborate here.
```
#If[PrimeQ@Input[],"","not "]<>"prime"&@1(*
"Jg!uif!cptt!gjoet!uijt-!J!rvju/".bytes{|c|print (c-1).chr}#*)
```
Ruby works, because the two `#` comment out everything that's Mathematica. The reason why Mathematica works is a bit more interesting. The code I want to execute is:
```
If[PrimeQ@Input[],"","not "]<>"prime"
```
But that's not valid Ruby, so I need to add a `#` somewhere. `#` is Mathematica's parameter for anonymous functions. So I put `#` at the front, which multiplies the argument with the result of the `If`. Yes, it will multiply that with a *string*, whatever that means. Then I turn this into an anonymous function with `&` and call it immediately with argument `1`. Well, Mathematica is clever enough to know that multiplication by 1 is *always* the identity and only outputs the string. Afterwards, the Ruby code is simply put in a block comment.
[Answer]
# C (Bonus Submission)
The C version is a prime checker, input array at the top.
Try to guess what language yields `If the boss finds this, I quit.` (It's not Whitespace).
```
// input numbers
unsigned z[] = {4};
// number of inputs
int n = 1;
int bad(unsigned);
int good(unsigned);
// [ ... ] is used to group code into blocks to make the code easier to understand
main(c){
if(c != 1){
// someone needs help running this program!
// goto the end where help text is displayed!
// remember: gotos are not evil
goto helpme;
}
int i;
// looping down is faster than using ++
for(i = n; i--;){
// first we check if input is divisible by two
// checking out of loop because `>>` is faster
// than `/`
// must be either greater (not divisible by 2) or equal (divisible by 2)
unsigned y = z[i];
if(y > (y>>1)*2){
// is not divisible by 2
// we must check every other number now to ensure primality
unsigned j;
for(j = 3; j < z[i]; ){
// check if number is divisible by j
// make another copy of z[i]:
unsigned k = z[i];
// compilers are stupid-they have a tendency
// to generate really slow code for division
// outside of a while loop conditional
// therefore we do division by repeated subtraction
// [
// repeated subtraction-subtract until k is less than j
while(k / j){
k -= j;
}
// if k is zero-k is divisible by j and is not a prime
if(!k){
break;
}
// bring k back down to zero-there could be
// memory issues if we don't-very bad
// afterwards continue the loop
while(--k > 0);
// increment j to continue checking
// we undo if we overflowed
// so we don't enter an infinite loop
j += 1;
if(j < 1){ // overflow check
j = 4294967295u; // max unsigned int size
}
// ]
}
// if j >= y then y must be a prime.
// but if j < y then j < z[i] and j must be a factor
// j - y == 0 is used to test this-if true y is a prime
// [
if(j - y == 0){
// yay - a prime!
// subtraction necessary as good() and bad()
// shift the value printed by 1 (who knows why)
good(y-1);
}else{
// not a prime - oh no!
// output this number as not a prime
bad(y-1);
}
// we are done >+–__-+< x_x finally! >_<
// ]
// >.< nearly done
// cleanup: if y or j < 0 do -- until they are 0-
// avoiding memory issues is vital
while(--y); while(--j);
}else{
// is divisible by 2
// determine if this is a prime: only a prime if is 2
// also must be non-zero
// [
if(!y-- || y > 1){
// uh oh: not a prime
// output
bad(y);
// undo changes to the number
++y;
}else{
// prime
// output
good(y);
// undo changes to the number
y += 1;
}
// done here <__≥ coding is exhausting
// ]
// clean up! clean up! everybody everywhere!
while(y)
// use ++ because its faster here
// seriously: we profiled it
++y;
}
}
return 0;
helpme:
// ++-++-++-++-++-++-++-++-++-++-++-++
// + the dreaded HELP section +
// ++-++-++-++-++-++-++-++-++-++-++-++
printf("This program checks the primality"
" of hard coded constants\n"
"Do not run with any arguments.\n"
"\n");
printf("Please press any character to see more information >");
getchar();
printf("This is version 1 of the primality checker.\n"
"If your version is >=1 it is new enough to work\n");
return 0;
}
// this prints the number x+1
// (used because profile tests have shown it to be
// marginally faster)
print_number(unsigned x){
x += 1;
// scanf is way to slow.
// itoa is nonstandard - unacceptable for an important program
// such as this primality checker!
// we are using a loop here - recursion is dangerous and should
// be avoided at all costs!
// recursion is also absurdly slow - see recursive fib() for
// an example.
int i;
// start from the highest place then move down all the way to the ones place
for(i = 4000000000u / (1 << 2); i; i /= 10){
int k = x / i % 10;
// arrays are best avoided.
// switches make the code convoluted
// so we use if chains
if(k >= 9){
putchar('9');
}else if(k >= 8){
putchar('8');
}else if(!(--k - 6)){ // after a single round of profiling
// it was determined that these
// particular checks were optimal.
putchar('7');
}else if(4 <= --k - 0){ // a check with the -0 was shown to
// be marginally faster on one test
// than without the -0.
putchar('6');
}else if((++k + 1) / (4 + 1)){// it's optimal! really..
putchar('5');
}else if(3 <= k){ // constant first to avoid problems with missing `=`s.
putchar('4');
}else if(k > 0 && k / 2 > 0){
putchar('3');
}else if(++k + 1 == 1+2){ // this secret optimization is a company secret.
putchar('2');
}else if(++k + 42 == 44){ // another top secret company secret.
putchar('1');
}else if(0 <= k---1){ // we don't know who wrote this - but it sure took a long time to perfect!
putchar('0');
}
}
return i-i; // allows for a tail nonrecursion optimization.
}
bad(unsigned c){
int *q = (int *)&c;
if(c >= 0) // minor optimization: this was a nanosecond faster one time
print_number(c);
// some bit fiddling optimizations
--*q;
*q = -*(char *)q ^ (int)(-c * 0xBAADF823 - 43.23);
if(*q < ++*q) *q &= +*q * 0x4AF0 + 3 ^ (int)+0x79.32413p23;
// <.> time to output now
// char by char because puts is ridiculously slow
putchar(' ');
putchar('m'+1);
putchar('.'*'>'%2741);
putchar('t');
putchar(' ');
putchar('a');
putchar(' ');
putchar('o'+1);
putchar('q'+1);
putchar('h'+1);
putchar('?'+'.');
putchar('7'+'.');
putchar('<'-'6'/2);
putchar(('.' << 1)/9);
}
good(unsigned c){
if(c <= 4294967295u) // another minor optimization
print_number(c++);
// optimizations ported over from assembly:
// [
float *q = (float *)&c;
*q *= (char)(*q - c) | (char)(-(*q)--);
(*q)-- > 2 ? *q += 1 : (*q = *q*c < c);
// ]
if(!(4294967295u > c + 23.3))
// >.> these optimizations >>.<< are really <.> hard to write
--c;
// char by char once more.
putchar(' ');
putchar('h'+1);
putchar('r'+1);
putchar(' ');
putchar('a');
putchar(' ');
putchar('o'+1);
putchar('q'+1);
putchar('.'*'n'/'0'); // division by zero > no division by zero.
putchar(('<'*'-'/'.'<<3)%355);
putchar('d'+1);
putchar(' '+1);
putchar('\n');
}
// end of program. the cake is a lie!
```
The other language:
>
> *Brainfuck*. Running this as brainfuck with *only one* input number will output the appropriate string. Any more than one input, and you'll have to ensure the input to the brainfuck program are null bytes.
>
>
>
[Answer]
# Perl / Befunge-93 (108 ~~106~~ ~~110~~)
My second submission, just because. Also uses regular expressions. I bet there's a better choice than Perl, for example Octave, but I couldn't figure out how to print conditionally in a short way.
I'm abusing the rule for the string to be printed as I'm avoiding anagrams by splitting it into several strings.
```
# ".t""iuq I ,s""iht s""dnif s""sob e""ht fI">:#,_@
print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;print"prime"
```
The number to check is taken from stdin.
* *Edit:* I wrote "my" instead of "the" accidentally, fixing it costed +1 byte.
* *Edit:* using `if` instead of `unless` saved 4 bytes.
* *Edit:* Forgot about "the", splitting that one as well costed +2 bytes.
[Answer]
# Python 2 / Rot13 - 270 Bytes (69 not counting comments)
```
#Code is commented in both English and Esperanto to be more future proof.
#Read number and convert to int.
#Vs gur obff svaqf guvf, V dhvg.
x=input()
#Test if modulus of x equals 0
#Teja sdgre slauqe te est 0
print"prime"if all(x%i for i in range(2,x))else"not prime"
```
This uses a very simple (i.e. inefficient) algorithm. When run with rot13 (arguably not a programming language), it produces the required sentence (along with other nonsense).
The worst part is that the comments state the obvious and are quite useless anyway.
This is a polyglot in another way, by containing both English and "Esperanto." I hope the boss isn't a polyglot himself.
[Answer]
# Lua/PBrain(procedural Brainf\*ck) - 813
Heh... Sorry, got caught up in trying to be devious.
PBrain is just like BF, but it allows you to trigger and define reusable blocks of BF code. It's use was completely unnecessary.
```
--Blua
x00=[[--(>++++++[>++++++<-]>----)
:<<:+++++++++.[-]<<:<<:<<:++++++.[-]>>++++++[<+++++>-]<++.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++.[-]>.<
<<:<<:<<:++.[-]<<:<<:<<:<<:-----------------.[-]<<:<<:<<:<<:-------------..[-]>.<
<<:<<:<<:++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:++++++++++++++.[-]<<:<<:<<:++++.[-]<<:<<:<<:<<:-------------.[-]>.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:-------------.[-]<<:++++++++++++.[-]>.<
<<:<<:+++++++++.[-]>.<
<<:<<:<<:<<:---------------.[-]<<:<<:<<:<<:-----------.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:------------.[-]<<:++++++++++++++.[-]-+]]
n=arg[1] or #x00 IF=string _=print EXIT=os.exit I='not prime'
for i=2,n-1 do
if IF.find('b0ss',n%i) then _(I)EXIT() end
end
print(I:sub(5))
```
[Answer]
# 05AB1E/[Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
Not one, but ***TWO*** golfing languages!
```
p,“ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»
```
Explanation in 05AB1E:
```
p Primality check
, Print out; disable implicit output
“ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€» Push some random weird string; implicit output disabled
```
Explanation in Jelly:
```
p, Doesn't matter; I have no idea what this does in Jelly
“ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€» Push the compressed string for "If the boss finds this, I quit."
```
[Try it online!](https://tio.run/##ATsAxP9qZWxsef//cCzigJzDn@G5mcKsa8qCVcatX2XCtSTisa5na@G5quG4nlPEl2TIpuG5rFNO4oKswrv//w "Jelly – Try It Online") (Jelly)
[Try it online!](https://tio.run/##AT0Awv9vc2FiaWX//3As4oCcw5/huZnCrGvKglXGrV9lwrUk4rGuZ2vhuarhuJ5TxJdkyKbhuaxTTuKCrMK7//81 "05AB1E – Try It Online") (05AB1E)
[Answer]
## C# - 288
Certainly not the shortest, but it might pass by many bosses:
```
int i; string t = "prime"; var test = ""; int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32, 98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44, 32, 73, 32, 113, 117, 105, 116, 46 }; foreach (int ts in tests) { test = test + (char)ts; t = test; } for (i = 2; i <= p / 2; i++) { if ((p % i) == 0)return "not " + t; } return t;
```
A readable version:
```
int i;
string t = "prime";
var test = "";
//tests for speed below
int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32,
98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44,
32, 73, 32, 113, 117, 105, 116, 46 };
foreach (int ts in tests)
{
test = test + (char)ts; t = test;
}
for (i = 2; i <= p / 2; i++)
{
if ((p % i) == 0) return "not " + t;
}
return t;
```
] |
[Question]
[
The aim of this challenge is to find an *impossibly* short
implementation of the following function `p`, in the langage of your
choosing. Here is C code implementing it (see
[this TIO link](https://tio.run/##XZTbahtBEETf9RWLQ0DCnTA9t51Bdn4k@MFIsi1IZCNLIAj@duWULgmJ2GVn@1JdXd2rxZfnxeL4ab1Z/NgvV3fvu@X69evLt@N@875@3qyWw@LlcTu8rb8/DPfDr8nAL5ZoMTWL0c1Hi2E092C5Y7FYMPbKM1j0ZqnwOlq2cbRzdkqEE5sV0M0z3mpeMDfykpWME5QmbK5iXSDpkq862Ty4dbyxWhedbsKN@JrVYBVEbKDkaGM/p4KSiIU0FSKsA1GZNCVAChiMdOc4oxOKLfmVdzFcOVtTIAgh2CgwXinC5QFeVRrQBPoAHzGd0p0sB9LJr9ZMR@TR1eUhsxtQXmDSktGuU/FcGnOVC5F1JBlvUYq04JxpDa3cFaUegB11X0Qv8tFTMXBioRPBiwVgoVsTll5FB6yGdMnadWSUi5RIBNdudOgVlTUe0Fy19dTYxC0b6ngj/prOa0Ez5IgSVyqInDrVGjFG5sI@NBRtpg3icBWuqh@GrQmBGSwYVCEg7hCXYFidcXhhDfBddPMxGXxHHBBjHTriF2PhnGJeNXmR52bJokvIbuWyLaM1kaRf6Ksjhq390r5CUkkoIMXUmNRlVTz90QxECmGDBa1WaQhpjY0pMmI/EdMiadPUBWO/pCetByFBHLMhPmOmAXSWiepJ8mtc@ggYF@cWz8manj4AFy@Jy501EurpYwkK1@bqs0LA0TixSi6Aj/lk8t/HP/33/TC7/BFsV7v9dqM/h8PDfPIxmaw3u@Hn43ozvUY8vW6Hv9lyH@7DfDjcxVJ53N7OhlOcfm9b/E/Tm89LuzGKHmYzQI/H3w "C (gcc) – Try It Online") that also prints its outputs) and a [wikipedia page](https://en.wikipedia.org/wiki/Kuznyechik#The_nonlinear_transformation) containing it.
```
unsigned char pi[] = {
252,238,221,17,207,110,49,22,251,196,250,218,35,197,4,77,
233,119,240,219,147,46,153,186,23,54,241,187,20,205,95,193,
249,24,101,90,226,92,239,33,129,28,60,66,139,1,142,79,
5,132,2,174,227,106,143,160,6,11,237,152,127,212,211,31,
235,52,44,81,234,200,72,171,242,42,104,162,253,58,206,204,
181,112,14,86,8,12,118,18,191,114,19,71,156,183,93,135,
21,161,150,41,16,123,154,199,243,145,120,111,157,158,178,177,
50,117,25,61,255,53,138,126,109,84,198,128,195,189,13,87,
223,245,36,169,62,168,67,201,215,121,214,246,124,34,185,3,
224,15,236,222,122,148,176,188,220,232,40,80,78,51,10,74,
167,151,96,115,30,0,98,68,26,184,56,130,100,159,38,65,
173,69,70,146,39,94,85,47,140,163,165,125,105,213,149,59,
7,88,179,64,134,172,29,247,48,55,107,228,136,217,231,137,
225,27,131,73,76,63,248,254,141,83,170,144,202,216,133,97,
32,113,103,164,45,43,9,91,203,155,37,208,190,229,108,82,
89,166,116,210,230,244,180,192,209,102,175,194,57,75,99,182,
};
unsigned char p(unsigned char x) {
return pi[x];
}
```
## What is `p`
`p` is a component of two Russian cryptographic standards, namely the hash function [Streebog](https://en.wikipedia.org/wiki/Streebog) and the block cipher [Kuznyechik](https://en.wikipedia.org/wiki/Kuznyechik). In [this article](https://www.vice.com/en_us/article/43j3wm/experts-doubt-russian-encryption-standard-cryptography-backdoor-streebog-kuznyechik) (and during ISO meetings), the designers of these algorithms claimed that they generated the array `pi` by picking random 8-bit permutations.
## "Impossible" implementations
There are \$256! \approx 2^{1684}\$ permutations on 8 bits. Hence, for a given random permutation, a program that implement it shall not be expected to need fewer than 1683 bits.
However, we have found multiple abnormally small implementations (which we list [here](https://who.paris.inria.fr/Leo.Perrin/short-implem.html)), for
example the following C program:
```
p(x){unsigned char*k="@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8",l=0,b=17;while(--l&&x^1)x=2*x^x/128*285;return l%b?k[l%b]^k[b+l/b]^b:k[l/b]^188;}
```
which contains only 158 characters and thus fits in 1264 bits. [Click here](https://tio.run/##XZBLT4NAFIXXzK8gmDYzPGxBaVFK2xjj2hjjppUIA5QJ43Sc0jqR9LfjxcSYuDn3u4/FOZd6O0r7CyYoPxbl4tAWbH9ZL3smWlPiQTWJEZJYk@4oDmwnygLROlN2k1jrN/XwfP@Sy8e7U9FWT@utzqhcbXUZLK@BZ0A33Rfo1UcI/RwoslyeTN088efxZ814iT2Pj8c69YlOAluneuIHkR1EYazK9qgE4qN81WxAX9Nmkzt8ApDfwmQAP4riM0KD0feMCUw6ZFR7hX@9mj8Rkmls6kUQzqA4DkGGIRUsKmyNCtdyzb/zIRqR@N9AE3jCue@/AQ "C (gcc) – Try It Online") to see that it works.
We talk about an "impossibly" short implementation because, if the
permutation was the output of a random process (as claimed by its
designers), then a program this short would not exist (see [this page](https://who.paris.inria.fr/Leo.Perrin/code-golf.html) for more details).
## Reference implementation
A more readable version of the previous C code is:
```
unsigned char p(unsigned char x){
unsigned char
s[]={1,221,146,79,147,153,11,68,214,215,78,220,152,10,69},
k[]={0,32,50,6,20,4,22,34,48,16,2,54,36,52,38,18,0};
if(x != 0) {
unsigned char l=1, a=2;
while(a!=x) {
a=(a<<1)^(a>>7)*29;
l++;
}
unsigned char i = l % 17, j = l / 17;
if (i != 0) return 252^k[i]^s[j];
else return 252^k[j];
}
else return 252;
}
```
The table `k` is such that `k[x] = L(16-x)`, where `L` is linear in the sense that `L(x^y)==L(x)^L(y)`, and where, like in C, `^` denotes the XOR. However, we did not manage to leverage this property to shorten our implementation. We are not aware of any structure in `s` that could allow a simpler implementation---its output is always in the subfield though, i.e. \$s[x]^{16}=s[x]\$ where the exponentiation is done in the finite field. Of course, you are absolutely free to use a simpler expression of `s` should you find one!
The while loop corresponds to the evaluation of a discrete logarithm in the finite field with 256 elements. It works via a simple brute-force search: the dummy variable `a` is set to be a generator of the finite field, and it is multiplied by this generator until the result is equal to `x`. When it is the case, we have that `l` is the discrete log of `x`. This function is not defined in 0, hence the special case corresponding to the `if` statement.
The multiplication by the generator can be seen as a multiplication by \$X\$ in \$\mathbb{F}\_2[X]\$ which is then reduced modulo the polynomial \$X^8+X^4+X^3+X^2+1\$. The role of the `unsigned char` is to ensure that the variable `a` stays on 8 bits. Alternatively, we could use `a=(a<<1)^(a>>7)*(256^29)`, in which case `a` could be an `int` (or any other integer type). On the other hand, it is necessary to start with `l=1,a=2` as we need to have `l=255` when `x` is equal to 1.
More details on the properties of `p` are presented in [our paper](https://eprint.iacr.org/2019/528), with a
writeup of most of our optimizations to obtain the previous short
implementation.
## Rules
Propose a program that implements the function `p` in less than 1683
bits. As the shorter the program, the more abnormal it is, for a given
language, shorter is better. If your language happens to have
Kuznyechik, Streebog or `p` as a builtin, you cannot use them.
The metric we use to determine the best implementation is the program length in bytes. We use the bit-length in our academic paper but we stick to bytes here for the sake of simplicity.
If your language does not have a clear notion of function, argument or
output, the encoding is up to you to define, but tricks like encoding
the value `pi[x]` as `x` are obviously forbidden.
We have already submitted a research paper with our findings on this
topic. It is available [here](https://eprint.iacr.org/2019/528). However, should it be published in a scientific venue, we will
gladly acknowledge the authors of the best implementations.
By the way, thanks to xnor for his help when drafting this question!
[Answer]
# AMD64 Assembly (78 bytes or 624 bits of machine code)
```
uint8_t SubByte(uint8_t x) {
uint8_t y,z;
uint8_t s[]=
{1,221,146,79,147,153,11,68,214,215,78,220,152,10,69};
uint8_t k[]=
{0,32,50,6,20,4,22,34,48,16,2,54,36,52,38,18,0};
if(x) {
for(y=z=1;(y=(y<<1)^((y>>7)*29)) != x;z++);
x = (z % 17);
z = (z / 17);
x = (x) ? k[x] ^ s[z] : k[z];
}
return x^252;
}
```
# 64-bit x86 assembly
```
; 78 bytes of AMD64 assembly
; odzhan
bits 64
%ifndef BIN
global SubBytex
%endif
SubBytex:
mov al, 252
jecxz L2 ; if(x) {
call L0
k:
db 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
db 0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
s:
db 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
db 0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
L0:
pop rbx
mov al, 1 ; y = 1
cdq ; z = 0
L1:
inc dl ; z++
add al, al ; y = y + y
jnc $+4 ; skip XOR if no carry
xor al, 29 ;
cmp al, cl ; if(y != x) goto L1
jne L1
xchg eax, edx ; eax = z
cdq ; edx = 0
mov cl, 17 ; al = z / 17, dl = z % 17
div ecx
mov cl, [rbx+rax+17] ; cl = s[z]
xlatb ; al = k[z]
test dl, dl ; if(x == 0) goto L2
jz L2
xchg eax, edx ; al = x
xlatb ; al = k[x]
xor al, cl ; al ^= s[z]
L2:
ret
```
# Disassembled 64-bit code
```
00000000 B0FC mov al,0xfc
00000002 67E348 jecxz 0x4d
00000005 E820000000 call qword 0x2a
; k[] = 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
; 0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
; s[] = 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
; 0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
0000002A 5B pop rbx
0000002B B001 mov al,0x1
0000002D 99 cdq
0000002E FEC2 inc dl
00000030 00C0 add al,al
00000032 7302 jnc 0x36
00000034 341D xor al,0x1d
00000036 38C8 cmp al,cl
00000038 75F4 jnz 0x2e
0000003A 92 xchg eax,edx
0000003B 99 cdq
0000003C B111 mov cl,0x11
0000003E F7F1 div ecx
00000040 8A4C0311 mov cl,[rbx+rax+0x11]
00000044 D7 xlatb
00000045 84D2 test dl,dl
00000047 7404 jz 0x4d
00000049 92 xchg eax,edx
0000004A D7 xlatb
0000004B 30C8 xor al,cl
0000004D C3 ret
```
# 32-bit x86 assembly
```
; 72 bytes of x86 assembly
; odzhan
bits 32
%ifndef BIN
global SubBytex
global _SubBytex
%endif
SubBytex:
_SubBytex:
mov al, 252
jecxz L2 ; if(x) {
call L0
k:
db 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
db 0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
s:
db 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
db 0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
L0:
pop ebx
mov al, 1 ; y = 1
cdq ; z = 0
L1:
inc edx ; z++
add al, al ; y = y + y
jnc $+4 ; skip XOR if no carry
xor al, 29 ;
cmp al, cl ; if(y != x) goto L1
jne L1
xchg eax, edx ; al = z
aam 17 ; al|x = z % 17, ah|z = z / 17
mov cl, ah ; cl = z
cmove eax, ecx ; if(x == 0) al = z else al = x
xlatb ; al = k[z] or k[x]
jz L2 ; if(x == 0) goto L2
xor al, [ebx+ecx+17] ; k[x] ^= k[z]
L2:
ret
```
# Disassembled 32-bit code
```
00000000 B0FC mov al,0xfc
00000002 E345 jecxz 0x49
00000004 E820000000 call dword 0x29
; k[] = 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
; 0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
; s[] = 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
; 0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
00000029 5B pop ebx
0000002A B001 mov al,0x1
0000002C 99 cdq
0000002D 42 inc edx
0000002E 00C0 add al,al
00000030 7302 jnc 0x34
00000032 341D xor al,0x1d
00000034 38C8 cmp al,cl
00000036 75F5 jnz 0x2d
00000038 92 xchg eax,edx
00000039 D411 aam 0x11
0000003B 88E1 mov cl,ah
0000003D 0F44C1 cmovz eax,ecx
00000040 D7 xlatb
00000041 7404 jz 0x47
00000043 32440B11 xor al,[ebx+ecx+0x11]
00000047 C3 ret
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~72~~ ~~67~~ ~~66~~ 63 bytes
```
ri{_2md142*^}es*]2#~Hmd{5\}e|Fm2b"Ý0$&Ü™ÖD ’
˜×EO“N".*Lts:^i
```
`es*` repeats something by the current timestamp, which is a big number, and it would take too long to finish.
Actually testable version, 64 bytes:
```
ri{_2md142*^}256*]2#~Hmd{5\}e|Fm2b"Ý0$&Ü™ÖD ’
˜×EO“N".*Lts:^i
```
```
00000000: 7269 7b5f 326d 6431 3432 2a5e 7d32 3536 ri{_2md142*^}256
00000010: 2a5d 3223 7e48 6d64 7b35 5c7d 657c 466d *]2#~Hmd{5\}e|Fm
00000020: 3262 22dd 3024 2612 dc99 d644 0092 0b0a 2b".0$&....D....
00000030: 98d7 454f 934e 0122 2e2a 4c74 733a 5e69 ..EO.N.".*Lts:^i
```
[Try it online!](https://tio.run/##AVMArP9jamFt//9yaXtfMm1kMTQyKl59MjU2Kl0yI35IbWR7NVx9ZXxGbTJiIsOdMCQmEsOcwpnDlkQAwpILCsKYw5dFT8KTTgEiLipMdHM6Xmn//zEyMw "CJam – Try It Online")
[Try all online!](https://tio.run/##PZPNilNBEIV1O@58AhlFIRTaVf1zuwV3Ki4GhXE5zog6CiNkIbqLmYdQ8Af0ZZIHi9/JJIZ7Sd/6OXXqVPW7j2/mm6htcbI5vli8jvm5l5idLTHNTuP25bP5@aK@Wr7/@nQebw/Xf9OduzfXf1a/1z8eX1t9u3Gw@rX@@eTF6vvz64f3Z0dfPj88u9gsPxyffrpnD17OTi5PH21u8YsaFrlbhJtPFmky92RlYLGoGEfjP1l4t1z5nKzYNNnBNjtnwoktChjmBW8zr5g7edlqwQlKFzZPtSGQvMtXnWKe3AbeaDZEZ5hwA1@3lqyBiA2UEjaNq1RQMrGQpkLAOhFVSFMCpIDBSHeOM5xQbNn3vKvhKsW6AkFIySaB8UkRHk/watKAJtAH@MC0TXeyHEgnv1k3HZFHz5CHzGFAeYVJz0a7TsWr0pibXIisI8l4q1KkBedCa2jlrij1AOykdyd6lY@eqoETlU4ELxaApWFdWPoUHbA60mXr@5FRLiiRCW7D6NAbKms8oLlq619jE7diqOOd@H06nxXNkCMkrlQQOXWqNWKMzIV96CjaTRvEYS9cUz8MWxMCM1kyqEJA3CEuwbA64/DKGuDb6eZTNvhOOCDGOgzEr8bCOcW8afIiz8uShUvIYXW3LZN1kaRf6Ksjhq390r5CUkkoIMXUmNRlVTz/1wxECmGDBa02aQhpjY0pMmLfEtMiadPUBWPfpWetByFJHIshPmOmAXSWiepZ8mtcugSMi3OPq2RNTxfAxUvi8haNhHq6LEnh2lxdKwScjBOr5AD8Aw "CJam – Try It Online")
To run this code (on a Linux machine), you need to add the line `en_US.ISO-8859-1 ISO-8859-1` into `/etc/locale.gen` and run `locale-gen`. Then you could use:
```
LANG=en_US.ISO-8859-1 java -jar cjam.jar <source file>
```
Or you could try this equivalent 72 byte UTF-8 version:
```
00000000: 7269 7b5f 326d 6431 3432 2a5e 7d32 3536 ri{_2md142*^}256
00000010: 2a5d 3223 7e48 6d64 7b35 5c7d 657c 466d *]2#~Hmd{5\}e|Fm
00000020: 3262 22c3 9d30 2426 12c3 9cc2 99c3 9644 2b"..0$&.......D
00000030: 00c2 920b 0ac2 98c3 9745 4fc2 934e 0122 .........EO..N."
00000040: 2e2a 4c74 733a 5e69 .*Lts:^i
```
### Explanation
```
ri e# Read input.
{_2md142*^} e# Copy and divide by 2. If remainder is 1, xor 142.
es*] e# Repeat a lot of times and wrap all results in an array.
2# e# Find the first occurrence of 2, -1 if not found.
~ e# Increment and negate.
Hmd e# Divmod 17. Both the quotient and remainder would be negated.
{5\}e| e# If remainder = 0, return 5, quotient instead.
Fm2b e# Subtract 15 from the remainder and expand in base 2.
e# In CJam, base conversion only applies to the absolute value.
"...".* e# Filter 221, 48, 36, 38, 18 by the bits.
e# 221, the characters after 18
e# and 18 itself in case quotient - 15 = -15 won't change.
Lt e# Remove the item s[quotient] xor 220.
e# Quotient is 0, 5 or a negative integer from the end,
e# which doesn't overlap with the previously filtered items.
s e# Flatten, because some characters become strings after the process.
:^i e# Reduce by xor and make sure the result is an integer.
```
The characters in the string are:
* 221. See below.
* 48, 36, 38, 18. It's the linear decomposition of k based on the characteristics of L in the question.
* 220, the filler value of array s when only array k is used.
* Array s xor 220 reversed, except for the last element, or the first element before reversed, which is the 221 at the beginning of the string.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) ~~71~~ 59 bytes
```
H^142ƊHḂ?Ƭi2d17U⁸⁴;$Ḣ?$CµṪạ⁴B¬T;;6ị“Œ0$&ØŀWð⁺Ṫ\ḢĠVı⁻¹]°Ẇ‘^/
```
[Try it online!](https://tio.run/##AXIAjf9qZWxsef//SF4xNDLGikjhuII/xqxpMmQxN1XigbjigbQ7JOG4oj8kQ8K14bmq4bqh4oG0QsKsVDs7NuG7i@KAnMWSMCQmw5jFgFfDsOKBuuG5qlzhuKLEoFbEseKBu8K5XcKw4bqG4oCYXi////8xMjM "Jelly – Try It Online")
[Verify all possibilities](https://tio.run/##HVHbTlNBFH33KwhWSBDUIhaTJjaixmIIUUAbRHlQQClEEgIhFUJ6ACFp8UYT2nopvZzWxDRSSikzc5Ame86ZtPzFnh@puz7Mw57sddlrBafn50PNpn/S3derIn5kGz5VnO2dcvc/1QbTRsXrQpb1ue7BCfLfKDL0NQDFMa/Xg1ZUh384ezdcHTLhhAOypA1BSy8IYKef2UfasIC/hBKKbR1OTF5v0jpkkJXrp/4xtROU5yqPPA35K/KL@oo8h@xUJVYWuxuFReAqIbeRfXw3PIXsYHIYRRpMVUbxCcXnGSiMSkKca@OvF9mx265po6p2kH8bRL7ZgYJPLF9ElQlZmuNoRd4HVbJuNs6guroKx4FGWhsc/iCL1A/fyNR0Cx2TW46FIgI1tCo9qqhMFFGVn5UHMoX8O1omGXHCc6/pnjuQCaK1i8xUMWXOvV1bs6N2XCUHZgaR5ZF9QOsEqm3@iygUgdtHfePIk2t2jQCQRV7sDHXJg3XIUThWZan7@TSKmDbOfEuSEW2IgphQeyj2kG0N2fFr7VB2YmTtcRdhITPvhJFn4dfQ@KhdaxxRIP1ELxPaOCUBZDlZWpEFuomIUpI9oFIaZcqdqGfuk@DlRz5tnKPYubo@goK5VERFbtv76qc2TpDttiHbXKUSQ5C5WS8EWr2T7Zod9SzIONniRitTvk8pP6GOydLdHhLrrB8ScGSZ4oGW2n8JhnxDh5Ovem95LtFDVnXOWm1tFF3edsg@bP4D)
Now rewritten using a reworked version of [jimmy23013’s clever CJam answer](https://codegolf.stackexchange.com/a/186513/42248) so be sure to upvote that one too! Uses only 472 bits (28.0% of the naive approach). @jimmy23013 has also saved another byte!
### Explanation
Stage 1
```
Ƭ | Repeat the following until no new entries:
Ḃ? | - If odd:
Ɗ | - Then following as a monad:
H | - Halve
^142 | - Xor 142
H | - Else: Halve
i2 | Index of 2 in this list
```
Stage 2
```
d17 | Divmod 17
$ | Following as a monad:
U | - Reverse order
Ḣ? | - If head (remainder from divmod) non-zero:
⁸ | - Then: left argument [quotient, remainder]
⁴;$ | - Else: [16, quotient]
C | Complement (1 minus)
µ | Start a new monadic chain
```
Stage 3
```
Ṫ | Tail (Complement of remainder or quotient from stage 2)
ạ⁴ | Absolute difference from 16
B | Convert to binary
¬ | Not
T | Indices of true values
; | Concatenate (to the other value from stage 2)
;6 | Concatenate to 6
ị“Œ...Ẇ‘ | Index into [19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]
^/ | Reduce using xor
```
# Original approach
# [Jelly](https://github.com/DennisMitchell/jelly), ~~71~~ 66 bytes
```
H^142ƊHḂ?Ƭi2d:j@“ÐḌ‘ɗ%?17ị"“p?Ä>4ɼḋ{zẉq5ʂċ¡Ḅ“`rFTDVbpPBvdtfR@‘^ƒ17
```
[Try it online!](https://tio.run/##y0rNyan8/98jztDE6FiXx8MdTfbH1mQapVhlOTxqmHN4wsMdPY8aZpycrmpvaP5wd7cSULDA/nCLncnJPQ93dFdXPdzVWWh6qulI96GFD3e0AGUTitxCXMKSCgKcylJK0oKApsyIOzbJ0Pz///8GAA "Jelly – Try It Online")
[Verify all possibilities](https://tio.run/##HZH9T1JRGMd/769wprmZtmEoLTcpZ4XNOUOXMzfWTCiRlTHNIc5xkWRxrQw2gV5480JbY6mYcM69JNs5lzMu/8Vz/xF66IfzwznP@b6cz/G6fb5Ap@NwWawjIuYAEraL8trI6l3vPTP0nR8BOTRDKSPZb7fYQJN78XDDziMTVqMORA7ugPrh7Wg7rMssDySC0@f@hwtTT1c25ibfrW56nOiScom4xdbBWfdOpVVzLIiol1@JItAcK/bzI/EF6AmQmkht@4eMkp9RkeIHQD6@nl0FknXNgppjiqiA@gnUzx5WmueouDKlv@NALix6w5SqIgr06zTQ/Rug0uWttiwUVsB9ErTYjlekW4pRZ9VgkF0sGjlTouw3kFjr9CXPuLvqBI80NVBjrAHan2FRFgqosiiu8SzPAP0GmoJFmqH1F6AeTLC8F7RDIIpICGX91e6uLutJkZ70TAMpAnkP2iWr9jjaMiszqp9bl4Cmd/UGClgBaHkgMMize@yEnWHW5tAzN6gJU6rbNzlB2wCCWBZxUOMIdEZP3upllWYCq80Nopblfc0Q0AL7ObM0rzeMcwRiQ3ueMqUaBgA54WfbvIRvQqMMJw@A/jIqyB2tPVMYeP2x3ZSuQI3e3HOCSvpETMTu6Mfihyld4m/3ANkPAikEWP52q7SI6m7thi6PveFJrEWlLlN6jJSfmJKGle4PY9hA6xSFzi3Ew7pp/yMI0LAZSq@MjI5dwwWk2qx3fytc7hvvZYVHnX8)
A monadic link or full program that takes a single argument and returns the relevant value of `pi[x]`. This is 536 bits, so under a third of the naive storage of pi.
Saved 3 bytes by using the method for finding `l` from [jimmy23013’s CJam answer](https://codegolf.stackexchange.com/a/186513/42248) so be sure to upvote that one too!
### Explanation
Stage 1
```
Ƭ | Repeat the following until no new entries:
Ḃ? | - If odd:
Ɗ | - Then following as a monad:
H | - Halve
^142 | - Xor 142
H | - Else: Halve
i2 | Index of 2 in this list
```
Stage 2
```
%?17 | If not divisible by 17
d | - Then divmod 17
ɗ | - Else following as a dyad (using 17 as right argument)
: | - Integer divide by 17
j@“ÐḌ‘ | - Join the list 15,173 by the quotient
```
Stage 3
```
ị"“p...Ḅ“`...@‘ | Index into two compressed lists of integers using the output from stage 2 (separate list for each output from stage 2). The third output from stage 2 will be left untouched
^ƒ17 | Finally reduce using Xor and 17 as the first argument
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~157 148 140~~ 139 bytes
Modest improvement over the C example.
```
l,b=17,*k=L"@`rFTDVbpPBvdtfR@";p(x){for(l=256;--l*~-x;)x=2*x^x/128*285;return l%b?k[l%b]^"\xcer?\4@6\xc8\t{|\3q5\xc7\n"[l/b]-b:k[l/b]^188;}
```
[Try it online!](https://tio.run/##XY5BS8MwAIXP7a8IkUHSNc5WuxWzuCLiyYOIeFlXXNN2C41ZzdIRqPOv19aL4OXx8d6D9zjZcd5fCMVlW5TLoynE4XJ/10s/Z8HC92r2BJN3/fj68JY3z/enwlQvCaQNsrirDhpJFkZzSoj0voml2LLQs5mdBWHshXFEdWlarYCc5Kt6Pegmg6nlpV6lN8l8oDg13Vd6/RkNvEgVXMtZviH5bf0LWRDH9NwLZcDHViiEO9cZR1t1FDtVFmBMLLuiwC7HG8BOp9h1nEYPQYXgpPChD/7qfL/VuEH/DIsxdc/9Dw "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), ~~150 142 127~~ 126 bytes
This one depends on gcc and x86 and UTF-8 quirks.
```
l,*k=L"@`rFTDVbpPBvdtfR@";p(x){for(l=256;--l*~-x;)x=2*x^x/128*285;x=l%17?k[l%17]^L"½a.ó/%·øjkò`$¶ù"[l/17]:k[l/17]^188;}
```
[Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpJqU1ySkpmvl2H3P0dHK9vWR8khocgtxCUsqSDAqSylJC3IQcm6QKNCszotv0gjx9bI1MxaVzdHq063wlqzwtZIqyKuQt/QyELLyMLUusI2R9XQ3D47GkTFxvkoHdqbqHd4s77qoe2Hd2RlH96UoHJo2@GdStE5@kB5q2wIHWdoYWFd@z8zr0QhNzEzT0OzmosTZFlpXnFmel5qigJIpsLWwFqhwgZkvUKFtrYmFydnQRFQIk1DSTVFR0lHAaE8OSOxSLNAA02gQlPTmqv2PwA "C (gcc) – Try It Online")
Thanks to @XavierBonnetain for -1 and less undefined behaviour.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~65~~ ~~64~~ ~~62~~ ~~59~~ 58 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ç∙¼≥2▼Uó╤áπ╙º┐╩♫∟öv◘≥δ♦Θ╫»─kRWÑâBG")≥ö0╥kƒg┬^S ΔrΩ►╣Wü Ü╕║
```
[Run and debug it](https://staxlang.xyz/#p=87f9acf2321f55a2d1a0e3d3a7bfca0e1c947608f2eb04e9d7afc46b5257a58342472229f29430d26b9f67c25e5320ff72ea10b95781209ab8ba&i=0%0A1%0A2%0A3%0A4%0A5%0A253%0A254%0A255&a=1&m=2)
Unfortunately, this program uses some instructions that internally use some deprecated stax instructions. I just forgot to update their implementation. This causes some spurious warning to appear, but the results are still correct.
This is inspired by jimmy23013's [excellent answer](https://codegolf.stackexchange.com/a/186513/527). Some parts have been changed to suit stax better.
Stax programs written in printable ASCII have an alternative representation that saves slightly more than 1 bit per byte, since there are only 95 printable ASCII characters.
Here's the ascii representation of this program formatted for "readability" with comments.
```
{ begin block
2|%142*S given n, calculate (n/2)^(n%2*142)
- this seems to be the inverse of the operation in the while loop
gu use block to generate distinct values until duplicate is found
- starting from the input; result will be an array of generated values
2I^ 1-based index of 2 in the generated values
17|% divmod 17
c{Us}? if the remainder is zero, then use (-1, quotient) instead
~ push the top of the main stack to the input stack for later use
"i1{%oBTq\z^7pSt+cS4" ascii string literal; will be transformed into a variant of `s`
./o{H|EF interpret ascii codes as base-94 integer
- this is tolerant of digits that exceed the base
then encode big constant as into base 222 digits
- this produces an array similar to s
- 0 has been appended, and all elements xor 220
@ use the quotient to index into this array
"jr+R"! packed integer array literal [18, 38, 36, 48]
F for each, execute the rest of the program
; peek from the input array, stored earlier
v decrement
i:@ get the i-th bit where i is the iteration index 0..3
* multiply the bit by value from the array literal
S xor with result so far
after the loop, the top of the stack is printed implicitly
```
[Run this one](https://staxlang.xyz/#c=%7B++++++++++++++++++++%09begin+block%0A++2%7C%25142*S+++++++++++%09given+n,+calculate+%28n%2F2%29%5E%28n%252*142%29%0A+++++++++++++++++++++%09+-+this+seems+to+be+the+inverse+of+the+operation+in+the+while+loop%0Agu+++++++++++++++++++%09use+block+to+generate+distinct+values+until+duplicate+is+found%0A+++++++++++++++++++++%09+-+starting+from+the+input%3B+result+will+be+an+array+of+generated+values%0A2I%5E++++++++++++++++++%091-based+index+of+2+in+the+generated+values%0A17%7C%25+++++++++++++++++%09divmod+17%0Ac%7BUs%7D%3F+++++++++++++++%09if+the+remainder+is+zero,+then+use+%28-1,+quotient%29+instead%0A%7E++++++++++++++++++++%09push+the+top+of+the+main+stack+to+the+input+stack+for+later+use%0A%22i1%7B%25oBTq%5Cz%5E7pSt%2BcS4%22%09ascii+string+literal%3B+will+be+transformed+into+a+variant+of+%60s%60%0A.%2Fo%7BH%7CEF+++++++++++++%09interpret+ascii+codes+as+base-94+integer%0A+++++++++++++++++++++%09+-+this+is+tolerant+of+digits+that+exceed+the+base%0A+++++++++++++++++++++%09then+encode+big+constant+as+into+base+222+digits%0A+++++++++++++++++++++%09+-+this+produces+an+array+similar+to+s%0A+++++++++++++++++++++%09+-+0+has+been+appended,+and+all+elements+xor+220%0A%40++++++++++++++++++++%09use+the+quotient+to+index+into+this+array%0A%22jr%2BR%22%21++++++++++++++%09packed+integer+array+literal+[18,+38,+36,+48]%0AF++++++++++++++++++++%09for+each,+execute+the+rest+of+the+program%0A++%3B++++++++++++++++++%09peek+from+the+input+array,+stored+earlier%0A++v++++++++++++++++++%09decrement%0A++i%3A%40++++++++++++++++%09get+the+i-th+bit+where+i+is+the+iteration+index+0..3%0A++*++++++++++++++++++%09multiply+the+bit+by+value+from+the+array+literal%0A++S++++++++++++++++++%09xor+with+result+so+far%0A+++++++++++++++++++++%09after+the+loop,+the+top+of+the+stack+is+printed+implicitly&i=0%0A1%0A2%0A3%0A4%0A5%0A253%0A254%0A255&m=2)
[Modified version to run for all inputs 0..255](https://staxlang.xyz/#p=a6b7ffca69c7f6eb4d48d97161945c2303454528e57dc8b5095ee18e712e22c155ada79bea2adffa5aa35ce10d63191cccae5db51fe50337f6fec143b3&i=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~101~~ ~~100~~ ~~98~~ ~~97~~ ~~95~~ 94 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
U•α">η≠ε∍$<Θγ\&@(Σα•₅вV₁[<ÐX*Q#X·₁%Xžy÷Ƶ¹*₁%^₁%U}D17©%DĀiYsès®÷•¾#kôlb¸ù,-ó"a·ú•₅вë\Ƶ∞s®÷Y}sè^
```
-3 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f8/9FHDonMblezObX/UueDc1kcdvSo252ac2xyj5qBxbvG5jUDpR02tFzaFPWpqjLY5PCFCK1A54tB2IE814ui@ysPbj209tFMLxI0DEaG1Lobmh1aquhxpyIwsPryi@NC6w9uBZhzap5x9eEtO0qEdh3fq6B7erJR4aPvhXTDDD6@OOQa0eh5YdWQtUF/c//@GAA) or [verify all test cases](https://tio.run/##NVF7T5JRGP8qryBKzOYlK5emlZdlEpZXVNQAdVBOGujSyg1IiXSuRG22mSmWYjTlfpHb9vx4/aO2s7ev8H4ROrj1z9k5e87zu9ocRpN1uiS7XV26NoUge3xCv8W2MDslmKbvCIo22elvoPDLG/ex2SVlsQ5fnZhrQER27iKKvW4kDE9k78YIfg2/fUYFShhk50UNskWPUcr14MAke/fZNoUo9byKIoaHVFDXy86vjvH@ycVW2b1SqcWm6ONobAve17J3TYvgZXyZpemIhRHDvux2Y21puE7cwrdeuGtvSjmKFl2NGvouRTgzO0XW3KRX4X21Q4qwcBN8CNFhE07gohRWkZKybJuluSzZGWpD3oYQdsRU0YNEswoJlkHe2En5NzyC8R7K4Bh7Y7Lzy2M6WhS3KDZkt1XikH5QEL6ip1FM0bGYF/PcxME89oouOmueoQh2WFrNMg9QTiXJPdM5zu4iiAwyS484Ny4GWVxfviQogRV4Kri0@Fxt9V83CjNcGUuxuOx@J@VYGqssDi8@0gk@07nSbmlfwC7nIz8F@8nPU0NsEikONkAJCtwa1UgRLZ1q@aB5FD9/@xR1vDbuR4roEOj44@HFGuemBKuj3KiuNMinLKxoZUn5wwFn9W5UtrBdFjVU3VMzHvvV8qoUGeIQYy34pNc8VeopyV8qvZhfQvIyTmlN@TlRPgaXO@pv06mqo@i0jjgQcNAZj8Dpp7zyBWKzJt5CuuY6ogojJXHxHxxBwyWn3r/6PbLM9yZKV1K7de29fX2d7QMVgtlmt0@b5xVKnuY6AgpB/cpiNVu4EQGFa4oaipX@AQ).
**Explanation:**
[Port of Xavier Bonnetain's C function (1106 bits version) from here](https://who.paris.inria.fr/Leo.Perrin/short-implem.html), with the same improvement [*@ceilingcat* made in his C answer](https://codegolf.stackexchange.com/a/186515/52210) to save 3 bytes, so make sure to upvote him!
```
U # Store the (implicit) input in variable `X`
•α">η≠ε∍$<Θγ\&@(Σα• "# Push compressed integer 20576992798525946719126649319401629993024
₅в # Converted to base-255 as list:
# [64,96,114,70,84,68,86,98,112,80,66,118,100,116,102,82,64]
V # Pop and store this list in variable `Y`
₁ # Push `i` = 256
[ # Start an infinite loop:
< # Decrease `i` by 1
Ð # Triplicate `i`
X*Q # If `i` multiplied by `X` is equal to `i` (i==0 or X==1):
# # Stop the infinite loop
X·₁% # Calculate double(`X`) modulo-256
# (NOTE: all the modulo-256 are to mimic an unsigned char in C)
Xžy÷ # Calculate `X` integer-divided by builtin integer 128,
Ƶ¹* # multiplied by compressed integer 285,
₁% # modulo-256
^ # Bitwise-XOR those together
₁% # And take modulo-256 again
U # Then pop and store it as new `X`
}D # After the loop: Duplicate the resulting `i`
17© # Push 17 (and store it in variable `®` without popping)
% # Calculate `i` modulo-17
D # Duplicate it
Āi # If it's NOT 0:
Ysè # Index the duplicated `i` modulo-17 into list `Y`
s®÷ # Calculate `i` integer-divided by 17
•¾#kôlb¸ù,-ó"a·ú•
"# Push compressed integer 930891775969900394811589640717060184
₅в # Converted to base-255 as list:
# [189,97,46,243,47,37,183,248,106,107,242,96,36,182,249]
ë # Else (`i` == 0):
\ # Discard the duplicated `i` modulo-17, since we don't need it
Ƶ∞ # Push compressed integer 188
s®÷ # Calculate `i` integer-divided by 17
Y # Push list `Y`
}s # After the if-else: swap the integer and list on the stack
è # And index the `i` modulo/integer-divided by 17 into the list
^ # Then Bitwise-XOR the top two together
# (after which the top of the stack is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•α">η≠ε∍$<Θγ\&@(Σα•` is `20576992798525946719126649319401629993024`; `•α">η≠ε∍$<Θγ\&@(Σα•₅в` is `[64,96,114,70,84,68,86,98,112,80,66,118,100,116,102,82,64]`; `Ƶ¹` is `285`; `•¾#kôlb¸ù,-ó"a·ú•` is `930891775969900394811589640717060184`; `•¾#kôlb¸ù,-ó"a·ú•₅в` is `[189,97,46,243,47,37,183,248,106,107,242,96,36,182,249]`; and `Ƶ∞` is `188`.
[Answer]
# [Python 3](https://docs.python.org/3/), 151 bytes
```
f=lambda x,l=255,k=b'@`rFTDVbpPBvdtfR@':f(x*2^x//128*285,l-1)if~-x*l else[k[l%17]^(0x450a98dc4ed7d6440b99934f92dd01>>l//17*8&255),k[l//17]][l%17<1]^188
```
[Try it online!](https://tio.run/##VZTda1NBEMXf81fcF20SpnRnP@7dFVOKiM8i4ktJMTFJLY1pSaPEF//1@DsVEeFesjsfZ86cmZvHn4evD7t0Om1m28W35WrRHW07i6XY/Wx5dvV5/@7j20/Lx/dvfqwOmw9XZ6824@M03hwvLjzWaazFtuc@udv8Oj9Ot916@7S@vr/evvBhfjMOx1zCotXVl7xeDas@57BsraW8aXG1Cn55uQVmmNaX1JsYebrO58/5r31@47WeDov97frQzbrrWKLFVC1GNx8shsHcg@WGxWLB2Hp@g0WvlgrXwbINRKZEJGFZvmaecfTmBXMlJVnJOAGoguUp1pSfsCrNPLg1HLG3JhLNBBnxVeuD9YBhAyBHG5qRmwiDJbgRmoGATIZioQICRtpxnNEJxZZkLoY1Z6u6kByCDcLhCjSPB9j06hfWaAFylIkEB8hJ7a2ajqigp8lDRDNQvFC/JqM1p5iU7GVFRh3Jw1EUrb45Z3pBEndFiTSIg97BiszwLwaENkZ6JtUGJzSrgtFVJICpKJRMEkcJWywR1zejG@/RUdoD5KqoX81EjLIlNUg8mZygTWaMkk8di4260mYwI5RnzhXhqmkpOEgycWeIkh@kYMHgRlmRhal0weoI7oXx4oPHkAyCAzaYMOGGvMVYH6eE95qo2PIGiSm9mD4ZVsWK3igt9gxR26LFg5XiJQMx6kQiMn1PsoEDPFdq01YvqWCpmTAiRufPdLQb2hvRZpyDJU0cbxCpbMjL@GCMkjJRU/BBs9AiMwvONZqmov11EZF8vFl6U0W7HhSpFdQHgU6DcWI7nNz5aLSf7Re72/U4ln4y2q@fvm@fv9W73WHMP8Vk0m0e9t2xu9t1/@Lmo8e9Av6Gz7o/H/nkP/vk9Bs "Python 3 – Try It Online")
A function that implements the permutation. The code uses only 7-bit ASCII chars.
Encodes `k` as a Python 3 bytestring, shifted `^64` into the printable range. In contrast, `s` is encoded as the base-256 digits of a numerical constant, and the digits are extracted as `[number]>>[shift]*8&255`. This was shorter than encoding `s` in a string due to the number of escape characters this required, even with an optimal shift `^160` to minimize those.
The discrete-log computation is done backwards. The update `x=x*2^x//128*285` loops forward in the cyclic group by simulating multiplying by the generate, until it reaches the identity `x=1`. We start the discrete log at `l=255` (the cycle length), and decrement it each iteration. To handle the `x=0` case and make it not loop forever, we also terminate when `l=0`, which makes `x=0` map to `l=0` as specified.
---
Python 2 loses out on not having nice bytestrings, so we need to do `map(ord,...)` (ArBo saved a byte here). It lets us use `/` rather than `//` for integer division.
**[Python 2](https://docs.python.org/2/), 156 bytes**
```
f=lambda x,l=255,k=map(ord,'@`rFTDVbpPBvdtfR@'):f(x*2^x/128*285,l-1)if~-x*l else[k[l%17]^(0x450a98dc4ed7d6440b99934f92dd01>>l/17*8&255),k[l/17]][l%17<1]^188
```
[Try it online!](https://tio.run/##VZTda1NBEMXf81fcF20SpnRnP@7dFVOKiM8i4ktJMTVJLU3TEKPEF//1@DsVEeFesjsfZ86cmZvdz8PXp208ndazzeLxdrnojraZxVLsYfa42I2f9ks7u/q8f/fx7afb3fs3P5aH9Yers8mr9fg4jTfHC491GmuxzblP7te/zo/TTbfafFtdP1xvXvgwvxmHYy5h0eryS14th2Wfc7htraW8bnG5DH55ubnwYVpfUnVipHGbz5@zX/v8xms9HRb7u9Whm3XXsUSLqVqMbj5YDIO5B8sNi8WCsfX8BoteLRWug2UbiEyJSMKyfM084@jNC@ZKSrKScQJQBctTrCk/YVWaeXBrOGJvTSSaCTLiq9YH6wHDBkCONjQjNxEGS3AjNAMBmQzFQgUEjLTjOKMTii3JXAxrzlZ1ITkEG4TDFWgeD7Dp1S@s0QLkKBMJDpCT2ls1HVFBT5OHiGageKF@TUZrTjEp2cuKjDqSh6MoWn1zzvSCJO6KEmkQB72DFZnhXwwIrY30TKoNTmhWBaOrSABTUSiZJI4Stlgirm9GN96jo7QHyFVRv5qJGGVLapB4MjlBm8wYJZ86Fht1pc1gRijPnCvCVdNScJBk4s4QJT9IwYLBjbIiC1PpgtUR3AvjxQePIRkEB2wwYcINeYuxPk4J7zVRseUNElN6MX0yrIoVvVFa7BmitkWLByvFSwZi1IlEZPqeZAMHeK7Upq1eUsFSM2FEjM6f6Wg3tDeizTgHS5o43iBS2ZCX8cEYJWWipuCDZqFFZhacazRNRfvrIiL5eLP0pop2PShSK6gPAp0G48R2OLnz0Wg/2y@2d6txLP1ktF99@755/lbvt4cxfxOTSbd@2nfH7n7b/Yubj3Z7BfwNn3V/PvLJf/bJ6Tc "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 139 bytes
Similar to the Node.js version, but using characters beyond the ASCII range.
```
f=(x,l=256,b=17,k=i=>"@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è".charCodeAt(i))=>--l*x^l?f(x+x^(x>>7)*285,l):l%b?k(l%b)^k(b+l/b)^b:k(l/b)^188
```
[Try it online!](https://tio.run/##PZTrTtRQFIX/8xTNJCYd2WD3aU97iukAIiQm/jAg/jESGS6KTACBTEZ9G028JD4F82Djt2BG0k5P92Xttdfe5dPh@PDm6Prs6nbl4vL4ZDY77fKJjboQaxt23th5d9YNehvvr3deP38zvHr1bHx8e7q7cff3an36fVDd/Zz@@fZ1@uNzvPs1/d1bPfp4eL0F0OZtftbvd4OVldHjycFo/TSfLE8O8slg0PQfhxRt1F8bPRqun@f89g/O8@Hy6AmH4RoWHTyl2Wb3NgsxWCiTheAGnVA05l5Y1WKxEDG2Nc/CgicrI6@NVdY0tpTxF8qScGIrBbTmFd7aPGJO5JUWK5ygJGFzRWsFUs7zVacyL9xavKG2VnRaE27Al6wurAYRGyhVsKZ9SAWlJBbSVAiwLoiqSFMCpIDBSHeOMzih2Epf8I6Gq6osKRCEorBGYLxShMsLeNXSgCbQB/iA6T7dyXIgnfzakumIPLpaechsDShnyp5Ko12n4kNpzLVciKwjyXijUqQF54rW0MpdUeoB2Eb3XPQoHz1FAydEOhG8WABWtJaEpVfRASshXWlpMTLKBUqUBNet0aHXqKzxgOaqrafGJm6VoY6zUIuJaVwRzZAjSFypIHLqVGvEGJkL@5BQNJk2iMNCuFr9MGxNCMzCCoMqBMQd4hIMqzMOj6wBvrlu3pQG3wYHxFiHFvGjsXBOMa81eZHnZsmCS8jW4nxbGksiSb/QV0cMW/ulfYWkklBAiqkxqcuqePlfMxAphA0WtFpLQ0hrbEyREfs9MS2SNk1dMPZ5eqn1IKQQx8oQnzHTADrLRPVS8mtc@ggYF@cUHpI1PX0ALl4Sl7vSSKinj6VQuDZXnxUCNsaJVfIUsndPl5aOLi9uLkcnq6PLD/nm6sn45PpLno8tm/SzbpDxf4Nn12Xjfrae9fb2t7a29/Z62VrW29l88XJ/d7vXn/0D "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), ~~149~~ 148 bytes
Based on Xavier Bonnetain's C implementation (which is presented [here](https://who.paris.inria.fr/Leo.Perrin/short-implem.html)).
```
f=(x,l=256,b=17,k=i=>Buffer("@`rFTDVbpPBvdtfR@,p?b>4&i{zcq5'h")[~~i]|3302528>>i-b&128)=>--l*x^l?f(x+x^(x>>7)*285,l):l%b?k(l%b)^k(b+l/b)^b:k(l/b)^188
```
[Try it online!](https://tio.run/##PZRtT9RQEIW/8yuaTcQuDti5t7e9xXQRFBITPxhRvxCILOzqykYQdLO@hL@Oz5FF0m5v5@XMmTNTvpwuTm/OrmdX3ze/Xp5P7u6mfbm0eR9SY@PeW7voZ/1o78d0OrkuB88/Xh@8e/lhfPVmb3H@ffr2uV3tjEf1@uz3r7Nv6fHnwfDo9nZ2/CfGKqSQR6PZ5njdQx72o83N@cbyZL4zLZdPliflcjRqhxshJ5sPt@ePxjsXJb/Dk4ty/GT@lMN4G4sOnvPdbn9UAGghZgvBDV6has29srrDYiFh7BqelQXPFhOvrdXWtrZW8BdiJJzYWgGdeY23MU@YM3nRUo0TlCxsrmSdQOIqX3Vq88qtwxsa60SnM@EGfNmayhoQsYFSB2u7@1RQIrGQpkKAdUVUTZoSIAUMRrpznMEJxRb9gXcyXHVtWYEgVJW1AuOVIlxewauRBjSBPsAHTP/SnSwH0slvLJuOyKOrk4fMzoByxu05Gu06Fe9LY27kQmQdScablCItONe0hlbuilIPwLa6V6In@egpGTgh0YngxQKwqrMsLL2KDlgZ6aLlh5FRLlAiEtx0RofeoLLGA5qrtp4am7jVhjrOQj1MTONKaIYcQeJKBZFTp1ojxshc2IeMotm0QRwehGvUD8PWhMCsrDKoQkDcIS7BsDrj8MQa4Fvp5m00@LY4IMY6dIifjIVzinmjyYs8N0sWXEJ2llbb0loWSfqFvjpi2Nov7SsklYQCUkyNSV1WxeN/zUCkEDZY0GojDSGtsTFFRuz/iGmRtGnqgrGv0qPWg5BKHGtDfMZMA@gsE9Wj5Ne49BEwLs453CdrevoAXLwkLnetkVBPH0ulcG2uPisEbI0Tq@Q5FMfP1tbOLr/eXM4nW/PLT@Xu1mQxuf5ZlgsrlsOiHxX83@DZ98ViWOwUg8P3L17sHx4Oiu1icLD76vX7t/uD4d1f "JavaScript (Node.js) – Try It Online")
### Encoding
In Xavier's original answer, the tables `s[]` and `k[]` are stored in the following string:
```
"@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8"
\_______________/\__________________________________/
k s
```
The first 17 characters are the ASCII representations of `k[i] XOR 64` and the
next 15 characters are the ASCII representations of `s[i-17] XOR 173`, or `s[i-17] XOR 64 XOR 17 XOR 252`.
All the ASCII codes for `k[i] XOR 64` are matching printable characters, but 7 ASCII codes for `s[i-17] XOR 173` are beyond \$126\$ and need to be escaped. We force them into the printable range by subtracting \$128\$.
Here is what we get:
```
original value : 172 112 63 226 62 52 166 233 123 122 227 113 53 167 232
subtract 128? : 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1
result : 44 112 63 98 62 52 38 105 123 122 99 113 53 39 104
as ASCII : "," "p" "?" "b" ">" "4" "&" "i" "{" "z" "c" "q" "5" "'" "h"
```
By reversing the bitmask formed by the 2nd row in the above table, we get `110010011001001` in binary, or \$25801\$ in decimal.
This bitmask is multiplied by \$128\$, so that we can directly perform a bitwise OR with the extracted bit. Hence the formula:
```
| 3302528 >> i - b & 128
```
---
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 141 bytes
```
x=>{var k="@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è";int l=256,b=17;for(;--l*x!=l;)x=2*x^x/128*285;return l%b>0?k[l%b]^k[b+l/b]^b:k[l/b]^188;}
```
Just a port of the example solution, ported to C#.
[Try it online!](https://tio.run/##bZTbbiNFEIav46eYWEJy4op2qufUw6yzywJ7xQVCCC6CV8RZGzkZJcF2FgvLLwMSB4mnSB4sfL8Piy@wPJqeOvz911/VfTU/u5pPn98@3F69nN4ujOd8MnheDs5XHy5nyc2g@/rH2dtvv/hudP/1mw/vF5NvXj/@c//q6bfz/PGPp79Xvz79/nPx@OfTX92G1KQdhKK00cCrZnI36zVnZ@3p8njQNifLQThdvlu@8BBPQyya2XjxMLtN2k9G5@mrmwvew3c3F6N@@4LF6FMsWniMzfq56YB9MUzup8kgWXUSfqEIFrJoIbh5ZSGtzD21vMZiocBYl7xTCx4tK/isLLeqsm12lhFObK6A2jzHW5oXmCN5mRU5TlCisPkXVgsk2@Vrn9w8davxhtJq0alNuAFftDK1EkRsoOTBqnqbCkpGLKTZIcA6JSonTQmQAgYj1TnO4IRiy3zPuzBceW5RgSCkqVUC45NN@HsKr1IaUAT6AB8wbdKdLAfSyS8tmpbIo38tD5m1AeX00GNmlOvsuN0acykXImtJMt5CKdKCdU5paOWuKNUAbKVnJ3ohHzUVBk4oqETwYgFYWlsUlj5FB6yIdJnFfcvYLrBFRnBZGxV6icpqD2iuvfVW28QtN9TxSPw@nc8CzZAjSFypIHKqVGNEG@kL8xBRNJomiMVeuFL10Gx1CMzUUoMqBMQd4hIMq9MOLxgDfDvdvMoMvhUOiDEONeIXxsA5m3mpzos8D0MWXELWVuympbIoktQLfVVEszVfmldIKgkFpJgKk7qMimcfNQORjbDBglJLaQhptY0u0mLfENMgadJUBW3fpWcaD0JSccwN8WkzBaCzTOyeSX61S4eAdrGOYZus7ukAuHhJXJ5cLWE/HZZU4ZpcHSsErIwVo@QxdNb7Az8bzx/axZxTfzv@JZGN62XYdEZ3d21y2baft2MuqUGymD2Mm45uHF1CuiXShtdLromSRb9/wrVxtEO7mA4JmPSmJ03naDpJevdTmY4HyX8Bm/ij72fTxfir6e241/1yeT@@WozfJ6t0bclPd4tk5euuJZtcO8wE9OiA2uSyncPtaN1Zd6aT3t5zkhyAf9a2ycZ63CX9/@rwgzL27uut@3rnvsa959z7yOfUy/71sN/9YSHog4r4Wj//Cw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 182 bytes
```
def p(x,t=b'@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8',l=255,d=17):
if x<2:return 252-14*x
while~-x:x=x*2^(x>>7)*285;l-=1
return(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0]
```
[Try it online!](https://tio.run/##JYvRCoIwGIXvfYrdRJsp5nJp1iwiuo6Ibkopm6IgtmTVX0Gvbqtuzvm@A0c@VHGuB20rshxJDJbiaXd2aJabxTaVq/lNqHw928PxJKd7yGjkaR5qGr2eOgcXpt3XFHStilPGLMFdn4QGKnMEExo2mbo2NaKM2q5ngoHuRVllbxtC4GDSBEMU@cSkARtXNncN9D9gNwgStascR8SW@FJHxLpE7zeRr0f9uJVNWSssMSOk/QA "Python 3 – Try It Online")
Python isn't going to win first prize here, but this is still a 10-byte golf of the best Python program [here](https://who.paris.inria.fr/Leo.Perrin/short-implem.html).
# [Python 3](https://docs.python.org/3/), 176 bytes
```
p=lambda x,l=255,t=b'@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8',d=17:2>x<l>254and-14*x+252or(p(x*2^(x>>7)*285,l-1)if~-x else(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0])
```
[Try it online!](https://tio.run/##nZAxT8MwEIVn/CtuQbXTRMVu04QoCRVCzAghljaBFDutJeMYE8CAxF8PDmJATIjhfO@d5PP7bF77fafnw2AK1dxveQMuVAWL47AvtpPVrT2/OrvemovTZ963l6uNa@7MycYJVi68Xnp1/P7mz/lD7H3iVToJeUGTjJUuVyWLF43mEV0Ebspi1llssAtYjV1ZJiRgaRyqiBLZfkQOhHoUmKZp3a/VbMarkI/qkFe@8enXiIy@PKrIwEULnZU7qRt145eSDMH/MyNQPvbITRMEsgWXs8yK/slq7HOHbJ6StasQvOylEkBrl40fhV2eU/KLBsH3xb@hINR2FiRIDbbRO@HfW3qYA2Ol7vFYBktCIPqJ6wfDJw "Python 3 – Try It Online")
As a lambda, it's six bytes shorter still. It pains me to have to use `if... else`, but I don't see another option for short-circuiting, given how 0 is a possible answer.
# [Python 3](https://docs.python.org/3/), 173 bytes
```
p=lambda x,l=255,t=bytes('@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è','l1'),d=17:2>x<l>254and-14*x+252or(p(x*2^(x>>7)*285,l-1)if~-x else(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0])
```
[Try it online!](https://tio.run/##jZDfSsMwFMav7VPkRppsLTNZu9XSdkPEaxHxZuu0M@kWiG0Wq2Yb@DAK/gGfYn2wmooXojdenJzvO5CT7xe5rpZl0W8aGYvsZk4zoB0RE993qni@rtgttMdX6uT8@GIuT4/uaZWfjXcfclQ/Jd7upX7fburnlb97rd9sxxbYRg6N8TAkiY5EQnwvK6iLvY7uEp@UCkqoO2QGdZIMUYcEviNcjHj@6GrAxC2DOAhm1UT0ejR1aKv2aWoa7X6NUOuTgxQ1lOWgVHzBi0xcmqUotIAJ/DfrVGfXcjTVjCSe0QOjDrcbc/ZXvvFDowLbAsLEbqHx0AI8BzoioWLVnSqgye2QfoAmOrXAw5ILBvBMh@0vQR1FGP2iscD3xf@hWFZeKsABL4DKigUz7w0MzJ5UvKhgWxJyhID7E9cMmk8 "Python 3 – Try It Online")
Even shorter in bytes (though I'm not sure about bits, because this isn't pure ASCII anymore), courtesy of ovs.
[Answer]
# [Rust](https://www.rust-lang.org/), ~~170~~ 163 bytes
```
|mut x|{let(k,mut l)=(b"QqcWEUGsaASguewCQ\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8",255);while l*x!=l{x=2*x^x/128*285;l-=1}(if l%17>0{l+=289;k[l%17]}else{173})^k[l/17]}
```
[Try it online!](https://tio.run/##NY9da8IwFIbv/RXHwiCpndq42LoSZYzhtcjYxZxQJd2Cx0z7gWExv72mA9@Ll/d5rs4pm6puCw3HXGlCwfbAp/gtQYHSQMbDIePTu@9yKpWuUfdJYJ8XLoiAtNdjU4O5WpQ1OUQdIBVkF6zO@4@392WVv6y/G3l5XW1Mvj8tNkay@ZPfU79m9s/35Mw9J36lQcQ4p9nlR6EEDE1foDWChWZrRjFLQ5byDB9F7IgqAB/iZD62OBAsnWWHz46/nMRK2jiZOLr1atSp9n4@JYrS7P8b13PtDQ "Rust – Try It Online")
This is a port of my solution in C, with a slightly different string, that do not require to xor 17. I expect that most of the solutions based the string "@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8" can be improved as well (just change the string, remove the xor 17, and xor 173 instead of 188).
I removed one of the lookups by conditionally adding `17*17` to `l`, as we (more or less) did in the ARM machine code solution.
Rust has type inference and closures, but its casts (even for booleans or between integers) are always explicit, mutability has to be marked, it does not have a ternary operator, integer operations, by default, panic on overflow, and mutating operations (`l+=1`) returns unit. I did not manage to obtain a shorter solution with iterators, as closures+mapping is still fairly verbose.
This seems to make Rust a pretty bad choice for golfing. Nevertheless, even in a language that stresses readability and safety over conciseness, we're far too short.
Update: used an anonymous function, from manatwork's suggestion.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 74 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄FÐ;sÉiƵf^])2k>17‰Dθ_i¦16š}<(Rć16α2в≠ƶ0Kì6ª•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•ƵŠвs<è.«^
```
Port of [*@NickKennedy*'s first Jelly answer](https://codegolf.stackexchange.com/a/186516/52210). I was working on a port of [*@jimmy23013*'s CJam answer directly](https://codegolf.stackexchange.com/a/186513/52210), but I was already at 78 bytes and still had to fix a bug, so it would have been larger. This can definitely still be golfed quite a bit, though.
[Try it online](https://tio.run/##AYEAfv9vc2FiaWX//@KChEbDkDtzw4lpxrVmXl0pMms@MTfigLBEzrhfacKoMTbFoX08KFLEhzE2zrEy0LLiiaDGtjBLw6w2wqrigKI14oC6QMK@w4LDjEzDrMOBxZLCqS7DsMedxaHCq1lXx53FoOKAosa1xaDQsnM8w6guwqte//8xMjM) or [verify all test cases](https://tio.run/##HZH9T5JRHMX/FURNdE6BlFyYVr4sk7Cp5Uu@hKiDatJAl1ZsQIqotRK12aYGWoriEh6BHuRt@x4e2mq7e/oXnn/Erv1073bvzvmccxwuy4R96lLxeTvNrWqV4g@q@myOuReTqompmyp1q@LZ11P85fU7WO@Us1hDUCvl9BAUzzbOsdOF1MhDJfBhCKcDb59SgVIjiueiFtmi3yLnuhGaUAJ7bJNiJD67RsLIPSpodIpn1zXaNz7fovgWK0xYl4JcjW0g8FoJrJoQLSXdLE0HLI4E9hSfD6sLA1ppA1974KtvlHN0XvQ21NA3WeDO7BhZa9NgJZarXLLA4k0IIkbhJhzBSyKWIMpZtsnSHEvxxFqRdyCGLUks@pEyViLFMshbOij/hlcw2k0ZHGLnieL58oAO5qUNSjx2OioQpu8URbDob5BEOpTyUp6HCM1ip@ilH8ZpErDF0hqWuYurVn7yzHSGH7cQRQaZhfvcGxePWHLw6pKiFBbhL@NoyZn6qr8@FKY5GRNZUvG9k3MsjSWWRAAf6Qif6azcaWubwzb3o32K9tE@bw2JcYhcrJ9SFDEM18iCiY5N/ME4jJPfQbWWz8bzyIIZkfY/fj6sZWZSZXddLWrmYy924pPRhRV7KTk95nZX65@36G5wiHYmjtspojNIYXezpre4rDOwuJ73vBIqpbTdODXQCZdu5Na3KQ8f3ptwCq8UpOM6xH7tSmGKDg3wM8R/lZJSSBZczYjUUXTs8j9Hl7mtp7e3o62/TGV1OJ1T1ll1Oa9qDRG1SvPKZrfaOKUKhWp1LSUu/wE).
**Explanation:**
```
₄F # Loop 1000 times:
Ð # Triplicate the current value
# (which is the implicit input in the first iteration)
; # Halve it
s # Swap to take the integer again
Éi # If it's odd:
Ƶf^ # Bitwise-XOR it with compressed integer 142
] # Close the if-statement and loop
) # Wrap all values on the stack into a list
2k # Get the 0-based index of 2 (or -1 if not found)
> # Increase it by 1 to make it 1-based (or 0 if not found)
17‰ # Take the divmod-17 of this
Dθ_i } # If the remainder of the divmod is 0:
¦16š # Replace the quotient with 16
< # Decrease both values by 1
( # And then negate it
R # Reverse the pair
ć # Extract head; push head and remainder-list
16α # Get the absolute difference between the head and 16
2в # Convert it to binary (as digit-list)
≠ # Invert booleans (0 becomes 1; 1 becomes 0)
ƶ # Multiply all by their 1-based indices
0K # And remove all 0s
ì # And prepend this in front of the remainder-list
6ª # And also append a trailing 6
•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•
# Push compressed integer 29709448685778434533295690952203992295278432248
ƵŠв # Converted to base-239 as list:
# [19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]
s # Swap to take the earlier created list again
< # Subtract each by 1 to make them 0-based
è # And index them into this list
.«^ # And finally reduce all values by bitwise XOR-ing them
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶf` is `142`; `•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•` is `29709448685778434533295690952203992295278432248`, `ƵŠ` is `239`; and `•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•ƵŠв` is `[19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]`.
] |
[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.
As a little joke in the office someone wanted a script that randomly picks a name, and said person will make a round of drinks.
Let's call the people John, Jeff, Emma, Steve and Julie.
I thought it would be funny to make a script that seems random at a quick glance, but actually always gives the same person as the output (Up to you who you choose).
Highest voted answer wins after a week
And the winner is....
Paul R with (currently) 158 votes.
The answers here are great, and if anyone else has any other ideas what haven't been posted yet, please add them, I love reading through them.
[Answer]
# C
It's important to decide who is buying as quickly as possible, so as not to waste precious drinking time - hence **C** is the obvious choice in order to get maximum performance:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
const char *buyer;
int n;
srand(time(NULL)); // make sure we get a good random seed to make things fair !
n = rand();
switch (n % 5)
{
case 0: buyer = "John";
case 1: buyer = "Jeff";
case 2: buyer = "Emma";
case 3: buyer = "Steve";
case 4: buyer = "Julie";
}
printf("The person who is buying the drinks today is: %s !!!\n", buyer);
return 0;
}
```
Explanation:
>
> This would work just fine if there was a `break;` after each case in the switch statement. As it stands however each case "falls through" to the next one, so poor Julie always ends up buying the drinks.
>
>
>
[Answer]
# PHP
Couldn't let this go, so here is another one:
```
$f = fopen('/dev/random','r');
$s = fread($f, 4);
fclose($f);
$names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];
echo $names[$s % count($names)];
```
>
> This is actually not guaranteed to produce john, but chances are
> very good. PHP will happily take whatever /dev/random have to offer
> see that it (probably) can't parse it and come up with the very
> reasonable number 0 instead. After all, alerting the programmer to
> a potential error is considered a deadly sin in PHP.
>
>
>
[Answer]
# Haskell
It's too transparent if it always returns the same name so try the following
```
import Control.Monad
import System.Exit
import Control.Concurrent
import Control.Concurrent.MVar
data Person = John | Jeff | Emma | Steve | Julie deriving (Show, Enum)
next Julie = John
next p = succ p
rotate :: MVar Person -> IO ()
rotate mp = modifyMVar_ mp (return . next) >> rotate mp
main :: IO ()
main = do
mp <- newMVar John
forkIO $ rotate mp
putStrLn "Shuffling"
readMVar mp >>= print
exitWith ExitSuccess
```
Whenever you want it to be random:
```
[~]$ runghc prog.hs
Shuffling
Steve
[~]$ runghc prog.hs
Shuffling
Julie
```
And for your unfortunate target:
```
[~]$ runhugs prog.hs
Shuffling
John
[~]$ runhugs prog.hs
Shuffling
John
```
>
> Hugs only implements cooperative multitasking, so the `rotate` thread
> will never run
>
>
>
[Answer]
# Bash - maximum simplicity
A very simple example - let's avoid any problems by doing it the textbook way. Don't forget to seed the generator from the system clock for a good result!
```
#!/bin/bash
names=(John Jeff Emma Steve Julie) # Create an array with the list of names
RANDOM=$SECONDS # Seed the random generator with seconds since epoch
number=$((RANDOM % 5)) # Pick a number from 0 to 4
echo ${names[number]} # Pick a name
```
>
> This relies on the user not knowing what the `$SECONDS` builtin actually does; it returns the number of seconds since the current shell started.
>
> As it's in a script, the shell always started zero seconds ago, so the generator is always seeded with `0` and Julie always buys the beer.
>
>
>
Bonus:
>
> This one stands up to scrutiny quite well; If you enter the same code on the commandline instead of in a script, it will give random results, because `$SECONDS` will return the length of time the user's interactive shell has been running.
>
>
>
[Answer]
## C#
```
using System;
using System.Linq;
namespace PCCG {
class PCCG31836 {
public static void Main() {
var names = new string[]{ "John", "Jeff", "Emma", "Steve", "Julie" };
var rng = new Random();
names.OrderBy(name => rng.Next());
Console.WriteLine(names[0]);
}
}
}
```
>
> This might not fool people who are familiar with the .Net API, but people who don't know it might believe that `OrderBy` modifies the object you call it on, and it's a plausible error for a newbie to the API to make.
>
>
>
[Answer]
## PowerShell
```
$names = @{0='John'; 1='Jeff'; 2='Emma'; 3='Steve'; 4='Julie'}
$id = random -maximum $names.Length
$names[$id]
```
This will always output `John`.
>
> `$names` is a `System.Collections.Hashtable` which doesn't have a `Length` property. Starting with PowerShell v3, `Length` (and also `Count`) can be used as a property on any object. If an object does not have the property, it will return `1` when the object is not null, else it will return `0`. So in my answer, `$names.Length` evaluates as 1, and `random -maximum 1` always returns 0 since the maximum is exclusive.
>
>
>
[Answer]
# Q
```
show rand `John`Jeff`Emma`Steve`Julie;
exit 0;
```
>
> Q always initialises its random number seed with the same value.
>
>
>
[Answer]
# Perl
```
use strict;
my @people = qw/John Jeff Emma Steve Julie/;
my @index = int(rand() * 5);
print "Person @index is buying: $people[@index]\n";
```
>
> Prints: `Person X is buying: Jeff` (where X is from 0-4)
>
>
> Abusing scalar context a bit. `@index = int(rand() * 5)` places a random integer from 0 - 4 in the 0th position of the `@index` list. When printing the array, it properly prints the random integer in @index, but when using as an array index in `$people[@index]`, @index uses scalar context, giving it the value of the list size, i.e. `1`.
>
> Interestingly enough, `@people[@index]` makes it index properly.
>
>
> Interestingly enough `@people[@index]` is a hash slice in Perl, so `@index` is evaluated in the list context; in this case, it's a single entry list and that's why it works correctly
>
>
>
>
>
>
>
[Answer]
## ECMAScript
```
// Randomly pick a person on only one line!
var people = [('John', 'Jeff', 'Emma', 'Steve', 'Julie')];
console.log(people[new Date() % people.length | 0]);
```
It **always** picks Julie.
>
> It has brackets inside the square brackets, and [the comma operator](http://www.ecma-international.org/ecma-262/5.1/#sec-11.14) returns the value of its right operand.
>
> It's also very easy to miss. I've missed it before in **real** code.
>
>
>
[Answer]
# C#
```
using System;
namespace LetsTroll {
class Program {
static void Main() {
var names = new string[]{ "John", "Jeff", "Emma", "Steve", "Julie" };
var random = new Random(5).NextDouble();
var id = (int)Math.Floor(random);
Console.WriteLine(names[id]);
}
}
}
```
>
> The trick is, the method `new Random().NextDouble()` returns a double between 0 and 1. By applying `Math.Floor()` on this value, it will always be 0.
>
>
>
[Answer]
## C#
```
var names = new string[] {"John", "Jeff", "Emma", "Steve", "Julie"};
var guidBasedSeed = BitConverter.ToInt32(new Guid().ToByteArray(), 0);
var prng = new Random(guidBasedSeed);
var rn = (int)prng.Next(0, names.Length);
Console.WriteLine(names[rn]);
```
Hint:
>
> Generate seed from GUID. Guids have 4 × 10−10 chance of collision. Super random.
>
>
>
Answer:
>
> At least when you use `Guid.NewGuid()`, whoops! (Sneaky way to make seed always 0). Also pointless (int) for misdirection.
>
>
>
[Answer]
# bash / coreutils
This is taken almost verbatim from a script I wrote for a similar purpose.
```
#!/bin/bash
# Sort names in random order and print the first
printf '%s\n' John Jeff Emma Steve Julie | sort -r | head -1
```
>
> Even forgetting to use an upper case R is a mistake I have occasionally made in real life scripts.
>
>
>
[Answer]
# Ruby
```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]
puts names.sort{|x| rand()}.first
```
>
> This would work correctly with `sort_by`, but `sort` expects a comparison function that works like `<=>`. rand()'s result will always be positive, so it will always produce equivalent results provided your Ruby implementation's `sort` algorithm is deterministic. My Ruby 1.9.3 always outputs Julie.
>
>
>
[Answer]
# Ruby
```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]
puts names[rand() % 5]
```
>
> `rand()` with no arguments produces a random float between 0 and 1. So modulo 5 does nothing, and when slicing into an array with a float argument Ruby just rounds it down, so this always returns John.
>
>
>
[Answer]
# Perl
three `srand`s will make it three times more random!
```
#!perl
use feature 'say';
sub random_person {
my ($aref_people) = @_;
srand; srand; srand;
return $aref_people->[$RANDOM % scalar @$aref_people];
}
my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);
say "$person makes next round of drinks!";
```
explanation
>
> there is no $RANDOM in perl, it's an undefined variable. the code will always return the first element from the list - drinks on John :)
>
>
>
edit:
after going through the code, one of the five guys has decided to fix the obvious error, producing the following program:
```
#!perl
use feature 'say';
sub random_person {
my ($aref_people) = @_;
return $aref_people->[rand $#$aref_people];
}
my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);
say "$person buys next round of drinks!";
```
can you tell who did it just by looking at the code?
explanation:
>
> in Perl, `$#array` returns the index of last element; since arrays are zero-based, given a reference to an array with five elements, `$#$aref_people` will be `4`.
>
> `rand` returns a random number greater or equal to zero and less than its parameter, so it will never return `4`, which effectively means Julie will never buy drinks :)
>
>
>
[Answer]
# Python
Everybody knows that you can't trust randomness in such a small sample space; to make it truly random, I've abandoned the outdated method of picking a name from a list, and instead my program will spell out a completely random name. Since most of the names in the office had 4 letters, we'll settle for that.
```
import random
def CHR (n):
# Just easily convert a number between 0 and 25 into a corresponding letter
return chr(n+ord('A'))
# Seed the RNG with a large prime number. And multiply it by 2 for good measure.
random.seed (86117*2)
# Now, let's see what COMPLETELY RANDOM name will be spelled out!
totallyRandomName = ''
for i in range(4) :
totallyRandomName += CHR(int(random.random()*26))
print (totallyRandomName)
```
>
> Naturally, I did some preparation work to make sure I pick the right seed.
>
>
>
[Answer]
# C
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
char *name[]={"John", "Jeff", "Emma", "Steeve", "Julie"};
int i;
int n=rand()%10000;
int r=3;
for (i=0; i<10000+n; i++) // random number of iteration
{
r=(r*r)%10000; // my own PRNG (square and mod)
}
printf("%s", name[r%5] );
}
```
Sorry, Jeff!
>
> After a few iteration r==1 mod 5, because of math. Morality : don't write your own PRNG if you're bad at math. :)
>
>
>
[Answer]
**C++x11**
```
#include <vector>
#include <iostream>
int main () {
std::srand(time(NULL));
std::vector<std::string> choice{("jen","moss","roy")};
std::cout << choice[rand()%choice.size()] << std::endl;
}
```
>
> Size of vector is actually 1 due to the parenthesis used in the initializer list. Comma operator will discard all the names and return the last one, hence the buyer is always Roy.
>
>
>
[Answer]
## Scala
I know my users will be skeptical, so I have included a proof that my randomness is truly fair!
```
object DrinkChooser {
def main(args: Array[String]): Unit = {
proveRandomness()
val names = List("John","Jeff","Emma","Steve","Julie")
val buyer = names(randomChoice(names.size))
println(s"$buyer will buy the drinks this time!")
}
def proveRandomness(): Unit = {
val trials = 10000
val n = 4
val choices = for (_ <- 1 to 10000) yield randomChoice(n)
(choices groupBy(identity)).toList.sortBy(_._1) foreach { case (a, x) =>
println(a + " chosen " + (x.size * 100.0 / trials) + "%")
}
}
def randomChoice(n: Int): Int = {
var x = 1
for (i <- 1 to 1000) { // don't trust random, add in more randomness!
x = (x * randomInt(1, n)) % (n + 1)
}
x
}
// random int between min and max inclusive
def randomInt(min: Int, max: Int) = {
new scala.util.Random().nextInt(max - min + 1) + min
}
}
```
One example run:
```
1 chosen 25.31%
2 chosen 24.46%
3 chosen 24.83%
4 chosen 25.4%
John will buy the drinks this time!
```
Unless someone else gets extremely lucky, John will always buy the drinks.
>
> The "proof" of randomness relies on the fact that `rand(1, 4) * rand(1, 4) % 5` is still evenly distributed between 1 and 4, inclusive. But `rand(1, 5) * rand(1, 5) % 6` is degenerate. There's the possibility you get a 0, which would then make the final result 0 regardless of the rest of the "randomness".
>
>
>
[Answer]
# Javascript (with [Underscore.js](http://underscorejs.org/))
Since javascript does not have a built in shuffle we'll be using [Underscore.js](http://underscorejs.org/)
```
var people = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];
_.shuffle(people); // Shuffle the people array
console.log("Next round is on", people[0]);
```
>
> [\_.shuffle](http://underscorejs.org/#shuffle) returns the shuffled array, it does not modify in place as [Array.prototype.sort()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), sorry John
>
>
>
[Answer]
## JavaScript
Second try, this one's a little trickier:
```
var getRandomEntry = function(args){
return args[Math.floor(Math.random() * arguments.length)];
}
alert(getRandomEntry(["peter","julie","samantha","eddie","mark"]));
```
>
> The `arguments` variable is locally accessible for functions and is an array of all arguments passed in to the function. By using simple naming and passing in an array to the function itself, you can spoof that we're not taking the length of the array, but in fact the length of the arguments list (which is 1). This can be even better executed by using special chars or a font type.
>
>
>
[Answer]
# C++
To be fair we should run many, many trials and pick whomever is selected the most often.
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <map>
static const char *names[] = { "John", "Jeff", "Emma", "Steve", "Julie" };
int main() {
srand(time(NULL));
std::map<int, int> counts;
// run 2^31 trials to ensure we eliminate any biases in rand()
for (int i = 0; i < (1<<31); i++) {
counts[rand() % (sizeof(names)/sizeof(*names))]++;
}
// pick the winner by whomever has the most random votes
int winner = 0;
for (std::map<int, int>::const_iterator iter = counts.begin(); iter != counts.end(); ++iter) {
if (iter->second > counts[winner]) {
winner = iter->first;
}
}
printf("%s\n", names[winner % (sizeof(names)/sizeof(*names))]);
}
```
>
> What's the value of `1<<31`? Sorry, John.
>
>
>
[Answer]
## T-SQL (2008+)
```
SELECT TOP 1 name
FROM
(VALUES('John'),('Jeff'),('Emma'),('Steve'),('Julie')) tbl(name)
ORDER BY RAND()
```
Explanation:
>
> In MS SQL Server, `RAND()` only evaluates once per execution. Every name always gets assigned the same number, leaving the original ordering. John is first. Sucks for John.
>
>
>
Suggested improvement:
>
> T-SQL can produce decent quality, per-row random numbers with `RAND(CHECKSUM(NEWID()))`.
>
>
>
[Answer]
# Lua
```
buyer={'John', 'Jeff', 'Emma', 'Steve', 'Julie'}
-- use clock to set random seed
math.randomseed(os.clock())
-- pick a random number between 1 and 5
i=math.random(5)
io.write("Today's buyer is ",buyer[i],".\n")
```
>
> `os.clock()` is for timing purposes, `os.time()` is what ought to be used with `math.randomseed` for good RNG. Sadly, Julie always buys (at least on my computer).
>
>
>
[Answer]
# Idiomatic C++11
When drinks are involved, it's especially important to be up to date with the latest standards and coding styles; this is a great example of a highly efficient and idiom-compliant C++11 name picker.
It is seeded from the system clock, and outputs the seed along with the name for verification each time.
```
#include <vector>
#include <chrono>
#include <random>
#include <iostream>
auto main()->int {
std::vector<std::string> names; // storage for the names
names.reserve(5); // always reserve ahead, for top performance
names.emplace_back("John"); // emplace instead of push to avoid copies
names.emplace_back("Jeff");
names.emplace_back("Emma");
names.emplace_back("Steve");
names.emplace_back("Julie");
std::mt19937_64 engine; // make sure we use a high quality RNG engine
auto seed((engine, std::chrono::system_clock::now().time_since_epoch().count())); // seed from clock
std::uniform_int_distribution<unsigned> dist(0, names.size() - 1); // distribute linearly
auto number(dist(engine)); // pick a number corresponding to a name
std::string name(names.at(number)); // look up the name by number
std::cout << "Seed: " << seed << ", name: " << name << std::endl; // output the name & seed
return EXIT_SUCCESS; // don't forget to exit politely
}
```
Try this live: <http://ideone.com/KOet5H>
>
> Ok so this actually is pretty good code overall; there are a lot of red herrings to make you look too closely at the code to notice the obvious - that the RNG is never actually seeded :) In this case `seed` is just an integer, and while it looks like `engine` is passed as a parameter to a seeding function, it's actually just ignored. The seed variable really is set from the clock, so it can be output at the end along with the name to add insult to injury, but it'll still always be Steve who buys the drinks.
>
>
>
[Answer]
# JavaScript
```
console.log(["Jeff", "Emma", "Steve", "Julie"][Math.floor(Math.random(5))]);
```
>
> Well, sorry, [`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) doesn't take a parameter, and will always return a number from [0, 1). Still, it is a happy [variadic function](https://en.wikipedia.org/wiki/Variadic_function) and doesn't complain about arguments!
>
>
>
[Answer]
# Python
```
names=["John", "Jeff", "Emma", "Steve", "Julie"]
import random # Import random module
random.seed(str(random)) # Choose strictly random seed
print(random.choice(names)) # Print random choice
```
>
> str(random) gives a constant string; not a random value
>
>
>
[Answer]
# Perl
Emma had better not forget her purse! Runs under `strict` and `warnings`.
```
use strict;
use warnings;
# Use a hash to store names since they're more extendible
my %people;
$people{$_}++ for qw/John Jeff Emma Steve Julie/;
print +(@_=%people)[rand@_]; # 'cos (keys %people)[rand( keys %people )]
# is just too long-winded.
```
>
> Explanation [here](https://stackoverflow.com/q/8554060/133939).
>
>
>
[Answer]
JavaScript
```
function getDrinksBuyer(){
var people = ["Jeff", "Emma", "Steve", "Julie"];
var rand = Math.random(0,4)|0;
return people[rand];
}
```
>
> The `|0` results in 0 all the time but looks like it's doing some other rounding.
>
>
>
[Answer]
# J
```
;(?.5) { 'John'; 'Jeff'; 'Emma'; 'Steve'; 'Julie'
```
Poor Julie...
Trivia: this might've been the cleanest J I've ever written...
>
> This code is actually correct, except for one thing. `?.` is the uniform rng: `?.5` will always return 4. `?5` would've been correct.
>
>
>
] |
[Question]
[
There have been many other flag challenges posted but not one for the [national flag](https://en.wikipedia.org/wiki/Flag_of_France) of [France](https://en.wikipedia.org/wiki/French_Fifth_Republic). [This week](https://en.wikipedia.org/wiki/November_2015_Paris_attacks) seems like an appropriate time.
Produce this flag in the fewest bytes possible:
[![French flag](https://i.stack.imgur.com/56yYW.png)](https://i.stack.imgur.com/56yYW.png)
* The image must be in a ratio of 3:2, with size at least 78 pixels wide and 52 pixels tall.
* Each stripe takes up one third of the width.
* The stripe colors from left to right are RGB: `(0, 85, 164)`, `(255, 255, 255)`, `(239, 65, 53)`.
* The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed.
* Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using [ANSI color codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) to color it. (Use standard blue, white, and red.)
* Built-in flag images/libraries are not allowed.
The shortest code in bytes wins.
# Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64140; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 42156; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
# Pure Bash (on OSX), 84
The default OSX terminal supports full colour emojis. Not sure if this counts as text or graphical output.
```
printf -vs %26s
for i in {1..26}
do echo ${s// /üîµ}${s// /‚ö™Ô∏è}${s// /üî¥}
done
```
### Output looks like:
[![enter image description here](https://i.stack.imgur.com/fSnFq.png)](https://i.stack.imgur.com/fSnFq.png)
---
Alternatively:
# Bash with OSX utilities, 56
```
yes `dc -e3do26^d1-dn2/*p|tr 201 üîµüö™Ô∏è`|sed 26q
```
The `dc` expression:
* calculates `3^26-1` and prints it in ternary `22222222222222222222222222`
* divides this by 2, then multiplies by `3^26`. Output in ternary this is `1111111111111111111111111100000000000000000000000000`
`tr` then translates the 210 characters to üö™Ô∏èüî¥.
`yes` outputs this line indefinitely.
`sed 26q` halts output at 26 lines.
[Answer]
# Desmos, ~~30~~ 12 bytes
```
3x>10
3x<-10
```
[Try it online.](https://www.desmos.com/calculator/2icdrhtvy5)
I'm not entirely sure if this is valid, please let me know if there are any issues.
[Answer]
## Python 2, 47 bytes
```
s="[3%smF";print(s%4*26+s%7*26+s%1*26+"\n")*30
```
Contains unprintables - here's a hexdump (reversible with `xxd -r`):
```
00000000: 733d 221b 5b33 2573 3b31 6d46 223b 7072 s=".[3%s;1mF";pr
00000010: 696e 7428 7325 342a 3236 2b73 2537 2a32 int(s%4*26+s%7*2
00000020: 362b 7325 312a 3236 2b22 5c6e 2229 2a33 6+s%1*26+"\n")*3
00000030: 30 0
```
Uses ANSI escape codes to print colored characters to STDOUT - I chose "F" for France. No online link because ideone doesn't support ANSI escape codes in output.
Thanks to Dennis and xnor for some great tips.
Screenshot from xterm:
[![flag](https://i.stack.imgur.com/FQUZM.png)](https://i.stack.imgur.com/FQUZM.png)
[Answer]
# HTML / SVG, 76 bytes ~~87 88 121 122 149~~
*Saved 27 bytes thanks to @insertusernamehere*
*Saves 9 bytes thanks to @Joey*
*Saved 1 bytes thanks to @sanchies*
*Saves 1 bytes thanks to @Neil*
```
<svg><path fill=#0055a4 d=m0,0h26v52H0 /><path fill=#ef4135 d=M52,0h26v52H52
```
Using lots of HTML syntax abuse, this can get pretty short.
---
Screenshot of output:
[![France Flag Output](https://i.stack.imgur.com/Bb5pW.png)](https://i.stack.imgur.com/Bb5pW.png)
---
Or try it (make sure your browser supports SVG):
```
<svg><path fill=#0055a4 d=m0,0h26v52H0 /><path fill=#ef4135 d=M52,0h26v52H52
```
[Answer]
# CJam, ~~23~~ 22 bytes
```
00000000: 27 9b 22 5c 22 25 1f 22 66 7b 69 27 6d 32 37 2a '."\"%."f{i'm27*
00000010: 7d 4e 5d 32 36 2a }N]26*
```
The above is a hexdump that can be reversed with `xxd -r`.
At the cost of two extra bytes – for a total of **24 bytes** – we can use background colors instead, making the output a bit prettier.
```
00000000: 27 9b 22 2c 2f 29 00 22 66 7b 69 27 6d 53 32 36 '.",/)."f{i'mS26
00000010: 2a 7d 57 4e 74 32 36 2a *}WNt26*
```
### How it works
In both programs, we use the ANSI escape sequence `\x9bXYm` – where `X` is `3` for foreground color and `4` for background color, and `Y` specifies the color to use – to switch between the three colors of the flag.
```
'<CSI> Push the '\x9b' character (Control Sequence Introducer).
"\"%<US>" Push the string of the ISO 8859-1 characters with code
points 34, 37, and 31.
f{ For each character in the string, push the CSI and that
character; then:
i Cast the character to integer.
'm27* Push 27 m's. The first completes the control sequence,
the remaining 26 will be printed.
}
N] Wrap the generated array and "\n" in an array.
26* Repeat it 26 times.
```
The other program is similar.
### Output
[![output](https://i.stack.imgur.com/3emfL.png)](https://i.stack.imgur.com/3emfL.png)
[Answer]
# [Brainfuck$](http://esolangs.org/wiki/Brainfuck$), 153 bytes
```
+++++++++++++[->>>++>+++++++>++++>>>>++++++++>+++<<<<<<<<<<]>>>+>>#->$#>$#+++++++>$--->+++++[<]<<+++++[->+++++>++++++<<]>+#>($#([-]>[.>]<[<])>>>>+++<<<<)
```
Outputs the image with ANSI color codes. I chose a height of 30 [like Mego](https://codegolf.stackexchange.com/a/64141/30164).
The reference implementation from 2009 linked on the esolangs page has gone missing. You can run it using this interpreter made by me, which supports everything from the esolangs page.
```
window.addEventListener("load",function(){document.querySelector("#r").addEventListener("click",function(){var c=document.querySelector("#c").value,u=document.querySelector("#i").value,d=Array(30000).fill(0),p=0,i=0,q=0,s=[],o=document.querySelector("#o");o.value="";eval(c.replace(/[^]/g,function(e,i){return{"+":"d[p]=(-~d[p]+256)%256;","-":"d[p]=(~-d[p]+256)%256;",">":"p++;","<":"p--;",",":"d[p]=q-u.length?u[q++].charCodeAt()%256:0;",".":"o.value+=String.fromCharCode(d[p]);","[":"while(d[p]){","]":"}","#":"s.push(d[p]);","$":"d[p]=s.pop();",";":"d[p]=(parseInt(prompt())%256+256)%256;",":":"o.value+=d[p].toString();","(":"for(var i"+i+"=d[p];i"+i+">0;i"+i+"--){",")":"}","@":"o.value+=('D '+d.slice(0,20)+'\\nS '+s+'\\nIP '+i+' DP '+p);"}[e]||"";}));});});
```
```
<label for=c>Code:</label><br/><textarea style="width:100%;height:15em;white-space:pre" id=c>+++++++++++++[->>>++>+++++++>++++>>>>++++++++>+++<<<<<<<<<<]>>>+>>#->$#>$#+++++++>$--->+++++[<]<< init sequence to cells 3 to 10 +++++[->+++++>++++++<<] set cells 1~2 to 25 & 30 >+ set cell 1 to 26 # push 26 to stack > go to cell 2 ( do 30 times $# get 26 to this cell from stack ( do 26 times [-]>[.>]<[<] print sequence ) >>>>+++<<<< change color to white $# get 26 to this cell from stack ( do 26 times [-]>[.>]<[<] print sequence ) >>>>------<<<< change color to red $# get 26 to this cell from stack ( do 26 times [-]>[.>]<[<] print sequence ) >>>>+++<<<< change color to blue ++++++++++. print newline )</textarea><br/><button id=r>Run</button><br/><label for=i>Input:</label><br/><textarea id=i style="width:100%"></textarea><br/><label for=o>Output:</label><br/><textarea readonly id=o style="width:100%;height:15em;white-space:pre"></textarea>
```
# Brainfuck, 258 bytes
This is basically the same thing, but just in plain old Brainfuck.
```
>>+++++++++++++[-<<++>>>>++>+++++++>++++>++++>+++++>++++>++++++++>+++[<]<]>>+>>->>------>--->+++++[<]<<<++++[>+++++[->+++++<]>+[>>[.>]<[<]<-]>>>>>+++[<]+++++[-<+++++>]<+[>>[.>]<[<]<-]>>>>>------[<]+++++[-<+++++>]<+[>>[.>]<[<]<-]>>>>>+++[<]<++++++++++.[-]<<-]
```
Or, if you prefer this one in **oOo CODE** (984 bytes):
```
one day ThERe WIlL Be PEaCE iN ThIS wORlD
OnE DaY ThERe WiLl Be peaCe iN ThIS wOrld
one day theRe WIlL be pEaCE iN ThIS wORlD
OnE DaY theRe WIlL Be PEaCe in ThIS wORlD
OnE day ThERe WIlL Be PEaCe in ThIS wORlD
OnE day ThERe WIlL Be PEaCE iN ThIS wOrld
OnE DaY ThErE wilL bE PeaCe IN this woRlD
one day There will Be pEacE in ThiS woRld
one Day TheRe will Be PEaCE iN ThIS wOrLd
onE dAY thEre WilL Be PEaCE iN ThIs World
OnE DaY ThERe WIlL bE pEace in ThIS wORlD
OnE DaY thErE Will Be PeAce in this WoRLd
one dAY thErE wilL bE PeaCE in tHIs world
one day theRe WIlL Be PeAce iN tHIS wORlD
OnE DaY ThErE wIll be PEaCE iN ThIS wORlD
one dAY thERe WiLl be peace In THis worLD
onE dAy thErE WilL Be peACe in this world
one Day TheRe wIll Be pEace In thIs WORlD
OnE DaY ThERe WiLl Be peaCE iN ThIS wORlD
OnE day tHEre WIlL bE peace in tHiS World
oNE daY tHere WiLL be PEace IN this world
one day ThERe WIlL bE peaCe IN thIS wORlD
OnE DaY ThERe WIlL Be PEaCE iN THis WoRld
oNE daY thERe wiLL
```
[Answer]
# LaTeX, 139 bytes
Thanks to @WChargin for saving 21 bytes.
```
\documentclass{proc}\input color\begin{document}\def\z#1!{{\color[rgb]{#1}\rule{4cm}{8cm}}}\z0,.33,.64!\z1,‚Äå‚Äã1,1!\z.94,.25,.21!\end{document}
```
This prints the following 12cm\*8cm image on an A4 page:
[![enter image description here](https://i.stack.imgur.com/TKYrE.png)](https://i.stack.imgur.com/TKYrE.png)
*Note that "Page 1" is also printed at the bottom of the page*
[Answer]
# Pyth, 27 bytes
```
.w*52[smmdGc3CM"\0U¤ÿÿÿïA5
```
There are some unprintable chars, so here's a hexdump:
```
00000000 2E 77 2A 35 32 5B 73 6D 6D 64 47 63 33 43 4D 22 .w*52[smmdGc3CM"
00000010 5C 30 55 A4 FF FF FF EF 41 35 \0U.....A5
```
This creates a file `o.png`, which is exactly 78 pixels wide and 52 pixels tall:
[![enter image description here](https://i.stack.imgur.com/oDDn6.png)](https://i.stack.imgur.com/oDDn6.png)
### Explanation:
```
.w*52[smmdGc3CM"........
"........ a string containing the bytes
0, 85, 164, 255, 255, 255, 239, 65, 53
CM convert them to integers
c3 split into 3 lists
smmdG duplicate each list 26 times
[ put them into a list
*52 and duplicate it 52 times
.w save it as an image o.png
```
[Answer]
## Bash + ImageMagick, ~~60~~ ~~77~~ 73 bytes
```
convert -sample 78x52\! - a<<<"P3 3 1 255 0 85 164 255 255 255 239 65 53"
```
(ugh, +17 chars due to color requirements I didn't notice earlier...)
Outputs to the file `a`, in netpbm format:
```
llama@llama:~$ convert -sample 78x52\! - a<<<"P3 3 1 255 0 85 164 255 255 255 239 65 53"
llama@llama:~$ file a
a: Netpbm image data, size = 78 x 52, rawbits, pixmap
```
Can also output in PNG, if you change the filename to `a.png` (+4 chars).
Output:
[![enter image description here](https://i.stack.imgur.com/qAjSb.png)](https://i.stack.imgur.com/qAjSb.png)
[Answer]
# HTML (quirks mode), 68 bytes
This uses quirks mode to render the flag.
The HTML is **VERY** invalid, but works on a stock Android 4.4.2 browser and on Firefox 42.0 (on Windows 7 x64).
```
<table width=78 height=52><td bgcolor=0055a4><td><td bgcolor=ef4135>
```
The flag is rendered with the right size and the standard red and blue colors. All webpages start with a standard white background.
---
---
As an alternative:
A **perfectly valid** HTML5 version (141 bytes):
```
<!DOCTYPE html><title>x</title><table style=width:78px;height:52px><tr><td style=background:#0055a4><td><td style=background:#ef4135></table>
```
Check it's validity on: <https://html5.validator.nu/>
Print-screen of the result:
[![validation result](https://i.stack.imgur.com/R1D7X.png)](https://i.stack.imgur.com/R1D7X.png)
[Answer]
## ffmpeg, ~~110~~ ~~113~~ ~~116~~ ~~117~~ ~~119~~ ~~108~~ 100 bytes
Display, using ffplay, 100 bytes:
```
ffplay -f lavfi color=#0055a4:49x98[r];color=white:49x98[w];color=#ef4135:49x98[b];[r][w][b]hstack=3
```
Saved to file, using ffmpeg, 108 bytes:
```
ffmpeg -lavfi color=#0055a4:49x98[r];color=white:49x98[w];color=#ef4135:49x98[b];[r][w][b]hstack=3 -t 1 .png
```
The current version of the command will abort with an error BUT will output a single image ".png", same as shown below.
[![enter image description here](https://i.stack.imgur.com/Uut2w.png)](https://i.stack.imgur.com/Uut2w.png)
[Answer]
# CSS, 127 ~~128~~ ~~144~~ bytes
```
body:before,body:after{content:'';float:left;width:33%;height:100%;background:#0055a4}body:after{float:right;background:#ef4135}
```
No need for another tag, works solely with the `body`-element.
**Edits**
* *Saved* **16 bytes** by removing `display:block;` and some `;`.
* *Saved* **1 byte**, removed the trailing `}`.
[Answer]
# TI-Basic, ~~52~~ ~~44~~ 42 bytes
```
GridOff
AxesOff
11
Shade(-Ans,Ans,Xmin,Xmin/3
Shade(-Ans,Ans,Xmax/3,Xmax,1,1,Ans
```
(assumes a default [-10,10,1] by [-10,10,1] graph area)
Would be 4 bytes shorter without the first 2 lines, but by default would have axes and would not look as nice.
Looks like this:
[![enter image description here](https://i.stack.imgur.com/J0Sbr.png)](https://i.stack.imgur.com/J0Sbr.png)
If the shading is invalid for the challenge, let me know!
Without the first 2 lines, it looks like this:
[![enter image description here](https://i.stack.imgur.com/lUySx.png)](https://i.stack.imgur.com/lUySx.png)
[Answer]
# JavaScript, 140 ~~143~~ ~~147~~ ~~151~~ ~~153~~ bytes
```
with(document)with(body.appendChild(createElement`canvas`).getContext`2d`)for(i=2;i--;fillRect(i*52,0,26,52))fillStyle=i?"#ef4135":"#0055a4"
```
---
**Edits**
* *Saved* **2 bytes** by replacing `2*i*26` with `i*52`. Thanks to [C·¥è…¥·¥è Ä O'B Ä…™·¥á…¥](https://codegolf.stackexchange.com/users/31957/c%E1%B4%8F%C9%B4%E1%B4%8F%CA%80-ob%CA%80%C9%AA%E1%B4%87%C9%B4).
* *Saved* **4 bytes** by refactoring the `for`-loop. Thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions).
* *Saved* **2 bytes** by using the `with`-statement. Thanks to [Dendrobium](https://codegolf.stackexchange.com/users/20519/dendrobium).
* *Saved* **2 bytes** by turning increment into decrement. Thanks to [Shaun H](https://codegolf.stackexchange.com/users/43545/shaun-h).
* *Saved* **3 bytes** by replacing `fillStyle=["#0055a4","#ef4135"][i]` with `i?"#ef4135":"#0055a4"`.
[Answer]
## R, 59 bytes
```
frame();rect(0:2/3,0,1:3/3,1,,,c("#0055a4",0,"#ef4135"),NA)
```
Output is displayed:
[![enter image description here](https://i.stack.imgur.com/Ixjvs.png)](https://i.stack.imgur.com/Ixjvs.png)
One can also do 49 bytes with
```
barplot(rep(1,3),,0,col=c("#0055a4",0,"#ef4135"))
```
if you do not mind the axes and borders:
[![enter image description here](https://i.stack.imgur.com/JO2fN.png)](https://i.stack.imgur.com/JO2fN.png)
[Answer]
# Mathematica, ~~63~~ ~~94~~ 103 bytes
When I first saw this challenge, I thought *Sweet! Mathematica would be perfect for this!* until I noticed that built-ins were banned :'(
But wait! I can use bar graphs!
```
r=RGBColor;BarChart[{1,1,1},ChartStyle->{r@"#0055a4",White,r@"#ef4135"},BarSpacing->0,AspectRatio->2/3]
```
(Thanks to Martin Büttner for shaving off 5 bytes but adding 16)
Looks like this:
[![enter image description here](https://i.stack.imgur.com/Ei4V1.png)](https://i.stack.imgur.com/Ei4V1.png)
If you add `,Axes->None` it looks like this:
[![enter image description here](https://i.stack.imgur.com/ZXLxA.png)](https://i.stack.imgur.com/ZXLxA.png)
If you don't care about the border, you can use this: (95 bytes)
```
r=RGBColor;BarChart[{1,1},ChartStyle->{r@"#0055a4",r@"#ef4135"},BarSpacing->1,AspectRatio->2/3,Axes->None]
```
Looks like this:
[![enter image description here](https://i.stack.imgur.com/AIwrl.png)](https://i.stack.imgur.com/AIwrl.png)
Without axes:
[![enter image description here](https://i.stack.imgur.com/7J476.png)](https://i.stack.imgur.com/7J476.png)
[Answer]
## [Blitz 2D/3D](http://www.blitzbasic.com/Products/blitz3d.php), ~~154~~ 108 bytes
This produces exactly the same thing as the example given in the question (except for the anti-aliasing at the edges where colors meet).
```
Graphics 800,533
ClsColor 255,255,255
Cls
Color 0,35,149
Rect 0,0,267,533
Color 237,41,57
Rect 533,0,267,533
```
Output is displayed and it looks like this:
[![enter image description here](https://i.stack.imgur.com/dbxRJ.png)](https://i.stack.imgur.com/dbxRJ.png)
[Answer]
# [pb](https://esolangs.org/wiki/pb), 68 bytes
```
cw[Y!52]{cccw[X!26]{b[77]>}ccccw[X!52]{b[77]>}cw[X!78]{b[77]>}<[X]v}
```
Wow, a challenge that pb is actually kinda good for! Those are few and far between.
When I was writing the spec for pb, I included coloured output mostly as a joke. The language was named after a "paintbrush", why would it *not* do colour? Other than example programs, this is the second time I've ever used it. It is implemented with ANSI codes as the question requires.
I used 'M' as the character to output with because it's fairly dense.
**Output:**
![](https://i.stack.imgur.com/0s1ZI.png)
I resized that screenshot vertically to be two thirds of its height because letters aren't square. The output is 78 by 52, but the original screenshot looks really wrong.
**With comments and indentation and junk:**
```
c # Increase output colour by 1
# 0 (White) -> 1 (Red)
# Loop ends with output colour == 1, this is cheaper than
# setting it back to white every time.
w[Y!52]{ # While the brush's Y coordinate is not 52:
ccc # Increase output colour by 3
# 1 (Red) -> 4 (Blue)
w[X!26]{ # While the brush's X coordinate is not 26:
b[77] # Write 'M' at the brush's coordinates
> # Increase X coordinate by 1
}
cccc # Increase output colour by 4
# 4 (Blue) -> 8 mod 8 = 0 (White)
w[X!52]{ # While the brush's X coordinate is not 52:
b[77] # (same as before)
>
}
c # Increase output colour by 1
# 0 (White) -> 1 (Red)
w[X!78]{ # While the brush's X coordinate is not 78:
b[77] # (same as before)
>
}
<[X] # Set X back to 0
v # Increase Y by 1
}
```
[Answer]
# Javascript (ES6) 117 bytes
Draws it in the console
```
for(i=c=s=[];i<156;c[i++]=`color:${[,'blue','#fff'][i%3]||(s+=`
`,'red')}`)s+='%c'+'+'.repeat(26);console.log(s,...c)
```
[Answer]
# MATLAB, 82 79 78 bytes
```
x=[0 1 1 0];y(3:4)=2;fill(x,y,[0 85 164]/255,x+1,y,'w',x+2,y,[239 65 53]/255)
```
Output looks like:
[![](https://i.stack.imgur.com/GF4ea.png)](https://i.stack.imgur.com/GF4ea.png)
[Answer]
# C, 115 bytes
[![enter image description here](https://i.stack.imgur.com/D0sNE.png)](https://i.stack.imgur.com/D0sNE.png)
```
#define c"[48;2;%d;%d;%dm%9c"
d=255;main(a){while(a++<9)printf(c c c c,0,85,164,0,d,d,d,0,239,65,53,0,0,0,0,10);}
```
Contains unprintables:
```
00000000: 2364 6566 696e 6520 6322 1b5b 3438 3b32 #define c".[48;2
00000010: 3b25 643b 2564 3b25 646d 2539 6322 0a64 ;%d;%d;%dm%9c".d
00000020: 3d32 3535 3b6d 6169 6e28 6129 7b77 6869 =255;main(a){whi
00000030: 6c65 2861 2b2b 3c39 2970 7269 6e74 6628 le(a++<9)printf(
00000040: 6320 6320 6320 632c 302c 3835 2c31 3634 c c c c,0,85,164
00000050: 2c30 2c64 2c64 2c64 2c30 2c32 3339 2c36 ,0,d,d,d,0,239,6
00000060: 352c 3533 2c30 2c30 2c30 2c30 2c31 3029 5,53,0,0,0,0,10)
00000070: 3b7d 0a ;}.
```
For this program to work, a couple of things need to be true:
* The terminal supports the `ESC [48;2;<r>;<g>;<b>m` "truecolor" escape sequence.
* The terminal is not xterm, becase xterm's implementation of the above will produce slightly wrong colors.
* The terminal completely ignores NUL characters.
It also looks nicer if your terminal's background is black.
To change to height of the flag, pass command line arguments to the program. For every argument passed, the flag becomes one line shorter. *It's not a bug, it's a feature!*
Output:
[![enter image description here](https://i.stack.imgur.com/9UE2y.png)](https://i.stack.imgur.com/9UE2y.png)
[Answer]
## Visual Basic+Excel, 618 137 bytes
Just curious to see how this can be golfed.
**EDIT:** Curiosity sated, thanks to @Neil and @JimmyJazzx, 618 bytes dropped right down to 137 bytes
```
Sub a(): Columns("A:C").ColumnWidth = 26: Range("A1:A13").Interior.Color = RGB(0, 85, 164): Range("C1:C13").Interior.Color = RGB(239, 65, 53): End Sub
```
[![Excel flag](https://i.stack.imgur.com/j5ePA.png)](https://i.stack.imgur.com/j5ePA.png)
[Answer]
## CSS, 102 ~~110~~ ~~111~~ ~~114~~ bytes
```
*{background:linear-gradient(90deg,#0055a4 33%,#fff 33%,#fff 66%,#ef4135 66%) 0 0/78px 52px no-repeat
```
[Answer]
# Dyalog APL (~~47~~ 44)
```
⎕SM←↑1 21 41{(''⍴⍨2/20)1⍺,⍵,⍨4↑0}¨2*8 11 10
```
Result:
[![flag](https://i.stack.imgur.com/xo7dx.png)](https://i.stack.imgur.com/xo7dx.png)
[Answer]
# [iKe](http://johnearnest.github.io/ok/ike/ike.html), 43 bytes
```
,(0 0;"|"\"#0055A4|#FFF|#EF4135";52#,&3#26)
```
This is an example of a "raw tuple" iKe program- it's just a description of an origin (`0 0`), a palette (`3 7#"#0055A4#FFFFFF#EF4135"`) and a bitmap (`+52#'&3#26`). You need to wrap a description like this in a function or use references to views if you want to animate it.
The palette is a very simple way of creating a series of CSS colors, hex equivalents of the spec.
```
3 7#"#0055A4#FFFFFF#EF4135"
("#0055A4"
"#FFFFFF"
"#EF4135")
```
If the color requirements were less stringent we could use one of iKe's built-in palettes and save a considerable number of characters:
```
windows@7 0 4
```
![flag](https://i.stack.imgur.com/DSoiL.png)
Try it [in your browser](http://johnearnest.github.io/ok/ike/ike.html?gist=ff4cdd10b8ec75ed81d7).
## Edit:
Saved one byte by using a short `#FFF` CSS color for the white stripe:
```
,(0 0;3 7#"#0055A4#FFFFFF#EF4135";+52#'&3#26)
,(0 0;"|"\"#0055A4|#FFF|#EF4135";+52#'&3#26)
```
If anyone else is interested in playing with iKe, there's a manual on the [github repo](https://github.com/JohnEarnest/ok/tree/gh-pages/ike). [here's another problem](https://codegolf.stackexchange.com/a/57152/38485) I solved using iKe.
## Edit 2:
Saved one byte with a simpler way to construct the bitmap:
```
+52#'&3#26
52#,&3#26
```
My question in the OP hasn't been answered, but for the record if more flexible color requirements are permitted, this program would be 30 bytes by using the Windows 3.1 palette:
```
,(0 0;windows@7 0 4;52#,&3#26)
```
![flag2](https://i.stack.imgur.com/QrDNa.png)
Since this problem was posted, iKe has gained a feature which automatically centers textures drawn without a position, which could save another 3 bytes, but this would be against the rules:
```
,(;windows@7 0 4;52#,&3#26)
```
[Answer]
# Octave, ~~77~~ 76 bytes
```
s(98,49)=0;imshow(cat(3,[s w=s+255 w-18],[s+35 w s+41],[s+149 w s+57])/255);
```
Displays the image:
[![enter image description here](https://i.stack.imgur.com/ioUkH.png)](https://i.stack.imgur.com/ioUkH.png)
[Answer]
# Processing, 100 Bytes
```
size(78,52);background(255);noStroke();fill(#0055A4);rect(0,0,26,52);fill(#EF4135);rect(52,0,26,52);
```
Displays this:
[![France](https://i.stack.imgur.com/RVB57.png)](https://i.stack.imgur.com/RVB57.png)
(The naive solution is shorter than my first one.)
[Answer]
# ShaderToy (GLSL), 147 bytes
```
void mainImage(out vec4 o,vec2 i){float x=i.x/iResolution.x*3.0;vec3 w=vec3(255,255,255);o=vec4((x<1.0?vec3(0,85,164):x<2.0?w:vec3(239,65,53))/w,1);}
```
[See it here](https://www.shadertoy.com/view/lddGRn)
Not particularly exciting. I'm sure there are ways to golf it more; I'll take a crack when I get home.
[Answer]
# Ruby, ~~56~~ ~~47~~ 45 bytes
ASCII
```
$><<"\e[34z\e[37z\e[31z\n".gsub(?z,?m*27)*52
```
[Answer]
# PHP, 70 bytes
```
0000000: 424d 0000 0000 0000 0000 2300 0000 0c00 BM........#.....
0000010: 0000 2001 c000 0100 0800 a455 00ff ffff .. ........U....
0000020: 3541 ef3c 3f66 6f72 283b 3665 343e 2469 5A.<?for(;6e4>$i
0000030: 3b29 6563 686f 2063 6872 2824 692b 2b2f ;)echo chr($i++/
0000040: 3936 2533 293b 96%3);
```
*The above is a hexdump which may be reversed with `xxd -r`. Alternatively, it may also be generated with the following PHP script:*
```
<?=hex2bin('424d0000000000000000230000000c0000002001c00001000800a45500ffffff3541ef3c3f666f72283b3665343e24693b296563686f206368722824692b2b2f39362533293b');
```
I assume default settings, as they are without an .ini (you may disable your local .ini with the `-n` option). Produces a .bmp image (288 x 192), which should be piped to a file. This is as large as I can make it without affecting the byte count.
---
**Sample Usage**
```
$ xxd -r in.hex > france.php
$ php -n france.php > out.bmp
$ out.bmp
```
---
**Output**
![French Flag](https://i.stack.imgur.com/qndpG.png)
] |
[Question]
[
Following the [best](https://stackoverflow.com/questions/1197417/why-are-plain-text-passwords-bad-and-how-do-i-convince-my-boss-that-his-treasur) [security](http://plaintextoffenders.com/about/) [practices](http://gizmodo.com/sony-kept-thousands-of-passwords-in-a-document-marked-1666772286), I keep a plain text file with my passwords on my hard drive. In fact, I just copied and pasted one of them to access my PPCG account.
In a lucid moment, I decide that the password should better not remain in the clipboard after its use. Since this happens to me often, I could use a program to remove the clipboard contents.
## Challenge
Write a [program or function](http://meta.codegolf.stackexchange.com/a/2422/36398) that deletes or overwrites any text contained in the clipboard, using a [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398) of your choice.
Additional details:
* If your system has several clipboards, you can write the program for any one of them. The only requirement is that it must be possible for the user to copy and paste text using that clipboard.
* If your clipboard keeps a history of recent copied entries, assume the most recent entry.
* If your answer is specific to an operating system or clipboard, indicate it in the title of your post, together with the used language.
* The clipboard is guaranteed to contain text when your program is run. You can either delete the contents from the clipboard, or overwrite it with something else (not necessarily text). The only requirement is that after running the program, pasting from the clipboard will not produce the original text.
* If you choose to overwrite with some fixed or randomly chosen text, you can assume that the previous clipboard contents are different from that text, so the password is effectively removed. In other words, disregard the possibility that the filler text coincides with the password.
* The program should not have any side-effects like restarting the system, closing programs, shutting down the computer, or freezing it. After your program is run, the user should be able to keep using the computer as normal, only with the password removed from the clipboard. Also, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
Shortest code in bytes wins.
[Answer]
# PowerShell, 3 bytes
```
scb
```
That's a default alias for `Set-Clipboard`. When called with nothing piped in and no arguments supplied, it blows away the current clipboard contents.
[Answer]
# Vim, 3 bytes
```
"*Y
```
Sets the clipboard content to a newline.
By default, vim opens an empty buffer on start up. Now the program `Y`anks (copy) the entire line (including a newline) and store it in your clipboard by yanking it the text into register `"*`. The `*` can be changed to a `+` for the other clipboard.
[Answer]
# Javascript (Chrome DevTools Console), 6 bytes
```
copy``
```
Note that this is a feature of the console (which also works in the FF console) and is not part of the language standard.
[Answer]
## AppleScript, 20 bytes
```
set the clipboard to
```
Sets the clipboard to... nothing.
---
I saved a lot of bytes by removing the code to send me the contents of the clipboard ;)
[Answer]
# Batch (Windows 7 and higher version), 7 bytes
```
fc|clip
```
Note: it will response error message like "FC:..." but it works.
"clip" is a command to copy the output of another program to clipboard (available since windows 7)
"fc" is a command to compare two or more files. in this case we not input any file. it will error, then "clip" will set clipboard to an empty string.
provided that you have a file "a" in your current directory (it can be empty), you can do one better:
```
clip<a
```
---
Edit: See @Matthew Steeples comment for the shorter version (but in powershell not a batch)
[Answer]
# Bash on macOS, 8 bytes
```
:|pbcopy
```
`:` could be replaced with almost any other single character.
[Answer]
## C (on Windows), ~~65~~ ~~62~~ ~~42~~ 41 bytes
```
main(){EmptyClipboard(OpenClipboard(0));}
```
Note that the Visual C++ command-line needs `/link user32.lib` but the IDE or other compilers may automatically include this. Also this won't work in Win16 because the calling convention is incorrect.
Edit: Saved 3 bytes thanks to @Orion. Saved 20 bytes thanks to @KrzysztofSzewczyk. Saved a further byte thanks to @ceilingcat.
[Answer]
## [AHK](https://en.wikipedia.org/wiki/AutoHotkey), 10 bytes `(Windows)`
```
clipboard=
```
Clears text content of the clipboard. If `clipboardAll` is used it clears everything.
From the *[docs](https://autohotkey.com/docs/misc/Clipboard.htm#Clipboard_and_ClipboardAll)* -
>
> Clipboard is a built-in variable that reflects the current contents of the Windows clipboard if those contents can be expressed as text. By contrast, ClipboardAll contains everything on the clipboard, such as pictures and formatting.
>
>
>
[Answer]
# Excel, 1 keystroke
`Ctrl-C`
Works because Excel, uniquely, always has a selection. Probably works in other spreadsheet applications too. As opposed to the other joking entries, Excel answers are actually somewhat frequent on PPCG.
[Answer]
# Java 8, 127 125 bytes
Golfed:
```
()->java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(""),null)
```
Ungolfed:
```
public class ICopiedMyPasswordToTheClipboardCanYouDeleteIt {
public static void main(String[] args) {
f(() -> java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
new java.awt.datatransfer.StringSelection(""), null));
}
private static void f(Runnable x) {
x.run();
}
}
```
[Answer]
# SmileBASIC 3, 10 bytes
Finally, a challenge practically *made* for SmileBASIC 3!
```
CLIPBOARD"
```
`CLIPBOARD` is a builtin that sets the environment's text clipboard to the given string. Here we give it an empty string (closing `"` isn't needed!)
[Answer]
## Excel VBA, ~~9~~ 8 bytes
```
[A1].Cut
```
Overwrites the clipboard with contents of `A1` cell in active worksheet (empty by default but may be any string/expression of your choice - just make sure it's not your password!).
Utilises the Immediate Window.
*One byte saved thanks to [Slai](https://codegolf.stackexchange.com/users/59149/slai)*
[Answer]
# Google Chrome Language, 2 keystrokes
`Ctrl-S` `Ctrl-C`
Based on [this](https://codegolf.stackexchange.com/a/111573/61904) Notepad++ answer.
Google Chrome supports Javascript (which in turn supports RegExp), so I hereby claim it to be a superset of Javascript and a language of its own.
How it works:
`Ctrl+S` will invoke the "Save Page" dialog with the "New Tab" text pre-selected, `Ctrl+C` will copy it into the clipboard, displacing the previous content.
Sidenote:
>
> You can access the Javascript functionality in Chrome, via `javascript:` URLs and the Developer Tools console (invoked with Ctrl+Shift+J)
>
>
>
[Answer]
# **Python 56 48 40 bytes (Only works on Linux)**.
8 bytes saved thanks to @wheatwizard.
```
import os as o
o.system("echo|xclip")
```
[Answer]
# Mathematica, 17 bytes
```
CopyToClipboard@0
```
Sets clipboard to the number 0.
[Answer]
## bash + xsel ~~8~~ 7bytes
```
xsel -c
```
## Explanation
~~`-b`: Works on clipboard selection~~
`-c`: clears the selection
[Answer]
# R (Windows) 18
```
writeClipboard("")
```
[Answer]
# Matlab, ~~19~~ 13 bytes
```
gcf;print -dm
```
Set clipboard contents to an empty figure.
[Answer]
# Bash, ~~11~~ ~~10~~ ~~8~~ 7 bytes
*2 bytes saved thanks to @seshoumara for using `ls` instead of `echo`*
*Thanks to hexafraction, isaacg and Riker for suggesting several 7-byters*
```
w|xclip
```
The clipboard is set to the result of `w`. This only works on X11 based systems. For example, on macOS, this clipboard can be accessed by using an X based application like XQuartz.
---
Old answer only for macOS (~~11~~ 9 bytes):
```
ls|pbcopy
```
This sets the clipboard content to a newline.
[Answer]
# Applescript, 23 bytes
```
set the clipboard to ""
```
[Answer]
# Notepad++, 3 Keystrokes
`a` `Ctrl-A` `Ctrl-C`
Inserts the letter a, selects it, copies it to the keyboard.
Notepad++ *is* a valid language, it supports regex and is therefore a superset of regex, and we consider regex to be a valid language.
[Answer]
# Python + tkinter, 43 bytes
Python 3:
```
from tkinter import*;Tk().clipboard_clear()
```
Python 2:
```
from Tkinter import*;Tk().clipboard_clear()
```
[Answer]
# **Python 33 bytes (Only works on Windows)**.
4 bytes saved from @hubacub version.
3 bytes switching to windows, using @Divcy solution
```
import os
os.system("fc|clip")
```
Just registered in stackexchange, so I don't have the reputation to just comment on @hubacub submition. There is no need to expend 5 bytes with " as o" in the import to save 1 byte to reduce "os.system" to "o.system".
[Answer]
# C#, 30 bytes
*Thanks to [Nat](https://codegolf.stackexchange.com/users/45619/nat), [JMD](https://codegolf.stackexchange.com/users/66095/jmd) and [BgrWorker](https://codegolf.stackexchange.com/users/61283/bgrworker) for their suggestions!*
```
System.Windows.Clipboard.Clear
```
# C# without WPF, 36 bytes
```
System.Windows.Forms.Clipboard.Clear
```
Built-in function which empties the clipboard.
Full program with test case:
```
using System;
using System.Windows.Forms;
class ClearClipboard
{
static void Main()
{
Action f =
()=>System.Windows.Forms.Clipboard.Clear();
// test case:
Clipboard.SetText("SomePassword!");
Console.WriteLine("In clipboard initially: " + Clipboard.GetText());
f();
Console.WriteLine("In clipboard now: " + Clipboard.GetText());
}
}
```
[Answer]
## Haskell, 34 bytes
```
import System.Hclip
setClipboard""
```
Just a boring library function. There's also `clearClipboard` for the same byte count.
[Answer]
## [J](http://www.jsoftware.com) (Windows), 12 bytes
```
wd'clipcopy'
```
`wd` is J's standard library for Windows. `wd 'clipcopy password'` would put the text `password` into the clipboard. Specifying nothing wipes the clipboard.
If you want a program to put your plaintext password into your clipboard, you could use the following:
```
pass =. 'abc123'
wd 'clipcopy ' , pass
```
[Answer]
# Java 8 (JavaFX), 61 bytes
`()->javafx.scene.input.Clipboard.getSystemClipboard().clear()`
The JavaFX API for manipulating the clipboard is a little more terse than AWT's ;)
[Answer]
# Tcl/Tk wish shell (REPL), 5 bytes
```
cli c
```
Wish shell (REPL) allows for the incomplete commands, as long as there is no ambiguity, the full command would be:
```
clipboard clear
```
[Answer]
# Cow, 9 bytes
```
OOOMMMOOO
```
Explanation:
```
OOO set current memory block to 0
MMM if the current memory block is 0, paste the clipboard and clear the clipboard.
OOO set it back to 0
```
[Answer]
# HTML + JavaScript, ~~175~~ ~~148~~ ~~139~~ ~~135~~ 69 Bytes
Golfed:
```
<input value="c"onclick="this.select();document.execCommand('copy')">
```
[Fiddle](https://jsfiddle.net/g0sk97ch/)
Ungolfed
Got help from [SitePoint](https://www.sitepoint.com/javascript-copy-to-clipboard/)
HTML:
```
<input style="display: none;" id="Empty" value="x">
<input id="clipclear" type="button" value="Clear The Clipboard">
```
JS:
```
function clearclip(){
empty=document.getElementById("Empty");
empty.style.display="block";
empty.select();
document.execCommand('copy');
empty.style.display="none";
}
document.getElementById("clipclear").addEventListener("click", clearclip, false);
```
] |
[Question]
[
Are there any useful shortcuts that can be used in Java?
As shown below, `import` already adds at least 17 characters to a program.
```
import java.io.*;
```
I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.
---
Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more [general list of tips](https://codegolf.stackexchange.com/questions/5285/tips-for-golfing-in-all-languages).
[Answer]
* Use the most recent possible java. Java 8 lets you use lambda expressions, so use it if you need anything even *like* functional objects.
* Define shortened functions for things you use a lot. For instance, you have a hundred calls to `exampleClassInstance.doSomething(someParameter)`, define a new function `void d(ParameterType p){exampleClassInstance.doSomething(p)}` and use it to save yourself some characters.
* If you are using a particular long class name more than once, like
```
MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory
```
instead define a new class:
```
class X extends MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory{}
```
If you are only using one particular method of that class (but still need to instantiate it), you can define a shortened version inside the new class at the same time.
* Use function type parameters to shorten things, where possible, like this:
```
<T>void p(T o){System.out.println(o);}
```
* Use `for(;;)` instead of `while(true)`.
* Do not use access modifiers unless absolutely necessary.
* Do not use `final` for anything.
* Never put a block after a `for` loop (but a foreach loop `for(x:y)` is different). Additional statements should be placed inside the `for` statement itself, like `for(int i=0;i<m;a(i),b(++i))c(i);`.
* Use inline assignment, incrementation, instantiation. Use anonymous inline classes where appropriate. Use lambdas instead if possible. Nest function calls. Some functions are guaranteed to return their parent object, these ones are actually even *meant* to be chained together.
* Your `main` method `throws Exception`s, not catches them.
* `Error` is shorter than `Exception`. If for some reason you *really* need to `throw` messages up the stack, use an `Error`, even if it is perfectly normal situation.
* If some condition would require immediate termination, use `int a=1/0;` rather than `throw null;` or `System.exit(0);`. At run time, this throws an `ArithmeticException`. If you already have a numeric variable in your code, use it instead. (If you already have `import static java.lang.System.*;`, go with `exit(0);`.)
* Instead of implementing interfaces, like `List<E>`, extend an immediate (or not-so-immediate, if there is any advantage to doing so at all) child class, like `AbstractList<E>`, which provides default implementations of most of the methods, and requires only the implementation of a few key pieces.
* Write your code out in longhand first, with newlines, indentation, and full variable names. Once you have working code, then you can shorten names, move declarations around, and add shortcut methods. By writing it out long to start, you give yourself more opportunity to simplify the program as a whole.
* Compare alternative optimizations to a piece of code, because the most optimal strategy can change dramatically with very small changes to the code. For instance:
+ If you have only up to two calls to `Arrays.sort(a)`, the most efficient way to is to call it with its fully qualified name, `java.util.Arrays.sort(a)`.
+ With three or more calls, it is more efficient to instead add a shortcut method `void s(int[]a){java.util.Arrays.sort(a);}`. This should still use the fully-qualified name in this case. (If you need more than one overload, you are probably doing it wrong.)
+ However, if your code needs to also copy an array at some point (usually done with a short `for` loop in golfing, in the absence of an easily-accessible library method), you can take advantage of `Arrays.copyOf` to do the task. When more than one method is used, and there are 3 or more calls, doing `import static java.util.Arrays.*;` is the most efficient way of referring to those methods. After that, only if you have more than 8 separate calls to `sort` should you be using a shortcut method for it, and only at 5 or more calls is a shortcut warranted for `copyOf`.The only real way of performing such analysis on code is to actually perform potential modifications on copies of the code, and then compare the results.
* Avoid using `someTypeValue.toString();` method, instead just append `someTypeValue+""`.
* If you do need windows, don't use Swing, use AWT (unless you really need something from Swing). Compare `import javax.swing.*;` and `import java.awt.*;`. Additionally, components in Swing have a `J` prepended to their name (`JFrame`, `JLabel`, etc), but components in AWT don't (`Frame`, `Label`, etc)
[Answer]
**Use `interface` instead of `class`.**
In java 8, static methods were added to interfaces. In interfaces, all methods are public by default. Consequently
```
class A{public static void main(String[]a){}}
```
can now be shortened to
```
interface A{static void main(String[]a){}}
```
which is obviously shorter.
For example, [I used](https://codegolf.stackexchange.com/a/64567/32700) this feature in the [Hello, World!](https://codegolf.stackexchange.com/q/55422/32700) challenge.
[Answer]
With [varargs](http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html) you can "cast" a parameter to an array of the same type:
```
void f(String...x){
x=x[0].split("someregex");
// some code using the array
}
```
instead of
```
void f(String s){
String[]x=s.split("someregex");
// some code using the array
}
```
[Answer]
With a **static import**:
```
import static java.lang.System.out;
// even shorter (thanks to Johannes Kuhn):
import static java.lang.System.*;
```
you can save some boilerplate later, but you need multiple invocations to reach a payoff:
```
public static void main (String[] args) {
out.println ("foo");
out.println ("bar");
out.println ("baz");
}
```
[Answer]
The argument to `main` doesn't have to be called `args`, and you can cut some whitespace:
```
public static void main(String[]a){}
```
will do just fine.
[Answer]
If you ever have to use the boolean expressions `true` or `false`, replace them with `1>0` and `1<0` respectively.
For example:
```
boolean found=false;
for(i=0; i<10; i++) if(a[i]==42) found=true;
```
This linear search example can be reduced to
```
boolean f=1<0;
for(i=0;i<10;)if(a[i++]==42)f=1>0;
```
[Answer]
This may seem obvious, but there are shorter options for some `Math` functions:
```
a=Math.max(b,c);
a=b>c?b:c;
a=Math.min(b,c);
a=b<c?b:c;
a=Math.abs(b);
a=b<0?-b:b;
(In certain situations, (a|1)%2*a, may be shorter)
a=Math.round(b);
a=(int)(b+.5); // watch for precision loss if it matters
```
[Answer]
If you are going to be using some method a lot, assign its resident class to a variable. For example, assign `System.out` to a variable:
```
java.io.PrintStream o=System.out;
//now I can call o.print() or o.println() to the same effect as System.out.println()
```
Also for `Integer.parseInt()`:
```
Integer i=1;
i.parseInt("some string");
```
This will almost surely trigger an ide warning about "accessing static method from variable"
[Answer]
Rather than using the `import static java.lang.System.*` technique to save on `println()` statements, I've found that defining the following method is much more effective at saving characters:
```
static<T>void p(T p){
System.out.println(p);
}
```
This is because it can be invoked as `p(myString)` rather than `out.println(myString)` which has a much quicker and more dramatic character payoff.
[Answer]
# Some small code-golfing tips
These tips were a bit too small for a separated answers, so I will use this answer for very small codegolfing tips that I found or came up with, and aren't mentioned in the other tips yet:
### Removing the last character of a String:
```
// I used to do something like this:
s.substring(0,s.length()-1) // 27 bytes
// But this is shorter:
s.replaceAll(".$","") // 21 bytes
```
In some cases you know what the last character is beforehand, and you also know this character only occurs once in the String. In that case you can use `.split` instead:
```
// As example: "100%" to "100"
s.split("%")[0] // 15 bytes
```
### Encoding shortcuts:
```
// When you want to get the UTF-8 bytes I used to do this:
s.getBytes("UTF-8"); // 20 bytes
// But you can also use "UTF8" for the same result:
s.getBytes("UTF8"); // 19 bytes
```
All encodings have a canonical name used in the `java.nio` API, as well as a canonical name used in the `java.io` and `java.lang` APIs. [Here is a full list of all supported encodings in Java.](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html) So always use the shortest of the two; the second is usually shorter (like `UTF-8` vs `utf8`, `Windows-1252` vs `Cp1252`, etc.), but not always (`UTF-16BE` vs `UnicodeBigUnmarked`).
### Random boolean:
```
// You could do something like this:
new java.util.Random().nextBoolean() // 36 bytes
// But as mentioned before in @Geobits' answer, Math.random() doesn't require an import:
Math.random()<.5 // 16 bytes
```
### Primes:
There are a lot of different ways to check for primes or get all primes. [@SaraJ's answer here](https://codegolf.stackexchange.com/a/181611/52210) is the shortest for positive integers (\$\geq1\$), and *@primo*'s method is the shortest for integers \$\geq2\$.
```
// Check if n (≥ 1) is a prime (@SaraJ's method):
n->{int i=1;for(;n%++i%n>0;);return n==i;}
// Check if n (≥ 2) is a prime (@primo's method):
n->{int i=n;for(;n%--i>0;);return i<2;}
```
These prime checks can be modified to loop over primes. Here doing so with *@SaraJ*'s approach for example:
```
v->{for(int n=2,i;;){for(i=1;n%++i%n>0;);if(n++==i)/*do something with prime `i` here*/;}}
```
NOTE: Usually you can merge it with other existing loops depending on how you want to use it, so you won't need a separate method. This saved a lot of bytes in [this answer](https://codegolf.stackexchange.com/a/128774/52210) for example.
### Integer truncation instead of Math.floor/Math.ceil:
If you are using ***positive*** doubles/floats and you want to `floor` them, don't use `Math.floor` but use an `(int)`-cast instead (since Java truncates on integers):
```
double d = 54.99;
int n=(int)Math.floor(d); // 25 bytes
int m=(int)d; // 13 bytes
// Outputs 54 for both
```
The same trick can be applied to ***negative*** doubles/floats you want to `ceil` instead:
```
double d = -54.99;
int n=(int)Math.ceil(d); // 24 bytes
int m=(int)d; // 13 bytes
// Outputs -54 for both
```
### Use `&1` instead of `%2` to get rid of parenthesis:
Because the [Operator Precedence](http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html) of `&` is lower than default arithmetic operators like `*/+-` and `%`, you can get rid of parenthesis in some cases.
```
// So instead of this:
(i+j)%2 // 7 bytes
// Use this:
i+j&1 // 5 bytes
```
Note that this doesn't really help in boolean-checks, because then you'd still need parenthesis, they're just moved a bit:
```
(i+j)%2<1 // 9 bytes
(i+j&1)<1 // 9 bytes
```
### BigIntegers and creating variables for static method calls:
When using BigIntegers, only create it once which you can then re-use. As you may know, BigInteger contains static fields for `ZERO`, `ONE` and `TEN`. So when you only use those three, you don't need an `import` but can use `java.Math.BigInteger` directly.
```
// So instead of this:
import java.math.BigInteger.*;
BigInteger a=BigInteger.ONE,b=BigInteger.ZERO; // 76 bytes
// or this:
java.math.BigInteger a=java.math.BigInteger.ONE,b=a.ZERO; // 57 bytes
// Use this:
java.math.BigInteger t=null,a=t.ONE,b=t.ZERO; // 45 bytes
```
NOTE: You have to use `=null` so `t` is initialized in order to use `t.`.
Sometimes you can add multiple BigIntegers to create another to save bytes. So let's say you want to have the BigIntegers `1,10,12` for some reason:
```
// So instead of this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=new BigInteger(12); // 55 bytes
// Use this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=b.add(a).add(a); // 52 bytes
```
As correctly pointed out in the comments, the trick with `BigInteger t=null;` for it's static method calls can also be used with other classes.
For example, [this answer](https://codegolf.stackexchange.com/a/1525/52210) from 2011 can be golfed:
```
// 173 bytes:
import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}
// 163 bytes
class g{public static void main(String[]p){java.util.Arrays x=null;String[]a=p[0].split(""),b=p[1].split("");x.sort(a);x.sort(b);System.out.print(x.equals(a,b));}}
```
### `getBytes()` instead of `toCharArray()`
When you want to loop over the characters of a String, you'll usually do this:
```
for(char c:s.toCharArray()) // 27 bytes
// or this:
for(String c:s.split("")) // 25 bytes
```
Looping over the characters can be useful when printing them, or appending them to a String, or something similar.
However, if you only use the chars for some unicode-number calculations, you can replace the `char` with `int`, AND you can replace `toCharArray()` with `getBytes()`:
```
for(int c:s.getBytes()) // 23 bytes
```
Or even shorter in Java 8+:
```
s.chars().forEach(c->...) // 22 bytes
```
In Java 10+ looping over the character to print can now also be done in 22 bytes:
```
for(var c:s.split("")) // 22 bytes
```
### Random item from a `List`:
```
List l=...;
// When we have an `import java.util.*;` in our code, shuffling is shortest:
return l.get(new Random().nextInt(l.size())); // 45 bytes
return l.get((int)(Math.random()*l.size())); // 44 bytes
Collections.shuffle(l);return l.get(0); // 39 bytes
// When we don't have an `import java.util.*` in our code, `Math.random` is shortest:
return l.get(new java.util.Random().nextInt(l.size())); // 55 bytes
return l.get((int)(Math.random()*l.size())); // 44 bytes
java.util.Collections.shuffle(l);return l.get(0); // 49 bytes
```
### Check if a String contains leading/trailing spaces
```
String s=...;
// I used to use a regex like this:
s.matches(" .*|.* ") // 20 bytes
// But this is shorter:
!s.trim().equals(s) // 19 bytes
// And this is even shorter due to a nice feature of String#trim:
s!=s.trim() // 11 bytes
```
Why does this work, when `!=` on Strings is to check for reference instead of value in Java? Because [`String#trim`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()) will return "*A copy of this string with leading and trailing white space removed, or **this string if it has no leading or trailing white space**.*" I've used this, after someone suggested this to me, in [this answer of mine](https://codegolf.stackexchange.com/a/143387/52210).
### Palindrome:
To check if a String is a palindrome (keeping in mind both even and odd lengths of Strings), this is the shortest (`.contains` works here because we know both the String itself and its reversed form are of equal length):
```
String s=...;
s.contains(new StringBuffer(s).reverse()) // 41 bytes
```
`.contains(...)` instead of `.equals(...+"")` thanks to [*@assylias*'s comment here](https://codegolf.stackexchange.com/questions/153249/list-all-palindromic-prime-dates-between-0000-01-01-and-99999-12-31/153255#comment374815_153255).
### Either is 0, or both are 0?
I think most already know this one: if you want to check if either `a` or `b` is zero, multiply instead to save bytes:
```
a==0|b==0 // 9 bytes
a*b==0 // 6 bytes
```
And if you want to check if both `a` and `b` are zero, you could use a bitwise-OR, or add them together if they are always positive:
```
a==0&b==0 // 9 bytes
(a|b)==0 // 8 bytes (if either `a`, `b` or both can be negative)
a+b<1 // 5 bytes (this only works if neither `a` nor `b` can be negative)
```
### Even = 1, odd = -1; or vice-versa
```
// even = 1; odd = -1:
n%2<1?1:-1 // 10 bytes
1-n%2*2 // 7 bytes
// even = -1; odd = 1:
n%2<1?-1:1 // 10 bytes
n%2*2-1 // 7 bytes
```
The reason I add this was after seeing `k+(k%2<1?1:-1)` in [this answer](https://codegolf.stackexchange.com/a/64269/52210):
```
k+(k%2<1?1:-1) // 14 bytes
// This would already have been shorter:
k%2<1?k+1:k-1 // 13 bytes
// But it can also be:
k%2*-2-~k // 9 bytes
```
### Loop `n` times in Full Program
If we have a challenge where a full program is mandatory, and we need to loop a specific amount of times, we can do the following:
```
// instead of:
interface M{static void main(String[]a){for(int n=50;n-->0;)/*do something*/}} // 78 bytes
// we could do:
interface M{static void main(String[]a){for(M m:new M[50])/*do something*/}} // 76 bytes
```
The same applies when we have to take this range as input:
```
interface M{static void main(String[]a){for(int n=new Byte(a[0]);n-->0;)/*do something*/}} // 90 bytes
interface M{static void main(String[]a){for(M m:new M[new Byte(a[0])])/*do something*/}} // 88 bytes
```
Credit to [*@JackAmmo* in this comment](https://codegolf.stackexchange.com/questions/67921/what-is-the-smallest-positive-base-10-integer-that-can-be-printed-by-a-program-s#comment165935_67983).
### try-finally instead of try-catch(Exception e), and when/how to use it
If you have to catch and ignore an Exception, in most cases it's shorter to use `finally{...;}` instead of `catch(Exception){}`. Some examples:
When you want to return the result as soon as you hit an error:
```
try{...}catch(Exception e){return ...;} // 33 bytes
try{...}finally{return ...;} // 22 bytes
```
I've used this initially to save bytes in [this answer of mine](https://codegolf.stackexchange.com/a/153993/52210) (credit for the indirect golf goes to *@KamilDrakari*). In this challenge we have to loop diagonally over an NxM matrix, so we have to determine whether the amount of columns or amount of rows is the lowest as our maximum in the for-loop (which is quite expensive in terms of bytes: `i<Math.min(a.length,a[0].length)`). So, simply catching the `ArrayIndexOutOfBoundsException` using `catch-finally` is shorter than this check, and thus saves bytes:
```
int[] a = ...;
int r=0,i=0;for(;i<Math.min(a.length,a[0].length);)r=...i++...;return r; // 66 bytes
int r=0,i=0;try{for(;;)r=...i++...;}finally{return r;} // 48 bytes
```
This also works with a void `return;`, like this:
```
try{...}catch(Exception e){} // 25 bytes
try{...}finally{return;} // 21 bytes
```
Which actually saved an additional byte in that same linked answer above by putting the answer in the very first cell, like [*@KamilDrakari* does in his C# answer](https://codegolf.stackexchange.com/a/154011/52210) as well:
```
m->{try{for(...);}finally{return;}}
```
But what about a try-catch where you don't want to immediately return? Unfortunately, you can't have a completely empty `finally{}` block as alternative to catch an Exception. You can however still use it inside a loop by using `continue` (or `break`) as alternatives. Here an example where we want to continue with the next iteration of the loop when an Exception occurs:
```
for(...)try{...}catch(Exception e){} // 30 bytes
for(...)try{...}finally{continue;} // 28 bytes
```
I've used this approach in [this answer of mine](https://codegolf.stackexchange.com/a/154563/52210) to save 2 bytes.
So when you can use a `return`, `continue` or `break`, it's always better to use `try{...}finally{...;}` instead of `try{...}catch(Exception e){}`. And in most cases, especially when checking boundaries of matrices, it's shorter to `try-finally` any `ArrayIndexOutOfBoundsExceptions`, instead of doing manual checks to see whether the indices are still in bounds.
### Math.pow(2,n)
When you want a power of 2, a bit-wise approach is much shorter:
```
(int)Math.pow(2,n) // 16 bytes
(1<<n) // 6 bytes
```
### Combining bit-wise and logical checks instead of using parenthesis
I think it is well-known by now that `&` and `|` can be used instead of `&&` and `||` in Java (boolean) logical checks. In some cases you'd still want to use `&&` instead of `&` to prevent errors though, like `index >= 0 && array[index].doSomething`. If the `&&` would be changed to `&` here, it will still evaluate the part where it uses the index in the array, causing an `ArrayIndexOutOfBoundsException`, hence the use of `&&` in this case instead of `&`.
So far the basics of `&&`/`||` vs `&`/`|` in Java.
When you want to check `(A or B) and C`, the shortest might seem to use the bit-wise operators like this:
```
(A|B)&C // 7 bytes
```
However, because the bit-wise operators have [operator precedence](https://introcs.cs.princeton.edu/java/11precedence/) over the logical checks, you can combine both to save a byte here:
```
A|B&&C // 6 bytes
```
### Use `n+=...-n` instead of `(long)...`
When you have a long as both in and output in a lambda, for example when using `Math.pow`, you can save a byte by using `n+=...-n` instead of `(long)...`.
For example:
```
n->(long)Math.pow(10,n) // 23 bytes
n->n+=Math.pow(10,n)-n // 22 bytes
```
This saved a byte in [this answer of mine](https://codegolf.stackexchange.com/questions/161281/make-an-emergency-corridor/161346#161346), and even two bytes by combining `-n-1` to `+~n` in [this answer of mine](https://codegolf.stackexchange.com/questions/163737/return-the-highest-possible-placement-value-based-on-the-input/163783#163783).
[Answer]
If you need `Integer.MAX_VALUE` (2147483647), use `-1>>>1`. `Integer.MIN_VALUE` (-2147483648) is better written `1<<31`.
[Answer]
Don't use `public class`. The main method needs to be public, but its class doesn't. This code works:
```
class S{public static void main(String[]a){System.out.println("works");}}
```
You may run `java S` even though `class S` is not a public class. (*Update:* I was using Java 7 when I wrote this tip. In Java 8, [your main method should be in an interface](https://codegolf.stackexchange.com/a/64713/4065). In Java 5 or 6, [your main method should be in an enum](https://codegolf.stackexchange.com/a/140181/4065).)
Plenty of Java programmers don't know this! About half the answers to [a Stack Overflow question about main in non-public class](https://stackoverflow.com/q/12524322/3614563) wrongly claim that the main method must be in a public class. Now you know better. Delete the `public` in `public class` and save 7 characters.
[Answer]
You don't have to use `Character.toLowerCase(char c)`. Instead use `(c|32)`. Instead of `Character.toUpperCase(char c)` use `(c&95)`. This only works with ASCII letters.
[Answer]
If you need to grab *a number* from an argument (or any other string), normally you see something like:
```
public static void main(String[]a){
int n=Integer.valueOf(a[0]);
...
}
```
Many times, you don't *need* an `Integer`. Plenty of challenges don't use large numbers. Since `Short` and `Byte` will both unbox to an `int`, use the more appropriate `valueOf()` instead and save a couple bytes.
Keep your actual *variable* as an `int`, though, since it's shorter than both `byte` and `short`:
```
int n=Byte.valueOf(a[0]);
```
If you need to do this for multiple numbers, you can combine with [this method](https://codegolf.stackexchange.com/a/16089/14215):
```
Byte b=1;
int n=b.valueOf(a[0]),m=b.valueOf(a[1])...
```
[Answer]
# Convert String to number
There are multiple ways to convert a String to an numeric value:
```
String s = "12";
```
*ABC.parseABC*:
```
Short.parseShort(s); // 20 bytes
Integer.parseInt(s); // 20 bytes
Long.parseLong(s); // 18 bytes
```
*ABC.valueOf*:
```
Short.valueOf(s); // 17 bytes
Integer.valueOf(s); // 19 bytes
Long.valueOf(s); // 16 bytes
```
*ABC.decode*:
```
// Note: does not work for numeric values with leading zeros,
// since these will be converted to octal numbers instead
Short.decode(s); // 16 bytes
Integer.decode(s); // 18 bytes
Long.decode(s); // 15 bytes
```
*new ABC*:
```
new Short(s); // 13 bytes
new Integer(s); // 15 bytes
new Long(s); // 12 bytes
```
So, for code-golfing, it's best to use the constructor when converting a String to a numeric value.
The same applies to `Double`; `Float`; and `Byte`.
---
This doesn't always apply when you can re-use an already present primitive as object.
As example, let's say we have the following code:
```
// NOTE: Pretty bad example, because changing the short to int would probably be shorter..
// but it's just an example to get the point across
short f(short i,String s){
short r=new Short(s); // 21 bytes
... // Do something with both shorts
}
```
You can use `.decode` instead of the shorter constructor by re-using the parameter as object:
```
short f(Short i,String s){ // Note the short parameter has changed to Short here
short r=i.decode(s); // 20 bytes
... // Do something with both shorts
}
```
[Answer]
For golfing that doesn't require input, you can use static blocks, and run it just fine without any main method, just compile it with Java 6.
```
public class StaticExample{
static {
//do stuff
}
}
```
[Answer]
We all know about the bitwise xor (`^`), but it is also a logical xor.
So `(a||b)&&!(a&&b)` simply becomes `a^b`.
Now we can use xor.
[Additionally](https://codegolf.stackexchange.com/questions/6671/tips-for-golfing-in-java#comment56317_25950 "Thanks to Geobits"), the operators `|` and `&` [also work](http://ideone.com/rG4XIq), just remember that operator precedence changes.
[Answer]
# Don't be afraid to use scientific notation
If you are dealing with doubles, or floats, you can use scientific notation for numbers. So instead of writing `double a=1000` you can change it to `double a=1e3` to save 1 byte.
[Answer]
**Don't use `Random`!**
*In general,* if you need random numbers, [`Random`](http://docs.oracle.com/javase/8/docs/api/java/util/Random.html) is a horrible way to go about it\*. Much better to use [`Math.random()`](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--) instead. To use `Random`, you need to do this (let's say we need an `int`):
```
import java.util.*;
Random r=new Random();
a=r.nextInt(9);
b=r.nextInt(9);
```
Compare that to:
```
a=(int)(Math.random()*9);
b=(int)(Math.random()*9);
```
and:
```
int r(int m){return(int)(Math.random()*m);}
a=r(9);
b=r(9);
```
The first method takes `41+15n` characters (`n` is number of calls).
The second is `25n` characters, and the third is `43+7n`.
So, if you only need it once or twice, use the inline `Math.random()` method. For three or more calls, you'll save by using a function. Either one saves characters on the *first use* over `Random`.
---
If you're already using `Math.random()` for `double`, remember that at four uses, it's still a savings to pull it out into:
```
double r(){return Math.random();}
```
For 33 characters, you'll save 10 on each call to `r()`
---
**Update**
If you need an integer and want to save on casting, *don't cast it!* Java auto-casts if you do an operation instead of an assignment. Compare:
```
a=(int)(Math.random()*9);
a=9;a*=Math.random();
```
\* *Unless you have to seed the PRNG for predictable results. Then, I don't see much of a way around it.*
[Answer]
# Try using `int` instead of `boolean`
In some cases I've found that it's shorter to return an integer value from a method that would normally return a boolean, similarly to what might be done in C programs.
Right off the bat `int` is 4 bytes shorter than `boolean`. Each time you write `return 0` instead of `return 1<0`, you save an additional 2 bytes and the same for `return 1` over `return 1>0`.
The pitfall here is that each time you want to use the return value directly as a boolean, it costs 2 bytes (`if(p(n))` v. `if(p(n)>0)`). This can be made up for by use of boolean arithmetic. Given a contrived scenario where you want to write
```
void a(int[]t){t[0]+=p(n)?10:0;}
```
you can instead write
```
void a(int[]t){t[0]+=p(n)*10;}
```
in order to save 2 bytes.
[Answer]
If you use **enum instead of class**, you save one character.
```
enum NoClass {
F, G, H;
public static void main (String[] args) {
}
}
```
But you have to introduce at least one enum instance (F, G, H in this example) which have to payoff themselves.
[Answer]
I don't know if you would consider this 'pure' Java, but [Processing](http://www.processing.org) allows you to create programs with little initial setup (completed automatically).
For console output, you can have something as simple as:
```
println("hi"); //done
```
for graphical output, a little more:
```
void setup() {
size(640,480);
}
void draw() {
fill(255,0,0); //color used to fill shapes
rect(50,50,25,25); //25x25 pixel square at x=50,y=50
}
```
[Answer]
## Shortening returning
You can shorten return statements of strings by a byte with:
```
return "something";
```
to
```
return"something";
```
And, if you happen to begin your return statement with a parenthesis, you can do the same thing with them:
```
return (1+taxRate)*value;
```
to
```
return(1+taxRate)*value;
```
I guess quotes are considered like parentheticals? I actually picked this up through AppleScript, funnily enough, and thought it might be worth mentioning.
[Answer]
# Use Java 10's `var`
If you define a single variable of a specific type, use `var`.
### Examples
```
var i=0; // int
var l=0L; // long
var s=""; // String
var a=new int[]{1,2,3}; // int[]
var i=java.math.BigInteger.ONE; // BigInteger
var m=new java.util.HashMap(); // HashMap
var i=3+"abc".length() // int
var a="a b c".split(" "); // String[]
for(var a:"a b c".split(" ")) // String
```
### Not usable in any of the following examples
`var` cannot be used in many examples
```
var i=1,j=2; // only one variable is accepted at a time
var a={1,2,3}; // arrays must be explicitly declared
var f=a->a+" "; // can't know what type a is.
var f=String::replace; // method references aren't properly inferred (weirdly, though)
```
[Answer]
# Avoid `StringBuilder`s
Appending stuff to a `String` takes up much fewer bytes.
```
// s is a StringBuilder
s.append("Hello, World!");
// S is a String
S+="Hello, World!";
```
If you have to reverse a string and print it right away, use a `StringBuffer`.
```
System.out.print(new StringBuilder("Hello, World!").reverse());
System.out.print(new StringBuffer("Hello, World!").reverse()); // Note that you can omit toString() when printing a non-String object
```
If you have to reverse a string and then do something else than printing it, use a `for`each loop.
```
String b=new StringBuffer("Hello, World!").reverse().toString();
String B="";for(String c:"Hello, World!".split(""))B=c+B;
```
[Answer]
# Use `new Stack()` when you need basic `List` functionality
When you need a `java.util.List` (for example when you want to `.add(Object)`, `.remove(Object)`, `java.util.Collections.shuffle(java.util.Collection)`, etc.), I used to use `java.util.ArrayList` in most of my answers. But I was recently tipped to use `java.util.Vector` instead, and `java.util.Stack` is even shorter:
```
import java.util.*;
List a=new ArrayList(); // 23 bytes
List b=new Vector(); // 20 bytes
List c=new Stack(); // 19 bytes
```
[Answer]
# Shortest full program templates.
### Introduction
The [Java spec](https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html) never ever say that a full program must contain a `main` method. It only says:
>
> The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.
>
>
>
So to the best of our efforts, we can define a Java program as something which when invoked in this way will provide an output:
```
$ javac A.java
$ java A
```
All the following templates do that.
### Java 8 (42 bytes)
```
interface A{static void main(String[]a){/* Your code here */}}
```
### Java 7 (45 bytes)
```
class A{public static void main(String[]a){/* Your code here */}}
```
### Java 5, 6 (12 or 27 bytes)
```
enum A{A;{/* Your code here */}}
```
This code above **will** write something on `stderr`. Usually something like `java.lang.NoSuchMethodError: main\nException in thread "main"`. If you can write on `stderr` after execution, use this!
```
enum A{A;{/* Your code here */System.exit(0);}}
```
This code above is longer (27 bytes), but it **will** execute your code **and** avoid writing anything on `stderr`.
### Conclusion
1. Don't ever use Java 7.
2. If your program can be written in Java 5 or 6, use it. If your program can be written in Java 5 or 6, but is longer than a Java 8 version, always check if it could be shorter to write it in Java 5 or 6.
[Answer]
When you have a method that should return a `boolean` or `Boolean`, i.e.:
```
// Return true if the (non-negative) input is dividable by 5
boolean c(int i){return i%5<1;}
```
You can change the `boolean`/`Boolean` return-type to `Object` to save 1 byte:
```
Object c(int i){return i%5<1;}
```
---
In addition, as you may have noticed, you can use a `<1` check instead of `==0` to save a byte. Although that is more a general code-golf tip instead of Java-specific.
This is mostly used when the integer can't be negative, like checking for length:
```
a.length<1
```
instead of
```
a.length==0
```
[Answer]
# How to Draw in Java...
Here's the shortest possible GUI paint boiler-plate:
```
import java.awt.*;
static void main(String[]x){
new Frame(){
public void paint(Graphics g){
// Draw your stuff here.
}
}.show();
}
```
# Golfed for 111 Bytes:
```
import java.awt.*;static void main(String[]x){new Frame(){public void paint(Graphics g){/*CodeHere*/}}.show();}
```
[Answer]
Using Java Applet can save you a lot of space:
```
import java.applet.Applet;
public class B extends Applet{
public B(){
System.out.print("Hello world!");
}
}
```
**Output:**
>
> Hello world!
>
>
>
Also this can be even more shorten by making `B` to extends nothing.
```
public class B{
public B(){
System.out.print("Hello world!");
}
}
```
How ever in additional to desired output we will also get exception:
**Output:**
>
> Hello world!
>
> java.lang.ClassCastException: B cannot be cast to
> java.applet.Applet
>
> at sun.applet.AppletPanel.createApplet(Unknown Source)
>
> at sun.applet.AppletPanel.runLoader(Unknown Source)
>
> at sun.applet.AppletPanel.run(Unknown Source)
>
> at java.lang.Thread.run(Unknown Source)
>
>
>
Also you can combine this with constructor block and save another 10 bytes like this:
```
public class B{
{
System.out.println("Hello world!");
}
}
```
Same output with exception as above.
] |
[Question]
[
One nice property of a Turing-complete language is that it can be used to write any program, up to and including the simulation of the entire Universe.
Your job is to do exactly that: **write a program which simulates the Universe**.
---
Note: although I don't doubt you'll be able to accomplish this task, nowadays I don't have enough spare time to verify whether all 1090 of the particles in your simulation do what they really should do. Therefore, solely to simplify testing and evaluation, it is enough if your universe simulator only works with a single starting particle. To keep things interesting, let's assume this particle is the recently discovered Higgs Boson.
Your universe starts with nothing but a single Higgs Boson of approximately 120 GeV in the middle of it. To not make the output too long, let's make this universe tick at only 10-25 seconds instead of its "usual clock rate" of 5.4×10−44 seconds..
This Higgs boson will decay sooner or later as it has a half-life of 1.6×10−22 seconds, so at every tick of the simulation, it has a 0.0433% chance of decaying. You can check [here what it will decay into](http://arxiv.org/pdf/1107.5909.pdf). To have a central and simplified requirement, I list the branching ratios you should use:
# Running the simulation
At each tick of the simulation, the Higgs boson has a 0.0433% chance of decaying. If that happens, it will decay into the following particles, with the listed probabilities (you should use these names in the output):
* bottom quark + bottom antiquark (64.8%)
* 2 W bosons (14.1%)
* 2 gluons (8.82%)
* tau lepton + antitau lepton (7.04%)
* charm quark + charm antiquark (3.27%)
* 2 Z bosons (1.59%)
* 2 photons (0.223%)
* 1 Z boson + 1 photon (0.111%)
* muon + antimuon (0.0244%)
* top quark + top antiquark (0.0216%)
For a total of 100%.
Some of these particles will decay further.
**W boson**: half-life of 10-25 seconds, this means a 50% chance to decay at every tick into one of the following, with equal probabilities:
* positron + neutrino
* antimuon + neutrino
* antitau lepton + neutrino
**Z boson**: half-life of 10-25 seconds, this means a 50% chance to decay at every tick into one of the following:
* neutrino + antineutrino (20.6%)
* electron + positron (3.4%)
* muon + antimuon (3.4%)
* tau lepton + antitau lepton (3.4%)
* down quark + down antiquark (15.2%)
* strange quark + strange antiquark (15.2%)
* bottom quark + bottom antiquark (15.2%)
* up quark + up antiquark (11.8%)
* charm quark + charm antiquark (11.8%)
**top quark**: half-life of 5×10-25 seconds, this means a 12.95% chance to decay at every tick into the following, with equal probabilities:
* W boson + down quark
* W boson + strange quark
* W boson + bottom quark
Of course, the W boson will also soon decay...
The **top antiquark** behaves similarly to the top quark: it decay into a W boson and a d/s/b antiquark.
**All other particles** (so all except for the Z and W bosons and top quarks) have a half life many orders of magnitude longer, so to not clutter the output, they **are all considered stable for our simulation**.
As the universe is largely empty, all the particles will have enough space for themselves and will not interact with each other. Therefore all individual particles are independent from each other in every regard, including the probabilities of splitting.
# Output:
Every tick of the simulation, you have to print the contents of the simulated universe into a new line. For example:
```
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 2 W bosons.
The universe contains 2 W bosons.
The universe contains 1 W boson, 1 positron and 1 neutrino.
The universe contains 1 positron, 1 antitau lepton and 2 neutrinos.
Simulation ended after 0.8 yoctoseconds.
```
The order of the particles in the line is not important. The formatting, however, **must be exactly as in the example above**, including punctuation and pluralization. If you simulate an entire (mini-) universe, it should look nice (And I wanted to eliminate the abusing of a not sufficiently strict output requirement)
Each line corresponds to 0.1 yoctoseconds, but you will be forgiven if it takes longer than that for your program to print the output.
The simulation ends when only "stable" particles remain.
# Scoring
Standard code golf rules apply.
The random number generator can be pseudo-random, but you must seed it if the language doesn't seed it by default. The probability distribution of your RNG must be uniform.
* You will get a bonus -10% to the code size if the program takes an integer as an input, and starts with that many Higgs bosons.
# Exception for Turing machine enthusiasts.
For those who dare to try their luck with an *actual* Turing machine or a similar language (like Brainfuck), their task is made easier by the following rule changes *(only applicable if the language is a Brainfuck-derivative or otherwise a very simplified Turing-machine, incapable of assignment, lacking an ALU, and values on the tape can only be incremented and decremented by one)*:
* The particle names are simplified to d, s, b, t, u, c for the quarks, v for the neutrino, T for tau lepton, m for muon, g for gluon, p for photon, Z, W and H for the bosons, - for the electron and + for the positron. At each tick, an input with the value of 0 or 1 are provided from the standard input, indicated whether the first unstable particle in the list decays or not.
The example output will therefore become
```
H
H
H
H
W W
W W
W + n
+ !T n n
```
[Answer]
## C++ (~~2420~~,~~2243~~,~~2353~~,~~1860~~,1822\*.9=1639.8)
Ok, so this is probably the worst ever code golf submission, but it's my first and I had fun. I think it even works. :)
```
#include <iostream>
#include <list>
#include <string>
#include <time.h>
#define D r=rand();d=((double)r/RAND_MAX)
using namespace std;class P{int n[25];public:int S;P(int N){for(S=0;S<24;S++)n[S]=0;n[24]=N;S=1;}void C(){string s[25]={"down quark","down antiquark","up quark","up antiquark","bottom quark","bottom antiquark","tau lepton","antitau lepton","charm quark","charm antiquark","strange quark","strange antiquark","neutrino","antineutrino","muon","antimuon","gluon","photon","electron","positron","top quark","top antiquark","Z boson","W boson","Higgs boson"};int r,i,j,w,f,F,x,y;double d;S=0;F=0;for(i=0;i<25;i++){w=0;for(j=0;j<n[i];j++){D;x=-1;y=-1;if(i==24){if(d<.000433){D;if(d<.648){x=4;y=5;}else if(d<.789){x=23;y=23;}else if(d<.8772){x=16;y=16;}else if(d<.9476){x=6;y=7;}else if(d<.9803){x=8;y=9;}else if(d<.9962){x=22;y=22;}else if(d<.99843){x=17;y=17;}else if(d<.99954){x=22;y=17;}else if(d<.999784){x=14;y=16;}else{x=21;y=20;}}}else if(i==23){if(d<.5){D;if(d<.33){x=19;y=12;}else if(d<.67){x=16;y=12;}else{x=17;y=12;}}}else if(i==22){if(d<.5){D;if(d<.206){x=12;y=13;}else if(d<.24){x=18;y=19;}else if(d<.274){x=14;y=16;}else if(d<.308){x=16;y=17;}else if(d<.46){x=0;y=1;}else if(d<.612){x=10;y=11;}else if(d<.764){x=4;y=5;}else if(d<.882){x=2;y=3;}else{x=8;y=9;}}}else if(i==21||i==20){if(d<.1295){D;x=23;if(d<.33){y=0;}else if(d<.67){y=10;}else{y=4;}if(i==21)y-=32;}}if(x>=0){++n[x];++n[y];w++;}if(x>19||y>19)S=1;}n[i]-=w;if(n[i]>0){F=i;if(i>19)S=1;}}cout<<"The universe contains";f=0;for(i=0;i<25;i++){if(n[i]>0){cout<<(f>0?(i<F?", ":" and "):" ")<<n[i]<<' '<<s[i]<<(n[i]>1?"s":"");f=1;}}cout<<'.'<<endl;}};int main(int c,char* v[]){int w=1,y=0;if(c>1){w=atoi(v[1]);}srand(time(0));rand();P p=P(w);int Time=time(0);while(p.S){p.C();y++;}cout<<"Simulation ended after "<<(double)y/10<<" yoctoseconds.";}
```
## Fast Version
This one isn't as short (9 extra bytes), but it runs *way* faster for testing huge numbers. Since it's not short enough to compete, I also added a little code to clock real-world execution time and print it right after simulated time. My original version did n=100k in about 8 minutes. The version above does it in about 2 minutes. This fast version can do it in 9 seconds. n=1 million took 53 seconds.
```
#include <iostream>
#include <list>
#include <string>
#include <time.h>
#define D r=rand();d=((double)r/RAND_MAX)
using namespace std;class P{int n[25];public:int S;P(int N){for(S=0;S<24;S++)n[S]=0;n[24]=N;S=1;}void C(){string s[25]={"down quark","down antiquark","up quark","up antiquark","bottom quark","bottom antiquark","tau lepton","antitau lepton","charm quark","charm antiquark","strange quark","strange antiquark","neutrino","antineutrino","muon","antimuon","gluon","photon","electron","positron","top quark","top antiquark","Z boson","W boson","Higgs boson"};int r,i,j,w,f,F,x,y;double d;S=0;F=0;for(i=20;i<25;i++){w=0;for(j=0;j<n[i];j++){D;x=-1;y=-1;if(i==24){if(d<.000433){D;if(d<.648){x=4;y=5;}else if(d<.789){x=23;y=23;}else if(d<.8772){x=16;y=16;}else if(d<.9476){x=6;y=7;}else if(d<.9803){x=8;y=9;}else if(d<.9962){x=22;y=22;}else if(d<.99843){x=17;y=17;}else if(d<.99954){x=22;y=17;}else if(d<.999784){x=14;y=16;}else{x=21;y=20;}}}else if(i==23){if(d<.5){D;if(d<.33){x=19;y=12;}else if(d<.67){x=16;y=12;}else{x=17;y=12;}}}else if(i==22){if(d<.5){D;if(d<.206){x=12;y=13;}else if(d<.24){x=18;y=19;}else if(d<.274){x=14;y=16;}else if(d<.308){x=16;y=17;}else if(d<.46){x=0;y=1;}else if(d<.612){x=10;y=11;}else if(d<.764){x=4;y=5;}else if(d<.882){x=2;y=3;}else{x=8;y=9;}}}else if(i==21||i==20){if(d<.1295){D;x=23;if(d<.33){y=0;}else if(d<.67){y=10;}else{y=4;}if(i==21)y-=32;}}if(x>=0){++n[x];++n[y];w++;}if(x>19||y>19)S=1;}n[i]-=w;if(n[i]>0&&i>19)S=1;}for(i=0;i<25;i++){if(n[i]>0)F=i;}cout<<"The universe contains";f=0;for(i=0;i<25;i++){if(n[i]>0){cout<<(f>0?(i<F?", ":" and "):" ")<<n[i]<<' '<<s[i]<<(n[i]>1?"s":"");f=1;}}cout<<'.'<<endl;}};int main(int c,char* v[]){int w=1,y=0;if(c>1){w=atoi(v[1]);}srand(time(0));rand();P p=P(w);int Time=time(0);while(p.S){p.C();y++;}cout<<"Simulation ended after "<<(double)y/10<<" yoctoseconds.";cout<<endl<<"Time Taken: "<<(time(0)-Time)<<" seconds."<<endl;}
```
## Sample output (no args)
```
The universe contains 1 Higgs boson.
... (many lines later)
The universe contains 1 Higgs boson.
The universe contains 1 bottom quark and 1 bottom antiquark.
Simulation ended after 339.4 yoctoseconds.
```
## Sample output (universe.exe 10):
```
The universe contains 10 Higgs bosons.
The universe contains 1 bottom quark, 1 bottom antiquark and 9 Higgs bosons.
The universe contains 2 bottom quarks, 2 bottom antiquarks and 8 Higgs bosons.
The universe contains 3 bottom quarks, 3 bottom antiquarks and 7 Higgs bosons.
The universe contains 4 bottom quarks, 4 bottom antiquarks and 6 Higgs bosons.
The universe contains 4 bottom quarks, 4 bottom antiquarks, 1 charm quark, 1 charm antiquark and 5 Higgs bosons.
The universe contains 5 bottom quarks, 5 bottom antiquarks, 1 charm quark, 1 charm antiquark and 4 Higgs bosons.
The universe contains 5 bottom quarks, 5 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 Z bosons and 3 Higgs bosons.
The universe contains 5 bottom quarks, 5 bottom antiquarks, 1 charm quark, 1 charm antiquark, 1 neutrino, 1 antineutrino, 1 Z boson and 3 Higgs bosons.
The universe contains 5 bottom quarks, 5 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 neutrinos, 2 antineutrinos and 3 Higgs bosons.
The universe contains 6 bottom quarks, 6 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 neutrinos, 2 antineutrinos and 2 Higgs bosons.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 neutrinos, 2 antineutrinos and 1 Higgs boson.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 neutrinos, 2 antineutrinos and 2 W bosons.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 1 charm quark, 1 charm antiquark, 2 neutrinos, 2 antineutrinos and 2 W bosons.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 1 charm quark, 1 charm antiquark, 3 neutrinos, 2 antineutrinos, 1 photon and 1 W boson.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 1 charm quark, 1 charm antiquark, 4 neutrinos, 2 antineutrinos, 1 gluon and 1 photon.
Simulation ended after 1160.5 yoctoseconds.
```
## Sample Output (universe.exe 1000000)
(not quite 10^90, but we're getting there)
```
(about a minute, 14 MB and 33000 lines of output later)
The universe contains 5006 down quarks, 4945 down antiquarks, 3858 up quarks, 3858 up antiquarks, 653289 bottom quarks, 653190 bottom antiquarks, 70388 tau leptons, 70388 antitau leptons, 36449 charm quarks, 36449 charm antiquarks, 4956 strange quarks, 4873 strange antiquarks, 289364 neutrinos, 6764 antineutrinos, 1401 muons, 275514 gluons, 99433 photons, 1065 electrons and 94219 positrons.
Simulation ended after 3299.9 yoctoseconds.
```
## Larger Outputs
If you're using console output from a command line, I would suggest something like `universe.exe 100 > temp.txt` so it will go *much* faster. With Notepad++, you can then open temp.txt, hit `ctrl+H`, enter `^(.*?)$\s+?^(?=.*^\1$)` into the *Find What* field, enter nothing in the *Replace With* field, turn *Search Mode* to `Regular Expression`, turn *In selection* and *. matches newline* `OFF`, then hit `Replace All`. Now you just see where the changes occurred instead of 8000 lines of output (I do seem to get bugs doing more than 2000-3000 lines at a time though).
## Fixes/Tweaks
```
v4 - complete overhaul, removed list, one character array, moved almost everything into the class functions. Fixed output error, was using "," instead of "and" for last item. Sped up execution a *lot* as an added bonus. :)
v3 - more fixes
v2 - more shorter
v1 - fixed numerous little issues, bug fixes
v0 - baseline
```
[Answer]
# Python 3, 1,247 \* 0.9 = 1,122.3
Well, this is my longest entry by a long shot, but at least I'm shorter than C++.
Now with added bonus! It has to be called with a number as the first argument.
My universe didn't work with decaying particles other than Higgs Boson, but now it does. Also, I didn't have pluralization or punctuation correct, but I **actually** do now.
I'm getting so close to sub 1k!
```
import random,sys,numpy as h
H,M,G,N,P,K,L,n,s='photon,muon,gluon,neutrino,positron, quark,tau lepton, boson,The universe '.split(',')
c=random.choice
Z=' anti'+K[1:]
B='bottom'+K
A=B[:6]+Z
U='anti '+M
T=U[:4]+L
Q='charm'+K
C=Q[:5]+Z
S='strange'+K
R=S[:7]+Z
D='down'+K
O=D[:4]+Z
def w(c):v,t=zip(*c);t=h.array(t);return v[h.random.choice(len(v),p=t/t.sum())]
y=M,U
f=lambda p:{z:w([(c([('up'+K,'up'+Z),(Q,C)]),11.8),((N,U[:5]+N),20.6),(c([('electron',P),y,(L,T)]),3.4),(c([(S,R),(B,B),(D,O)]),15.2)]),E:(I,c([D,S,B])),F:(I,c([O,R,A])),I:c([(P,N),(U,N),(T,N)]),J:w([((B,A),64.8),((I,I),14.1),((G,G),8.82),((L,T),7.04),((Q,C),3.27),((z,z),1.59),((H,H),0.223),((z,H),0.111),(y,0.0244),((E,F),0.0246)])}[p]
z='Z'+n,50
E='top'+K,12.95
F='top'+Z,E[1]
I='W'+n,50
J='Higgs'+n,.0433
u=[J]*int(sys.argv[1])
b={z,E,F,I,J}
k=isinstance
d=lambda p:p if k(p,str)else w([(p,100-p[1]),(f(p),p[1])])
a=0
g=lambda x:[x[0],x][k(x,str)]
while b&set(u):
n=[]
for p in u:q=d(p);n+=([q],(q,[q])[q in b])[p in b]
e=list(map(g,n));e=[(x,x+'s')[e.count(x)>1]for x in e];print(s+'contains %s'%', '.join(('%s %s'%(e.count(x),g(x))for x in set(e[:-1])))+('.',' and %s %s.'%(e.count(e[-1]),e[-1]))[len(set(e))>1]);a+=.1;u=n
print(s+'ended after %s yoctoseconds.'%round(a,1))
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), (707 bytes -10%) Score 636.3
With some unneeded line breaks for a bit more readability:
```
{
my%p;
%p=<H H2309.469bB64.8WW14.1gg8.82lL7.04cC3.27ZZ1.59pp0.223Zp0.111mM0.0244tT0.0216 W W3pn1Mn1Ln1 Z Z100nN20.6ep3.4mM3.4lL3.4dD15.2sS15.2bB15.2uU11.8cC11.8 t t7.722Wd1Ws1Wb1 T T7.722WD1WS1WB1>;
my&f=*.comb[0];
my%h;
%h{.&f}="$_ boson" for <Higgs W Z>;
{
%h{.&f}="$_ quark";
%h{.&f.uc}="$_ antiquark"
} for <bottom top charm up down strange>;
%h{.&f}=$_~"on" for <glu phot electr positr>;
%h{.&f.uc}="anti"~(%h{.&f}=$_) for <muon neutrino>;
%h<L>="anti"~(%h<l>="tau lepton");
my$t;
("H"x$^a),{
$t+=.1;
S:g/./{%((%p{$/}||$/~1).comb(/(\D+|<:!L>+)/)).Mix.roll}/
}...{
say "The universe contains {
.comb.Bag.map({
"{.value,%h{.key}~'s'x(.value>1)}"
}).join(', ')
}.";
!/<[HWZtT]>/
};
say "Simulation ended after $t yoctoseconds."
}
```
[Try it online!](https://tio.run/##VZBPc5swEMXv@RQbBsfQZBaEif8Em4OTgw92L3aHGdI0I2MZ04CkgkjjwfiruxB30vTydvZpn35aSZan/VO2v4onpyrbd6TXkZPxDGZOzx6h2x@tp30Xh0FAXCRxPMShk84HaLvRfQ@dQRgSvB1JaaPj9MKmEEKyhY2247pq1VbShwCCnuRkwcmcEwghJLbNvzo29pnsoZstGknnjWweyC06xbLV9bTV8hshOIzuWwUFaoADxwk2JChIsCawgtXZeSDBkgRT4nvNKtvJF4xEtn60n5q2s/M6uwqvtvVE059hLQrBNdiKHMazJI6L5nmh71WfZ36VNH/R/sawjM4u5So5n9Tn@FooJTJQQkK0o3kGpYSN@M2hUDnlMfM/wPrzUfugxmkJcicUsJRFKgcpikTl/n@4lqUdjX9585zNSsGBs1LlCRdtZDz3P02P06ZTtISUSdUATe8i2@vKM7SZ9qb/oOZNpavrCRJveRdbaFUdw@jISrfqw0G3jsR8/zfDMr4/XB/Gd5dz/9q0TBMXyRvmIk1rq0bEqqB70FY7BiVPXlleMIgEVzThBVTvN@CUxphRaVRaha80LdlNu8oL29fHbtF9M86mT8xaq038KRJudG@ga9aoeZfW@HEWhGr15Fu1985aJlmZUpU0yzO@YRugW8Vy0BXsRaREwRr@pkCtPnkXV7Hh2qZ3@gM "Perl 6 – Try It Online")
```
The universe contains 4 Higgs bosons.
The universe contains 4 Higgs bosons.
The universe contains 4 Higgs bosons.
The universe contains 4 Higgs bosons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 3 Higgs bosons, 2 gluons.
The universe contains 1 tau lepton, 2 Higgs bosons, 2 gluons, 1 antitau lepton.
The universe contains 1 tau lepton, 2 Higgs bosons, 2 gluons, 1 antitau lepton.
The universe contains 1 tau lepton, 2 Higgs bosons, 2 gluons, 1 antitau lepton.
The universe contains 1 tau lepton, 2 Higgs bosons, 2 gluons, 1 antitau lepton.
The universe contains 1 tau lepton, 1 Higgs boson, 4 gluons, 1 antitau lepton.
The universe contains 1 tau lepton, 6 gluons, 1 antitau lepton.
Simulation ended after 1.7 yoctoseconds.
```
# Some explanation: God and Man
There are 2 data structures holding the physics `%p` and the naming `%h`; god and man as it were. The physics hash gives a set of strings indexed by original unstable particle letter, which can be split, hashed and converted to a Mix:
```
say %((%p<H>).comb(/(\D+|<:!L>+)/)).Mix;
> Mix(H(2309.469), WW(14.1), ZZ(1.59), Zp(0.111), bB(64.8), cC(3.27), gg(8.82), lL(7.04), mM(0.0244), pp(0.223), tT(0.0216))
```
Each particle gets a letter, and thus each of these Mixes specifies a collection of particle decays. H decays to WW, with probability weighting 14.1. Particle-antiparticle pairs are coded with lower and uppercase letters, like `c` and `C` for charm quark and charm antiquark.
## And man thought for a bit, and named it antitau lepton
The naming is all set up in `%h`, which just maps each letter to a particle name. It's golfed to a degree, but I suspect there's room for improvement given the amount of repetition there.
```
p => positron
g => gluon
Z => Z boson
B => bottom antiquark
e => electron
s => strange quark
d => down quark
W => W boson
m => muon
U => up antiquark
c => charm quark
H => Higgs boson
L => antitau lepton
N => antineutrino
n => neutrino
S => strange antiquark
D => down antiquark
T => top antiquark
u => up quark
t => top quark
b => bottom quark
M => antimuon
C => charm antiquark
l => tau lepton
```
## Original string
With those two structures in place, the universe is simulated, of course, by string manipulation. So `"H"` is a universe with a single Higgs boson in it. The generator structure `_,_..._` is used to create a loop, and separates evolving the state of the universe string (held in `$_`) from printing it out. The printing is done by Bagging the letters in the universe and mapping the resulting counts (with plurals!).
## Sneezing particles into being
Evolving particles involves mapping them to a value picked from the Mix for that particle; so `t`, the top quark, evolves as
```
t=>7.722
Wd=>1
Ws=>1
Wb=>1
```
Perl6 permits us to randomly choose one of those keys with those given weightings via the flooringly simple `.roll`. So we roll for `t` and get, say `Wb` and substitute it into our universe "HtT"->"HWbT". Each unstable particle has itself as a possible roll, which permits us to simplify the structure vs having to check whether it decayed or not; most of the time you roll for "H", you just get "H" again.
## Experimental string theory
You can watch the universe string evolve via [this modified version](https://tio.run/##fVFNk5pAFLz7K95SaEFMPRhk/ViQg@uBg@aiKarYbCxARCowM4GhshbiXzegqc3mkku/mjfd1dM9PC6y8TU/DZL5tc5PfW71@dx2wTVG@gzN8SxcjE2ceh4xkSTJFKdGtpqgbkbPIzQmvk/wcca5joYx8ttBCMnXOuqGaYptN8kYPPBGnJI1JStKwAef6Dr9Yug4jvkIzXzdQrZqYb8kj2iUmw7DRYfVV0JwGj13CALEBCeG4e2JVxIvJLCF7X2zJN6GeAviWL0yOEFfUfrcdh0VI5aHiqZ8Ww7P9tPDyhmqmqriOn2zem3ow/zTjfGiv1pt@KPVP9Y4ODRzSd5ByEpGJTiwAmw3TZKyDeI7Vv2R87MKih/SHxlW0X0bUJHeb5q7PGRCsBwE4xAdgyKHisOe/aJQiiKgSey8G8u7i/TummQV8CMTEGdxJArgrExF4fxj13lJF@WvXr1r84pRoHElipSyTmKvnA9sO2tPIqggi7loDdWuD1lYiuRKb/L3QP1cy2I4R2JtnhINtfpWaS1rzfksaxfyn2axYFnWaA0i1t1nSCDvJOtBs19czxfbV0drrNt@k@ZVFoi0fWhM9/EegoOIC5AFnFgkWBlHjO5LlJqr1Rskiqmr1vU3).
```
HHH
HHH
HHbB
HHbB
HHbB
HHbB
HHbB
HHbB
lLHbB
lLHbB
lLHbB
lLHbB
lLHbB
lLbBbB
```
# Performance
I've taken it as far as 100 H on TIO, inevitably if you wanted to go much further it would be better to make some changes, this is Grand Unified String Theory after all.
[Answer]
# Groovy, ~~1506~~ 1454 - 10% = 1309 bytes
Assumes the number of starting Higgs boson particles is given as the first argument on the command line:
````
A='anti'
B='bottom '
C='charmed '
D='downward'
E='tau '
F='top '
L='lepton'
M='muon'
N='nutrino'
O=' boson'
P='upward '
Q='quark'
T='strange '
a=[n:'gluon']
b=[n:B+Q]
c=[n:B+A+Q]
d=[n:D+Q]
e=[n:D+A+Q]
f=[n:P+Q]
g=[n:P+A+Q]
h=[n:T+Q]
i=[n:T+A+Q]
j=[n:C+Q]
k=[n:C+A+Q]
l=[n:'positron']
m=[n:'electron']
n=[n:N]
o=[n:A+N]
p=[n:'photon']
q=[n:M]
r=[n:A+M]
s=[n:E+L]
t=[n:A+E+L]
u=[n:'W'+O,c:50,s:[[c:33,p:[l,n]],[c:33,p:[l,n]],[c:33,p:[l,n]]]]
v=[n:F+Q,c:12.95,s:[[c:33,p:[u,d]],[c:33,p:[u,h]],[c:33,p:[u,b]]]]
w=[n:F+A+Q]
x=[n:'Z'+O,c:50,s:[[c:20.6,p:[n,o]],[c:3.4,p:[m,l]],[c:3.4,p:[q,r]],[c:3.4,p:[s,t]],[c:15.2,p:[d,e]],[c:15.2,p:[h,i]],[c:15.2,p:[b,c]],[c:11.8,p:[f,g]],[c:11.8,p:[j,k]]]]
y=[n:'Higgs'+O,c:0.0433,s:[[c:64.8,p:[b,c]],[c:14.1,p:[u,u]],[c:8.82,p:[a,a]],[c:7.04,p:[s,t]],[c:3.27,p:[j,k]],[c:1.59,p:[x,x]],[c:0.223,p:[p,p]],[c:0.111,p:[x,l]],[c:0.0244,p:[q,r]],[c:0.0216,p:[v,w]]]]
O={new Random().nextInt(1000001)/10000}
S={s,c->for(Map p:s){c-=p.c;if(c<=0){return p.p}};S(s,O())}
P={r=[];it.collect{it.n}.groupBy{it}.each{k,v->c=v.count{it};r<<"${c} ${c>1?k+'s':k}"};r.join(', ').reverse().replaceFirst(',', 'dna ').reverse()}
U=[]
args[0].times{U<=O()){I.remove();S(J.s,O()).each{I.add(it)}}}
if(!Z){println "Simulation ended after $Y yoctoseconds.";break}}
````
[Answer]
# PHP, 989 - 10% = 890.1 bytes
Sub 1K baby! Thanks vsz, this was a really fun challenge. So many ways to go about it and very hard to verify your output is correct.
The program can take a command line argument to specify the starting number of Higgs bosons, e.g. `php universe_simulator.php 5`
```
<?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx81z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnAKoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqMUTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/ifO991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJomxvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15aVXtwdpbm8yaRlH1eUOFsv8B')));
```
Here's the same thing with line breaks for, uh... "readability"...
```
<?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7
mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6
rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx8
1z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnA
KoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqM
UTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/if
O991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8
vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK
8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB
8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJom
xvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU
7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15
aVXtwdpbm8yaRlH1eUOFsv8B')));
```
Some output:
```
The universe contains 2 Higgs bosons.
[...]
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 2 neutrinos, 1 positron, 1 antimuon, 1 bottom antiquark and 1 bottom quark.
Simulation ended after 153.2 yoctoseconds.
```
[Answer]
## QBasic ~~2161 \* .9 = 1945~~ ~~2028 \* .9 = 1825~~ 1854 \* .9 = 1669 bytes
Now that QBasic is the LOTM I thought I'd revise my very first answer on PPCG ever. Managed to knock off 140 bytes, not bad!
Based on feedback by @TaylorScott and @DLosc I've done a complete redesign:
* Time keeping altered
* Formatting now conforms to spec
* Saved a ton of bytes by making an array into an indexed string
**The code**
```
SUB f(p$,c)
DIM e$(25)
q$=" quark
a$=" antiquark
e$(1)="HHiggs boson
e$(2)="bbottom"+q$
e$(3)="1bottom"+a$
e$(4)="WW boson
e$(5)="gGluon
e$(6)="TTau lepton
e$(7)="2Tau antilepton
e$(8)="ccharm"+q$
e$(9)="3charm"+a$
e$(10)="ZZ boson
e$(11)="pphoton
e$(12)="mmuon
e$(13)="4antimuon
e$(14)="0top"+q$
e$(15)="5top"+a$
e$(16)="+positron
e$(17)="nneutrino
e$(18)="6antineutrino
e$(19)="-electron
e$(20)="ddown"+q$
e$(21)="7down"+a$
e$(22)="sstrange"+q$
e$(23)="8strange"+a$
e$(24)="uup"+q$
e$(25)="9up"+a$
FOR i=1TO 25
IF LEFT$(e$(i),1)=p$THEN ?str$(c)" "MID$(e$(i),2);
NEXT
IF c>1THEN?"s";
END SUB
RANDOMIZE TIMER
z=100
INPUT x
p$=string$(x,"H")
1:b=0
REDIM m$(LEN(p$))
FOR i=1TO LEN(p$)
m$(i)=MID$(p$,i,1)
NEXT
p$=s$(m$())
t=t+1
?"The universe contains";
FOR i=1TO LEN(p$)
y$=MID$(p$,i,1)
z$=MID$(p$,i+1,1)
c=c+1
IF(y$=z$ AND i<LEN(p$))=0THEN f y$,c:c=0
NEXT
?
r$="
FOR i=1TO LEN(p$)
d&=(RND*z)*z
e&=(RND*z)*(z^2)
q$=MID$(p$,i,1)
IF INSTR("HWZ02",q$) THEN b=1
r$=r$+g$(d&,e&,q$)
NEXT
p$=r$
IF b GOTO 1
?"Simulation ended after"t/10"yoctoseconds.
FUNCTION g$(d&,p&,q$)
DIM e$(28)
FOR i=1TO 28
x$=Mid$("H00433099979405H004330999550m4H004330998440ZpH004330996210ppH004330980310ZZH004330947610c3H004330877210T2H004330789010ggH004330648010WWH004330000000b12012950666670W12012950333340W82012950000000W70012950666670Wb0012950333340Ws0012950000000WdW0500006666702nW0500003333404nW050000000000+nZ050000882010c3Z050000764010u9Z050000612010b1Z050000460010s8Z050000308010d7Z050000274010T2Z050000240010m4Z050000206010-+Z050000000000n6",15*i+1,15)
a&=VAL(MID$(x$,8,7))
g$=q$
IF LEFT$(x$,1)=q$ THEN
IF d&<VAL(MID$(x$,2,5)) THEN
IF(p&>a& OR a&=0) THEN
g$=RIGHT$(x$,2)
EXIT FUNCTION
ENDIF
ENDIF
ENDIF
NEXT
END FUNCTION
FUNCTION s$(n$())
x=UBOUND(n$)
FOR i=1TO x:FOR J=1TO x
IF n$(i)<n$(J)THEN SWAP n$(i),n$(J)
NEXT j,i
FOR i=1TO UBOUND(n$)
a$=a$+n$(i)
NEXT
s$=a$
END FUNCTION
```
**Sample output**
```
? 3
The universe contains 3 Higgs bosons
The universe contains 3 Higgs bosons
The universe contains 3 Higgs bosons
The universe contains 3 Higgs bosons
The universe contains 1 bottom antiquark 2 Higgs bosons 1 bottom quark
The universe contains 1 bottom antiquark 2 Higgs bosons 1 bottom quark
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 2 bottom antiquarks 1 Higgs boson 2 bottom quarks
The universe contains 3 bottom antiquarks 3 bottom quarks
Simulation ended after 2.3 yoctoseconds.
```
[Answer]
# C#6, ~~3619~~ ~~3617~~ ~~3611~~ 3586 - 10% = 3227.4 bytes
Program takes two optional arguments for the number of starting Higgs Bosons and the seed to use for the Random class.
```
using System;using System.Collections.Generic;class a{List<P>L;List<Q>S;double Y;static void Main(string[]a){a b;b=a.Length<1?new a():a.Length<2?new a(int.Parse(a[0])):new a(int.Parse(a[0]),int.Parse(a[1]));}a(int j=1,int e=1){Random r=new Random(e);L=new List<P>();S=new List<Q>();for(int i=0;i<j;i++)L.Add(new H());while(L.Count>0){List<P>l=new List<P>();foreach(P p in L){List<P>d=p.C(r);if(d!=null)foreach(P y in d){if(y.GetType()==typeof(Q))S.Add((Q)y);else l.Add((P)y);}else l.Add(p);}L=l;Y+=.1;W();}var s=$"Simulation ended after {Y} yoctosecond";if(Y!=1d)s+="s";Console.WriteLine(s+".");}void W(){var t="";Dictionary<string,int>N=new Dictionary<string,int>();int M=0;foreach(P x in L){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}foreach(Q x in S){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}var o="The universe contains ";int i=N.Keys.Count;foreach(var x in N.Keys){i--;if(M==1){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";}else if(M==2){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";if(i!=0)o+=" and ";}else{if(i<1){o+=$"and {N[x]} {x}";if(N[x]!=1)o+="s";}else{o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";o+=", ";}}}Console.WriteLine(o+".");}}abstract class P{public static string[]Z=new string[]{"photon","gluon","positron","electron","quark","lepton","muon","neutrino"};public double l;public abstract List<P>D(Random r);public List<P>C(Random r){List<P>d=null;if(r.NextDouble()<l)d=D(r);return d;}}class H:P{public H(){l=.000433;}public override List<P>D(Random r){var d=new List<P>();Action<P>U=d.Add;var n=r.NextDouble();if(n<.648){U(new Q("bottom "+Z[4]));U(new Q("bottom anti"+Z[4]));}else if(n<.789){U(new W());U(new W());}else if(n<.8772){U(new Q(Z[1]));U(new Q(Z[1]));}else if(n<.9476){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.9803){U(new Q("charm "+Z[4]));U(new Q("charm anti"+Z[4]));}else if(n<.9962){U(new Z());U(new Z());}else if(n<.99843){U(new Q(Z[0]));U(new Q(Z[0]));}else if(n<.99954){U(new Z());U(new Q(Z[0]));}else if(n<.999784){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else{U(new T(0>1));U(new T(1>0));}return d;}public override string ToString(){return"Higgs Boson";}}class W:P{public W(){l=.5;}public override List<P> D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new Q(Z[7]));if(n<1/3d)d.Add(new Q(Z[2]));else if(n<2/3d)d.Add(new Q("anti"+Z[6]));else d.Add(new Q("antitau "+Z[5]));return d;}public override string ToString(){return"W Boson";}}class Z:P{public Z(){l=.5;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();Action<P>U=d.Add;var t=Z[4];if(n<.206){U(new Q(Z[7]));U(new Q("anti"+Z[7]));}else if(n<.24){U(new Q(Z[3]));U(new Q(Z[2]));}else if(n<.274){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else if(n<.308){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.46){U(new Q("down "+t));U(new Q("down anti"+t));}else if(n<.612){U(new Q("strange "+t));U(new Q("strange anti"+t));}else if(n<.764){U(new Q("bottom "+t));U(new Q("bottom anti"+t));}else if(n<.882){U(new Q("up "+t));U(new Q("up anti"+t));}else{U(new Q("charm "+t));U(new Q("charm anti"+t));}return d;}public override string ToString(){return"Z Boson";}}class T:P{bool A;public T(bool a){A=a;l=.1295;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new W());if(n<1/3d)d.Add(new Q("down "+Z[4]));else if(n <2/3.0)d.Add(new Q("strange "+Z[4]));else d.Add(new Q("bottom "+Z[4]));return d;}public override string ToString(){var r=A?"top anti":"top ";return r+Z[4];}}class Q:P{string N;public Q(string n){N=n;}public override List<P>D(Random r){return null;}public override string ToString(){return N;}}
```
I should not have used objects for this, I'll probably try to do a second solution using arrays instead, but it'd probably be similar to the C++ solution posted already. The number of Higgs Bosons I can handle is severely limited as well, I think at least an hour for H=1,000,000. Smaller numbers run reasonably well though.
Sample output:
```
$ b
// Default h=1,seed=1
The universe contains 1 Higgs Boson.
...
The universe contains 1 bottom quark and 1 bottom antiquark.
Simulation ended after 65.5000000000006 yoctosecond.
$ b 10 12345
The universe contains 10 Higgs Bosons.
The universe contains 9 Higgs Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 2 W Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 1 bottom quark, 1 bottom antiquark, 2 neutrinos, and 2 antitau leptons.
The universe contains 7 Higgs Bosons, 2 bottom quarks, 2 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 6 Higgs Bosons, 3 bottom quarks, 3 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 5 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 2 W Bosons, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 1 W Boson, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 3 neutrinos, 2 antitau leptons, and 1 antimuon.
The universe contains 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 3 Higgs Bosons, 5 bottom quarks, 5 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 2 Higgs Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 2 W Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 1 W Boson, 6 bottom quarks, 6 bottom antiquarks, 5 neutrinos, 2 antitau leptons, and 3 antimuons.
The universe contains 1 Higgs Boson, 6 bottom quarks, 6 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
Simulation ended after 540.500000000054 yoctoseconds.
```
~~I'll post the last two lines for the h=1000000 run when it finishes, probably later today.~~ As promised:
```
$ b 1000000
(a few hours, 35K lines, and 15MB later)
The universe contains 653391 bottom quarks, 653271 bottom antiquarks, 36336 charm quarks, 36336 charm antiquarks, 176724 gluons, 71397 tau leptons, 165604 antitau leptons, 5626 photons, 288869 neutrinos, 95047 positrons, 95556 antimuons, 5254 strange quarks, 5130 strange antiquarks, 1389 muons, 1081 electrons, 5240 down quarks, 5104 down antiquarks, 6529 antineutrinos, 3862 up quarks, and 3862 up antiquarks.
Simulation ended after 3599.29999999782 yoctoseconds.
```
[Answer]
## Mathematica, 950bytes-10% = 855 bytes
Using expression compressing:
```
ToExpression[Uncompress["1:eJxdVG1v2jAQ7of9kMyVpna9pkkKLV0aROlW2AQVb1MqPGsKYCBaYtPEjFLgf+zn7vKGaD/kse/J+fz4zuePI9nr//twdOQ5ZTt0DHvkDLxRwGkTPGZHTs8TExnez6U/5nYvN3vcC+zAaXExU3P7l2Faz7T7m31xiEZuqwPZV5EvZrRLqcUYu62mdH/lq/E8IU3GoAmk6c9msVaXsRQEXoHUpVIy1LpLL/pDYLgn7oTynzPSBeIWKxpAGsEymQ1aQAbeUmvxhUrs3EzWBTk1BXI/96J99IfCPgiOOw6L4AsgnbnEpTGBNpB2us8aSOIepsYLbiIXRbynzDqI1sEIMvZVlDgLII98mWRFEhhnYcSe4EC+BXycua6AYPo8MePvDl6w+Y6o6qtciUMnmVO5xx2Qn28k1VMi+8uSqrlzTBBt83DEoy4dQXPrbofbl+0Tg/DsDK/CQ+ApxQU9yYt3jHX7PqU9ym4N3YSIbvSrUgV0s2SCXqlYoBvXRgnx0rpGNMs3iIZlXSaDaZrJYFilUjaaV7vz6mbzCsMdbFxwERvQQMSCtnCYwgPiMP29gEU67yC2YY34Ak+7HV4khsnZayonmjYdEOiwTrGFiG4uw/q+dTN0y7gCA8WW3qFZtt6jWckwVSxgjJH5gZhcsYQ24gpWiNmx6nCXnwRFDBmcYHZPD3Jo3WSSXZBpElYpvqI3g99wnJbp9NNFbcTs2Hm+qJ08yij0gtq9XAoV0xG70HvLgJ9XW36sTu0O3ihFyWDOtaXw//Io5tpYCuX5eJOxB9PG/CF9QYvSDvBWxQsZc7rJGh+1BbXYcXwoZiYQAkTD1icsIf2CAoIqNz6YgH54PvzSdtcJs1PluZw+9gxu50uhcTHhE82bKh69eSswFZ/D9KlYy7FCOah6EmOg/5kZdRM="]]
```
Uncompressed Code (1168 bytes-10% = 1051.2bytes):
```
a=5;m=0;b=Table[H,a];r=RandomChoice;R=RandomReal;l=Length;
q[Q_]:=" "<>ToString[Q[[2]]]<>" "<>Switch[Q[[1]],H,"Higgs Boson",z,"Bottom Quark",Z,"Bottom Antiquark",W,"W Boson",G,"Gluon",TL,"Tau Lepton",L,"Tau Antilepton",f,"Charm Quark",F,"Charm Antiquark",Z,"Z Boson",p,"Photons",M,"Muon",y,"Antimuon",x,"Top Quark",X,"Top Antiquark",P,"Positron",n,"Neutrino",c,"Antineutrino",e,"Electron",w,"Strange Antiquark",W,"Strange Quark",M,"Down Antiquark",o,"Down Quark",A,"Up Antiquark",B,"Up Quark"]
While[MemberQ[b,H|W|Z|x|X],m++;b=Flatten[(Switch[#,H,If[R[]<0.1,r[{.648,.141,.882,.0704,.0327,.0159,.00223,.00111,.000244,.000216}->{{z,Z},{W,W},{G,G},{TL,L},{f,F},{Z,Z},{p,p},{Z,P},{M,y},{x,X}}],H],W,If[R[]<0.5,r[{{P,n},{y,n},{L,n}}],W],Z,If[R[]<0.5,r[{0.206,0.034,0.034,0.034,0.152,0.152,0.152,0.118,0.118}->{{n,c},{e,P},{M,y},{TL,L},{o,M},{w,w},{z,Z},{B,A},{f,F}}],Z],(x|X),If[R[]<0.1295,r[{{W,o},{W,w},{W,z}}]],_,#]
)&/@b];s=q/@(Normal@Counts[b]/.Rule->List);Print["The universe contains"<>StringJoin[Flatten[Transpose[{Table[If[l@s==i,If[l@s==1,""," and"],If[i==1,"",","]],{i,1,l@s}],s}]]]<>"."];]
Print["Simulation ended after "<>ToString[0.1*m]<>" yoctoseconds."]
```
The startparameter can by choosen by altering the value for a.
I noticed i've used the wrong probability for the Higgs boson but cant currently change it (in some hours or so). So add 3 oder 4 bytes to the current solution. (It was a test-value)
[Answer]
# Perl, ~~973~~ ~~986~~ ~~959~~ 944 bytes -10% = 849.6 points
Indentation and newlines are not part of the code, and are provided solely so you aren't scrolling for 30 years to read it all.
There are a couple of 0-byte optimizations that I never bothered to undo.
```
%p=(H,Higgs.($o=$".Boson),W,W.$o,Z,Z.$o,B,Bottom.($Q=$".Quark),b,Bottom.($q=$".Antiquark),G,Gluon,A,Tau.($t=$".Lepton),a,Antitau.$t,P,Photon,M,Muon,w,Antimuon,T,Top.$Q,t,Top.$q,e,Positron,N,Neutrino,n,Antineutrino,E,Electron,D,Down.$Q,d,Down.$q,S,Strange.$Q,z,Strange.$q,U,Up.$Q,u,Up.$q,C,Charm.$Q,c,Charm.$q);
%d=(H,[433e-6,.648,Bb,.141,WW,.0882,GG,.0704,Aa,.0327,Cc,.0159,ZZ,.00223,PP,.00111,ZP,244e-6,Mw,216e-6,Tt],W,[.5,$x=1/3,eN,$x,wN,$x,tN],Z,[.5,.206,Nn,.034,Ee,.034,Mw,.034,Aa,.152,Dd,.152,Sz,.152,Bb,.152,Uu,.118,Uu,.118,Cc],T,[.1295,$x,WD,$x,WS,$x,WB],t,[.1295,$x,Wd,$x,Wz,$x,Wb]);
for(@a=(H)x<>;grep/[HWZTt]/,@a;$z++){
for$m(@a){
@b=(@b,$m),next if$d{$m}[0]<rand;
$e=rand;
($e-=$d{$m}[($_*=2)+1])>0||($e=2,@b=(@b,split//,$d{$m}[$_+2]))for 0..9
}
(@a,@b,%u,$w)=@b;
$u{$_}++for@a;
$w.=" $u{$_} $p{$_}".($u{$_}>1?'s,':',')for keys%u;
say"The universe contains",$w=~s/.$/./r=~s/,([^,]+)$/ and$1/r
}
$z/=10;say"Simulation ended after $z yoctoseconds."
```
Obviously, the bulk of the code is creating the initial hashes. `%p` contains the names of all of the particles, exploiting Perl's bareword feature. `%r` determines the decay rates. If it's not featured in here, then it doesn't decay at all. `%d` contains the decay particles.
Since the order of particles in the output doesn't matter, I don't bother changing it from the random way Perl accesses the keys in the hash, which leads to things like the following:
```
[snip]
The universe contains 1 Higgs Boson.
The universe contains 1 Higgs Boson.
The universe contains 2 W Bosons.
The universe contains 2 Neutrinos, 1 Positron and 1 Top Antiquark.
The universe contains 1 Top Antiquark, 1 Positron and 2 Neutrinos.
The universe contains 1 Top Antiquark, 1 Positron and 2 Neutrinos.
The universe contains 1 Top Antiquark, 1 Positron and 2 Neutrinos.
The universe contains 2 Neutrinos, 1 Positron and 1 Top Antiquark.
The universe contains 1 Positron, 1 Top Antiquark and 2 Neutrinos.
The universe contains 2 Neutrinos, 1 Top Antiquark and 1 Positron.
The universe contains 1 Positron, 1 Strange Antiquark, 2 Neutrinos, 1 Bottom Antiquark and 2 W Bosons.
The universe contains 1 W Boson, 1 Bottom Antiquark, 2 Neutrinos, 1 Positron and 1 Strange Antiquark.
The universe contains 2 Neutrinos, 1 Bottom Antiquark, 1 W Boson, 1 Strange Antiquark and 1 Positron.
The universe contains 1 W Boson, 1 Bottom Antiquark, 2 Neutrinos, 1 Strange Antiquark and 1 Positron.
The universe contains 1 Bottom Antiquark, 4 Neutrinos, 1 Antimuon, 2 Positrons and 1 Strange Antiquark.
```
This has truly been an exhilarating adventure. Wonderful puzzle, honestly, I had a lot of fun! :)
[Answer]
## Python 3.6.1, ~~1183~~ ~~1157~~ ... ~~905~~ 889 \* 0.9 = 800.1 bytes
First time submitting one of these but this challenge looked pretty fun so here we go...
Almost certainly not as golfed as it could be but I'm pretty inexperienced at this so any tips are welcome.
```
from random import*
w,z='WZ';b,q,v=' boson',' .quark',[1]*3;p,n,u,t={'H':[433e-6,['Bb',w*2,'GG','Xx','Cc',z*2,'PP','ZP','Mm','Tt'],[6480,1410,882,704,32.7,15.9,2.23,1.11,.244,.216]],w:[.5,['FN','mN','xN'],v],z:[.5,['Nn','EF','Mm','Xx','Dd','Ss','Bb','Uu','Cc'],[2060]+[340]*3+[152]*3+[118]*2],'T':[.1295,['WD','WS','WB'],v]},{'H':'Higgs'+b,'B':'bottom'+q,w:w+b,'G':'gluon','X':'.tau lepton','C':'charm'+q,z:z+b,'P':'photon','M':'.muon','T':'top'+q,'E':'electron','F':'positron','N':'.neutrino','D':'down'+q,'S':'strange'+q,'U':'up'+q},['H']*int(input()),0
while{*u}&{*p}:
for x in[*u]:
if x in p and random()<p[x][0]:u.remove(x);u+=choices(*p[x][1:])[0]
print("The universe contains %s."%' and'.join((', '.join(str(u.count(x))+' '+n[x.upper()].replace('.',(x>x.upper())*'anti')+(1<u.count(x))*'s'for x in{*u})).rsplit(',',1)));t+=.1
print('Simulation ended after %.1f yoctoseconds.'%t)
```
[Try it online!](https://tio.run/##TVJNb@IwED2XX2FVYicfXgsHSimUPfT7UlSJVq0a5RCCAe@CnSY2pFT8dnYc6Govz34zfjNvbOefZqFVe7@fFXpFilRNcZGrXBcmaGzodgiv7zCY0A@6HgKZ6FIroEDYh02LP0BjngTtQU4VtdQMv@AB@nGn3RY/uzSGqwnQTRBRuL9HzVuFcJ0B3brQ0xOydwePK4RnAwmNu51ei/IOb9FeL6LnrQ5tR@yc8jN2QSMWtSlnnFMWdToIvJskdNOP2Rm2uhthkZWDaoSV1gndHjMj5/f27rtR7eJmijAuEZxFeLEHZ@gganVbSRi3Oy2cK4z5WXRYeS8JogR94nyMRxeu8usNyl7HDq7qnjtaXwA8yPm8hHCC5ZFNtDF6BeEHmt244D0G50tbX@Qb7plJLVmK3NSRa4xki7SoFdv@1imeMJYv9OHAo5OsDnK0A0bn7ijc4l4sRWaKOnXnNLqURzpyKiWsKaTS7gqQT/VG1dIxktLg489FzV@QW1d1h2M@QBJIZTypcms836etxmYhl@IrsLsfX0G@6zdOZrogFZEqDmyC9ETOakpygh/q@Ks8/zKPqyRuJX3LCrHSa@FV/sCGw2yhZSZKL6jzvJ/4eKhxkheu7enzQhCr5FoUpSCZViaVqiTNkp02wZUH9ltL5XlAyXGLo3iWZdqivPL9EAiEKq6YzXNReH6C3fNlmgkPGFCv@vUv4weQKiPBDz1@@V@FAEr4HtGN7fusKPOlNNgUKPd9f2DCIeONg2UYy5VdpkZqRYSaiilJZ0YUpMn4jHzqzOhS4CDTkkHT@Ps9/ws)
**Edit: In the interest of brevity, an abridged list of the edits I've made (thank you commenters for the help!):**
* Saved 25 bytes thanks to Cat Wizard (semicolons instead of newlines) and the other Python answer (saved a couple of bytes defining strings).
* Figured out a few more things to save another 107(!) bytes, mostly just better arrangement of dicts and it's no longer a function.
* Realised `random.choices()` is weighted probabilities, not percentages, so I could save a few bytes from shifting things up a few powers of ten - 28 bytes saved! Higgs decay probability was wrong - I read 0.43% instead of 0.043% so that cost two bytes.
* Saved another 28 bytes from assorted fancy tricks - set intersection instead of `any()`, `+=` instead of `list.extend()` and a different `import` statement.
* Swapped the nested dicts for a dict of lists, used `choices(*p[x][1:])` to save a couple and `x and y or z` to avoid `if...else...or`.
* Slightly better assignment, LBYL works out better and replaced `enumerate()` by copying the universe and using `list.remove()` on the original (the `enumerate` method was broken anyway as it happens).
* Fixed a couple of silly things that were missed, better `print()` statement and merged `if` statements. Removed some unneeded brackets.
More readable version:
```
from random import *
w,z='WZ'
b,q,v=' boson',' .quark',[1]*3
# Decayable particle products/probabilities
p,n,u,t={'H':[433e-6,['Bb',w*2,'GG','Xx','Cc',z*2,'PP','ZP','Mm','Tt'],[6480,1410,882,704,32.7,15.9,2.23,1.11,.244,.216]],
w:[.5,['FN','mN','xN'],v],z:[.5,['Nn','EF','Mm','Xx','Dd','Ss','Bb','Uu','Cc'],[2060]+[340]*3+[152]*3+[118]*2],
'T':[.1295,['WD','WS','WB'],v]},
# Particle names
{'H':'Higgs'+b,'B':'bottom'+q,w:w+b,'G':'gluon','X':'.tau lepton','C':'charm'+q,z:z+b,
'P':'photon','M':'.muon','T':'top'+q,'E':'electron','F':'positron','N':'.neutrino',
'D':'down'+q,'S':'strange'+q,'U':'up'+q},
# Universe
['H']*int(input()),
# Time taken
0
while {*u} & {*p}: # While any particles can still decay
for x in[*u]: # Iterate through them
if x in p and random()<p[x][0]: # Check if they should decay
u.remove(x) # If they should, remove them
u+=choices(*p[x][1:])[0] # And add in the products
# Join particle names with their counts together, separated by ',', add 'anti' where
# needed, add 's' where needed, replace last ',' with 'and', then print.
a = ' and'.join((', '.join(str(u.count(x))
+ ' '
+ n[x.upper()].replace('.',(x>x.upper())*'anti')
+ (1<u.count(x))*'s' for x in {*u})).rsplit(',',1))
print("The universe contains %s." % a)
t+=.1
print('Simulation ended after %.1f yoctoseconds.'%t)
```
Sample output with 5000 Higgs bosons - might do a bigger run later to see if any top quark decay makes it in:
```
The universe contains 1 up antiquark, 23 charm quarks, 1 electron, 23 charm antiquarks, 371 tau leptons, 1542 neutrinos, 500 antimuons, 16 antineutrinos, 505 positrons, 4 muons, 3 photons, 3373 bottom quarks, 3373 bottom antiquarks, 1 up quark, 916 gluons and 897 antitau leptons.
Simulation ended after 2410.5 yoctoseconds.
```
If I've done anything wrong then please let me know and I'll try to fix it!
[Answer]
# Ruby, ~~997~~ 995 bytes -10% = 895.5 points
*edit: added 'and' as the last delimiter as noticed by breadbox*
First time posting on PPCG, this is an old challenge but I had much fun doing it. Here is the code
```
s=%w(boson quark top bottom anti tau lepton charm muon neutrino down strange up)
t="Higgs 0;Z 0;W 0;2 1;2 41;3 1;3 41;gluon;5 6;45 6;7 1;7 41;photon;8;48;positron;9;49;electron;#a 1;#a 41;#b 1;#b 41;#c 1;#c 41"
h=[4.33e-2,50,50,12.95]
d=[[64.8,14.1,8.82,7.04,3.27,1.59,0.223,0.111,0.0244,0.0216],[20.6,*[3.4]*3,*[15.2]*3,*[11.8]*2],*[[33.3]*3]*3]
r=["fgcchhijklbbmmbmnode","qrspnoijtuvwfgxykl","pqoqjq","ctcvcf","ctcvcf"]
r=r.map{|a|a.chars.map{|e|e.ord-97}}
s.size.times{|i|c=i>9?"#"+(i+87).chr: i.to_s;t=t.gsub(c,s[i])}
t=t.split(';')
z=Random.new
p=[0]*25
p[0]=gets.to_i
o=0
f=->p{puts"The universe contains "+(*a,b=(0..24).map{|i|e=p[i];e>0?"#{e} "+t[i]+(e>1?"s":""):nil}.compact;a*", "+(a.size>0?" and ":"")+b)+"."}
while p[0..4].sum>0 do
f[p]
q=p.clone
(0..4).map{|i|p[i].times{|j|a=z.rand(100.0);a<h[i]?(q[i]-=1;a=z.rand(100.0);d[i].size.times{|k|a<d[i][k]?(q[r[i][k]]+=1;q[r[i][k+1]]+=1):a-=d[i][k]}):0}}
p=q.clone
o+=1
end
f[p]
puts "Simulation ended after #{o/10.0} yoctoseconds."
```
The strings are compressed by factoring recurring words (vars `s` and `t`)
Products of decay are store compactly as string (var `r`), each letter is a particle.
A function `f` prints the state of the universe by mapping the particle array to strings.
I feel like there are some bytes to cut off in the state update line, but I can't find anything better.
## Sample Output
```
[snip]
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 3 W bosons, 4 gluons and 1 tau lepton.
The universe contains 3 W bosons, 4 gluons and 1 tau lepton.
The universe contains 2 W bosons, 4 gluons, 1 tau lepton, 1 antimuon and 1 neutrino.
The universe contains 2 W bosons, 4 gluons, 1 tau lepton, 1 antimuon and 1 neutrino.
The universe contains 1 W boson, 4 gluons, 1 tau lepton, 3 antimuons, 1 positron and 4 neutrinos.
The universe contains 4 gluons, 1 tau lepton, 4 antimuons, 1 positron and 5 neutrinos.
Simulation ended after 653.2 yoctoseconds.
```
## Performance
It's not so bad! It computed 100000 Higgs boson in 25sec
```
The universe contains 64751 bottom quarks, 93044 bottom antiquarks, 170984 gluons, 59927 tau leptons, 33038 antitau leptons, 14718 charm quarks, 12419 charm antiquarks, 5250 muons, 261567 antimuons, 53148 positrons, 305169 neutrinos, 2142 antineutrinos, 1575 electrons, 14080 down quarks and 7926 down antiquarks.
Simulation ended after 3131.4 yoctoseconds.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 572 \* 0.9 = 514.8 bytes
```
Jm?tld,hd,-1^.5c1shced\ sm*]<k2s>k2tced\ dcR\,cu:GhHtHc"A76 !B17 !C1 v!D_top !E00 !F bosR!GmuR_!Ineutrino_!Jtau leptR_!KQ_charm !LQ_strange !MQ_down !NQ_up !OQ_bottom !Panti!Qquark!Ron"\!"HiggsF,16Efg3240Ebb705Epp441Eqr352ER16350 cc7950 ss1115 cs555 tu122 de108_WF,CxCuCr1_ZF,Cw103 yxBtuBqrBjkAlmAfgAhi59 R59DQ,5 bj1 bl1 bf1DPOOPNNPMMPLLPKKPQ_gluR_JPJphotR_GPGIPIpositrR_electrR"\_L%"The universe contains %s.":j", "fT.e?bs[b\ h@Jk?tb\s"")0b",(?!.*,)"" and"K+Q*]Z24Ws<K4yK=+Z1Vs.em?>O1.0he@JkY,kOee@Jkb<K4IN XhNK_1 XRK1xLGeN;yK%"Simulation ended after %s yoctoseconds."cZT
```
Qualifies for the -10% bonus. Try it online [here](https://tio.run/##HU9tb9owGPwrjy0hrW2G4kBgdF0Z7y/hJcnQ2jE6K3EMCSRxiJ0Wfj3z9uHRnU53j@6Kq4pvt3nWVWlkxJHxmfyp24zImPFoBzK7f3s6WfL5ZKn/QsT8ncGqx0k8VVOGe@0WoD5pAxoQeEdDqkQBaGSagMYQCumjSVb5FM1yXqkyyQVFcxVUkPJCadnxKIuDMgO08KhUZZAfOKClRyPxkQNaebTS79YeDYVSQtvcIFcJ8s5VUJ6QL3K8Q3iaHA5ybJDWaH9oWE1zFIZt0x4VRbNJRueyYVsjn7QatgmMtTsapCSE2MCkbdugKmJZEHFifqEvY2NwGVSDktCtph/EbMD10ldV/1z2j6demvX2h16c2B3w7c7QM2wIjwTCVN@eDN312l2t3OXSXSxcx3E9ekj1@Lk7L2Kh507cycydFUImqvQpTznTiHd0UcObmEOVJ@@8lByYyFWQ5BJqso4fj9gAvN/UeTeUv8MdxN/np64KdxLjOzPExqcuqt8bdxhDkEfYefDu37ZW80U@Oc2r8@1hS37KOs@6z2tSN2Ouw7@M05r/I6G2zFbwGq8cSuDVd8hlMeGrr1enhn8kWZUGKhE58DziEQR7xUvdCK6CKSG5Lhnpemy7ud2I@Rc), or try it out with the Higgs boson half life reduced to 1ys [here](https://tio.run/##HU9tb9owGPwrjy0hrTRDcSBldF0Z7y/hJcnQ2jE6K3EMCSRxiJ0Wfj3z9uHRnU53j@6Kq4pvt3nWVWlkxJHxmfxp2IzImPFoBzKrvz2dLPl8stR/IWL@zmDV4ySeqinDvfYDoD5pAxoQeEdDqkQBaGSagMYQCumjSVb5FM1yXqkyyQVFcxVUkPJCadnxKIuDMgO08KhUZZAfOKClRyPxkQNaebTS79YeDYVSQtvcIFcJ8s5VUJ6QL3K8Q3iaHA5ybBAT9oem1TJHYdg27VFRtFpkdC6btjXyyUPTNoGxdkeDlIQQG5i0bRtURSwLIk7ML/RlbAwug2pQErrV9IOYTbhe@qrqn8v@8dRLs97@0IsTuwO@3Rl6hg3hkUCY6tuTobteu6uVu1y6i4XrOK5HD6keP3fnRSz03Ik7mbmzQshElT7lKWca8Y4uangTc6jy5J2XkgMTuQqSXEJNNvDjERuA95sG74byd7iD@Pv81FXhTmJ8Z4bY@NRFjbpxhzEEeYSde6/@trVaL/LJaV2db/db8lM2eNZ9XpOGGXMd/mWc1vwfCbVltoLXeOVQAq@@Qy6LCV99vTo1/CPJqjRQiciB5xGPINgrXupGcBVMCcl1yUjXY9vN7UbMvw) (makes for less repetition in the output, and a more exciting universe!).
I'm convinced this is far from optimal, especially the dictionary compression, but I've wasted more than enough time on this already, so improvement suggestions are welcome.
The program is split into three parts - dictionary preparation, output function definition, and simulation execution.
## Dictionary preparation
`Jm?tld,hd,-1^.5c1shced\ sm*]<k2s>k2tced\ dcR\,cu:GhHtHc"A76 !B17 !C1 v!D_top !E00 !F bosR!GmuR_!Ineutrino_!Jtau leptR_!KQ_charm !LQ_strange !MQ_down !NQ_up !OQ_bottom !Panti!Qquark!Ron"\!"HiggsF,16Efg3240Ebb705Epp441Eqr352ER16350 cc7950 ss1115 cs555 tu122 de108_WF,CxCuCr1_ZF,Cw103 yxBtuBqrBjkAlmAfgAhi59 R59DQ,5 bj1 bl1 bf1DPOOPNNPMMPLLPKKPQ_gluR_JPJphotR_GPGIPIpositrR_electrR"\_`
This is the largest section of the finished code, taking up 381 bytes. The dictionary is built using the following string:
```
Higgs boson,1600 fg324000 bb70500 pp44100 qr35200 on16350 cc7950 ss1115 cs555 tu122 de108_W boson,1 vx1 vu1 vr1_Z boson,1 vw103 yx17 tu17 qr17 jk76 lm76 fg76 hi59 on59_top quark,5 bj1 bl1 bf1_top antiquark_bottom quark_bottom antiquark_up quark_up antiquark_down quark_down antiquark_strange quark_strange antiquark_charm quark_charm antiquark_gluon_tau lepton_antitau lepton_photon_muon_antimuon_neutrino_antineutrino_positron_electron
```
The string is an underscore separated list of the particles and, if the particle is unstable, its behaviour - a space separated list consisting of its half life in simulation ticks followed by what it decays into, along with the distinct probabilies of each. Each particle has a single-letter code associated with it, given by their position in the list indexed into the lower case alphabet - so the Higgs boson is `a`, the W boson is `b`, all the way up to the electron being `y`.
Rather than storing the decay probabilities, the half life is stored instead and the probability calculated when the dictionary is processed. The formula used is `P=1-(1/2)^(1/h)` where `P` is the probablity to decay per tick, and `h` is the half life of the particle measured in ticks.
The unstable particles are the first four in the list. As the number of these particles is what determines when the simulation ends, having these at the start of the list makes them easy to check later on.
The problem is that this string is huge - 436 bytes! - and using Pyth's built-in string compression actually increases the byte count, as it uses so many multi-byte characters. I've settled on a relatively simple iterative dictionary compression scheme. The snippet `u:GhHtHc"xxx"\!"yyy"` decompresses it, as follows:
```
u:GhHtHc"xxx"\!"yyy" xxx -> dictionary, yyy -> encoded string
c"xxx"\! Chop the dictionary on !
u "yyy" Reduce the above, with initial state as encoded string, using:
:G In the current string, replace...
hH ... the first character of the dictionary entry...
tH ... with the remainder of the dictionary entry
```
The dictionary entries I've chosen are based only on my intuition and some trial and error, so I'm sure there is plenty of room for improvement.
The decompressed dictionary string is then interpreted and stored as described below:
```
Jm?tld,hd,-1^.5c1shced\ sm*]<k2s>k2tced\ dcR\,cxxx\_ xxx -> decompressed dictionary
cxxx\_ Split the string on underscores
cR\, Split each part on commas
m Map each element (particle), d, using:
?tld d Is the element length >1? If not, no change, otherwise...
,hd Create a pair consisting of the particle's name and...
ced\ Split the decay data on spaces
sh Parse 1st element (half life) as int
-1^.5c1 Calculate per-tick decay probability
, Pair the above with...
m tced\ Map the rest of the decay data, k, using:
]<k2 Take the 1st two characters
s>k2 Parse the rest of the characters as a string
* Repeat the characters that many times
s Flatten the list
J Store the processed dictionary in J
```
The result is that `J` contains an ordered list of the particle names. If they decay, the name is paired with its decay probability and a set of the particles it could decay into, weighted by their relative probabilities.
## Output function definition
```
L%"The universe contains %s.":j", "fT.e?bs[b\ h@Jk?tb\s"")0b",(?!.*,)"" and"
```
This defines a function `y(b)`, which accepts the current state of the universe as its input. This is simply a list of the numbers of the particles, ordered by their type as defined in the dictionary string described in the previous section.
```
L%"x":j", "fT.e?bs[b\ h@Jk?tb\s"")0b",(?!.*,)"" and" "x" -> format string, omitted for brevity
L Define a function, y(b)
.e b Map each element of b with its index, k, using:
?b 0 Is b non zero? If not, 0, otherwise...
b Particle count
\ Space
h@Jk Particle name (lookup in dictionary, then take 1st element)
?tb\s"" Trailing s if more than 1
s[ ) Concatenate the above 4
fT Filter out the 0s
j", " Join on comma + space
: Replace in the above...
",(?!.*,)" ... the last comma...
" and" ... with "and"
%"x" Insert the above into the format string
```
## Simulation execution
`K+Q*]Z24Ws<K4yK=+Z1Vs.em?>O1.0he@JkY,kOee@Jkb<K4IN XhNK_1 XRK1xLGeN;yK%"Simulation ended after %s yoctoseconds."cZT`
With the prep done, the simulation can now be executed. This consits of a few steps:
**Universe initialisation**
As the particle at index 0 in the universe state is the Higgs boson, the initial state of the universe is an array of input number followed by 24 zeroes.
```
K+Q*]Z24 implicit: Q=eval(input())
Q Input number
*]Z24 0 repeated 24 times
+ Concatenate
K Assign to K
```
**Simulation loop**
At each tick in the simulation, the current state of the universe needs to be displayed, a counter incremented, and each volatile particle needs to check if it should decay, applying the results to the universe state once each particle has been evaluated.
```
Ws<H4yK=+Z1Vs.em?>O1.0he@JkY,kOee@Jkb<K4IN XhNK_1 XRK1xLGeN;
s<K4 Take the sum of the first 4 particle counts
W ; Loop until the above is 0
yK Output the current universe state
=+Z1 Increment variable Z (initially 0)
.e <K4 Map each particle count, b, with its index, k, using:
m b Map over the particle count using:
@JK Look up the particle data
he Get the decay probability
O1.0 Generate random float between 0 and 1
?> Y Has particle failed to decay? Empty array if so, otherwise...
ee@Jk Get the particle decay choices
O Choose one of them at random
,k Create a pair with the current particle index and the above
s Combine into single nested list
V For N in the above:
IN If N is not empty:
X K Add to element in K...
hN ... at the correct particle's index...
_1 ... -1
xLGeN Get the index of each particle to be added to the universe
(lookup using index in G, lowercase alphabet)
XRK1 Add 1 to the element in K at each of the indexes
```
**Final output**
The simulation finishes when there are no unstable particles left. All that remains is to output the final state of the universe, and how long (how many ticks) the simulation took.
```
yK%"Simulation ended after %s yoctoseconds."cZT
yK Output final universe state
cZT Float divide ticks count by 10
%"Simulation ended after %s yoctoseconds." Format string, implicit print
```
[Answer]
## D, 1172 1101 bytes - 10% = 990.9 bytes
```
import std.random,std.conv,std.stdio,std.algorithm,std.range;alias I=int,V=void,S=string,F=float,U=uniform01!F,W=writef,J=join,X=split;V main(S[]v){I[26]c;c[0]=to!I(v[1]);S[84]s;s[65..$]="antiX bosonXcharm Xdown XelectronXZXgluonXHiggsXtop Xbottom Xup Xtau leptonXmuonXneutrinoXWXphotonXquarkXpositronXstrange ".X('X');S[]f="HBXOBXFBXKQXKAQXDQXDAQXIQXIAQXJQXJAQXSQXSAQXCQXCAQXLXALXEXRXGXPXMXAMXNXAN".X('X');V
D(I i,F p,F[]d,S v){d~=200;if(c[i]&&U()<p){c[i]--;p=U();foreach(j,q; d){if(p<q/100){c[v[2*j]-65]++;c[v[2*j+1]-65]++;break;}}}}S
C(T)(T s){return(s.length>1)?s[0..$-1].J(", ")~" and "~s[$-1]:s.J(" and ");}I
y=0;while(1){W("The universe contains "~C(iota(0,c.length).filter!(i=>c[i]).map!(i=>to!S(c[i])~" "~f[i].map!(a=>s[a]).J~((c[i]>1)?"s":"")).array)~".\n");y++;if(c[0]+c[1]+c[7]+c[8]<1)break;F[]u=[100/3.0,200/3.0];D(0,.000433,[.0216,.0460,.157,.38,1.97,5.24,12.28,21.1,35.2],"HIVWCUUUCCNOPQTTBBJK");D(2,.5,[11.8,23.6,38.8,54.,69.2,72.6,76.,79.4],"XYRSVWPQFGLMJKDENO");D(1,.5,u,"SXWXQX");D(7,.1295,u,"BFBLBJ");D(8,.1295,u,"BGBMBK");}W("Simulation ended after %f yoctoseconds.\n",y/10.0);}
```
### Ungolfed
```
import std.random,std.conv,std.stdio,std.algorithm,std.range;
alias I=int,V=void,S=string,F=float,U=uniform01!F;
//uppercase is antiparticle. The enums are replaced with constants
//in the golfed version.
enum P{
h, w, z, //bosons
u,U, d,D, t,T, b,B, s,S, c,C,//quarks
l,L, //tau lepton, antitau lepton
e,E, //electron,positron
g, //gluon
p, //photon
m,M, //muon, antimuon
n, N, //neutrino, antineutrino
};
void main(string[] v) {
int[26]c;//particle counts
c[0]=to!int(v[1]);//mandatory argument
string format_particle(ulong i) {
string[84] strs;
strs[65..$]=["anti"," boson","charm ","down ","electron",/*f*/"Z",
"gluon","Higgs",/*i*/"top ",/*j*/"bottom ",/*k*/"up ","tau lepton","muon","neutrino",/*o*/"W","photon","quark",/*r*/"positron","strange "];
string[] fmt = [
"HB","OB","FB",//bosons
"KQ","KAQ",//up
"DQ","DAQ",//down
"IQ","IAQ",//top
"JQ","JAQ",//bottom
"SQ","SAQ",//strange
"CQ","CAQ",//charm
"L","AL",//Tau leptons
"E","R",//electron/positron
"G", //gluon
"P", //photon
"M","AM", //muon, antimuon
"N", "AN", //neutrino, antineutrino
];
//In the golfed version, we instead use X to delimit strings and call split to convert to array.
return to!string(c[i])
~ " " ~ fmt[i].map!(a=>strs[a]).join
~ ((c[i]>1) ? "s" : "");
}
/* if there exist any of particle `i`,
it decays with probability `p`.
into the particles specified in `v[j]`
where `j` is drawn from distribution `decay_probs` */
void decay(int i, float p, float[] decay_probs, P[] v...) {
decay_probs ~= 2;//1.0, but with a margin for error in case of floating point precision issues
if (c[i] && U()<p){
c[i]--;
p=U();
foreach(j,q; decay_probs) {
if (p<q) {
c[v[2*j]]++;
c[v[2*j+1]]++;
/*writef("Decay %s, Add: %s, %s\n",
format_particle(i),
format_particle(v[2*j]), format_particle(v[2*j+1]));*/
break;
}
}
}
}
int y=0;
while(1) {
string commas(T)(T s) {
return (s.length > 1)
? s[0..$-1].join(", ") ~ " and " ~ s[$-1]
: s.join(" and ");
}
//print line for particle `d`
writef("The universe contains "
~ commas(
iota(0,c.length)
.filter!(i=>c[i])
.map!(i=>format_particle(i))
.array) ~ ".\n");
y++;
if(c[P.h]+c[P.w]+c[P.t]+c[P.T]<1)break;
F[] u = [1/3.0,2/3.0];
decay(P.h, .000433,
[.000216,.000460,.00157,.0038,.0197,.0524,.1228,.211,.352],
P.t,P.T, P.m,P.M, P.z,P.p, P.p,P.p, P.z,P.z, P.c,P.C, P.l,P.L, P.g,P.g, P.w,P.w, P.b,P.B);
decay(P.z, .5,
[.118,.236,.388,.54,.692,.726,.76,.794],
P.n,P.N, P.e,P.E, P.m,P.M, P.l,P.L, P.d,P.D, P.s,P.S, P.b,P.B, P.u,P.U, P.c,P.C);
decay(P.w, .5, u, P.E,P.n, P.M,P.n, P.L,P.n);
decay(P.t, .1295, u, P.w,P.d, P.w,P.s, P.w,P.b);
decay(P.T, .1295, u, P.w,P.D, P.w,P.S, P.w,P.B);
//In the golfed version, the list of enums is replaced by a string: each char is 65 + the enum's value. D() is adjusted to subtract it again.
}
writef("Simulation ended after %f yoctoseconds.\n", y/10.0);
}
```
[Answer]
# [Kotlin](https://kotlinlang.org): 1330 - 10% = 1197 bytes
My first ever code golf submission; very inefficient due to lists being golfier than maps, but seemingly correct! Works on JVM or JS implementation, and takes an (optional) argument.
```
operator fun String.minus(p:Pair<String,String>)=replace(p.first,p.second)
operator fun<A,B>A.div(b:B)=to(b)
val l=1.0
val e=l/3
val t=l-e
enum class V(val c:Double=.0,vararg val v:Pair<Pair<V,V>,Double>){E,F,G,P,L,AL,M,AM,N,AN,_Q,_AQ,CQ,CAQ,DQ,DAQ,SQ,SAQ,UQ,UAQ,WB(.5,P/N/e,AM/N/t,AL/N/l),TQ(.1295,WB/DQ/e,WB/SQ/t,WB/_Q/l),TAQ(.1295,WB/DAQ/e,WB/SAQ/t,WB/_AQ/l),ZB(.5,N/AN/.206,E/P/.24,M/AM/.274,L/AL/.308,DQ/DAQ/.46,SQ/SAQ/.612,_Q/_AQ/.764,UQ/UAQ/.882,CQ/CAQ/l),HiggsB(.000433,_Q/_AQ/.648,WB/WB/.789,G/G/.8772,L/AL/.9476,CQ/CAQ/.9803,ZB/ZB/.9962,F/F/.99843,ZB/F/.99954,M/AM/.999784,TQ/TAQ/l);fun d()=if(Math.random()<c)with(Math.random()){v.first{this<it.second}.first.toList()}else listOf(this)
override fun toString()=name-"_"/"bottom "-"A"/"anti"-"B"/" boson"-"C"/"charm "-"D"/"down "-"E"/"electron"-"F"/"photon"-"G"/"gluon"-"L"/"tau lepton"-"N"/"neutrino"-"M"/"muon"-"P"/"positron"-"Q"/"quark"-"S"/"strange "-"T"/"top "-"U"/"up "}
fun main(vararg a:String){var t=.0
var l=List(a.lastOrNull()?.toInt()?:1){V.HiggsB}
while(true){++t
var s="The universe contains"
with(l.toSet()){forEachIndexed{i,p->l.count{it==p}.let{s+=(" $it $p")
if(it>1)s+='s'
s+=when(size){i+1->"."
i+2->" and"
else->","}}}}
println(s)
if(l.filter{it.c>0}.isEmpty())break
for(p in l){l-=p;l+=p.d()}}
t/=10
print("Simulation ended after $t yoctoseconds.")}
```
# Less Golfed Version
```
operator fun String.minus(p:Pair<String,String>)=replace(p.first,p.second)
operator fun<A,B>A.div(b:B)=to(b)
val l=1.0
val e=l/3
val t=l-e
enum class V(val c:Double=.0,vararg val v:Pair<Pair<V,V>,Double>){
E,F,G,P,L,AL,M,AM,N,AN,_Q,_AQ,CQ,CAQ,DQ,DAQ,SQ,SAQ,UQ,UAQ,
WB(.5,P/N/e,AM/N/t,AL/N/l),
TQ(.1295,WB/DQ/e,WB/SQ/t,WB/_Q/l),
TAQ(.1295,WB/DAQ/e,WB/SAQ/t,WB/_AQ/l),
ZB(.5,N/AN/.206,E/P/.24,M/AM/.274,L/AL/.308,DQ/DAQ/.46,SQ/SAQ/.612,_Q/_AQ/.764,UQ/UAQ/.882,CQ/CAQ/l),
HiggsB(.000433,_Q/_AQ/.648,WB/WB/.789,G/G/.8772,L/AL/.9476,CQ/CAQ/.9803,ZB/ZB/.9962,F/F/.99843,ZB/F/.99954,M/AM/.999784,TQ/TAQ/l);
override fun toString()=name-
"_"/"bottom "-
"A"/"anti"-
"B"/" boson"-
"C"/"charm "-
"D"/"down "-
"E"/"electron"-
"F"/"photon"-
"G"/"gluon"-
"L"/"tau lepton"-
"N"/"neutrino"-
"M"/"muon"-
"P"/"positron"-
"Q"/"quark"-
"S"/"strange "-
"T"/"top "-
"U"/"up "
fun d()=if(Math.random()<c)
with(Math.random()){
v.first{this<it.second}.first.toList()
}else listOf(this)
}
fun main(vararg a:String){
var t=.0
var l=List(a.lastOrNull()?.toInt()?:99){V.HiggsB}
while(true){
++t
var s="The universe contains"
with(l.toSet()){
forEachIndexed{i,p->
l.count{it==p}.let{
s+=(" $it $p")
if(it>1)s+='s'
s+=when(size){
i+1->"."
i+2->" and"
else->","
}
}
}
}
println(s)
if(l.filter{it.c>0}.isEmpty())break
for(p in l){l-=p;l+=p.d()}
}
t/=10
print("Simulation ended after $t yoctoseconds.")
}
```
[Answer]
## F#, 1993 1908 bytes - 10% = 1718 bytes
```
open System
let r=new Random()
let p()=r.NextDouble()*100.0
type P=
|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
let q="quark"
let n=dict[(A,"Higgs boson");(B,"Bottom "+q);(C,"Bottom anti"+q);(D,"Top "+q);(E,"Top anti"+q);(F,"W boson");(G,"Gluon");(H,"Tau lepton");(I,"Anti-tau lepton");(J,"Charm "+q);(K,"Charm anti"+q);(L,"Z boson");(M,"Photon");(N,"Muon");(O,"Antimuon");(P,"Antiquark");(Q,"Positron");(R,"Neutrino");(S,"Antineutrino");(T,"Electron");(U,"Down"+q);(V,"Down anti"+q);(W,"Strange "+q);(X,"Strange anti"+q);(Y,"Up "+q);(Z,"Up anti"+q);]
let c(u:P seq)=Option.isSome(Seq.tryFind(fun p->Seq.contains p [A;F;L;D])u)
let w()=
if r.Next(2)=0 then
let p=r.Next(3)
if p=0 then[Q;R]elif p=1 then[O;R]else[I;R]
else[F]
let t a=
if p()<12.95 then
let p=r.Next(3)
if p=0 then[F;U]elif p=1 then[F;W]else[F;B]
else[a]
let h()=
if p()<0.0433 then
let p=p()
if p<64.8 then[B;C]elif p<78.9 then[F;F]elif p<87.72 then[G;G]elif p<94.76 then[H;I]elif p<98.03 then[J;K]elif p<99.62 then[L;L]elif p<99.843 then[M;M]elif p<99.954 then[L;M]elif p<99.9784 then[N;O]else[D;E]
else[A]
let z()=
if r.Next(2)=0 then
let p=p()
if p<20.6 then[R;S]elif p<24.0 then[T;Q]elif p<27.4 then[N;O]elif p<30.8 then[H;I]elif p<46.0 then[U;V]elif p<61.2 then[W;X]elif p<76.4 then[B;C]elif p<88.2 then[Y;Z]else[J;K]
else[F]
let d u=List.map(fun p->if p=A then h()elif p=F then w()elif p=L then z()elif p=D||p=E then t p else[p])u|>List.concat
let b h=List.init h (fun x->id A)
let o u=
let e=List.countBy id u|>List.map(fun t->n.[fst t],snd t)|>List.map(fun t->
if snd t>1 then(snd t,(fst t)+"s")else snd t,fst t)
String.Join(", ",(List.map(fun x->(string(fst x))+" "+(snd x))e))|>printfn"The universe contains %s."
let [<EntryPoint>]m a=
let mutable u=int a.[0]|>b
let mutable t=0
while c u do
o u
u<-d u
t<-t+1
o u
(float t)/10.0|>printfn"Simulation ended after %f yoctoseconds."
0
```
[Try it online!](https://tio.run/##jZVbb@o4EMff8yksS0dKtiELlHJZEyQol164lUtpi3hIiSnRgh0SZylH/u4cx064nH3YfYk8P4/nPx6PnVWYWdIAH4/UxwSMDyHDW22DGQhsgvdg5BCXbnVDIl837MDq42/WpNHnBuvGH7ls1spq7OBjMLQ1wOu8we95k7d4m3f4A3/kT/yZd3mP9/mAD/kLH/Exn/Apf@Uz/sbf@YcMvbPhLnKCv6G0iO16SzbX6yZ88L6@QvBJQ0qggfSGCRuUMboF8GYn7PuT7RDmKdY04YT6iUNLGefZtgln53gdE3Y2kRo/CFcnAhvsMwUeTVgX6zLsij6Z8H7tBGkGz6l5luia8OMs0TPhcE2TxX0T9hK5gYq@TcyhMlUVhP0iltHQY4GaHpmwjyMWeITG5lh5kws0MWFrg5fpgqkJm3RPVEavyrjIcWbCMQsc8oWTfbydwdnr3YTTtJIfcnyaW8iTWurRX0MQ4p1hD3zmUWJ54ZhusT7GO4sFh7ZHXH0VEeBnajFaUsIcj4TAB/M6aqMuai6MSLXXXrSXBrwVUD2m5w07C9gaEw0A2X5J8@m3hiDCz0/m5y9otMAbSXKKDCQJ8fxRDDQgh22VMgOOkhHtXM3lrcrd/xNpo@lvIm00UyJt1EhFHCWyTvcSi4grUri9vVYRPIlfLRassgrYQPeJRLVUtiqpSjuF5ZJVyivaQZ2UVgpWqajoA3o80bKVVZrzJ/R8ohWrmEToou4FLRcS5x7qXeDKXSH1vsKlcsL7aKBq0ESttAZ1VYOf/3meF0XIZ61kDyM0TpXyBSsp/gS9nGDJutKW8Dab1vCiBIViunyKXlNYzFlJAWbo7VTtYhrz4gjK5dTzHX2oTcaVvO4mF0R21wuZtXX8tNFlj9Tl0rgRkqZpK7A/ga4CP0@gyblvtxQV5VE6vrgfvCYlxOVZOgxI3U@wVroe8US7Aan9LbRdUFfXiYrMNFlobCfLI8IaByBc0ohp0ixTI9Z8FYrbsTBD4gJm/NtDHFV8VnK6pq6ALg1TlyuNGxhCI05a@ZiKamAcv1Ff1hP1iA5NAE39KrTIWg@li4zzbYhA4s2RsYWBDZGLL6bZisDJGoOIeP/gQKicHpMfoaV@HPNqi4hXZyiUWG2xlTc95tuIOeKHJSoiJoBjzbMLXvu8nmN2VgP7tSeGSxABl4r9ihqKb1TNuHLAqhl2k9MU1lcb6sQb/DMnLvg5xbF40jdO/BYCTFzsAmfFcAB@rMCBLhkNsUjbjRMG2ePxePcL)
Ungolfed it looks like this:
[![That's a lot of particles...](https://i.stack.imgur.com/MQ9mb.jpg)](https://i.stack.imgur.com/MQ9mb.jpg)
[Answer]
Quite a long submission.
Not that much golfed but still shorter than the other python one.
Take initial amount of Higgs as input.
# [Python 3](https://docs.python.org/3/), ~~1134~~ 1120 bytes - 10% = ~~1020.6~~ 1008 points
```
from random import *
n=int(input())
M=random
seed()
def D(i):
for a in i:d[a]=d[a]+1 if a in d else 1
def X(p,A,B):
for l in d[s]*' ':
n[0]=1
if M()<=p:d[s]-=1;r=M();D(A[B.index(next(x for x in B if x>r))])
s=lambda x:x.replace(Z,'')
Z,C,e,i,k,m,p,t,v='anti, boson,electron,gluon,neutrino,muon,photon,tau lepton,positron'.split(',')
B=' '+Z+'quark'
a='bottom'+B
c='charm'+B
f='down'+B
h="Higgs"+C
o='top'+B
u=Z+k
w="W"+C
x=Z+m
y=Z+t
z='Z'+C
S='strange'+B
U='up'+B
b,g,j,q,Q,T=map(s,[a,f,c,o,S,u])
d={h:n,0:0}
I=0
A=[(a,b),(w,w),(i,i),(t,y),(c,j),(z,z),(p,p),(z,p),(m,x),(o,q)]
B=[.648,.789,.8772,.9476,.9803,.9962,.99843,.99954,.999784,1]
O=[[k,v],[k,x],[k,y]]
E=[1/3,2/3,1]
F=[(u,k),(e,v),A[8],A[3],(g,f),(S,Q),A[0],(T,U),(c,j)]
G=[.206,.24,.274,.308,.46,.612,.764,.882,1]
H=[[w,g],[w,Q],[w,a]]
n={1}
while n:
I+=1
n={}
P=dict(d)
for s in P:
if s==h:X(.00433,A,B)
if s==w:X(.5,O,E)
if s==z:X(.5,F,G)
if s in [q,o]:X(.1295,H,E)
l='The universe contains '
for s in d:l+= str(d[s])+' '+s+'s'*(d[s]>1)+', ' if d[s]>0 else ''
print(l[:-2]+'.')
print('Simulation ended after '+str(I/10)+' yoctoseconds.')
```
[Try it online!](https://tio.run/##TZNNc5swEIbv@hWaXARhS8F2bEyrzsT9Sg6dNpN02jHDQTayrRokAiLG6eS3pyvcr4NfrR602he8Wx/tzujx8/OmMRVthC5wUVVtGkvPieZKW0/purOe75NP/HSAtFIWnk8KuaHvPOWnhG5MQwVVmqq0yETOnQQxVZsTLagsW0njIeW7V8MlLP6klcOBrM3PGWXIqM6inMcYYPYnz3/N69Q9fsHjVw1H8Oqdd5ktQqUL2Xta9tbrh4t6d9HCZfVvGt/PfdLyUlSrQtA@7cNG1qVYS28JjPlkCW9BgoI9VFCDhQfOhLYK6Mq0RoMs5do2GGzLDlXLzjZKG6jcrt4Zi4sVHS1l7cLatModZ2Fbl8p6DLDEguMLBcuA3Xei2TMiOFsZa03FggVZc7beiWaIN5wV5qBduONnV2q7bc@Ct8RwZk3taMeXwZ4c@Nk3x3vcVeSIaskjZ0uG7Jaz1uK/s5Xu/FfOuiFxBVv4AfdwA3e8ErXXQiZgA2swcAsdfqGC/9ylGqI0eiLXPCKXPPMErHzwDnBAVaBQLRxR1/AD9REeUWuoh9hpBT2qgXs/x3fOwukkgXCWzCFMZrMRhPPJbIqaRGPU@dSReTIZNvOLybDMkgnEOfnMs2wPDzmg9oMe85y851n8cgwj/OGZD@iwgz1WlPDgw2WW5CjjHLwtbJDewo2jEYI7@Prbdk4@orFRhD5GWHE0QxlHaHOCZBqjpdkUUZKMXIkrtHGALRo4wM2gAm1o/jN@IoedKiXV2KfXgWtSpE@EfuGFWluv8E8t3bpO/JKeWrjlfJd@98IomozHQ@P/5QfHL@AzvP/HHk/sA3z8w9xl2T2Y3D2JR/MLuBoSSs7udpJ2Wj3IBqdrbbQVSreU/eeiSMuAU@wNz82QH7iWbAPWsvMBvIkRAWWu0LCPTpPK8I66cdNfZumLUR6wEDv6RNitqrpSWGU0lTiEBRUbKxt3MZa5fhlHrszRrK1pJZoqWsx9fo6jXw "Python 3 – Try It Online")
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
# Challenge
Draw the Olympic Games logo...
![Olympic Games logo](https://i.stack.imgur.com/FroIE.png)
...as character (e.g. ASCII) art!
# Sample Output
```
* * * * * * * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * *
* * * *
* * * * * *
```
Your art doesn't have to look exactly like mine, but it has to represent the Olympic rings well enough that it's recognizable.
# Rules
* The program must write the art to the console.
* Shortest code (in bytes, any language) wins.
* **A solution that prints rings in their respective colors (or a close representation) will be awarded a minus-twenty-point bonus.**
The winner will be chosen on February 23rd at the end of the 2014 Winter Olympics.
---
# Winners
* **Gold**: marinus - [APL, 62 points](https://codegolf.stackexchange.com/a/19053/1654)
* **Silver**: Ayiko - [Perl 6, 75 points](https://codegolf.stackexchange.com/a/19005/1654)
* **Bronze**: evuez - [Python, 107 points](https://codegolf.stackexchange.com/a/19003/1654)
* **Popular choice**: Danko Durbić - [Commodore 64 BASIC](https://codegolf.stackexchange.com/a/19009/1654)
[Answer]
## Commodore 64 BASIC
Writing directly in the screen and color memory.
![Program](https://i.stack.imgur.com/PbKOc.png)
**Output:**
![Output](https://i.stack.imgur.com/gmn8m.gif)
---
[Here's how you do this with sprites.](https://codegolf.stackexchange.com/questions/19050/olympic-games-logo-free-style-edition/19159#19159)
[Answer]
## [HTML Fiddle](http://jsfiddle.net/briguy37/hT9vP/) - 48, 35, 33 characters (Thanks @Dom and @cnst!)
```
OOO<p style="margin:-15px 6px">OO
```
Output:
![enter image description here](https://i.stack.imgur.com/wvzNG.png)
[Answer]
## BASH in color - 271 - 20 = 251 – With entangled rings ;P
```
o='_4mGA _0mGA _1mG\n _4m/A \A _0m/A \\_1mA /A \\\n_4mD_3m---_0mD_2m---_1mD\n _4m\A_3m/_4m/A_0m\\_3m\\A_2m/_0m/A_1m\\_2m\A _1m/\n_4mG_3mD_0m---_2mD_1m---\n_3m A\A /A _2m\A /_1m\n _3mA G A_2mG\n';o=${o//D/|A |};o=${o//A/ };o=${o//G/ ---};printf "${o//_/\\e[3}"
```
Result:
![enter image description here](https://i.stack.imgur.com/9pt9n.png)
---
### And the *for fun* of it one: 61 - 20 = 41.
```
x='_4mO_3m^_0m0_2m^_1mO\n_3m V _2mV\n';printf "${x//_/\\e[3}"
```
![enter image description here](https://i.stack.imgur.com/d8ZlH.png)
---
[Answer]
# Sinclair BASIC on the ZX Spectrum 48K (261 bytes)
BASIC listing:
![BASIC listing](https://i.stack.imgur.com/qFs8J.png)
Final result:
![Result](https://i.stack.imgur.com/rHop7.png)
Program running and code measuring:
![Program running](https://i.stack.imgur.com/eW96H.gif)
BASIC listing in text format:
```
5 INK VAL "7": CLS
10 LET a=VAL "42": LET b=VAL "131": LET c=VAL "40": CIRCLE INK SGN PI;a,b,c: CIRCLE INK PI-PI;a+a+a,b,c: CIRCLE INK VAL "2";VAL "210",b,c
20 LET a=VAL "84": LET b=VAL "87": CIRCLE INK VAL "6";a,b,c: CIRCLE INK VAL "4";a+a,b,c
30 FOR l=PI-PI TO VAL "21": FOR c=PI-PI TO VAL "31": IF ATTR (l,c)<>VAL "63" THEN PRINT INK VAL "8";AT l,c;"*"
40 NEXT c: NEXT l
```
TAP file with the program, suitable for emulators or real machine using DivIDE or DivMMC:
<http://www.zxprojects.com/images/stories/draw_the_olympics_flag.tap>
[Answer]
So I didn't actually read properly, it's ASCII-art, so I guess this is invalid. Oops!
---
## HTML 121 (141 - 20)
```
<pre style=line-height:3px;letter-spacing:-3px><font color=#06f>O <font color=#000>O <font color=red>O
<font color=#fa0>O <font color=#193>O
```
In Chrome:
![What is this! An Olympic flag for ants?](https://i.stack.imgur.com/tdbOh.png)
## PHP 103 (123 - 20)
```
<pre style=line-height:3px;letter-spacing:-3px><?=($f='<font color=')."#06f>O ${f}#000>O ${f}red>O
${f}#fa0>O ${f}#193>O";
```
[Answer]
# Ruby: 198 characters - 20 = 178
```
a=[*0..9].map{[' ']*35}
d=->c,x,y=0{11.times{|i|7.times{|j|a[y+j][x+i]="^[[3#{c}m#^[[0m"if[248,774,1025,1025,1025,774,248][j]&1<<i!=0}}}
d[4,0]
d[0,12]
d[1,24]
d[3,6,3]
d[2,18,3]
$><<a.map{|r|r*''}*$/
```
(Note that `^[` are single characters.)
Sample run:
![olympic games logo](https://i.stack.imgur.com/Muutr.png)
[Answer]
# Mathematica - 185
```
c[x_, y_] :=
Table[Boole[Abs[(i - x)^2 + (j - y)^2 - 16] < 4], {i, 0, 15}, {j, 0,
30}]
MatrixForm@
Replace[Blue c[5, 4] + Black c[5, 14] + Red c[5, 24] +
Yellow c[9, 9] + Green c[9, 19], {0 -> "",
c_ + _ | c_ :> Style["*", c]}, {2}]
```
Here is the ouput
![enter image description here](https://i.stack.imgur.com/CKXA6.png)
Another version, based on rasterization of vector graphics
```
MatrixForm@
Replace[ImageData@
Rasterize[
Graphics[{Blue, Circle[{4, 9}, 4], Black, Circle[{14, 9}, 4], Red,
Circle[{24, 9}, 4], Yellow, Circle[{9, 4}, 4], Green,
Circle[{19, 4}, 4]}], ImageSize -> {30, 15}], {c_ :>
Style["*", RGBColor@c]}, {2}]
```
![enter image description here](https://i.stack.imgur.com/DPrxq.png)
[Answer]
PostScript, 203 (-20 = 183)
```
%!
/Courier findfont 12 scalefont setfont
/l { setrgbcolor translate 20 { 0 30 moveto (*) show 18 rotate } repeat } def
140 200 0 0 1 l 45 -30 1 1 0 l 45 30 0 0 0 l 45 -30 0 1 0 l 45 30 1 0 0 l
showpage
```
I maintain that this counts as "ASCII art", though it doesn't write to the console. Output:
![Olympic Rings](https://i.stack.imgur.com/ViILg.png)
This could be golfed a little more.
[Answer]
## Windows Command Script - 112 percent bytes
```
%1%0 @echo. set
%2.= oooo
%2,=o o
%1%.%%.%%.%&%1%,%%,%%,%&%1o %.%%.% o&%1%.%%.%%.%&%1 %,%%,%&%1 %.%%.%
```
![100% Olympic rings](https://i.stack.imgur.com/KEthe.png)
**And of course, the obligatory cheat'ish version - 4 bytes**
```
%~n0
```
saved as:
```
@echo. oooo oooo oooo&echo.o oo oo o&echo.o oooo oooo o&echo. oooo oooo oooo&echo. o oo o&echo. oooo oooo.cmd
```
[Answer]
## APL (82) (-20 = 62)
Edit: for a change, this program is simple enough that [TryAPL](http://tryapl.com) will touch it, so you can run it there (just paste the line in).
Not sure if I can claim the 'color' bit, I'm representing them all differently though.
```
2/' ▓█░▓▒'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]
```
The APL console doesn't support color, so I used shaded block characters (assigning any kind of other ASCII art would be as simple as replacing the characters at the beginning of the string.)
They should look like unbroken circles (depending on your font.)
```
2/' ▓█░▓▒'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]
‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì ‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà‚ñà ‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì
‚ñì‚ñì ‚ñì‚ñì ‚ñà‚ñà ‚ñà‚ñà ‚ñì‚ñì ‚ñì‚ñì
‚ñì‚ñì ‚ñì‚ñì ‚ñà‚ñà ‚ñà‚ñà ‚ñì‚ñì ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë ‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë ‚ñì‚ñì ‚ñà‚ñà ‚ñë‚ñë ‚ñí‚ñí ‚ñà‚ñà ‚ñì‚ñì ‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë ‚ñì‚ñì ‚ñà‚ñà ‚ñë‚ñë ‚ñí‚ñí ‚ñà‚ñà ‚ñì‚ñì ‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë ‚ñì‚ñì ‚ñà‚ñà ‚ñë‚ñë ‚ñí‚ñí ‚ñà‚ñà ‚ñì‚ñì ‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë ‚ñì‚ñì ‚ñà‚ñà ‚ñë‚ñë ‚ñí‚ñí ‚ñà‚ñà ‚ñì‚ñì ‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì ‚ñë‚ñë ‚ñì‚ñì ‚ñà‚ñà ‚ñë‚ñë ‚ñí‚ñí ‚ñà‚ñà ‚ñì‚ñì ‚ñí‚ñí ‚ñì‚ñì
‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñë‚ñë‚ñì‚ñì‚ñì‚ñì ‚ñà‚ñà‚ñë‚ñë‚ñà‚ñà‚ñí‚ñí‚ñà‚ñà‚ñà‚ñà ‚ñì‚ñì‚ñí‚ñí‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì‚ñì
‚ñë‚ñë ‚ñë‚ñë ‚ñí‚ñí ‚ñí‚ñí
‚ñë‚ñë ‚ñë‚ñë ‚ñí‚ñí ‚ñí‚ñí
‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë‚ñë ‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí‚ñí
```
Or:
```
2/' bByRg'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]
bbbbbbbbbbbb BBBBBBBBBBBB RRRRRRRRRRRR
bb bb BB BB RR RR
bb bb BB BB RR RR
bb yyyyyyyyyyyy gggggggggggg RR
bb yy bb BB yy gg BB RR gg RR
bb yy bb BB yy gg BB RR gg RR
bb yy bb BB yy gg BB RR gg RR
bb yy bb BB yy gg BB RR gg RR
bb yy bb BB yy gg BB RR gg RR
bbbbbbyybbbb BByyBBggBBBB RRggRRRRRRRR
yy yy gg gg
yy yy gg gg
yyyyyyyyyyyy gggggggggggg
```
[Answer]
# Another attempt in Perl, ~~130~~ 120
Thanks to manatwork for helping with this
```
for(qw(15005 40410 802a0 80a28 41414 15005 808 2a0)){$s=sprintf"%20b",hex;$s=~y/01/ #/;print$s.substr(reverse($s),1).$/}
```
Output:
```
# # # # # # # # #
# # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # #
# # # #
# # # # # #
```
[Answer]
# Python: ~~157~~ ~~140~~ ~~138~~ ~~133~~ ~~122~~ 107 characters
## 107
(thanks to [manatwork](https://codegolf.stackexchange.com/questions/18986/draw-the-olympic-games-logo#comment37393_19003))
```
for o in"jzd360 1zlpwci 3ydgr29 20pzv5u jzd360 149ytc b8n40".split():print bin(int(o,36))[2:].rjust(34,'0')
```
sample output:
```
0001001000000001001000000001001000
0100000010000100000010000100000010
1000000001001000000001001000000001
0100000110000110000110000110000010
0001001000000001001000000001001000
0000000100000010000100000010000000
0000000001001000000001001000000000
```
## 157
```
print'\n'.join(['{0:b}'.format(o).rjust(39,'0') for o in [45099909288,137984246274,275230249985,276241138945,137984246274,45099909288,1078001920,352343040]])
```
## 122
(just started this one, I will try to improve it)
```
h=lambda x:bin(int("15bb511iun9aqulod22j8d4 ho8skh "[x::8],36))[2:].rjust(20)
for x in range(8):print h(x)+h(x)[::-1][1:]
```
---
### with better output: 120 characters
```
for o in"jzd360 1zlpwci 3ydgr29 20pzv5u jzd360 149ytc b8n40".split():print bin(int(o,36))[2:].replace('0',' ').rjust(34)
```
sample output:
```
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 11 11 11 11 1
1 1 1 1 1 1
1 1 1 1
1 1 1 1
```
[Answer]
# Perl, ~~177~~ 163
An improved version thanks to Dom Hastings:
```
$s=$"x3;print" .-~-. "x3 .$/." /$s \\"x3 .$/."|$s$s "x4 ."
\\$s ./~\\.$s./~\\.$s /
'-./'$s'\\-/'$s'\\.-'
"."$s |$s"x3 ."
$s "." \\$s /"x2 ."
$s"."$s'-.-'"x2;
```
Output:
```
.-~-. .-~-. .-~-.
/ \ / \ / \
| | | |
\ ./~\. ./~\. /
'-./' '\-/' '\.-'
| | |
\ / \ /
'-.-' '-.-'
```
[Answer]
# C, 257 bytes
```
#include <stdio.h>
d(i,j){int r=35;float x=r,y=0;while(--r>0){char s[8]={29,(((int)y+j)/32)+32,(((int)y+j)%32)+96,(((int)x+i)/32)+32,(((int)x+i)%32)+64,31,'.',0};puts(s);x-=0.2*y;y+=0.2*x;}}main(){d(140,200);d(185,170);d(230,200);d(275,170);d(320,200);}
```
This could have been golfed a bit more.
This has to be run on a Tektronix 4010 (or an emulator such as xterm -t). Output:
![Ooutput](https://i.stack.imgur.com/tUidi.png)
This is indeed ASCII art, since those are all '.' characters. And it does output to the console, as requested. Some Tektronix emulators support colour. Mine didn't, so I couldn't do that.
[Answer]
# Java, ~~181~~ ~~179~~ ~~161~~ 156 bytes
```
enum M{M;{System.out.print(new java.math.BigInteger("2b13bp4vx9rreb1742o0tvtpxntx0mgsfw48c4cf",36).toString(2).replaceAll(".{29}","$0\n"));System.exit(1);}}
```
(Won't compile on jdk 1.7, requires 1.6 or lower)
The output:
```
11100011111110001111111000111
10111110111011111011101111101
01111111000111111100011111110
10111100111001110011100111101
11100011111110001111111000111
11111101111101110111110111111
11111111000111111100011111111
```
Definitely not a winner, but come on, it's *java*.
[Answer]
# Haskell, 200
```
main=mapM(putStrLn.map(\b->if b then '#' else ' '))$(map.map)(\(x,y)->or$map(\(n,m)->(<2).abs.(18-)$sqrt$(n-x)^2+(m-y*2)^2)$[(20,20),(60,20),(100,20),(40,40),(80,40)])$map(zip[0..120].repeat)[0..30]
```
Output:
```
################# ################# #################
########### ########### ########### ########### ########### ###########
####### ####### ####### ####### ####### #######
##### ##### ##### ##### ##### #####
##### ##### ##### ##### ##### #####
##### ##### ##### ##### ##### #####
##### ##### ##### ##### ##### #####
#### #### #### #### #### ####
#### #### #### #### #### ####
### ### ### ### ### ###
#### ################# ################# ####
#### ########### ########### ########### ########### ####
##### ####### ##### ##### ####### ####### ##### ##### ####### #####
##### ##### ##### ##### ##### ##### ##### ##### ##### #####
##### ##### ##### ##### ##### ##### ##### ##### ##### #####
##### ##### ##### ##### ##### ##### ##### ##### ##### #####
####### ##### ####### ####### ##### ##### ####### ####### ##### #######
########### ########### ########### ########### ########### ###########
################# ################# #################
### ### ### ###
#### #### #### ####
#### #### #### ####
##### ##### ##### #####
##### ##### ##### #####
##### ##### ##### #####
##### ##### ##### #####
####### ####### ####### #######
########### ########### ########### ###########
################# #################
```
golfed out of:
```
{-# LANGUAGE NoMonomorphismRestriction #-}
olympMids = [(1,1),(3,1),(5,1),(2,2),(4,2)]
circleRadius = 0.9
circleBorder = 0.1
scaleFactor = 20
verticalScale = 0.5
distance :: Floating a => (a,a) -> (a,a) -> a
distance (x,y) (x2,y2) = sqrt $ (x2-x)^2 + (y2-y)^2
match :: (Floating a, Ord a) => (a,a) -> (a,a) -> Bool
match v v2 = (<circleBorder) . abs . (circleRadius-) $ distance v v2
matchOlymp :: (Floating a, Ord a) => (a,a) -> Bool
matchOlymp v = or $ map (match $ scale v) $ olympMids
where
scale (x,y) = (x / scaleFactor, y / scaleFactor / verticalScale)
board :: (Enum a, Num a) => a -> a -> [[(a, a)]]
board lx ly = map (zip [0..lx] . repeat) [0..ly]
printOlymp = mapM (putStrLn . map to) $ (map.map) matchOlymp $ board 120 30
main = printOlymp
to :: Bool -> Char
to True = '#'
to False = ' '
```
[Answer]
## Ruby, 9
```
p"\044"*5
```
**#satire**
The rules allow for art that does not look exactly like the example, but it must *"represent the Olympic rings well enough that it's recognizable"*.
You may recognize this representation of the Olympic Games logo.
[Answer]
# Javascript - 170 ~~185~~ ~~189~~ Chars
```
'jzd36071zlpwci73ydgr29720pzv5u7jzd3607149ytc7b8n40'.split(7).map(function(x){a=parseInt(x,36).toString(2);console.log((Array(35-a.length).join(0)+a).replace(/0/g,' '))})
```
**Output:**
```
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
1 11 11 11 11 1
1 1 1 1 1 1
1 1 1 1
1 1 1 1
```
# 2nd Javascript - 25 Chars
```
console.log('O O O\n O O')
```
**Output:**
```
O O O
O O
```
The second is lazy
[Answer]
**Binary! (265 CHARS)**
```
0001111100000000111110000000011111000
0100000001000010000000100001000000010
1000000001111100000000011111000000001
0100000011000011000001100001100000010
0001111100000000111110000000011111000
0000000010000001000001000000100000000
0000000001111100000000011111000000000
```
It is too large to win, but at least it looks cool!
[Answer]
# PHP - 99 (-20?)
```
bbbb #### rrrr
b b# #r r
b ybyy g#gg r
bbyb ##g# rrrr
y yg g
yyyy gggg
```
That is definitely recognizable. I say that my "colors" count; it's a close representation.
If you don't like that, then here is
# GolfScript - 101 (-20?)
```
' bbbb #### rrrr
b b# #r r
b ybyy g#gg r
bbyb ##g# rrrr
y yg g
yyyy gggg'
```
[Answer]
# Bash + ImageMagick: 163 characters
```
e=ellipse
c=,10,5,0,360
convert -size 70x20 xc:black +antialias -stroke white -fill none -draw "$e 10,5$c$e 34,5$c$e 58,5$c$e 22,10$c$e 46,10$c" xpm:-|tr -dc ' .
'
```
Sample output:
```
.
........... ........... ...........
.... .... .... .... .... ....
... ... ... ... ... ...
.. .. .. .. .. ..
.. .. .. .. .. ..
. ........... ........... .
.. ...... ...... ...... ...... ..
.. ... .. .. ... ... .. .. ... ..
... .. ... ... .. .. ... ... .. ...
.... ...... ...... ...... ...... ....
........... ........... ...........
.. .. .. ..
.. .. .. ..
... ... ... ...
.... .... .... ....
........... ...........
```
[Answer]
## Perl 6: ~~112~~ ~~77~~ 56 characters, 75 bytes
```
say flip .ord.base(2).trans("01"=>" @")for"úúú¢¢¢ÒÉ£°¶∂≤úúú‰îê„£†".comb
```
* Unicde strings! (above string is "\x1C71C\x228A2\x438E1\x26DB2\x1C71C\x4510\x38E0")
* `.comb` gives a List of the separate characters in a String (without argument anyway)
* `.ord` gives character code number from character
* `.base(2)` returns a string with base-2 encoding of that Int
* `.trans` replaces the digits with space and @ for better visibility
* `flip` reverses the characters of a string so that missing leading 0's don't mess up the drawing.
```
@@@ @@@ @@@
@ @ @ @ @ @
@ @@@ @@@ @
@ @@ @@ @@ @@ @
@@@ @@@ @@@
@ @ @ @
@@@ @@@
```
---
edit2: newer solution using qwote words and base-36 encoded
```
say flip :36($_).base(2).trans("01"=>" @")for<2HWC 315U 5XI9 3ESY 2HWC DN4 B8G>
```
* `<ABC DEF GHI>` is a quote-words syntax in perl6, so you get a list of Strings
* `:36($_)` creates an Int from a base-36 encoded string in `$_` (`for` loop default variable)
---
edit: old solution has nicer (copied) drawing but is longer:
```
say flip :36($_).base(2).trans("01"=>" o")for<KPVBKQ0 1RE099TU 3IFSZG1T 3IWIUAYP 1SDK5282 KPVBKQ0 HTTBLS 5TRXMO>
```
```
o o o o o o o o o
o o o o o o
o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o
o o o o
o o o o o o
```
[Answer]
# Mathematica ~~185~~ 175
10 bytes saved by mathe.
The rings below are ASCII 'O's.
The letter "O", slightly translucent, in Century Gothic, printed 5 times at font size=145 printer points.
This is not terminal art. However it fully satisfies Wikipedia's definition of Ascii art: <http://en.wikipedia.org/wiki/ASCII_art>.
```
Graphics[{[[email protected]](/cdn-cgi/l/email-protection),Style["O",#]~Text~#2&@@@{{Blue,{-1.5,1}},{Black,{0,1}},{Red,{1.5,1}},{Orange,{-.8,.4}},{Darker@Green,{.8,.4}}}},BaseStyle->{145,FontFamily->"Century Gothic"}]
```
![olympic rings](https://i.stack.imgur.com/xoUuV.png)
[Answer]
**JavaScript: 153 chars**
I wanted to see if I could do it any faster using algebra to actually graph the circles:
```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3}s+=t}}
```
(`c` is an array of five (x,y) pairs, the centers of the circles, flattened to save ten characters.)
output:
```
1110000000111111111000000011111111100000001111
1000111110001111100011111000111110001111100011
0011111111100111001111111110011100111111111001
0011111111100000001111111110000000111111111001
0011111110000111000011111000011100001111111001
1000111100001111100001110000111110000111100011
1110000000111111111000000011111111100000001111
1111111100111111111001110011111111100111111111
1111111110001111100011111000111110001111111111
1111111111100000001111111110000000111111111111
```
**159 chars** is a little more readable:
```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3}s+=t?" ":t}}
```
output:
```
0000000 0000000 0000000
000 000 000 000 000 000
00 00 00 00 00 00
00 0000000 0000000 00
00 0000 0000 0000 0000 00
000 0000 0000 0000 0000 000
0000000 0000000 0000000
00 00 00 00
000 000 000 000
0000000 0000000
```
In **167 chars** we have "colors":
```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3;h=t?i:h}s+=t?" ":h}}
```
output:
```
8888888 0000000 2222222
888 888 000 000 222 222
88 88 00 00 22 22
88 8844400 0066622 22
88 4444 0044 6600 2266 22
888 4444 0004 6000 2226 222
8888888 0000000 2222222
44 44 66 66
444 444 666 666
4444444 6666666
```
And with **189 chars**, I can make the radius `r` adjustable as well:
```
r=5;s="";c=[r,0,2*r+1,r,3*r+2,0,4*r+3,r,5*r+4,0];for(y=-r;y<3*r;y++){s+="\n";for(x=0;x<9*r;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-r*r;t&=(d<0?-d:d)>r;h=t?i:h}s+=t?" ":h}}
```
<http://jsfiddle.net/mblase75/5Q6BX/>
[Answer]
# APL, 8 chars/bytes\*
Here's an answer pushing for lowest char count (this is code golf after all)
```
2 5⍴'○ '
```
Output:
```
‚óã ‚óã ‚óã
‚óã ‚óã
```
The symbol is ‚óã, APL circle operator. You can put an 'O' instead, in case you want strictly ASCII output. I just thought it fit to use an APL symbol.
---
Just for kicks, here's a color version (37 chars - 20 = 17 score)
```
2 20⍴'m',⍨¯2↓3↓∈(⊂'m○ ^[[3'),⍪'40132 '
‚Äæ‚Äæ ‚Üê single Esc character, type Ctrl+V Esc on the terminal
```
Output:
![color rings terminal output](https://i.stack.imgur.com/odDwd.png)
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
[Answer]
# CSS, ~~1176~~ ~~922~~ ~~855~~ 771 bytes, -20 colour bonus = 751
```
html,head,title,body{display:block; color:transparent; font:bold 1em/1 monospace; height:0}
link,meta,style{display:none}
:before,:after{float:left; color:#000; white-space:pre;
content:' @@@@@@@\A @@@ @@@\A@@ @@ \A @@\A@@ @@\A@@ @@\A @@@ @@@\A @@@@ @'}
html:before{color:blue}
title:before,title:after{color:blue; position:absolute; left:0; top:3em; content:'@@'}
title:after{color:red; top:7em; content:' @@'}
head:after{color:red}
body:before{clear:left; content:' '}
body:after,html:after{position:relative; top:-5em; color:#EC0;
content:' @ @@@@\A @@@ @@@\A @@ @@\A @@ @@\A @@\A @@ @@\A @@@ @@@\A @@@@@@@'}
html:after{color:#090}
```
CSS only, no markup needed. See markupless fiddle here: <http://jsfiddle.net/XcBMV/12/>
![Rings](https://i.stack.imgur.com/MaFhG.png)
In colour, and with the correct overlap.
[Answer]
**Perl - 12 characters**
```
say"OOO\nOO"
```
OK, so it's not an especially artistic rendering. ;-)
Slightly cuter:
```
perl -MTerm::ANSIColor=:constants -E'say ON_BRIGHT_WHITE,BLUE,O,BLACK,O,RED,O,$/,YELLOW,O,GREEN,O,RESET'
```
[Answer]
# GAS Assembly 16-bit BIOS OL loader – 617 - 20 = 597
Going crazy on length here, so mere for the fun of it.
---
It does not load much, but it loads The Olympic Games logo as ASCII with colors ;)
Code:
```
.code16;S:jmp o;nop;o:mov $1984,%ax;mov %ax,%ds;mov %ax,%es;movw $t,%si;r:lodsb;or %al,%al;jz q;cmp $33,%al;jg k;movb $0,c;call X;inc %dh;mov $0,%dl;call G;jmp r;k:sub $48,%al;mov %al,%cl;add %al,c;lodsb;cmp $32,%al;je v;mov %al,%bl;and $15,%bl;mov $35,%al;v:mov $9,%ah;mov $0,%bh;mov $0,%ch;int $16;call X;mov c,%dl;call G;jmp r;q:ret;G:mov $2,%ah;int $16;X:mov $3,%ah;mov $0,%bh;int $16;ret;c:.byte 0;t:.asciz "3 5A9 5H9 5D!1 1A7 1A5 1H7 1H5 1D7 1D!1A9 1A4N9 1H4B9 1D!1A7 1N1 1A3 1H1 1N5 1B1 1H3 1D1 1B7 1D!1 1A5 1N1 1A5 1H1 1N3 1B1 1H5 1D1 1B5 1D!3 4A1N9 4H1B9 5D!8 1N7 1N5 1B7 1B!9 1 5N9 5B!";.=S+510;.word 0xaa55
```
### (Linux) Build and extract MBR image
```
as -o olymp.o olymp.S
objcopy -O binary olymp.o olymp.img
```
### Running in emulator
*(Have not tested it on my home computer yet ...)*
```
qemu-system-i386 olymp.img
```
### Result
![enter image description here](https://i.stack.imgur.com/llY1L.png)
[Answer]
# TI-Basic (16 bytes)
Note: TI-Basic is tokenized. If I remember correctly, `ClrHome` and `Disp` are one-byte tokens.
```
ClrHome
Disp "O O O"," O O
```
[Answer]
```
#include<iostream.h>
#include<conio.h>
#define tc textcolor
void circle(int x,int y,int k)
{
tc(k);
int n;
for(n=0;n<=6;n++)
{
if(n==0||n==6)
{
gotoxy(x+3,y+n);
cprintf("* * *");
}
else if(n==1||n==5)
{
gotoxy(x+1,y+n);
cprintf("*");
gotoxy(x+9,y+n);
cprintf("*");
}
else if(n>1&&n<5)
{
gotoxy(x,y+n);
cprintf("*");
gotoxy(x+10,y+n);
cprintf("*");
}
}
}
void main()
{
clrscr();
circle(1,1,BLUE);
circle(14,1,WHITE);
circle(27,1,RED);
circle(8,4,YELLOW);
circle(21,4,GREEN);
_setcursortype(0);
getch();
}
```
![Made in turbo c++ 3.0 compiler. Tried t make the code as short as possible](https://i.stack.imgur.com/hJDA5.jpg)
] |
[Question]
[
Hold up..... this isn't trolling.
---
# Background
These days on YouTube, comment sections are littered with such patterns:
```
S
St
Str
Stri
Strin
String
Strin
Stri
Str
St
S
```
where `String` is a mere placeholder and refers to any combination of characters. These patterns are usually accompanied by a `It took me a lot of time to make this, pls like` or something, and often the OP succeeds in amassing a number of likes.
---
# The Task
Although you've got a great talent of accumulating upvotes on PPCG with your charming golfing skills, you're definitely not the top choice for making witty remarks or referencing memes in YouTube comment sections. Thus, your constructive comments made with deliberate thought amass a few to no 'likes' on YouTube. *You want this to change.* So, you resort to making the abovementioned clichéd patterns to achieve your ultimate ambition, but without wasting any time trying to manually write them.
Simply put, your task is to take a string, say `s`, and output `2*s.length - 1` substrings of `s`, delimited by a newline, so as to comply with the following pattern:
(for `s` = "Hello")
```
H
He
Hel
Hell
Hello
Hell
Hel
He
H
```
---
# Input
A single string `s`. Input defaults of the community apply.
You can assume that the input string will only contain printable ASCII characters.
---
# Output
Several lines separated by a newline, constituting an appropriate pattern as explained above. Output defaults of the community apply.
Leading and trailing **blank (containing no characters or characters that cannot be seen, like a space)** lines in the output are permitted.
---
# Test Case
A multi-word test case:
```
Input => "Oh yeah yeah"
Output =>
O
Oh
Oh
Oh y
Oh ye
Oh yea
Oh yeah
Oh yeah
Oh yeah y
Oh yeah ye
Oh yeah yea
Oh yeah yeah
Oh yeah yea
Oh yeah ye
Oh yeah y
Oh yeah
Oh yeah
Oh yea
Oh ye
Oh y
Oh
Oh
O
```
Note that there are apparent distortions in the above test case's output's shape (for instance, line two and line three of the output appear the same). Those are because we can't see the trailing whitespaces. Your program need NOT to try to fix these distortions.
---
# Winning Criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins!
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 32 bytes
```
,[[<]>[.>]++++++++++.,[>>]<[-]<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzraJtYuWs8uVhsO9HSi7exibaJ1Y21i///3z1CoTE2EEAA "brainfuck – Try It Online")
The same loop is used for both halves of the pattern.
### Explanation:
```
, Take first input character as initial line
[ Until line to output is empty:
[<]> Move to beginning of line
[.>] Output all characters in line
++++++++++. Output newline
, Input next character
[>>] Move two cells right if input character nonzero
<[-] Otherwise remove last character in line
< Move to new last character in line
]
```
[Answer]
# JavaScript (ES6), 36 bytes
```
f=([c,...r],s=`
`)=>c?s+f(r,s+c)+s:s
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjOllHT0@vKFan2DaBK0HT1i7Zvlg7TaNIp1g7WVO72Kr4f3J@XnF@TqpeTn66RpqGkn@GQmVqIoRQ0tT8DwA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
// the input string split into:
[c, // c = next character (may be undefined if we've reached the end)
...r], // r[] = array of remaining characters
s = `\n` // the output string s, initialized to a linefeed
) => //
c ? // if c is defined:
s + // append s (top of the ASCII art)
f(r, s + c) + // append the result of a recursive call to f, using r[] and s + c
s // append s again (bottom of the ASCII art)
: // else:
s // append s just once (this is the final middle row) and stop recursion
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~4~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
[*Crossed out ` 4 ` is no longer 4 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
η.∊
```
[Try it online](https://tio.run/##MzBNTDJM/f//3Ha9Rx1d///7ZyhUpiZCCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVvn/3Ha9Rx1d/3UObbP/H1xSlJmXzuWRmpOTz@WfoVCZmgghAA).
**Explanation:**
```
η # Get the prefixes of the (implicit) input-string
.∊ # Vertically mirror everything with the last line overlapping
# (which implicitly joins by newlines in the legacy version of 05AB1E)
# (and output the result implicitly)
```
In the new version of 05AB1E, and explicit `»` is required after the `η`, which is why I use the legacy version of 05AB1E here to save a byte.
---
**3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative provided by *@Grimy*:**
```
ηû»
```
This version works in both the legacy and new version of 05AB1E.
[Try it online (legacy)](https://tio.run/##MzBNTDJM/f//3PbDuw/t/v/fP0OhMjURQgAA), [try it online (new version)](https://tio.run/##yy9OTMpM/f//3PbDuw/t/v/fP0OhMjURQgAA) or [verify all test cases (new version)](https://tio.run/##yy9OTMpM/V9TVvn/3PbDuw/t/q9zaJv9/@CSosy8dC6P1JycfC7/DIXK1EQIAQA).
**Explanation:**
```
η # Get all prefixed of the (implicit) input-string
û # Palindromize each string in this list
» # And then join the list of strings by newlines
# (after which the result is output implicitly)
```
[Answer]
# x86-16 machine code, IBM PC DOS, ~~44~~ ~~43~~ 39 bytes
```
00000000: d1ee ad8b d648 93b7 248a cbd0 e13a d975 .....H..$....:.|
00000010: 01fd ac86 3cb4 09cd 2186 3cb8 0d0e cd10 ....<...!.<.....
00000020: b00a cd10 e2e7 c3 .......
```
Build and test `YT.COM` using `xxd -r` from above.
***Unassembled:***
```
D1 EE SHR SI, 1 ; point SI to DOS PSP at 80H (SI intialized at 100H)
AD LODSW ; load input length into AL, SI = 82H
8B D6 MOV DX, SI ; save start of string pointer
48 DEC AX ; remove leading space from string length
93 XCHG AX, BX ; save string length in BL
B7 24 MOV BH, '$' ; put end-of-string marker in BH
8A CB MOV CL, BL ; set up loop counter in CL
D0 E1 SHL CL, 1 ; number of lines = 2 * string length - 1
LINE_LOOP:
3A D9 CMP BL, CL ; does CL = string length?
75 01 JNZ LINE_OUT ; if not, go to output line
FD STD ; otherwise flip DF to descend
LINE_OUT:
AC LODSB ; increment or decrement SI
86 3C XCHG BH, [SI] ; swap current string byte with end of string delimiter
B4 09 MOV AH, 9 ; DOS API display string function
CD 21 INT 21H ; write substring to console
86 3C XCHG BH, [SI] ; restore string byte
B8 0E0D MOV AX, 0E0DH ; AH = 0EH (BIOS tty function), AL = CR char
CD 10 INT 10H ; write CR to console
B0 0A MOV AL, 0AH ; AL = LF char
CD 10 INT 10H ; write LF to console
E2 E6 LOOP LINE_LOOP ; move to next line
C3 RET ; return to DOS
```
***Explanation***
Loop `2 * input length - 1` for each row. The DOS API's string display function (`INT 21H,9`) writes a `$`-terminated string to the screen, so each time through the loop the character after the last to be displayed is swapped with the end-of-string terminator.
The loop counter is compared with the string length, and if it's greater (meaning the ascending part of the output) the string/swap position is incremented, otherwise it's decremented.
Standalone PC DOS executable program, takes input string from command line.
***Output***
[![enter image description here](https://i.stack.imgur.com/PlPSP.png)](https://i.stack.imgur.com/PlPSP.png)
* -1 byte use `SHR SI, 1` instead of `MOV` - thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!
* -1 byte flipping loop comparison
* -1 byte write newline directly instead of as string
* -1 byte use `XCHG` instead of `MOV`
* -1 byte use `STD` / `LODSB` to ascend/descend SI pointer
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
nZv"G@:)
```
[Try it online!](https://tio.run/##y00syfn/Py@qTMndwUrz/391n8zsVIWSjMxiheT83NzUvBJFdQA "MATL – Try It Online")
Please like this post for the smiley `:)` in the code it took me a lot of time to make.
```
n % Length of the input string
Zv % Symmetric range ([1 2 ... n ... 1])
" % For each k in above range
G % Push input
@: % Push [1 2 ... k]
) % Index
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ 52 bytes
```
f=lambda s,n=1:s[n:]and[s[:n]]+f(s,n+1)+[s[:n]]or[s]
```
[Try it online!](https://tio.run/##LcgxCoAgFADQvVN8mhRbbBQ8QwcQB8NEwb6iLp7@F9TyhlfniAV3oqCzu0/voG@opeoGlXXoTTcKrRWBvS8kF3@UZrqlUBpkSAiBrUeEebmPlasFaks4WOb0AA "Python 2 – Try It Online")
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 50 bytes
```
f=lambda s,n=1:s>(x:=s[:n])and[x,*f(s,n+1),x]or[s]
```
[Try it online!](https://tio.run/##JckxCoAgFADQvVN8mrRcpCUEu0IHEAfDpMC@8m2w01vQ8paXn/tIOM2ZWgs6umvzDopALVVZWFW6GIWWO/SmiiGwr0bJRbWJTLEtJIIIJ0Jg/XrAs7ufnqsOMp14s8jbCw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 11 bytes
Anonymous tacit prefix function. Returns a space-padded character matrix.
```
[:(}:,|.)]\
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aSqPWSqdGTzM25r8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoJ6cElRZl66Opzvn6FQmZoIIdT/AwA "J – Try It Online")
`]\` the list of prefixes
`[:(`…`)` apply the following function to that list
`|.` the reverse list
`,` prepended with
`}:` the curtailed (without last item) list
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes
```
{[\~](@_)[0...@_-1...0]}o*.comb
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo6pi5WwyFeM9pAT0/PIV7XEEgZxNbma@kl5@cm/bfmStNQCi4pysxLV9K0s9MrTqwEC/lnKFSmJkIImMR/AA "Perl 6 – Try It Online")
Anonymous code block that takes a string and returns a list of lines.
### Explanation:
```
{ }o*.comb # Pass the list of characters into the codeblock
[\~](@_) # Triangular reduce by concatenation
# e.g. The list [1,2,3,4] turns into [1,12,123,1234]
[0...@_-1 # Return the elements from 0 to length of string minus 1
...0] # And back down to 0
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [-R](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 4 bytes
```
å+ ê
```
Cumulative reduce on a string.
*-1 byte thanks to @Shaggy*
[Try it online!](https://tio.run/##y0osKPn///BSbYXDq/7/V/LPUKhMTYQQSly6QQA "Japt – Try It Online")
[Answer]
# Perl 5 (`-p`), 26 bytes
```
s,.,$\=$`.$/.$\;"$`$&
",ge
```
[TIO](https://tio.run/##K0gtyjH9/79YR09HJcZWJUFPRV9PJcZaSSVBRY1LSSc99f9/j9ScnPx/@QUlmfl5xf91C/7r@prqGRgCAA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, ~~9~~ 7 bytes
-2 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
```
Êõ@¯XÃê
```
[Try it online!](https://tio.run/##y0osKPn//3DX4a0Oh9ZHHG4@vOr/fyX/DIXK1EQIocSlGwQA "Japt – Try It Online")
[Answer]
# Haskell, ~~52~~ ~~50~~ 44 bytes
```
f x=unlines$init<>reverse$scanr(\_->init)x x
```
* -2 bytes by a variant of [Ørjan Johansen's trick](https://codegolf.stackexchange.com/a/177153/81540)
* -6 bytes by [taking advantage of `instance Semigroup b => Semigroup (a -> b)`](https://codegolf.stackexchange.com/a/177774/81540)
[Try it online!](https://tio.run/##LY2xCsJAEER7v2KQFAmYgGJhoQFRUCsLLQU5w8YsXu7C7UWTr48nkV1eMTs7Uyl5kdYD1411HnvlVXahmp/Otg3ieJ0nCdIUvmJBWGt0D0MFiSjX40GFaoVwPZ1/V/GsdfDgcNxhlS3CYBueyr@wzOazMepj3SuQfQVjMbZLNpnUig02aFp/8Q4RSkzPFXpSI6ZDiW7TGs2GJGLDfp07epMTiqRQxsW3e5r/9KRDNwxf "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~79~~ ~~65~~ ~~62~~ 58 bytes
```
write(substring(s<-scan(,""),1,c(1:(r=nchar(s)),r-1:r)),1)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVo7g0qbikKDMvXaPYRrc4OTFPQ0dJSVPHUCdZw9BKo8g2LzkjsUijWFNTp0jX0KoISBtq/g8G6/gPAA "R – Try It Online")
*-14 by Giuseppe's superior function knowledge*
*-3 with cleaner indexing*
*-4 thanks to Nick Kennedy and Giuseppe's move to `scan` and `write`*
Avoiding loops (and `substr`) is nice.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
*-1 byte thanks to [@JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!*
```
¹ƤŒḄ
```
[Try it online!](https://tio.run/##y0rNyan8///QzmNLjk56uKPl/@H2yP//lTyAwvmKSgA "Jelly – Try It Online") I think this is my second Jelly answer? ~~I don't know if this is optimal.~~ I am more convinced of it being optimal. Returns an array of lines.
## Explanation
```
¹ƤŒḄ input: "Hi!"
¹Ƥ prefixes of the input: [["H"], ["H", "i"], ["H", "i", "!"]]
ŒḄ bounce, using each array: [["H"], ["H", "i"], ["H", "i", "!"], ["H", "i"], ["H"]]
```
Another approach, proposed by @JonathanAllan, is `;\ŒḄ`, which cumulatively reduces (`\`) concatenation (`;`), which is another way to generate prefixes.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 48 bytes
```
lambda s,r='':(l:=[r:=r+c for c in s])+l[-2::-1]
```
[Try it online!](https://tio.run/##FcixCoAgEADQva84WlKsoVriwC@xBrOswEwuB/t6wze@8MXz8eMUKFs5Z6fvddPwtiSbBplDqQglCQP2ITBweXgXLpzqBsSuX3LpVNqyWq9m2@1Rc6wg0OUjSzz/ "Python 3.8 (pre-release) – Try It Online")
Uses [assignment expressions](https://www.python.org/dev/peps/pep-0572/) with `:=` to [accumulate a list of prefixes](https://codegolf.stackexchange.com/a/180041/20260) and then again to save the result to concatenate its reverse (without the first char).
# [Python 2](https://docs.python.org/2/), 51 bytes
```
f=lambda s,l=[]:s and f(s[:-1],[s]+l)or l+l[-2::-1]
```
[Try it online!](https://tio.run/##FcoxDoAgDEDR3VM0TBB0kJHEkxAGEFGTWog46Omrjv/l1@faChnmPGE4YgrQepyctw0CJciyOTuMvnfNa1TlBNToBmN/5Pz1DTt9mwhxTktehbId1HOnS96KXw "Python 2 – Try It Online")
We almost have the following nice 45-byte solution, but it has the original string twice and I don't see a short way to fix this.
```
f=lambda s,l=[]:s and f(s[:-1],[s]+l+[s])or l
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVgnxzY61qpYITEvRSFNozjaStcwVie6OFY7RxtIauYXKeT8TwOSFQqZeUAFSolJySmpaelKmlZcCgVFmXklGhWa/wE "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
G^Lθθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9PwypOR8EnNS@9JEOjUFNHoVDT@v9//wyFytRECMH1X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `G` draws a filled polygon, `^` specifies that the sides are down right and down left (the polygon then automatically closes itself), `Lθ` specifies the length of those sides as being the length of the original input and the final `θ` specifies the fill string.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~123~~ ~~109~~ ~~94~~ ~~84~~ 74 bytes
Assumes we can return a char array array (I believe we can, as a char array is a valid representation for a string and a string array is a valid representation for multiple lines)
```
a=>new int[a.Length*2-1].Select((b,i)=>a.SkipLast(Math.Abs(a.Length-i-1)))
```
[Try it online!](https://tio.run/##TY7BasJAEEDvfsXixdmSLNhrzIKIAUtKCyn00HqYLIMZjBPZXVv9@nRpELwMD@Yx81zIXeCxuohbhehZDtluK5cTeWx7Wj2y69Bba1VVlSOWVuhXscQvNDXJIXZPz/lybxrqyUWANmNdWjTNkc81hgivGDuzbgPc/ZzzpdZ6LGY/6JWnoMp0GuZvnboRTmOui9l7ioqQ9ok3g4ShJ/PpOVLNQjA1m5eBBRbfssiSeI@4TpHNvwJX8zGsvccbpK@PXIx/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. Returns list of strings.
```
(⊢,1↓⌽),\
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR1yIdw0dtkx/17NXUifmf9qhtwqPevkd9Uz39H3U1H1pv/KhtIpAXHOQMJEM8PIP/pymoB5cUZealq3MBmf4ZCpWpiRBCHQA "APL (Dyalog Unicode) – Try It Online")
`,\` the list of prefixes (lit, the cumulative concatenation)
`(`…`)` apply the following function to that list:
`⌽` the reversed list
`1↓` drop the first item
`,` prepend
`⊢` the unmodified list
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 15 bytes
```
Bounce@Prefixes
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@98pvzQvOdUhoCg1LbMitfh/Wj5QVMErPzNPLSdNQVlZIY2LK6AoM68kOi0/Wsk/Q6EyNTFDUSk29j8A "Attache – Try It Online")
Pretty simple. `Bounce`s (appends reverse without center) the `Prefixes` of the input.
Alternatively, **21 bytes:** `Bounce@{_[0..0:~-#_]}`, re-implementing prefix.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 6 bytes
```
a₀ᶠ⊆.↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRU8PDbQsedbXpPWqb8v@/UmISUDYxBUQp/Y8CAA "Brachylog – Try It Online")
Function submission, returning an array of lines. Loosely based on [@Fatalize's answer](https://codegolf.stackexchange.com/a/180542/76359).
## Explanation
```
a₀ᶠ⊆.↔
.↔ Find a palindrome
⊆ that contains, in order,
ᶠ all
a₀ prefixes of {the input}
```
Tiebreak order here is set by the `⊆`, which, when used with this flow pattern, prefers [the shortest possible output, tiebroken by placing the given elements as early as possible](https://tio.run/##SypKTM6ozMlPN/r//1FX28NtCw5tOrTp//9oQx0jHWMdk9j/UQA "Brachylog – Try It Online"). The shortest possible output is what we want here (due to it not being possible to have any duplicate prefixes), and placing the given elements (i.e. the prefixes) as early as possible will place them in the first half (rounded up) of the output. Given that we're also requiring them to be placed in the same order, we happen to get exactly the pattern we need even though the description we gave Brachylog is very general; the tiebreaks happen to work out exactly right, causing Brachylog to pick the output we want rather than some other output that obeys the description.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 bytes
```
($l=$args|% t*y|%{($s+=$_);++$i})+$l[$i..0]|gu
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9X0Mlx1YlsSi9uEZVoUSrska1WkOlWNtWJV7TWltbJbNWU1slJ1olU0/PILYmvfR/LReXGlCnB9CEfDBLyT9DoTI1EUIo/QcA "PowerShell – Try It Online")
---
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes (YouTube special, dirty)
It is known that the maximum length of a comment on youtube is 10,000 characters. Ok, use this as the upper limit.
```
($l=$args|% t*y|%{($s+=$_)})+$l[1e4..0]|gu
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9X0Mlx1YlsSi9uEZVoUSrska1WkOlWNtWJV6zVlNbJSfaMNVET88gtia99H8tF5caUJcHUHc@mKXkn6FQmZoIIZT@AwA "PowerShell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~51~~ ~~42~~ 40 bytes
```
f=->s,i=1{s[i]?[t=s[0,i],*f[s,i+1],t]:s}
```
[Try it online!](https://tio.run/##KypNqvz/P81W165YJ9PWsLo4OjPWPrrEtjjaQCczVkcrLRoorm0Yq1MSa1Vc@7@gtKRYIS1ayT9DoTI1EUIoxf4HAA "Ruby – Try It Online")
Thanks to Doorknob for -2 bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
This can probably be golfed alot more, [Arnauld](https://codegolf.stackexchange.com/a/180514/84942) already has a way shorter one but I had fun atleast!
```
s=>{a=[];for(c=s.length-1;c--;)a[c]=s.slice(0,c+1);return[...a,s,...a.reverse()].join`\n`}
```
[Try it online!](https://tio.run/##JchRCgIhEIDhq/S2Sjq0z2JX6ACbsDKNuy6i4dhCRGe3opf/g3/zu2es8d50LjfqwXa255e3kzOhVIGWIVFe2qpHg1ob6Sd038kpIomTwuMoTaX2qHkCAK9Y/YBKO1UmIR1sJeb5mud3x5K5JIJUFhHEcFkPT/L/DFKa/gE "JavaScript (Node.js) – Try It Online")
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 118 bytes
```
N =INPUT
L =1
1 X =LT(X,SIZE(N)) X + 1 :F(D)
O N ARB . OUTPUT POS(X) :($L)
D X =GT(X) X - 1 :F(END)
L ='D' :(O)
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NPwdbTLyA0hIvTR8HWkMuQM0LB1idEI0In2DPKVcNPU1MhQkFbwZDTyk3DRZPLH6jeMchJQU/BPzQEqEshwD9YI0KT00pDxUeTywWk2R2oGaRJF6LJ1Q@oDWS2uos6UJm/JhdQ5P//4JKizLx0AA "SNOBOL4 (CSNOBOL4) – Try It Online")
There appears to be a bug in this implementation of SNOBOL; attempting to replace the label `D` with the label `2` causes an error, although the manual for Vanilla SNOBOL indicates that (emphasis added)
>
> If a label is present, it must begin with the first character of the line. Labels provide a name for the statement, and serve as the target for transfer of control from the GOTO field of any statement. **Labels must begin with a letter or digit, optionally followed by an arbitrary string of characters.** The label field is terminated by the character blank, tab, or semicolon. If the first character of a line is blank or tab, the label field is absent.
>
>
>
My supposition is that the CSNOBOL interpreter only supports a single label that begins with an integer.
[Answer]
# APL+WIN, 31 bytes
Prompts for input of string:
```
⊃((⍳n),1↓⌽⍳n)↑¨(¯1+2×n←⍴s)⍴⊂s←⎕
```
Explanation:
```
(¯1+2×n←⍴s)⍴⊂s create a nested vector of the string of length =1+2x length of string
((⍳n),1↓⌽⍳n)↑¨ progressively select elements from each element of the nested vector
following the pattern 1 2 ...to n to n-1 ... 1
⊃ convert nested vector into a 2d array.
```
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~67~~ 61 bytes
```
let l=s.Length
[1..l*2-1]|>Seq.map(fun i->s.[..l-abs(i-l)-1])
```
[Try it online!](https://tio.run/##HYq9CsIwEID3PsVxILRCDurezA5uHatDDEkNnJfai1vfPQbH7yeq8XkPlUMBhQnwGpgz/pknpVuQtby6ZSTi88WMj8PO4UNvt/XxK5CMVVpaM@6pfTI8tGWoh4W57ElW8lm8K4B3QWh2a7JEATwpdvUH "F# (.NET Core) – Try It Online")
Input is a `string` and output is a `seq<string>`
Another solution could be `let f(s:string)=for i=1 to s.Length*2-1 do printfn"%s"s.[..s.Length-abs(i-s.Length)-1]` for 80ish bytes... I am not sure that it is worth looking into.
[Answer]
# [sed](https://www.gnu.org/software/sed/), 31 35 bytes
```
:x
h
s/.\n.*\|.$//
/^$/{x;q}
H
G
bx
```
[Try it online!](https://tio.run/##K05N0U3PK/3/36qCK4OrWF8vJk9PS1@fSz9ORb@6wrqwlsuDy50rqeL//5DU4pLMvHSFjNScnHwA "sed – Try It Online")
# Explanation
At the beginning of each iteration of the loop, pattern space is some "central chunk" of the desired output, and each loop adds a shortened copy to the top and bottom.
```
:x
h Copy the current chunk to hold space
s/.\n.*\|.$// Remove the last letter of the first line, and all other lines (if there are any)
/^$/{x;q} If pattern space is empty we're done; output hold space
H Add the shortened line to the end of hold space
G and add the new hold space to pattern space.
bx
```
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
]\,[:}.@|.]\
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D82RifaqlbPoUYvNua/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCenBJUWZeujqc75@hUJmaCCHU/wMA "J – Try It Online")
Still 1 byte longer than Adám's
# [K (oK)](https://github.com/JohnEarnest/ok), ~~12~~ 11 bytes
-1 byte thanks to ngn
```
{x,1_|x}@,\
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukLHML6motZBJ@Z/moKSf4ZCZWoihFD6DwA "K (oK) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~68~~ ~~67~~ ~~64~~ 59 bytes
thanks @ceilingcat for -6
thanks @gastropner for -5
```
i,j;f(char*s){for(j=1;i+=j;puts(""))j-=2*!s[write(1,s,i)];}
```
[Try it online!](https://tio.run/##fY2xDoIwGITn9ilKE5MWSxA307C7OToAJk0t8DdQDK0xSnh2hLh7w930faeTRutlAWFlzXSrxtjzqR5GZvNMwj638vEMnlHKuU3yYxz54jVCMCwTXgCv5LxsFNFFdthSSYx7BY7xCSOvlasZ3RW30lWlo4JoLjFaj9bBKE0JOAigOviAa1ZHhVFvem8C04IcBDlt2ZC/pnm5tORt1K/w2XTdIMh1GLt79AU "C (gcc) – Try It Online")
[Answer]
# x86-16 machine code, IBM PC-DOS, 33 bytes
Hexdump:
```
00000000: bf 82 00 91 89 fa e8 0a 00 74 06 41 eb f8 e8 02 .........t.A....
00000010: 00 e2 fb b4 40 cd 21 b0 0d ae cd 29 b0 0a cd 29 ....@.!....)...)
00000020: c3 .
```
Commented assembly:
```
[org 0x100]
start:
; DI <- first command line argument
mov di, 0x0082
; DOS startup state abuse 1: set CX to zero by swapping AX (0x0000)
xchg cx, ax
; DX <- DI
mov dx, di
.loop1:
; A multitasking loop.
; This both prints the string up to the full length and counts
; the chars by scanning for '\r'.
; Print DS:DX(CX)
; We test for the end of string when printing
; the newline by using SCASB.
call putsn
; If the SCASB returned true, break to the end of .loop2
; We don't go to the top because it would print the full
; length string twice.
jz .next
; Increment the length and character counter
inc cx
; Loop to loop1
jmp .loop1
.loop2: ; Shortening loop
; Print
call putsn
.next:
; while (--CX)
loop .loop2
; Fallthrough: prints an empty line (as CX is 0) and exits
; Prints CX chars from DX, followed by a newline.
putsn:
; DOS startup state abuse 2: BX is 0x0000.
; DOS lets you write to STDIN and it still prints to the screen.
; Why? I have no idea. It's very convenient though. Note that
; this behavior is consistent on DOS 6.22 and FreeDOS 1.3rc4.
;
; write(0, argv, CX)
mov ah, 0x40
int 0x21
; Print \r\n with INT 29h
mov al, 13
; Since we have \r in AL, we can use SCASB to check
; for the end of the string when we return.
; Interrupts save the flags.
;
; Yes, this reads out of bounds on the second loop,
; but it is DOS, who cares?
scasb
int 0x29
mov al, 10
int 0x29
ret
```
To be even with 640KB, I also used the command line arguments, but I made some changes:
1. I use `write` (`21:40`) instead of `puts` (`21:09`). While it does require manually printing a newline, it lets me manually control the length just by changing CX.
2. I count the length of the command line arguments on the fly.
3. I did some other tricks.
This abuses the newline rule: it actually prints empty strings at the start and end.
[![What did you expect?](https://i.stack.imgur.com/bYAG1.png)](https://www.youtube.com/watch?v=dQw4w9WgXcQ)
] |
[Question]
[
The challenge is to find a string of characters that **cannot** appear in *any* legal program in your programming language of choice. That includes comments, strings, or other "non-executable" parts.
## Challenge
* Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars.
* Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result (e.g. passing a flag to convert warnings into errors).
* If your programming language requires a specific encoding (e.g. UTF-8), your string must also be correctly encoded (i.e. strings which fail solely due to character decoding errors are not allowed).
* Every individual character in your submission must be admissible in a legal program; that is, you can't just use a character which is always rejected.
* The compiler/interpreter/runtime must give an error when given *any* source code that contains your string as a substring. The error does not have to be the same across programs - one embedding of your string might cause a syntax error, while another might cause a runtime error.
## Scoring
* Shortest illegal string for each language wins.
* You should explain *why* your string is illegal (why it cannot appear anywhere in a legal program).
* Dispute incorrect solutions in the comments. More specifically, you should provide a link to TIO or equivalent demonstrating a legal program (i.e. one that doesn't produce any errors) that contains the proposed substring.
* Some languages (e.g. Bash, Batch, Perl) allow arbitrary binary data to be appended to a program without affecting validity (e.g. using `__DATA__` in Perl). For such languages, you may submit a solution that can appear *only* in such a trailing section. Make sure to make a note of that in your answer. (The definition of this "trailing section" is language-dependent, but generally means any text after the parser has entirely stopped reading the script).
## Example
In Python, I might submit
```
x
"""
'''
```
but this can be embedded into the larger program
```
"""
x
"""
'''
y
'''
```
so it isn't admissible.
[Answer]
# [Changeling](https://github.com/DennisMitchell/shapescript), 2 bytes
```
```
That's two linefeeds. Valid Changeling must always form a perfect square of printable ASCII characters, so it cannot contain two linefeeds in a row.
The error is always a parser error and always the same:
```
This shape is unpleasant.
```
accompanied by exit code **1**.
[Try it online!](https://tio.run/##S85IzEtPzcnMS///n4vr/38A "Changeling – Try It Online")
[Answer]
# Java, 4 bytes
```
;\u;
```
[Try it online!](https://tio.run/##y0osS9TNL0jNy0rJ/v8/OSexuFjBsZqroDQpJzNZobgksQRIleVnpijkJmbmaQSXFGXmpUfHJmpWc@nrW8eUWnPVctX@/w8A "Java (OpenJDK 8) – Try It Online")
This is an invalid Unicode escape sequence and will cause an error in the compiler.
```
error: illegal unicode escape
```
[Answer]
# [COBOL (GNU)](https://sourceforge.net/projects/open-cobol/), 8 bytes
```
THEGAME
```
First, a linefeed to prevent you from putting my word in a commented line.
Then, historically, COBOL programs were printed on coding sheets, the compiler relies heavily on 80-character limited lines, there are no multiline comments and the first 6 characters are comments (often used as editable line numbers), you can put almost anything there, AFAIK. I chose `THEGAM` at the beginning of the next line.
Then, the 7th symbol in any line only accepts a very restricted list of characters : Space (no effect), Asterisk (comments the rest of the line), Hyphen, Slash, there may be others, but certainly not `E`.
The error given by GnuCobol, for instance, is :
```
error: invalid indicator 'E' at column 7
```
[Try it online!](https://tio.run/##S85Pys/RTc8r/f@fK8TD1d3R1/X/fwA "COBOL (GNU) – Try It Online")
Also, you just lost the game.
[Answer]
# JavaScript, 7 bytes
```
;*/\u)
```
Note the leading newline.
* `\u)` is an invalid Unicode escape sequence and this is why this string is invalid
* Adding a `//` at the beginning will still not work because of the leading newline, leaving the second line uncommented
* Adding a `/*` will not uncomment the string completely because of the closing `*/` that completes it, leaving the `\u)` exposed
* As stated by @tsh, the bottom line can be turned into a regex by having a `/` after the string, so by having the `)` in front of the `\u`, we can ensure that the regex literal will always be invalid
* As stated by @asgallant, one could do `1||1(string)/` to avoid having to evaluate the regex. The semi-colon at the beginning of the second line stops that from happening by terminating the expression `1||1` before it hits the second line, thus forcing a SyntaxError with the `;*`.
### Try it!
```
clicky.onclick=a=>{console.clear();console.log(eval(before.value+"\n;*/\\u)"+after.value));}
```
```
textarea {
font-family: monospace;
}
```
```
<button onclick="console.clear();">Clear console</button>
<br>
<textarea id=before placeholder="before string"></textarea>
<pre><code>
*/\u)</code></pre>
<textarea id=after placeholder="after string"></textarea>
<br>
<button id=clicky>Evaluate</button>
```
[Answer]
# Python, 10 bytes (not cpython)
```
?"""?'''?
```
### Edit:
Due to @feersum's diligence in finding obscure ways to break the Python interpreter, this answer is completely invalidated for any typical cpython environment as far as I can tell! (Python 2 and 3 for both Windows and Linux) I do still believe that these cracks will not work for Pypy on any platform (the only other Python implementation I have tested).
### Edit 2:
In the comments @EdgyNerd has found this [crack](https://tio.run/##K6gsycjPM/7/X1lBV0tXITk/JTMv3UohucDA2BwkwnVo@qGZhzoPTT202Leey15JScleXV3dnqs@9v9/AA) taking advantage of a non-ascii [encoding declaration](https://www.python.org/dev/peps/pep-0263/)! This seems to decode to `print("")`. I don't know exactly how this was found but I imagine the way to fix this sort of exploit would maybe be to try different combinations of any invalid characters where the `?`s are, and find one that doesn't behave well with any encoding.
---
Note the leading newline.
Cannot be commented out due to the newline, and no combination of triple quoted strings should work if I thought about this correctly.
@feersum in the comments seems to have completely broken any cpython program on Windows as far as I can tell by adding the 0x1A character to the beginning of a file. It seems that maybe (?) this is due to the way this character is handled by the operating system, apparently being a translated to an EOF as it passes through stdin because of some legacy DOS standard.
In a very real sense this isn't an issue with python but with the operating system. If you create a python script that reads the file and uses the builtin `compile` on it, it gives the more expected behavior of throwing a syntax error. Pypy (which probably does just this internally) also throws an error.
[Answer]
# [C (clang)](http://clang.llvm.org/), 16 bytes
```
*/
#else
#else
```
[Try it online!](https://tio.run/##S9ZNzknMS///X0FLn0s5Nac4FUr@/w8A "C (clang) – Try It Online")
`*/` closes any `/*` comment, and the leading space makes sure we didn’t just start one. The newline closes any `//` comment and breaks any string literal. Then we cause an `#else without #if` or `#else after #else` error (regardless of how many `#if 0`s we might be inside).
[Answer]
# Rust, 65540 bytes
```
`"###... a lot more #s ###
```
That is a backtick, quote, 65535 `#`s, and an invisible U+202A Per [this advisory](https://github.com/rust-lang/rust/security/advisories/GHSA-rcv6-wg5m-24v6) there is an issue with Unicode bidirectional overrides that can cause Unicode-aware editors to misrender the code, allowing bad actors to hide malicious code in plain sight. Starting in rust 1.56.1, rustc contains mitigation for that vulnerability, preventing the use of the relevant codepoints by default anywhere in the source code. However, the `text_direction_codepoint_in_literal` lint can be set to `allow` or `warn` to let use it in string literals. String literals are tricky to break out of, mainly because raw string literals are designed to allow any valid utf8 within them. However, take a look at rustc's lexer, and you will find something [interesting](https://github.com/rust-lang/rust/blob/4961b107f204e15b26961eab0685df6be3ab03c6/compiler/rustc_lexer/src/lib.rs#L173)- no more than 65535 hashtags are permitted in delimiters. Simply adding the quote followed by the long string of hashtags is enough to break any attempts at surrounding it in strings, and the U+202A is always invalid anywhere but a string. However there is another problem- someone could use the starting quote to begin a string, and hide the nastiness that way. This is where the backtick comes into play- it is an error anywhere but a literal or a comment, thus making it truly impossible for rust to contain this code. If you're wondering if there is an easier solution that fails after the lexer you'd be disappointed- anything that passes the lexer can be thrown away by a macro, and tacking on a `#[cfg(nope)]` will make anything that parses disappear.
edit: an actually valid answer this time
[Answer]
# Ada - 2 bytes
I think this should work:
```
_
```
That's newline-underscore. Newline terminates comments and isn't allowed in a string. An underscore cannot follow whitespace; it used to be allowed only after letters and numbers, but the introduction of Unicode made things complicated.
[Answer]
# Pyth, 6 bytes
```
¡¡$¡"¡
```
`¡` is an unimplemented character, meaning that if the Pyth parser ever evaluates it, it will error out with a PythParseError. The code ensures this will happen on one of the `¡`s.
There are three ways a byte can be present in a Pyth program, and not be parsed: In a string literal (`"` or `."`, which are parsed equivalently), in a Python literal (`$`) and immediately after a `\`.
This code prevents `\` from making it evaluate without error, because that only affects the immediately following byte, and the second `¡` errors.
`$` embeds the code within the `$`s into the compiled Python code directly. I make no assumptions about what might happen there.
If the program reaches this code in a `$` context, it will end at the `$`, and the `¡` just after it will make the parser error. Pyth's Python literals always end at the next `$`, regardless of what the Python code might be doing.
If the program starts in a `"` context, the `"` will make the string end, and the final `¡` will make the parser error.
[Answer]
# x86 32-bit machine code, 11 bytes (and future-proof 64-bit)
```
90 90 90 90 90 90 90 90 90 0f 0b
```
This is `times 9 nop` / `ud2`. It's basically a [NOP sled](https://en.wikipedia.org/wiki/NOP_slide), so it still runs as 0 or more `nop`s and then [`ud2`](http://felixcloutier.com/x86/UD2.html) to raise an exception, regardless of how many of the `0x90` bytes were consumed as operands to a preceding opcode. Other single-byte instructions (like `times 9 xchg eax, ecx`) would work, too.
# x86 64-bit machine code, 10 bytes (current CPUs)
There are some 1-byte illegal instructions in 64-bit mode, until some future ISA extension repurposes them as prefixes or parts of multi-byte opcodes in 64-bit mode only, separate from their meaning in 32-bit mode. `0x0e` is illegal in 64-bit mode on current CPUs (tested on Intel Skylake). It's [`push cs` in 32-bit mode](https://www.felixcloutier.com/x86/push); AMD64 [freed up](https://stackoverflow.com/questions/30938318/assembly-why-some-x86-opcodes-are-invalid-in-x64) a [bunch of opcodes](https://stackoverflow.com/questions/32868293/x86-32-bit-opcodes-that-differ-in-x86-x64-or-entirely-removed) for future use but as of yet neither Intel nor AMD have added any 64-bit-only extension to use them. But they still could, which is why this isn't future-proof; some future CPU could decode `0x0e` as an opcode or prefix.
```
0e 0e 0e 0e 0e 0e 0e 0e 0e 0e
```
---
**Rules interpretation for executable machine code**:
* The bytes can't be jumped over (like the "not parsed" restriction), because CPUs don't raise exceptions until they actually try to decode/execute (non-speculatively).
* Illegal means *always* raises an exception, for example an illegal-instruction exception. (Real programs can catch that with an exception handler on bare metal, or install an OS signal handler, but I think this captures the spirit of the challenge.)
---
[Answer]
# Shakespeare Programming Language, 2 bytes
```
.:
```
Explanation: If this string is in the title of the play, the `.` ends it and the `:` is not a valid character name. Similar problems occur in an act and scene name. No character can speak a line beginning with `:`, and the `.` will end a `Recall` statement, which can otherwise create a comment.
[Answer]
# [INTERCAL](http://www.catb.org/~esr/intercal/), 12 bytes
```
DOTRYAGAINDO
```
[Try to crack it online!](https://tio.run/##y8wrSS1KTsz5/9/FPyQo0tHd0dPPxf//fwA "INTERCAL – Try It Online")
INTERCAL's approach to syntax errors is a bit special. Essentially, an invalid statement won't actually error unless the program tries to execute it. In fact, the idiomatic syntax for comments is to start them with `PLEASE NOTE`, which really just starts a statement, declares that it isn't to be executed, and then begins it with the letter `E`. If your code has `DODO` in the middle of it, you could prepend `DOABSTAINFROM(1)(1)` and tack any valid statement onto the end and you'll be fine, if it's `DODODO` you can just bend execution around it as `(1)DON'TDODODOCOMEFROM(1)`. Even though INTERCAL lacks string literal syntax for escaping them, there's no way to use syntax errors to create an illegal string, even exhausting every possible line number with `(1)DO(2)DO...(65535)DODODO`, since it seems that it's plenty possible to have duplicate line numbers with `COME FROM` working with any of them.
To make an illegal string, we actually need to use a perfectly valid statement: `TRY AGAIN`. Even if it doesn't get executed, it strictly must be the last statement in a program if it's in the program at all. 12 bytes is, to my knowledge, the shortest an illegal string can get using `TRY AGAIN`, because it needs to guarantee that there is a statement after it (executed or not) so `DOTRYAGAIN` is just normal code, and it needs to make sure that the entire statement is indeed `TRY AGAIN`, so `TRYAGAINDO` doesn't work because it can easily be turned into an ignored, normal syntax error: `DON'TRYAGAINDOGIVEUP`, or `PLEASE DO NOT TRY TO USE TRYAGAINDO NOT THAT IT WOULD WORK`. No matter what you put on either side of `DOTRYAGAINDO`, you'll error, with either `ICL993I I GAVE UP LONG AGO`, `ICL079I PROGRAMMER IS INSUFFICIENTLY POLITE`, or `ICL099I PROGRAMMER IS OVERLY POLITE`.
[Answer]
## Commodore 64 Basic, 2 bytes
```
B
```
(that's a newline followed by the letter "B").
Any line in a Commodore 64 program must begin with either a line number or a BASIC keyword, and stored programs only permit line numbers. There are no keywords beginning with "B" (or "H", "J", "K", "Q", "X", "Y", or "Z").
[Answer]
# [APL](https://www.dyalog.com/) and [MATL](https://github.com/lmendo/MATL) and [Fortran](https://gcc.gnu.org/fortran/), 3 bytes
```
'
```
Newline, Quote, Newline always throws an error since block comments do not exist:
* APL: [`unbalanced quotes`](https://tio.run/##SyzI0U2pTMzJT///n0ud6/9/AA "APL (Dyalog Unicode) – Try It Online")
* MATL: [`string literal not closed`](https://tio.run/##y00syfn/n0ud6/9/AA "MATL – Try It Online")
* Fortran: [`Invalid character in name`](https://tio.run/##S8svKilKzNNNT4Mw/v/nUuf6/x8A "Fortran (GFortran) – Try It Online")
[Answer]
# C#, 16 bytes
```
*/"
#endif<#@#>
```
Works because:
* `//` comment won't work because of the new line
* `/*` comment won't work because of the `*/`
* You can't have constants in the code alone
* Adding `#if false` to the start won't work because of the `#endif`
* The `"` closes any string literal
* The `<#@#>` is a nameless directive so fails for T4 templates.
* The new line tricks it so having `/` at the start won't trick the `*/`
Each variation fails with a compilation error.
[Answer]
# [Desmos](https://www.desmos.com/calculator), 3 bytes
```
\
```
(linefeed, backslash, linefeed)
I recently said "[Pasting in invalid-formatted text [into Desmos] simply does nothing.](https://codegolf.stackexchange.com/a/220829/96155)" As I recently discovered, this isn't quite true. When pasting in multiple lines, it's happy to throw errors if one of them is invalid. Now, this works even if some of those lines other are blank, causing them to be ignored. Therefore, we make a `\` on its own line, which is guaranteed to throw an error.
Logically, we *should* be able to knock this down to two bytes (`\`, `LF`), as no legal line can end with a `\`. However, Desmos strangely interprets this as an empty list (normally represented as `[]`), for reasons I don't understand. This makes that two-byte string an unusual almost-illegal string, where the only valid program containing that string is the string itself.
[Answer]
# [Literate Haskell](https://www.haskell.org/onlinereport/literate.html), 15 bytes
Repairing a [deleted attempt](https://codegolf.stackexchange.com/a/133563/) by nimi.
```
\end{code}
5
>
```
[Try it online!](https://tio.run/##y0gszk7NydHNySxJLUosSf3/nysmNS@lOjk/JbWWy5TL7v9/AA "Literate Haskell – Try It Online")
nimi's original attempt is the last two lines, based on Literate Haskell not allowing `>` style literate code to be on a neighboring line to a literate comment line (`5` here). It failed because it can be embedded in a comment in the alternate ("LaTeX") literate coding style:
```
\begin{code}
{-
5
>
-}
\end{code}
```
However, the `\begin{code}` style of Literate Haskell does *not* nest, neither in itself nor in `{- -}` multiline comments, so by putting a line with `\end{code}` just before the line with the `5`, that workaround fails, and I don't see a different one.
[Answer]
# Free Pascal, 18 bytes
```
*)}{$else}{$else}
```
First close all possible comments, then handle conditional compile.
Please comment here if I forgot something.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 7 bytes
```
"e#"
:"
```
[Try it online!](https://tio.run/##S85KzP3/XylVWYnLSun/fwA "CJam – Try It Online")
[Answer]
# [Brain-Hack](https://github.com/Flakheads/BrainHack/releases/tag/v1.0) (a variation of [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak)), ~~3~~ 2 bytes
Thanks to [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for pointing out that Brain-Hack doesn't support comments, saving me a byte.
```
(}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/n0uj9v9/AA "Brain-Flak – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~9~~ 8 bytes
```
`*/
\u`~
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/QUufK6Y0oe7/fwA "JavaScript (Node.js) – Try It Online")
I think this should be illegal enough.
## Previous JS attempts in other answers
>
>
> ```
>
>
> ;*/\u)
>
> ```
>
> By @Cows quack
>
>
> As an ES5 answer this should be valid, but in ES6 wrapping the code with a pair of backticks wrecks this. As a result valid ES6 answers must involve backticks.
>
>
>
> ```
>
> `
> `*/}'"`\u!
>
> ```
>
> By @iovoid
>
>
> This is an improved version involving backticks. However a single `/` after the code breaks this (It becomes a template literal being multiplied by a regex, useless but syntactically valid.) @Neil made a suggestion that changing `!` to `)`. This should theoretically work because adding `/` at the end no longer works (due to malformed regex.)
>
>
>
## Explanation
```
`*/
\u`~
```
[This is by itself illegal, and also blocks all single and double quotes because those quotes cannot span across lines without a `\` at the end of a line](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/QUufK6Y0oe7/fwA "JavaScript (Node.js) – Try It Online")
```
//`*/
\u`~
```
and
```
/*`*/
\u`~
```
[Blocks comments by introducing](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fXz9BS58rpjSh7v9/AA "JavaScript (Node.js) – Try It Online")
[illegal escape sequences](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fXytBS58rpjSh7v9/AA "JavaScript (Node.js) – Try It Online")
```
``*/
\u`~
```
[Blocks initial backtick by introducing non-terminated RegExp literal](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/IUFLnyumNKHu/38A "JavaScript (Node.js) – Try It Online")
```
console.log`*/
\u`~
```
[Blocks tagged template literals by introducing an expected operator between two backticks](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nPz1BS58rpjSh7v9/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Go](https://golang.org/), 6 bytes
```
*/```
```
[Try to crack it online!](https://tio.run/##S8///59LSz8hIeH/fwA "Go – Try It Online")
The grave accent (`) marks a raw string literal, inside which all characters except `, including newlines and backslashes, are interpreted literally as part of the string. Three `'s in a row are the core: adjacent string literals are invalid and ` always closes a ` string, so there's no way to make sense of them. I had to use 3 more bytes for anti-circumvention, a newline so we can't be inside a single-line comment or a normal quoted string, and a \*/ so we can't be inside a multi-line comment.
[Answer]
# Google Sheets, Excel; 3 bytes
For a single-cell Formula (starts with `+` or `=`). Otherwise, you can just put whatever arbitrary text you want into a cell.
Here it is: `1"1`
* A string has to be enclosed in `"`s. A double quote must be escaped by `""`.
* The `"` has to be a string token boundary.
* If it's the end, following a string with a 1 is illegal.
* If it's the beginning, preceding a string with a 1 is also illegal.
[Answer]
## Swift, ~~4~~ 3 bytes
There's control characters in here, so I'll just give their ASCII values: `0A 22 00`.
Most of the ways that other C-family languages do this don't work in Swift, because Swift allows nested block comments.
The null character always generates at least a warning. However, if it's in the middle of whitespace or a line comment, it's *only* a warning, not an error. Additionally, Xcode lets you put most control characters inside of a block comment and just rolls with it.
Emphasis on most. For some reason, if you have a null byte in the middle of a block comment or string literal, the Swift compiler gets lost and can't find the end, no matter where it is. This causes an error (and also breaks Xcode's syntax highlighting).
So, this is three bytes:
* `0A` -- a newline, to make sure we're not in a line comment or single-line string literal.
* `22` -- `"`, the start of a single-line string literal, unless it's inside a multi-line string literal or block comment. This does not end a multi-line string literal if it started inside of one.
* `00` -- a null byte, to prevent the block comment or string literal from terminating.
The original answer used `/*` (open block comment) rather than `"`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 4 bytes
```
»»
€
```
[Try it online!](https://tio.run/##y0rNyan8///Q7kO7uR41rfn/HwA "Jelly – Try It Online")
Alternative 4 bytes:
```
»
€
```
*+1 byte because [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) found an issue with the old approach*
Jelly has no comments, and every line in the code is parsed whether or not it is reachable. The only way to prevent some code from being executed is by putting it in a string literal. There are different types of string literals based on the ending character, but almost all start with `“`. This is countered by `»`, which terminates a string (and interprets it as a dictionary-compressed string).
The only two string literal types that do not terminate at the first `»` are `⁾` and `⁽`, which each process precisely the next two characters. However this still leaves the newline unescaped.
Thus `€` (each/map) will always be executed on a link (line) of its own. It tries to get a link from its left; since none exists, the interpreter errors.
[Answer]
# VBA, 2 Bytes
A linefeed followed by an underscore - the `_` functions as the line continuation character in VBA, and as there is nothing in the line directly to the left or above the line continuation, coupled with VBA's lack of multiline comments means that this will always throw the compile time error `Compile Error:` `Invalid character`
```
_
```
[Answer]
# SmileBASIC, 2 bytes
```
!
```
Nothing continues past the end of a line, so all you need is a line break followed by something which can't be the start of a statement. `!` is the logical not operator, but you aren't allowed to ignore the result of an expression, so even something like `!10` would be invalid (while `X=!10` works, of course)
Similar things will work in any language where everything ends at the end of a line, as long as it parses the code before executing it.
There are a lot of alternative characters that could be used here, so I think it would be more interesting to list the ones that COULD be valid.
`@` is the start of a label, for example, `@DATA`; `(` could be part of an expression like `(X)=1` which is allowed for some reason; any letter or `_` could be a variable name `X=1`, function call `LOCATE 10,2`, or keyword `WHILE 1`; `'` is a comment; and `?` is short for `PRINT`.
[Answer]
# [Rockstar](https://github.com/dylanbeattie/rockstar), ~~4~~ 5 bytes
*Crossed out 4 is still 4 :(*
```
)
"""
```
Rockstar is a very... wordy language.
While `"` can be used to define a string, such as `Put "Hello" into myVar`, to my knowledge there is no way for 3 quotes to appear outside of a comment, and the close paren ensures that won't happen either (Comments in Rockstar are enclosed in parentheses, like this).
Rockstar also has a poetic literal syntax, in which punctuation is ignored, so the newline makes sure that the 3 quotes are the start of a line of code, which should always be invalid
[Answer]
## TI-Basic (83+/84+/SE, 24500 bytes)
```
A
```
(24500 times)
TI(-83+/84+/SE)-Basic does syntax checking only on statements that it reaches, so even 5000 `End` statements in a row can be skipped with a `Return`. This, in contrast, cannot fit into the RAM of a TI-83+/84+/SE, so no program can contain this string. Being a bit conservative with the character count here.
The original TI-83 has 27000 bytes of RAM, so you'll need 27500 `A`s in that case.
## TI-Basic (89/Ti/92+/V200, 3 bytes)
```
"
```
Newline, quote, newline. The newline closes any comments (and disallows embedding the illegal character in a string, since AFAIK multiline string constants are not allowed), the other newline disallows closing the string, and the quote gives a syntax error.
You can get to 2 bytes with
```
±
```
without the newline, but I'm not sure whether this counts because `±` is valid only in string constants.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 4 bytes
```
/
```
[Try it online!](https://tio.run/##SyzP/v@fi0uf6/9/AA "AWK – Try It Online")
Since `AWK` doesn't have a method to do multi-line comments, need 2 newlines before and 1 after `/` to prevent commenting out or turning this into a regex, e.g. add `1/`. The most common message being `unexpected newline or end of string.
[With previous crack](https://tio.run/##SyzP/v9fP4aLS5/r//9ELiAEAA "AWK – Try It Online")
] |
[Question]
[
Write a function or program that determines the *cost* of a given string, where
* the cost of each character equals the number of how many times the character has occurred up to this point in the string, and
* the cost of the string is the sum of its characters' costs.
### Example
For an input of `abaacab`, the cost is computed as follows:
```
a b a a c a b
1 2 3 4 occurrence of a
1 2 occurrence of b
1 occurrence of c
1+1+2+3+1+4+2 = 14
```
Thus the cost for the string `abaacab` is 14.
### Rules
* **The score of your submission is the cost of your code as defined above**, that is your submission run on its own source code, with a **lower** score being better.
* Your submission should work on strings containing printable ASCII-characters, plus all characters used in your submission.
* Characters are case-sensitive, that is `a` and `A` are different characters.
### Testcases
```
input -> output
"abaacab" -> 14
"Programming Puzzles & Code Golf" -> 47
"" -> 0
" " -> 28
"abcdefg" -> 7
"aA" -> 2
```
### Leaderboard
```
var QUESTION_ID=127261,OVERRIDE_USER=56433;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} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</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]
# [MATL](https://github.com/lmendo/MATL), score 4
```
&=Rz
```
[Try it online!](https://tio.run/##y00syfn/X802qOr/f/XEpMTE5MQkdQA "MATL – Try It Online")
### Explanation
Consider input `'ABBA'` as an example.
```
&= % Implicit input. Matrix of all equality comparisons
% STACK: [1 0 0 1;
0 1 1 0;
0 1 1 0;
1 0 0 1]
R % Upper triangular part
% STACK: [1 0 0 1;
0 1 1 0;
0 0 1 0;
0 0 0 1]
z % Number of nonzeros. Implicitly display
% STACK: 6
```
[Answer]
# [Python](https://docs.python.org/2/), score 49
```
lambda S:sum(1+S.count(C)for[C]in S)/2
```
[Try it online!](https://tio.run/##JYu9CoMwFEZnfYrLHUrE0lJHwSmDq5DROqQxsYH8SKLQ@vJppGf7ON9Zv9vbuyYJP8vumdBw@5o5sDbuljxqdhN@dxuhlfJhpJN2BavuDSb5kQJVh/UZlllCBO1gPOcVcAh@Cdxa7RYY9uMwMsIFaJbQe6MwX@APTm1ZrEG7DRSJVfoB "Python 2 – Try It Online")
There's a tab after `in`.
Score breakdown:
* +27 for 27 unique chars
* +16 for 8 double chars: `()Camnou`
* +6 for 1 tripled char: `S`
[Answer]
# T-SQL, score ~~775 579!~~ 580
```
declaRe @ char(876),@x int,@v int=0Select @=q+CHAR(9)from z X:seleCT @x=len(@),@=REPLACE(@,LEFT(@,1),''),@v+=(@x-LEN(@))*(@x-LEN(@)+1)/2IF LEN(@)>0GOTO X prINT @v-1
```
**EDIT**: Dropped a couple of variables, compacted a bit. Down to 16 `@` symbols instead of 22, that by itself reduces my score by a whopping 117 points!
Nice contest, I like the requirement to optimize for something besides total character count.
Input is via varchar field *q* in pre-existing table *z*, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). The database containing this input table must be set to a *case-sensitive collation*.
Formatted:
```
declaRe @ char(876), @x int, @v int=0
Select @=q+CHAR(9)from z
X:
seleCT @x=len(@)
,@=REPLACE(@,LEFT(@,1),'')
,@v+=(@x-LEN(@))*(@x-LEN(@)+1)/2
IF LEN(@)>0 GOTO X
prINT @v-1
```
SQL keywords aren't case sensitive, so I used mixed case to minimize the count of duplicate letters (*aaAA* generates a better/lower score than *aaaa*).
The main loop compares the length before and after stripping all instances of the first character out. That difference n\*(n+1)/2 is added to a running total.
The SQL `LEN()` function annoyingly ignores trailing spaces, so I had to append a control character and subtract 1 at the end.
**EDIT**: Fixed a miscalculation of my own score by 2 points (issue with quoting quotes), reduced by 1 by changing casing of one `R`. Also working on a completely different strategy, I'll be posting that as its own answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score: ~~113~~ ~~103~~ ~~100~~ ~~96~~ 91
*Thanks to @ugoren, @CalculatorFeline, @gastropner, @l4m2, and @JS1 for their tips.*
```
g(char*s){int y[238]={};while(*s)*y-=--y[*s++];*y/=1;}
```
Initializes an array of zeros, then uses the ASCII values of the characters in the string as indices to that array to keep track of the number of instances of each character in the string.
[Try it online!](https://tio.run/##nY2xDoIwFEV3vuKFRNMWG6MuRsJgHFxJHIGhlFKaQDFFYwrh2xFwMjEM3vHe887jVHI@DBLxghnS4E7pB9hofzgmQdf7r0KVAo09sTSg1Eak8bzEJ3Yb7Px@mOCKKY2w0zkw5m7GKkfujddGnGCVxTrW7gYkcv974WLsO1/qyfkxspQxztIZ@U2EppaGVZXSEsJn25aigTVc6kzAtS7zhcuFCT5ZIFjKM5HLJeI8j/3wBg)
[Answer]
# JavaScript (ES6), score ~~81~~ 78
*Saved 3 points thanks to @Arnauld*
```
s=>s.replace(d=/./g,z=>q+=d[z]=-~d[z],q=0)&&q
```
My original score-81 recursive solution:
```
f=([c,...s],d={})=>c?(d[c]=-~d[c])+f(s,d):0
```
[Answer]
# [Haskell](https://www.haskell.org/), score 42
```
f l=sum[1|c<-l,d<-c:l,d==c]/2
```
[Try it online!](https://tio.run/##fYuxDoIwFEV/5aYxTBAjo6GTgys7YXiUFhvfa0kLC/Hfq/yA0znDOS/Kb8tcigPrvMtw@5iu4XruGnP/QWszXtsi5AM01uTDhguEVjgM6u@kaiiaiAxNp/YpLolEfFjQ78fBNqPCI84Wz8juTNRYvg "Haskell – Try It Online")
Anonymizing `\l->` gives the same score.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 6
```
;\ċ"⁸S
```
[Try it online!](https://tio.run/##y0rNyan8/9865ki30qPGHcH/kdgA "Jelly – Try It Online")
[Answer]
## [Retina](https://github.com/m-ender/retina), score 34
```
s(O`.
M&!`^|(?<=(.))\1*
.
```
[Try it online!](https://tio.run/##K0otycxL/P@/WMM/QY/LV00xIa5Gw97GVkNPUzPGUItLD48UAA "Retina – Try It Online")
### Explanation
```
s(O`.
```
We start by sorting all the characters in the input so that identical characters are grouped together into a single run. The `s(` activates singleline mode for all stages (i.e. makes `.` match linefeeds).
```
M&!s`^|(?<=(.))\1*
```
The goal is to turn a run of **n** characters into **Tn** characters (the **n**th triangular number) because that's the score of the occurrences of this character. To do so, we find overlapping matches. In particular, for each **i** in **[1,n]**, we're going to include **i-1** characters in the match. We get all those matches due to the overlapping flag `&`. That gives us **n\*(n-1)/2 = Tn-1 = Tn - n** characters just from the matches. But the match stage will join these with linefeeds, which are **n** linefeeds for **n** matches. There's only one problem. There won't be a linefeed after the last match, so the overall number of characters in the output is one less than we need. We fix this by also matching the beginning of the input, which gives us a single leading linefeed if there is at least one other match.
```
.
```
Finally, we just count how many characters there are in the string.
[Answer]
## Haskell, score ~~52~~ 51
```
f(a:b)=1+sum[1|c<-b,c==a]+f b;f _=0
```
There's a tab between `f` and `_`.
[Try it online!](https://tio.run/##hY49C8IwGAZn/RUPQUSpgl3VTA5du6vImzRpg/koSbsU/3t0zuJ4xw03UHora3PWOzqLPa@rNLt7/ZHXozhIzulZaYiLXr34KTsyHhxdwBrAGI2fsIEGI0EkSbBCtzH0kZwzvkc7L4tVCVvcQqfQBKvLvOQ/S4/p98TyFw "Haskell – Try It Online")
The value of the empty string is 0. The value of the string s, where `a` is the first char and `b` the rest of the string is 1 plus the occurrences of `a` in `b` plus a recursive call with b.
[Answer]
## [J](http://jsoftware.com/), score 16
```
1#.,@(*+/\"1)&=
```
[Try it online!](https://tio.run/##y/r/P03B1krBUFlPx0FDS1s/RslQU832f2pyRr5CmoJ6YlJiYnJikjoXTABNofp/AA "J – Try It Online")
## Explanation
```
1#.,@(*+/\"1)&=
= Self-classify: bit matrix of equality between input
and its unique elements.
( )& Apply verb in parentheses to it:
+/\ running sums
"1 of each row
* multiplied with original matrix.
This causes the i'th 1 on each row to be replaced by i.
,@ Flatten the resulting matrix
1#. and interpret as a base-1 number, computing its sum.
```
Using `1#.` instead of `+/@` for the sum saved a few points, and `&` could be used instead of `@` in a monadic context to save one more.
The repeated `1` costs me one extra point, but I haven't been able to get rid of it.
[Answer]
# [R](https://www.r-project.org/), score: 67 ~~83~~ ~~95~~ ~~128~~
*-61 thanks to top tips from Giuseppe*
```
function(x,y=table(utf8ToInt(x)))y%*%{y+1}/2
```
[Try it online!](https://tio.run/##jZFNa8MwDIbv@xUmrIvUFkp6Gowcxg5jh0EPu5Ue7MTODI4dbAfqlv72zIn3wTpoJ4yNhJ5XL7IdlGSW2gB5y/27qV2ON6IcRK8rL42G/TKUnjLFoffi/s28aA97RAyz@ewYFsVptR4E5JRRWlE2wpBvrGksbVupG7LpDwfFHbkjT6bm5NkokZrSTVKkhLKq5qL5TB7T@yqdG0/XyamQ/VhD17cAurTRnTPWA1fgvHWdktHkMo6IcatwtZ6DXhSI2bnA8Sr8MM7Q3wqnixK/@e222O3@p/G14zMDExgiOG36L3j9bzIcPgA "R – Try It Online")
The string is split using `utf8ToInt` and each ascii value is counted `table`. The the result is calculated using doing a matrix multiplication `%*%` over that at itself + 1 and finally halfed.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score 6
```
{γ€gLO
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@tzmR01r0n38kZgA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 5
```
ĠJ€ẎS
```
[Try it online!](https://tio.run/##y0rNyan8///IAq9HTWse7uoL/o/MAQA "Jelly – Try It Online")
Thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for -2 (previously on [his answer](https://codegolf.stackexchange.com/a/127265/41024))
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score 6
1 byte thanks to isaacg.
```
+F/V._
```
[Test suite.](http://pyth.herokuapp.com/?code=%2BF%2FV._&test_suite=1&test_suite_input=%22s%2B0%2FV._%22%0A%22abaacab%22%0A%22Programming+Puzzles+%26+Code+Golf%22%0A%22%22%0A%22+++++++%22%0A%22abcdefg%22%0A%22aA%22&debug=0)
## How it works
```
+F/V._
+F/V._QQ implicit input
/V vectorize count: for each element in the first argument,
count the number of occurrences of the
second argument:
._Q all prefixes of input
Q input
+F fold (reduce) on +, base case 0.
```
[Answer]
# [J](http://jsoftware.com/), score: ~~14 12~~ 11
```
$+/@,2!1#.=
```
[Try it online!](https://tio.run/##y/pfZmulUGtloGBl8F9FW99Bx0jRUFnP9r8mV0q@gnqarZ66ThlXanJGvkKagnpiUmJicmKSOlwgoCg/vSgxNzczL10hoLSqKie1WEFNwTk/JVXBPT8nDaEQwVKAALhA2X8A)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score of 7
```
ċЀQRFS
```
Explanation:
```
Q get unique letters
ċЀ count the occurences of each letter in the original string
R [1..n] for n in list of frequencies
F flatten list
S sum
(implicit output)
```
[Try it online!](https://tio.run/##y0rNyan8//9I9@EJj5rWBAa5Bf9H4QEA "Jelly – Try It Online")
[Answer]
# C, 60 bytes, score 108 95
```
g(char*s){int y[256]={},z=0;while(*s)z-=--y[*s++];return z;}
```
[Try it online!](https://tio.run/##pY3dDoIgAIVfhdnaAKFlW92Qvohx4QCBTakh2sT57AbP0N3Z@fmOoFqI42SdGGapwHMK0r4vpjk0FKbzeEKbdQGs7e3@4PW2k1hf2dfYQcGURVpTurZ4KkvOvAqzdyCy/Rg762DedV4LkkEA46SXROthNpsKfXxq9LA4y5criM720lYcoQT46/4H "C (gcc) – Try It Online")
Usually pre- and post-increment operators are great for code golf, but they really hurt on this challenge!
EDIT: By subtracting negative counts instead of adding positive ones, I saved a whole bunch of score. Replacing `for()` with `while()` eliminated a semicolon as well.
[Answer]
# [Perl 6](https://perl6.org), score ~~61 56 53 46~~ 44
```
(1 X..*.comb.Bag.values).flat.sum
```
[Try it](https://tio.run/##hY9PT8MwDMXv@RRPY1o2NEUMTQMp4gAcuO7AgdvkpklXKSFV3UzaEJ@99I@gXBC@2P7p2c@ubO13bWKL004ZLcIZCxO5wUO73OBNqWtlYsjUExXqRD5ZXinnqVGcQqsF0xny9WhhYm5RNmy9w5EYhGFLdJDrsZT/7pNaVKkTdllwypCXXPnOYIn5ASt8CKD3U1V38xryD5/5QYtPIb6HJWVEhjKpcYXN9ofP9nUsagqhfC@wT5eLt4wFnvs/XqJ3s16/vZv0A7iZeowx4Nv7iVNmcuuKgf8ap8dR2X4B "Perl 6 – Try It Online")
```
{sum flat 1 X.. .comb.Bag.values}
```
[Try it](https://tio.run/##hY9Pa8MwDMXv/hSPrtQbFLOO0g7CDtsOu/aww25Fduw0YM8higtt6WfP8octu4zpIunHk55U2dpv2sQWx40ymQgnLEzkBk/thVOA89RghQ@loEwMWr1QoY7kk@Vry3SCfD9YmJhblA1b73AgBmHYER3kcizlv9tkJqrUCbssOGnkJVe@M7jFfI87XATQ@6mqu3gJ@YfPfJ@JqxDfw5I0kSEtM9xgtf7hs10di5pCKD8L7NL57C1jgdf@j7fo3azXr7eTfgD3U48xBvzwOHHSJreuGPivcXoele0X "Perl 6 – Try It Online")
```
{sum flat 1 X.. values(.comb.Bag)}
```
[Try it](https://tio.run/##hY9Pa8MwDMXv/hSPrtQtFLOO0g5CD9sOu/aww25Fcew0YNchigtt6WfP8octu4zpIunHk55UmsptmsgG543SifAXzHTgGrvmxtHDOqqxwqdSOJOLhudKB5@qV8oX94bpAvlxNNAhMyhqNs7iSAxCvyRYyOVQyv/XyUSUsVW2WXBMkRVcutZhjukBC9wE0Bmqsr15CfmH0fSQiLsQ38OSUiJNqUzwgNX6h0/2Vcgr8r445djH69UZxgxv3SPvwdlJp19vR30PHsceQ/T46XnklOrM2Lznv8bpZVA2Xw "Perl 6 – Try It Online")
```
{[+] flat 1 X.. values(.comb.Bag)}
```
[Try it](https://tio.run/##hY9PawIxEMXP5lM8VIyihFrEFhYP2kOvHnoolCKTbLIuZM2y2Qgqfvbt/qHdXkrnMjM/3sybyXVh11XwGue1UBHLLpgo50tsqtvH/BPGUjlYDt6FwJls0H4qlMuk2FEyu1eeLuBvRw3lYo209NoaHMmD0C5xBnzRlfz/dTxieaiVdWY@SMSpz23tMMX4gBluDGgMRV7fvAD/w2h8iNidse9hTpJIkeQRRliufvhwX7ikoCxLTwn24Xq12mOCl@aRV2fNsNGvnnp9Cx76Hl20@PG55yRVrE3S8l/jtO2U1Rc "Perl 6 – Try It Online")
```
{[+] flat 1 X.. values(bag
.comb)}
```
[Try it](https://tio.run/##hY9PawIxEMXP5lM8rBilEmoRW1g8lB569dCDIEUm2WRdyJplsxFU/Ozr/qFdL9K5zMyPN/Nmcl3YZRW8xnEpVMSyE8bK@RKr6rJ9/oGxVA7mg40QOJIN2k8kJUwol8nptfJ0Av/eaygXa6Sl19ZgTx6Edokz4LOu5P@v4xHLQ62sM/NBIk59bmuHCUY7THFhQGMo8vrmGfgDo9EuYlfGfoc5SSJFkkd4wnzxx4frwiUFZVl6SLAO57PVHmN8No98OWuGjX7x1utb8NL36KLFr@89J6libZKW343TR6esbg "Perl 6 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), score ∞ (I mean, 209)
```
b=>b.Distinct().Select(z=>{var w=b.Count(p=>p==z);return w*(w+1)/2;}).Sum()
```
[Try it online!](https://tio.run/##rVA9a8MwEN39K44MQeqHTEqggysvLu3SQiBDZ1mRg0CWEn3E1MG/3ZWMm0K7ZOgbjuM@3r173N1zY8UIEcFJvYftp/OiJW9SH4ssS3WumHOwsWZvWTtVzlNMcJ55yeFk5A7emdQIX1o/Qwkz7UvQ/Ml5Gy/dgdS@hAZoNta0rMmzdF5q7hEmW6FETHpank/MQkdrUpmgPTrQ8kBpjwsrfLAauhvU3a5w/lAMcSu0CI@z6l@HK6OdUYJ8WOlFfE6gBi1YzRhn9QLjAvIcVuurN2c32uTYJvS9Eg6WUJmdgFejmm/G9ePVjH/d/0dTkp6LkmHKhvEL "C# (.NET Core) – Try It Online")
The score includes the following:
```
using System.Linq;
```
[Answer]
## PowerShell, score 64
```
$z=@{}
$ARGS|% getE*|%{$u+=($Z.$_+=1)};$U
```
(Score is based on a single linefeed newline, which isn't Windows standard but does work in PS).
```
PS C:\> D:\unique-is-cheap.ps1 (gc D:\unique-is-cheap.ps1 -raw)
64
```
* Hashtable counter `@{}`
* Iterate through the letters; `$args` is an array of parameters - in this case the input string makes it a single item array; `|%` does a foreach loop over the items, and uses the `getE*` shortcut to match the `GetEnumerator()` string method and call it to turn the string into a character stream.
* `|%` loop over the characters and increment their hashtable entry, add it to a running total. The `($x+=1)` form with parens both modifies the variable and outputs the new value for use.
* Output the running total.
(When I first wrote it, it was `$c=@{};$t=0;[char[]]"$args"|%{$c[$_]++;$t+=$c[$_]};$t` with a score of 128, and felt like it wouldn't go much lower. Halving it to 64 is quite pleasing).
[Answer]
# [Julia 0.6](http://julialang.org/), 45 bytes, Score: 77
Inspired by the MATL solution:
```
f(w)=sum(UpperTriangular([z==j for z=w,j=w]))
```
[Try it online!](https://tio.run/##yyrNyUw0@/8/TaNc07a4NFcjtKAgtSikKDMxL700J7FII7rK1jZLIS2/SKHKtlwny7Y8VlPzf3ByflGqgq1CQVFmXolGmoYSSdqVgCYAAA "Julia 0.6 – Try It Online")
A less pretty solution, using counts:
[Julia 0.6](http://julialang.org/), score: 82
```
F(w)=sum(l->[l+1]l/2,count(x->x==i,w)for i=Set(w))
```
[Try it online!](https://tio.run/##yyrNyUw0@//fTaNc07a4NFcjR9cuOkfbMDZH30gnOb80r0SjQteuwtY2U6dcMy2/SCHTNji1BKhY839BUSZQ1k1DiXS9SkDtAA "Julia 0.6 – Try It Online")
Thanks to Guiseppe for pointing out the scoring and for tips.
These comments helped me loads.
[Answer]
# Java 10, score: ~~149~~ ~~138~~ ~~137~~ ~~134~~ ~~133~~ ~~130~~ ~~103~~ ~~102~~ ~~101~~ 100
(**Bytes: ~~72~~ ~~73~~ ~~74~~ ~~75~~ ~~64~~ ~~62~~ 61**) ~~Bytes go up, but score goes down. :D~~
```
x->{int j=0,q[]=new int[256];for(var C:x)j+=++q[C];return
j;}
```
-28 score (and -11 bytes) thanks to *@Nevay*.
-1 score (and -2 bytes) thanks to *@OlivierGrégoire*.
-1 score (and -1 byte) by converting Java 8 to Java 10.
**Explanation:**
[Try it here.](https://tio.run/##lZE/b4MwEMXn8ilOGSojGlRVaociKkUMnRpFykgYDmMoFOzkbGj@iM9OTeiYSsWyhzvfe/eTXoUdLqvsa@A1ag0fWMqLA1BKIyhHLmA9ltcGcMY/keIEtBvYZm@fvdqgKTmsQUIIw3H5dhlnq/Dx4RAnoRTfozZ@en5JglwR65DuotejW3mh5x3iKAlImJakUwX9EEyW@zatreWvc6fKDBoLxraGSllYAHQnqu1JG9H4qjX@3n6ZWjLpc7bAFJFjuvCNiizyighPzHWv2H@rNqQKwqaxO2DTns@10HAPkcoEvKs6n@k2cxymM1OFKc9EXsxVrWYK/pPqztyKdSdtrje39U4//AA)
```
x->{ // Method with character-array parameter and integer return-type
int j=0, // Result-integer, starting at 0
q[]=new int[256]; // Integer-array with 256 times 0
for(var C:x) // Loop over the characters of the input array
j+=++q[C]; // Raise the value in the array by 1,
// and then add it to the result-integer
return // Return
j;} // the result
```
[Answer]
## F#, score 120 118
```
let j z=Seq.countBy id z|>Seq.sumBy(fun x->List.sum[0..snd x])
```
-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
[Try it online!](https://tio.run/##pc/NioMwFAXgvU9xCLQojNL9TLPoMHQzC6FL6yLVKBlMYvMzVOm720RhXmB2h8vHufd2Nm@04csycIcfzMcLvxeN9sqdJogW85PGifXyNKWdV3jk9FtYFyfVoSisavGos6X6@FLOTKUWytE6iW2SCQVm@l8cE1SEvIOwG2MNu8VYGt0bJqVQPUo/zwO32ONTtxxnPXSR/O8kUid4UkQq2YhVCjV6h5wiXdNbqF9Dlv1Z4bjZ8MiEsQEnwGjCW50C2dmr2wkSgHUbyJDGhVsONYflBQ)
Takes a `string` as an input. `Seq.countBy` pairs each distinct character with its count (`id` is the identity function) so you end up with a collection like `'a' = 4, 'b' = 2` etc.
The `Seq.sumBy` takes the count for every letter and sums all the numbers from `0` to the count for that letter. So if `'a' = 4` the collection would be `0, 1, 2, 3, 4` which summed together is `10`. Then `Seq.sumBy` sums all those totals.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), Score: 4
```
≠+´⊒
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omgK8K04oqSCgo+4ouI4p+cRsKoIOKfqCLiiaArwrTiipIiCiJhYmFhY2FiIgoiUHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZiIKIiIKIiAgICAgICAiCiJhYmNkZWZnIgoiYUEi4p+p)
The *occurrence count* builtin `⊒` calculates the cost of each character decremented by 1. To adjust for that we can either add 1 to each cost or add the length `≠` to the sum. The latter turns out to be a byte shorter.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), score 15
```
+/1 1⍉+\∘.=⍨⍞
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdOb@45L@2vqGC4aPeTu2YRx0z9Gwf9a541DsPJPtfAQxAirgSkxITkxOTuJCEsOoDAA "APL (Dyalog Unicode) – Try It Online")
`⍞` get text input
`∘.=⍨` equality table with self
`+\` cumulative sum across
`1 1⍉` diagonal (lit. collapse both dimensions into dimension one)
`+/` sum
[Answer]
# [Retina](https://github.com/m-ender/retina), score ~~68~~ ~~45~~ 43
```
s`(.)(?<=((\1)|.)+)
$#3$*
1
```
[Try it online!](https://tio.run/##K0otycxL/P@/OEFDT1PD3sZWQyPGULNGT1Nbk0tF2VhFi8sQryQA "Retina – Try It Online") Link shows score. Edit: Thanks to @MartinEnder who saved 20 bytes by using overlapping matches instead of lookaheads and a further three bytes by grouping the stages so that the `s` flag only needs to be applied once. Saved a further two bytes by calculating the triangular number differently, avoiding the need for a sort.
[Answer]
# [PHP](https://php.net/), 45 bytes, Score 78
```
WHILE($x=ORD($argn[$v++]))$y+=$$x-=-1;echo$y;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nqx7u4enjqqFSYesf5KIBFotWKdPWjtXUVKnUtlVRqdC11TW0Tk3OyFeptFa3/k@S@v//AQ "PHP – Try It Online")
# [PHP](https://php.net/), 46 bytes, Score 79 Bytes
```
WHILE(~$xy=$argn[$vz++])$su-=-$$xy+=1;echo$su;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nqx7u4enjqlGnUlFpCxaJVimr0taO1VQpLtW11VUBimvbGlqnJmfkA0Ws1a3/k6bh/38A "PHP – Try It Online")
# [PHP](https://php.net/), 56 bytes, Score 92
```
FOREAch(COUNT_CHARS($argn)as$z)WHILE($z)$y+=$z--;echo$y;
```
[Try it online!](https://tio.run/##K8go@G9jX5BRoMCVWlSUXxRflFqQX1SSmZeuUeca7@cf4unsqmnNpZJYlJ5nq@7mH@TqmJyh4ewf6hcS7@zhGBSsAZbSTCxWqdIM9/D0cdUAMlQqtW1VqnR1rVOTM/JVKq3Vrf@Tq/X//695@brJickZqQA "PHP – Try It Online")
[Answer]
# Perl 5 score ~~91~~ 83
Uses the `-p` flag which adds 2 because of the p in split.
```
$x=$_;$b+=++$a{$_}for(split//,$x);$_=$b
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 39 bytes, Score 69
```
@(a)sum((b=hist(a,unique(1*a))).^2+b)/2
```
[Try it online!](https://tio.run/##jc0xCgIxEEDRq0wjk9FVcVsRBI@gpQiT7AQDmrjJZGFPHxttrOw/7yenPElrR8NU6tMYe7iHooa7GsNYxeyWTESbW7@ytO3beOBY9v6VQ1RvcDHAGs4uZQGfMpzSINeI3WjwTxCJfrSLFAXHRQCRLbNjiwiaYJIc/Ay@RqchRX4EnT@zb0fU3g "Octave – Try It Online")
While there is another Octave answer, this one is entirely my own and a different approach, plus it scores less :).
The approach boils down to first finding the count (b) of each unique character, which is achieved using the histogram function. Then for each element we calculate the sum of 1 to b which is done using the formula `(b*(b+1))/2`. Then the individual sums are all summed into the final score.
In testing it seems brackets are really costly in the scoring because many are needed. I've optimised down from an initial score of about 88 by rearranging the questions to minimise the number of open/close brackets - hence we now do the /2 on the final total rather than individually, and also I've modified the formula to `(b^2+b)/2` as that requires fewer brackets.
[Answer]
# Octave , score ~~77~~ 31 bytes
\*same as @LuisMendo 's [MATL answer](https://codegolf.stackexchange.com/a/127290/62451).
```
@(a)nnz(triu(a==a'))
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNRMy@vSqOkKLNUI9HWNlFdU/N/mm1iXrE1V5qGEjZpJU2QTGJSYmJyYpKS5n8A "Octave – Try It Online")
Previous answer:
```
@(d,g=accumarray(+d',1)-(0:254))sum(g(g>0));
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNFJ902MTm5NDexqCixUkM7RV3HUFNXw8DKyNREU7O4NFcjXSPdzkBT0/p/mm1iXrE1V5qGEinalDRBOhKTEhOTE5OUNP8DAA "Octave – Try It Online")
] |
[Question]
[
The goal of this challenge is to produce an animation of a **[chain drive](https://en.wikipedia.org/wiki/Chain_drive)** system, comprised of a set of **[sprocket gears](https://en.wikipedia.org/wiki/Sprocket)** connected together by a **[chain](https://en.wikipedia.org/wiki/Roller_chain)**.
**General Requirements**
Your program will be given a **list of sprockets**, specified as `(x, y, radius)` triplets.
The **resulting chain drive system** is comprised of these sprockets, connected together by a **closed taut chain** passing over each of them, **in order**.
Your goal is to produce an **infinitely looping animation**, showing the system in motion.
For example, given the input
```
(0, 0, 16), (100, 0, 16), (100, 100, 12), (50, 50, 24), (0, 100, 12)
```
, the output should look something like
![Example 1](https://i.stack.imgur.com/2xcUU.gif).
The **coordinate system** should be such that the x-axis points right, and the y-axis points up.
You may assume that the **radii are even numbers** greater than or equal to 8 (we'll see why this matters later.)
You may also assume that there are **at least two sprockets**, and that the **sprockets don't intersect** one another.
The **units** of the input are not too critical.
All the examples and test cases in this post use pixels as the input units (so, for example, the radius of the middle sprocket in the previous figure is 24 pixels;) try not to deviate too much from these units.
In the rest of the challenge, spatial quantities are understood to be given in the same units as the input—make sure to keep the proportions right!
The **dimensions of the output** should be slightly bigger than the bounding box of all the sprockets, big enough so that the entire system is visible.
In particular, the absolute positions of the sprockets should not affect the output; only their relative positions should (so, for example, if we shifted all the sprockets in the above example by the same amount, the output would remain the same.)
The chain should be **tangent** to the sprockets it passes over at all points of contact, and **straight** everywhere else.
The chain should pass over the sprockets such that **adjacent chain segments** (that is, parts of the chain between two sprockets, that meet at the same sprocket) **don't intersect** each other.
![Chain Intersection](https://i.stack.imgur.com/42tkj.gif).
For example, while the left system above is valid, the middle one is not, since the two adjacent chain segments that pass over the bottom left sprocket intersect.
However, note that the right system *is* valid, since the two intersecting chain segments are not adjacent (this system is produced by a different input than the other two, though.)
To keep things simple(r), you may assume that **no sprocket intersects the convex hull** of its two neighboring sprockets, or the convex hulls of each of its neighbors and their other neighbor.
In other words, the top sprocket in the diagram below may not intersect any of the shaded regions.
![Exclusion](https://i.stack.imgur.com/Hj037.gif)
Chain segments may intersect sprockets other than the ones they pass over (such as in the last test case).
In this case, the chain should always appear in front of the sprockets.
**Visual Requirements**
The chain should consist of a series of **links** of alternating widths.
The width of the **narrow link** should be about 2, and the width of the **wide link** should be about 5.
The **length** of both types of links should be about equal.
The **period** of the chain, that is, the total length of a wide/narrow pair of links, should be the closest number to 4π that fits an integer number of times in the length of the chain.
For example, if the length of the chain is 1,000, then its period should be 12.5, which is the closest number to 4π (12.566...) that fits an integer number of times (80) in 1,000.
It's important for the period to fit an integer number of times in the chain's length, so that there are no artifacts at the point where the chain wraps around.
![Chain](https://i.stack.imgur.com/kXGvg.png)
A sprocket of radius ***R*** should consist of three concentric parts:
a central **axle**, which should be a circle of radius about 3;
the **sprocket's body**, around the axle, which should be a circle of radius about *R* - 4.5;
and the **sprocket's rim**, around the body, which should be a circle of radius about
*R* - 1.5.
The rim should also contain the **sprocket's teeth**, which should have a width of about 4;
the teeth's size and spacing should match the the sizes of the chain links, so that they enmesh neatly.
![Sprocket](https://i.stack.imgur.com/UQWxP.png)
The period of the sprocket's teeth, that is, the distance between two consecutive teeth along the circumference of the sprocket, should match the period of the chain.
Since the period is about 4π, and since the radius of the sprocket is guaranteed to be even, the period should fit in the sprocket's circumference an almost-integer number of times, so that there shouldn't be any noticeable artifacts at the point where the sprocket's teeth wrap around.
You may use **any combination of colors** for the chain, the different parts of the sprocket, and the background, as long as they are **easily distinguishable**.
The background may be transparent.
The examples in this post use ![Chain Color](https://i.stack.imgur.com/4bymL.png) `#202020` for the chain, ![Sprocket Axle and Rim Color](https://i.stack.imgur.com/gCSKw.png) `#868481` for the sprocket's axle and rim, and ![Sprocket Body Color](https://i.stack.imgur.com/nR4N3.png) `#646361` for the sprocket's body.
**Animation Requirements**
The **first sprocket** in the input list should rotate **clockwise**; the rest of the sprockets should rotate accordingly.
The chain should move at a **speed** of about 16π (about 50) units per second; the frame rate is up to you, but the animation should look smooth enough.
The animation should **loop seamlessly**.
**Conformance**
Some of the visual attributes and proportions are intentionally specified only roughly—you don't have to match them *exactly*.
Your program's output doesn't have to be a pixel-to-pixel replica of the examples given here, but it should look similar.
In particular, the exact proportions of the chain and the sprockets, and the exact shape of the chain's links and sprocket's teeth, are flexible.
The most important points to follow are these:
* The chain should pass over the sprockets, in input order, from the correct direction.
* The chain should be tangent to the sprockets at all points of contact.
* The links of the chain and the teeth of the sprockets should enmesh neatly, at least up to correct spacing and phase.
* The spacing between the links of the chain, and the teeth of the sprockets, should be such that there are no noticeable artifacts at the point where they wrap around.
* The sprockets should rotate in the correct direction.
* The animation should loop seamlessly.
As a final note, while, technically, the goal of this challenge is to write the shortest code, if you feel like getting creative and producing a more elaborate output, by all means, go for it!
## Challenge
Write a **program** or a **function**, taking a list of sprockets, and producing a corresponding chain drive system animation, as described above.
## Input and Output
You may take the **input** through the **command line**, through **STDIN**, as **function arguments**, or using an **equivalent method**.
You may use **any convenient format** for the input, but make sure to specify it in your post.
As **output**, you may **display the animation directly**, produce an **animation file** (e.g., an animated GIF), or produce a **sequence of frame files** (however, there's a small penalty in this case; see below.)
If you use file output, make sure the **number of frames is reasonable** (the examples in this post use very few frames;) the number of frames doesn't have to be minimal, but you shouldn't produce too many superfluous frames.
If you output a sequence of frames, make sure to **specify the frame rate** in your post.
## Score
This is **code-golf**.
The **shortest answer**, in bytes, wins.
**+10% Penalty**
If your program produces a sequence of frames as output, instead of displaying the animation directly or producing a single animation file, add 10% to your score.
## Test Cases
**Test 1**
```
(0, 0, 26), (120, 0, 26)
```
![Test 1](https://i.stack.imgur.com/AMCrI.gif)
**Test 2**
```
(100, 100, 60), (220, 100, 14)
```
![Test 2](https://i.stack.imgur.com/BeQEZ.gif)
**Test 3**
```
(100, 100, 16), (100, 0, 24), (0, 100, 24), (0, 0, 16)
```
![Test 3](https://i.stack.imgur.com/ozwb9.gif)
**Test 4**
```
(0, 0, 60), (44, 140, 16), (-204, 140, 16), (-160, 0, 60), (-112, 188, 12),
(-190, 300, 30), (30, 300, 30), (-48, 188, 12)
```
![Test 4](https://i.stack.imgur.com/GwErt.gif)
**Test 5**
```
(0, 128, 14), (46.17, 63.55, 10), (121.74, 39.55, 14), (74.71, -24.28, 10),
(75.24, -103.55, 14), (0, -78.56, 10), (-75.24, -103.55, 14), (-74.71, -24.28, 10),
(-121.74, 39.55, 14), (-46.17, 63.55, 10)
```
![Test 5](https://i.stack.imgur.com/NQSBy.gif)
**Test 6**
```
(367, 151, 12), (210, 75, 36), (57, 286, 38), (14, 181, 32), (91, 124, 18),
(298, 366, 38), (141, 3, 52), (80, 179, 26), (313, 32, 26), (146, 280, 10),
(126, 253, 8), (220, 184, 24), (135, 332, 8), (365, 296, 50), (248, 217, 8),
(218, 392, 30)
```
![Test 6](https://i.stack.imgur.com/l0OLw.gif)
---
![Have Fun!](https://i.stack.imgur.com/YUiaq.gif)
[Answer]
# JavaScript (ES6), ~~2557~~ ~~1915~~ ~~1897~~ 1681 bytes
This isn't super-duper *golfed* really; it's minified - partly by hand - but that's nothing special. It could no doubt be shorter if I'd golfed it more before minifying, but I've spent (more than) enough time on this already.
*Edit: Ok, so I spent more time on it and golfed the code more before minifying (very manually this time). The code's still using the same approach and overall structure, but even so I still ended up saving 642 bytes. Not too shabby, if I do say so myself. Probably missed some byte-saving opportunities, but at this point even I'm not sure how it works anymore. The only thing that's different in terms of output, is that it now uses slightly different colors that could be written more tersely.*
*Edit 2 (much later): Saved 18 bytes. Thanks to ConorO'Brien in the comments for pointing out the blindingly obvious that I'd totally missed.*
*Edit 3: So, I figured I'd reverse engineer my own code, because, frankly, I couldn't remember how I'd done it, and I lost the ungolfed versions. So I went through, and lo and behold found another 316 bytes to save by restructuring and doing some micro-golfing.*
```
R=g=>{with(Math){V=(x,y,o)=>o={x,y,l:sqrt(x*x+y*y),a:v=>V(x+v.x,y+v.y),s:v=>o.a(v.m(-1)),m:f=>V(x*f,y*f),t:r=>V(x*cos(r)-y*sin(r),x*sin(r)+y*cos(r)),c:v=>x*v.y-y*v.x,toString:_=>x+','+y};a='appendChild',b='setAttribute';S=(e,a)=>Object.keys(a).map(n=>e[b](n,a[n]))&&e;T=(t,a)=>S(k.createElementNS('http://www.w3.org/2000/svg',t),a);C=(e,a)=>S(e.cloneNode(),a);P=a=>T('path',(a.fill='none',a));w=h=-(x=y=1/0);G=g.map((a,g)=>(g=V(...a))&&(u=(g.r=a[2])+5,x=min(x,g.x-u),y=min(y,g.y-u),w=max(w,g.x+u),h=max(h,g.y+u))&&g);k=document;I=k[a].bind(k.body[a](T('svg',{width:w-x,height:h-y}))[a](T('g',{transform:`translate(${-x},${h})scale(1,-1)`})));L=(c)=>(h=G.length)&&G.map((g,i)=>c(G[i],G[i?i-1:h-1],G[(i+1)%h]))&&L;l='';L((g,p,n)=>g.f=p.s(g).c(n.s(g))>0)((g,a,n)=>{d=g.s(n),y=x=1/d.l;g.f!=n.f?(a=asin((g.r+n.r)*x),g.f?(x=-x,a=-a):(y=-y)):(a=asin((g.r-n.r)*x),g.f&&(x=y=-x,a=-a));t=d.t(a+PI/2);g.o=t.m(x*g.r).a(g);n.i=t.m(y*n.r).a(n)})((g,p,n)=>{z='#888';d=(l,s,e)=>`A${g.r},${g.r} 0 ${1*l},${1*s} ${e}`;e=(f,r)=>T('circle',{cx:g.x,cy:g.y,r,fill:f});g.k=p.o.s(n.i).l<g.i.s(g.o).l;w=d(g.k,!g.f,g.o);g.j=`${w}L${n.i}`;l+=g.j;I(e(z,g.r-1.5));g.g=I(P({d:`M${g.i}${w}${d(!g.k,!g.f,g.i)}`,stroke:z,'stroke-width':5}));g.h=I(C(g.g,{d:`M${g.i}${g.j}`,stroke:'#222'}));I(e('#666',g.r-4.5));I(e(z,3))});t=e=>e.getTotalLength(),u='stroke-dasharray',v='stroke-dashoffset',f=G[0];l=I(C(f.h,{d:'M'+f.i+l,'stroke-width':2}));s=f.w=t(l)/round(t(l)/(4*PI))/2;X=8*s;Y=f.v=0;L((g,p)=>{g.g[b](u,s);g.h[b](u,s);g==f||(g.w=p.w+t(p.h),g.v=p.v+t(p.h));g.g[b](v,g.w);g.h[b](v,g.v);g.h[a](C(g.g[a](T('animate',{attributeName:v,from:g.w+X,to:g.w+Y,repeatCount:'indefinite',dur:'1s'})),{from:g.v+X,to:g.v+Y}))})}}
```
The function above appends an SVG element (including animations) to the document. E.g. to display the 2nd test case:
```
R([[100, 100, 60], [220, 100, 14]]);
```
Seems to work a treat - at least here in Chrome.
Try it in the snippet below (clicking the buttons will draw each of OP's test cases).
```
R=g=>{with(Math){V=(x,y,o)=>o={x,y,l:sqrt(x*x+y*y),a:v=>V(x+v.x,y+v.y),s:v=>o.a(v.m(-1)),m:f=>V(x*f,y*f),t:r=>V(x*cos(r)-y*sin(r),x*sin(r)+y*cos(r)),c:v=>x*v.y-y*v.x,toString:_=>x+','+y};a='appendChild',b='setAttribute';S=(e,a)=>Object.keys(a).map(n=>e[b](n,a[n]))&&e;T=(t,a)=>S(k.createElementNS('http://www.w3.org/2000/svg',t),a);C=(e,a)=>S(e.cloneNode(),a);P=a=>T('path',(a.fill='none',a));w=h=-(x=y=1/0);G=g.map((a,g)=>(g=V(...a))&&(u=(g.r=a[2])+5,x=min(x,g.x-u),y=min(y,g.y-u),w=max(w,g.x+u),h=max(h,g.y+u))&&g);k=document;I=k[a].bind(k.body[a](T('svg',{width:w-x,height:h-y}))[a](T('g',{transform:`translate(${-x},${h})scale(1,-1)`})));L=(c)=>(h=G.length)&&G.map((g,i)=>c(G[i],G[i?i-1:h-1],G[(i+1)%h]))&&L;l='';L((g,p,n)=>g.f=p.s(g).c(n.s(g))>0)((g,a,n)=>{d=g.s(n),y=x=1/d.l;g.f!=n.f?(a=asin((g.r+n.r)*x),g.f?(x=-x,a=-a):(y=-y)):(a=asin((g.r-n.r)*x),g.f&&(x=y=-x,a=-a));t=d.t(a+PI/2);g.o=t.m(x*g.r).a(g);n.i=t.m(y*n.r).a(n)})((g,p,n)=>{z='#888';d=(l,s,e)=>`A${g.r},${g.r} 0 ${1*l},${1*s} ${e}`;e=(f,r)=>T('circle',{cx:g.x,cy:g.y,r,fill:f});g.k=p.o.s(n.i).l<g.i.s(g.o).l;w=d(g.k,!g.f,g.o);g.j=`${w}L${n.i}`;l+=g.j;I(e(z,g.r-1.5));g.g=I(P({d:`M${g.i}${w}${d(!g.k,!g.f,g.i)}`,stroke:z,'stroke-width':5}));g.h=I(C(g.g,{d:`M${g.i}${g.j}`,stroke:'#222'}));I(e('#666',g.r-4.5));I(e(z,3))});t=e=>e.getTotalLength(),u='stroke-dasharray',v='stroke-dashoffset',f=G[0];l=I(C(f.h,{d:'M'+f.i+l,'stroke-width':2}));s=f.w=t(l)/round(t(l)/(4*PI))/2;X=8*s;Y=f.v=0;L((g,p)=>{g.g[b](u,s);g.h[b](u,s);g==f||(g.w=p.w+t(p.h),g.v=p.v+t(p.h));g.g[b](v,g.w);g.h[b](v,g.v);g.h[a](C(g.g[a](T('animate',{attributeName:v,from:g.w+X,to:g.w+Y,repeatCount:'indefinite',dur:'1s'})),{from:g.v+X,to:g.v+Y}))})}}
// ========================
// Test code
var testCases = [
[[0, 0, 16], [100, 0, 16], [100, 100, 12], [50, 50, 24], [0, 100, 12]],
[[0, 0, 26], [120, 0, 26]],
[[100, 100, 60], [220, 100, 14]],
[[100, 100, 16], [100, 0, 24], [0, 100, 24], [0, 0, 16]],
[[0, 0, 60], [44, 140, 16], [-204, 140, 16], [-160, 0, 60], [-112, 188, 12], [-190, 300, 30], [30, 300, 30], [-48, 188, 12]],
[[0, 128, 14], [46.17, 63.55, 10], [121.74, 39.55, 14], [74.71, -24.28, 10], [75.24, -103.55, 14], [0, -78.56, 10], [-75.24, -103.55, 14], [-74.71, -24.28, 10], [-121.74, 39.55, 14], [-46.17, 63.55, 10]],
[[367, 151, 12], [210, 75, 36], [57, 286, 38], [14, 181, 32], [91, 124, 18], [298, 366, 38], [141, 3, 52], [80, 179, 26], [313, 32, 26], [146, 280, 10], [126, 253, 8], [220, 184, 24], [135, 332, 8], [365, 296, 50], [248, 217, 8], [218, 392, 30]]
];
function clear() {
var buttons = document.createElement('div');
document.body.innerHTML = "";
document.body.appendChild(buttons);
testCases.forEach(function (data, i) {
var button = document.createElement('button');
button.innerHTML = String(i);
button.onclick = function () {
clear();
R(data);
return false;
};
buttons.appendChild(button);
});
}
clear();
```
The code draws the chain and gear teeth as a dashed strokes. It then uses `animate` elements to animate the `stroke-dashoffset` attribute. The resulting SVG element is self-contained; there's no JS-driven animation or CSS styling.
To make things line up nicely, each gear's ring of teeth is actually drawn as a path consisting of two arcs, so the path can start right at the tangent point where the chain touches. This makes it a lot simpler to line it up.
Furthermore, it seems there's a lot of rounding errors when using SVG's dashed strokes. At least, that's what I saw; the longer the chain, the worse it'd mesh with each successive gear. So to minimize the issue, the chain is actually made up of several paths. Each path consists of an arcing segment around one gear and a straight line to the next gear. Their dash-offsets are calculated to match. The thin "inner" part of the chain, however, is just a single looping path, since it isn't animated.
[Answer]
# C# 3566 bytes
~~Not golfed at all, but~~ works (I think)
Ungolfed in edit history.
Uses Magick.NET to render gif.
```
class S{public float x,y,r;public bool c;public double i,o,a=0,l=0;public S(float X,float Y,float R){x=X;y=Y;r=R;}}class P{List<S>q=new List<S>();float x=float.MaxValue,X=float.MinValue,y=float.MaxValue,Y=float.MinValue,z=0,Z=0,N;int w=0,h=0;Color c=Color.FromArgb(32,32,32);Pen p,o;Brush b,n,m;List<PointF>C;double l;void F(float[][]s){p=new Pen(c,2);o=new Pen(c,5);b=new SolidBrush(c);n=new SolidBrush(Color.FromArgb(134,132,129));m=new SolidBrush(Color.FromArgb(100,99,97));for(int i=0;i<s.Length;i++){float[]S=s[i];q.Add(new S(S[0],S[1],S[2]));if(S[0]-S[2]<x)x=S[0]-S[2];if(S[1]-S[2]<y)y=S[1]-S[2];if(S[0]+S[2]>X)X=S[0]+S[2];if(S[1]+S[2]>Y)Y=S[1]+S[2];}q[0].c=true;z=-x+16;Z=-y+16;w=(int)(X-x+32);h=(int)(Y-y+32);for(int i=0;i<=q.Count;i++)H(q[i%q.Count],q[(i+1)%q.Count],q[(i+2)%q.Count]);C=new List<PointF>();for(int i=0;i<q.Count;i++){S g=q[i],k=q[(i+1)%q.Count];if(g.c)for(double a=g.i;a<g.i+D(g.o,g.i);a+=Math.PI/(2*g.r)){C.Add(new PointF((float)(g.x+z+g.r*Math.Cos(a)),(float)(g.y+Z+g.r*Math.Sin(a))));}else
for(double a=g.o+D(g.i,g.o);a>g.o;a-=Math.PI/(2*g.r)){C.Add(new PointF((float)(g.x+z+g.r*Math.Cos(a)),(float)(g.y+Z+g.r*Math.Sin(a))));}C.Add(new PointF((float)(g.x+z+g.r*Math.Cos(g.o)),(float)(g.y+Z+g.r*Math.Sin(g.o))));C.Add(new PointF((float)(k.x+z+k.r*Math.Cos(k.i)),(float)(k.y+Z+k.r*Math.Sin(k.i))));k.l=E(C);}l=E(C);N=(float)(K(l)/10.0);o.DashPattern=new float[]{N,N};double u=q[0].i;for(int i=0;i<q.Count;i++){S g=q[i];double L=g.l/(N*5);g.a=g.i+((1-(L%2))/g.r*Math.PI*2)*(g.c?1:-1);}List<MagickImage>I=new List<MagickImage>();for(int i=0;i<t;i++){using(Bitmap B=new Bitmap(w,h)){using(Graphics g=Graphics.FromImage(B)){g.Clear(Color.White);g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;foreach(S U in q){float R=U.x+z,L=U.y+Z,d=7+2*U.r;PointF[]f=new PointF[4];for(double a=(i*(4.0/t));a<2*U.r;a+=4){double v=U.a+((U.c?-a:a)/U.r*Math.PI),j=Math.PI/U.r*(U.c?1:-1),V=v+j,W=V+j,r=U.r+3.5;f[0]=new PointF(R,L);f[1]=new PointF(R+(float)(r*Math.Cos(v)),L+(float)(r*Math.Sin(v)));f[2]=new PointF(R+(float)(r*Math.Cos(V)),L+(float)(r*Math.Sin(V)));f[3]=new PointF(R+(float)(r*Math.Cos(W)),L+(float)(r*Math.Sin(W)));g.FillPolygon(n,f);}d=2*(U.r-1.5f);g.FillEllipse(n,R-d/2,L-d/2,d,d);d=2*(U.r-4.5f);g.FillEllipse(m,R-d/2,L-d/2,d,d);d=6;g.FillEllipse(n,R-d/2,L-d/2,d,d);}g.DrawLines(p,C.ToArray());o.DashOffset=(N*2.0f/t)*i;g.DrawLines(o,C.ToArray());B.RotateFlip(RotateFlipType.RotateNoneFlipY);B.Save(i+".png",ImageFormat.Png);I.Add(new MagickImage(B));}}}using(MagickImageCollection collection=new MagickImageCollection()){foreach(MagickImage i in I){i.AnimationDelay=5;collection.Add(i);}QuantizeSettings Q=new QuantizeSettings();Q.Colors=256;collection.Quantize(Q);collection.Optimize();collection.Write("1.gif");}}int t=5;double D(double a,double b){double P=Math.PI,r=a-b;while(r<0)r+=2*P;return r%(2*P);}double E(List<PointF> c){double u=0;for(int i=0;i<c.Count-1;i++){PointF s=c[i];PointF t=c[i+1];double x=s.X-t.X,y=s.Y-t.Y;u+=Math.Sqrt(x*x+y*y);}return u;}double K(double L){double P=4*Math.PI;int i=(int)(L/P);float a=(float)L/i,b=(float)L/(i+1);if(Math.Abs(P-a)<Math.Abs(P-b))return a;return b;}void H(S a,S b,S c){double A=0,r=0,d=b.x-a.x,e=b.y-a.y,f=Math.Atan2(e,d)+Math.PI/2,g=Math.Atan2(e,d)-Math.PI/2,h=Math.Atan2(-e,-d)-Math.PI/2,i=Math.Atan2(-e,-d)+Math.PI/2;double k=c.x-b.x,n=c.y-b.y,l=Math.Sqrt(d*d+e*e);A=D(Math.Atan2(n,k),Math.Atan2(-e,-d));bool x=A>Math.PI!=a.c;b.c=x!=a.c;if(a.r!=b.r)r=a.r+(x?b.r:-b.r);f-=Math.Asin(r/l);g+=Math.Asin(r/l);h+=Math.Asin(r/l);i-=Math.Asin(r/l);b.i=x==a.c?h:i;a.o=a.c?g:f;}}
```
Class P has a function F;
Example:
```
static void Main(string[]a){
P p=new P();
float[][]s=new float[][]{
new float[]{10,200,20},
new float[]{240,200,20},
new float[]{190,170,10},
new float[]{190,150,10},
new float[]{210,120,20},
new float[]{190,90,10},
new float[]{160,0,20},
new float[]{130,170,10},
new float[]{110,170,10},
new float[]{80,0,20},
new float[]{50,170,10}
};
p.F(s);}
```
[![enter image description here](https://i.stack.imgur.com/Nncsp.gif)](https://i.stack.imgur.com/Nncsp.gif)
[Answer]
## JavaScript (ES6) 1626 bytes
This solution is the result of reverse engineering of @Flambino's solution, I post it with his accord.
```
R=g=>{with(Math){v='stroke';j=v+'-dasharray';q=v+'-dashoffset';m='appendChild';n='getTotalLength';b='setAttribute';z='#888';k=document;V=(x,y,r,o)=>o={x,y,r,l:sqrt(x*x+y*y),a:v=>V(x+v.x,y+v.y),s:v=>o.a(v.m(-1)),m:f=>V(x*f,y*f),t:r=>V(x*cos(r)-y*sin(r),x*sin(r)+y*cos(r)),c:v=>x*v.y-y*v.x,toString:_=>x+','+y};S=(e,a)=>Object.keys(a).map(n=>e[b](n,a[n]))&&e;T=(t,a)=>S(k.createElementNS('http://www.w3.org/2000/svg',t),a);C=(e,a)=>S(e.cloneNode(),a);w=h=-(x=y=1/0);G=g.map((a,g)=>(g=V(...a))&&(u=(g.r=a[2])+5,x=min(x,g.x-u),y=min(y,g.y-u),w=max(w,g.x+u),h=max(h,g.y+u))&&g);f=G[0];w-=x;h-=y;s=T('svg',{width:w,height:h,viewBox:x+' '+y+' '+w+' '+h,transform:'scale(1,-1)'});c='';L=(c)=>(h=G.length)&&G.map((g,i)=>c(G[i],G[(h+i-1)%h],G[(i+1)%h]))&&L;L((g,p,n)=>g.w=(p.s(g).c(n.s(g))>0))((g,p,n)=>{d=g.s(n),y=x=1/d.l;g.w!=n.w?(p=asin((g.r+n.r)*x),g.w?(x=-x,p=-p):(y=-y)):(p=asin((g.r-n.r)*x),g.w&&(x=y=-x,p=-p));t=d.t(p+PI/2);g.o=t.m(x*g.r).a(g);n.i=t.m(y*n.r).a(n)})((g,p,n)=>{l=(p.o.s(n.i).l<g.i.s(g.o).l);d=(l,e)=>`A${g.r} ${g.r} 0 ${+l} ${+!g.w} ${e}`;a=d(l,g.o);e=(f,r)=>T('circle',{cx:g.x,cy:g.y,r,fill:f});c+=a+'L'+n.i;s[m](e(z,g.r-1.5));s[m](e('#666',g.r-4.5));s[m](e(z,3));g.p=s[m](C(g.e=s[m](T('path',{d:'M'+g.i+a+d(!l,g.i),fill:'none',[v]:z,[v+'-width']:5})),{d:'M'+g.i+a+'L'+n.i,[v]:'#222'}))});c=C(f.p,{d:'M'+f.i+c,[v+'-width']:2});g=c[n]();y=8*(x=g/round(g/(4*PI))/2);f.g=x;f.h=0;L((g,p)=>{g!=f&&(g.g=p.g+p.p[n](),g.h=p.h+p.p[n]());S(g.p,{[j]:x,[q]:g.h})[m](C(S(g.e,{[j]:x,[q]:g.g})[m](T('animate',{attributeName:[q],from:g.g+y,to:g.g,repeatCount:'indefinite',dur:'1s'})),{from:g.h+y,to:g.h}))});k.body[m](s)[m](c)}}
```
The ungolfed version:
```
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
this.length = Math.sqrt(x * x + y * y);
}
add(vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
}
subtract(vector) {
return new Vector(this.x - vector.x, this.y - vector.y);
}
multiply(scalar) {
return new Vector(this.x * scalar, this.y * scalar);
}
rotate(radians) {
const cos = Math.cos(radians);
const sin = Math.sin(radians);
return new Vector(this.x * cos - this.y * sin, this.x * sin + this.y * cos);
}
cross(vector) {
return this.x * vector.y - this.y * vector.x;
}
toString() {
return `${this.x},${this.y}`;
}
}
class Gear {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
getVector() {
return new Vector(this.x, this.y);
}
}
const setAttributes = (element, attributes) => {
Object.keys(attributes).forEach((attribute) => {
element.setAttribute(attribute, attributes[attribute]);
});
};
const createElement = (tagName, attributes) => {
const element = document.createElementNS('http://www.w3.org/2000/svg', tagName);
setAttributes(element, attributes);
return element;
};
const cloneElement = (element, attributes) => {
const clone = element.cloneNode();
setAttributes(clone, attributes);
return clone;
};
const createPath = (attributes) => {
return createElement('path', {
...attributes,
fill: 'none'
});
};
const createCircle = (cx, cy, r, fill) => {
return createElement('circle', {
cx,
cy,
r,
fill
});
};
const loopGears = (gears, callback) => {
const length = gears.length;
gears.forEach((gear, index) => {
const prevGear = gears[(length + index - 1) % length];
const nextGear = gears[(index + 1) % length];
callback(gear, prevGear, nextGear);
});
};
const arcDescription = (radius, largeArcFlag, sweepFlag, endVector) => {
return `A${radius} ${radius} 0 ${+largeArcFlag} ${+sweepFlag} ${endVector}`;
};
const renderGears = (data) => {
let x = Infinity;
let y = Infinity;
let w = -Infinity;
let h = -Infinity;
const gears = data.map((params) => {
const gear = new Gear(...params);
const unit = params[2] + 5;
x = Math.min(x, gear.x - unit);
y = Math.min(y, gear.y - unit);
w = Math.max(w, gear.x + unit);
h = Math.max(h, gear.y + unit);
return gear;
});
const firstGear = gears[0];
w -= x;
h -= y;
const svg = createElement('svg', {
width: w,
height: h,
viewBox: `${x} ${y} ${w} ${h}`,
transform: `scale(1,-1)`
});
let chainPath = '';
loopGears(gears, (gear, prevGear, nextGear) => {
const gearVector = gear.getVector();
const prevGearVector = prevGear.getVector().subtract(gearVector);
const nextGearVector = nextGear.getVector().subtract(gearVector);
gear.sweep = (prevGearVector.cross(nextGearVector) > 0);
});
loopGears(gears, (gear, prevGear, nextGear) => {
const diffVector = gear.getVector().subtract(nextGear.getVector());
let angle = 0;
let x = 1 / diffVector.length;
let y = x;
if (gear.sweep === nextGear.sweep) {
angle = Math.asin((gear.radius - nextGear.radius) * x);
if (gear.sweep) {
x = -x;
y = -y;
angle = -angle;
}
} else {
angle = Math.asin((gear.radius + nextGear.radius) * x);
if (gear.sweep) {
x = -x;
angle = -angle;
} else {
y = -y;
}
}
const perpendicularVector = diffVector.rotate(angle + Math.PI / 2);
gear.out = perpendicularVector.multiply(x * gear.radius).add(gear.getVector());
nextGear.in = perpendicularVector.multiply(y * nextGear.radius).add(nextGear.getVector());
});
loopGears(gears, (gear, prevGear, nextGear) => {
const largeArcFlag = (prevGear.out.subtract(nextGear.in).length < gear.in.subtract(gear.out).length);
const arcPath = arcDescription(gear.radius, largeArcFlag, !gear.sweep, gear.out);
const gearExterior = createCircle(gear.x, gear.y, gear.radius - 1.5, '#888');
const gearInterior = createCircle(gear.x, gear.y, gear.radius - 4.5, '#666');
const gearCenter = createCircle(gear.x, gear.y, 3, '#888');
const gearTeeth = createPath({
d: `M${gear.in}${arcPath}${arcDescription(gear.radius, !largeArcFlag, !gear.sweep, gear.in)}`,
stroke: '#888',
'stroke-width': 5
});
const chainParts = cloneElement(gearTeeth, {
d: `M${gear.in}${arcPath}L${nextGear.in}`,
stroke: '#222'
});
gear.teeth = gearTeeth;
gear.chainParts = chainParts;
chainPath += `${arcPath}L${nextGear.in}`;
svg.appendChild(gearExterior);
svg.appendChild(gearInterior);
svg.appendChild(gearCenter);
svg.appendChild(gearTeeth);
svg.appendChild(chainParts);
});
const chain = cloneElement(firstGear.chainParts, {
d: 'M' + firstGear.in + chainPath,
'stroke-width': 2
});
const chainLength = chain.getTotalLength();
const chainUnit = chainLength / Math.round(chainLength / (4 * Math.PI)) / 2;
const animationOffset = 8 * chainUnit;
loopGears(gears, (gear, prevGear) => {
if (gear === firstGear) {
gear.teethOffset = chainUnit;
gear.chainOffset = 0;
} else {
gear.teethOffset = prevGear.teethOffset + prevGear.chainParts.getTotalLength();
gear.chainOffset = prevGear.chainOffset + prevGear.chainParts.getTotalLength();
}
setAttributes(gear.teeth, {
'stroke-dasharray': chainUnit,
'stroke-dashoffset': gear.teethOffset
});
setAttributes(gear.chainParts, {
'stroke-dasharray': chainUnit,
'stroke-dashoffset': gear.chainOffset
});
const animate = createElement('animate', {
attributeName: 'stroke-dashoffset',
from: gear.teethOffset + animationOffset,
to: gear.teethOffset,
repeatCount: 'indefinite',
dur: '1s'
});
const cloneAnimate = cloneElement(animate, {
from: gear.chainOffset + animationOffset,
to: gear.chainOffset
});
gear.teeth.appendChild(animate);
gear.chainParts.appendChild(cloneAnimate);
});
svg.appendChild(chain);
document.body.appendChild(svg);
};
var testCases = [
[[0, 0, 16], [100, 0, 16], [100, 100, 12], [50, 50, 24], [0, 100, 12]],
[[0, 0, 26], [120, 0, 26]],
[[100, 100, 60], [220, 100, 14]],
[[100, 100, 16], [100, 0, 24], [0, 100, 24], [0, 0, 16]],
[[0, 0, 60], [44, 140, 16], [-204, 140, 16], [-160, 0, 60], [-112, 188, 12], [-190, 300, 30], [30, 300, 30], [-48, 188, 12]],
[[0, 128, 14], [46.17, 63.55, 10], [121.74, 39.55, 14], [74.71, -24.28, 10], [75.24, -103.55, 14], [0, -78.56, 10], [-75.24, -103.55, 14], [-74.71, -24.28, 10], [-121.74, 39.55, 14], [-46.17, 63.55, 10]],
[[367, 151, 12], [210, 75, 36], [57, 286, 38], [14, 181, 32], [91, 124, 18], [298, 366, 38], [141, 3, 52], [80, 179, 26], [313, 32, 26], [146, 280, 10], [126, 253, 8], [220, 184, 24], [135, 332, 8], [365, 296, 50], [248, 217, 8], [218, 392, 30]]
];
function clear() {
var buttons = document.createElement('div');
document.body.innerHTML = "";
document.body.appendChild(buttons);
testCases.forEach(function (data, i) {
var button = document.createElement('button');
button.innerHTML = String(i);
button.onclick = function () {
clear();
renderGears(data);
return false;
};
buttons.appendChild(button);
});
}
clear();
```
] |
[Question]
[
Your task is to reverse the order in which some `prints` get executed.
---
**Specs:**
Your code will be in this form:
```
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
```
You will have to `print` (or `echo`, or `write`, or equivalent) those strings **from the fourth to the first.**
* You decide which lines of your program must `print` the strings, but they must be **adjacent**;
* Every line can contain only one `print`, and cannot exceed *60 bytes* in length;
* Since this is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), be creative and avoid to write just a `goto` or a simple `for(i){if(i=4)print"Line1";if(i=3)...}`
* The most upvoted answer in 2 weeks wins this.
* Your output **MUST** be `Line4 Line3 Line2 Line1` **OR** `Line4Line3Line2Line1` **OR** `Line4\nLine3\nLine2\nLine1`(where `\n` is a newline), and it must be generated only by executing those `prints` backwards.
Happy coding!
**UPDATE:** Contest is over! Thank you all :)
[Answer]
## Commodore 64 BASIC
```
40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"
```
[Answer]
## PHP
Abusing precedence... :-)
```
!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";
```
[Answer]
## C
Undefined behavior is the most exciting kind of behavior!
```
f(){}
main()
{
f(printf("Line 1\n"),
printf("Line 2\n"),
printf("Line 3\n"),
printf("Line 4\n"));
}
```
Actual output may vary depending on your compiler, linker, operating system, and processor :)
[Answer]
# Java
Using reflection
```
public class ReversePrint {
public static void main(String[]a) {
System.out.println("Line1");
System.out.println("Line2");
System.out.println("Line3");
System.out.println("Line4");
}
static {
try{
Field f=String.class.getDeclaredField("value");
f.setAccessible(true);
f.set("Line1","Line4".toCharArray());
f.set("Line2","Line3".toCharArray());
f.set("Line3","Line2 ".trim().toCharArray());
f.set("Line4","Line1 ".trim().toCharArray());
}catch(Exception e){}
}
}
```
Output:
```
Line4
Line3
Line2
Line1
```
An explanation of why this works can be found [here](https://stackoverflow.com/a/20945113/597419).
[Answer]
## C (and sort-of Python)
New version, using a macro to fit the question format perfectly.
Following Quincunx's comment, I added `return` to make it nicer.
It also works in Python, but it prints in correct order.
```
#define print"\n",printf(
#define return"\n"))));}
#define def main(){0?
def main():
print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4"
return
main();
```
Original version - the two are practically the same, after macro substitution:
```
main(){
printf("Line 1\n",
printf("Line 2\n",
printf("Line 3\n",
printf("Line 4\n",
0))));
}
```
[Answer]
## ES6 (using backwards mode ;)
Wow, it looks like the designers of ECMAScript had some incredible foresight when they made [backwards mode](http://wiki.ecmascript.org/doku.php?id=harmony:backwards_mode) part of the spec:
```
// activate backwards mode:
'use backwardsˈ; \* mode backwards in now *\
code of lines some ⧵\
\*code*\ "Line1" print \*code*\
\*code*\ "Line2" print \*code*\
\*code*\ "Line3" print \*code*\
\*code*\ "Line4" print \*code*\
code of lines some ⧵\
⁏ˈforwards useˈ // back to ˈnormal'.
// So simple! No need to do anything this complicated:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')
```
Output (evaluation, really):
```
"Line4Line3Line2Line1"
```
Note that it's *exactly* of the form requested, with only slight backwardification to fit [the syntax of the mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Backwards_mode). Note also that this mode is only supported in recent versions of Firefox [at the moment](http://caniuse.com/use-backwards).
*Final note: Actually, there is no backwards mode. But this is still a valid script that runs in Firefox (copy the whole thing). :D*
---
### ES6 "lax mode"
**BONUS**: Here's an updated version that doesn't use backwards mode, but uses the newly-specified "lax mode" where the JS engine will just try to guess what the code is supposed to do, regardless of adherence to any specified JS syntax (basically the antithesis of strict mode):
```
// activate "lax" mode:
`use laxˋ; // also works: ˋuse relaxˋ, ˋuse guessingˋ, ˋuse whatevsˋ, etc.
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
ˋuse normalˋ; // same as ˋuse default`.
// Again, compare to inferior, illegible "traditional" ES6:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')
```
Please note that "[lax mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/template_strings)" is currently only available in Firefox >= 34. ;P
[Answer]
# C
```
main()
{
int i = 0;
for(; i == 0; printf("Line 1\n"))
for(; i == 0; printf("Line 2\n"))
for(; i == 0; printf("Line 3\n"))
for(; i == 0; printf("Line 4\n"))
i = 1;
}
```
[Answer]
## Ruby
```
print 'Line1' unless
print 'Line2' unless
print 'Line3' unless
print 'Line4'
```
Edit: Alternatively,
```
def method_missing(meth,*)
puts meth.to_s.sub('print'){}
end
printLine1(
printLine2(
printLine3(
printLine4)))
```
[Answer]
# PHP
I know, this is madness...
```
goto d;
a: print "Line1\n"; goto end;
b: print "Line2\n"; goto a;
c: print "Line3\n"; goto b;
d: print "Line4\n"; goto c;
end: exit;
```
[Answer]
## Haskell
This is almost idiomatic Haskell, as the program now looks like a right-to-left function composition. If the function wasn't print, but something that would return a (useful) value the operator declaration would be unnecessary and the code would be something you'd see in libraries.
```
a << b = (const a =<< b)
main = putStrLn "Line1"
<< putStrLn "Line2"
<< putStrLn "Line3"
<< putStrLn "Line4"
```
[Answer]
## Perl
```
use threads;
$a=threads->create(sub {sleep(5); print("Line1\n");});
$b=threads->create(sub {sleep(4); print("Line2\n");});
$c=threads->create(sub {sleep(3); print("Line3\n");});
$d=threads->create(sub {sleep(2); print("Line4\n");});
$a->join();
$b->join();
$c->join();
$d->join();
```
[Answer]
# HTML + CSS
```
<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
<p>Line 4</p>
```
CSS:
```
body {margin-top:7em}
p + p {margin-top:-4em}
```
See [jsFiddle](http://jsfiddle.net/udU4X/1/).
Edit:
To conform to the rules better, here is a variant in XML, that actually uses `print`.
```
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="style.css"?>
<root>
<print>Line 1</print>
<print>Line 2</print>
<print>Line 3</print>
<print>Line 4</print>
</root>
```
where style.css should be
```
* {display:block; margin-top:3em}
print + print {margin-top:-3em}
```
# HTML without CSS
And for the heck of it, here's one without CSS.
```
<table>
<tfoot><tr><td><table><tfoot><tr><td>Line 1</tr></tfoot>
<tbody><tr><td> Line 2</table></tfoot>
<tbody><tr><td><table><tfoot><tr><td>Line 3</tr></tfoot>
<tbody><tr><td> Line 4</table></tbody>
</table>
```
[Fiddle](http://jsfiddle.net/m45Y2/1/).
[Answer]
# C++
```
#include <iostream>
#define Q(x,y) x ## y
#define P(x,y) Q(x, y)
#define print S P(s, __LINE__) =
struct S { const char *s; S(const char *s): s(s) {} ~S() { std::cout << s << std::endl; } };
int main() {
print "Line1";
print "Line2";
print "Line3";
print "Line4";
}
```
(Local variables are destroyed in reverse order of declaration.)
# C++11
```
#include <iostream>
int main() {
struct S { void (*f)(); S(void (*f)()): f(f) {} ~S() { f(); } } s[] = {
{[](){ std::cout << "Line1" << std::endl; }},
{[](){ std::cout << "Line2" << std::endl; }},
{[](){ std::cout << "Line3" << std::endl; }},
{[](){ std::cout << "Line4" << std::endl; }},
};
}
```
(Much the same, but using lambdas and an array data member instead.)
[Answer]
# Haskell
```
main = sequence_ $ reverse [
putStr "Line1",
putStr "Line2",
putStr "Line3",
putStr "Line4"]
```
[Answer]
# Javascript
```
setTimeout(function(){console.log("Line 1");},900);
setTimeout(function(){console.log("Line 2");},800);
setTimeout(function(){console.log("Line 3");},700);
setTimeout(function(){console.log("Line 4");},600);
```
[Answer]
# C
Trying to make defiance of the tips in the question as creative as possible:
```
#include <stdio.h>
#define print if (i == __LINE__) puts
static unsigned i;
int main(void) {
while (--i) {
print("Line 1");
print("Line 2");
print("Line 3");
print("Line 4");
}
return 0;
}
```
[Answer]
## Bash
In memory of the revered [SleepSort](https://codegolf.stackexchange.com/a/16452/11422) and [SleepAdd](https://codegolf.stackexchange.com/a/16316/11422), I present to you... **SleepReverse**:
```
#!/bin/bash
function print(){(sleep $((4-$1));echo "Line $1";)&}
print 1
print 2
print 3
print 4
```
[Answer]
# BF
Assumes cell-wrapping.
```
++++[->+
----[> (line 1) .[-]<]++++
---[> (line 2) .[-]<]+++
--[> (line 3) .[-]<]++
-[> (line 4) .[-]<]+
<]
```
**Why it works**
The first and last lines compose of a loop that repeats four times (counter = `cell0`).
Inside the loop, there is a counter variable (`cell1`) that is increased every run.
Each lines checks if decreasing by four, three, two, or one equals zero. Therefore, on the first run, the counter is one and the last line is executed, on the second run, the third line is executed, etc.
The `(line 1)` shows where you should make the text that is printed. The arrows in the loops allocate `cell2` for this purpose. The `[-]` cleans out `cell2` after you use it.
[Answer]
## Java
```
import java.io.PrintStream;
import java.util.concurrent.FutureTask;
public class Print {
public static void main(String[] args) {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
new FutureTask<PrintStream>(new Runnable() {
public void run() {
System.out.append("Line1"); }
}, System.out.append("Line2")).run(); }
}, System.out.append("Line3")).run(); }
}, System.out.append("Line4")).run();
}
}
```
It's all in the right timing... ;-)
[Answer]
## Bash
Here comes the double-faced script:
```
#!/bin/bash
s=1
if [ $s -ne 0 ]; then tac $0 | bash; exit; fi
s=0
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"
```
[Answer]
# Python 3
```
import atexit
atexit.register(print,"Line1")
atexit.register(print,"Line2")
atexit.register(print,"Line3")
atexit.register(print,"Line4")
```
[Answer]
## Common Lisp № 1
It's easy to write a `ngorp` macro that executes its forms in reverse order:
```
(macrolet ((ngorp (&body ydob) `(progn ,@(reverse ydob))))
(ngorp
(write-line "Line 1")
(write-line "Line 2")
(write-line "Line 3")
(write-line "Line 4")))
```
```
Line 4
Line 3
Line 2
Line 1
```
## Common Lisp № 2
Here's one that takes the problem very literally; the code from the question appears in program without modification:
```
(macrolet ((execute-prints-backwards (&body body)
`(progn
,@(nreverse (mapcar (lambda (string)
(list 'write-line string))
(remove-if-not 'stringp body))))))
(execute-prints-backwards
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
))
```
```
Line4
Line3
Line2
Line1
```
[Answer]
# PHP
Another `eval` variant:
```
$lines=array_slice(file(__FILE__),-4); // get last 4 lines of current file
eval(implode('',array_reverse($lines)));exit; // eval lines reversed and exit
print "Line1\n";
print "Line2\n";
print "Line3\n";
print "Line4\n";
```
[Answer]
# F#
```
let inline (?) f g x = g x; f x
(printfn "Line1%s") ?
(printfn "Line2%s") ?
(printfn "Line3%s") ?
(printfn "Line4%s") ""
```
Just created a custom operator that executes functions in reverse order.
[Answer]
# Go (Golang)
```
package main
import "fmt"
func main() {
defer fmt.Println("Line 1")
defer fmt.Println("Line 2")
defer fmt.Println("Line 3")
defer fmt.Println("Line 4")
}
```
Try it out: <http://play.golang.org/p/fjsJLwOFn2>
[Answer]
# Python3
```
print("Line1",
print("Line2",
print("Line3",
print("Line4") or '') or '') or '')
```
Can be 6 bytes shorter by removing all spaces in last line.
[Answer]
## Javascript
```
[
"console.log('Line1')",
"console.log('Line2')",
"console.log('Line3')",
"console.log('Line4')"
].reverse().forEach(function(e){eval(e)})
```
## C++11
```
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::function<void()>> functors;
functors.push_back([] { std::cout << "Line1"; });
functors.push_back([] { std::cout << "Line2"; });
functors.push_back([] { std::cout << "Line3"; });
functors.push_back([] { std::cout << "Line4"; });
std::reverse(functors.begin(),functors.end());
std::for_each (functors.begin(), functors.end(), [](std::function<void()> f) {f();});
return 0;
}
```
[Answer]
**Batch**
```
echo off
call :revers ^
echo.line1 ^
echo.line2 ^
echo.line3 ^
echo.line4
:revers
if not "%2"=="" call :revers %2 %3 %4 %5 %6 %7 %8 %9
%1
```
[Answer]
# C#
Instead of directly calling the Run method, I'm creating a dynamic method that contains a copy of Run's IL bytecode, except that the load-string opcode operands are swapped. Which causes the new method to display the strings in reverse order.
```
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace TestApp
{
class Program
{
public static void Run()
{
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
Console.WriteLine("Line 3");
Console.WriteLine("Line 4");
}
static void Main(string[] args)
{
var method = typeof(Program).GetMethod("Run");
var il = method.GetMethodBody().GetILAsByteArray();
var loadStringOperands = new Stack<int>();
for (int i = 0; i < il.Length; i++)
{
if (il[i] == OpCodes.Ldstr.Value)
{
loadStringOperands.Push(BitConverter.ToInt32(il, i + 1));
i += 4;
}
}
var run = new DynamicMethod("Run", typeof(void), null);
var gen = run.GetILGenerator(il.Length);
for (int i = 0; i < il.Length; i++)
{
if (il[i] == OpCodes.Ldstr.Value)
{
var str = method.Module.ResolveString(loadStringOperands.Pop());
gen.Emit(OpCodes.Ldstr, str);
i += 4;
}
else if (il[i] == OpCodes.Call.Value)
{
var mInfo = method.Module.ResolveMethod(BitConverter.ToInt32(il, i + 1)) as MethodInfo;
gen.Emit(OpCodes.Call, mInfo);
i += 4;
}
else if (il[i] == OpCodes.Ret.Value)
{
gen.Emit(OpCodes.Ret);
}
}
run.Invoke(null, null);
}
}
}
```
[Answer]
# Python
yet another solution using `eval()`
```
a = [
"print('Line1')",
"print('Line2')",
"print('Line3')",
"print('Line4')"]
for line in reversed(a):
eval(line)
```
it's not very complex, but easy to understand.
] |
[Question]
[
You need to produce output that is **non-deterministic**.
In this case, this will be defined to mean that the output will not always be the same result.
**Rules:**
* A pseudo-random number generator that always has the same seed does not count.
* You can rely on the program being run at a different (unknown) time each execution.
* Your code's process id (if it's not fixed by the interpreter) can be assumed to be non-deterministic.
* You may rely on web-based randomness.
* Your code may not take non-empty input. [Related meta post](https://codegolf.meta.stackexchange.com/a/7172/34718).
* The program is not required to halt, but the output must be displayed.
## Leaderboard
```
function answersUrl(a){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"https://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&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(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.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(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery("<a>"+g+"</a>").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101638,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=34718,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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:400px;float:left}table thead{font-weight:800}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# WinDbg, 1 byte
```
#
```
Wow! Never expected a 1 byte solution from WinDbg!
`#` searches for a disassembly pattern, but since there's no parameters, it looks to just return the next assembly instruction in whatever dump/process you're attached to. Not sure the logic for setting the initial address, but it does.
Sample output:
```
0:000> #
Search address set to 75959556
user32!NtUserGetMessage+0xc
75959556 c21000 ret 10h
0:000> #
user32!NtUserGetMessage+0xf
75959559 90 nop
0:000> #
user32!NtUserMessageCall
7595955a 90 nop
0:000> #
user32!NtUserMessageCall+0x1
7595955b 90 nop
0:000> #
user32!NtUserMessageCall+0x2
7595955c 90 nop
0:000> #
user32!NtUserMessageCall+0x3
7595955d 90 nop
0:000> #
user32!GetMessageW
7595955e 8bff mov edi,edi
0:000> #
user32!GetMessageW+0x2
75959560 55 push ebp
0:000> #
user32!GetMessageW+0x3
75959561 8bec mov ebp,esp
0:000> #
user32!GetMessageW+0x5
75959563 8b5510 mov edx,dword ptr [ebp+10h]
```
[Answer]
# MATLAB, 3 bytes
```
why
```
`why` provides answers to almost any question. A few examples:
```
why
The programmer suggested it.
why
To fool the tall good and smart system manager.
why
You insisted on it.
why
How should I know?
```
This is shorter than any `rand` function I can think of.
[Answer]
# Java 7, ~~33~~ ~~30~~ 27 bytes
```
int a(){return hashCode();}
```
Because Java.
[Answer]
# [huh?](http://esolangs.org/wiki/Huh%3F), 0 bytes
```
```
An empty program still produces output. The last lines of the Python interpreter that are executed:
```
print "..."
f = open('Notes.txt', 'w')
f.write(time.strftime("%c") + " - The user tried to give me commands again. I still have no idea what they are talking about...\n")
```
At the end of a program, the Python interpreter will print `...`, then it will create/open a text file called `Notes.txt` and write a string which contains the current time in front.
[Answer]
# R, 1 byte
```
t
```
Outputs the function's source code and a memory pointer address which changes with every (re-)start of R.
[Answer]
# Minecraft, ~~5~~ 4 bytes
```
op 8
```
Used by typing into a server's console or a command block and giving it power. Can be run from the chat interface by prepending a `/`.
Usually this does nothing, but if there's a player with the username "8" on the server, they will be given operator permissions. Note that while Minecraft normally requires usernames to be 3 characters long, some accounts with shorter name lengths were created before this restriction.
The version that can be demonstrated to be non-deterministic without one of these usernames or risk of giving a user operator permissions is here:
```
me @r
```
Displays a message to everyone, the message being the username of a random player. The `op` command only takes a string literal, not any script that returns a string.
The `me` command wouldn't really work for the first example, it would display `"<your-username> 8"`. When run from a command block, it wouldn't be deterministic since all command blocks have the same "username" but running it from the chat interface would require the `/` for one extra byte.
[Answer]
## [Labyrinth](http://github.com/mbuettner/labyrinth), 5 bytes
```
v
!
@
```
Either prints `0` or nothing (50% chance each).
[Try it online!](http://labyrinth.tryitonline.net/#code=dgohCkA&input=)
There is a very specific case in which Labyrinth exhibits random behaviour:
* There must be a wall in front of the instruction pointer and behind it.
* There must be a non-wall left and right of the instruction pointer.
* The current top of the stack must be zero.
If all of those conditions are met, the direction the IP moves in is chosen (uniformly) randomly. The cherry on top is that those three conditions are impossible to meet in regular control flow, which means unless you modify the source code at runtime.
(This may seem a bit arbitrary, but it's actually the most consistent behaviour I could find for these conditions, since normally the direction of the IP always depends on the previous direction, its neighbours, and the sign of the top of the stack, and this seemed like an elegant way to include a source of randomness in the language.)
With the help of the source code rotation instructions (`<^>v`) it's possible to bring the IP into this situation. One such example is seen at the top. The IP initially points east and starts at the top. The `v` rotates the current column so that we get:
```
@
v
!
```
The IP moves along with this rotation so that it's still on the `v`, pointing east. All the conditions are fulfilled now, so the IP will either go up or down randomly. If it goes up, the program terminates immediately. If it goes down, it prints a zero, rotates the column again, and then terminates.
There are three other programs making use of this (one which also prints `0`, one which prints `00` and one which prints `000`):
```
v
@
!
```
```
"
>@!
```
```
"
>!@
```
(Actually there are a lot more than three other programs, because you could also use `.` instead of `!` to print null bytes, or replace that `"` with a large variety of commands, but I believe they all work essentially the same.)
[Answer]
# Befunge (-93 and -98), 3 bytes
```
?.@
```
The `?` sends execution in a random direction. If it goes up or down, it loops back to the `?` and rerolls. If it goes left, the program wraps round to the `@` and thus exits without printing anything. If it goes right, it prints `0` (the output produced by `.` when the stack is empty) and then exits on the `@`.
[Answer]
# sh + procps, 1 byte
```
w
```
This is the shortest solution I'm aware of that works via calling into external executables. `procps` is the responsible package for reporting information about the current system state (`ps` and friends), and is installed on most Linux distributions by default; `w` is the shortest-named command in it, and returns information about the logged-in users, but also some nondeterministic information like uptime.
[Answer]
## Inform 7, 6 bytes
```
x is y
```
This isn't a valid Inform 7 program, since neither "x" nor "y" has been defined. So this throws an error.
However, some of Inform 7's error messages—including this one—are randomized. So the text it prints is technically non-deterministic.
A few possible outputs include:
>
> **Problem.** The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Adams is Jefferson'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Virginia is a lighted room' says that something called Virginia exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.
>
>
> **Problem.** The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Adam is Eve'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Land of Nod is a lighted room' says that something called Land of Nod exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.
>
>
> **Problem.** The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Clark Kent is Lex Luthor'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Metropolis is a lighted room' says that something called Metropolis exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.
>
>
> **Problem.** The sentence 'x is y' appears to say two things are the same - I am reading 'x' and 'y' as two different things, and therefore it makes no sense to say that one is the other: it would be like saying that 'Aeschylus is Euripides'. It would be all right if the second thing were the name of a kind, perhaps with properties: for instance 'Underworld is a lighted room' says that something called Underworld exists and that it is a 'room', which is a kind I know about, combined with a property called 'lighted' which I also know about.
>
>
>
[Answer]
# JavaScript, 4 bytes
```
Date
```
A function which returns the current date/time. I *think* this is the shortest it will get...
## Explanation
Since this seems to be causing a lot of confusion as to why it's valid, I'll try to explain.
In JavaScript, a function entry is valid if it can be assigned to a variable and called like a function. For example, this function is a valid entry:
```
function(){return Date()}
```
Because it is a function that can be assigned to a variable like so:
```
f=function(){return Date()}
```
And then run with `f()` as many times as necessary. Each time, it returns the current date/time string, which has been ruled non-deterministic by the OP.
This ES6 arrow function is also valid:
```
_=>Date()
```
It can be assigned with `f=_=>Date()`, then run with `f()` like the other one.
Now, here's another valid entry:
```
Date
```
Why? Because just like the other two entries, it can be assigned with `f=Date` and then called with `f()`, returning exactly the same thing as the other two. Try it:
```
var f = Date
```
```
<button onclick="console.log(f())">Run</button>
```
[Answer]
# [Haskell](https://www.haskell.org/), 49 bytes
```
import Unsafe.Coerce
main=putStr[unsafeCoerce(+)]
```
Unfortunately this seems to always outputs the same thing on TIO (I don't quite know why, but I have some guesses), so if you want to try it you should run it locally.
I've only tested this on Linux and OSX. I make no guarentees about Windows. If you are having trouble getting it to work on Linux I would be interested to know.
## Explanation
### What is `unsafeCoerce`?
This answer relies on `unsafeCoerce`. This function is a bit of magic, so first we are going to have to do a quick intro to Haskell's type system.
Haskell has something called type erasure. This means that the compiler checks all the types to make sure that nothing in the program is called on the wrong type. Once it is done with that there is no need to actually store type information any more, so Haskell erases it. So at runtime all data is the same and just relies on the fact that we already checked all the types before hand so nothing goes horribly wrong.
`unsafeCoerce` is a function that lies to the type checker. It tells it that it can take any input and produce any output; it's type is
```
forall a. forall b. a -> b
```
But it does nothing, it gives back the input exactly as it got it. So if you take a string like `"abcd"` and coerce it to an int using `unsafeCoerce` the result will be whatever the representation of `"abcd"` in memory is when interpreted as an integer.
## How are functions represented in memory?
In Haskell, all complex objects including functions are internally represented as a pointer. This is a number in binary that "points" to a specific location in memory. This is because we want to pass these values by reference, since copying the whole thing is expensive, and since Haskell disallows mutation we can with no problem.
However simple objects like ints are passed by value since they are so small that copying them is about as expensive as copying a pointer would be. So they are not represented as pointers but rather just whatever structure they are.
So if we use `unsafeCoerce` from a complex object, say a function, to a simple object, say an `Int`, what happens is that the pointer to the function gets converted to the simple object. And the value of that simple object is dependent only on *where* the complex object is located not anything about what it is.
## Address Space Layout Randomization
*[More reading](https://security.stackexchange.com/questions/18556/how-do-aslr-and-dep-work)*
Many software vulnerabilities rely in part on being able to find particular functions in computer memory to access them. For these techniques you create some malicious code somewhere in memory (this can be done a few ways) and then by hijacking the stack pointer convince a program to run your code. In order to combat these exploits many systems implement something called **A**ddress **S**pace **L**ayout **R**andomization or ASLR. With ASLR key components are placed randomly so that their locations cannot be predicted. This means even if you do get control of the stack pointer it is hard to find where your malicious code is placed. ALSR is not the only technique used against these attacks but it is one we care about.
For Linux systems you can check of ASLR is on using
```
cat /proc/sys/kernel/randomize_va_space
```
Or since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"):
```
sysctl -anr "e_v"
```
There are three levels of security here `0` for off, and `1` and `2` for varying levels of on. My computer has this set to `2` (and your computer probably does too).
You can also set this. However do not do this unless you know what you are doing. Please do not mess with your kernel (unless you know what you are doing). For this reason I'm not going to include the command to do this, but you can look it up online or figure it out from the commands I already gave.
What this means for us is that the locations for objects allocated by Haskell at runtime is random or at least non-deterministic. This means that when we take a complex object like a function and convert it to a simple object like an `Int` the value of that object is random too.
## The program
So that's what our program does. We coerce a function, `(+)` because it is short. We wrap this in a list and print it using `putStr`. Since `putStr` expects a string the compiler infers that the output of `unsafeCoerce(+)` must be a `Char`, which is a simple type.
So we end up printing a random one character string.
# A more normal solution, 44 bytes
```
import System.Random
main=randomIO>>=putChar
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVcvKDEvJT@XKzcxM8@2CMz29Lezsy0oLXHOSCz6/x8A "Haskell – Try It Online")
For completion sake this is the "normal" Haskell approach. It is slightly shorter but far more boring.
[Answer]
# Pyth, 2 bytes
```
O0
```
Explanation:
```
0 0
O Random float in [0, 1)
```
It's that, when `O` has `0` as its argument, it simply returns a random float between `0` and `1`, exclusive.
[Let's do it just for the heck of it!](//pyth.herokuapp.com?code=O0)
Also, it seems that this can be sorta retro (thanks to 34718/mbomb007):
[![Dilbert: September 8, 1992](//assets.amuniversal.com/f6cd08809d50012f2fe500163e41dd5b)](//dilbert.com/1992-09-08)
---
# Pyth, 2 bytes
```
OT
```
Explanation:
```
T 10
O Random integer in [0, 10]
```
[Try this *boooooooooooooooring* version instead `>:(`](//pyth.herokuapp.com?code=OT)
[Answer]
## Python 2, 11 bytes
```
print id(1)
```
[Answer]
# Bash (procps-ng), 2 bytes
```
ps
```
`$$` is also a solution.
[Answer]
# Commodore 64 Basic, 4 bytes
```
1S|0
```
PETSCII substitution: `|` = `SHIFT+Y`
The [zero page](https://en.wikipedia.org/wiki/Zero_page) of a Commodore 64 is an area of 256 bytes of memory that can be accessed faster than the rest of RAM. Consequently, programs (such as the BASIC interpreter) use it for frequently-accessed data, and the CPU itself stores some of its internal state here. The contents are subject to change without notice.
The BASIC program above, ungolfed, is `1 SYS 0`, ie. transfer execution to memory location 0. This starts executing the zero page as code. Normally, when the BASIC interpreter starts running a program, the first 16 bytes are
```
2F 37 00 AA B1 91 B3 22
22 00 00 4C 00 00 00 00
```
so `SYS 0` would execute the following
```
00: ROL-AND $37,A - Undocumented opcode: rotate the value at memory location 0x37 left, and store the result in the accumulator
02: BRK - Call the interrupt vector
```
The overall result is to output the BASIC `READY.` prompt and return control to the user. However, memory location 0x00 is the CPU's I/O direction register, and memory location 0x01 is CPU's I/O address register. If you've done something that changes these before running the program, the results can be unpredictable, ranging from outputting garbage to locking up the computer (the 0x22 usually contained in memory location 0x07, if executed as an instruction, is an undocumented `HALT` opcode).
Alternatively, a more reliably unpredictable program is the four-byte
```
1?TI
```
Prints the elapsed time, in jiffies (1/60 of a second), since system power-on.
[Answer]
## PowerShell, ~~4~~ 2 bytes
*(crossed out 4 [still looks like 4](http://meta.codegolf.stackexchange.com/a/7427/42963))*
```
ps
```
This is the alias for `Get-Process` which will output the current process listing as a table, including handles, private memory, CPU time, etc.
Execute it via something like the following:
```
C:\Tools\Scripts\golfing>powershell.exe "ps"
```
[Answer]
# [Baby Language](https://esolangs.org/wiki/Baby_Language), 0 bytes
```
```
I didn't submit this originally because I thought it postdated the question. I was wrong; the language did have an interpreter created in time. It's also probably the least cheaty 0-byte solution I've seen (given that a 0-byte program is specified to do exactly what the program asks, and not for the purpose of cheating on golfing challenges).
Baby Language is specified to ignore the program it's given and do something at random. (The interpreter linked on the Esolang page generates a random legal BF program and runs it.) That seems like a perfect fit for this challenge.
[Answer]
# [Notepad](https://www.microsoft.com/en-us/p/windows-notepad/9msmlrh6lzf3?activetab=pivot:overviewtab), 1 keystroke
`F5`
Pressing `F5` inserts the time and date in the format `(h)h:mm XM (m)m/(d)d/yyyy`. For example: `12:00 AM 1/1/1970`
[Answer]
# Zsh, 5 bytes
```
<<<$$
```
Prints PID.
[Answer]
## C, ~~25~~ 21 bytes
*Thanks to pseudonym117 for saving 4 bytes.*
```
main(i){putchar(&i);}
```
Compiled with `gcc -o test lol.c` (yeah I'm quite original with my file's name...), and ran with `./test`.
It does what it says: prints the character corresponding to the memory address of `i`, which is defined at runtime, so it should be non-deterministic.
[Answer]
## [BrainfuckX](https://esolangs.org/wiki/BrainfuckX) and [small s.c.r.i.p.t.](https://esolangs.org/wiki/Small_s.c.r.i.p.t.) (etc) polyglot - 2 bytes
```
?.
```
? - Randomize the value in the current cell
. - Send current cell to stdout
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes
```
žd
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xb5k&input=)
Outputs current microseconds from the executing machine's internal clock.
**Or you could do something like this...**
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
A.r
```
[Try it online!](http://05ab1e.tryitonline.net/#code=QS5y&input=)
Outputs a randomly shuffled lower-case alphabet.
**Or this also works:**
```
A.R
```
[Try it online!](http://05ab1e.tryitonline.net/#code=QS5S&input=)
Outputs a random letter from the alphabet.
**Or this also works, and is cooler:**
# [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes
```
"ž"A.RJ.V
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IsW-IkEuUkouVg&input=)
Outputs randomly one of these:
```
ž 23 > ža push current hours
žb push current minutes
žc push current seconds
žd push current microseconds
že push current day
žf push current month
žg push current year
žh push [0-9]
ži push [a-zA-Z]
žj push [a-zA-Z0-9_]
žk push [z-aZ-A]
žl push [z-aZ-A9-0_]
žm push [9-0]
žn push [A-Za-z]
žo push [Z-Az-a]
žp push [Z-A]
žq push pi
žr push e
žs pop a, push pi to a digits (max. 100000)
žt pop a, push e to a digits (max. 10000)
žu push ()<>[]{}
žv push 16
žw push 32
žx push 64
žy push 128
žz push 256
```
[Answer]
# Perl, 5 bytes
```
say$$
```
Outputs the process ID and a newline.
[Answer]
# Python 2, 29 bytes
```
import os
print os.urandom(9)
```
Sadly not the first time writing code on a smartphone.
[Answer]
## [Ruby](https://www.ruby-lang.org/), 3 bytes
```
p$$
```
[Try it online!](https://tio.run/nexus/ruby#@1@govL/PwA "Ruby – TIO Nexus")
Prints the process ID.
[Answer]
# Groovy, 9 bytes
`{print{}}`
Outputs:
`Script1$_run_closure1@2c8ec01c`
Because it outputs the memory address of the closure it is non-deterministic.
[Answer]
# Emotinomicon, 15 bytes
```
üòÄüòÖüé≤‚è¨
```
Explanation:
```
üòÄüòÖüé≤‚è¨
üòÄ push 0. Stack: [0]
üòÖ push 1. Stack: [1]
üé≤ random[pop;pop]. Stack: [1 or 0]
⏬output
```
[Answer]
## Pyke, 1 byte
```
C
```
[Try it here!](http://pyke.catbus.co.uk/?code=C)[broken]
[Try it Online!](https://tio.run/##K6jMTv3/3/n/fwA)
Outputs the current time
[Answer]
## ><>, ~~4~~ 3 bytes
[*(crossed out 4 still looks like 4)*](https://codegolf.stackexchange.com/a/101644/32686)
```
0nx
```
[Try It Online!](http://fish.tryitonline.net/#code=MG54&input=)
Outputs some amount of 0's.
On an empty stack `n` throws an error and terminates the program. `x` chooses a random direction for the stack pointer. This means that for each `0` printed, there is a 50% chance for the program to exit.
] |
[Question]
[
I always used a [Mandelbrot](http://en.wikipedia.org/wiki/Mandelbrot_set) image as the 'graphical' version of Hello World in any graphical application I got my hands on. Now it's your guys' turn.
* Language must be capable of graphical output or drawing charts (saving files disallowed)
* Render a square image or graph. The size at least 128 and at most 640 across\*
* The fractal coordinates range from approximately -2-2i to 2+2i
* The pixels outside of the Mandelbrot set should be colored according to the number of iterations before the magnitude exceeds 2 (excluding\* black & white)
* Each iteration count must have a unique color\*, and neighboring colors should preferably be easily distinguishable by the eye
* The other pixels (presumably inside the Mandelbrot set) must be colored either black or white
* At least 99 iterations
* ASCII art not allowed
\* unless limited by the platform, *e.g.* graphical calculator
Allowed:
![Allowed](https://i.stack.imgur.com/5CQ3j.png)
Disallowed:
![Disallowed](https://i.stack.imgur.com/3NPX6.png)
(shrunken images)
**Winning conditions:**
Shortest version (size in bytes) for each language will get a mention in this post, ordered by size.
No answer will ever be 'accepted' with the button.
**Leaderboard:**
```
/* Configuration */
var QUESTION_ID = 23423; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 17419; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Sharp EL-9300 Graphics Calculator, 296 bytes
[This was my secondary school graphing calculator](https://www.google.com/search?q=sharp%20el-9300c%20graphing%20scientific%20calculator), getting on for 20 years ago! I remember writing a mandelbrot generator for it way back then. And sure enough, its still sitting there in the NV memory:
```
ClrG
DispG
Range -2.35,2.35,.5,-1.55,1.55,0.5
y=-1.55
Label ly
x=-2.35
Label lx
n=1
zx=0
zy=0
Label ln
tzx=zx²-zy²+x
zy=(2*zx*zy)+y
zx=tzx
If zx²+zy²>4Goto esc
n=n+1
If n<20Goto ln
Label esc
If fpart (n/2)=0Goto npl
Plot x,y
Label npl
x=x+.05
If x<=2.35Goto lx
y=y+.05
If y<=1.55Goto ly
Wait
```
It took about 90 minutes to render.
This is totally ungolfed. I'm sure I could save a bit of space, but I just wanted to share this historical curiosity!
I love that the only control statements available are `goto`s.
Here's a photo. I don't have any other means to get the graphical output out:
![enter image description here](https://i.stack.imgur.com/mMVr4.jpg)
[Answer]
I came across this the other day. I don't take credit for it, but damn, is it awesome:
Python 2:
```
_ = (
255,
lambda
V ,B,c
:c and Y(V*V+B,B, c
-1)if(abs(V)<6)else
( 2+c-4*abs(V)**-0.4)/i
) ;v, x=1500,1000;C=range(v*x
);import struct;P=struct.pack;M,\
j ='<QIIHHHH',open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
i ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
*i-950*T **99,T*70-880*T**18+701*
T **9 ,T*i**(1-T**45*2)))(sum(
[ Y(0,(A%3/3.+X%v+(X/v+
A/3/3.-x/2)/1j)*2.5
/x -2.7,i)**2 for \
A in C
[:9]])
/9)
) )
```
![enter image description here](https://i.stack.imgur.com/gafUL.jpg)
<http://preshing.com/20110926/high-resolution-mandelbrot-in-obfuscated-python/>
[Answer]
## LaTeX, 673 bytes
```
\countdef\!1\!129\documentclass{article}\usepackage[margin=0pt,papersize=\!bp]{geometry}\usepackage{xcolor,pgf}\topskip0pt\offinterlineskip\def~{99}\let\rangeHsb~\countdef\c2\countdef\d3\countdef\e4\begin{document}\let\a\advance\let\p\pgfmathsetmacro\makeatletter\def\x#1#2#3{#10
\@whilenum#1<#2\do{#3\a#11}}\d0\x\c{\numexpr~+1}{\expandafter\edef\csname\the\c\endcsname{\hbox{\noexpand\color[Hsb]{\the\d,1,1}\/}}\a\d23
\ifnum\d>~\a\d-~\fi}\def\/{\rule{1bp}{1bp}}\x\c\!{\hbox{\x\d\!{\p\k{4*\d/(\!-1)-2}\p\K{2-4*\c/(\!-1)}\def\z{0}\def\Z{0}\x\e~{\p\:{\z*\z-\Z*\Z+\k}\p\Z{2*\z*\Z+\K}\let\z\:\p\:{\z*\z+\Z*\Z}\ifdim\:pt>4pt\csname\the\e\endcsname\e~\fi}\ifnum\e=~\/\fi}}}\stop
```
>
> ![Result 129x129](https://i.stack.imgur.com/qWIxb.png) (129 × 129)
>
>
>
The PDF image consists of colored square units with size 1bp × 1bp.
## Ungolfed
```
% count register \size contains the width and height of the square
\countdef\size=1
\size=31
\documentclass{article}
\usepackage[margin=0pt,papersize=\size bp]{geometry}
\usepackage{xcolor,pgf}
\topskip0pt
\offinterlineskip
\def\iterations{99}
\let\rangeHsb\iterations
\countdef\c2
\countdef\d3
\countdef\e4
\begin{document}
\let\p\pgfmathsetmacro
\makeatletter
% \Loop: for (#1 = 0; #1 < #2; #1++) {#3}
\def\Loop#1#2#3{%
#1=0
\@whilenum#1<#2\do{#3\advance#11}%
}
\d0%
\Loop\c{\numexpr\iterations+1\relax}{%
\expandafter\edef\csname\the\c\endcsname{%
\hbox{\noexpand\color[Hsb]{\the\d,1,1}\noexpand\pixel}%
}%
\advance\d23 \ifnum\d>\iterations\advance\d-\iterations\fi
}
\def\pixel{\rule{1bp}{1bp}}
% \c: row
% \d: column
% \e: iteration
\Loop\c\size{%
\typeout{c: \the\c}%
\hbox{%
\Loop\d\size{%
\pgfmathsetmacro\k@re{4*\d/(\size-1)-2}%
\pgfmathsetmacro\K@im{2-4*\c/(\size-1)}%
\def\z@re{0}%
\def\Z@im{0}%
\Loop\e\iterations{%
% calculate z(n+1) = z^2(n) + k
\pgfmathsetmacro\temp{\z@re*\z@re-\Z@im*\Z@im+\k@re}%
\pgfmathsetmacro\Z@im{2*\z@re*\Z@im+\K@im}%
\let\z@re\temp
% calculate abs(z)^2
\pgfmathsetmacro\temp{\z@re*\z@re+\Z@im*\Z@im}%
\ifdim\temp pt>4pt\csname\the\e\endcsname\e\iterations\fi
}%
\ifnum\e=\iterations\pixel\fi
}%
}%
}
\stop
```
[Answer]
## x86 DOS Assembly, ~~208~~ ~~177~~ 173 bytes
The full binary, in HEX, that I created by hand, is:
```
DBE3BE00A0B81300CD1056BA640007BF87F9FDBDC7008BCDE81A008AC3AA4979F7B9C70083EF784D79EE33C0CD16B80300CD10CD208BC12BC289441CDF441CDF06A701DEF9D95C088BC52BC289441CDF441CDF06A701DEF9D95C0CD9EED914D95404D95410D95C14B301D904D84C04DE0EA901D8440CD95404D94410D86414D84408D914D80CD95C10D84C04D95414D84410DF06AB01DED99BDFE09B9E7207433ADA72C632DBC3320002000400
```
The sample image is:
![Mandlebrot screen shot with black cropped](https://i.stack.imgur.com/7ISUi.png)
The full source in readable ASM is fairly long (I used this to figure out how I was coding this sucker):
```
.286
CODE SEGMENT
ASSUME CS:code, DS:code
ORG 0100h
; *****************************************************************************
start:
; Mandlebrot coordinates
zr = DWORD PTR [SI+0]
zi = DWORD PTR [SI+4]
cr = DWORD PTR [SI+8]
ci = DWORD PTR [SI+12]
zrsq = DWORD PTR [SI+16]
zisq = DWORD PTR [SI+20]
; Temp int
Temp = WORD PTR [SI+28]
; ===========================================================================
; Initialize
; Initialize the FPU
FNINIT
; SI points to our memory
mov si, 0A000h ; So we can push it
; Shave off some bytes by reusing 100
mov dx, 100
; Switch to MCGA
mov ax, 013h
int 010h
; ES:DI is the end of our drawing area
push si
pop es
mov di, 63879
std ; We're using stosb backwards
; Initialize our X and Y
mov bp, 199
mov cx, bp
; ===========================================================================
; Main draw loop
MainLoop:
; Get our next mandelbrot value
call GMV
; Store it
mov al, bl
stosb
; Decrement our X
dec cx
jns MainLoop
; Decrement our Y
mov cx, 199
sub di, 120
dec bp
jns MainLoop
; ===========================================================================
; Done
; Wait for a key press
xor ax, ax
int 016h
; Change back to text mode
mov ax, 3
int 010h
; Exit to DOS
int 020h
; *****************************************************************************
; GMV: Get Mandelbrot Value
; Gets the value for the next Mandelbrot pixel
; Returns:
; BL - The color to use
GMV:
; ===========================================================================
; Initialize
; cr = (x - 100) / 50;
mov ax, cx
sub ax, dx ; \
mov Temp, ax ; > ST0 = Current X - 100
FILD Temp ; /
FILD Divisor ; ST0 = 50, ST1 = Current X - 100
FDIVP ; ST0 = (Current X - 100) / 50
FSTP cr ; Store the result in cr
; ci = (y - 100) / 50;
mov ax, bp
sub ax, dx ; \
mov Temp, ax ; > ST0 = Current Y - 100
FILD Temp ; /
FILD Divisor ; ST0 = 50, ST1 = Current Y - 100
FDIVP ; ST0 = (Current Y - 100) / 50
FSTP ci ; Store the result in ci
; zr = zi = zrsq = zisq = 0;
FLDZ
FST zr
FST zi
FST zrsq
FSTP zisq
; numiteration = 1;
mov bl, 1
; ===========================================================================
; Our main loop
; do {
GMVLoop:
; zi = 2 * zr * zi + ci;
FLD zr
FMUL zi
FIMUL TwoValue
FADD ci
FST zi ; Reusing this later
; zr = zrsq - zisq + cr;
FLD zrsq
FSUB zisq
FADD cr
FST zr ; Reusing this since it already is zr
; zrsq = zr * zr;
;FLD zr ; Reused from above
FMUL zr
FSTP zrsq
; zisq = zi * zi;
;FLD zi ; Reused from above
FMUL zi
FST zisq ; Reusing this for our comparison
; if ((zrsq + zisq) < 4)
; return numiteration;
FADD zrsq
FILD FourValue
FCOMPP
FSTSW ax
FWAIT
sahf
jb GMVDone
;} while (numiteration++ < 200);
inc bx
cmp bl, dl
jb GMVLoop
;return 0;
xor bl, bl
GMVDone:
ret
;GMV
; *****************************************************************************
; Data
; Divisor
Divisor DW 50
; Two Value
TwoValue DW 2
; 4 Value
FourValue DW 4
CODE ENDS
END start
```
This is designed for compiling with TASM, runs in MCGA, and waits for a keypress before ending the program. The colors are just the default MCGA palette.
**EDIT:** Optimized it, now it draws backwards (same image though), and saved 31 bytes!
**EDIT 2:** To assuage the OP, I have recreated the binary by hand. By doing so, I also shaved another 4 bytes off. I documented every single step of the process, showing all of my work so anybody can follow along if they really want to, here (warning, it's boring and very long):
<http://lightning.memso.com/media/perm/mandelbrot2.txt>
I used a couple regex's in EditPadPro, to find all the `; Final: ...` entries in the file and dump them as hex binary to a .com file. The resulting binary is what you see at the top of this post.
[Answer]
## Java, ~~505~~ ~~405~~ 324 bytes
Just a standard calculation, ~~with golfitude~~ now with extra golfitude.
![enter image description here](https://i.stack.imgur.com/XMrxo.png)
Golfed:
```
import java.awt.*;class M{public static void main(String[]v){new Frame(){public void paint(Graphics g){for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);}}}.show();}}
```
With line breaks:
```
import java.awt.*;
class M{
public static void main(String[]v){
new Frame(){
public void paint(Graphics g){
for(int t,s,n=640,i=n*n;--i>0;g.setColor(new Color(s*820)),g.drawLine(i/n,i%n+28,i/n,i%n),setSize(n,668)){
float c=4f/n,a=c*i/n-2,b=i%n*c-2,r=a,e=b,p;
for(s=t=99;t-->0&&r*r+e*e<4;s=t,p=r*r-e*e+a,e=r*e*2+b,r=p);
}
}
}.show();
}
}
```
[Answer]
# Javascript (ECMAScript 6) - ~~315~~ 308 Characters
```
document.body.appendChild(e=document.createElement("canvas"));v=e.getContext("2d");i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(87);f(0);f(0);k[j++]=255}v.putImageData(i,0,0)
```
![Default Output](https://i.stack.imgur.com/J1bSN.png)
```
(d=document).body.appendChild(e=d.createElement`canvas`);v=e.getContext`2d`;i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(87);f(0);f(0);k[j++]=255}v.putImageData(i,0,0)
```
* Change `n` to vary the image size (and number of iterations).
* Change the values passed in the `f(87);f(0);f(0);` calls (near the end) to change the RGB colour values. (`f(8);f(8);f(8);` is greyscale.)
With `f(8);f(23);f(87);`:
![enter image description here](https://i.stack.imgur.com/0DqHq.png)
```
(d=document).body.appendChild(e=d.createElement`canvas`);v=e.getContext`2d`;i=v.createImageData(e.width=e.height=n=600,n);j=0;k=i.data;f=r=>k[j++]=(n-c)*r%256;for(y=n;y--;)for(x=0;x++<n;){c=s=a=b=0;while(c++<n&&a*a+b*b<5){t=a*a-b*b;b=2*a*b+y*4/n-2;a=t+x*4/n-2}f(8);f(23);f(87);k[j++]=255}v.putImageData(i,0,0)
```
[Answer]
# J, 73 bytes
```
load'viewmat'
(0,?$~99 3)viewmat+/2<|(j./~i:2j479)(+*:) ::(3:)"0^:(i.99)0
```
![mandelbrot set](https://i.stack.imgur.com/BktN5.png)
**Edit**, some explaining:
```
x (+*:) y NB. is x + (y^2)
x (+*:) ::(3:) y NB. returns 3 when (+*:) fails (NaNs)
j./~i:2j479 NB. a 480x480 table of complex numbers in required range
v =: (j./~i:2j479)(+*:) ::(3:)"0 ] NB. (rewrite the above as one verb)
v z0 NB. one iteration of the mandelbrot operation (z0 = 0)
v v z0 NB. one iteration on top of the other
(v^:n) z0 NB. the result of the mandelbrot operation, after n iterations
i.99 NB. 0 1 2 3 4 ... 98
(v^:(i.99))0 NB. returns 99 tables, one for each number of iterations
2<| y NB. returns 1 if 2 < norm(y), 0 otherwise
2<| (v^:(i.99))0 NB. 99 tables of 1s and 0s
+/... NB. add the tables together, element by element.
NB. we now have one 480x480 table, representing how many times each element exceeded norm-2.
colors viewmat M NB. draw table 'M' using 'colors'; 'colors' are rgb triplets for each level of 'M'.
$~99 3 NB. 99 triplets of the numbers 99,3
?$~99 3 NB. 99 random triplets in the range 0 - 98 and 0 - 2
0,?$~99 3 NB. prepend the triplet (0,0,0): black
```
[Answer]
# Mathematica, ~~214~~ ~~191~~ ~~215~~ ~~19~~ 30
Since version 10.0 there is a built-in: (19 bytes)
```
MandelbrotSetPlot[]
```
[![mandelbrot](https://i.stack.imgur.com/WeLG1.png)](https://i.stack.imgur.com/WeLG1.png)
---
To conform to the coordinate range requirements, 11 additional bytes are required. (30 bytes)
```
MandelbrotSetPlot@{-2-2I,2+2I}
```
[![m2](https://i.stack.imgur.com/n9TKj.png)](https://i.stack.imgur.com/n9TKj.png)
---
A hand-rolled case:
```
m=Compile[{{c,_Complex}},Length[FixedPointList[#^2+c&,0,99,SameTest→(Abs@#>=2&)]]];
ArrayPlot[Table[m[a+I b],{b,-2,2,.01},{a,-2,2,.01}],DataRange→{{-2,2},{-2,2}},
ColorRules→{100→Black},ColorFunction→(Hue[Log[34,#]]&)]
```
![green](https://i.stack.imgur.com/efxtb.png)
[Answer]
# Python with Pylab+Numpy, 151 bytes
I couldn't bear to see a non-DQ'ed Python entry, but I think I really outdid myself on this one, and I made it down to 153 characters!
```
import numpy as n
from pylab import*
i=99
x,y=n.mgrid[-2:2:999j,-2:2:999j]
c=r=x*1j+y
x-=x
while i:x[(abs(r)>2)&(x==0)]=i;r=r*r+c;i-=1
show(imshow(x))
```
Also, notably, the second to last line raises 4 distinct runtime warnings, a new personal record!
![enter image description here](https://i.stack.imgur.com/RzPhj.png)
[Answer]
# C + Allegro 4.2.2 - 248 bytes
```
#include<allegro.h>
x=-1,y,K=400;float a,h,c,d,k;main(i){set_gfx_mode('SAFE',K,K,allegro_init(),0);while(x++<K)
for(y=0;y<K;y++){for(a=h=i=0;a*a+h*h<4&&++i<256;k=a,a=a*a-h*h+x*0.01-2,h=2*k*h+y*0.01-2);
putpixel(screen,x,y,i);}while(1);}END_OF_MAIN()
```
Output:
![MSet 1](https://i.stack.imgur.com/t95Jk.png)
[Answer]
### Windows PowerShell (v4), 299 bytes
[![Mandelbrot fractal picture](https://i.stack.imgur.com/zx9Uf.png)](https://i.stack.imgur.com/zx9Uf.png)
```
# Linewrapped here for show:
$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;(
$a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{
$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while(((
$k=$k*$k).Magnitude-lt4)-and$i--){$k+=$C}$b.SetPixel($_,$r,-5e6*++$i)}};$a.Show()
# The single line 299 char entry version:
$M='System.Windows.Forms';nal n New-Object;Add-Type -A System.Drawing,$M;($a=n "$M.Form").backgroundimage=($b=n Drawing.Bitmap 300,300);0..299|%{$r=$_;0..299|%{$i=99;$k=$C=n numerics.complex($_/75-2),($r/75-2);while((($k=$k*$k).Magnitude-lt4)-and$i--){$k+=$C}$b.SetPixel($_,$r,-5e6*++$i)}};$a.Show()
```
**Instructions**
* Run a normal PowerShell console (ISE might not work)
* Copy/paste code in, press Enter
* Wait - it takes a minute or more to run
* The only way to quit is to close the console
**Comment**
* There's a tiny bit of rule-testing going on with the colours inside the set; the rules say *"The other pixels (presumably inside the Mandelbrot set) must be colored either black or white'"*; the code is colouring the pixels completely black RGB(0,0,0) ... it just happens to be a transparent black RGBA(0,0,0,0). So what shows up is the form background colour of the current Windows theme, a slightly off-white RGB(240,240,240) in this case.
[Answer]
## Python + [PIL](http://www.pythonware.com/products/pil/), 166 bytes
```
import Image
d=600;i=Image.new('RGB',(d,d))
for x in range(d*d):
z=o=x/9e4-2-x%d/150.j-2j;c=99
while(abs(z)<2)*c:z=z*z+o;c-=1
i.putpixel((x/d,x%d),5**8*c)
i.show()
```
Output (will open in the default \*.bmp viewer):
![](https://i.stack.imgur.com/K7WCm.png)
[Answer]
# BBC Basic (228 bytes)
What about languages that nobody ever heard of in code golf? Most likely could be optimized, but I'm not quite where - improvements possible. Based of <http://rosettacode.org/wiki/Mandelbrot_set#BBC_BASIC>, but I tried to code golf it as much as possible.
```
VDU23,22,300;300;8,8,8,8
ORIGIN0,300
GCOL1
FORX=0TO600STEP2
i=X/200-2
FORY=0TO300STEP2
j=Y/200
x=0
y=0
FORI=1TO128
IFx*x+y*y>4EXIT FOR
t=i+x*x-y*y
y=j+2*x*y
x=t
NEXT
COLOUR1,I*8,I*4,0
PLOTX,Y:PLOTX,-Y
NEXT
NEXT
```
![The generated Mandelbrot set](https://i.stack.imgur.com/DEi59.png)
The `>` symbol on image is prompt, and it's automatically generated after running the program.
[Answer]
# APL, 194 chars/bytes\*
```
m←{1{⍺=99:0⋄2<|⍵:⍺⋄(⍺+1)∇c+⍵*2}c←⍵}¨⍉v∘.+0j1×v←¯2+4÷s÷⍳s←640
'F'⎕WC'Form'('Coord' 'Pixel')('Size'(s s))
'B'⎕WC'Bitmap'('CMap'(0,,⍨⍪0,15+10×⍳24))('Bits'(24⌊m))
'F.I'⎕WC'Image'(0 0)('Picture' 'B')
```
This is for Dyalog APL with `⎕IO ⎕ML←1 3`
Most of the space is taken by API calls to show a bitmap in a window (lines 2, 3, 4)
If there was a shortcut to do it, the code would be down to 60 chars (line 1)
**Ungolfed version** (only line 1)
```
s←640 ⍝ size of the bitmap
v←(4×(⍳s)÷s)-2 ⍝ vector of s reals, uniform between ¯2 and 2
m←(0j1×v)∘.+v ⍝ square matrix of complex numbers from ¯2j¯2 to 2j2
m←{ ⍝ transform each number in matrix m according to the following
1{ ⍝ function that takes iteration counter as ⍺ and current value as ⍵
⍺=99: 0 ⍝ if we have done 99 iterations, return 0
2<|⍵: ⍺ ⍝ if |⍵| > 2 return the number of iterations done
(⍺+1)∇c+⍵*2 ⍝ otherwise, increment the iterations and recurse with the new value
}c←⍵ ⍝ save the initial value as c
}¨m
```
**Screenshot:**
![screenshot](https://i.stack.imgur.com/XzwhZ.png)
\*: Dyalog has its own single byte charset, with the APL symbols mapped to the upper 128 byte values, so the entire code can be stored in 194 bytes.
[Answer]
### R, ~~199~~ 211 characters
Old solution at 199 characters:
```
r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1)
```
With indentation:
```
r=seq(-2,2,l=500)
c=t(sapply(r,function(x)x+1i*r)) #Produces the initial imaginary number matrix
d=z=array(0,dim(c)) #empty matrices of same size as c
a=1:25e4 #(z will store the magnitude, d the number of iterations before it reaches 2)
for(i in 1:99){ #99 iterations
z[a]=c[a]+z[a]^2
s=abs(z[a])<=2
d[a[!s]]=i
a=a[s]
}
image(d,b=0:99,c=c(1,sample(rainbow(98))),ax=F,asp=1) #Colors are randomly ordered (except for value 0)
```
![enter image description here](https://i.stack.imgur.com/0s72f.png)
**Edit:** Solution at 211 characters that colors the inside of the set and the outside of the first layer differently:
```
r=seq(-2,2,l=500);c=t(sapply(r,function(x)x+1i*r));d=z=array(0,dim(c));a=1:25e4;for(i in 1:99){z[a]=c[a]+z[a]^2;s=abs(z[a])<=2;d[a[!s]]=i;a=a[s]};d[a[s]]=-1;image(d,b=-1:99,c=c(1:0,sample(rainbow(98))),ax=F,asp=1)
```
With indentation:
```
r=seq(-2,2,l=500)
c=t(sapply(r,function(x)x+1i*r))
d=z=array(0,dim(c))
a=1:25e4
for(i in 1:99){
z[a]=c[a]+z[a]^2
s=abs(z[a])<=2
d[a[!s]]=i
a=a[s]
}
d[a[s]]=-1 #Gives the inside of the set the value -1 to differenciate it from value 0.
image(d,b=-1:99,c=c(1,sample(rainbow(99))),ax=F,asp=1)
```
![enter image description here](https://i.stack.imgur.com/sqm6V.png)
[Answer]
# TI-80 BASIC, ~~125~~ 106 bytes
```
ZDECIMAL
FOR(Y,-2,2,.1
FOR(X,-2,2,.1
0->S
0->T
1->N
LBL N
N+1->N
IF S²+T²≥4
GOTO B
S²-T²+X->I
2ST+Y->T
I->S
IF N<20
GOTO N
LBL B
IF FPART (N/2
PT-ON(X,Y
END
END
```
Based on Digital Trauma's answer.
[![enter image description here](https://i.stack.imgur.com/0f0ap.jpg)](https://i.stack.imgur.com/0f0ap.jpg)
[Answer]
# Mathematica 10.0, 19 chars
```
MandelbrotSetPlot[]
```
[`MandelbrotSetPlot`](http://reference.wolfram.com/language/ref/MandelbrotSetPlot.html) is a new function in Mathematica 10.0.
![enter image description here](https://i.stack.imgur.com/Sa6G6.png)
[Answer]
# Java - Processing (271 bytes)
```
void setup(){int h=100,e=5*h,i;float d,v,w,a,b,c;size(e,e);colorMode(HSB,h);loadPixels();d=4./e;v=2;for(int x=1;x<=e;x++){v-=d;w=2;for(int y=0;y<e;){w-=d;a=b=c=0;i=-1;while(a*a+b*b<4&&++i<h){c=a*a-b*b+v;b=2*a*b+w;a=c;}pixels[e*++y-x]=color(i*9%h,h,h-i);}}updatePixels();}
```
Expanded:
```
void setup(){
int h=100, e=5*h, i; //init of size "e", max hue "h", iterator "i"
float d,v,w,a,b,c; //init of stepwidth "d", y-coord "v", x-coord "w", Re(z) "a", Im(z) "b", temp_a "c"
size(e,e);
colorMode(HSB,h);
loadPixels();
d = 4./e;
v = 2;
for(int x = 1; x <= e; x++){
v -= d;
w = 2;
for(int y = 0; y < e;){
w -= d;
a = b = c = 0;
i = -1;
while(a*a + b*b < 4 && ++i < h){
c = a*a - b*b + v;
b = 2*a*b + w;
a = c;
}
pixels[e * ++y - x] = color(i*9 % h, h, h-i);
}
}
updatePixels();
}
```
![](https://i.stack.imgur.com/5FCSN.jpg)
[Answer]
# Applesoft BASIC, ~~302~~ ~~286~~ 280 bytes
This picks random points to draw, so it will run forever and may never fill in the full plane.
```
1HGR:POKE49234,0:DIMco(10):FORc=0TO10:READd:co(c)=d:NEXT:DATA1,2,3,5,6,1,2,3,5,6,0
2x=INT(RND(1)*280):y=INT(RND(1)*96):x1=x/280*3-2:y1=y/191*2-1:i=0:s=x1:t=y1
3s1=s*s-t*t+x1:t=2*s*t+y1:s=s1:i=i+1:IFs*s+t*t<4ANDi<20THENGOTO3
4c=co(i/2):IFc THENHCOLOR=c:HPLOTx,y:HPLOTx,191-y
5GOTO2
```
Turns out Applesoft BASIC is *really* forgiving about lack of spaces. Only one space is necessary in the entire program.
Output after 14 hours:
[![output](https://i.stack.imgur.com/qCoDC.png)](https://i.stack.imgur.com/qCoDC.png)
GIF:
[![gif](https://i.stack.imgur.com/l5IYO.gif)](https://i.stack.imgur.com/l5IYO.gif)
Before golfing:
```
10 HGR : POKE 49234,0
20 DIM co(10) : FOR c = 0 TO 10 : READ d : co(c) = d : NEXT
30 DATA 1, 2, 3, 5, 6, 1, 2, 3, 5, 6, 0
100 x = INT(RND(1) * 280) : y = INT(RND(1) * 96)
110 x1 = x / 280 * 3 - 2 : y1 = y / 191 * 2 - 1
120 i = 0:s = x1:t = y1
130 s1 = s * s - t * t + x1
140 t = 2 * s * t + y1:s = s1: i = i + 1
150 IF s * s + t * t < 4 AND i < 20 THEN GOTO 130
160 c = co(i/2) : IF c THEN HCOLOR= c : HPLOT x,y : HPLOT x,191 - y
170 GOTO 100
```
Note: `POKE 49234,0` (in Applesoft BASIC) puts the machine into full graphics mode.
### A version optimized for B&W displays:
```
110 HGR:POKE 49234,0:HCOLOR=3
120 FOR x = 0 TO 279:FOR y = 0 TO 95
130 x1 = x / 280 * 3 - 2:y1 = y / 191 * 2 - 1
140 i = 0:s = x1:t = y1:c = 0
150 s1 = s * s - t * t + x1
160 t = 2 * s * t + y1:s = s1:c = 1 - c:i = i + 1
170 IF s * s + t * t < 4 AND i < 117 THEN GOTO 150
180 IF c = 0 THEN HPLOT x,y:HPLOT x,191 - y
190 NEXT:NEXT
```
Output after 12 hours:
[![b&w](https://i.stack.imgur.com/K2fu9.png)](https://i.stack.imgur.com/K2fu9.png)
### A version that will work in GW-BASIC (DOS):
```
5 CLS
6 SCREEN 1
20 DIM co(10) : FOR c = 0 TO 10 : READ d : co(c) = d : NEXT
30 DATA 1, 2, 3, 5, 6, 1, 2, 3, 5, 6, 0
100 x = INT(RND(1) * 280) : y = INT(RND(1) * 96)
110 x1 = x / 280 * 3 - 2 : y1 = y / 191 * 2 - 1
120 i = 0 : s = x1 : t = y1
130 s1 = s * s - t * t + x1
140 t = 2 * s * t + y1 : s = s1 : i = i + 1
150 IF s * s + t * t < 4 AND i < 20 THEN GOTO 130
160 c = co(i/2) : PSET (x,y),C : PSET (x,191 - y),C
170 GOTO 100
```
[Answer]
# [R](https://www.r-project.org/), ~~140~~ ~~136~~ ~~128~~ ~~124~~ ~~123~~ ~~110~~ 109 bytes\*
```
image(outer(j<-1:396/99-2,j,Vectorize(function(x,y,n=99){while((n=n-1)&abs(F)<2)F=F*F+x+1i*y;n})),c=colors())
```
[Try it at rdrr.io](https://rdrr.io/snippets/embed/?code=image(outer(j%3C-1%3A396%2F99-2%2Cj%2CVectorize(function(x%2Cy%2Cn%3D99)%7Bwhile((n%3Dn-1)%26abs(F)%3C2)F%3DF*F%2Bx%2B1i*y%3Bn%7D))%2Cc%3Dcolors()))
6y after the Q was asked, but I love Mandelbrot sets, and the earlier R solution was 211 characters...
[![enter image description here](https://i.stack.imgur.com/I0XrN.png)](https://i.stack.imgur.com/I0XrN.png)
\*Or just [62 bytes](https://rdrr.io/snippets/embed/?code=pixel_shader%3Dfunction(x%2Cy%2Cn%3D99)%7Bwhile((n%3Dn-1)%26abs(F)%3C2)F%3DF*F%2Bx%2B1i*y%3Bcolors()%5Bn%2B1%5D%7D%0Aj%3D1%3A396%2F99-2%0Aimage(outer(j%2Cj%2CVectorize(function(x%2Cy)which(colors()%3D%3Dpixel_shader(x%2Cy))))%2Cc%3Dcolors())) as a [pixel-shader](https://codegolf.meta.stackexchange.com/a/18305/95126) function in [R](https://www.r-project.org/)≥4.1:
`\(x,y,n=99){while((n=n-1)&abs(F)<2)F=F*F+x+1i*y;colors()[n+1]}`
[Answer]
## JavaScript, ~~284 283 ...(12 improvements)... 191 190 188~~ 199 bytes
currenty (2019-10-05) this is shortest js solution (the shortest one before this has [285 bytes](https://codegolf.stackexchange.com/a/24080/88163))
[![enter image description here](https://i.stack.imgur.com/1vJFc.png)](https://i.stack.imgur.com/1vJFc.png)
Expanded
```
// Fractal calculations
c=512;
// p has pixels, p+= allways join 4 digit number implicit casted to string
// 4 char string interpred as base64 gives 3bytes = 1 RGB pixel
for( p=i=''; j=x=y=0,++i<=c*c; p+= j<c ? 9*c+9*j : 'AAAA' )
while( x*x+y*y<4 && ++j-c )
[x,y] = [ x*x-y*y+i%c/128-2, 2*x*y+i/c/128-2 ];
// draw pixels in 512x512 BMP base64 image
document.write("<img src=data:;base64,Qk0bAAwAAAAAABsAAAAMAAAAAAIAAgEAGAAA"+p)
```
After small constans changes
```
c=512;for(p=i='';j=x=y=0,++i<=c*c;p+=j<c?2*c+9*j:'AAAA')while(x*x+y*y<4&&++j-c)[x,y]=[x*x-y*y+i%c/128-2,2*x*y+i/c/128-2]
document.write("<img src=data:;base64,Qk0bAAwAAAAAABsAAAAMAAAAAAIAAgEAGAAA"+p)
```
[Answer]
# GLSL - 225 bytes:
```
void main(){vec2 c=gl_FragCoord.xy/iResolution.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(iChannel0,v);}
```
Defining variables in the code (242 bytes):
```
uniform vec3 r;uniform sampler2D t;void main(){vec2 c=gl_FragCoord.xy/r.y*4.-2.,z=c,v;for(int i=0;i<99;i++){z=vec2(z.x*z.x-z.y*z.y,2.*z.x*z.y)+c;if(length(z)>2.&&v.y<1.)v=vec2(float(i)/99.,1.);}gl_FragColor=(v.y<1.)?vec4(v,v):texture2D(t,v);}
```
[See it in ShaderToy](https://www.shadertoy.com/view/Xs2GW3)
![Mandelbrot Golf](https://i.stack.imgur.com/Wjn4B.png)
This requires a suitable palette texture be loaded as `iChannel0`. (The colouring here is from the "random pixel" texture on ShaderToy).
[Answer]
# Octave (~~212~~ 136 bytes)
(Now including some ideas due to @ChrisTaylor.)
```
[y,x]=ndgrid(-2:.01:2);z=c=x+i*y;m=c-c;for n=0:99;m+=abs(z)<2;z=z.^2+c;end;imagesc(m);colormap([hsv(128)(1+mod(0:79:7890,128),:);0,0,0])
```
With whitespace:
```
[y,x] = ndgrid(-2:.01:2);
z = c = x + i*y;
m = c-c;
for n=0:99
m += abs(z)<2;
z = z.^2 + c;
end
imagesc(m)
colormap([hsv(128)(1+mod(0:79:7900,128),:);
0,0,0])
```
Output:
![Mandelbrot steps to abs(z)>2](https://i.stack.imgur.com/MHQOw.png)
To convert to Matlab, change "`m+=abs(z)<2`" to "`m=m+(abs(z)<2)`". [+3 bytes]
To make the aspect ratio 1:1, add "`;axis image`". [+11 bytes]
My first answer (212 bytes):
```
[x,y]=meshgrid(-2:.01:2);z=c=x+i*y;m=0*e(401);for n=0:99;m+=abs(z)<2;z=z.^2+c;endfor;t=[0*e(1,7);2.^[6:-1:0]];[s{1:7}]=ndgrid(num2cell(t,1){:});t=1+sum(cat(8,s{:}),8);imagesc(m);colormap([hsv(128)(t(:),:);0,0,0])
```
[Answer]
## [PostScript](https://en.wikipedia.org/wiki/PostScript), ~~290~~ ~~285~~ ~~282~~ ~~271~~ 261 bytes
#### Screenshot:
[![screeshot](https://i.stack.imgur.com/eK42t.png)](https://i.stack.imgur.com/eK42t.png)
#### Golfed code:
```
-2 .01 2{/a exch def -2 .01 2{/b exch def/x 0 def/y 0 def 0 1 99{/i exch def x x mul y y mul add 4 ge{i log 2 div 1 1 sethsbcolor a 2 add 100 mul b 2 add 100 mul 1 1 rectfill exit}if/x x x mul y y mul sub a add/y 2 x mul y mul b add def def}for}for}for showpage
```
#### Ungolfed code:
```
-2 .01 2 {
/a exch def
-2 .01 2 {
/b exch def
/x 0 def
/y 0 def
0 1 99 {
/i exch def % iteration count
x x mul y y mul add 4 ge {
i log 2 div 1 1 sethsbcolor % rainbow colors outside
a 2 add 100 mul
b 2 add 100 mul 1 1 rectfill
exit
} if
/x x x mul y y mul sub a add
/y 2 x mul y mul b add
def def
} for
} for
} for
showpage
```
[Answer]
# gnuplot 110 (105 without newlines)
Obligatory gnuplot entry. It's been done countless times but this one is from scratch (not that it's difficult). I like how `gnuplot` golfs its commands intrinsically :)
```
f(z,w,n)=abs(z)>2||!n?n:f(z*z+w,w,n-1)
se vi map
se si sq
se isos 256
sp [-2:2] [-2:2] f(0,x+y*{0,1},99) w pm
```
ungolfed:
```
f(z,w,n)=abs(z)>2||n==0?n:f(z*z+w,w,n-1)
set view map
set size square
set isosamples 256
splot [-2:2] [-2:2] f(0,x*{1,0}+y*{0,1},99) with pm3d
```
However, I'm DEEPLY disappointed at the entry of complex numbers. `x*{1,0}+y*{0,1}` must be the saddest existing way of constructing a complex number.
Oops, the image:
![gnuplot mandelbrot](https://i.stack.imgur.com/oY7Wa.png)
Set isosamples higher for better resolution. We could also say `unset tics` and `unset colorbox` for a pure image, but I think this version qualifies just fine.
[Answer]
## Matlab (89 bytes)
```
[X,Y]=ndgrid(-2:.01:2);C=X+i*Y;Z=C-C;K=Z;
for j=1:99,Z=Z.*Z+C;K=K+(abs(Z)<2);end,imagesc(K)
```
Output -
![enter image description here](https://i.stack.imgur.com/3zaic.png)
Doesn't satisfy the requirement that the inner cells must be black or
white, but that can be satisfied by either (1) using `imshow(K)` instead
of `imagesc(K)` (requires 1 fewer byte but needs the image processing
toolbox) or (2) appending `colormap hot` (requires 12 more bytes).
Ungolfed version -
```
Z = zeros(N);
K = Z;
[X,Y]=ndgrid(-2:.01:2);
C = X+1i*Y;
for j = 1:99
Z = Z.*Z + C;
K(K==0 & abs(Z) > 2) = j;
end
imagesc(K)
```
[Answer]
# Excel VBA, ~~251~~ ~~246~~ ~~224~~ ~~223~~ 221 bytes
Saved 5 bytes thanks to ceilingcat
Saved 23 bytes thanks to Taylor Scott
```
Sub m
D=99
For x=1To 4*D
For y=1To 4*D
p=0
q=0
For j=1To 98
c=2*p*q
p=p^2-q^2-2+(x-1)/D
q=c+2+(1-y)/D
If p^2+q^2>=4Then Exit For
Next
j=-j*(j<D)
Cells(y,x).Interior.Color=Rnd(-j)*1E6*j/D
Next y,x
Cells.RowHeight=48
End Sub
```
Output:
[![Output with D = 99](https://i.stack.imgur.com/jcPqJ.png)](https://i.stack.imgur.com/jcPqJ.png)
I made a version that did this a long time ago but it had a lot of extras like letting the user pick the basic color and easy-to-follow math. Golfing it way down was an interesting challenge. The `Color` method uses `1E6` as a means to get a wide range of colors since the valid colors are `0` to `2^24`. Setting it to `10^6` gave nice contrast areas.
Explanation / Auto-Formatting:
```
Sub m()
'D determines the number of pixels and is factored in a few times throughout
D = 99
For x = 1 To 4 * D
For y = 1 To 4 * D
'Test to see if it escapes
'Use p for the real part and q for the imaginary
p = 0
q = 0
For j = 1 To 98
'This is a golfed down version of complex number math that started as separate generic functions for add, multiple, and modulus
c = 2 * p * q
p = p ^ 2 - q ^ 2 - 2 + (x - 1) / D
q = c + 2 + (1 - y) / D
If p ^ 2 + q ^ 2 >= 4 Then Exit For
Next
'Correct for no escape
j = -j * (j < D)
'Store the results
'Rnd() with a negative input is deterministic
'This is what gives us the distinct color bands
Cells(y, x).Interior.Color = Rnd(-j) * 1000000# * j / D
Next x, y
'Resize for pixel art
Cells.RowHeight = 48
End Sub
```
---
I also played around with `D=999` and `j=1 to 998` to get a much larger and more precise image. The results are irrelevant to the challenge because they're way too large but they *are* neat.
[![D=999](https://i.stack.imgur.com/FHIHY.jpg)](https://i.stack.imgur.com/FHIHY.jpg)
[Answer]
## [Floater](https://esolangs.org/wiki/Floater), 620 pixels
A language I made up when I got inspired by my own challenge, as well as from the esoteric language Piet.
![enter image description here](https://i.stack.imgur.com/VfnKu.png)
[Answer]
# JavaScript + HTML5 (356B)
(Note: lines ending with '//' are added here for some readability)
Performant version (375B):
```
<body onload='var
w,h=w=C.width=C.height=500,X=C.getContext("2d"),I=X.createImageData(w,h),D=I.data, //
y=0,f=255,T=setInterval(function(x,i,j,k,l,c,o){for(x=0;x<w;){ //
for(i=x*4/w-2,j=y*4/h-2,k=l=0,c=f;--c&&k*k+l*l<4;)t=k*k-l*l+i,l=2*k*l+j,k=t
D[o=(y*w+x++)*4]=(c*=0xc0ffeeee)&f
D[++o]=c>>8&f
D[++o]=c>>16&f
D[++o]=f}X.putImageData(I,0,0)
++y-h||clearInterval(T)},0)'><canvas id=C>
```
Slow version (356B): remove the 'var' and parameters in the inner function so that the global scope is used.
Try it out: <http://jsfiddle.net/neuroburn/Bc8Rh/>
![enter image description here](https://i.stack.imgur.com/WlPl6.png)
[Answer]
# Javascript, 285B
Based off my code and some improvements on [MT0's](https://codegolf.stackexchange.com/users/15968/mt0) code, I've got this down to 285B in colour:
```
document.body.appendChild(V=document.createElement('Canvas'));j=(D=(X=V.getContext('2d')).createImageData(Z=V.width=V.height=255,Z)).data;for(x=Z*Z;x--;){k=a=b=c=0;while(a*a+b*b<4&&Z>k++){c=a*a-b*b+4*(x%Z)/Z-3;b=2*a*b+4*x/(Z*Z)-2;a=c;}j[4*x]=99*k%256;j[4*x+3]=Z;}X.putImageData(D,0,0);
```
in action: <http://jsfiddle.net/acLhe/7/>
### was: Coffeescript, 342B
```
document.body.appendChild V=document.createElement 'Canvas'
N=99
Z=V.width=V.height=400
P=[]
P.push "rgba(0,0,0,"+Math.random()*i/N+')' for i in [N..0]
X=V.getContext '2d'
for x in [0..Z]
for y in [0..Z]
k=a=b=0
[a,b]=[a*a-b*b+4*x/Z-3,2*a*b+4*y/Z-2] while a*a+b*b<4 and N>k++
X.fillStyle=P[k-1]
X.fillRect x,y,1,1
```
Coffeescript is supposed to be readable :-/ see it in action: <http://jsfiddle.net/acLhe/6/>
![Mandelbrot Coffeescript](https://i.stack.imgur.com/9rMdo.png)
] |
[Question]
[
Consider a square of [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters (code points 0x20 to 0x7E) for side length **N**, like the following (here, **N = 6**):
```
=\
g \
7
m+y "g
L ~
e> PHq
```
We also require **each row** and **each column** to contain at least **1 space** and **1 non-space** character. (The above example satisfies this.)
We define the **negative** of such a square, to be a square of the same size, where each space is replaced with a non-space and vice versa. E.g., the following would be a valid negative of the above example:
```
1234
a b cd
ZYXWV
!
{} [ ]
?
```
The choice of non-space characters is irrelevant (as long as they are from the printable ASCII range).
## The Challenge
You're to write a program, with square source code with side length **N > 1**, which prints a negative of itself to STDOUT. Trailing spaces *have* to be printed. You may or may not print a single trailing newline.
The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment, which automatically prints the value of each entered expression.
The winner is the program with the lowest side length **N**. In the event of a tie, the submission with the fewest non-space characters in the source code wins. If there's still a tie, the earliest answer wins.
[Answer]
# Perl, 7×7 (42 non-spaces)
```
for$i(
1..56 )
{$_= $i
%8? $i%
7? $":7
: $/;1;
print}
```
## Output:
```
7
7
7
7
7
7
7
```
[Answer]
# CJam, 4X4 (~~12~~ 10 non-spaces)
```
6,
SS +
* 4/
N*
```
Output:
```
0 1
2
3
4 5
```
---
Previous version with 12 non-spaces:
```
4a4
* 4S
** 4
/N*
```
And the output is
```
4
4
4
4
```
As pointed out by Martin, this version has
* **4** Spaces,
* **4** `*`,
* **4** `4`,
* **4** other characters, and
* **4** `4` as the output
;)
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Marbelous - 16x16
```
....@0..@1....
@3..0A08..@2 ..
/\--....>1 ..Hp
..@2..\\ =0@3..
ss..// --\\\\..
@0/\ @1/\Hp..!!
:s #the-cake-is
2020#a-pie/lie
```
[Test it here!](https://codegolf.stackexchange.com/a/40808/29611) Spaces as blanks, cylindrical board, and include libraries all must be checked.
### Output
```
07
06
05
04
03
02
01
01
```
### Explanation
There are two boards here: the main board (shown below), and the `ss` board, which takes no inputs and outputs two spaces (0x20) to STDOUT.
A blank cell is equivalent to a `..`, and anything after a `#` is a comment.
![Picture of Board](https://i.stack.imgur.com/iIv75.png)
Every tick, `ss` outputs two spaces to STDOUT.
The green path is a simple loop that outputs a newline (0x0A) at the end of every 7th tick.
The blue path will output the numbers (`Hp` prints a marble as two hex digits) present in the output, at the end of every 6th tick.
After we have printed `01` once, the loop ends, and moves down the red path, which duplicates this marble.
One duplicate is printed (the second `01`), and the other is sent down the black path, which terminates the board at the `!!` cell. Because of the location of the `Hp` used in this last print, the `01` appears *before* the same tick's two spaces, rather than after, the behavior of every other `Hp` call.
[Answer]
# Python - 11x11
```
import re
[print(
re.sub(
"0", " ",
bin(x)[
2:].zfill(
11)))for x
in[19,15,
1920,116,
15,1,5,3,
3,3, 67]]
```
## Output
```
1 11
1111
1111
111 1
1111
1
1 1
11
11
11
1 11
```
It's a pretty messy and boring solution, but I just thought I'd show that...
1. It can be done in Python
2. If you can compress information about your code shorter than your code, then you can pull off something like this :)
This solution takes advantage of the fact that, if you're within a pair of brackets in Python, then you can split your code over several lines and arbitrarily add spaces without getting an `IndentationError`. Another way of doing something like this is by ending the line with a backslash.
[Answer]
# Python - 7x7 (37 non-spaces)
```
print(
'%+7s'
'\n'%1
*6+'%'
'-7s'%
111111
)
```
## Output
```
1
1
1
1
1
1
111111
```
Uses Python's old `%` string formatting operator to do the job: `+7` and `-7` take care of right/left justification, and the last space to match the closing parenthesis for `print` in particular. In preparing the format string, we also have
* automatic concatenation of string literals across lines, and
* string repetition by multiplication (giving us multiple replacement fields for the price of one)
[Answer]
# CJam, 4 x 4 (8 non-spaces)
```
L _
{ _
_ }
_ p
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%20L%20_%0A%7B%20_%20%0A%20_%20%7D%0A_%20p%20).
### Output
```
{ _
_ }
{ _
_ }
```
### How it works
* `L` pushes an empty array and `_` pushes a copy of it.
* The block
```
{ _
_ }
```
pushes that block on the stack.
* `_` pushes a copy of the code block and `p` prints it, followed by a linefeed.
* Finally, the interpreter prints all remaining items on the stack: two empty arrays that do not affect the output, and the original code block.
## Alternate version
```
L ~
{ _
p }
_ ~
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%20L%20~%0A%7B%20_%20%0A%20p%20%7D%0A_%20~%20).
### Output
```
{ _
p }
{ _
p }
```
### How it works
* `L` pushes an empty array and `~` dumps it. The stack is empty again.
* The block
```
{ _
p }
```
pushes that block on the stack.
* `_` pushes a copy of the block and `~` executes the copy.
The `_` inside the copy of the block will push a copy of the original block, which `p` will print, followed by a linefeed.
* Finally, the interpreter prints the remaining item on the stack: the original code block.
[Answer]
# JavaScript (9x9)
```
i=9;q=""
; for(;++
i< 91;){;
var q=q+(
!(i% 10.0
)?1:" ");
;i%9|| (q
+="\n") }
alert(q)
```
# Output
```
1
1
1
1
1
1
1
1
1
```
# Notes
I made and golfed (to the best of my ability) code for a square with diagonal of any size n:
```
q="";for(i=***n***;++i<***n^2+n+1***;i%***n***||(q+="\n"))q+=i%***n+1***?"0":1
```
replacing the \*\*\*asdf\*\*\* numbers with constants depending on the side length n, for example for n=6:
```
q="";for(i=6;++i<43;i%6||(q+="\n"))q+=i%7?" ":1
```
But, even though that code is length 46, I couldn't get the constant space to line up with a space in the diagonal of the code until it was as big as a 9x9, with a wasted line (the 5th one)
Edit: Changed to add alert(). Before:
```
i=9;q=""
; while((
++ i)<91)
{q= q+""+
""+( "")+
(!((i %10
))?1:" ")
;i%9||( q
+="\n")}
```
[Answer]
# CJam, 5x5, 12 non-spaces
Not a winner, but I wanted to add a rather small and *sparse* submission, since most answers just print a diagonal.
```
1 ]
D * S
* 5
/ N *
1 ;
```
prints
```
1 1 1
1 1
1 1 1
1 1
1 1 1
```
[Test it here.](http://cjam.aditsu.net/)
The last two characters of the code, don't do anything, so it actually only has 10 bytes of real code. For a smaller grid, I could even reduce it by another two bytes to 8, but that doesn't fit on 3x3, and this code doesn't work for even grid sizes.
How it works:
```
1] "Push [1].";
D* "Repeat 13 times.";
S* "Riffle with spaces.";
5/ "Split into runs of five elements.";
N* "Join those with line breaks.";
1; "Push and pop a 1. No-op.";
```
[Answer]
# [Befunge](http://esolangs.org/wiki/Befunge), 9x9
I have no idea why I did this. It took *way* too long. I have a massive headache now.
```
8>v_20gv
v9<^v#<4
1@,/<>^6
v1,*$:<p
->,!-^87
:^*25<^g
_88g,^^4
9vp\v#6<
@
```
Output:
```
@
@
@
@
@
@
@
@
$$$$$$$$
```
## Some explanation
The code uses `g` to read the `@` characters from the grid "on the fly" (and also the final space, which is `@ / 2`), and `p` to modify the loop to write the last output line.
Every single character on the code is used at some point, either as code or as data (the `9` and the `@` on the two last lines).
I basically had to do a lot of workarounds to make the code work. The instruction pointer does multiple intersections during execution, of which some are jumped over. (I couldn't use any instruction there for different directions as they would interfere. There is no NOP.) Elsewhere I either reused the same character or just undid it (see the `$:` in the middle).
I also did some creative work on the stack:
* When the (inner) character writing loop terminates (all spaces done for this line), the stack has `n,0`. I then have to decrement `n`. The obvious solution would be `$1-`, but I managed to shorten it by using `!-`.
* When the (outer) line writing loop terminates (all normal lines printed), the stack has a `0`. I then organized code changer (`20g46p7g46\p`) to use that `0`, instead of wasting 2 characters on `$0`.
[Answer]
## Python 3, 8x8
There are 50 non-space characters and 14 spaces. The last line has one useless character, but everything else is necessary.
```
(*_,q,n
)=p='''
p
'''[2:]
print(p
*2+q*7,
n+p*4+p
[0:-1])
```
Output:
```
p
p
ppppppp
p
p
p
p
p
```
[Answer]
# Ruby, 8x8
```
(0...8)
. map(){
|x |$><<
32. chr*
x+[x ]*'
'<<32 .\
chr*(7 -
x)+?\n}
```
Output:
```
0
1
2
3
4
5
6
7
```
[Answer]
# CJam, 5X5
```
SSSS
1N]4
*B11
S
```
And the output is
```
1
1
1
1
1111
```
~~I was this close to 4X4 solution. `<sigh>`~~ See my [other answer](https://codegolf.stackexchange.com/a/42032/31414)
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# C++, 12x12
**Edit:** So, I became a little obsessed with this challenge and managed to get it down from 17x17 to 12x12. It took me a little while to realize I could use `/**/` as a token delimiter. This code takes advantage of the fact that a line splice still works in Clang with a space after it, though it does give warnings and ruins Xcode's colorization of the code.
```
#include<c\
stdio>/***/
int/**/mai\
n(){for(in\
t/**/i=0;i\
<12;++i)pr\
intf(i^8?"\
\
|\n":"~~~~\
~~~~~~~\x2\
0\n");}/**/
```
Output:
```
|
|
|
|
|
|
|
|
~~~~~~~~~~~
|
|
|
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3x3 (6 non-space [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
```
3Ð
Λ q
°°
```
**Output:**
```
3
3
3
```
[Try it online.](https://tio.run/##MzBNTDJM/f9fwfjwBK5zsxUKuQ5tOLRB4f9/AA)
**Explanation:**
```
3Ð # Push three 3s to the stack
Λ # Canvas with parameters num; filler; pattern
# num: The amount of characters to display (3)
# filler: The character to display ('3')
# pattern: The available options are single-digit integers in the range [0,7]
# indicating the direction to print in.
# (Option 3 is a top-left to bottom-right diagonal line)
q # Exit the program
°° # no-ops to complete the pattern
```
[Answer]
# [Befunge-98](https://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown "Funge-98 Spec"), 8x8 (56 non-spaces [11 nops])
Note: In the interest of good sports-person-ship, this reads its own source via `'`, making it a cheat-quine to some. Read the debate [here](http://meta.codegolf.stackexchange.com/a/4878/36773).
## Program
```
07'?>:8v
v y+da:%<
<v ':vj!-
,+# '<zzv
v1#a vj!<
>z,\1 -\v
z>+,$v z<
1_@#:<v -
zzzzzv<z
```
## Output
```
(
,
&
%
$
#
"
!
```
## Explanation
The un-golfed version
```
07'?>:8%:ad+y-!jv>'n,$v
!jv a,\1-\v > 's,
> > v
v-1_@#: <
```
(non-space and space are replaced with 'n and 's for readability sake.)
This solution is based off of the fact that using an index [0,width^2) mod the width of the square can tell you if you are at the end of the row or on the diagonal. Since all spaces are placed along the diagonal, it is easy to tell when to print a non-space!
### In Pseudocode
```
const int WIDTH = 8
push 0 //Because of the way the 'y' instruction works when picking
int row=7 //8-1 rows
int i=63 //Starting at the end allows for the cheaper i != 0
do
{
pick variable row from the stack bottom + 1//ad+y
if(i%WIDTH == row)
{
print non-space
}
else
{
print space
if(i%WIDTH == 0)
{
print new-line
--row
}
}
--i
}
while(i != 0);
```
## Discussion
I'm very proud of it, though I wish I could have made every non-space also a non-nop. I'm also proud that I didn't use the standard Befunge get-increment-put trope! It prints out different symbols for non-space because I had the room for it and didn't want to be boring.
Try it on Windows with [BefungeSharp](https://github.com/tngreene/Befungesharp "Download the latest release!")!
[Answer]
# CJam, 4 x 4 (8 non-spaces)
```
N a
` S
* N
X $
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%20N%20a%0A%60%20S%20%0A%20*%20N%0AX%20%24%20).
### Output
```
[ "
" ]
[ "
" ]
```
### How it works
* `N` pushes a linefeed as a singleton string. `a` wraps that string in an array.
* ``` inspects the result, i.e., it pushes a string representation of the array.
This is the result:
```
["
"]
```
* `S*` joins the resulting string (array of characters), separating its elements using spaces. In other words, it puts a space character between all pairs of adjacent characters of the string.
This is the result:
```
[ "
" ]
```
* `N` pushes another linefeed.
* `X$` copies the stack item at index 1 (counting from the top), i.e., the multi-line string.
* Finally, the interpreter prints all items on the stack: the original multi-line string, the linefeed and the copy of the multi-line string.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 2x2 (2 non-spaces)
```
2
╚
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MiUyMCUwQSUyMCV1MjU1QQ__)
### Output
```
/
/
```
### Explanation
In SOGL all lines except the last are replacing lines - it replaces everywhere in the continuing code the last character of the line with everything before it. SO the 1st line here is `replace space with 2 in the next line`.
Then the next line - `2╚` gets executed: `2` pushes 2, and `╚` creates a diagonal of size 2.
[Answer]
# CBM BASIC v2.0 (8×8)
An improvement over [my previous answer](https://codegolf.stackexchange.com/a/60922/46220), using a completely different approach:
```
1s=56/8
2?sP7);
3?"?"::
4s=s-+1
5ifsgO2
6?-8^6;
7?sP1):
8
```
Output:
```
?
?
?
?
?
?
?
-262144
```
[Answer]
## Ruby, ~~8x8~~ 7x7
```
print(
(?f+"\
"*6+?\
)*6).!
$><<"\
f"<<!1
;
```
Output:
```
f
f
f
f
f
f
ffalse
```
Previous version, 8x8 with 20 spaces:
```
puts((
"ff"+#
?\s*6+
?\n)*7
);$><<
?\s*2+
?f;p:p
.!
```
Output:
```
ff
ff
ff
ff
ff
ff
ff
ffalse
```
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 4x4 square
Non-competing as the language postdates the challenge:
**Code:**
```
H32
2 C4
:" }
\o/
```
**Outputs:**
```
d
d
d
d
```
[**Try it online!**](https://tio.run/nexus/pushy#@6/gYWzEZaTgbMJlpaRQq8AVk6///z8A)
Because whitespace is irrelevant in Pushy, the code is easily arranged to match the negative of its output. The actual program looks like this:
```
H \ Push char 100, 'd'
32 2C \ Push char 32, a space, and make 2 extra copies
\ We now have the string 'd '
4: \ 4 times do:
" \ Print the string
} \ Cyclically shift it right, once
```
Backslashes begin a comment, so the trailing `\o/` is just there to complete the negative, and look cool.
---
Alternatively, for the same score, we can have the following solutions:
```
Code Output
35; #
3 2j #
2C 4 #
:"} #
K 36 #
33 2 #
Ct4 #
:}" #
```
[Answer]
# Haskell, 10 × 10
```
main=let{
0&c='\32'
!c;n&c=c!
'\32'>>(n
-1)&c;a!b
=putStrLn
$(b<$[1..
10])++[a]
}in(9&'*'
)
```
Defines a helper function `a ! b` that prints a line of the form `bbbbbbbbba`, and a recursive function `n & c` that prints `n` lines of the form `ccccccccc␣` followed by one line of the form `␣␣␣␣␣␣␣␣␣c`.
Uses `<$` (`fmap const`, again) on a range to repeat a character. Note that `<$` is only available without imports since GHC 7.10, which post-dates this challenge. ~~I am not entirely sure if this makes this submission noncompeting.~~
Nothing really exciting with the choice of layout or algorithm here; I didn't have a lot of bytes to spare and it's just fortunate one can get the line breaks to occur around the `putStrLn` the way they did.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 3x3 square
```
3ƛ
S ↳
3↲
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%203%C6%9B%0AS%20%E2%86%B3%0A3%E2%86%B2%20&inputs=&header=&footer=)
[Answer]
## Perl, 6x6 (26 non-spaces)
I spent a whlie looking through these and was sure there would be a Perl solution smaller than 7x7 somehow... A very fun challenge! This solution requires `-E`.
```
say+(
$"x5,
"5$/"
)x5,5
x5,$"
;
```
### Usage:
```
perl -E 'say+(
$"x5,
"5\n"
)x5,5
x5,$"
;'
```
### Output:
```
5
5
5
5
5
55555
```
[Answer]
# CBM BASIC v2.0 (9×9)
```
0dA8,7,6
1dA5,4, 3
2dA2,1 ,0
3rEs: rem
4?sP s)::
5:? "*";:
6p =8---s
7 ?sPp):?
8ifsgO3:
```
Output:
```
*
*
*
*
*
*
*
*
*
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 x 4 (12 non-spaces)
```
4=þ
¢ +⁴
¢+ ⁴
¢ỌY
```
[Try it online!](https://tio.run/##y0rNyan8/1/BxPbwPq5DixS0HzVuAdLaChD64e6eyP//AQ "Jelly – Try It Online")
Output:
```
!
!
!
!
```
This was pretty fun.
### How it works
```
4=þ Link 1 (nilad): Generate an identity matrix of size 4
¢ +⁴ Link 2 (nilad): Add 16 to above
¢+ ⁴ Link 3 (nilad): Add 16 again
¢ỌY Main link (nilad): Convert the above to ASCII chars, and join by newline
```
Easy part: Jelly ignores whitespaces (as long as only one-byte builtins are used).
Hard part: Each line in Jelly is a separate link (or function), so it's not very short to spread a constant statement in multiple lines. Using a string literal is a good candidate, but no idea how to generate the negative.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~7x7~~ 8x8
EDIT: Previous version had incorrect behaviour.
```
main(i)
{ for(;i
<9 ;pri\
ntf ("%\
*d%" "*\
c",i, 1,
9-i,10 )
,i++);}
```
[Try it online!](https://tio.run/##BcE7CoAwDADQPacIhUI/Kdix1KN0kUglg1WKm3j2@B6ng1kVz02GEw8v9mu6KrAWrPeUBuPp6IxtEHZr0IQGbEgIM0FJQnlBDyQx@vqh6g8 "C (gcc) – Try It Online")
[Answer]
# [PHP](https://php.net/), 11 x 11 square
```
for($x=0;#
$x<10;$x++
){echo('|'
.#########
str_repeat
(chr(32),#
10)."\n");
}echo(chr(
32).'----'
.'------')
;
```
Output:
```
|
|
|
|
|
|
|
|
|
|
----------
```
This was a nightmare. I don't think I can fit any smaller.
[Try it online!](https://tio.run/##K8go@G9jXwAkFdLyizRUKmwNrJW5FFQqbAwNrFUqtLW5FDSrU5Mz8jXUa9S5FPSUYYBLobikKL4otSA1sYRLQSM5o0jD2EhTByhuaKCppxSTp6RpzaVQC9YKkuRSAErrqesCAcgcMAPI1OSyVoCD//8B)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 71 bytes
```
for(i=s
='';71 >
++i;s +=
i%9? i%+
8?' ':+1
:[ '\n']
) ;print
(s);;;;
```
[Try it online!](https://tio.run/##DcE7CoAwDADQPafIIlGCg5OfUj2IOogfiGItjQievvrePj2TzkH8nauXZQ3n5Y71jXG7QipWESyRKQtsgVmMIluQpO5QEoaqI6SGC2h6pMHRCBkaH8TdgKlm5hfjBw "JavaScript (SpiderMonkey) – Try It Online")
Why everyone do LU-RD diag?
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 15x15, 112 nonspace
```
+ + + + + + +
+ [ - > + > + +
+ + + + + + +
+ + + < < ] > +
+ > > + > > +
< < [ < . [ - >
> + < < ] > >
[ - < < + + + >
> ] > + + + +
+ + + + + + + +
+ + + + + [ <
] < < < < [ . >
> + + > > + <
< < < < ] > > >
+ ] a a a a a
```
[Try it online!](https://tio.run/##ZY1BCoAwDATveUXuxb6g5COlhyoIIngQfH/sJrQqsqSkyWZnPut2rNeyq3L4iAJnnlhaiwr030OpqcBBZpTxEja5VfQcsmm3CxOm@HqO7Yuj3vlDbz5iqdi1U2LP7/Tk/AcnuC9ch1Rv "brainfuck – Try It Online")
```
++++++++[->+>++++<<]>++>>+>>+<<[ 10 32(00)00 01 ; Old didn't care nonspaces
<.[->>+<<]>>[-<<+++>>]> 10 96 01 00(01) 10 96 16 0(-17)
+++++++++++++++++[<]<<<< (00)10 96 01 00 18 (10)96 16 00 00
[.>>++>>+<<<<<]>>>+] 10 96(02)00 18 10 96(18)00 01
```
[Answer]
# Deadfish~, 10x10 square
```
{(icdcccc
ccccc{dd}
ddc{d}){i
ii}ii}cic
cccccccch
hhhhhhhhh
hhhhhhhhh
hhhhhhhhh
hhhhhhhhh
h
```
Outputs
```
!
!
!
!
!
!
!
!
!
!!!!!!!!!
```
# Explanation
```
{ repeat 10 times
( skip following the first time (if accumulator is 0), so repeat x9
ic increment (will be 32 once this is run , so 33, then print as '!'
dccccccccc decrement (to 32) and print 9 times
{dd}dd decrement to 10 for newline
c{d} print and decrement to 0
) end if
{iii}ii increment accumulator to 32
} end loop
c print as character (' ')
iccccccccc increment and print 9 '!'s
h stop the program, anything after this is junk
```
[Try it online!](https://tio.run/##hcohDoBQDANQv1NUguBQZIWsGrn8s48hpnlpmoryOnnriaMKucnpzfC1J7kMZI@1pwzS6rjm0MIQ438GRtUL "Deadfish~ – Try It Online")
] |
[Question]
[
**[Watch live](https://trichoplax.github.io/formic-functions/) | [Active answers](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest?answertab=active#tab-top) | [Add new answer](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest#footer) | [Chat room](https://chat.stackexchange.com/rooms/62666/formic-functions) | [Source code](https://github.com/trichoplax/formic-functions) | [Leaderboard](https://github.com/trichoplax/formic-functions/blob/master/README.md#leaderboard)**
*New tournaments whenever needed. New players and new updates very welcome.*
[![Queen ant on a dance floor with changing coloured tiles](https://i.stack.imgur.com/7xiOD.gif)](https://i.stack.imgur.com/7xiOD.gif)
Not actual game footage.
Each player starts with one ant - a queen, who collects food. Each piece of food can be held or used to produce a worker. Workers also collect food to be brought back to the queen.
16 players compete in one arena. The winner is the queen holding the most food after she has taken 30,000 turns. The catch is that the ants can only communicate by changing the colors of the arena squares, which may also be changed by rival ants...
# Watching the game
This is a JavaScript competition, which means you can watch the game play out live in your browser by clicking the link below.
### [Click here to watch the game being played live](https://trichoplax.github.io/formic-functions/)
*Many thanks to **[Helka Homba](https://codegolf.stackexchange.com/users/26997/helka-homba)** for the original Stack Snippet King of the Hill contests, **[Red vs. Blue - Pixel Team Battlebots](https://codegolf.stackexchange.com/q/48353/20283)**, and **[Block Building Bot Flocks](https://codegolf.stackexchange.com/q/50690/20283)**, which provided the idea of a web browser hosted KotH and heavily informed the code for this one.*
*Huge thanks also for all the feedback and testing from the wonderful people in the Sandbox and in Chat.*
# Leaderboard
[![Picture of top places of leaderboard](https://i.stack.imgur.com/TFkMu.png)](https://github.com/trichoplax/formic-functions/blob/master/README.md#leaderboard)
*(Click the image to see the full leaderboard and joint places explanation - only a few players are showing here to save space.)*
This leaderboard is based on the players as they were on Sunday 2nd September 2018.
# Screenshots
Some images of how the arena looks towards the end of a game. Click images to view full size.
[![image of the arena](https://i.stack.imgur.com/hho4Gt.png)](https://i.stack.imgur.com/hho4G.png)
[![image of the arena](https://i.stack.imgur.com/i7Zj1t.png)](https://i.stack.imgur.com/i7Zj1.png)
[![image of the arena](https://i.stack.imgur.com/m23aLt.png)](https://i.stack.imgur.com/m23aL.png)
[![image of the arena](https://i.stack.imgur.com/rWTLrt.png)](https://i.stack.imgur.com/rWTLr.png)
[![image of the arena](https://i.stack.imgur.com/CyDeEt.png)](https://i.stack.imgur.com/CyDeE.png)
[![image of the arena](https://i.stack.imgur.com/SWxcyt.png)](https://i.stack.imgur.com/SWxcy.png)
[![image of the arena](https://i.stack.imgur.com/SQ0xet.png)](https://i.stack.imgur.com/SQ0xe.png)
[![image of the arena](https://i.stack.imgur.com/H2KW8t.png)](https://i.stack.imgur.com/H2KW8.png)
[![image of the arena](https://i.stack.imgur.com/yzSEwt.png)](https://i.stack.imgur.com/yzSEw.png)
[![image of the arena](https://i.stack.imgur.com/gidc4t.png)](https://i.stack.imgur.com/gidc4.png)
[![image of the arena](https://i.stack.imgur.com/IOG2Pt.png)](https://i.stack.imgur.com/IOG2P.png)
[![image of the arena](https://i.stack.imgur.com/7aQejt.png)](https://i.stack.imgur.com/7aQej.png)
[![image of the arena](https://i.stack.imgur.com/xp040t.png)](https://i.stack.imgur.com/xp040.png)
[![image of the arena](https://i.stack.imgur.com/e8bCpt.png)](https://i.stack.imgur.com/e8bCp.png)
[![image of the arena](https://i.stack.imgur.com/TxNdHt.png)](https://i.stack.imgur.com/TxNdH.png)
[![image of the arena](https://i.stack.imgur.com/gpDY4t.png)](https://i.stack.imgur.com/gpDY4.png)
To get an idea of what is happening in the arena and how all these patterns form, you can run the game and hover the mouse over the arena to zoom in and see the ants at work. Also see the fascinating explanations in the answers.
# The arena
The arena is a toroidal (edge wrapping) grid of square cells. It has width 2500 and height 1000. All cells start as color 1.
Initially exactly 0.1% of cells will contain food. The 2500 pieces of food will be scattered uniformly randomly. No new food will be introduced during the game.
The queens will be placed randomly on empty cells, with no guarantee that they will not be adjacent to each other (although this is very unlikely).
# Ant abilities
* **Sight:** Each ant sees the 9 cells in its 3 by 3 neighbourhood. It has no knowledge of any other ants outside this neighbourhood. It sees the contents of each of the 9 cells (other ants and food), and also each cell's *color*.
* **No memory:** Each ant makes its decisions based on what it sees - it does not remember what it did in the previous turn and has no way of storing state other than in the colors of the arena cells.
* **No orientation:** An ant does not know where it is or which way it faces - it has no concept of North. The 3 by 3 neighbourhood will be presented to it at a randomly rotated orientation that changes each turn so it cannot even walk in a straight line unless it has colors to guide it. *(Making the same move every turn will result in a random walk rather than a straight line.)*
* **Moving, color marking and producing workers:** See **Output** below.
* **Immortality:** These are highland ants that cannot die. You can confuse rival ants by changing the colors around them, or constrain them from moving by surrounding them with 8 ants of your own, but they cannot be harmed apart from this.
* **Carrying food:** A worker can carry up to 1 piece of food. A queen can carry an arbitrary amount of food.
* **Transferal of food:** If a worker is adjacent to a queen (in any of the 8 directions), food will be automatically transferred in one of the following ways:
+ A laden worker adjacent to its own queen will transfer its food to its queen.
+ An unladen worker adjacent to an enemy queen will steal 1 piece of food, if present.
A worker cannot steal from a worker, and a queen cannot steal from a queen. Also a worker cannot take food from its own queen, and a queen cannot steal from an enemy worker.
*Note that ants take turns sequentially and food transferral occurs at the end of each ant's individual turn and does not take up a turn. It happens regardless of whether a worker moves next to a queen or a queen moves next to a worker, and still happens if both ants involved stand still for their move.*
# Coding
### Provide a function body
Each ant is controlled by an ant function. ***Each turn the player's ant function is called separately for each ant (not just once per player, but once for the queen and once for each worker that player controls).*** Each turn, the ant function will receive its input and return a move for that particular ant.
Post an answer containing a code block showing the body of a JavaScript function, and it will be automatically included in the [controller](https://trichoplax.github.io/formic-functions/) (just refresh the controller page). The name of the player forms the title of the answer, in the form `# PlayerName` (which will be truncated to a maximum of 40 characters in the controller tables).
### No state, no time, no random
A function must not access global variables and must not store state between turns. It may use built in functions that do not involve storing state. For example, the use of `Math.abs()` is fine, but `Date.getTime()` must not be used.
**An ant function may only use a pseudo random number generator that it supplies itself, that does not store state.** For example, it may use the colors/food/ants visible as the seed each turn. `Math.random()` is explicitly forbidden, since like nearly all pseudorandom number generators, it stores state in order to progress to the next number in sequence.
A simple random strategy is still possible due to the random orientation of the input - an ant that always chooses the same direction will perform a random walk rather than a straight line path. See the example answers for simple ways of [using this randomness](https://codegolf.stackexchange.com/a/135103/20283) and [avoiding this randomness](https://codegolf.stackexchange.com/a/135104/20283).
An ant function is permitted to contain further functions within its body. See the [existing answers](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest?answertab=active#tab-top) for examples of how this can be useful.
### Console.log
You can log to the console during testing a new challenger player, but once posted as an answer here the player will have no access to `console.log`. Attempting to use it will result in an error and disqualification until edited. This should help to keep leaderboard tournaments fast, while still allowing debugging code pasted into the new challenger text area.
# Input and output
### Input
The orientation of the input will be chosen at random for each ant and for each turn. The input will be rotated by 0, 90, 180 or 270 degrees, but will never be reflected.
Cells are numbered in English reading order:
```
0 1 2
3 4 5
6 7 8
```
The ant function will receive an array called `view`, containing an object for each of the 9 visible cells. Each object will have the following:
```
color: a number from 1 to 8
food: 0 or 1
ant: null if there is no ant on that cell, or otherwise an ant object
```
If a cell contains an ant, the ant object will have the following:
```
food: 0 or more (maximum 1 for a worker)
type: 1 to 4 for a worker, or 5 for a queen
friend: true or false
```
The ant can determine its own details by looking at the ant in the central cell, `view[4].ant`. For example, `view[4].ant.type` is 5 for a queen, or a number from 1 to 4 for a worker (indicating its type).
### Output
Output is returned as an object representing the action to take. This can have any of the following:
```
cell: a number from 0 to 8 (mandatory)
color: a number from 1 to 8 (optional)
type: a number from 1 to 4 (optional)
```
If `color` and `type` are omitted or zero, then `cell` indicates the cell to move to.
If `color` is non-zero, the indicated cell is set to that color.
If `type` is non-zero, a worker ant of that type is created on the indicated cell. Only a queen can create a new worker, and only if she has food, as this costs one piece of food per worker.
Example outputs:
```
{cell:0}: move to cell 0
{cell:4}: move to cell 4 (that is, do nothing, as 4 is the central cell)
{cell:4, color:8}: set own cell to color 8
{cell:6, type:1}: create a type 1 worker on cell 6
{cell:6, color:1}: set cell 6 to color 1
{cell:6, color:0}: equivalent to just `{cell:6}` - move rather than set color
{cell:6, type:0}: equivalent to just `{cell:6}` - move rather than create worker
{cell:6, color:0, type:0}: move to cell 6 - color 0 and type 0 are ignored
```
Invalid outputs:
```
{cell:9}: cell must be from 0 to 8
{cell:0, color:9}: color must be from 1 to 8
{cell:0, type:5}: type must be from 1 to 4 (cannot create a new queen)
{cell:4, type:1}: cannot create a worker on a non-empty cell
{cell:0, color:1, type:1}: cannot set color and create worker in the same turn
```
An ant moving onto a cell containing food will automatically pick up the piece of food.
# Worker type
Each worker has a *type*, a number from 1 to 4. This has no meaning to the controller, and is for the player to do with as they wish. A queen could produce all her workers as type 1, and give them all the same behaviour, or she could produce several types of workers with different behaviours, perhaps type 1 as foragers and type 2 as guards.
The worker type number is assigned by you when a worker is created, and cannot be changed thereafter. Use it however you see fit.
# Turn order
Ants take turns in a set order. At the start of a game the queens are assigned a random order which does not change for the rest of the game. When a queen creates a worker, that worker is inserted into the turn order at the position before its queen. This means that all other ants belonging to all players will move exactly once before the new worker takes its first turn.
# Limit on number of players
Obviously an unlimited number of players cannot fit into the arena. Since there are now more than 16 answers, each game will feature a randomly chosen 16 of them. The average performance over many games will give a leaderboard featuring all the players, without ever having more than 16 in a single game.
# Time limit per turn
Each time the ant function is called, it should return within 15 milliseconds. Since the time limit may be exceeded due to fluctuations outside the ant function's control, an average will be calculated. If at any point the average is above 15 milliseconds and the total time taken by that particular ant function across all calls so far is more than 10 seconds, the relevant player will be disqualified.
# Disqualification
This means the player will not be eligible to win and their ant function will not be called again during that game. They will also not be included in any further games. If a player is disqualified on the tournament machine during a leaderboard game then it will be excluded from all future leaderboard games until edited.
A player will be disqualified for any of the following for any of its ants (queen or worker):
* Exceeding the time limit as described (averaged over 10 seconds).
* Returning an invalid move as described under Output.
* The cell to move to contains an ant.
* The cell to move to contains food and the ant is already a laden worker.
* The cell to produce a worker on is not empty (contains food or an ant).
* A worker is trying to produce a worker.
It may seem harsh to disqualify for invalid moves, rather than simply interpreting this as no move. However, I believe that enforcing correct implementations will lead to more interesting strategies over time. This is not intended to be an additional challenge, so a clear reason will be displayed when a player is disqualified, with the specific input and output alongside to aid in fixing the code.
# Multiple answers and editing
You may provide multiple answers, provided that they do not team up against the others. Provided each answer is working solely towards its own victory, you are permitted to tailor your strategy to take advantage of weaknesses in specific other strategies, including changing the color of the cells to confuse or manipulate them. Bear in mind that as more answers come in, the likelihood of meeting any particular player in a given game will diminish.
You may also edit your answers whenever you choose. It is up to you whether you post a new answer or edit an existing one. Provided the game is not flooded with many near-identical variations, there should be no problem.
If you make a variation of another person's answer, please remember to give them credit by linking to their answer from yours.
# Scoring
At the end of each game, a player's score is the number of other players who have less food carried by their queen. Food carried by workers is not counted. This score is added to the leaderboard, which is displayed in order of average score per game.
Joint places indicate that the order of players is not yet consistent between 6 subsets of the games played so far. The list of games is split into 6 subsets because this is the minimum number that will give a probability of less than 5% that a given pair of players will be assigned distinct places in the wrong order.
# Chat
To keep the comments section clear here, please use the [dedicated chat room](https://chat.stackexchange.com/rooms/62666/formic-functions) for any questions and discussion. Comments on this post are likely to be cleared after a while, whereas messages in the chat room will be kept permanently.
Just to let you know, I'll be more inclined to upvote answers that include a clear and interesting explanation of how the code works.
[Answer]
# Forensic Ants
*All my answers are sharing the same set of low-level helper functions.
Search for "High-level logic begins here" to see the code specific to this answer.*
```
// == Shared low-level helpers for all solutions ==
var QUEEN = 5;
var WHITE = 1;
var COL_MIN = WHITE;
var COL_LIM = 9;
var CENTRE = 4;
var NOP = {cell: CENTRE};
var DIR_FORWARDS = false;
var DIR_REVERSE = true;
var SIDE_RIGHT = true;
var SIDE_LEFT = false;
function sanity_check(movement) {
var me = view[CENTRE].ant;
if(!movement || movement.cell < 0 || movement.cell > 8) {
return false;
}
if(movement.type) {
if(movement.color) {
return false;
}
if(movement.type < 1 || movement.type > 4) {
return false;
}
if(view[movement.cell].ant || view[movement.cell].food) {
return false;
}
if(me.type !== QUEEN || me.food < 1) {
return false;
}
return true;
}
if(movement.color) {
if(movement.color < COL_MIN || movement.color >= COL_LIM) {
return false;
}
if(view[movement.cell].color === movement.color) {
return false;
}
return true;
}
if(view[movement.cell].ant) {
return false;
}
if(view[movement.cell].food + me.food > 1 && me.type !== QUEEN) {
return false;
}
return true;
}
function as_array(o) {
if(Array.isArray(o)) {
return o;
}
return [o];
}
function best_of(movements) {
var m;
for(var i = 0; i < movements.length; ++ i) {
if(typeof(movements[i]) === 'function') {
m = movements[i]();
} else {
m = movements[i];
}
if(sanity_check(m)) {
return m;
}
}
return null;
}
function play_safe(movement) {
// Avoid disqualification: no-op if moves are invalid
return best_of(as_array(movement)) || NOP;
}
var RAND_SEED = (() => {
var s = 0;
for(var i = 0; i < 9; ++ i) {
s += view[i].color * (i + 1);
s += view[i].ant ? i * i : 0;
s += view[i].food ? i * i * i : 0;
}
return s % 29;
})();
var ROTATIONS = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[2, 5, 8, 1, 4, 7, 0, 3, 6],
];
function try_all(fns, limit, wrapperFn, checkFn) {
var m;
fns = as_array(fns);
for(var i = 0; i < fns.length; ++ i) {
if(typeof(fns[i]) !== 'function') {
if(checkFn(m = fns[i])) {
return m;
}
continue;
}
for(var j = 0; j < limit; ++ j) {
if(checkFn(m = wrapperFn(fns[i], j))) {
return m;
}
}
}
return null;
}
function identify_rotation(testFns) {
// testFns MUST be functions, not constants
return try_all(
testFns,
4,
(fn, r) => fn(ROTATIONS[r]) ? ROTATIONS[r] : null,
(r) => r
);
}
function near(a, b) {
return (
Math.abs(a % 3 - b % 3) < 2 &&
Math.abs(Math.floor(a / 3) - Math.floor(b / 3)) < 2
);
}
function try_all_angles(solverFns) {
return try_all(
solverFns,
4,
(fn, r) => fn(ROTATIONS[r]),
sanity_check
);
}
function try_all_cells(solverFns, skipCentre) {
return try_all(
solverFns,
9,
(fn, i) => ((i === CENTRE && skipCentre) ? null : fn(i)),
sanity_check
);
}
function try_all_cells_near(p, solverFns) {
return try_all(
solverFns,
9,
(fn, i) => ((i !== p && near(p, i)) ? fn(i) : null),
sanity_check
);
}
function ant_type_at(i, friend) {
return (view[i].ant && view[i].ant.friend === friend) ? view[i].ant.type : 0;
}
function friend_at(i) {
return ant_type_at(i, true);
}
function foe_at(i) {
return ant_type_at(i, false);
}
function foe_near(p) {
for(var i = 0; i < 9; ++ i) {
if(foe_at(i) && near(i, p)) {
return true;
}
}
return false;
}
function move_agent(agents) {
var me = view[CENTRE].ant;
var buddies = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)];
}
for(var i = 0; i < agents.length; i += 2) {
if(agents[i] === me.type) {
return agents[i+1](me, buddies);
}
}
return null;
}
function grab_nearby_food() {
return try_all_cells((i) => (view[i].food ? {cell: i} : null), true);
}
function go_anywhere() {
return try_all_cells((i) => ({cell: i}), true);
}
function colours_excluding(cols) {
var r = [];
for(var i = COL_MIN; i < COL_LIM; ++ i) {
if(cols.indexOf(i) === -1) {
r.push(i);
}
}
return r;
}
function generate_band(start, width) {
var r = [];
for(var i = 0; i < width; ++ i) {
r.push(start + i);
}
return r;
}
function colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function(c) {
return colours[(colours.indexOf(c) + 1) % colours.length];
}
};
}
function random_colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function() {
return colours[RAND_SEED % colours.length];
}
};
}
function fast_diagonal(colourBand) {
var m = try_all_angles([
// Avoid nearby checked areas
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[5]].color) &&
colourBand.contains(view[rot[7]].color)
) {
return {cell: rot[0]};
}
},
// Go in a straight diagonal line if possible
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[8]].color)
) {
return {cell: rot[0]};
}
},
// When in doubt, pick randomly but avoid doubling-back
(rot) => (colourBand.contains(view[rot[0]].color) ? null : {cell: rot[0]}),
// Double-back when absolutely necessary
(rot) => ({cell: rot[0]})
]);
// Lay a colour track so that we can avoid doubling-back
// (and mess up our foes as much as possible)
if(!colourBand.contains(view[CENTRE].color)) {
var prevCol = m ? view[8-m.cell].color : WHITE;
return {cell: CENTRE, color: colourBand.next(prevCol)};
}
return m;
}
function follow_edge(obstacleFn, side) {
// Since we don't know which direction we came from, this can cause us to get
// stuck on islands, but the random orientation helps to ensure we don't get
// stuck forever.
var order = ((side === SIDE_LEFT)
? [0, 3, 6, 7, 8, 5, 2, 1, 0]
: [0, 1, 2, 5, 8, 7, 6, 3, 0]
);
return try_all(
[obstacleFn],
order.length - 1,
(fn, i) => (fn(order[i+1]) && !fn(order[i])) ? {cell: order[i]} : null,
sanity_check
);
}
function start_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => ((
!protectedCols.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 2 : 0]].color) &&
!colourBand.contains(view[rot[1]].color)
)
? {cell: rot[right ? 5 : 3], color: colourBand.next(WHITE)}
: null)
]);
}
function lay_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var ahead = rot[right ? 2 : 0];
var behind = rot[right ? 8 : 6];
if(
colourBand.contains(view[behind].color) &&
!protectedCols.contains(view[ahead].color) &&
!colourBand.contains(view[ahead].color) &&
!colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
return {cell: ahead, color: colourBand.next(view[behind].color)};
}
}
]);
}
function follow_dotted_path(colourBand, side, direction) {
var forwards = (direction === DIR_REVERSE) ? 7 : 1;
var right = (side === SIDE_RIGHT);
return try_all_angles([
// Cell on our side? advance
(rot) => {
if(
colourBand.contains(view[rot[right ? 5 : 3]].color) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[0]].color) &&
!colourBand.contains(view[rot[2]].color)
) {
return {cell: rot[forwards]};
}
},
// Cell ahead and behind? advance
(rot) => {
var passedCol = view[rot[right ? 8 : 6]].color;
var nextCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(passedCol) &&
nextCol === colourBand.next(passedCol) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[right ? 0 : 2]].color)
) {
return {cell: rot[forwards]};
}
}
]);
}
function escape_dotted_path(colourBand, side, newColourBand) {
var right = (side === SIDE_RIGHT);
if(!newColourBand) {
newColourBand = colourBand;
}
return try_all_angles([
// Escape from beside the line
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
!colourBand.contains(view[rot[right ? 8 : 6]].color) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[rot[7]].color) ||
colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
// not oriented, or in a corner
return null;
}
return best_of([
{cell: rot[right ? 0 : 2], color: newColourBand.next(approachingCol)},
{cell: rot[right ? 3 : 5]},
{cell: rot[right ? 0 : 2]},
{cell: rot[right ? 6 : 8]},
{cell: rot[right ? 2 : 0]},
{cell: rot[right ? 8 : 6]},
{cell: rot[right ? 5 : 3]}
]);
},
// Escape from inside the line
(rot) => {
if(
!colourBand.contains(view[rot[7]].color) ||
!colourBand.contains(view[rot[1]].color) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
return best_of([
{cell: rot[3]},
{cell: rot[5]},
{cell: rot[0]},
{cell: rot[2]},
{cell: rot[6]},
{cell: rot[8]}
]);
}
]);
}
function latch_to_dotted_path(colourBand, side) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(approachingCol) &&
view[rot[right ? 8 : 6]].color === colourBand.next(approachingCol) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color)
) {
// We're on the wrong side; go inside the line
return {cell: rot[right ? 5 : 3]};
}
},
// Inside the line? pick a side
(rot) => {
var passedCol = view[rot[7]].color;
var approachingCol = view[rot[1]].color;
if(
!colourBand.contains(passedCol) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
if((approachingCol === colourBand.next(passedCol)) === right) {
return best_of([{cell: rot[3]}, {cell: rot[6]}, {cell: rot[0]}]);
} else {
return best_of([{cell: rot[5]}, {cell: rot[2]}, {cell: rot[8]}]);
}
}
]);
}
// == High-level logic begins here ==
var PARTNER = 1;
var SENTINEL = 2;
var COL_DANCING1 = 8;
var COL_DANCING2 = 7;
var SAFE_COLOURS = random_colour_band(colours_excluding([WHITE, COL_DANCING1]));
function pass_time() {
// Wait patiently for the blockage to go away by setting
// random cell colours (unless we're near the sentinel)
for(var i = 0; i < 9; ++ i) {
if(i !== 4 && friend_at(i) === SENTINEL) {
return null;
}
}
return {cell: 0, color: SAFE_COLOURS.next()};
}
function move_sentinel(me, buddies) {
// Our job is to be a sentinel showing when the queen has wrapped around.
// We are created first, so will move first.
// We won't find any food.
if(!buddies[QUEEN] && !buddies[PARTNER]) {
// No ongoing dance; make sure our state is good for when they arrive
return try_all_angles([
{cell: CENTRE, color: WHITE},
(rot) => ({cell: rot[1], color: COL_DANCING2}),
(rot) => ((view[rot[0]].color === COL_DANCING1)
? {cell: rot[0], color: SAFE_COLOURS.next()}
: null)
]);
}
// Dance when queen passes
var danceStage = view[CENTRE].color;
if(danceStage === WHITE) {
// Dance has not begun yet, but queen & partner are nearby
return try_all_angles((rot) => {
if(friend_at(rot[5]) === QUEEN && friend_at(rot[8]) === PARTNER) {
return {cell: CENTRE, color: COL_DANCING1};
}
});
}
if(danceStage === COL_DANCING1) {
if(buddies[PARTNER]) {
return null; // Wait for partner to see us
}
// Partner saw us @8 and moved down, queen followed.
// We must also move down (will end up on a COL_DANCING2)
return try_all_angles((rot) =>
((friend_at(rot[8]) === QUEEN) ? {cell: rot[7]} : null));
}
// Move towards queen counter-clockwise when she's diagonally connected
return try_all_angles((rot) =>
((friend_at(rot[2]) === QUEEN) ? {cell: rot[1]} : null));
}
function move_partner(me, buddies) {
// Our job is to travel with the queen and keep her oriented.
// We are created second, so move after the sentinel.
// Any food we find will immediately go to the queen, since
// we are adjacent at all times.
// Queen will be N of us; orient ourselves
var rot = identify_rotation((rot) => friend_at(rot[1]) === QUEEN);
if(!rot) {
// Queen is lagging or lost;
return null;
}
var danceStage = view[rot[0]].color;
if(
friend_at(rot[0]) === SENTINEL &&
(danceStage === COL_DANCING1 || danceStage === COL_DANCING2)
) {
// Dance down (queen will follow)
return {cell: rot[7]};
}
if(view[rot[0]].ant) {
// Queen is blocked
return null;
}
// Lead queen if both can move
return {cell: rot[3]};
}
function move_queen(me, buddies) {
// Our job is to travel over the entire level collecting food.
// We move last.
if(buddies[PARTNER]) {
// Partner will be S or SW of us; follow if they are ahead
return try_all_angles((rot) =>
(friend_at(rot[6]) === PARTNER) ? {cell: rot[3]} : null);
}
var rot = identify_rotation((rot) => friend_at(rot[3]) === SENTINEL);
if(rot && view[rot[0]].color >= 7) {
// Dance down (follow partner)
return {cell: rot[7]};
}
// We're on our own, or the buddy strategy failed. Start again.
rot = identify_rotation((rot) => friend_at(rot[5]) === SENTINEL);
if(rot && me.food >= 1) {
// Already have a sentinel; just need a partner
return best_of([
{cell: rot[7], type: PARTNER},
{cell: rot[6], type: PARTNER},
]);
} else if(me.food >= 2) {
// Create sentinel first so that we'll know to create the partner next.
// (ensure the sentinel is created on a white cell so that it won't
// think it's dancing)
return try_all_angles(
(rot) => ((view[rot[5]].color === WHITE)
? {cell: rot[5], type: SENTINEL} : null),
(rot) => ({cell: rot[5], color: WHITE})
);
}
// Not able to start yet; fall back to lone behaviour:
// Random-walk until we find or make a buddy
return best_of([
grab_nearby_food,
fast_diagonal.bind(null, SAFE_COLOURS),
go_anywhere
]);
}
return play_safe([move_agent([
PARTNER, move_partner,
SENTINEL, move_sentinel,
QUEEN, move_queen,
]), pass_time]);
```
The forensic ants take a scientific approach to sweeping the grid. After an initial frantic scramble for food, 2 worker ants will be created. The roles are:
## Queen
The queen will team-up with the partner to travel in a straight line at the speed of light. Neither of them will diverge to fetch food; they're just grabbing whatever they stumble over.
## Partner
The partner moves with the queen, keeping her facing in the same direction. Because both ants can move 1 square each turn, they're able to stay in a straight line without wasting time painting the ground.
If the partner ever finds any food, it will immediately go to the queen, since they're adjacent at all times.
## Sentinel
The most important ant. This one stays put until the queen and partner reach it, then tells them to move 2 pixels along, and moves 2 pixels itself. This causes the queen and partner to gradually sweep over the whole board (well, about 30 pixels of it anyway). It only moves when the queen is nearby, so any food it finds will be handed over immediately.
In its spare time, the sentinel's hobbies include painting the ground around it at random to hopefully mess up any competitors.
---
These perform very consistently; between them they can sweep 2 cells each frame, which over 30000 frames means 60000 cells, and with 0.1% containing food, that means a final score of 60, which they pretty consistently achieve.
[Answer]
# Sliding Miners 6.4
```
const DEBUG = false;
const ADD = (a,b) => a + b;
var toReturn;
var me = view[4].ant;
me.me = true; // for basedOn to know
var food = me.food;
var type = me.type;
var isQueen = type == 5;
// raw directions
const UL = 0; const U = 1; const UR = 2;
const L = 3; const C = 4; const R = 5;
const DL = 6; const D = 7; const DR = 8;
// directions from the reference point
const ul = 16; const u = 17; const ur = 18;
const l = 19; const c = 20; const r = 21;
const dl = 22; const d = 23; const dr = 24;
const rp = 16;
function allRots (arr) {
return [arr,
[arr[2], arr[5], arr[8],
arr[1], arr[4], arr[7],
arr[0], arr[3], arr[6]],
[arr[8], arr[7], arr[6],
arr[5], arr[4], arr[3],
arr[2], arr[1], arr[0]],
[arr[6], arr[3], arr[0],
arr[7], arr[4], arr[1],
arr[8], arr[5], arr[2]]];
}
var allVRots = allRots(view);
function rotateCW3([[a,b,c],[d,e,f],[g,h,i]]) {
return [[g,d,a],[h,e,b],[i,f,c]]
}
function on (where, what) {
if (Array.isArray(where)) return where.some(c=>on(c, what));
if (Array.isArray(what)) return what.some(c=>on(where, c));
return basedOn(get(where), what);
}
function find (what) {
return view.findIndex(c=>basedOn(c, what));
}
function findAll (what) {
return view.map((c,i)=>[c,i]).filter(c=>basedOn(c[0], what)).map(c=>c[1]);
}
function count (what) {
return findAll(what).length;
}
function findRel (what) {
return ref(find(what));
}
function findAllRel (what) {
return findAll(what).map(c=>ref(c));
}
function found (what) {
return find(what) != -1;
}
function get (dir) {
if (Array.isArray(dir)) return dir.map(c=>get(c));
return view[raw(dir)];
}
function deq (a, b) {
return a==b || raw(a)==raw(b);
}
// returns a random number from 0 to 4, based on the rotation. Will always have a possibility of being 0
function random4 () {
var scores = allRots(view.map(c=>c.color)).map((c) => {
let cscore = 0;
c.forEach((c) => {
cscore*= 8;
cscore+= c-1;
});
return cscore;
});
var bestscore = -1, bestindex = 1;
scores.forEach((score, index) => {
if (score > bestscore) {
bestscore = score;
bestindex = index;
}
})
return bestindex;
}
function rotate (what, times) {
for (var i = 0; i < times; i++) what = [2,5,8,1,4,7,0,3,6][what];
return what;
}
function raw(dir) {
if (dir&rp) return rotate(dir&~rp, selectedRot);
return dir;
}
function ref(dir) {
if (dir == -1) return -1;
if (dir&rp) return dir;
return rotate(dir, 4-selectedRot)|rp;
}
function move(dir, force) {
if (Array.isArray(dir)) return dir.some(c=>move(c, force));
dir = raw(dir);
return result({cell:dir}, force);
}
function color(dir, col) {
if (Array.isArray(dir)) return dir.some(cdir => !color(cdir, col));
dir = raw(dir);
if (view[dir].color == col) return true;
result({cell:dir, color:Math.abs(col)});
return false;
}
function rcolOf(what) {
return Number.isInteger(what)? what : what.color;
}
function colOf(what) {
return Math.abs(Number.isInteger(what)? what : what.color);
}
function sees(c1,c2) {
c1 = raw(c1);
c2 = raw(c2);
return Math.abs(c1%3-c2%3)<2 && Math.abs(Math.floor(c1/3)-Math.floor(c2/3))<2;
}
function spawn(dir, t) {
if (Array.isArray(t)) return t.some(c=>spawn(dir, c));
if (Array.isArray(dir)) return dir.some(c=>spawn(c, t));
dir = raw(dir);
return result({cell:dir, type:t});
}
// repairs a single cell
function correct(dir) {
dir = raw(dir);
let col = colOf(selectedPt[dir]);
if (col && view[dir].color != col) {
color(dir, col);
return false;
}
return true;
}
// if pattern is repaired, returns true, otherwise fixes one cell
// firstdirs is lowercase (if you do want it to be from the patterns POV)
function repair(firstdirs, onlyThose) {
//log("FD",firstdirs);
var found = [];
view.forEach((v, i) => {
let col = colOf(selectedPt[i]);
if (col && v.color != col) {
found.push(i);
}
});
if (found.length == 0) return true;
if (firstdirs && (firstdirs = firstdirs.map(c=>raw(c))).some(c=>found.includes(c))) {
let dir = firstdirs.find(c=>found.includes(c));
let col = colOf(selectedPt[dir]);
color(dir, col);
return false;
}
if (!onlyThose) {
let dir = found[random4() % found.length];
let col = colOf(selectedPt[dir]);
color(dir, col);
return false;
} else return true;
}
function flatten (arr) {
return arr.reduce((a,b)=>a.concat(b));
}
var selectedHp, selectedVp, selectedPt, selectedRot;
class Pattern {
constructor(pattern, inherit) {
this.pt = pattern;
if (inherit) {
this.vp = inherit.vp;
this.hp = inherit.hp;
this.rot = inherit.rot;
} else {
this.vp = 0;
this.hp = 0;
this.rot = 0;
}
}
rotateClockwise() {
var arr = [];
for (var i = 0; i < this.pt[0].length; i++) {
var sarr = [];
for (var j = this.pt.length-1; j >= 0; j--) {
sarr.push(this.pt[j][i]);
}
arr.push(sarr);
}
//log(arr);
var res = new Pattern(arr, this);
res.rot = (this.rot+1) % 4;
return res;
}
select(x, y, w, h) {
var res = new Pattern(this.pt.slice(y, y+h).map(c=>c.slice(x, x+w)), this);
res.hp+= x;
res.vp+= y;
return res;
}
rots(dir) {
var pts = [];
var pt = new Pattern(this.pt, this);
for (let i = 0; i < this.lengthIn(dir); i++) {
pts.push(pt);
pt = pt.rotate(dir);
}
return pts;
}
map(fn) {
return new Pattern(this.pt.map(ln=>ln.map(fn)), this);
}
lengthIn(dir) {
if (dir == U || dir == D) return this.pt.length;
else if (this.pt.length > 0) return this.pt[0].length;
else return 0;
}
rotate(dir) { // moves the center to that direction, shifting the side
if (dir == R) {
var res = new Pattern(this.pt.map(c=>((h,...t)=>t.concat(h))(...c)), this);
res.hp++;
return res;
}
if (dir == L) {
var res = new Pattern(this.pt.map(a=>a.slice(-1).concat(a.slice(0,-1))), this);
res.hp++;
return res;
}
if (dir == D) {
var res = new Pattern(((h,...t)=>t.concat([h]))(...this.pt), this);
res.vp++;
return res;
}
throw "rotate unimplemented dir!";
}
center(dir) { // moves the center to that direction
if (dir == R) {
var res = new Pattern(this.pt.map(c=>((h,...t)=>t.concat(0))(...c)), this);
res.hp++;
return res;
}
if (dir == L) {
var res = new Pattern(this.pt.map(a=>[0].concat(a.slice(0,-1))), this);
res.hp++;
return res;
}
if (dir == D) {
var res = new Pattern(((h,...t)=>t.concat([new Array(h.length)]))(...this.pt), this);
res.vp++;
return res;
}
throw "center unimplemented dir!";
}
setSize(xs, ys) {
var arr = [];
for (let y = 0; y < ys; y++) {
var ca = [];
for (let x = 0; x < xs; x++) {
ca.push(this.pt[y % this.pt.length][x % this.pt[0].length]);
}
arr.push(ca);
}
return new Pattern(arr, this);
}
static add(pattern, action, scorer, presetRot) {
if (Array.isArray(pattern)) pattern = new Pattern(pattern);
pattern = pattern.setSize(3,3);
var cpt = pattern.setSize(3,3);
var orig = cpt.pt;
for (let i = 0; i < 4; i++) {
cpt = cpt.rotateClockwise();
if (!presetRot || presetRot == cpt.rot) {
cpt.action = action;
cpt.scorer = scorer;
cpt.raw = orig;
cpt.view = allVRots[cpt.rot];
allPatterns.push(cpt);
}
}
}
static choose() {
var maxScore = -1e307;
var nextScore = -1e308;
var maxPt;
allPatterns.forEach((c) => {
// null = easy
// 0 = bad queen
// false = no match
// >0 = score
var falseN = 0;
var corrects = c.raw.reduce((a,b)=>a.concat(b)).map((guess, index) => {
var bo = basedOn(c.view[index], guess, true);
var ant = guess.ant;
if (ant && basedOn(c.view[index], {ant})) bo+= 1;
if (bo === 0) return 0;
if (bo === false) return false;
if (bo && rcolOf(guess) > 0) return bo;
var easy = rcolOf(guess)<=0;
if (easy) {
falseN++;
return null;
}
return bo;
});
var corrstring = corrects.map((chr,i)=>chr>0? (colOf(c.raw[Math.floor(i/3)][i%3])==1? "W" : "#") : chr===null? "-" : " ").join("");
function match(pt) {
return new RegExp(pt.replace(/@/g, "[#-W]").replace(/C/g, "[#-]")).test(corrstring);
}
var score = corrects.reduce(ADD)*9/(9-falseN);
if (match(".?(...)?##.##.*")) {
if (match("(...)?@@@@@@.*|.?@@.@@.@@.?")) score+= foundEnemy? 5 : 3;
else score+= foundEnemy? 3 : 1;
} else if (!foundEnemy) score = Math.min(score/2, 5);
if (c.scorer instanceof Function) score = c.scorer(score, c, corrects, falseN, match);
if (DEBUG && score > -1) log(
"scored", score,
"corr", /*corrects.map(c =>
(c===false?"F":c===null?"N":c===true?"T":c)
)*/corrstring,
"pt", c.raw.map(c=>c.ant? "A"+c.ant.type : c), c.hp, c.vp);
if (score >= maxScore) {
nextScore = maxScore;
maxScore = score;
c.corrstr = corrstring;
maxPt = c;
}
});
var flattened = maxPt.pt.reduce((a,b)=>a.concat(b));
Pattern.hardcorr = flattened.map((guess, index) => rcolOf(guess)<2? 0 : basedOn(view[index], guess)).reduce(ADD);
Pattern.corrstr = maxPt.corrstr;
Pattern.corr = flattened.map((guess, index) => basedOn(view[index], guess)).reduce(ADD);
Pattern.incorr = 9-Pattern.corr;
Pattern.confidence = maxScore-nextScore;
selectedRot = maxPt.rot;
Pattern.action = maxPt.action;
selectedPt = flattened;
selectedHp = maxPt.hp;
Pattern.raw = maxPt.raw;
Pattern.view = maxPt.view;
selectedVp = maxPt.vp;
Pattern.score = maxScore;
if (DEBUG) log("score", maxScore, "confidence", Pattern.confidence, "corr", Pattern.corr, "hardc", Pattern.hardcorr, "pt", maxPt.pt);//, "fn", maxPt.action+""
}
}
var allPatterns = [];
function clear() {
allPatterns = [];
}
function adds(raw, action, scorer, presetRot) { // must get a 3x3 arr
var pt = raw;
var hp = raw.hp;
var vp = raw.vp;
for (let rot = 0; rot < 4; rot++) {
let view = allVRots[rot];
allPatterns.push({pt, action, scorer, rot, hp, vp, view, raw});
if (rot!=4) pt = rotateCW3(pt);
}
}
function refPt(...args) {
clear();
if (Array.isArray(args[0])) {
if (args[0].length != 3) args[0] = args[0].slice(0,3);
if (args[0][0].length != 3) args[0] = args[0].map(c=>c.slice(0,3));
adds(...args);
}
else Pattern.add(...args);
Pattern.choose();
}
/*
is the 2nd param a subset of the 1st param.
guess can be a number (color), or an object ({color:..,ant:..,..})
guess.ant can be "worker", "queen", "enemy", "enemyworker", "enemyqueen" with obvious meanings. Note that "friend" ≠ me
guess.ant.type can be an array, ORing
true - correct!
false - not correct
0 - notqueen doesn't match (aka very bad)
negativesEqual makes this always return true for negative colors, otherwise it treats negatives as regular colors
*/
function basedOn(real, guess, negativesEqual) {
if (Array.isArray(real)) return real.some(c=>basedOn(c, guess, negativesEqual));
if (Number.isInteger(guess)) guess = {color:guess};
if (guess.notqueen && real.ant && real.ant.friend && real.ant.type==5) return 0;
if (guess.not) {
var bo = basedOn(real, guess.not, negativesEqual);
if (bo) return 0;
}
if (guess.color && Math.abs(guess.color) != real.color && !(negativesEqual && guess.color<0)) return false; // 0 handles itself
if (guess.obstacle !== undefined) {
if (guess.obstacle && !real.ant && !(food && real.food && !isQueen)) return false;
if (!guess.obstacle && (real.ant || (food && real.food && !isQueen))) return false;
}
if (guess.badobstacle !== undefined) {
if (guess.badobstacle && !(real.ant && !real.ant.friend) && !(food && real.food && !isQueen)) return false;
if (!guess.badobstacle && ((real.ant && !real.ant.friend) || (food && real.food && !isQueen))) return false;
}
if (guess.ant) {
if (!real.ant) return false;
if (guess.ant == "worker" &&!( real.ant.friend && real.ant.type!=5)) return false;
if (guess.ant == "queen" &&!( real.ant.friend && real.ant.type==5)) return false;
if (guess.ant == "enemyqueen" &&!(!real.ant.friend && real.ant.type==5)) return false;
if (guess.ant == "enemyworker" &&!(!real.ant.friend && real.ant.type!=5)) return false;
if (guess.ant == "friend" && (!real.ant.friend || real.ant.me)) return false;
if (guess.ant == "enemy" && real.ant.friend) return false;
if (Number.isInteger(guess.ant) && real.ant.type != guess.ant) return false;
if (guess.ant.friend !== undefined && guess.ant.friend !== real.ant.friend) return false;
if (guess.ant.type !== undefined && !(Array.isArray(guess.ant.type)? guess.ant.type.some(c=>c == real.ant.type) : guess.ant.type == real.ant.type)) return false;
if (guess.ant.food !== undefined && guess.ant.food !== real.ant.food) return false;
}
if (guess.food !== undefined && guess.food !== real.food) return false;
// log("matched");
return true;
}
function result (action, force) {
if (!force) if (toReturn !== undefined) return 0;
var color = action.color;
var type = action.type;
var cell = action.cell;
if (type < 1 || type > 4) return false;
if (!(cell >= 0 && cell <= 8)) return false;
if (color < 1 || color > 8) return false;
if (!color && ((view[cell].ant && cell != 4) || (isQueen? (view[cell].food && type) : (food && view[cell].food)))) return false; // can't walk onto ant, can't spawn on food, can't move to food with food
if (!isQueen && type) return false;
if (!isQueen && !color && food && view[cell].food) return false;
if (isQueen && !food && type) return false;
if (type && cell==C) return false;
if (color && type) return false;
toReturn = action;
return true;
}
const WH = 1; // white
const C1 = 6; // green HW
const C2 = 5; // red
const C3 = 8; // black
const C4 = 2; // yellow HW
const C5 = 4; // cyan HW
const C6 = 7; // blue HW
const C7 = 3; // purple HW
// C1=GR,C2=BL,C4=YL,C5=DK
const ENEMY = {ant:"enemy"};
const foundEnemy = found(ENEMY);
//-----------------------------------------------------------------------------------------------------------------------------------------------------\\
//----------------------------------------------------------------------- MAIN CODE ---------------------------------------------------------------------\\
//---------------------------------------------------------------------------------------------------------------------------------------------------------\\
function log(...args) {
if (!DEBUG) return;
toLogRaw.push(args);
// for (let i of args) {
// if (i === undefined) i = "undefined";
// var res = "";
// if (typeof i === 'string') res = i;
// else res = JSON.stringify(i);
// toLog+= res + " ";
// }
// toLog+= "\n";
}
if (DEBUG) {
var toLog = "";
var logMyLogs = false;
var toLogRaw = [];
log(type, view.map(c=>c.ant? "A"+c.ant.type : c.color));
}
const Ut = 1;
const Dt = 2;
const Ht = 4;
const Uo = {ant:{type:Ut,friend:true}};
const Do = {ant:{type:Dt,friend:true}};
const Ho = {ant:{type:Ht,friend:true}};
const Mo = {ant:{type:[Ut,Dt],friend:true}};
const Fo = {food:1};
const Qo = {ant:{type:5,friend:true}};
const EQo = {ant:{type:5,friend:false}};
const FRIEND = {ant:"friend"};
const OBSTACLE = {obstacle:true};
const FREE = {obstacle:false};
const BADOBSTACLE = {badobstacle:true};
const STARTINGFOOD = 6;
const LESSENFOOD = 160;
const ENDINGFOOD = 160;
const isMiner = type==Ut || type==Dt;
var friendCount = count(FRIEND);
if (isMiner) {
var Mu = type==Ut? u : d;
var Md = type==Ut? d : u;
var Mur = Mu+1;
var Mul = Mu-1;
var Mdr = Md+1;
var Mdl = Md-1;
}
const foodExt = [C3, C7, WH];
const rawRail = [
[WH,-1,C7,-1], // 43 03 13 23
[C6,WH,WH,-1], // 42 02 12 22
[C4,C1,C2,C2],
[C2,C4,C5,C5],
[C3,C5,C1,C3],
//[C3,C1,C4,C4],
//[C4,C4,C5,C2],
//[C5,C2,C1,C3],
//[C3,C1,C2,C5],
//[C3,C3,C1,C5],
//[C2,C4,C5,C2],
//[C2,C1,C3,C5], // 41 01 11 21
//[C1,C5,C5,C4], // 40 00 10 20
//[C5,C4,C2,C3], // 41 01 11 21
[C6,WH,WH,-1], // 42 02 12 22
[WH,-1,C7,-1] // 43 03 13 23
]
.map((ln,row)=>(row<2||row>4)? ln.map(c=>({not:{ant:{friend:true, type:[Ht, 5]}},color:c})) : ln); // queen can't be in the top & bottom 2 rows
function section(ln, action, scorer) {
if (ln > 0) section(-ln, action, scorer);
var sct = rawRail.slice(ln+2, ln+5);
var parts;
if (Math.abs(ln) != 2) {
parts = [];
for (let i = 0; i < 4; i++) {
var cpt = sct.map(([a,b,c,d])=>[a,b,c]);
cpt.hp = i;
cpt.vp = ln;
parts.push(cpt);
if (i!=4) sct = sct.map(([a,b,c,d])=>[b,c,d,a]);
}
} else {
var o = sct.map(c=>c.slice(0,3));
o.vp = ln;
o.hp = 0;
parts = [o];
}
parts.map(c=>adds(c, action, scorer));
}
function sabotage(where) {
if (on(where, 1)) repair([where], true);
else color(where, 1);
}
section(0, ()=>{
if (isMiner) {
if (on([r,ur,dr], Fo) || on([u,d], Fo) && on([l,ul,dl], Mo)) { // FAKE RAIL
color(on([dr,d],Fo)? [dr,u,ul] : [dr,d,dl], C7);
}
else if ([l,ul,dl].every(c=>on(c,{ant:{}})) && !random4()) move([r,u,d,ur,dr]); // peer pressure
/* AV */ else if (found(EQo)) sabotage(find(EQo));
else if (repair()) {
if (on(r,Mo) && (random4() > 1 || random4() && friendCount > 3)) move([l,Mul,Mu,Mdl,Md]);
if (on([Mu,Mur], ENEMY)) move([R, D, DR]); // move somewhere away from enemy
else if (on(r, Qo) && on([l,ul,dl], {ant:{type:[Ut,Dt],food:1,friend:true}})) move([Mu, Mul, l, Mdl]); // make place for miners with food; Possibly stuck
else if (on(r, Qo)) move([Mu, Mul]); // don't do stupid things around queen
else if (on(l, Qo) && !foundEnemy) move([Mul, Mdl, Mu, Md]); //.. I've done stupid things around queen
else if (on([Mu,Mur], OBSTACLE)) { // up is blocked :/
if (random4()) move(on(Mu, FRIEND)? [Mur, r] : r);
else move([r, Mul, Md, Mul, l, Mdl]);
}
else move([Mu, r, Mur, Md, Mdr]); // move along
}
} else if (isQueen) {
var HM = Pattern.view.map(c=>+basedOn(c, Ho));
var helperRows = [HM.slice(0,3),HM.slice(6,9)].map(c=>c.lastIndexOf(1)).map((c,i) => (c==0 && on(i==0? u : d, OBSTACLE)) ? -1 : c);
var minH = Math.min(helperRows[0],helperRows[1]);
var maxH = Math.max(helperRows[0],helperRows[1]);
if (on(r, FRIEND) && [ur,dr].every(c=>on(c, ENEMY))) move([l,ul,dl]);
if (found(EQo)) { // vampire?
move(random4()%2? [ur,dr] : [dr,ur]);
var eQueenRel = (findRel(EQo)-rp)%3;
if (eQueenRel == 0) move(r,ur,dr);
spawn(Mu, [u,d,r,ur,dr]);
}
if (foundEnemy) // spawn helpers against enemies
if (food && minH == -1 && count(Ho) < 2) {
if (helperRows[0] == -1) spawn([u,ur,ul],Ht);
else spawn([d,dr,dl],Ht);
}
if ([r,ur,dr].every(c=>on(c, ENEMY))) move([ul,dl,l,u,d]); // OH GOD NO WHY
if ((minH == -1 || maxH == 2) && on(r, [ENEMY,Ho]) && Pattern.incorr < 2 && count({ant:{}})-1 != count(Ho))
move(on(ur, ENEMY)? [d,u,dr,ur,ul,dl,l] : [u,d,ur,dr,ul,dl,l]); // initialize transporting around enemy
if ((!random4() && on(l, OBSTACLE) && on([ul, dl], OBSTACLE)) && Pattern.corr >= 7) move(r); // move forward sometimes if left is 2/3s full
else if ([r,ur,dr].every(c=>c.ant && !c.ant.friend)) move([l,ul,dl]);
else if (food && minH > 0 && (
count(Mo) == 0 && selectedHp != 1 && Pattern.corr != 9 && food < LESSENFOOD
||
//Pattern.corr === 9 && [u,d].every(c=>on(c,Ho)) && selectedHp === 1 && food >= LESSENFOOD && food < ENDINGFOOD && random4() < 2
Pattern.corr === 9 && selectedHp == 0 && count(Mo) === 0 && food >= LESSENFOOD && food < ENDINGFOOD && random4() < 2
)) { // spawn miners
if (random4()%2) spawn([u,ul], Ut);
else spawn([d,dl], Dt);
} else if (repair()) {
if (food && minH == -1 && count(Ho) < 2) { // spawn helpers
if (helperRows[0] == -1) spawn([u,ur,ul],Ht);
else spawn([d,dr,dl],Ht);
}
else if (selectedHp != 1 || selectedHp==1 && /*(*/(maxH==2 || minH == -1 && helperRows.includes(2)) && (!random4() || food < LESSENFOOD || found(Mo)) || foundEnemy) move(r); // move forwards
else if (on(ul, Do) && on(dl,Uo) && on(l, {ant:{}})) move(r); // miners are in wrong places
}
} else { // helper
var repaired = repair();
var queenRel = (findRel(Qo)-rp)%3;
var dir = queenRel==0? 0 : 1;
if (repair()) {
if (on(r, EQo) && [u,d,ur,dr].map(c=>on(c, ENEMY)? 1 : 0).reduce(ADD) >= 3) move(c); // protect the queen from the evils ahead
else if (on(r, Qo)) move([u,d,ur,dr,ul,dl,l]);
else move((on([d,dr,dl], Ho)? [u+dir,d+dir] : [d+dir,u+dir]).concat([u+(1-dir), d+(1-dir)]), !random4());
}
}
})
section(1, ()=>{
const A = selectedVp > 0? d : u; // away
const I = selectedVp > 0? u : d; // in
const AR = A+1;
const AL = A-1;
const IR = I+1;
const IL = I-1;
if (isMiner) {
var queenRel = (findRel(Qo)-rp)%3;
if (on([r,IR], Fo)) color([r,IR, I], C7); // FAKE RAIL
else if ([l,IL].every(c=>on(c,{ant:{}})) && !random4()) move([r,IR]); // peer pressure
/* AV */ else if (found(EQo)) sabotage(find(EQo));
else if ((found(EQo) && random4() && Pattern.dist <= 1 && on(find(EQo), 1)) || repair()) {
if (on(I, Qo)) move(l); // what am I doing here?
else if (A == Mu) { // my dir!
if (!food && selectedHp == 0 && (on(r,Ho) && on(IR, Qo) || count(Mo) >= 6)) move(A); // move out!
else if (on(IR,Qo) && on([l,IL], {ant:{type:[Mu,Md],friend:true,food:1}})) move(C); // waiting in line :D
else if (on(IR,Qo)) move(C); // waiting in line :D
else if (random4()) move([r, I, IR]);
else move([r, I, IR, l, IL]);
} else { // not my dir
// TODO fix \\ if (selectedHp == 0 && count(Mo) >= 6 && food) move(A); // fake rail escape
if (random4()) {
move([I, IR, IL, l]);
} else {
move([r, I, IR, IL, l]);
}
}
}
} else if (isQueen) {
if (found(EQo)) { // vampire?
var eQueenRel = (findRel(EQo)-rp)%3;
if (eQueenRel==0) move(r, IR);
spawn(Mu, [r,IR]);
spawn(Md, I);
}
/* AV */ if (food > 70 && (
[IR,IL,I,l,r].every(c=>on(c,ENEMY)) // completely encased
|| on(IR, EQo) && [r,I].every(c=>on(c, ENEMY)) // getting leeched
|| on(I, EQo) && [r,l,IL,IR].map(c=>get(c)).map(c=>c.ant? (c.ant.friend? 1 : -1) : 0).reduce(ADD) < 0 // leeched
)) move([A,AR,AL]); // BAD NEWS COMPLETELY DEAD
if (!random4() || found(EQo) || repair())
move(random4()? [IR,r,I,l] : [IR,r,I]);
} else { // helper
var queenRel = (findRel(Qo)-rp)%3;
/* AV */ if (on(r,Qo) && on([I,IR], EQo)) move([IR,I,l,IL]);
if (on(l, Qo)) { if (!random4() || repair()) move(r) } // queen's transporting
if (on(I, Qo) && on(IR, {ant:"enemyworker"})) { if (!random4() || repair()) move(r) } // queen needs to transport
// what was this? if ([l,IL,I].every(c=>on(c,OBSTACLE)) && (count(ENEMY) > 1 || find(EQo)) && !random4()) move([r,ur]);
if ((selectedVp < 0? /...[#-W]{6}/ : /[#-W]{6}.../).test(Pattern.corrstr) && queenRel == 2 && count(Ho) == 1) move(r); // move forward without repairing
if (!random4() && queenRel == 1 && selectedHp == 1 && on(AL, {ant:{}})) move(r); // something is out; don't repair
else if (repair([r,l,A,AR,AL])) {
if (on(r, ENEMY) && on(I, Qo) && [l,IL].every(c=>on(c,FRIEND))) move(IR); // protect from vampire
if (on(r, ENEMY) && on(IL, Qo) && [l,IR].every(c=>on(c,FRIEND))) move(I);
if (on(r, ENEMY) && !get(r).ant.food && on(I, Qo)) move(IR);
if (queenRel == 1 && selectedHp == 1 && on(AL, {ant:{}})) move(r); // something is out
else if (on([l,r], Ho)) { // move to the other side
if (found(Qo)) move([I]); // TODO integrate ,IL,IR
else move([l,r]);
}
else if (queenRel == 2) move(r); // move forward
}
}
}, (pscore, pt, corrects, falseN, match) => {
if (match(".?(...)?@@.@@.*") && !foundEnemy) {
if (!match(pt.vp>0? ".?@@.@@.*" : ".?...@@.@@.*")) pscore/=2;
}
return pscore;
})
if (isMiner) {
section(2, () => {
const A = selectedVp > 0? d : u; // away
const I = selectedVp > 0? u : d; // in
if (on(A,OBSTACLE)) move(I);
else if (repair()) move(food? I: Mu);
}, (pscore, pt, corrects, falseN, match) => match(pt.vp>0? "@@@.@...." : "....@.@@@")? match("@@@@@@@@@")? 100 : ((pt.vp>0) == (type==Dt)? 13 : 10) : 0);
if (type==Dt) foodExt.reverse();
if (!found(Ho) && !found(Qo)) {
var lns = [rawRail[0], rawRail[1]].map(c=>c.slice(0,3));
[[lns[0],lns[1],lns[0]], [lns[1],lns[0],lns[1]]].map(c=>{
adds(c, () => {
var onL;
if (!food && ((onL = on(l, Fo)) || on(r, Fo))) {
var foodpt = Pattern.raw.map((ln, i) => [ln[0], foodExt[i], ln[2]]);
refPt(foodpt,undefined,undefined,selectedRot);
if (repair()) move(onL? l : r);
}
else if (repair([l,r,ul,ur,dl,dr], on([Mul, Mur, Mdl, Mdr, l, r], {ant:{friend:true,type:[Ut,Dt],food:1}}) || on([Mu, Md], Mo))) {
move(food? [Md, Mu] : [Mu, Md]);
}
}, (pscore, pt, corrects, falseN, match) => {
var score = 0;
var dMatch = match("...@.@@@@");
var uMatch = match("@.@@.@...");
if ((type==Ut ^ food) && dMatch) score = 15;
else if ((type==Dt ^ food) && uMatch) score = 15;
else if (uMatch || dMatch) score = 6;
if ([0,2,3,5,6,8].some(c=>basedOn(pt.view[c], FRIEND) && !pt.view[c].ant.food)) score = 0;
return score;
});
if (food) {
var extp = c.map((ln, i) => [ln[0], foodExt[i], ln[2]]);
[extp.map(([a,b,c])=>[0,a,b]), extp.map(([a,b,c])=>[b,c,0])].forEach((pt,i) => adds(pt, () => {
move(i? l : r);
}, (pscore, pt, corrects, falseN, match) => match("@@@@@@@@@")? 100 : 0));
}
});
}
}
Pattern.choose();
var confident = ((Pattern.confidence >= 1 && (Pattern.score > 4 || Pattern.corr >= 4)) || (Pattern.score >= 9 && Pattern.confidence > 0.05)); // && (selectedHp != || !found(Qo));
var failAction = () => {
if (foundEnemy) {
log(view);
log("dead around enemy :/");
logMyLogs = true;
}
if (isQueen) {
if (found(EQo)) {
move([8-(find(EQo)-rp) + rp]);
move(random4()%2? U : UR);
}
if (foundEnemy) move(random4()%2? U : UR);
} else {
// if (!found(Qo) && found(Fo)) move(find(Fo));
var enemyPlace = find(ENEMY);
if (enemyPlace !== -1) color(enemyPlace, get(enemyPlace).color==1? C3 : WH);
}
}
if (!confident) Pattern.action = failAction;
if (isMiner) {
if ((Pattern.hardcorr >= 4 || Pattern.score > 5) && confident) Pattern.action();
else {
failAction();
}
} else if (isQueen) {
if ((Pattern.hardcorr >= 6 || food > STARTINGFOOD+2 || friendCount>1 || found(Mo) || Pattern.score > 6 || (false)) && confident) Pattern.action();
else if (food >= STARTINGFOOD && friendCount == 1) {
clear();
Pattern.add([[1,{ant:Ho.ant,color:1},1],
[1,1,1],
[1,1,1]], ()=>spawn([ur,ul],Ht));
Pattern.add([[1,1,{ant:Ho.ant,color:1}],
[1,1,1],
[1,1,1]], ()=>spawn([ur,u],Ht));
Pattern.choose();
if (repair()) Pattern.action();
} else if (food == 0 && friendCount == 0) { // diagonal search
if (found(Fo)) {
move(find(Fo));
} else {
clear();
Pattern.add([[WH,WH,WH],
[WH,C1,WH],
[C1,WH,WH]], ()=>move(ur));
Pattern.add([[WH,WH,WH],
[WH,WH,WH],
[C1,WH,WH]], ()=>color(C, C1));
Pattern.add([[WH,WH,WH],[WH,WH,WH],[WH,WH,WH]], ()=>color(DL, C1));
Pattern.choose();
if (Pattern.corr == 9) Pattern.action();
else move(random4()? [DL,UL,DR,UL] : [D,L,U,R]);
}
} else if (food == 1 && friendCount == 0) spawn([U,L,D,R,UL,DL,UR,DR], Ht);
else if (friendCount == 1) lightSpeed();
else if (friendCount > 0) {
var pt = new Pattern(rawRail).select(0,2,4,3).rotate(L).rotate(L).pt;
pt[1][2] = {color:pt[1][2], ant:{type:Ht, friend:true}};
refPt(pt);
repair([c,u,d,ur,dr]);
} // TODO wtf to do after this
else Pattern.action(); // eh fuck it
} else if (type == Ht) {
if (confident && (Pattern.score >= 4 || Pattern.hardcorr >= 5 || friendCount>1)) Pattern.action();
else if (found(Qo)) lightSpeed();
else if (Pattern.hardcorr >= 3 && confident) repair();
}
function lightSpeed() {
var other = find(isQueen? Ho : Qo);
var orth = other%2;
if (isQueen || (view[other].ant.food < STARTINGFOOD && count(Ho) == 1)) { // LS
if (orth && found(Fo)) { // grab easy food
var fp = find(Fo);
if (sees(other, fp)) move(fp);
else {
refPt([[0,FRIEND,0],
[0,0,0],
[0,0,0]]);
move(l);
}
}
clear();
// Pattern.when(U,find(FRIEND), ()=>isQueen? move(ul) : move(ur)); when I'm not lazy imma make this a replacement of the below
Pattern.add([[0,FRIEND,0],
[0,0,0],
[0,0,0]], ()=>isQueen? move(ul) : move(ur));
Pattern.add([[0,0,FRIEND],
[0,0,0],
[0,0,0]], ()=>move(u));
Pattern.choose();
Pattern.action();
}
}
if (DEBUG) log("END", type, view.map(c=>c.ant? "A"+c.ant.type : c.color));
if (DEBUG && logMyLogs) {
//for (let i = 0; i < toLog.length; i+=800)
// console.log(toLog.substring(i,i+800));
for (let i of toLogRaw) console.log(...i);
}
if (toReturn) return toReturn;
else return {cell:4};
```
Previously this was Miners on a Rail (see the revision history), but has been changed to Sliding Miners as it performs better and MoaR would just get in the way of its success if this were an another entry.
[Answer]
# Glider
[![Glider in action](https://i.stack.imgur.com/BnHuW.gif)](https://i.stack.imgur.com/BnHuW.gif)[![Glider turning left](https://i.stack.imgur.com/kQScT.gif)](https://i.stack.imgur.com/kQScT.gif)[![Glider turning right](https://i.stack.imgur.com/EPUUm.gif)](https://i.stack.imgur.com/EPUUm.gif)
```
//console.log(JSON.stringify(view))
var TRAIL = 6;
var SPAWN = 3;
var IDLE = 4;
var FOOD_THRESHOLD = 150;
var SPAWN_MIN = 3;
var HIGHWAY_COLORS = [7,6,4,2,3];
var HIGHWAY_THRESHOLD = 70;
var ret = {cell:4};
if(isOnHighway()) {
var cont = true;
//== Make best guess to if in a glider formation ==//
if(view[4].ant.type == 5) {
if((findWorker(1) >= 0 && findWorker(4) >= 0) || view[4].ant.food < HIGHWAY_THRESHOLD) {
cont = false;
}
}
else if(view[4].ant.type == 4) {
if(findWorker(1) >= 0 && findWorker(5) >= 0) {
cont = false;
}
}
else if(view[4].ant.type == 3) {
if(findWorker(2) >= 0 && findWorker(5) >= 0) {
cont = false;
}
}
else if(view[4].ant.type == 2) {
if(findWorker(5) < 0) {
var pos3 = findWorker(3);
if(pos3 >= 0 && view[pos3].ant.food == 0) {
cont = false;
}
}
else if(findWorker(3) >= 0 || (findWorker(1) >= 0 && view[findWorker(5)].color == SPAWN))
cont = false;
}
else if(view[4].ant.type == 1) {
if(findWorker(5) < 0) {
var pos4 = findWorker(4);
if(pos4 >= 0 && view[pos4].ant.food == 0) {
cont = false;
}
}
else if(!isHighwayCenter())
cont = false;
}
if(findWorker(5) >= 0) {
for(var i=0;i<9;i++) {
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.type == 5) {
if(view[i].ant.food > 10 || view[i].ant.food == 0)
cont = true;
else
cont = false;
}
}
}
//== End guesswork ==//
if(cont) {
ret = highwayRobbery();
if(view[4].ant.type == 1) {
//try to repair
var curIndex = HIGHWAY_COLORS.indexOf(view[4].color);
var prvCol = HIGHWAY_COLORS[(curIndex+1)%HIGHWAY_COLORS.length];
var nxtCol1 = HIGHWAY_COLORS[(curIndex+HIGHWAY_COLORS.length-1)%HIGHWAY_COLORS.length];
var nxtCol2 = HIGHWAY_COLORS[(curIndex+HIGHWAY_COLORS.length-2)%HIGHWAY_COLORS.length];
var nxtCol3 = HIGHWAY_COLORS[(curIndex+HIGHWAY_COLORS.length-3)%HIGHWAY_COLORS.length];
var prevAt = -1;
for(var i=0;i<9;i++) {
if(i%2 == 1 && view[i].color == prvCol && view[deRotate(i,1)].color == nxtCol1 && view[deRotate(i,-1)].color == nxtCol1) prevAt = i;
}
if(prevAt >= 0) {
// yep, brute force it. Because I'm lazy.
var goNxt = 8-prevAt;
if(view[deRotate(goNxt,1)].color == nxtCol3 && view[deRotate(goNxt,-1)].color == prvCol) ret = {cell:goNxt};
else if(view[deRotate(goNxt,1)].color == prvCol && view[deRotate(goNxt,-1)].color == nxtCol3) ret = {cell:goNxt};
else if(view[goNxt].color != nxtCol1) ret = {cell:goNxt,color:nxtCol1};
else if(view[deRotate(goNxt,2)].color != nxtCol2) ret = {cell:deRotate(goNxt,2),color:nxtCol2};
else if(view[deRotate(goNxt,-2)].color != nxtCol2) ret = {cell:deRotate(goNxt,-2),color:nxtCol2};
else if(view[deRotate(goNxt,1)].color != nxtCol3) ret = {cell:deRotate(goNxt,1),color:nxtCol3};
else if(view[deRotate(goNxt,-1)].color != nxtCol3) ret = {cell:deRotate(goNxt,-1),color:nxtCol3};
else ret = {cell:goNxt};
ret = sanityCheck(ret);
return ret;
}
}
if(view[4].ant.type == 5 && isHighwayCenter()) {
if(ret.cell >= 0) {
ret = {cell:8-ret.cell};
if(view[4].color == SPAWN && (view[4].ant.food > 90 || view[4].ant.food % 7 == 0) && getHighestWorker() == 0 && (view[4].ant.food < 140 || view[4].ant.food % 9 == 0) && view[0].color == 2 && view[4].ant.food > 50 && view[4].ant.food < 200) {
//fine
if(view[4].ant.food % 10 < 5)
ret = {cell:deRotate(ret.cell,3),type:3};
}
if(view[ret.cell].ant != null && !view[ret.cell].ant.friend && view[ret.cell].ant.food == 0 && view[4].ant.food > 0) {
if(view[deRotate(ret.cell,1)].ant == null)
ret = {cell:deRotate(ret.cell,1),type:3};
if(view[deRotate(ret.cell,-1)].ant == null)
ret = {cell:deRotate(ret.cell,1),type:3};
}
}
for(var i=0;i<9;i++) {
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.type == 5) {
ret = {cell:8-i};
}
}
}
if(ret.cell >= 0) {
for(var i=0;i<9;i++) {
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.type == 5) {
var rr = basicHighwayMove();
if(rr.cell >= 0 && view[4].ant.type != 5)
ret = {cell:deRotate(rr.cell,-2)};
}
}
if(view[ret.cell].ant != null) {
var n = HIGHWAY_COLORS.indexOf(view[4].color) + 1;
var nextMove = HIGHWAY_COLORS[n % HIGHWAY_COLORS.length];
for(var i=0;i<9;i++) {
if(view[i].color == nextMove) {
if(view[i].ant == null) {
ret = {cell:i};
break;
}
}
}
if(view[4].ant.type == 5) ret = {cell:8-ret.cell};
}
}
if(view[4].ant.type == 5) {
var foodedEnemy = false;
for(var i=0;i<9;i++) {
if(getNumWorkers(3) >= 2) break;
if(i != 4 && view[i].ant != null && view[i].ant.type == 5 && view[i].ant.food > 25) {
if(view[deRotate(i,1)].ant == null) {
ret = {cell:deRotate(i,1),type:3};
}
else if(view[deRotate(i,-1)].ant == null) {
ret = {cell:deRotate(i,-1),type:3};
}
else if(i%2 == 1 && view[deRotate(i,2)].ant == null) {
ret = {cell:deRotate(i,2),type:3};
}
else if(i%2 == 1 && view[deRotate(i,-2)].ant == null) {
ret = {cell:deRotate(i,-2),type:3};
}
}
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.type == 3 && view[8-i].ant == null) {
if(i == ret.cell) {
ret = {cell:deRotate(i,1)}
}
else {
return {cell:8-i};
}
}
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.food == 0) {
foodedEnemy = true;
}
}
}
var numAnts = 0;
for(var i=0;i<9;i++) {
if(view[i].ant != null)
numAnts++;
}
if(numAnts > 2 && sanityCheck(ret).cell == 4) {
ret = {cell:findOpenSpace(0,1)};
}
if(view[4].ant.type == 3) {
if(getNumWorkers(5) > 0) {
for(var i=0;i<9;i++) {
if(view[i].ant != null && !view[i].ant.friend && view[i].ant.type == 5) {
ret = {cell:4};
}
}
}
}
if(view[4].ant.type == 4 && getNumWorkers(1) && isHighwayCenter()) {
var workerPos = findWorker(1);
for(var i=0;i<9;i++) {
if(!areAdjacent(i,workerPos)) ret = {cell:i};
}
}
if(ret.cell == -1) {
if(isHighwayCenter()) {
for(var i=0;i<9;i++) {
var p1 = deRotate(i,3);
var p2 = deRotate(i,-3);
if(view[i].color == view[p1].color && view[i].color == view[p2].color) {
ret = {cell:8-i};
}
}
if(view[4].ant.type == 1 || view[4].ant.type == 5) {
ret = {cell:8-ret.cell};
}
}
}
if(ret.cell >= 0)
return sanityCheck(ret);
}
}
switch(view[4].ant.type) {
case 5:
ret = doQueen();
break;
case 1:
case 2:
ret = doSweep();
break;
case 3:
case 4:
ret = doGuide();
break;
default:
break;
}
//basic sanity check
ret = sanityCheck(ret);
return ret;
function sanityCheck(ret) {
if(!ret || ret.cell < 0 || ret.cell > 8) {
return {cell:4};
}
if(ret.color) {
return ret;
}
if((ret.cell != 4 && view[ret.cell].ant != null) || (view[ret.cell].food > 0 && (view[4].ant.food > 0 && view[4].ant.type < 5))) {
return {cell:4};
}
if(ret.type && (view[ret.cell].ant != null || view[ret.cell].food > 0 || view[4].ant.food == 0 || view[4].ant.type < 5)) {
return {cell:4};
}
return ret;
}
function doQueen() {
if((view[4].ant.food == SPAWN_MIN || (view[4].ant.food >= SPAWN_MIN && view[4].ant.food < FOOD_THRESHOLD && (view[4].ant.food % 3 == 1 || isOnHighway()))) && getHighestWorker() <= 1 ) {
//prep for first ant
var s0 = view[0].ant;
var s1 = view[1].ant;
var s2 = view[2].ant;
var s3 = view[3].ant;
var s5 = view[5].ant;
var s6 = view[6].ant;
var s7 = view[7].ant;
var s8 = view[8].ant;
var nullCount = 0 + (s0 == null?1:0) + (s1 == null?1:0) + (s2 == null?1:0) + (s3 == null?1:0) + (s5 == null?1:0) + (s6 == null?1:0) + (s7 == null?1:0) + (s8 == null?1:0);
var nullCount2 = 0 + (s0 == null || s0.friend?1:0) + (s1 == null || s1.friend?1:0) + (s2 == null || s2.friend?1:0) + (s3 == null || s3.friend?1:0) + (s5 == null || s5.friend?1:0) + (s6 == null || s6.friend?1:0) + (s7 == null || s7.friend?1:0) + (s8 == null || s8.friend?1:0);
if(nullCount >= 7 && nullCount2 >= 8 && view[1].food == 0 && view[3].food == 0 && view[5].food == 0 && view[7].food == 0) {
var high = getHighestWorker();
if (high <= 1 && view[4].color != SPAWN && !isOnHighway()) {
// 50% chance of delaying the respawn by 1 additional move away from where we exploded
// reduces the chance of a second, immediate explosion
var pos1 = findWorker(1);
if(findFirstTrail() < 2 && view[4].ant.food > SPAWN_MIN+1 && pos1 < 0) return foreverAlone();
if(pos1 >= 0) {
var space = deRotate(pos1,2);
if(view[space].ant != null) return {cell:findOpenSpace(0,1)};
}
return {cell:4,color:SPAWN};
}
//spawn first ant
else if(view[4].color == SPAWN) {
var pos1 = findWorker(1);
if(pos1 < 0) {
pos1 = findFirstTrail();
if(pos1 % 2 == 0) pos1 = deRotate(pos1,1);
else pos1 = deRotate(pos1,4);
}
var space = findOpenSpace(pos1,2);
var high = getHighestWorker();
if(space < 0) return {cell:4,color:TRAIL}
if(high == 0) { //no workers
return {cell:space,type:1};
}
else if(high < 4) { //1 worker of type:high
return {cell:space,type:high+1};
}
else { //1 worker of type 4
//we have all workers, skip!
}
}
}
else {
return foreverAlone();
}
}
else if(view[4].ant.food == 1 && getHighestWorker() == 0 ) {
var space = findOpenSpace(1,2);
return {cell:space,type:1};
}
else if(view[4].ant.food >= 1 && getHighestWorker() < 4 && findWorker(1) >= 0) {
//spawn remaining ants
if(view[4].color == SPAWN && !isHighwayCenter()) {
var pos1 = findWorker(getHighestWorker());
var space = deRotate(pos1,2);
var high = getHighestWorker();
if(space < 0 || view[space].ant != null) return {cell:findOpenSpace(0,1)};
if(high == 0) { //no workers
return {cell:space,type:1};
}
else if(high < 4) { //1 worker of type:high
return {cell:space,type:high+1};
}
else { //1 worker of type 4
//we have all workers, skip!
}
}
}
if(view[4].color == SPAWN && getNumWorkers(3) == 1 && getNumWorkers(4) == 1) {
var one = getNumWorkers(1);
var two = getNumWorkers(2);
if((one ^ two) == 1 && (findWorker(1) % 2 == 0 || findWorker(2) % 2 == 0))
return {cell:4,color:1};
}
if(getNumWorkers(1) == 0 && getNumWorkers(2) == 0) {
if(getNumWorkers(4) == 1 && getNumWorkers(3) == 0) {
var pos4 = findWorker(4);
if(view[deRotate(pos4,1)].ant == null && view[deRotate(pos4,2)].ant == null && findWorker(4) % 2 == 1) {
//finish rotate with only one glider arm
return {cell:4};
}
}
return foreverAlone();
}
else if(getNumWorkers(1) >= 1 && getNumWorkers(2) >= 1 && getNumWorkers(3) >= 1 && getNumWorkers(4) >= 1) {
if(view[4].color != 2 && findWorker(1)%2 == 1 && findWorker(2)%2 == 1) {
return {cell:4,color:TRAIL};
}
//move diagonally
var pos = findWorker(4);
pos = deRotate(pos,1);
var checkpos = view[deRotate(pos,4)];
if(checkpos.ant != null && checkpos.ant.friend) {
if(checkpos.ant.type == 2)
return {cell:4};
if(checkpos.ant.type == 1)
return {cell:4};
}
if(view[pos].ant) return {cell:4,color:1};
return {cell:pos};
}
else {
var pos = findWorker(4);
if(pos < 0) {
//if gliding along with only a buddy
pos = findWorker(1);
if(pos >= 0 && view[deRotate(pos,2)].food > 0 && view[deRotate(pos,1)].food == 0) {
return {cell:4};
}
}
if(pos < 0) {
var s1 = view[1].ant;
var s3 = view[3].ant;
var s5 = view[5].ant;
var s7 = view[7].ant;
//return {cell:999}
if(s1 == null) {
if(s3 == null) {
return {cell:0};
}
if(s5 == null) {
return {cell:2};
}
}
if(s7 == null) {
if(s3 == null) {
return {cell:6};
}
if(s5 == null) {
return {cell:8};
}
}
return {cell:4};
}
pos = deRotate(pos,1);
var checkpos1 = view[pos];
for(var i=0;i<9;i++) {
if(i != 4 && view[i].ant != null && view[i].ant.type == 5 && view[i].ant.food > 2) {
if(i%2==0) {
if(view[deRotate(i,1)].ant == null) return {cell:deRotate(i,1),type:3};
if(view[deRotate(i,-1)].ant == null) return {cell:deRotate(i,-1),type:3};
}
else {
if(view[deRotate(i,1)].ant == null) return {cell:deRotate(i,1),type:3};
if(view[deRotate(i,-1)].ant == null) return {cell:deRotate(i,-1),type:3};
if(view[deRotate(i,2)].ant == null) return {cell:deRotate(i,2),type:3};
if(view[deRotate(i,-2)].ant == null) return {cell:deRotate(i,-2),type:3};
}
return {cell:4};
}
}
if(checkpos1.ant != null && view[deRotate(pos,1)].ant != null && !view[deRotate(pos,1)].ant.friend) {
return foreverAlone();
}
var checkpos2 = view[deRotate(pos,4)];
var checkpos3 = view[deRotate(checkpos,1)];
if(checkpos1.ant != null && checkpos1.ant.friend && checkpos1.ant.type == 1 && checkpos2.ant != null && checkpos2.ant.friend && checkpos2.ant.type == 2 && checkpos3.ant != null && checkpos3.ant.friend && checkpos3.ant.type == 3) {
//move out of spawn orientation
return {cell:4};
}
if(view[pos].ant != null) {
if(checkpos2.ant == null && checkpos1.ant == null) {
return {cell:8-pos};
}
if(!view[pos].ant.friend) {
return foreverAlone();
}
if(view[4].color == TRAIL) return foreverAlone();
return {cell:4,color:TRAIL};
}
if(8 - findWorker(3) == findWorker(4)) {
//finish rotate to the right
return {cell:4};
}
if((view[deRotate(pos,1)].food > 0 || view[deRotate(pos,2)].food > 0) && view[deRotate(pos,1)].ant == null && view[4].color != TRAIL) {
if(findWorker(1) < 0 || view[deRotate(findWorker(1),1)].food == 0) {
return {cell:4};
}
}
return {cell:pos};
}
return {cell:100+view[4].ant.type}; //oh god
}
//guides sit next to the queen
function doGuide() {
var queenPos = findWorker(5);
var ty = view[4].ant.type==3?2:1;
var dir = view[4].ant.type==3?1:-1;
if(queenPos >= 0 && queenPos%2 == 1 && view[queenPos].color == SPAWN) {
if(view[deRotate(queenPos,dir*2)].ant == null) {
return {cell:4};
}
}
if(queenPos < 0 || findWorker(ty) < 0) {
if(findWorker(ty) >= 0 && view[0].color != IDLE) return {cell:0,color:IDLE}
return firebreak();
}
var checkpos = view[deRotate(queenPos,-2*dir)];
if(view[4].ant.type==4 && checkpos.ant != null && checkpos.ant.friend && checkpos.ant.type == 1) {
//attempt rotate
return {cell:deRotate(queenPos,-dir)};
}
checkpos = view[deRotate(queenPos,4)];
if(checkpos.ant != null && checkpos.ant.friend && checkpos.ant.type == ty) {
//attempt rotate
if(getNumWorkers(ty) == 1) {
return {cell:4};
}
}
var pos = deRotate(queenPos,dir);
if(pos >= 0 && view[4].ant.type==3 && findWorker(4) < 0) {
//wait for rotate
if(view[4].color == TRAIL) {
return {cell:4};
}
}
if(pos >= 0 && findWorker(2) >= 0 && view[deRotate(findWorker(2),1)].ant != null) {
//rotate
return {cell:4,color:TRAIL};
}
if(pos < 0) pos = 4;
else if(view[pos].ant != null) return {cell:deRotate(queenPos,4)};
if(pos == 4 && view[queenPos].color == TRAIL) return {cell:queenPos,color:1};
return {cell:pos};
}
//sweepers sit next to guides
function doSweep() {
var queenPos = findWorker(5);
var followType = view[4].ant.type==1?4:3;
var pos = findWorker(followType);
if(pos % 2 == 0 && getNumWorkers(followType) > 1) {
//if there's more than one worker #4, we want to use the best one
for(var i=pos+1;i<9;i++) {
if(i != 4 && view[i].ant != null) {
if(view[i].ant.friend && view[i].ant.type == followType) {
pos = i;
break;
}
}
}
}
if(queenPos >= 0 && queenPos%2 == 1 && view[queenPos].color == SPAWN) {
var p = findWorker(view[4].ant.type);
if(p >= 0 && (deRotate(p,1) == queenPos || deRotate(p,-1) == queenPos)) {
return {cell:8-queenPos};
}
return {cell:4};
}
if(queenPos >= 0 && pos < 0) {
//if Worker #1 is the only ant besides the queen:
//TODO
//good
if(view[queenPos].ant.food <= SPAWN_MIN || !(view[queenPos].ant.food < FOOD_THRESHOLD && view[queenPos].ant.food % 3 == 1 && !isOnHighway())) {
var go = deRotate(queenPos,-1);
if((view[deRotate(queenPos,-2)].food > 0 || view[deRotate(queenPos,-3)].food > 0 || (queenPos %2 == 1 && view[deRotate(queenPos,-3)].food > 0)) && view[go].food == 0) {
go = deRotate(queenPos,2);
//return {cell:4};
}
return {cell:go};
}
else if(view[queenPos].ant.food < FOOD_THRESHOLD && view[queenPos].ant.food % 3 == 1) {
return {cell:4};
}
}
if(queenPos >= 0) {
var dir = view[4].ant.type==1?1:-1;
//var checkpos = view[deRotate(pos,-dir)];
var moveTo = deRotate(pos,dir);
if(moveTo >= 0 && view[moveTo].ant != null && view[moveTo].ant.friend && view[moveTo].ant.type == 5) {
moveTo = deRotate(pos,-dir);
}
if(view[4].ant.type == 2 && findWorker(1) < 0 && view[queenPos].color != TRAIL) {
moveTo = 4;
}
return {cell:moveTo};
}
else {
if(pos < 0) return {cell:4}; //firebreak();
var dir = view[4].ant.type==1?-1:1;
var moveTo = deRotate(pos,dir);
if(view[4].ant.food > 0 && view[moveTo].food > 0) {
//have food, attempt to give to queen
moveTo = deRotate(pos,-dir);
}
if(view[4].ant.type==1 && pos >= 0 && (view[deRotate(pos,dir*2)].food > 0 || view[deRotate(pos,dir*3)].food > 0)) {
//attempt rotate
moveTo = deRotate(pos,-dir);
}
if(view[4].ant.type==2 && pos >= 0 && (view[deRotate(pos,dir*2)].food > 0 || view[deRotate(pos,dir*3)].food > 0)) {
//attempt rotate
moveTo = deRotate(pos,-dir);
}
if(moveTo >= 0 && view[moveTo].ant != null && view[moveTo].ant.type == 5) {
if(view[moveTo].ant.friend)
moveTo = deRotate(moveTo,dir*2);
else
moveTo = deRotate(pos,-dir);
}
return {cell:moveTo};
}
return {cell:100+view[4].ant.type};//oh god
}
function foreverAlone() {
var s0 = view[0].ant;
var s1 = view[1].ant;
var s2 = view[2].ant;
var s3 = view[3].ant;
var s5 = view[5].ant;
var s6 = view[6].ant;
var s7 = view[7].ant;
var s8 = view[8].ant;
//good
if(!(s0 == null && s1 == null && s2 == null && s3 == null && s5 == null && s6 == null && s7 == null && s8 == null) && view[4].color == TRAIL) {
if (view[0].color == TRAIL && !view[8].ant && view[8].color != TRAIL) return {cell: 8};
else if (view[2].color == TRAIL && !view[6].ant && view[6].color != TRAIL) return {cell: 6};
else if (view[6].color == TRAIL && !view[2].ant && view[2].color != TRAIL) return {cell: 2};
else if (view[8].color == TRAIL && !view[0].ant && view[0].color != TRAIL) return {cell: 0};
//Can't find color, or path is blocked? try diagonals regardless of color
else if (!view[0].ant) return {cell: 0};
else if (!view[2].ant) return {cell: 2};
else if (!view[6].ant) return {cell: 6};
else if (!view[8].ant) return {cell: 8};
//Everything else failed? Stay put.
else return {cell: 4};
}
//good
if (view[4].color == TRAIL) { //If on colored square, try to move
var totGreen = 0;
for (var i = 0; i < 9; i++) { //Look for food
if (view[i].food) {
return {cell: i};
}
if(view[i].color == TRAIL) totGreen++;
}
var ret = getTrailMove();
if(view[deRotate(ret.cell,1)].color == TRAIL && totGreen <= 4) ret.cell = deRotate(ret.cell,-1);
else if(view[deRotate(ret.cell,-1)].color == TRAIL && totGreen <= 4) ret.cell = deRotate(ret.cell,1);
return ret;
} else { //If not on colored square, look for food, or set current color to 2.
for (var i = 0; i < 9; i++) { //Look for enemies
if (i != 4 && view[i].ant != null && !view[i].ant.friend) {
var r = findOpenSpace(8-i,1);
if(view[r].color == TRAIL) r = deRotate(r,1);
return {cell: r};
}
}
return {cell: 4, color:TRAIL};
}
}
function getTrailMove() {
if (view[0].color == TRAIL && !view[8].ant && view[8].color != TRAIL) return {cell: 8};
else if (view[2].color == TRAIL && !view[6].ant && view[6].color != TRAIL) return {cell: 6};
else if (view[6].color == TRAIL && !view[2].ant && view[2].color != TRAIL) return {cell: 2};
else if (view[8].color == TRAIL && !view[0].ant && view[0].color != TRAIL) return {cell: 0};
//Can't find color, or path is blocked? try diagonals regardless of color
else if (!view[0].ant) return {cell: 0};
else if (!view[2].ant) return {cell: 2};
else if (!view[6].ant) return {cell: 6};
else if (!view[8].ant) return {cell: 8};
//Everything else failed? Stay put.
else return {cell: 4};
}
function firebreak() {
var ret = -1;
if(findWorker(5) >= 0) {
return {cell:8-findWorker(5)};
}
if(view[4].color != 5) {
var myView = [0,0,0,0,0,0,0,0,0]
for(var i=0; i < 9; i++) {
myView[i] = view[i].color
if(view[4].ant.food > 0 && view[i].food > 0) {
myView[i] = 8;
}
if(view[i].ant != null && !view[i].ant.friend) return {cell:findOpenSpace(deRotate(i,2),1)};
}
var ret = clearAhead(myView);
if(ret == null)
return {cell:4,color:5};
else {
if(!(view[ret.cell].ant != null && view[ret.cell].ant.friend == false) && (view[4].ant.food == 0 || view[ret.cell].food == 0))
return ret;
return {cell:4,color:5};
}
}
if(view[1].color == 5 && view[3].color == 5 && view[5].color == 5 && view[7].color == 5) {
if(view[0].color != 8) return {cell:0,color:8};
if(view[1].color != 8) return {cell:1,color:8};
}
if(view[1].color == 5 && view[7].color != 5) ret = {cell:7};
if(view[3].color == 5 && view[5].color != 5) ret = {cell:5};
if(view[5].color == 5 && view[3].color != 5) ret = {cell:3};
if(view[7].color == 5 && view[1].color != 5) ret = {cell:1};
if(view[1].color != 5 && view[3].color != 5 && view[5].color != 5 && view[7].color != 5) ret = {cell:1};
if((view[1].color == 5 && view[7].color == 5) || (view[3].color == 5 && view[5].color == 5)) ret = {cell:0};
var loop = 0;
while(ret.cell >= 0 && ((view[ret.cell].food > 0 && view[4].ant.food > 0) || view[ret.cell].ant != null) && loop < 9) {
loop++;
ret.cell = (ret.cell + 2) % 9;
}
if(loop < 9 && ret.cell >= 0) return ret;
return {cell:4};
}
//7,6,4,2,3
//O7,D2
function highwayRobbery() {
var move = basicHighwayMove();
if(move.cell >= 0 && view[move.cell].ant != null) {
var n = HIGHWAY_COLORS.indexOf(view[4].color) + (view[4].color%2==0?1:HIGHWAY_COLORS.length);
var nextMove = HIGHWAY_COLORS[n % HIGHWAY_COLORS.length];
for(var i=0;i<9;i++) {
if(view[i].color == nextMove) {
return {cell:i};
}
}
}
return move;
}
function basicHighwayMove() {
var isQueen = view[4].ant.type == 5;
if(isHighwayCenter()) {
var n = HIGHWAY_COLORS.indexOf(view[4].color) + 1;
var nextMove = HIGHWAY_COLORS[n % HIGHWAY_COLORS.length];
for(var i=0;i<9;i++) {
if(view[i].color == nextMove) {
if(view[i].ant == null)
return {cell:i};
else {
return {cell:deRotate(i,1)};
}
}
}
}
else {
if(view[4].color == 7) {
//move diagonal to yellow (2)
for(var i=0;i<9;i++) {
if(i != 4 && i % 2 == 0 && view[i].color == 2) {
return {cell:i};
}
}
}
else {
//move orthogonal to blue (7)
for(var i=0;i<9;i++) {
if(i % 2 == 1 && view[i].color == 7) {
//try ortho yellow first
for(var j=0;j<9;j++) {
if(j % 2 == 1 && view[j].color == 2 && areAdjacent(i,j))
return {cell:j};
}
return {cell:i};
}
}
//if orthogonal blue doens't exist...
//...try diagonal to magenta
for(var i=0;i<9;i++) {
if(i != 4 && i % 2 == 0 && view[i].color == 3) {
return {cell:i};
}
}
if(view[4].color != 2) {
//...try diagonal blue
for(var i=0;i<9;i++) {
if(i % 2 == 0 && view[i].color == 7)
return {cell:i};
}
}
//...and orthogonal yellow
for(var i=0;i<9;i++) {
if(i % 2 == 1 && view[i].color == 2)
return {cell:i};
}
}
var n = HIGHWAY_COLORS.indexOf(view[4].color) + 1;
var nextMove = HIGHWAY_COLORS[n % HIGHWAY_COLORS.length];
for(var i=0;i<9;i++) {
if(view[i].color == nextMove) {
return {cell:i};
}
}
}
return {cell:-1};
}
function isOnHighway() {
var match = 0;
var nxt = HIGHWAY_COLORS[(HIGHWAY_COLORS.indexOf(view[4].color)+1) % HIGHWAY_COLORS.length];//4
var prv = HIGHWAY_COLORS[(HIGHWAY_COLORS.indexOf(view[4].color)+HIGHWAY_COLORS.length-2) % HIGHWAY_COLORS.length];//6
for(var i=0;i<9;i++) {
if(HIGHWAY_COLORS.indexOf(view[i].color) >=0 && (i == 4 || view[i].color != view[4].color))
match++;
}
if(match >= 5) {
//7,6,4,2,3
if((view[1].color == nxt && view[7].color == prv)||(view[1].color == prv && view[7].color == nxt) ||
(view[3].color == nxt && view[5].color == prv)||(view[3].color == prv && view[5].color == nxt)) {
return true;
}
if((view[1].color == view[8].color && (view[1].color == nxt || view[1].color == prv))||(view[1].color == view[6].color && (view[1].color == nxt || view[1].color == prv)) ||
(view[3].color == view[2].color && (view[3].color == nxt || view[3].color == prv))||(view[3].color == view[8].color && (view[3].color == nxt || view[3].color == prv))) {
return true;
}
if((view[0].color == view[7].color && (view[0].color == nxt || view[0].color == prv))||(view[2].color == view[7].color && (view[2].color == nxt || view[2].color == prv)) ||
(view[0].color == view[5].color && (view[0].color == nxt || view[0].color == prv))||(view[6].color == view[5].color && (view[6].color == nxt || view[6].color == prv))) {
return true;
}
if(isHighwayCenter()) {
return true;
}
}
return false;
}
function isHighwayCenter() {
if(HIGHWAY_COLORS.indexOf(view[4].color) >=0 && (((view[0].color != view[8].color || view[2].color != view[6].color) && view[4].ant.type == 1) || (view[0].color != view[8].color && view[2].color != view[6].color))){
var m1 = view[1].color == view[7].color;
var m2 = view[2].color == view[8].color;
var m3 = view[0].color == view[6].color;
var m4 = view[0].color != 1 && view[2].color != 1;
if((m1?1:0)+(m2?1:0)+(m3?1:0) >= 2 && m4) {
if(view[3].color != view[5].color && ((view[2].color != view[5].color && view[8].color != view[5].color) || view[4].ant.type == 1) && ((view[3].color != view[0].color && view[3].color != view[6].color) || view[4].ant.type == 1)) {
return true;
}
}
m1 = view[3].color == view[5].color;
m2 = view[0].color == view[2].color;
m3 = view[6].color == view[8].color;
m4 = view[0].color != 1 && view[6].color != 1;
//good
if((m1?1:0)+(m2?1:0)+(m3?1:0) >= 2 && m4) {
m1 = view[1].color != view[7].color;
m2 = (view[0].color != view[1].color && view[1].color != view[2].color);
m3 = (view[6].color != view[7].color && view[7].color != view[8].color);
if(m1 && m2 && m3) {
return true;
}
if(view[4].ant.type == 1 && ((m1?1:0)+(m2?1:0)+(m3?1:0)) >= 2) {
return true;
}
}
}
return false;
}
function deRotateSide(m, amt) {
return deRotate(m,amt*2);
}
/**Positive amount is clockwise**/
function deRotate(m, amt) {
var rotationsCW = [1,2,5,8,7,6,3,0];
var rotationsCCW = [3,6,7,8,5,2,1,0];
if(m == 4 || m < 0 || m > 8 || amt == 0) return m;
if(amt > 0)
return rotationsCW[(rotationsCW.indexOf(m)+amt)%8];
amt = -amt;
return rotationsCCW[(rotationsCCW.indexOf(m)+amt)%8];
}
function areAdjacent(A, B) {
if(A == 4 || B == 4 || A == B) return true;
if(A % 2 == 0 && B % 2 == 0) return false;
if(A % 2 == 1 && B % 2 == 0) return areAdjacent(B,A);
if(A % 2 == 1 && B % 2 == 1) return !(8-A == B || 8-B == A);
if(A == 0 && (B == 1 || B == 3)) return true;
if(A == 2 && (B == 1 || B == 5)) return true;
if(A == 6 && (B == 3 || B == 7)) return true;
if(A == 8 && (B == 5 || B == 7)) return true;
return false;
}
function findFirstTrail() {
var pos = 0;
var b = 0;
while(view[pos].color != TRAIL && b < 8) {
pos=deRotate(pos,1);
b++;
}
return pos;
}
function clearAhead(sides) {
var c=0;
for(var i=0;i<9;i++) {
if(view[i].color == 5) c++;
if(view[i].color == 5 && i%2 == 0) c+=10;
}
if(c == 2) {
if(view[0].color == 5 || view[2].color == 5 || view[6].color == 5 || view[8].color == 5) {
return {cell:4,color:5};
}
if(view[0].ant == null)
return {cell:0};
if(view[2].ant == null)
return {cell:2};
if(view[6].ant == null)
return {cell:6};
if(view[8].ant == null)
return {cell:8};
}
c = 0;
sides[4] = 0;
var toMatch =[{state:[1,1,1,
2,0,2,
0,1,0]},
{state:[0,2,1,
1,0,1,
0,2,1]},
{state:[0,1,0,
2,0,2,
1,1,1]},
{state:[1,2,0,
1,0,1,
1,2,0]}];
for(var m=0;m<4;m++) {
var score=0;
for(var j=0;j<9;j++) {
if(j!=4) {
if(sides[j] == 5 && toMatch[m].state[j] == 1) {
score++;
}
if(sides[j] != 5 && (toMatch[m].state[j] == 0 || toMatch[m].state[j] == 2)) {
score++;
}
if(sides[j] == 5 && toMatch[m].state[j] == 2) {
score--;
}
}
}
if(score >= 6) {
var clearOrder=[1,0,2];
for(var r=0;r<clearOrder.length;r++) {
var s = deRotateSide(clearOrder[r],m);
if(view[s].color == 5) {
if(view[s].ant == null)
return {cell:s,color:8};
else
return {cell:4};
}
}
}
}
return null;
}
function findOpenSpace(pos, dir) {
if(pos > 8 || pos < 0) return pos;
var b = 0;
while(view[pos].ant != null && b < 8) {
pos=deRotate(pos,dir);
b++;
}
return pos;
}
function getHighestWorker() {
var r=0;
for(var i=0;i<9;i++) {
if(i != 4 && view[i].ant != null) {
if(view[i].ant.friend && view[i].ant.type > r) r = view[i].ant.type;
}
}
return r;
}
function getNumWorkers(type) {
var r=0;
for(var i=0;i<9;i++) {
if(i != 4 && view[i].ant != null) {
if(view[i].ant.friend && view[i].ant.type == type) r++;
}
}
return r;
}
function findWorker(type) {
for(var i=0;i<9;i++) {
if(i != 4 && view[i].ant != null) {
if(view[i].ant.friend && view[i].ant.type == type) return i;
}
}
return -1;
}
```
**422% Complete**
422% because the update was on 4/22This joke has gone on too long
Invalid move detection: check
Turning: check
Respawning workers when they get trimmed: mostly check
Avoiding stuck on other ants leeching food: ...
**Update 8/1**
Turns twice as often, resulting in ~15% more food collected
**Update 8/2**
Added robustness vs. getting stuck.
**Update 9/9**
Added code to respawn workers 2 and 3 when that arm is missing.
**Update 9/12**
Revert prior update. The glider could move forward with the newly spawned arm, but workers would act out of order when trying to turn and it would blow apart.
In addition to fixing that, reconfigured the respawn-all-workers code to be more discriminatory: it reduce collisions with nearby "lost" workers as well as preventing the respawn entirely above 60 food: 60 food is sufficient to score in the top 3 spots most of the time, which is better than spending 4 food on workers that are likely to just get stripped off again in short order: very few ants ever score more than 60 except when they out-strip Glider's capabilities anyway. Also added some code to let lost workers run about messing up other ants trails.
Few other fixes relating to situations in which the glider could get stuck even when there was a valid move it could make (e.g. having the queen ditch a stuck arm and respawn them later).
Reconfigured the color to use a defined variable and changed the trail color from yellow to green to avoid getting "trapped" in Miners on a Rail's rail system (solo queen would get constantly redirected).
Some of the new code is incorporated from my other entry, [Black Hole](https://codegolf.stackexchange.com/a/135157/8927).
**Update 9/13**
Fixed a bug in the move-out-of-spawn-orrientation code. Couple of `2`s handle gotten converted to `TRAIL`s.
**Update 1/21**
* Glider can now turn to the left (animation pending).
* Early game accelerated by spawning one worker as soon as food is available.
* One-arm gliding can turn both directions as well.
* "Don't respawn workers" threshold raised
* "Don't waste food trying to respawn and failing" reduced from `%5` to `%3`
**Update 1/25**
* Fixed some deadlock scenarios, boosting efficiency a few points in some matches.
**Update 2/20**
* Addressed several edge-case explosion / deadlock scenarios, making both the 5-and and 3-ant configurations more stable. Several arrangements of food could result in the Glider becoming confused and either deadlocking (repeatedly rotating back and forth) or exploding.
+ One explosion was the result of the sweeper ant moving onto food during the last step of a rotation, then assuming "shit, I have food, sacrifice myself to get it to the queen" when it didn't need to (standard move was valid).
+ One explosion was the result of the cell under the queen already being `TRAIL` (green), causing one of the queen's "stay still" moves (handled by the fallback to `foreverAlone()` making the queen move away from the group. Fixed this by making a stationary guard modify the queen's cell's color just before the queen takes her action.
+ More desirable than fixing the queen's code, as this allows us to escape deadlocks that may otherwise occur by retaining the fallback to `foreverAlone()`, getting the queen out, even if we can't save her wings.
* `foreverAlone()` function updated to only move onto food if the cell under the queen is `TRAIL` (green). Very slight efficiency loss.
* Glider rebuild morebetter locates an adjacent green cell, a change in `findFirstYellow()` and its usage. This, combined with the previous bullet results in better avoidance of previously seen cells and/or the site of a recent explosion: a newly formed glider will--in a large majority of cases--move off in a direction not along the queen's incoming trajectory.
+ Function renamed: Yellow has not been the queen's trail color in a long, long time.
+ Function was also *incorrectly* locating the "first cell of trail" due to an inverted logic check: `while ==` instead of `while !=`
**Update 2/25**
* More edge-case explosion/crash/deadlock fixes, overall improving performance.
* Some alterations to LightSpeed-like behavior, suggested by Alion (from his [own entry's behavior](https://codegolf.stackexchange.com/a/153688/47990)). Generally increases food collection, but also avoids certain deadlock scenarios.
**Update 3/11:**
Broken Glider wings that find themselves on the Highway switch behavior to a Vampire-like "steal food" system. Predominantly this won't mean much unless the queen *herself* is alone inside the Highway, which with its vast amounts of green, make this an impossible space to escape from.
Worker 1 will attempt to enact repairs on the Highway central corridor and performing a best-guess abort if it finds itself on a spot of Highway that is NOT rail (rather than repairing a false center). Travels in the same direction as the queen (counter to workers 2, 3, and 4).
Workers 2, 3, and 4 attempt to perform drive-by theft on the Highway queen, then return to their own queen, who spawns workers when she...
* cannot see any of her own workers
* is sitting on magenta
* has food between thresholds (with soft boundaries on both sides)
* modified by a simple random
This avoids creating too many workers (works out to ~100) and when a string of laden workers return, there is net food income (due to the no-spawning while seeing own workers) eventually pushing Glider above the top threshold and spawning (massively reduced) new workers.
This was a tactic I had been planning on writing into Vampire, but Vampire's first attempt at blocking the Highway queen and just bleeding her dry worked, so there was no incentive to create this behavior. On-highway detection code is written from scratch and is distinct from Vampire, although the mirror-detection (IsHighwayCenter) is very similar, just due to the simplicity of the pattern.
**Update 3/16**
Aside from two minor bug fixes (see edit history) an optimization was made to the Forever Alone function (stolen from...? originally) as to avoid back tracking, allowing the queen to observe more cells on average when by herself.
Fallback movement method added when the `highwayRobbery()` function failed to return a valid move when the ant is in the highway center (and no other logic had adjusted this to a sensible value). If *that* fails, the ants perform their standard gliding logic.
Minor tweaks
* Queen no longer attempts to start spawning when she detects that she is on the highway
* Queen no longer burns through Calories trying to complete a glider formation that will never complete (spawns a worker 4, worker 4 doesn't see worker 1, worker 4 moves away, repeat)
* Adjusted the food modulo values to be coprime with the Highway color cycle.
* Fixed a "finish rotate with 1 arm" that was causing a deadlock
* Minor fixes to the `isOnHighway()` check
* Made ants move onto an orthogonal yellow before moving onto an orthogonal blue cell when in the highway (saves 1 turn finding the center after becoming detatched).
**Update 3/26**
More minor tweaks.
**Update 4/21**
Minor fixes.
---
Loosely based on [Steamroller](https://codegolf.stackexchange.com/a/135154/47990).
Gathers 4 food leaving behind a yellow trail. Once it has four food, it produces one of each worker type around itself. It then begins gliding along at maximum thrust. Moving animation at the top takes 1 game turn to complete: as worker 1 is produced first, it executes first, then 2, 3, and 4, before finishing the turn with the queen. Turning animation takes 2 turns, the short pauses are when the queen performs `{cell:4}` and the food moves when workers 3, 4, and the queen all perform `{cell:4}` in order to prepare for continued gliding.
[Answer]
# Windmill
Here's a windmill... waiting for the Man from la Mancha (or Vampire from la Mancha?) who will ride up to bring it down.
[![Windmill, early middle stage of the game](https://i.stack.imgur.com/dYW8v.png)](https://i.stack.imgur.com/dYW8v.png)
I tried to explore how much further the design of [Miners on a Rail](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/136694#136694) - now relegated to that answer's edit history - could be pushed, prompted by the observation that the stepping stones had better be painted onto *alternate* walls of the mine shafts. And then it just grew and evolved...
While our heavyweight rail plus lightweight shaft geometry is almost the same and the rail patterns look similar enough to cause some ants to mistake either one for the other, the implementation is written from scratch and much more pedestrian in coding style, and introduces one new key idea. Zoom into the hub to watch it *milling*.
```
var AJM=1;var ASM=2;var AE=3;var ASF=4;var AQ=5;var RW=true;var EFCO=false;var THC=1;var TH0=0;var TH1=15;var TH2=17;var TH3=67;var TH4=120;var TH5=390;var THX=15;var THFCO1=9;var THFCO2=26;var THFCO3=75;var RM1=7;var RD1=4;var RM2=19;var RD2=THX;var PW=1;var PY=2;var PP=3;var PC=4;var PR=5;var PG=6;var PB=7;var PK=8;var LN=0;var LCLR=PW;var LT=PB;var LLSF=PP;var LA=PP;var LRL0=PC;var LRL1=PG;var LRL2=LRL0;var LRM0=PR;var LRM1=PB;var LRM1_WRP=PK;var LRM2=PG;var LRR0=PG;var LRR1=PW;var LRR1U=PR;var LRR1V=PY;var LRR1X=PK;var LRR2=PY;var LMX_M0=LCLR;var LMX_M1IN=PC;var LMX_M1OUT=PY;var LMX_M2IN=PP;var LMX_M2OUT=PR;var LMX_M3IN=PB;var LMX_M3OUT=PK;var LMS_WRP=PK;var LMR0=PK;var LML1=PY;var LMR2=PR;var LML3=PC;var LMMF=PG;var LMMH=PP;var LG3=PK;var LG4=PR;var LG5=PK;var LG6=PB;var LP0=LCLR;var LPB=PC;var LPG=PY;var LPG1=PR;var LPX=PP;var FALSE_X9=[false,false,false,false,false,false,false,false,false];
var UNDEF_X9=[undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined];
var QCPERD=6;var LCL_QC_RESET=LCLR;var LCRQC=[PY,PP,PC,PR,PG,PK];var LCRQCVAL=Array.from(FALSE_X9);var LCRQC_VALUE=Array.from(UNDEF_X9);for (var i=0; i<QCPERD; i++){LCRQCVAL[LCRQC[i]]=true;LCRQC_VALUE[LCRQC[i]]=i;}var SCPERD=7;var LCL_SC_RESET=LCLR;var LCRSC=[PY,PP,PC,PR,PG,PB,PK];var LCRSCVAL=Array.from(FALSE_X9);var LCRSC_VALUE=Array.from(UNDEF_X9);for (i=0; i<SCPERD; i++){LCRSCVAL[LCRSC[i]]=true;LCRSC_VALUE[LCRSC[i]]=i;}var LCRPHR=Array.from(FALSE_X9);LCRPHR[LPG]=true;LCRPHR[LPG1]=true;var LCRPHASES=Array.from(LCRPHR);LCRPHASES[LPX]=true;var LCRGRM1=Array.from(FALSE_X9);LCRGRM1[LRM1]=true;LCRGRM1[LRM1_WRP]=true;var LCRGRM_ALL=Array.from(FALSE_X9);LCRGRM_ALL[LRM0]=true;LCRGRM_ALL[LRM1]=true;LCRGRM_ALL[LRM1_WRP]=true;LCRGRM_ALL[LRM2]=true;var LCRGRR1_OUT=Array.from(FALSE_X9);LCRGRR1_OUT[LRR1V]=true;LCRGRR1_OUT[LRR1X]=true;var LCRGRR1B=Array.from(LCRGRR1_OUT);LCRGRR1B[LRR1U]=true;var LCRGRR1=Array.from(LCRGRR1B);LCRGRR1[LRR1]=true;var LCRMX_IO=Array.from(FALSE_X9);LCRMX_IO[LMX_M1IN]=true;LCRMX_IO[LMX_M1OUT]=true;LCRMX_IO[LMX_M2IN]=true;LCRMX_IO[LMX_M2OUT]=true;LCRMX_IO[LMX_M3IN ]=true;LCRMX_IO[LMX_M3OUT]=true;var LCRMX=Array.from(LCRMX_IO);LCRMX[LMX_M0]=true;var LCRMX_IN=Array.from(FALSE_X9);LCRMX_IN[LMX_M1IN]=true;LCRMX_IN[LMX_M2IN]=true;LCRMX_IN[LMX_M3IN ]=true;var LCRMX_OUT=Array.from(FALSE_X9);LCRMX_OUT[LMX_M1OUT]=true;LCRMX_OUT[LMX_M2OUT]=true;var LCRMM_FOOD=Array.from(FALSE_X9);LCRMM_FOOD[LCLR]=true;LCRMM_FOOD[LMMF]=true;var LCRMM_HOME=Array.from(FALSE_X9);LCRMM_HOME[LCLR]=true;LCRMM_HOME[LMMH]=true;var LCRMS=Array.from(FALSE_X9);LCRMS[LCLR]=true;LCRMS[LMS_WRP]=true;var LCRFRLL0=Array.from(FALSE_X9);LCRFRLL0[LCLR]=true;LCRFRLL0[LMR0]=true;LCRFRLL0[LMR2]=true;LCRFRLL0[LRM0]=true;LCRFRLL0[LRM2]=true;var LCRFRLL1=Array.from(FALSE_X9);LCRFRLL1[LCLR]=true;LCRFRLL1[LMR0]=true;LCRFRLL1[LMR2]=true;LCRFRLL1[LRR0]=true;LCRFRLL1[LRM1]=true;LCRFRLL1[LRR2]=true;var LCRFRLL2=Array.from(FALSE_X9);LCRFRLL2[LCLR]=true;LCRFRLL2[LMR0]=true;LCRFRLL2[LMR2]=true;LCRFRLL2[LRM0]=true;LCRFRLL2[LRR1V]=true;var TN=8;var POSC=4;var NOP={cell:POSC};var AIMU=1;var AIML=3;var AIMR=5;var AIMD=7;var FWD_CELLS=[[ true,true,false,true,true,false,false,false,false ],[ true,true,true,true,true,true,false,false,false ],[ false,true,true,false,true,true,false,false,false ],[ true,true,false,true,true,false,true,true,false ],[ true,true,true,true,true,true,true,true,true ],[ false,true,true,false,true,true,false,true,true ],[ false,false,false,true,true,false,true,true,false ],[ false,false,false,true,true,true,true,true,true ],[ false,false,false,false,true,true,false,true,true ]];var PTNOM=-9;var PTHOME=[LRM0,LRL0,LRM0,LRL0,LN,LRL0,LN,LN,LRM0];var PTGARDEN=[LG6,LG5,LG4,LN,LN,LG3,LN,LRL0,LRL1];var PTFRM0=[LRL1,LRM1,LCRGRR1,LRL0,LRM0,LRR0,LRL2,LRM2,LRR2];var PTFRM1=[LRL2,LRM2,LRR2,LRL1,LCRGRM1,LCRGRR1,LRL0,LRM0,LRR0];var PTFRM2=[LRL0,LRM0,LRR0,LRL2,LRM2,LRR2,LRL1,LCRGRM1,LCRGRR1];var PTGRM0=[LRL1,LCRGRM1,LCRGRR1,LRL0,LRM0,LRR0,LRL2,LRM2,LRR2];var PTGRM1=PTFRM1;var PTGRM2=PTFRM2;var PTGRM2B=[LRL0,LRM0,LRR0,LRL2,LRM2,LRR2,LRL1,LCRGRM1,LCRGRR1B];var PTGRM1_WRP=[LRL2,LRM2,LRR2,LRL1,LRM1_WRP,LRR1X,LRL0,LRM0,LRR0];var PTFRL0=[LCRFRLL1,LRL1,LRM1,LCRFRLL0,LRL0,LRM0,LCRFRLL2,LRL2,LRM2];var PTFRL1=[LCRFRLL2,LRL2,LRM2,LCRFRLL1,LRL1,LCRGRM1,LCRFRLL0,LRL0,LRM0];var PTFRL0H=[LN,LRL1,LRM1,LN,LRL0,LRM0,LN,LN,LN];var PTFRL1G=[LCRFRLL2,LRL2,LRM2,LG3,LRL1,LCRGRM1,LCRPHASES,LRL0,LRM0];var PTFRL2=[LCRFRLL0,LRL0,LRM0,LCRFRLL2,LRL2,LRM2,LCRFRLL1,LRL1,LCRGRM1];var PTGRL0=[LCRFRLL1,LRL1,LCRGRM1,LCRFRLL0,LRL0,LRM0,LCRFRLL2,LRL2,LRM2];var PTGRL1=PTFRL1;var PTGRL2=PTFRL2;var PTGRR0=[LCRGRM1,LCRGRR1,LCLR,LRM0,LRR0,LMR0,LRM2,LRR2,LCRMX];var PTGRR2=[LRM0,LRR0,LMR0,LRM2,LRR2,LCRMX,LCRGRM1,LCRGRR1,LCLR];var PTGRR1=[LRM0,LCRGRM1,LRM2,LRR0,LCRGRR1,LRR2,LMR0,LCLR,LCRMX];var PTMS0R_IN=[LRR0,LRR1U,LRR2,LMR0,LCLR,LCRMX_IN,LCLR,LCLR,LML1];var PTMS0R_OUT=[LRR0,LRR1U,LRR2,LMR0,LCLR,LCRMX_IO,LCLR,LCLR,LML1];var PTMS0R_OUT1=[LRR0,LCRGRR1_OUT,LRR2,LMR0,LCLR,LCRMX,LCLR,LCLR,LML1];var PTMS0=[LCLR,LCRMM_HOME,LML3,LMR0,LCRMM_FOOD,LCLR,LCLR,LCLR,LML1];var PTMS1=[LMR0,LCRMM_HOME,LCLR,LCLR,LCRMM_FOOD,LML1,LMR2,LCLR,LCLR];var PTMS2=[LCLR,LCRMM_HOME,LML1,LMR2,LCRMM_FOOD,LCLR,LCLR,LCLR,LML3];var PTMS3=[LMR2,LCRMM_HOME,LCLR,LCLR,LCRMM_FOOD,LML3,LMR0,LCLR,LCLR];var PTMS1_IN=[LMR0,LCRMM_HOME,LCRMX_IN,LCLR,LCRMM_FOOD,LML1,LMR2,LCLR,LCLR];var PTMS1_IO=[LMR0,LCRMM_HOME,LCRMX_IO,LCLR,LCRMM_FOOD,LML1,LMR2,LCLR,LCLR];var PTMS0_OUT=[LCLR,LCLR,LML3,LMR0,LCLR,LCRMX_IO,LCLR,LCLR,LML1];var PTMS0_WRAPPING=[LCLR,LCRMM_HOME,LML3,LMR0,LCRMM_FOOD,LCRMS,LRL0,LRL1,LRL2];var PTGRL1_WRP=[LMR0,LCLR,LMS_WRP,LRL0,LRL1,LRL2,LRM0,LRM1_WRP,LRM2];var PTMS0FL=[LMMH,LML3,LN,LMMF,LCLR,LN,LCLR,LML1,LN];var PTMS1FL=[LMMH,LCLR,LN,LMMF,LML1,LN,LCLR,LCLR,LN];var PTMS2FL=[LMMH,LML1,LN,LMMF,LCLR,LN,LCLR,LML3,LN];var PTMS3FL=[LMMH,LCLR,LN,LMMF,LML3,LN,LCLR,LCLR,LN];var PTMS0FR=[LN,LCLR,LMMH,LN,LMR0,LMMF,LN,LCLR,LCLR];var PTMS1FR=[LN,LMR0,LMMH,LN,LCLR,LMMF,LN,LMR2,LCLR];var PTMS2FR=[LN,LCLR,LMMH,LN,LMR2,LMMF,LN,LCLR,LCLR];var PTMS3FR=[LN,LMR2,LMMH,LN,LCLR,LMMF,LN,LMR0,LCLR];var CCW=[6,7,8,5,2,1,0,3,6,7,8,5,2,1,0,3,6,7,8,5,2,1];
var xn=-1;var fwdWrong=[];var rearWrong=[];var here=view[POSC];var mC=here.color;var myself=here.ant;var mT=myself.type;var mF=myself.food;var mS=(mT==AE||(mT!=AQ&&mF>0));if (EFCO&&(mT==AQ)){if (mF<=THFCO1){QCPERD=5;} else if (mF<=THFCO2){QCPERD=4;} else if (mF<=THFCO3){QCPERD=5;}}var dOK=[true,true,true,true,true,true,true,true,true];
var uo=true;var sL=[0,0,0,0,0,0,0,0,0];var sD=[0,0,0,0,0,0,0,0,0];var sN=[0,0,0,0,0,0,0,0,0];var sT=[0,0,0,0,0,0,0,0,0];var fdL=0;var fdD=0;var fdT=0;sT[mC]++;for (i=0; i<TN; i+=2){var cell=view[CCW[i]];sD[cell.color]++;sN[cell.color]++;sT[cell.color]++;if (cell.food>0){fdD++;fdT++;if (mS){dOK[CCW[i]]=false;uo=false;}}}for (i=1; i<TN; i+=2){var cell=view[CCW[i]];sL[cell.color]++;sN[cell.color]++;sT[cell.color]++;if (cell.food>0){fdL++;fdT++;if (mS){dOK[CCW[i]]=false;uo=false;}}}var aF=[0,0,0,0,0,0];var aLF=[0,0,0,0,0,0];var aUF=[0,0,0,0,0,0];var fT=0;var mQ=0;var aE=[0,0,0,0,0,0];var aLE=[0,0,0,0,0,0];var aUE=[0,0,0,0,0,0];var eT=0;for (i=0; i<TN; i++){var cell=view[CCW[i]];if (cell.ant){if (cell.ant.friend){aF[cell.ant.type]++;fT++;if (cell.ant.type==AQ){xn=i&6;mQ=i&1;}if (cell.ant.food>0){aLF[cell.ant.type]++;} else {aUF[cell.ant.type]++;}} else {aE[cell.ant.type]++;eT++;if (cell.ant.food>0){aLE[cell.ant.type]++;} else {aUE[cell.ant.type]++;}}dOK[CCW[i]]=false;uo=false;}}switch (mT){case AQ:return (rQSs());case ASF:if (mQ==1){return (rSSs());} else if (aF[AQ]>0){return (rGSs());} else {return (rLSSy());}case AE:return (rESs());case AJM:case ASM:if (aE[AQ]>0){return (rDSs());} else if (mF>0){return (rLSs());} else {return (rUSs());}default:return NOP;}function rQSs (){switch (aF[ASF]){case 0:return (rQScrSy());case 1:for (var i=0; i<TN; i++){var cell=view[CCW[i]];if (cell.ant&&cell.ant.type==ASF){xn=i&6;if (i&1){if (mF<=THX){return (rQLsSy());} else {return (rQLvSy());}} else {return (rQSgSy());}}}break;case 2:for (i=0; i<TN; i+=2){var cell0=view[CCW[i]];var cell1=view[CCW[i+1]];if ((cell0.ant&&(cell0.ant.type==ASF))&&(cell1.ant&&(cell1.ant.type==ASF))){xn=i;return (rQOSy());}}return (rQCSy());default:return (rQCSy());}return NOP;}function rSSs (){if (view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&(view[CCW[xn+3]].ant.type==ASF)){return (rSOSy());} else if (view[CCW[xn+1]].ant.food<=THX){return (rSLSy());} else {return (rSESy());}}function rGSs (){var secCell=view[CCW[xn+7]];if (secCell.ant&&(secCell.ant.friend==1)&&(secCell.ant.type==ASF)){return (rGOSy());} else {return (rGSSy());}return NOP;}function rESs (){if (aF[AQ]>0){return (rEHyS());} else if (aF[AJM] +aF[ASM]>0){return (rEBRSy());} else {return (rEASy());}return NOP;}function rDSs(){if (aF[AQ]>0){return (rDHSy());} else {for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&(view[CCW[i]].ant.type==AQ)){if (i&1){if ((view[CCW[i+1]].ant&&view[CCW[i+1]].ant.friend&&view[CCW[i+2]].ant&&view[CCW[i+2]].ant.friend)||(view[CCW[i-1]].ant&&view[CCW[i-1]].ant.friend&&view[CCW[i+6]].ant&&view[CCW[i+6]].ant.friend)||(view[CCW[i+2]].ant&&view[CCW[i+2]].ant.friend&&view[CCW[i+6]].ant&&view[CCW[i+6]].ant.friend)){if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else if (dOK[CCW[i+3]]){return {cell:CCW[i+3]};} else if (dOK[CCW[i+5]]){return {cell:CCW[i+5]};}}} else {if (view[CCW[i+1]].ant&&view[CCW[i+1]].ant.friend&&
view[CCW[i+7]].ant&&view[CCW[i+7]].ant.friend){if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else if (dOK[CCW[i+3]]){return {cell:CCW[i+3]};} else if (dOK[CCW[i+5]]){return {cell:CCW[i+5]};} else if (dOK[CCW[i+6]]){return {cell:CCW[i+6]};} else if (dOK[CCW[i+2]]){return {cell:CCW[i+2]};}}if ((i<=2)&&dOK[CCW[i+7]]){return {cell:CCW[i+7]};}if ((i>=4)&&dOK[CCW[i+1]]){return {cell:CCW[i+1]};}}if (fT==0){if (view[CCW[i]].color!=PP){return {cell:CCW[i],color:PP};} else if (mC!=LCLR){return {cell:POSC,color:LCLR};}}}}}return NOP;}function rUSs (){if ((aF[AQ]>0)&&!LCRQCVAL[view[CCW[xn+mQ]].color]){return (rUHSy());} else if ((fT+eT>=4)&&(aF[AJM]+aF[ASM] +aF[AE]>=3)){return (rUCRSy());} else if (aF[AQ]>0){return (rUHSy());} else if (aF[ASF]>0){if (aF[ASF]>1){return (rM2R1Sy());} else {return (rURHSy());}} else if (aF[AE]>0){return (rUBRSy());} else if (spcRL1()){return (rULRL1Sy());} else if (spcRR0()){return (rULRR0Sy());} else if (spcRR2()){return (rULRR2Sy());} else if (spcMS()){return (rUDSSy());} else if (spcRL02()){return (rULRL02Sy());} else if (spcRM()){return (rUTRRSy());} else if (spcRR1()){return (rUPSSy());} else if (spcMS0R()){return (rUESSy());} else if (spcMS0W()){return (rUSWSy());}return (rLostMSy(true));}function rLSs (){if ((fT>=3)&&(fT+eT>=4)){return (rLCRSy());} else if (aF[ASF]>0){if (aF[ASF]>1){return (rM2R1Sy());} else {return (rLRHSy());}} else if (spcMFL()){return (rLLLWSy());} else if (spcMFR()){return (rLLRWSy());} else if (spcRL1()){return (rLLRL1Sy());} else if (spcRR0()){return (rLLRR0Sy());} else if (spcRR2()){return (rLLRR2Sy());} else if (spcMS0R()){return (rLLSSy());} else if (spcMS0ROut()){return (rLLVSSy());} else if (spcMS()&&(aF[AE]==0)){return (rLASSy());} else if (spcRL02()){return (rLLRL02Sy());} else if (spcRM()){return (rLTRRSy());} else if (spcRR1()){return (rLDSSy());} else if (aF[AE]>0){return (rLFRSy());}return (rLostMSy(true));}function rQScrSy(){if (uo){if (fdT>0){return (rQSETc());} else if (mF>=THC){for (var i=0; i<TN; i+=2){if ((view[CCW[i]].color==LT)||(view[CCW[i+1]].color==LT)){return {cell:CCW[i+1],type:ASF};}}return {cell:1,type:ASF};} else if (mC!=LT){if ((mC==LCLR)||(sN[LCLR]>=TN-1)){return {cell:POSC,color:LT};} else {return (rQSTCTc());}} else if ((sN[LCLR]>=4)&&(sN[LT]==1)){for (var i=0; i<TN; i+=2){if ((view[CCW[i]].color==LT)||(view[CCW[i+1]].color==LT)){return {cell:CCW[i+4]};}}} else if (sN[LCLR]==TN){return {cell:0};} else {return (rQSATc());}} else {if ((fdT>0)&&(eT>0)&&(eT==aE[AQ])){return (rQSSTc());} else {return (rQSEvTc());}}return NOP;}function rQSgSy(){if (fdT>0){if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else {for (var i=2; i<TN-1; i++){if (dOK[CCW[xn+i]]&&(view[CCW[xn+i]].food>0)){return {cell:CCW[xn+i]};}}for (var i=2; i<TN-1; i++){if (dOK[CCW[xn+i]]){ return {cell:CCW[xn+i]};}}return NOP;}} else if ((mF>TH0)&&(mC==LCL_QC_RESET)){if (dOK[CCW[xn+7]]){return { cell:CCW[xn+7],type:AE};} else if (view[CCW[xn]].color==LPB){if (dOK[CCW[xn+3]]){return { cell:CCW[xn+3],type:AE};} else if (dOK[CCW[xn+5]]){return { cell:CCW[xn+5],type:AE};} else if (dOK[CCW[xn+6]]){return { cell:CCW[xn+6],type:AJM};} else if (dOK[CCW[xn+2]]){return { cell:CCW[xn+2],type:AJM};} else if (dOK[CCW[xn+4]]){return { cell:CCW[xn+4],type:AJM};} else if (dOK[CCW[xn+1]]){return { cell:CCW[xn+1],type:ASF};}}}return NOP;}function rQOSy(){if ((aE[AQ]>0)&&(mF>0)){for (var i=2; i<TN; i++){if (view[CCW[xn+i]].ant&&(view[CCW[xn+i]].ant.type==AQ)&&!view[CCW[xn+i]].ant.friend){var j=(xn&4) ? 1 : -1;if (dOK[CCW[xn+i-j]]){return {cell:CCW[xn+i-j],type:AJM};} else if (dOK[CCW[xn+i+j]]){return {cell:CCW[xn+i+j],type:AJM};} else if (i==5){var i1=5-2*j;var i2=5+2*j;if (dOK[CCW[xn+i1]]&&!(view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend&&
view[CCW[xn+6]].ant&&view[CCW[xn+6]].ant.friend&&
view[CCW[xn+i2]].ant&&view[CCW[xn+i2]].ant.friend)){return {cell:CCW[xn+i1],type:AJM};} else if (dOK[CCW[xn+i2]]&&!(view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend&&
view[CCW[xn+6]].ant&&view[CCW[xn+6]].ant.friend&&
view[CCW[xn+i1]].ant&&view[CCW[xn+i1]].ant.friend)){return {cell:CCW[xn+i2],type:AJM};}} else if ((i==3)&&dOK[CCW[xn+5]]&&!(view[CCW[xn+2]].ant&&view[CCW[xn+2]].ant.friend&&
view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend)){return {cell:CCW[xn+5],type:AJM};} else if ((i==7)&&dOK[CCW[xn+5]]&&!(view[CCW[xn+6]].ant&&view[CCW[xn+6]].ant.friend)){return {cell:CCW[xn+5],type:AJM};}}}} else if ((mF>0)&&(view[CCW[xn+7]].color==LA)&&dOK[CCW[xn+7]]){return {cell:CCW[xn+7],type:AJM};} else if (view[CCW[xn+1]].ant.food>0){if ((mF>0)&&dOK[CCW[xn+2]]){return {cell:CCW[xn+2],type:AJM};}} else if ((aLF[AJM]+aLF[ASM]>0)&&(mF>0)&&(sN[LA]>0)){for (var i=2; i<TN; i++){var c=CCW[xn+i];if (dOK[c]&&(view[c].color==LA)){return {cell:c,type:AJM};}}} else if (eT>0){var bandits=aUE[1]+aUE[2]+aUE[3]+aUE[4];if ((mF>THX)&&((bandits>=2)||((bandits>=1)&&view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&(view[CCW[xn+5]].color==LA)&&(view[CCW[xn+7]].ant&&view[CCW[xn+7]].ant.friend&&
(view[CCW[xn+7]].color==LA))||(view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&
(view[CCW[xn+3]].color==LA))))){if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}}if (mF<RD1){if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}} else if ((bandits>=1)&&(mF>0)){if ((mF>THX)&&(mF % RM2==RD2+xn/2)){if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}}for (var i=2; i<TN; i++){var c=CCW[xn+i];var c1,c2;if ((xn==2)||isSc0(view[CCW[xn+1]].color)){c1=CCW[xn+i-1];c2=CCW[xn+i+1];} else if ((xn==6)||isSc1(view[CCW[xn+1]].color)){c1=CCW[xn+i+1];c2=CCW[xn+i-1];} else {break;}if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.food==0)){if (dOK[c1]&&!(view[c2].ant&&view[c2].ant.friend&&view[c2].ant.food>0)){return {cell:c1,type:AJM};} else if (dOK[c2]&&!(view[c1].ant&&view[c1].ant.friend&&view[c1].ant.food>0)){return {cell:c2,type:AJM};}break;}}}}if (!(LCRQCVAL[mC])){return {cell:POSC,color:LCRQC[1]};} else if ((view[CCW[xn]].color==LPX)&&isSc0(view[CCW[xn+1]].color)){if ((mF<=TH0)||(mF % RM1==RD1)){return (rQHTc());} else if (mF<=TH2){if (dOK[CCW[0]]){return {cell:CCW[0],type:AJM};} else {return (rQHTc());}} else {var destCycle=[2,4,6,4,6,2,6,2,4];var destination=destCycle[mF % 9];if (!dOK[CCW[xn+destination]]){destination=destination % 6+2;}if (!dOK[CCW[xn+destination]]){destination=destination % 6+2;}if (!dOK[CCW[xn+destination]]){return (rQHTc());}if (mF<=TH3){if (xn<=2){return {cell:CCW[xn+destination],type:AJM};} else {return (rQHTc());}} else if (mF<=TH4){if (xn<=2){return {cell:CCW[xn+destination],type:((xn>0) ? AJM : ASM)};} else {return (rQHTc());}} else if (mF<=TH5){if (xn==0){return {cell:CCW[xn+destination],type:ASM};} else {return (rQHTc());}} else {return (rQHTc());}}} else {return {cell:POSC,color:incQc(mC)};}return NOP;}function rQLsSy(){if (mF>=TH1){if (mC!=LCLR){return {cell:POSC,color:LCLR};} else {for (var i=0; i<TN; i+=2){if (view[CCW[i]].color!=LCLR){return {cell:CCW[i],color:LCLR};}}}if ((eT==0)&&(fT==1)){return {cell:CCW[xn+3]};}}if ((eT==0)&&(fT==1)){if (view[CCW[xn+2]].food>0){return {cell:CCW[xn+2]};} else if ((view[CCW[xn+3]].food +view[CCW[xn+4]].food>0)&&(view[CCW[xn+1]].color!=LLSF)){return NOP;} else {return {cell:CCW[xn+2]};}} else if (dOK[CCW[xn+2]]&&(dOK[CCW[xn+3]]||(view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend))){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn]]&&dOK[CCW[xn+7]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else {return NOP;}}function rQLvSy(){if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}return NOP;}function rQCSy(){return NOP;}function rSOSy(){if (!(LCRSCVAL[mC])){return {cell:POSC,color:LCRSC[1]};} else if (isSc0(mC)&&isQc0(view[CCW[xn+1]].color)&&
(view[CCW[xn+3]].color==LPG)){return {cell:CCW[xn+3],color:LPX};} else {return {cell:POSC,color:incSc(mC)};}return NOP;}function rSLSy(){if ((eT==0)&&(fT==1)){if (view[CCW[xn]].food>0){return {cell:CCW[xn]};} else if (view[CCW[xn+7]].food +view[CCW[xn+6]].food>0){return {cell:POSC,color:LLSF};} else {return {cell:CCW[xn]};}} else if ((eT>0)&&view[CCW[xn+2]].ant&&!view[CCW[xn+2]].ant.friend){return {cell:POSC,color:LLSF};} else {if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}}return NOP;}function rSESy(){if (view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&(view[CCW[xn+5]].ant.type==ASF)){if (dOK[CCW[xn]]){return {cell:CCW[xn]};}} else if ((mC==LRR0)&&(view[CCW[xn+5]].color==LG6)){if (dOK[CCW[xn]]){return {cell:CCW[xn]};}} else {if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn]]){return {cell:CCW[xn]};}}return NOP;}function rGSSy(){if (view[CCW[xn]].color!=LCL_QC_RESET){return {cell:CCW[xn],color:LCL_QC_RESET};}if (mC!=LPB){return {cell:POSC,color:LPB};}return (rGGTc());}function rGOSy(){if (aE[AQ]>0){var c=CCW[xn+2];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+1]].ant){return {cell:CCW[xn+1],color:LA};}c=CCW[xn+3];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+1]].ant){return {cell:CCW[xn+1],color:LA};}}if (!LCRPHR[mC]){if ((mC==LPX)&&isSc0(view[CCW[xn+7]].color)){return NOP;} else if (eT==0){return {cell:POSC,color:LPG};}} else if (isSc1(view[CCW[xn+7]].color)&&isQc2(view[CCW[xn]].color)){switch (mC){case LPG:return {cell:POSC,color:LPG1};case LPG1:return {cell:POSC,color:LPG};default:return {cell:POSC,color:LPG};}}if ((eT>0)&&!LCRPHR[mC]&&(xn&4)){return {cell:POSC,color:LPG};} else {return (rGGTc());}}function rLSSy(){if (mC!=LCLR){return {cell:POSC,color:LCLR};}return NOP;}function rEHyS(){if (mQ==1){var ptrn=PTFRL0H;var msm=patC(ptrn,AIMU,0,1);if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (LCRQCVAL[view[CCW[xn+mQ]].color]&&dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};}}return NOP;}function rEBRSy(){if (aF[ASF]>0){return (rELGTc());} else {return (rEBRTc());}}function rEASy(){return NOP;}function rUHSy(){if ((mQ==0)&&(view[CCW[xn]].ant.food<RD1)&&view[CCW[xn+1]].ant&&view[CCW[xn+1]].ant.friend&&(view[CCW[xn+1]].ant.type==ASF)){var cc=[5,6,7,4,2];for (var i=0; i<cc.length; i++){var c=CCW[xn+cc[i]];if (dOK[c]){return {cell:c};}}return NOP;}if ((eT>0)&&(aE[AQ]+aUE[1]+aUE[2] +aUE[3]+aUE[4]>0)){var common;if (mQ==0){common=[1,7];} else {common=[0,2,3,7];}for (var i=0; i<common.length; i++){var c=CCW[xn+common[i]];if (view[c].ant&&!view[c].ant.friend&&((view[c].ant.type==AQ)||(view[c].ant.food==0))){if ((aE[AQ]==0)&&(mC!=LA)){return {cell:POSC,color:LA};} else {return NOP;}}}}if (mQ==0){if (mC!=LRM0){return {cell:POSC,color:LRM0};} else if (view[CCW[xn+3]].color!=LRR0){return {cell:CCW[xn+3],color:LRR0};} else if (view[CCW[xn+7]].color!=LRL0){return {cell:CCW[xn+7],color:LRL0};} else if (view[CCW[xn+5]].color!=LRM1){return {cell:CCW[xn+5],color:LRM1};} else if (view[CCW[xn+6]].color!=LRL1){return {cell:CCW[xn+6],color:LRL1};} else if ((!LCRGRR1[view[CCW[xn+4]].color])&&!(view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend)){return {cell:CCW[xn+4],color:LRR1};}if (LCRQCVAL[view[CCW[xn]].color]||(view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&
(view[CCW[xn+5]].ant.food>0))||(view[CCW[xn+6]].ant&&view[CCW[xn+6]].ant.friend&&
(view[CCW[xn+6]].ant.food>0))){if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};}}} else {var ptrn=PTFRL0H;var msm=patC(ptrn,AIMU,0,1);if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (LCRQCVAL[view[CCW[xn+mQ]].color]){if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};}}}return NOP;}function rUBRSy(){if (spcRL1()){return (rULRL1Sy());} else if (spcRL02()){return (rULRL02Sy());} else if (spcRM()){return (rUFCRTc());}for (var i=TN-1; i>=0; i--){if (view[CCW[i+1]].ant&&view[CCW[i+1]].ant.friend&&
(view[CCW[i+1]].ant.type==AE)&&dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}function rUTRRSy(){return (rUCRTc());}function rULRL1Sy(){var ptrn=PTGRL1;var msm=patC(ptrn,AIMR,0,1);if (xn>=0){if ((view[CCW[xn+6]].color==LMS_WRP)&&(view[CCW[xn+7]].color==LCLR)&&(view[CCW[xn]].color==LMR0)&&(view[CCW[xn+3]].color!=LRM1_WRP)){return {cell:CCW[xn+3],color:LRM1_WRP};} else if ((view[CCW[xn+3]].color!=LRM1_WRP)&&view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return NOP;}} else if (spcRM()){return (rUTRRSy());}return (rLostMSy(false));}function rULRL02Sy(){var ptrn;var msm;if (sL[LRM0]>0){ptrn=PTGRL0;msm=patC(ptrn,AIMR,1,1);}if (xn<0){ptrn=PTGRL2;msm=patC(ptrn,AIMR,1,1);}if (xn>=0){if (view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return NOP;}} else if (spcRM()){return (rUTRRSy());}return (rLostMSy(false));}function rULRR0Sy(){var ptrn=PTGRR0;var msm=patC(ptrn,AIML,2,1);if (xn>=0){return (runUMLeaveRRTactic());} else if (spcRM()){return (rUTRRSy());}return (rLostMSy(false));}function rULRR2Sy(){var ptrn=PTGRR2;var msm=patC(ptrn,AIML,2,1);if (xn>=0){return (runUMLeaveRRTactic());} return (rLostMSy(false));}function rUPSSy(){var ptrn=PTGRR1;var msm=patC(ptrn,AIMD,3,2);if (xn>=0){var c=CCW[xn+1];if (view[c].ant&&view[c].ant.friend&&(view[c].ant.food>0)){if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return NOP;}}if ((view[CCW[xn+2]].color==LMX_M3OUT)&&(view[CCW[xn]].color==LMR0)&&(view[CCW[xn+1]].color==LCLR)&&(mC!=LRR1X)){return {cell:POSC,color:LRR1X};} else if ((mT==AJM)&&(mC==LRR1U)&&(view[CCW[xn]].color==LMR0)&&(view[CCW[xn+1]].color==LCLR)&&LCRMX_OUT[view[CCW[xn+2]].color]){return {cell:POSC,color:LRR1V};} else if ((mC==LRR1X)||((mT==AJM)&&(mC==LRR1V))||((mC==LRR1U)&&(view[CCW[xn]].color==LMR0)&&(view[CCW[xn+1]].color==LCLR)&&LCRMX_IN[view[CCW[xn+2]].color])){if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}} else if (mC!=LRR1U){return {cell:POSC,color:LRR1U};} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {if (dOK[c]){return {cell:c};} else if (view[c].ant&&view[c].ant.friend){if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}} else {return NOP;}}}return (rLostMSy(false));}function rUESSy(){var ptrn=PTMS0R_IN;var msm=patC(ptrn,AIMD,4,2);if (xn>=0){return (rUESTc(ptrn,msm));}return (rLostMSy(false));}function rUDSSy(){var ptrn;var msm;if ((sL[LML3]>=1)&&(sD[LMR2]+sD[LMR0]>=1)){ptrn=PTMS3;msm=patC(ptrn,AIMD,3,2);}if ((xn<0)&&(sL[LMR2]>=1)&&(sD[LML1]+sD[LML3]>=1)){ptrn=PTMS2;msm=patC(ptrn,AIMD,3,2);}if (xn>=0){if ((msm<0)&&(view[CCW[xn]].color==LRM0)&&(view[CCW[xn+1]].color==LRR0)&&(view[CCW[xn+2]].color==LMR0)){if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else {return NOP;}}return (rUDSTc(ptrn,msm));}if ((xn<0)&&(sL[LML1]>=1)&&(sD[LMR0]+sD[LMR2]>=1)){ptrn=PTMS1_IN;msm=patC(ptrn,AIMD,3,4);if (xn<0){ptrn=PTMS1;msm=patC(ptrn,AIMD,3,2);}}if (xn>=0){return (rUDSTc(ptrn,msm));}if ((sD[LML3]+sL[LMR0]>=2)&&(sD[LRL0] >=2)&&(sD[LML1]==0)){ptrn=PTMS0_WRAPPING;msm=patC(ptrn,AIMD,0,1);if (xn>=0){return (rUWRTc(ptrn,msm));}}if ((sL[LMR0]>=1)&&(sD[LML3]+sD[LML1]>=1)){ptrn=PTMS0;msm=patC(ptrn,AIMD,3,2);if (xn>=0){return (rUDSTc(ptrn,msm));}}if (spcRR1()){ptrn=PTGRR1;msm=patC(ptrn,AIMD,3,2);if (xn>=0){if (mC==LRR1){return {cell:POSC,color:LRR1U};}return NOP;}}if (spcMS0R()){ptrn=PTMS0R_IN;msm=patC(ptrn,AIMD,4,2);if (xn>=0){return (rUESTc(ptrn,msm));}}return (rLostMSy(false));}function rUSWSy(){var ptrn=PTMS0_WRAPPING;var msm=patC(ptrn,AIMD,0,1);if (xn>=0){return (rUWRTc(ptrn,msm));}return (rLostMSy(false));}function rURHSy(){return (rMNGTc());}function rUCRSy(){for (var i=TN; i>=1; i--){if (view[CCW[i]].ant&&dOK[CCW[i-1]]){return {cell:CCW[i-1]};}}return NOP;}function rLLLWSy(){var ptrn;var msm;if (mC==LML1){ptrn=PTMS1FL;msm=patC(ptrn,AIML,0,1);if (xn>=0){return (rLLLWTc());}} else if (mC==LML3){ptrn=PTMS3FL;msm=patC(ptrn,AIML,0,1);if (xn>=0){return (rLLLWTc());}} else if (sL[LML1]+sL[LML3]>=2){ptrn=PTMS0FL;msm=patC(ptrn,AIML,0,1);if (xn<0){ptrn=PTMS2FL;msm=patC(ptrn,AIML,0,1);}if (xn>=0){return (rLLLWTc());}} else if (spcMFR()){return (rLLRWSy());} else if (spcMS()){return (rLASSy());}return (rLostMSy(false));}function rLLRWSy(){var ptrn;var msm;if (mC==LMR0){ptrn=PTMS0FR;msm=patC(ptrn,AIMR,0,1);if (xn>=0){return (rLLRWTc());}} else if (mC==LMR2){ptrn=PTMS2FR;msm=patC(ptrn,AIMR,0,1);if (xn>=0){return (rLLRWTc());}} else if (sL[LMR0]+sL[LMR2]>=2){ptrn=PTMS1FR;msm=patC(ptrn,AIMR,0,1);if (xn<0){ptrn=PTMS3FR;msm=patC(ptrn,AIMR,0,1);}if (xn>=0){return (rLLRWTc());}} else if (spcMS()){return (rLASSy());}return (rLostMSy(false));}function rLASSy(){var ptrn;var msm;if ((sL[LML3]>=1)&&(sD[LMR2]+sD[LMR0]>=1)){ptrn=PTMS3;msm=patC(ptrn,AIMU,3,2);}if ((xn<0)&&(sL[LMR2]>=1)&&(sD[LML1]+sD[LML3]>=1)){ptrn=PTMS2;msm=patC(ptrn,AIMU,3,2);}if ((xn<0)&&(sL[LML1]>=1)&&(sD[LMR0]+sD[LMR2]>=1)){ptrn=PTMS1_IO;msm=patC(ptrn,AIMU,0,1);if (xn<0){ptrn=PTMS1;msm=patC(ptrn,AIMU,3,2);}}if (xn>=0){return (rLASTc(ptrn,msm));}if ((sD[LML3]+sL[LMR0]>=2)&&(sD[LRL0] >=2)&&(sD[LML1]==0)){ptrn=PTMS0_OUT;msm=patC(ptrn,AIMU,0,1);if (xn>=0){return {cell:CCW[xn+3],color:LCLR};}ptrn=PTMS0_WRAPPING;msm=patC(ptrn,AIMD,0,1);if (xn>=0){return (rLWRTc(ptrn,msm));}}if ((sL[LMR0]>=1)&&(sD[LML3]+sD[LML1]>=1)){ptrn=PTMS0;msm=patC(ptrn,AIMU,3,2);if (xn>=0){return (rLASTc(ptrn,msm));}}if (spcRM()){return (rLTRRSy());}return (rLostMSy(false));}function rLLSSy(){var ptrn=PTMS0R_OUT;var msm=patC(ptrn,AIMU,0,1);if (xn>=0){} else {ptrn=PTMS0R_IN;msm=patC(ptrn,AIMU,4,2);if (xn>=0){ptrn=PTMS0R_OUT;msm=patC(ptrn,AIMU,0,1);}}if (xn>=0){return (rLLSTc(ptrn,msm));} else if (spcMS()){return (rLASSy());} else {return (rLostMSy(false));}return NOP;}function rLLVSSy(){var ptrn=PTMS0R_OUT1;var msm=patC(ptrn,AIMU,0,1);if (xn>=0){if (view[CCW[xn+3]].color==LCLR){return {cell:CCW[xn+3],color:((mT==ASM) ? LMX_M2OUT : LMX_M1OUT)};
} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&
dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}} else if (spcMS()){return (rLASSy());}return (rLostMSy(false));}function rLDSSy(){var ptrn=PTGRR1;var msm=patC(ptrn,AIMU,1,1);if (xn>=0){if ((view[CCW[xn]].color==LMR0)&&(view[CCW[xn+1]].color==LCLR)){if ((mC==LRR1X)&&(view[CCW[xn+2]].color!=LMX_M3OUT)){return {cell:CCW[xn+2],color:LMX_M3OUT};}if ((view[CCW[xn+2]].color==LMX_M3OUT)&&(mC!=LRR1X)){return {cell:POSC,color:LRR1X};} else if ((LCRMX_OUT[view[CCW[xn+2]].color])&&
(mC!=LRR1V)){return {cell:POSC,color:LRR1V};} else if ((LCRMX_IN[view[CCW[xn+2]].color])&&(mC!=LRR1U)){return {cell:POSC,color:LRR1U};} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}}if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}}return (rLostMSy(false));}function rLTRRSy(){return (rLCRTc());}function rLFRSy(){for (var i=1; i<TN; i+=2){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==AE)&&dOK[CCW[i+2]]){return {cell:CCW[i+2]};}}return NOP;}function rLRHSy(){var ptrn=PTFRL1G;var msm=patC(ptrn,AIMR,0,1);if (xn>=0){return (rLRLTc());}return (rMNGTc());}function rLLRL1Sy(){var ptrn=PTGRL1;var msm=patC(ptrn,AIMR,0,1);if (xn>=0){return (rLRLTc());} else if (spcRM()){return (rLTRRSy());}return (rLostMSy(false));}function rLLRL02Sy(){var ptrn;var msm;if (sL[LRM0]>0){ptrn=PTGRL0;msm=patC(ptrn,AIMR,1,1);}if (xn<0){ptrn=PTGRL2;msm=patC(ptrn,AIMR,1,1);}if (xn>=0){return (rLRLTc());}return (rLostMSy(false));}function rLLRR0Sy(){var ptrn=PTGRR0;var msm=patC(ptrn,AIML,2,1);if (xn>=0){return (rLRRTc());} else if (spcRM()){return (rLTRRSy());}return (rLostMSy(false));}function rLLRR2Sy(){var ptrn=PTGRR2;var msm=patC(ptrn,AIML,2,1);if (xn>=0){return (rLRRTc());} else if (spcRM()){return (rLTRRSy());}return (rLostMSy(false));}function rLCRSy(){for (var i=TN; i>=1; i--){if (!dOK[CCW[i]]&&dOK[CCW[i-1]]){return {cell:CCW[i-1]};}}return NOP;}function rM2R1Sy(){for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==ASF)&&view[CCW[i+1]].ant&&view[CCW[i+1]].ant.friend&&
(view[CCW[i+1]].ant.type==ASF)){if (i&1){} else {}if (dOK[CCW[i+7]]){return {cell:CCW[i+7]};} else {return NOP;}}}return (rLostMSy(true));}function rLostMSy(totally){if ((fdT>0)&&(mF==0)){for (var i=0; i<TN; i++){if ((view[CCW[i]].food>0)&&dOK[CCW[i]]){return {cell:CCW[i]};}}}if (totally&(fT==0)){if (((mC==PY)&&(sN[PY]==0))||((mC==PR)&&(sN[PR]==0))){return {cell:POSC,color:PP};}if (((mC==PG)&&(sN[PG]==0))||((mC==PC)&&(sN[PC]==0))||((mC==PB)&&(sN[PB]==0))||((mC==PP)&&(sN[PP]==0))){return {cell:POSC,color:PW};} else if ((sT[PG]==0)&&(((mC==PK)&&(sN[PK]==0))||((mC==PY)&&(sN[PY]==0))||((mC==PR)&&(sN[PR]==0)))){return {cell:POSC,color:PW};} else if ((mC!=PW)&&(sN[mC]>=4)){return {cell:POSC,color:PW};}}if ((mC==PG)&&(sL[PG]>=2)){return {cell:POSC,color:PW};} else if (((mC==PK)||(mC==PR))&&(sN[PK]+sN[PR]>=3)){return {cell:POSC,color:PW};}if (sN[PW]<=4){var preferredColors =[PG,PB,PC,PP,PY,PR,PK];for (var ci=0; ci<preferredColors.length; ci++){var c=preferredColors[ci];if (mC==c){break;}if (sN[c]>0){for (var i=1; i<TN; i++){if ((view[CCW[i]].color==c)&&dOK[CCW[i]]){return {cell:CCW[i]};}}}}}if (RW){for (var i=1; i<TN; i+=2){if (dOK[CCW[i]]){return {cell:CCW[i]};}}for (i=0; i<TN; i+=2){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;} else {return NOP;}}function rDHSy(){if (mQ==0){var c=CCW[xn+2];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+1]].ant){return {cell:CCW[xn+1],color:LA};}c=CCW[xn+6];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+7]].ant){return {cell:CCW[xn+7],color:LA};}} else {var c=CCW[xn+4];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+3]].ant){return {cell:CCW[xn+3],color:LA};}c=CCW[xn+6];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)&&!view[CCW[xn+7]].ant){return {cell:CCW[xn+7],color:LA};}c=CCW[xn+5];if (view[c].ant&&!view[c].ant.friend&&(view[c].ant.type==AQ)&&(view[c].ant.food>0)){if (!view[CCW[xn+3]].ant){return {cell:CCW[xn+3],color:LA};} else if (!view[CCW[xn+7]].ant){return {cell:CCW[xn+7],color:LA};}}}return NOP;}function rQSETc(){if (mC!=LT){return {cell:POSC,color:LT};}for (var i=0; i<TN; i++){if (view[CCW[i]].food>0){return {cell:CCW[i]};}}return NOP;}function rQSSTc(){for (var i=0; i<TN; i++){if ((view[CCW[i]].food>0)&&(dOK[CCW[i]])){return {cell:CCW[i]};}}return NOP;}function rQSTCTc(){if ((mC!=LCLR)&&(sN[mC]>=4)){if (sN[LT]==0){return {cell:POSC,color:LT};} else if (sN[LT]>=3){return {cell:POSC,color:LT};} else {for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LT)&&(view[CCW[i+2]].color!=LT)){return {cell:CCW[i+2],color:LT};}}return NOP;}} else if (sN[LT]==1){for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LT)&&(view[CCW[i+4]].color!=LCLR)){if (view[CCW[i+1]].color==LCLR){return { cell:CCW[i+1]};} else if (view[CCW[i+7]].color==LCLR){return { cell:CCW[i+7]};} else {return {cell:POSC,color:LT};}}}return {cell:POSC,color:LT};} else {return {cell:POSC,color:LT};}return NOP;}function rQSATc(){for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LCLR)&&(view[CCW[i+1]].color==LCLR)&&(view[CCW[i+2]].color==LCLR)){if ((view[CCW[i+3]].color==LCLR)&&(view[CCW[i+4]].color==LCLR)){return {cell:CCW[i+2]};}return {cell:CCW[i+1]};}}for (i=TN-1; i>=0; i--){if (view[CCW[i]].color!=LT){return {cell:CCW[i]};}}for (i=0; i<TN; i++){if (view[CCW[i]].color!=LT){return {cell:CCW[i],color:LCLR};}}return {cell:0,color:LCLR};}function rQSEvTc(){if (sN[LT]>0){for (var i=0; i<TN; i++){if (view[CCW[i]].color==LT){xn=i&6;}}if ( dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]&&dOK[CCW[xn+2]]&&dOK[CCW[xn+3]] ){return {cell:CCW[xn+1]};} else if (dOK[CCW[xn+5]]&&dOK[CCW[xn+6]]&&dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+3]]&&dOK[CCW[xn+4]]&&dOK[CCW[xn+5]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+5]]&&dOK[CCW[xn+6]]&&dOK[CCW[xn+7]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+1]]&&dOK[CCW[xn+2]]&&dOK[CCW[xn+3]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]){return {cell:CCW[xn]};} else {for (i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}} else {for (var i=0; i<TN; i++){if (dOK[CCW[i]]&&dOK[CCW[i+1]]&&dOK[CCW[i+2]]&&dOK[CCW[i+3]]&&dOK[CCW[i+4]]){return {cell:CCW[i+2]};}}for (i=0; i<TN; i++){if (dOK[CCW[i]]&&dOK[CCW[i+1]]&&dOK[CCW[i+2]]){return {cell:CCW[i+1]};}}for (i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}return NOP;}function rQHTc(){var ptrn=PTHOME;var msm=patC(ptrn,POSC,0,1);if (msm!=0){var cc=fwdWrong[0];return {cell:cc.v,color:ptrn[cc.p]};} else {return NOP;}}function rGGTc(){var ptrn=PTGARDEN;var msm=patC(ptrn,POSC,0,1);if (msm!=0){var cc=fwdWrong[0];return {cell:cc.v,color:ptrn[cc.p]};} else {return NOP;}}function rUFCRTc(){var ptrn;var msm;if (mC==LRM0){ptrn=PTFRM0;msm=patC(ptrn,AIMU,4,1);if ((xn<0)&&(eT>0)){ptrn=PTFRM1;msm=patC(ptrn,AIMU,4,1);}if ((xn<0)&&(eT>0)){ptrn=PTFRM2;msm=patC(ptrn,AIMU,4,1);}} else if (mC==LRM2){ptrn=PTFRM2;msm=patC(ptrn,AIMU,4,1);if ((xn<0)&&(eT>0)){ptrn=PTFRM0;msm=patC(ptrn,AIMU,4,1);}if ((xn<0)&&(eT>0)){ptrn=PTFRM1;msm=patC(ptrn,AIMU,4,1);}} else if (mC==LRM1){ptrn=PTFRM1;msm=patC(ptrn,AIMU,4,1);if ((xn<0)&&(eT>0)){ptrn=PTFRM2;msm=patC(ptrn,AIMU,4,1);}if ((xn<0)&&(eT>0)){ptrn=PTFRM0;msm=patC(ptrn,AIMU,4,1);}} else if (mC==LRM1_WRP){ptrn=PTGRM1_WRP;msm=patC(ptrn,AIMR,1,1);}if ((xn<0)&&spcRR1()){return (rUPSSy());}if (xn<0){return (rLostMSy(false));}if (msm==0){if (fdL>0){if ((view[CCW[xn+7]].food>0)&&dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if ((view[CCW[xn+3]].food>0)&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};}}if ((mC==LRM1)&&(view[CCW[xn+3]].color!=LRR1X)&&(view[CCW[xn+3]].color!=LRR1U)&&!((mT==AJM)&&(view[CCW[xn+3]].color==LRR1V))&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};}if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};}return NOP;}for (var i=0; i<TN; i++){var ce=CCW[xn+i];if (view[ce].ant&&view[ce].ant.friend&&(view[ce].ant.type==AE)){if ((2<=i)&&(i<=4)){var msmSaved=msm;var fwdWrongSaved=Array.from(fwdWrong);var rearWrongSaved=Array.from(rearWrong);xn=xn % 4+4;msm=patC(ptrn,POSC,0,1);if (msm<msmSaved){xn=xn % 4+4;msm=msmSaved;fwdWrong=fwdWrongSaved;rearWrong=rearWrongSaved;} else {}break;}}}if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}return NOP;}function rUCRTc(){var ptrn;var msm;if (mC==LRM0){ptrn=PTGRM0;msm=patC(ptrn,AIMU,4,2);if ((xn<0)&&spcRR1()){return (rUPSSy());}if ((xn<0)&&(eT>0)){ptrn=PTGRM1;msm=patC(ptrn,AIMU,4,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM2;msm=patC(ptrn,AIMU,4,2);}} else if (mC==LRM2){ptrn=PTGRM2;msm=patC(ptrn,AIMU,4,2);if ((xn<0)&&(eT>0)){ptrn=PTGRM0;msm=patC(ptrn,AIMU,4,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM1;msm=patC(ptrn,AIMU,4,2);}} else if (mC==LRM1){ptrn=PTGRM1;msm=patC(ptrn,AIMU,4,2);if ((xn<0)&&(eT>0)){ptrn=PTGRM2;msm=patC(ptrn,AIMU,4,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM0;msm=patC(ptrn,AIMU,4,2);}} else if (mC==LRM1_WRP){ptrn=PTGRM1_WRP;msm=patC(ptrn,AIMR,1,1);}if ((xn<0)&&spcRR1()){return (rUPSSy());}if (xn<0){return (rLostMSy(true));}if (msm==0){if (fdL>0){if ((view[CCW[xn+7]].food>0)&&dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if ((view[CCW[xn+3]].food>0)&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};}}if ((mC==LRM1)&&(view[CCW[xn+3]].color!=LRR1X)&&(view[CCW[xn+3]].color!=LRR1U)){if ((((mT==AJM)&&(view[CCW[xn+3]].color==LRR1))||((mT==ASM)&&(view[CCW[xn+3]].color==LRR1V)))&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};}}if (mC==LRM0&&(view[CCW[xn+5]].color==LRM1_WRP)&&!(view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend)){return {cell:CCW[xn+5],color:LRM1};}var c=CCW[xn+5];if (dOK[c]){return {cell:c};} else if (view[c].ant&&view[c].ant.friend){var evade=false;if (view[c].ant.food>0){evade=true;} else if (view[CCW[xn+1]].ant&&view[CCW[xn+1]].ant.friend&&(view[CCW[xn+1]].ant.food==0)){evade=true;}if (evade){if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else {return NOP;}} else {return NOP;}}} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}return NOP;}function rUESTc(ptrn,msm){switch (view[CCW[xn+3]].color){case LMX_M0:return {cell:CCW[xn+3],color:LMX_M1IN};case LMX_M1OUT:if (mT==ASM){return {cell:CCW[xn+3],color:LMX_M2IN};}break;case LMX_M2OUT:if (mT==ASM){return {cell:CCW[xn+3],color:LMX_M3IN};}break;case LMX_M3OUT:break;case LMX_M1IN:case LMX_M2IN:case LMX_M3IN:if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if ((msm==0)&&dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else {break;}default:break;}if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};}return NOP;}function runUMLeaveRRTactic(){if (view[CCW[xn+7]].ant&&view[CCW[xn+7]].ant.friend&&dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return NOP;}}function rUDSTc(ptrn,msm){var c=CCW[xn+1];if ((msm==0)&&(fdL>0)&&(view[CCW[xn+3]].food+view[CCW[xn+7]].food>0)){if (mC!=LMMF){return {cell:POSC,color:LMMF};} else if (view[CCW[xn+5]].color!=LMMH){return {cell:CCW[xn+5],color:LMMH};} else if ((view[CCW[xn+3]].food>0)&&dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if ((view[CCW[xn+7]].food>0)&&dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};}} else if ((msm<0)&&!(view[c].ant&&view[c].ant.friend)){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (msm>=0){if (dOK[c]){return {cell:c};} else {if (view[c].ant&&view[c].ant.friend){if (view[c].ant.food>0){if ((view[CCW[xn]].color==LCLR)&&dOK[CCW[xn]]){return {cell:CCW[xn]};} else if ((view[CCW[xn+2]].color==LCLR)&&dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else {return NOP;}} else {var c=CCW[xn+5];if (view[c].ant&&view[c].ant.friend&&(view[c].ant.food==0)){if (view[c].color==LMMH){if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else {return NOP;}} else if (mC!=LMMH){return {cell:POSC,color:LMMH};} else {return NOP;}} else {return NOP;}}} else {return NOP;}}}return NOP;}function rUWRTc(ptrn,msm){if (view[CCW[xn+3]].color!=LMS_WRP){return {cell:CCW[xn+3],color:LMS_WRP};} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};}return NOP;}function rLLLWTc(){if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else {return NOP;}}function rLLRWTc(){if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else {return NOP;}}function rLWRTc(ptrn,msm){if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else {return NOP;}}function rLASTc(ptrn,msm){var c=CCW[xn+5];if ((msm<0)&&!(view[c].ant&&view[c].ant.friend)){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (mC==LMMF){return {cell:POSC,color:LCLR};} else if (view[CCW[xn+5]].color==LMMH){return {cell:CCW[xn+5],color:LCLR};} else if (msm>=0){if (dOK[c]){return {cell:c};} else if ((view[c].food>0)&&(eT==0)){if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};}}}return NOP;}function rLLSTc(ptrn,msm){if (msm<0){if (view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend){return NOP;}var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}switch (view[CCW[xn+3]].color){case LMX_M1IN:return {cell:CCW[xn+3],color:LMX_M1OUT};case LMX_M2IN:return {cell:CCW[xn+3],color:LMX_M2OUT};case LMX_M3IN:default:return {cell:CCW[xn+3],color:LMX_M3OUT};case LMX_M1OUT:case LMX_M2OUT:case LMX_M3OUT:if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};}break;}return NOP;}function rLCRTc(){var ptrn;var msm;var trust=(aF[AE]>0 ? 1 : 0);if (mC==LRM0){ptrn=PTGRM0;msm=patC(ptrn,AIMD,3,2-trust);if ((xn<0)&&(eT>0)){ptrn=PTGRM1;msm=patC(ptrn,AIMD,3,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM2B;msm=patC(ptrn,AIMD,3,2);}} else if (mC==LRM2){ptrn=PTGRM2B;msm=patC(ptrn,AIMD,3,2-trust);if ((xn<0)&&(eT>0)){ptrn=PTGRM0;msm=patC(ptrn,AIMD,3,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM1;msm=patC(ptrn,AIMD,3,2);}} else if (mC==LRM1){ptrn=PTGRM1;msm=patC(ptrn,AIMD,3,2-trust);if ((xn<0)&&(eT>0)){ptrn=PTGRM2B;msm=patC(ptrn,AIMD,3,2);}if ((xn<0)&&(eT>0)){ptrn=PTGRM0;msm=patC(ptrn,AIMD,3,2);}} else if (mC==LRM1_WRP){ptrn=PTGRM1;msm=patC(ptrn,AIMD,3,2);if (xn>=0){if (view[CCW[xn+3]].color!=LRR1X){return {cell:CCW[xn+3],color:LRR1X};} else if (!(view[CCW[xn+7]].ant&&view[CCW[xn+7]].ant.friend)){return {cell:POSC,color:LRM1};}}}if (xn<0){if (spcRR1()){return (rLDSSy());}return (rLostMSy(true));}if (msm==0){var c=CCW[xn+1];if (dOK[c]){return {cell:c};} else if (view[c].ant&&view[c].ant.friend){var evade=false;if (view[c].ant.food==0){evade=true;} else if (view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&(view[CCW[xn+5]].ant.food>0)){evade=true;}if (evade){if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else {return NOP;}} else {return NOP;}}} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}return NOP;}function rLRLTc(){if (view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend&&
dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else {return NOP;}}function rLRRTc(){if (view[CCW[xn+7]].ant&&view[CCW[xn+7]].ant.friend&&dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else {return NOP;}}function rMNGTc(){for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==ASF)){if (view[CCW[i]].color==LCLR){if (i&1){if ((view[CCW[i+3]].color==LG5)&&dOK[CCW[i+3]]){return {cell:CCW[i+3]};}} else {if ((view[CCW[i+4]].color==LG6)&&dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else if ((view[CCW[i+3]].color==LG5)&&dOK[CCW[i+3]]){return {cell:CCW[i+3]};}}return (rLostMSy(true));} else if (dOK[CCW[i+1]]){return {cell:CCW[i+1]};}}}return NOP;}function rELGTc(){var ptrn=PTFRL1G;var msm;for (var i=0; i<TN; i+=2){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==ASF)){xn=i;break;}}msm=patC(ptrn,AIMU,0,1);if (xn<0){return NOP;} else if ((msm==0)&&dOK[CCW[xn+5]]&&((view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend)||
(view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend))){return {cell:CCW[xn+5]};} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (msm>0){var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {return NOP;}return NOP;}function rEBRTc(){var ptrn;var msm;if (mC==LRL0){for (var i=0; i<TN; i+=2){var c=CCW[i];if ((view[c].color==LRM0)&&view[c].ant&&view[c].ant.friend&&((view[CCW[i]].ant.type==AJM)||(view[CCW[i]].ant.type==ASM))){ptrn=PTFRL2;msm=patC(ptrn,AIMU,1,1);if (xn>=0){break;}}}if (xn<0){ptrn=PTFRL0;msm=patC(ptrn,AIMU,1,1);}if (xn<0){ptrn=PTFRL2;msm=patC(ptrn,AIMU,1,1);}if ((xn<0)&&(eT>0)){ptrn=PTFRL1;msm=patC(ptrn,AIMU,1,1);}if (xn<0){return rECLRETc();}} else if (mC==LRL1){ptrn=PTFRL1;msm=patC(ptrn,AIMU,1,1);if ((xn<0)&&(eT>0)){ptrn=PTFRL2;msm=patC(ptrn,AIMU,1,1);}if ((xn<0)&&(eT>0)){ptrn=PTFRL0;msm=patC(ptrn,AIMU,1,1);}if (xn<0){return rECLRETc();}} else if ((mC==LRR2)&&(sL[LRL1]>=1)&&(sL[LRL0]==0)){return {cell:POSC,color:LRL0};}if ((msm==0)&&dOK[CCW[xn+5]]&&((view[CCW[xn+3]].ant&&view[CCW[xn+3]].ant.friend)||
(view[CCW[xn+4]].ant&&view[CCW[xn+4]].ant.friend))){return {cell:CCW[xn+5]};} else if (msm<0){var cc=fwdWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else if (msm>0){var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};} else {return NOP;}return NOP;}function rECLRETc(){var ptrn;var msm;for (var i=3; i<TN+2; i+=2){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
((view[CCW[i]].ant.type==AJM)||(view[CCW[i]].ant.type==ASM))){xn=i-3;if (mC==LRL0){ptrn=PTFRL0;msm=patC(ptrn,AIMR,1,0.3);if (msm==PTNOM){ptrn=PTFRL2;msm=patC(ptrn,AIMR,1,0.3);}} else if (mC==LRL1){ptrn=PTFRL1;msm=patC(ptrn,AIMR,1,0.3);}if (msm>0){var cc=rearWrong[0];return {cell:cc.v,color:fixup(ptrn[cc.p])};}return NOP;}}return NOP;}function patC(ptrn,targetCell,qG,wt){if (xn>=0){return (patCO(ptrn,targetCell,qG,wt,xn));} else {var msm;for (var o=0; o<TN; o+=2){msm=patCO(ptrn,targetCell,qG,wt,o);if (xn>=0){return msm;}}return PTNOM;}}function patCO(ptrn,targetCell,qG,wt,ortn){var fwdFCs=FWD_CELLS[targetCell];var totDscs=0;fwdWrong=[];rearWrong=[];if ((Array.isArray(ptrn[POSC])&&!ptrn[POSC][mC])||
((ptrn[POSC]>0)&&(mC!=ptrn[POSC]))){if (fwdFCs[POSC]){fwdWrong.push({p:POSC,v:POSC});totDscs+=1;} else {rearWrong.push({p:POSC,v:POSC});totDscs+=wt;}}if ((xn<0)&&(totDscs>qG)){return PTNOM;}var jFrom=0;switch (targetCell){case AIMU:jFrom=4;break;case AIML:jFrom=6;break;case AIMR:jFrom=2;break;case AIMD:case POSC:default:break;}for (var j=jFrom; j<TN+jFrom; j++){var posP=CCW[j];var posV=CCW[ortn+j];var c=view[posV].color;if ((Array.isArray(ptrn[posP])&&!ptrn[posP][c])||
((ptrn[posP]>0)&&(c!=ptrn[posP]))){if (fwdFCs[posP]){fwdWrong.push({p:posP,v:posV});totDscs+=1;} else {rearWrong.push({p:posP,v:posV});totDscs+=wt;}}if ((xn<0)&&(totDscs>qG)){return PTNOM;}}if ((xn<0)){xn=ortn;}if (fwdWrong.length==0){return (totDscs);} else {return (-totDscs);}}function isQc0(color){return (LCRQCVAL[color]&&(LCRQC_VALUE[color]==0));
}function isQc2(color){return (LCRQCVAL[color]&&(LCRQC_VALUE[color]==2));
}function incQc(color){if (LCRQCVAL[color]){if (LCRQC_VALUE[color]>=QCPERD){return LCRQC[0];} else {return (LCRQC[(LCRQC_VALUE[color]+1) % QCPERD]);
}} else {return undefined;}}function isSc0(color){return (LCRSCVAL[color]&&(LCRSC_VALUE[color]==0));
}function isSc1(color){return (LCRSCVAL[color]&&(LCRSC_VALUE[color]==1));
}function incSc(color){if (LCRSCVAL[color]){return (LCRSC[(LCRSC_VALUE[color]+1) % SCPERD]);
} else {return undefined;}}function spcMS(){return (((mC==LCLR)||((mF+fdL>0)&&(mC==LMMF))||((mF>0)&&(mC==LMMH)))&&(sN[LMR0]+sN[LML1] +sN[LMR2]+sN[LML3]>=2)&&(sN[LCLR]>=3)&&(sN[LMMF] +sN[LMMH] +sN[PB]<=3)); }function spcRM(){return (LCRGRM_ALL[mC]&&(sT[LRL0]+sT[LRL1]>=3)&&(sN[LRL0]>=1)&&(sN[LRR0]+sN[LRR2]>=2)&&(sT[LRM0]+sT[LRM1_WRP] +sT[LRM1]+sT[LRM2]>=2)&&(sT[LCLR]<=4));}function spcRL1(){return ((mC==LRL1)&&(sL[LRL0]>=2)&&(sD[LRM0]>=1)&&(sL[LRM1_WRP]+sL[LRM1]>=1)&&(sD[LRM2]>=1));}function spcRL02(){return ((mC==LRL0)&&(sL[LRL1]+sL[LRL2]>=2)&&(sN[LRM0]>=1)&&(sD[LRM1_WRP]+sD[LRM1]>=1));}function spcRR0(){return ((mC==LRR0)&&(sL[LRM1]==0)&&(sD[LRM1]+sD[LRM1_WRP]>=1)&&(sL[LMR0]>=1)&&(sL[LRR2]>=1));}function spcRR1(){return (LCRGRR1[mC]&&(sN[LRR0]>=2)&&(sL[LRR2]>=1)&&(sD[LRM0]>=1)&&(sN[LCLR]<=3)&&(sL[LRM1] +sL[LRM1_WRP]>=1));}function spcRR2(){return ((mC==LRR2)&&(sD[LCLR]>=1)&&(sD[LRM0]>=1)&&(sD[LRM1]+sD[LMR0]>=2)&&(sL[LRR0]>=2));}function spcMS0R(){return((mC==LCLR)&&(sL[LMR0]>=1)&&(sL[LRR1U]>=1)&&(sD[LRR2]>=1)&&(sD[LRR0]>=1));}function spcMS0ROut(){return ((mC==LCLR)&&(sL[LMR0]+sL[LRR1V]>=2)&&(sD[LRR2]>=2)&&(sD[LRR0]>=1));}function spcMS0W(){return ((mC==LCLR)&&(sD[LRL0]>=3)&&(sL[LRL1]>=1)&&(sL[LMS_WRP]>=2)&&(sN[LCLR]>=2));}function spcMFL(){return ((sL[LMMF]>=1)&&(sD[LMMH]>=1)&&(sT[LCLR]>=2)&&(sT[LML1]+sT[LML3]>=1));}function spcMFR(){return ((sL[LMMF]>=1)&&(sD[LMMH]>=1)&&(sT[LCLR]>=2)&&(sT[LMR0]+sT[LMR2]>=1));}function fixup(ptrnCell){if (Array.isArray(ptrnCell)){for (var i=1; i<=9; i++){if (ptrnCell[i]){return i;}}return LCLR;} else {return ptrnCell;}}
```
(On trichoplax's and dzaima's advice - for which many thanks! - this has been uglified to fit within the PPCG size limits, at the expense of readability. **Edit:** The unabridged original, amply commented and with meaningful variable and function names, is now [available on GitHub](https://github.com/GNiklasch/formic-windmill).)
After the usual initial scramble, the Windmill Queen launches *three* rails, aiming to have an area closer to it scoured more thoroughly and reduce rail travel times, and adding redundancy. There's a little garden on the fourth side, with berries red and blue and black.
We dispense with Miners on a Rail's Repairer. (Their very long rail is a mixed blessing... it tends to attract vampires.) Instead, we have an Engineer on each rail. Their original purpose was to tell miners whether they are extending the rail (viz. when they can see the engineer) versus repairing it (when they can't), but this got somewhat buried as the code evolved. They now look after a few minor tasks, such as helping to prevent rails from sprouting upside-down continuations.
A shaft 3 cells wide by 1000 cells deep is expected to contain 3 food on average, and only 4% of all shafts of this depth won't contain any. Once we estimate from the amount of hoarded food that the rails have grown long enough to make it worthwhile, the queen will therefore begin to spawn senior miners who will re-inspect shafts previously explored by a junior miner. As in Miners on a Rail, we're prepared to handle shafts which wrap around the arena to the back (left) side of a rail.
The Windmill Queen also employs two other staff: A Gardener, and a Secretary. They're the same ant type, doing one thing or the other depending on their locations relative to the queen and to each other. They help the queen to orchestrate the creation of the engineers and of the first few junior miners, and then assist the queen in running a clock: an oscillator that will ring every 85 moves (when undisturbed).
This master clock, together with the amount of hoarded food and the random 1-of-4 orientations we receive, decouples the creation of miners from the arrival of food, and regulates the rate at which further miners will be spawned. When the queen has just settled, all incoming food is quickly converted into more miners until the rate of incoming food reaches about 9 per 1000 moves (which requires about a dozen productive miners). Then the clock cycle becomes the limiting factor and we start hoarding food. Later as the amount of food increases, we throttle down the spawning rate to at most 6 new miners per 1000 moves and later at most 3, and finally stop procreating altogether. A ratchet mechanism prevents the queen from expending too much food on spawning when all rails are blocked or damaged.
Even without any major damage, the mining efficiency will decrease a lot as each game unfolds. Initially, we expect a miner drilling at half light speed and returning at light speed to deliver 1 food every 1000 moves on average. Towards the end, it's more like 0.12-0.14 food per miner per 1000 moves. Travelling the longer rails, painting the mostly white shaft pattern onto a no longer mostly white canvas, and repairing shafts and rails all take time; miners get stuck, or lost, or tied up in paintball skirmishes with opponents.
Our miners make an effort to extract themselves from any major traffic jams.
And there's a rudimentary immune system to deal with unfriendly intruders.
Trying to steamroll our backyard is not recommended. Our staff won't be amused.
The main drawback is that the Windmill queen needs 8 food to afford her initial staff out of pocket, so the scrambling phase is rather long, giving other similar contenders a head start. If our nest gets overrun and the rails wiped out before we have hoarded any food, the day will end badly for us. Later, and with at least one rail running or repairable, we can usually keep going, or at least hold on to (most of) what we already have.
The implementation treats neighbor cells as numbered counter-clockwise, starting at a corner, with an array (`CCW`) to translate these numbers into the controller's `view` subscripts. When we have a need (and are able) to pin down our sense of North, we set our compass, a base subscript into `CCW`. The ant function always starts by taking stock of its surroundings, in particular recording a spectrum (how often each color occurs), and then branches out by ant type and situation along a multi-level decision tree of strategies and tactics. This makes it feasible to handle a host of weird special cases whilst dealing with the most common situations very quickly. The tree has almost 200 leaves which paint a cell or take a step or create an ant, and more than 70 which do nothing - distilled from the 2^27 possible view color patterns multiplied by possible ants in view, food in view, and food carried.
Here's an ASCII rendering of the hub geometry:
```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | | | | ^ |MR2| | v |MR2| | ^ | | | | | | | | |
| | | | | i | | | a | r | rail 2 | | | | | | | |
+---+---+---+---+-n-+---+---+-c-+---+---+---+---+---+---+---+---+---+---+---+
| | | |ML1| | |ML1| a | |RL0|RM0|RR0| | | | | | | |
| | | | y | u | | y | t | | c | r | g | | | | | | | |
+---+---+---+---+-s-+---+---+-e-+---+---+---+---+---+---+---+---+---+---+---+
| | | |MX | e |MR0|MX | d |MR0|RL2|RM2|RR2|MX |ML1| |ML3| |ML1| |
| | | | c | | k | y | | k | c | g | y | c | y | | c | | y | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| |RR1|RR0|RR2|RR1|RR0|RR2|RR1|RR0|RL1|RM1|RR1| | shaft in use | >| |
| r| | g | y | r | g | y | y | g | g | b | r | | | | | | | |
+--a+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| <i|RM1|RM0|RM2|RM1|RM0|RM2|RM1|RM0|RL0|RM0|RR0|MR0| |MR2| |MR0| | |
| l| b | r | g | b | r | g | b | r | c | r | g | k | | r | | k | | |
+-- +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 3|RL1|RL0|RL2|RL1|RL0|RL2|RL1|RL0|*Q*|RL0|RL1|RL2|RL0|RL1|RL2|RL0|RL1| |
| | g | c | c | g | c | c | g | c |clk| c | g | c | c | g | c | c | g |r |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+a--+
| | | | | | | |G3 |Grd|Sec|RM0|RM1|RM2|RM0|RM1|RM2|RM0|RM1|i >|
| | | | | | | | k |r/y|clk| r | b | g | r | b | g | r | b |l |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ --+
| | | | | | | |G4 |G5 |G6 |RR0|RR1|RR2|RR0|RR1|RR2|RR0|RR1|1 |
| | | | | | | | r | k | b | g | y | y | g | r | y | g | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| | | | | | | | | | |MR0| |MX |MR0| |MX | | | |
| | | | | | | | | | | k | | y | k | | c | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```
(showing MX and RR1 colors during and after the first descent by a junior miner).
There are dozens of loose ends. (E.g., we do clean food off the rail because it could become an obstacle to laden miners, but some food just off the rail won't be eaten since the extra complexity just didn't seem worth it.) The good-enough is the enemy of the better...
**v1.1** fixes a cause for disqualification and adds a few minor enhancements.
**v1.2** adds a few more fixes and enhancements.
**v1.3** adds previously mixing `var` declarations to make this work on strict-mode controllers like [Dave's](https://davidje13.github.io/koth-webplayer/formic.htm); no functional changes.
**v1.4** fixes a misunderstanding between queen and gardener about the use of garlic (as Vampires arriving along rail3 are going to find out), cures a stupid pattern-definition bug, and improves a few edge cases.
**v1.5** teaches the Windmill a new trick - wanna see an ant-elope?
**v1.6** lets miners scribble patterns into vast greenish expanses, refines the burglar alarm at home, and deals with enemy queens elsewhere in a slightly more elastic way, plus minor touch-ups.
**v1.7** aside from minor resilience fixes uses a [Lightspeed](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/153688#153688)-style startup phase, not to settle earlier but to settle with a larger stock of food. (We need 7 miners to exceed the expected food return rate of a lightspeed tandem, so no point in switching to mining before we can afford them.)
**v1.8** fixes a deadlock in the Lightspeed-phase logic and, more importantly, cures a spawning bug introduced in v1.6 which had resulted in disqualification.
**v1.9** fixes another exotic disqualifying bug, tentatively addresses some congestion cases in shafts, and attempts to deal with the latest vampiric inventions.
**v2.0** enables the queen to abandon an existing hub altogether when in dire need, resorting to Lightspeed-style scrambling, and with luck re-settling later to found a new mill elsewhere, far from the original site.
Experiments with a variable-speed Food Controlled Oscillator, on the other hand, did not result in convincing improvements. Sending out more miners earlier would somewhat increase some competitors' accident rates, but also our own. The FCO code remains in place but has been disabled for now.
**v2.1** addresses three edge cases where workers had better move than stay put.
[Answer]
# Black Hole
```
var COLOR=8
var COLOR2=7
var COLOR3=2
var LOCKDOWN=8
var orthogonals = [1, 3, 7, 5]
var isQueen = view[4].ant.type==5
var rotationsCW = [1,2,5,8,7,6,3,0]
var rotationsCCW = [3,6,7,8,5,2,1,0]
var matchStates = [
{state:[0,0,0,
0,1,0,
0,0,0],move:0,back:0,fill:true},
{state:[1,0,0,
0,1,0,
0,0,0],move:1,back:3,fill:true},
{state:[0,1,0,
1,0,0,
0,0,0],move:0,back:0,fill:false},
{state:[0,1,0,
0,0,1,
0,0,0],move:2,back:2,fill:false},
{state:[0,0,1,
0,0,1,
0,1,0],move:8,back:2,fill:false},
//5:
{state:[1,0,0,
1,0,0,
0,1,0],move:2,back:6,fill:false},
{state:[0,1,0,
0,1,0,
0,0,0],move:2,back:0,fill:false},
{state:[1,0,0,
1,1,0,
0,0,0],move:1,back:6,fill:false},
{state:[0,1,1,
0,1,0,
0,0,0],move:5,back:0,fill:false},
{state:[0,1,0,
1,1,0,
0,0,0],move:2,back:6,fill:false},
//10:
{state:[1,1,0,
0,1,0,
0,0,0],move:2,back:3,fill:false},
{state:[1,1,0,
1,1,0,
0,0,0],move:2,back:6,fill:false},
{state:[0,1,1,
0,1,1,
0,0,0],move:8,back:0,fill:false},
{state:[1,1,1,
0,1,0,
0,0,0],move:5,back:3,fill:false},
{state:[1,0,0,
1,1,0,
1,0,0],move:1,back:7,fill:false},
//15:
{state:[0,1,0,
1,1,1,
0,0,0],move:8,back:6,fill:false},
{state:[1,1,1,
1,1,0,
0,0,0],move:5,back:6,fill:false},
{state:[1,0,0,
1,1,0,
1,1,0],move:1,back:8,fill:false},
{state:[1,1,0,
1,1,0,
1,0,0],move:2,back:7,fill:false},
{state:[1,1,1,
0,1,1,
0,0,0],move:8,back:3,fill:false},
//20:
{state:[1,1,1,
0,0,1,
0,0,1],move:7,back:3,fill:true},
{state:[1,1,1,
1,0,0,
1,0,0],move:5,back:7,fill:true},
{state:[1,0,0,
1,0,0,
1,1,1],move:1,back:5,fill:true},
{state:[0,0,1,
0,0,1,
1,1,1],move:3,back:1,fill:true},
{state:[1,1,1,
0,1,1,
0,0,1],move:7,back:3,fill:true},
//25:
{state:[1,1,1,
1,1,0,
1,0,0],move:5,back:7,fill:true},
{state:[1,0,0,
1,1,0,
1,1,1],move:1,back:5,fill:true},
{state:[1,1,1,
1,1,1,
0,0,0],move:8,back:6,fill:true},
{state:[1,1,1,
1,1,1,
1,0,0],move:8,back:7,fill:true},
{state:[1,1,1,
1,1,0,
1,1,0],move:5,back:8,fill:true},
{state:[1,1,1,
1,1,1,
1,1,0],move:8,back:8,fill:true},
//30:
{state:[1,1,1,
1,1,1,
1,0,1],move:7,back:7,fill:true},
{state:[1,1,1,
1,1,0,
1,1,1],move:5,back:5,fill:true},
{state:[1,0,1,
1,1,1,
1,1,1],move:1,back:1,fill:true},
{state:[1,1,1,
0,1,1,
1,1,1],move:3,back:3,fill:true},
{state:[1,1,1,
1,1,1,
1,1,1],move:9,back:9,fill:false},
//35:
]
function matchesColor(c) {
return c==COLOR || c==COLOR2 || c==COLOR3 || (view[4] == COLOR3 && c == LOCKDOWN)
}
function matchesNonLineColor(c) {
return c==COLOR || c==COLOR2
}
function isAnyColor(c) {
var r=0
for(var i=0;i<9;i++) {
if(view[i].color == c) r++
}
return r
}
function howManyAnts() {
var r=0;
for(var i=0;i<9;i++) {
if(view[i].ant != null) r++
}
return r
}
function deRotate(m, amt) {
if(m == 4 || m < 0 || m > 8 || amt == 0) return m
if(amt > 0)
return rotationsCW[(rotationsCW.indexOf(m)+amt)%8]
amt = -amt
return rotationsCCW[(rotationsCCW.indexOf(m)+amt)%8]
}
function deRotateSide(m, amt) {
return deRotate(m,amt*2)
}
function matchWhileLost(sides) {
var c=0;
for(var i=0;i<9;i++) {
if(view[i].color == COLOR3) c++
if(view[i].color == COLOR3 && i%2 == 0) c+=10
}
if(c == 2) {
if(view[0].color == COLOR3 || view[2].color == COLOR3 || view[6].color == COLOR3 || view[8].color == COLOR3) {
return {cell:4,color:COLOR3}
}
if(view[0].ant == null)
return {cell:0}
if(view[2].ant == null)
return {cell:2}
if(view[6].ant == null)
return {cell:6}
if(view[8].ant == null)
return {cell:8}
}
c = 0
sides[4] = 0
var toMatch =[{state:[1,1,1,
2,0,2,
0,1,0]},
{state:[0,2,1,
1,0,1,
0,2,1]},
{state:[0,1,0,
2,0,2,
1,1,1]},
{state:[1,2,0,
1,0,1,
1,2,0]}]
for(var m=0;m<4;m++) {
var score=0
for(var j=0;j<9;j++) {
if(j!=4) {
if(sides[j] == COLOR3 && toMatch[m].state[j] == 1) {
score++
}
if(sides[j] != COLOR3 && (toMatch[m].state[j] == 0 || toMatch[m].state[j] == 2)) {
score++
}
if(sides[j] == COLOR3 && toMatch[m].state[j] == 2) {
score--
}
}
}
if(score >= 6) {
var clearOrder=[1,0,2]
for(var r=0;r<clearOrder.length;r++) {
var s = deRotateSide(clearOrder[r],m)
if(view[s].color == COLOR3) {
if(view[s].ant == null)
return {cell:s,color:COLOR}
else
return {cell:4}
}
}
}
}
return null
}
function matchBlueStyle(sides) {
return null
}
function bestMatch(sides) {
var c=0;
for(var i=0;i<9;i++) {
if(sides[i] > 1) c++
}
if(!isQueen && view[4].ant.food > 0) {
c++
sides[4] = 8
}
if(c <= 1) {
return {state:matchStates[0],rot:0,fill:matchStates[0].fill}
}
c = 0
while(!matchesColor(sides[0]) && !matchesColor(sides[1]) && c < 4) {
var s2 = [0,0,0,0,0,0,0,0,0]
s2[0] = sides[2]
s2[1] = sides[5]
s2[2] = sides[8]
s2[3] = sides[1]
s2[5] = sides[7]
s2[6] = sides[0]
s2[7] = sides[3]
s2[8] = sides[6]
sides = s2
c++
}
while(c < 8 && (matchesColor(sides[0]) || matchesColor(sides[1])) && matchesColor(sides[8])) {
var s2 = [0,0,0,0,0,0,0,0,0]
s2[0] = sides[2]
s2[1] = sides[5]
s2[2] = sides[8]
s2[3] = sides[1]
s2[5] = sides[7]
s2[6] = sides[0]
s2[7] = sides[3]
s2[8] = sides[6]
sides = s2
c++
}
var bestState = null
var bestMatchScore = -1
for(var i = 0; i < matchStates.length; i++) {
var score=0
for(var j=0;j<9;j++) {
if(j!=4) {
if(matchesColor(sides[j]) && matchStates[i].state[j] == 1) {
score++
}
if(!matchesColor(sides[j]) && matchStates[i].state[j] == 0) {
score++
}
}
}
if(score >= bestMatchScore) {
//console.log("state " + i + ": " + score);
bestMatchScore = score
bestState = matchStates[i]
}
}
return {state:bestState,rot:c,fill:bestState.fill,score:bestMatchScore}
}
function getHighestWorker() {
var r=0;
for(var i=0;i<9;i++) {
if(i != 4 && view[i].ant != null) {
if(view[i].ant.friend && view[i].ant.type > r) r = view[i].ant.type
}
}
return r
}
function pathLost() {
var i, j
var safe = []
for(var q=0;q<9;q++) {
if(q != 4 && view[q].ant != null && view[q].ant.friend && (view[q].ant.type > view[4].ant.type && view[4].ant.food == 0 && view[q].ant.type < 5)) {
if(!matchesColor(view[4].color)) return {cell:4,color:COLOR}
return {cell:4}
}
}
if (matchesNonLineColor(view[4].color)) {
var myView = [0,0,0,0,0,0,0,0,0]
for(var i=0; i < 9; i++) {
myView[i] = view[i].color
if(!isQueen && view[4].ant.food > 0 && view[i].food > 0) {
myView[i] = COLOR;
}
}
var ret = matchWhileLost(myView)
if(ret == null)
return {cell:4, color:COLOR3}
else {
if(!(view[ret.cell].ant != null && view[ret.cell].ant.friend == false) && (view[4].ant.food == 0 || view[ret.cell].food == 0 || isQueen))
return ret
}
}
for (i=0; i<view.length; i++) {
if (view[i].ant === null && (view[4].ant.food == 0 || view[i].food == 0 || isQueen)) {
safe.push(i);
}
}
for (i=0; i<4; i++) {
j = (i+2) % 4
if (matchesNonLineColor(view[orthogonals[i]].color) && view[orthogonals[j]].color == COLOR3) {
if (view[orthogonals[i]].ant == null) {
return {cell:orthogonals[i]}
} else if (safe.length > 0) {
return {cell:safe[0]}
} else if (view[0].ant === null && (view[4].ant.food == 0 || view[0].food == 0 || isQueen)) {
return {cell:0}
}
}
}
if (view[1].ant === null && (view[4].ant.food == 0 || view[1].food == 0 || isQueen)) {
return {cell:1}
} else {
if(!matchesColor(view[4].color)) return {cell:4,color:COLOR}
return {cell:4}
}
}
function isAllyAdjacentTo(view, place) {
var i = deRotate(place, 1)
var j = deRotate(place, -1)
if(view[i].ant != null && view[i].ant.friend && view[i].ant.type < 5) return 1
if(view[j].ant != null && view[j].ant.friend && view[j].ant.type < 5) return 1
if(orthogonals.indexOf(place) >= 0) {
i = deRotate(place, 2)
j = deRotate(place, -2)
if(view[i].ant != null && view[i].ant.friend && view[i].ant.type < 5) return 2
if(view[j].ant != null && view[j].ant.friend && view[j].ant.type < 5) return 2
}
return 0
}
function findOpenSpace(pos, dir) {
if(pos > 8 || pos < 0) return pos
if(view[pos].ant != null && view[pos].ant.friend && view[4].ant.food == 0) {
pos=deRotate(pos,4)
}
//var inc = dir>0?1:-1
var b = 0
while(view[pos].ant != null && b < 8) {
pos=deRotate(pos,dir)
b++
}
return pos
}
//end functions
function getReturn() {
var colToPlace=COLOR
var blueAmt = isAnyColor(COLOR2)
var myView = [0,0,0,0,0,0,0,0,0]
for(var i=0; i < 9; i++) {
myView[i] = view[i].color
if(!isQueen && view[4].ant.food > 0 && view[i].food > 0) {
myView[i] = COLOR;
}
if(!isQueen && view[4].ant.food == 0 && view[i].ant != null && view[i].ant.food > 0) {
if(!matchesColor(view[4].color)) return {cell:4,color:COLOR}
return {cell:4};
//myView[i] = COLOR;
}
if(view[i].ant != null && !view[i].ant.friend) {
myView[i] = COLOR;
}
}
if(isQueen) {
for(var i=0; i < 9; i++) {
if(i != 4 && !matchesColor(view[i].color) && view[i].ant != null) {
myView[i] = COLOR
}
}
}
//console.log("view:")
//console.log(myView)
//console.log("1")
var match = bestMatch(myView)
if(match.state.move != 9) {
var ctY = 0
var lastY = -1
var ctW = 0
var lastW = -1
for(var i=0; i < 9; i++) {
if(view[i].color == COLOR3) {
myView[i] = 8
ctY++
lastY = i
}
else if(!matchesColor(view[i].color)) {
ctW++
lastW = i
}
}
if(ctY > 0 && isQueen && view[4].ant.food > 0 && ctW >= 1) {
if(view[4].color != COLOR3 && matchesColor(view[4].color))
return {cell:4,color:COLOR3}
var tt = deRotate(lastW,-1)
if(view[tt].color != COLOR2)
return {cell:tt,color:COLOR2}
lastW = findOpenSpace(lastW,1)
return {cell:lastW}
}
else if(ctY >= 2 && ctW >= 3)
match = bestMatch(myView)
else if(ctY > 0 && view[lastY].ant == null && ctW >= 3) {
return {cell:lastY,color:1}
}
}
//console.log("2")
if(!isQueen) {
for(var i=0; i < 9; i++) {
if(view[i].ant != null && view[i].ant.type == 5 && view[i].ant.food > 0 && view[i].ant.food <= 2) {
if(view[4].ant.type == 4)
return {cell:4,color:COLOR2}
return {cell:4}
}
}
}
//console.log("3")
if(blueAmt > 0 && view[4].color != COLOR3 && match.state.move != 9) {
//console.log("Some blue")
var mb = match.state.back
mb = deRotateSide(mb,match.rot)
if(!isQueen || view[4].ant.food <= 2) {
var a = deRotate(mb,1)
var b = deRotate(mb,-1)//TODO should be -1
//console.log("mb: " + mb + "," + a + "," + b)
if(mb != 9 && (view[mb].color == COLOR2 || view[4].color == COLOR2 || view[a].color == COLOR2 || view[b].color == COLOR2)) {
//blue behind
//console.log("Blue behind")
colToPlace = COLOR2
}
else {
//console.log("No blue behind")
//console.log(match)
var myView2 = [0,0,0,0,0,0,0,0,0]
//construct a view without blue in it
for(var i=0; i < 9; i++) {
myView2[i] = view[i].color == COLOR2?1:view[i].color
}
var match2 = bestMatch(myView2)
if(match2.state.move == 9 || match2.state == matchStates[0]) {
//zero or one black
//console.log("<= 1 Black")
//console.log(myView2)
//console.log(match2.state)
colToPlace = COLOR2
}
else if(view[4].ant.type != 4) {
var mf = match2.state.move
mf = deRotateSide(mf,match2.rot)
//console.log("mf: " + mf)
if(mf != 9 && view[mf].color == COLOR2 && view[mf].ant == null) {
//about to move onto blue
//console.log("Moving onto blue")
//console.log(view)
//console.log(myView2)
return {cell:mf,color:1}
}
var clearOrder=[1,3,5,7,0,2,6,8]
for(var r=0;r<clearOrder.length;r++) {
var s = deRotateSide(clearOrder[r],0)
if(view[s].color == COLOR2 && (view[s].ant == null || !view[s].ant.friend || (isQueen && view[4].ant.food == 0))) {
//console.log("DIE BLUE SCUM")
//console.log(view)
//console.log(myView2)
return {cell:s,color:1}
}
else if(isQueen && view[s].ant != null && view[s].ant.friend) {
//console.log("Blue Queen")
//console.log(view)
//console.log(myView2)
return {cell:4,color:COLOR2}
}
}
}
}
}
//console.log("Nothing happened")
}
//console.log("4")
if(view[4].ant.type <= 2) {
for(var i=0; i < 9; i++) {
if(view[i].ant != null && !view[i].ant.friend) {
var canSeeAlly = isAllyAdjacentTo(view,i)
if(canSeeAlly == 0) {
if(view[i].color == LOCKDOWN) {
var a = deRotate(i, 1)
var b = deRotate(i, -1)
if(view[a].color != LOCKDOWN) return {cell:a,color:LOCKDOWN}
if(view[b].color != LOCKDOWN) return {cell:b,color:LOCKDOWN}
if(orthogonals.indexOf(i) >= 0) {
a = deRotate(i, 2)
b = deRotate(i, -2)
if(view[a].color != LOCKDOWN) return {cell:a,color:LOCKDOWN}
if(view[b].color != LOCKDOWN) return {cell:b,color:LOCKDOWN}
}
}
else {
return {cell:i,color:LOCKDOWN}
}
if(view[4].color == LOCKDOWN || view[4].color == COLOR) {
var ii = deRotate(i,4)
ii = findOpenSpace(ii,1)
return {cell:ii}
}
return {cell:4,color:COLOR}
}
else if(canSeeAlly == 2) {
var m = deRotate(i, 2)
var j = deRotate(i, -2)
if(view[m].ant != null && view[m].ant.friend && view[m].ant.type < 5) return {cell:m,color:LOCKDOWN}
if(view[j].ant != null && view[j].ant.friend && view[j].ant.type < 5) return {cell:j,color:LOCKDOWN}
}
else if(view[4].color == LOCKDOWN || view[4].color == 2) {
}
else {
return {cell:4,color:2}
}
}
}
for(var i=0; i < 9; i++) {
if(view[i].ant != null && view[i].ant.friend && (view[i].ant.type > view[4].ant.type && view[4].ant.food == 0)) {
if(match.state.move == 9)
return {cell:4}
if(view[i].ant.type == 5)
return {cell:4}
var m = findOpenSpace(i,1)
if(view[m].ant == null)
return {cell:m}
return {cell:4,color:2}
}
}
}
else if(view[4].ant.type <= 4) {
for(var i=0; i < 9; i++) {
if(view[i].ant != null && !view[i].ant.friend) {
var canSeeAlly = isAllyAdjacentTo(view,i)
if(canSeeAlly == 0) {
if(view[i].color == LOCKDOWN) {
var a = deRotate(i, 1)
var b = deRotate(i, -1)
if(view[a].color != LOCKDOWN) return {cell:a,color:LOCKDOWN}
if(view[b].color != LOCKDOWN) return {cell:b,color:LOCKDOWN}
if(orthogonals.indexOf(i) >= 0) {
a = deRotate(i, 2)
b = deRotate(i, -2)
if(view[a].color != LOCKDOWN) return {cell:a,color:LOCKDOWN}
if(view[b].color != LOCKDOWN) return {cell:b,color:LOCKDOWN}
}
}
else {
return {cell:i,color:LOCKDOWN}
}
if(view[4].color == LOCKDOWN || view[4].color == COLOR) {
var ii = deRotate(i,4)
ii = findOpenSpace(ii,1)
return {cell:ii}
}
return {cell:4,color:COLOR}
}
else if(canSeeAlly == 2) {
var m = deRotate(i, 2)
j = deRotate(i, -2)
if(view[m].ant != null && view[i].ant.friend && view[m].ant.type < 5) return {cell:m,color:LOCKDOWN}
if(view[j].ant != null && view[j].ant.friend && view[j].ant.type < 5) return {cell:j,color:LOCKDOWN}
}
else if(view[4].color == LOCKDOWN || view[4].color == 2) {
}
else {
return {cell:4,color:2}
}
}
}
}
else if(view[4].ant.food > 4) {
for(var i=0; i < 9; i++) {
if(view[i].ant != null && !view[i].ant.friend) {
var canSeeAlly = isAllyAdjacentTo(view,i)
if(canSeeAlly == 0) {
var m = findOpenSpace(i,1)
if(view[m].ant == null)
return {cell:m,type:1}
return {cell:4,color:3}
}
}
}
var high = getHighestWorker()
if(high >= 3 && view[4].ant.food % 2 == 1 && view[4].ant.food < 40) {
var typeToSpawn = 1
if(view[4].ant.food < 10 && high == 4 && view[4].ant.food % 4 == 1) {
typeToSpawn = 3
}
var m = findOpenSpace(0,1)
var canSeeAlly = isAllyAdjacentTo(view,m)
if(canSeeAlly == 0 && view[m].ant == null)
return {cell:m,type:typeToSpawn}
}
}
//console.log("5")
var m = match.state.move
if(isQueen && view[4].ant.food > 0 && view[4].ant.food <= 2 && isAnyColor(COLOR2) == 0 && isAnyColor(COLOR3) == 0 && m < 9) {
var high = getHighestWorker()+1
var num = howManyAnts();
//high += Math.max(num-2,0)
if(high < 5) {
m = deRotate(m,match.rot+4) //get space behind
m = findOpenSpace(m,1) //make sure its open
if(view[m].ant == null && view[m].food == 0)
return {cell:m,type:high}
return {cell:4}
}
else {
//return {cell:9}
colToPlace = COLOR2
}
}
if(!isQueen && view[4].ant.food > 0 /*&& view[4].ant.type >= 3*/) {
//console.log("type 3")
m = match.state.back
//console.log(m)
colToPlace = COLOR
}
if(view[4].ant.type == 3) {
colToPlace = COLOR
}
//console.log("6")
if(!matchesColor(view[4].color) && !(!isQueen && view[4].ant.food)) {
//console.log("6a")
/*for(var j=0; j < 9; j++) {
if(j != 4 && view[j].ant != null && view[j].ant.friend && view[j].ant.food > 0 && j != match.back) {
m = match.state.move
if(m < 9) {
m = findOpenSpace(m,1)
if(view[m].ant == null)
return {cell:m}
return {cell:4}
}
return {cell:4,color:colToPlace}
}
}*/
if(isQueen && view[4].color == LOCKDOWN) {
m = deRotateSide(m,match.rot)
m = findOpenSpace(m,1)
return {cell:m}
}
return {cell:4,color:colToPlace}
}
if(match.fill && !matchesColor(view[4].color)) {
return {cell:4,color:colToPlace}
}
if(m >= 9) {
if(!matchesColor(view[4].color)) {
return {cell:4,color:COLOR}
}
//console.log("lost! " + view[4].ant.food);
//console.log(pathLost());
return pathLost()
}
//console.log("7")
//console.log("m0: " + m + "+" + match.rot)
m = deRotateSide(m,match.rot)
//console.log("m1: " + m)
m = findOpenSpace(m,1)
//console.log("m2: " + m)
if(view[4].ant.food > 0 && !matchesColor(view[4].color) /*&& (view[4].ant.type >= 3)*/) {
var anyFood = false
for(var x=0;x<9;x++) {
if(view[x].food > 0) anyFood = true;
}
if(!anyFood)
return {cell:4,color:colToPlace}
}
//console.log("m3: " + m)
m = findOpenSpace(m,1)
//console.log("m4: " + m)
if((!isQueen && view[4].ant.food > 0 && view[m].food > 0) && view[m].ant == null) return {cell:4}
return {cell:m}
}
var ret = getReturn()
ret = sanityCheck(ret)
return ret
function sanityCheck(ret) {
if(!ret || ret.cell < 0 || ret.cell > 8 || (ret.cell != 4 && (ret.color == null || ret.color == 0) && view[ret.cell].ant != null) || (view[ret.cell].food > 0 && (view[4].ant.food > 0 && view[4].ant.type < 5))) {
return {cell:4}
}
if(ret.type && (view[ret.cell].ant != null || view[ret.cell].food > 0)) {
return {cell:4}
}
return ret;
}
```
This is a massive, massive ant function. It does this:
[![The black hole](https://i.stack.imgur.com/PnNKx.png)](https://i.stack.imgur.com/PnNKx.png)
The functionality is really quite simple. The top of the code block defines a `matchStates` object that the ants use to identify which way they're facing, and in so doing, they orbit around the known explored area. Then a few helper functions (matching colors, counting ants, etc).
`bestMatch()` takes in the view seen by the ant (mutable) and finds the best match in the `matchStates` and returns the best match.
Queeny does one thing as she moves around, placing down black:
* Make workers until she goes to make a worker that would be a queen, then switches to placing blue. Any ant placing a color that sees blue nearby places blue instead.
* The queen, if she sees blue, hoards food.
Type 1 and 2 workers act like the queen until they find food, then they abandon placing down color until they've walked around the circle and given their food to the queen.
Type 3 and 4 workers act like queens until they find food, then they work backwards around the circle (still placing color) until they hand off their food to the queen.
Any ant that finds itself lost invokes `pathLost()` which is a smarter straight line algorithm (it's litterrally the [smart straight path function from meta](https://codegolf.meta.stackexchange.com/a/13338/47990) with some tweaks).
Those tweaks are:
* Type 1 ants act randomly and attempt to erase paths (mostly not needed, but Type 1 ants aren't valuable long term, and this does clean up diagonal checkerboards)
* Non-queens won't act if they can see the queen
* Any time the ant can see and still determine orientation of its path that encounters previous paths in front of it, erases that path, ensuring ants make it back out:
[![Crossover example](https://i.stack.imgur.com/XeyQc.png)](https://i.stack.imgur.com/XeyQc.png)
Beyond that, most of the rest is just error handling to insure that no ants perform illegal operations (moving onto other ants, moving onto food, spawning ants *on* food...) although the biggest error handling chunk of code is down at the bottom:
```
if(view[4].ant.food > 0 && !matchesColor(view[4].color) && (view[4].ant.type >= 3) || surroundingColor > 6) {
var anyFood = false
for(var x=0;x<9;x++) {
if(view[x].food > 0) anyFood = true;
}
if(!anyFood)
return {cell:4,color:colToPlace}
}
```
Type 3 and 4 ants that are walking backwards won't place down color around food still on the ground (food is otherwise treated like colored tiles for the purposes of path orientation). Additionally, Type 1 or 2 ants that think they've been hemmed in (<=2 uncolored spaces in view) will place down color. For small 'islands' they eventually make themselves lost, rather than be permanently trapped.
The maximum food obtainable by this faction is only limited by how quickly it switches colors as well as the maximum duration of a game (10k minimum). More workers isn't necessarily beneficial, but it's essential to get several early. Type 3 and 4 workers are the most efficient (taking 6 steps closer to the queen every 6 game steps) but creating them too early leads to fewer total workers. So initial placement has a big impact, but as the area mapped by the swarm is ever-growing with few spaces unseen, it will grab *every last piece* even though no ant will risk getting lost in order to pick a piece up.
**Update 7/23**
Noticed some issues in specific edge-cases, like this one:
[![Queen wants to move onto an enemy](https://i.stack.imgur.com/bvfpF.png)](https://i.stack.imgur.com/bvfpF.png)
And made very minor tweaks to account for it. Basically, treat enemy ants and laden workers as colored tiles.
**Update 7/26**
Fox, I don't even know any more.
* Tweaked lost-yellow-trail-error handling to be more robust
* Tweaked friend-path-collision handling to be more robust
* Added Trail Eraser neutralizer code
* Added "blue trails" detection and handling code [BETA]
* Made queen continue to produce workers after going into hoard mode (occasionally, at least)
* Invalid move sanitation
* Miscellaneous spaghetti code
* Removed console.log
* Removed herobrine
* Added accretion disk
[![New accretion disk](https://i.stack.imgur.com/O8ezy.png)](https://i.stack.imgur.com/O8ezy.png)
Without the yellow trails:
[![Minus the yellow](https://i.stack.imgur.com/K3YYe.png)](https://i.stack.imgur.com/K3YYe.png)
**Update 7/26 PART 2**
* Completely revamped the "what do I do with blue?" code
+ Removed accretion disk
* Added salt and pepper
* Fixed issues with "which way am I facing?" detection
+ Removed circular shape
+ Added square shape
- Looks like boring now
* Removed immunity to Trail-Eraser
* Added smarts in "I am lost" code, reduces stuck ants
**Update 7/31**
* Re-added anti-Trail-Eraser code (it got lost in the "remove blue" update)
* Sanity check function was preventing coloring cells under other ants
* More better anti-eraser fix: no longer need 3 workers to counter a single eraser
**Update 8/4**
Minor tweaks.
* LOCKDOWN color is now black
* All ants walk "backwards" to deliver food. Those mechanics will lead to fewer ants getting trapped in "bubbles" left by Trail-Eraser
* Better handling of lost ants not getting each other stuck
* Reduced "only hoard" threshold to 40
**Weaknesses**
* Erasure.
* Color tampering.
[Answer]
# Vampire Mk.8 (Re-Vamped)
*This has been turned into a community wiki so that anybody can update it to target other victims. It uses the concept of environments to keep the different targeting code separate. If you want to make a change, please run a few tournaments to make sure your new code doesn't lower the average score!*
---
*All my answers are sharing the same set of low-level helper functions. Search for "High-level logic begins here" to see the code specific to this answer.*
```
// == Shared low-level helpers for all solutions ==
var QUEEN = 5
var WHITE = 1
var COL_MIN = WHITE
var COL_LIM = 9
var CENTRE = 4
var NOP = {cell: CENTRE}
var DIR_FORWARDS = false
var DIR_REVERSE = true
var SIDE_RIGHT = true
var SIDE_LEFT = false
function sanity_check(movement) {
var me = view[CENTRE].ant
if(!movement || (movement.cell|0) !== movement.cell || movement.cell < 0 || movement.cell > 8) {
return false
}
if(movement.type) {
if(movement.color) {
return false
}
if((movement.type|0) !== movement.type || movement.type < 1 || movement.type > 4) {
return false
}
if(view[movement.cell].ant || view[movement.cell].food) {
return false
}
if(me.type !== QUEEN || me.food < 1) {
return false
}
return true
}
if(movement.color) {
if((movement.color|0) !== movement.color || movement.color < COL_MIN || movement.color >= COL_LIM) {
return false
}
if(view[movement.cell].color === movement.color) {
return false
}
return true
}
if(view[movement.cell].ant && movement.cell != 4) {
return false
}
if(view[movement.cell].food + me.food > 1 && me.type !== QUEEN) {
return false
}
return true
}
function as_array(o) {
if(Array.isArray(o)) {
return o
}
return [o]
}
function best_of(movements) {
var m
for(var i = 0; i < movements.length; ++ i) {
if(typeof(movements[i]) === 'function') {
m = movements[i]()
} else {
m = movements[i]
}
if(sanity_check(m)) {
return m
}
}
return null
}
function play_safe(movement) {
// Avoid disqualification: no-op if moves are invalid
return best_of(as_array(movement)) || NOP
}
var RAND_SEED = (() => {
var s = 0
for(var i = 0; i < 9; ++ i) {
s += view[i].color * (i + 1)
s += view[i].ant ? i * i : 0
s += view[i].food ? i * i * i : 0
}
return s % 29
})()
var ROTATIONS = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[2, 5, 8, 1, 4, 7, 0, 3, 6],
]
function areAdjacent(A, B) {
if(A == 4 || B == 4 || A == B) return true
if(A % 2 == 0 && B % 2 == 0) return false
if(A % 2 == 1 && B % 2 == 0) return areAdjacent(B,A)
if(A % 2 == 1 && B % 2 == 1) return !(8-A == B || 8-B == A)
if(A == 0 && (B == 1 || B == 3)) return true
if(A == 2 && (B == 1 || B == 5)) return true
if(A == 6 && (B == 3 || B == 7)) return true
if(A == 8 && (B == 5 || B == 7)) return true
return false
}
function try_all(fns, limit, wrapperFn, checkFn) {
var m
fns = as_array(fns)
for(var i = 0; i < fns.length; ++ i) {
if(typeof(fns[i]) !== 'function') {
if(checkFn(m = fns[i])) {
return m
}
continue
}
for(var j = 0; j < limit; ++ j) {
if(checkFn(m = wrapperFn(fns[i], j))) {
return m
}
}
}
return null
}
function identify_rotation(testFns) {
// testFns MUST be functions, not constants
return try_all(
testFns,
4,
(fn, r) => fn(ROTATIONS[r]) ? ROTATIONS[r] : null,
(r) => r
)
}
function near(a, b) {
return (
Math.abs(a % 3 - b % 3) < 2 &&
Math.abs(Math.floor(a / 3) - Math.floor(b / 3)) < 2
)
}
function try_all_angles(solverFns) {
return try_all(
solverFns,
4,
(fn, r) => fn(ROTATIONS[r]),
sanity_check
)
}
function try_all_cells(solverFns, skipCentre) {
return try_all(
solverFns,
9,
(fn, i) => ((i === CENTRE && skipCentre) ? null : fn(i)),
sanity_check
)
}
function try_all_cells_near(p, solverFns) {
return try_all(
solverFns,
9,
(fn, i) => ((i !== p && near(p, i)) ? fn(i) : null),
sanity_check
)
}
function ant_type_at(i, friend) {
return (view[i].ant && view[i].ant.friend === friend) ? view[i].ant.type : 0
}
function friend_at(i) {
return ant_type_at(i, true)
}
function foe_at(i) {
return ant_type_at(i, false)
}
function foe_near() {
for(var i = 0; i < 9; ++ i) {
if(i !== 4 && view[i].ant && !view[i].ant.friend) {
return true
}
}
return false
}
function ant_type_near(p, friend) {
for(var i = 0; i < 9; ++ i) {
if(i !== 4 && ant_type_at(i, friend) && near(i, p)) {
return true
}
}
return false
}
function move_agent(agents) {
var me = view[CENTRE].ant
var buddies = [0, 0, 0, 0, 0, 0]
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)]
}
for(var i = 0; i < agents.length; i += 2) {
if(agents[i] === me.type) {
return agents[i+1](me, buddies)
}
}
return null
}
function grab_nearby_food() {
return try_all_cells((i) => (view[i].food ? {cell: i} : null), true)
}
function go_anywhere() {
return try_all_cells((i) => ({cell: i}), true)
}
function colours_excluding(cols) {
var r = []
for(var i = COL_MIN; i < COL_LIM; ++ i) {
if(cols.indexOf(i) === -1) {
r.push(i)
}
}
return r
}
function generate_band(start, width) {
var r = []
for(var i = 0; i < width; ++ i) {
r.push(start + i)
}
return r
}
function colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1
},
next: function(c) {
return colours[(colours.indexOf(c) + 1) % colours.length]
},
prev: function(c) {
return colours[(colours.indexOf(c) + colours.length - 1) % colours.length]
}
}
}
function random_colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1
},
next: function() {
return colours[RAND_SEED % colours.length]
}
}
}
function fast_diagonal(colourBand) {
var m = try_all_angles([
// Avoid nearby checked areas
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[5]].color) &&
colourBand.contains(view[rot[7]].color)
) {
return {cell: rot[0]}
}
},
// Go in a straight diagonal line if possible
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[8]].color)
) {
return {cell: rot[0]}
}
},
// When in doubt, pick randomly but avoid doubling-back
(rot) => (colourBand.contains(view[rot[0]].color) ? null : {cell: rot[0]}),
// Double-back when absolutely necessary
(rot) => ({cell: rot[0]})
])
// Lay a colour track so that we can avoid doubling-back
// (and mess up our foes as much as possible)
if(!colourBand.contains(view[CENTRE].color)) {
var prevCol = m ? view[8-m.cell].color : WHITE
var colours = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for(var i = 0; i < 9; ++ i) {
++ colours[view[i].color]
}
return {cell: CENTRE, color: colourBand.next(prevCol)}
}
return m
}
function checkAllNearEnvirons(colours, buddies) {
var nearMoves = [victims.length]
for(var e = 0; e < victims.length; e++) {
var env = victims[e]
nearMoves[e] = null
if(env.near_nest(colours)) {
nearMoves[e] = env.near_nest_move(colours, buddies)
}
}
return best_of(nearMoves)
}
function follow_edge(obstacleFn, side) {
// Since we don't know which direction we came from, this can cause us to get
// stuck on islands, but the random orientation helps to ensure we don't get
// stuck forever.
var order = ((side === SIDE_LEFT)
? [0, 3, 6, 7, 8, 5, 2, 1, 0]
: [0, 1, 2, 5, 8, 7, 6, 3, 0]
)
return try_all(
[obstacleFn],
order.length - 1,
(fn, i) => (fn(order[i+1]) && !fn(order[i])) ? {cell: order[i]} : null,
sanity_check
)
}
function start_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT)
return try_all_angles([
(rot) => ((
!protectedCols.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 2 : 0]].color) &&
!colourBand.contains(view[rot[1]].color)
)
? {cell: rot[right ? 5 : 3], color: colourBand.next(WHITE)}
: null)
])
}
function lay_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT)
return try_all_angles([
(rot) => {
var ahead = rot[right ? 2 : 0]
var behind = rot[right ? 8 : 6]
if(
colourBand.contains(view[behind].color) &&
!protectedCols.contains(view[ahead].color) &&
!colourBand.contains(view[ahead].color) &&
!colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
return {cell: ahead, color: colourBand.next(view[behind].color)}
}
}
])
}
function follow_dotted_path(colourBand, side, direction) {
var forwards = (direction === DIR_REVERSE) ? 7 : 1
var right = (side === SIDE_RIGHT)
return try_all_angles([
// Cell on our side? advance
(rot) => {
if(
colourBand.contains(view[rot[right ? 5 : 3]].color) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[0]].color) &&
!colourBand.contains(view[rot[2]].color)
) {
return {cell: rot[forwards]}
}
},
// Cell ahead and behind? advance
(rot) => {
var passedCol = view[rot[right ? 8 : 6]].color
var nextCol = view[rot[right ? 2 : 0]].color
if(
colourBand.contains(passedCol) &&
nextCol === colourBand.next(passedCol) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[right ? 0 : 2]].color)
) {
return {cell: rot[forwards]}
}
}
])
}
function escape_dotted_path(colourBand, side, newColourBand) {
var right = (side === SIDE_RIGHT)
if(!newColourBand) {
newColourBand = colourBand
}
return try_all_angles([
// Escape from beside the line
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color
if(
!colourBand.contains(view[rot[right ? 8 : 6]].color) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[rot[7]].color) ||
colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
// not oriented, or in a corner
return null
}
return best_of([
{cell: rot[right ? 0 : 2], color: newColourBand.next(approachingCol)},
{cell: rot[right ? 3 : 5]},
{cell: rot[right ? 0 : 2]},
{cell: rot[right ? 6 : 8]},
{cell: rot[right ? 2 : 0]},
{cell: rot[right ? 8 : 6]},
{cell: rot[right ? 5 : 3]}
])
},
// Escape from inside the line
(rot) => {
if(
!colourBand.contains(view[rot[7]].color) ||
!colourBand.contains(view[rot[1]].color) ||
colourBand.contains(view[CENTRE].color)
) {
return null
}
return best_of([
{cell: rot[3]},
{cell: rot[5]},
{cell: rot[0]},
{cell: rot[2]},
{cell: rot[6]},
{cell: rot[8]}
])
}
])
}
function latch_to_dotted_path(colourBand, side) {
var right = (side === SIDE_RIGHT)
return try_all_angles([
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color
if(
colourBand.contains(approachingCol) &&
view[rot[right ? 8 : 6]].color === colourBand.next(approachingCol) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color)
) {
// We're on the wrong side; go inside the line
return {cell: rot[right ? 5 : 3]}
}
},
// Inside the line? pick a side
(rot) => {
var passedCol = view[rot[7]].color
var approachingCol = view[rot[1]].color
if(
!colourBand.contains(passedCol) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[CENTRE].color)
) {
return null
}
if((approachingCol === colourBand.next(passedCol)) === right) {
return best_of([{cell: rot[3]}, {cell: rot[6]}, {cell: rot[0]}])
} else {
return best_of([{cell: rot[5]}, {cell: rot[2]}, {cell: rot[8]}])
}
}
])
}
// == High-level logic begins here ==
var TARGET_COLOURS_ZIG = colour_band([4, 5, 7, 8])
var TARGET_COLOURS_FIREFLY = colour_band([2, 5, 8])
var GROUND_COLOURS_BH = colour_band([2, 7, 8])
var SAFE_COLOURS = random_colour_band([8])
var THIEF = 1
var BOUNCER = 2
var LANCE = 4
var LANCE_TIP = 3
var INITIAL_GATHER = 12
function colour_band_prev(band, base) {
if(!band.contains(base)) {
return band.next(WHITE)
}
var cur = band.next(base)
var c
while((c = band.next(cur)) !== base) {
cur = c
}
return cur
}
function white_near(p) {
for(var i = 0; i < 9; ++ i) {
if(near(i, p) && view[i].color === WHITE) {
return true
}
}
return false
}
function white_near(p, min) {
var c = 0
for(var i = 0; i < 9; ++ i) {
if(near(i, p) && view[i].color === WHITE) {
if(++c >= min) return true
}
}
return false
}
var TARGET_ARRANGEMENT_RAIL = [
[8,4,5,8,5,2,4,2,6],
[8,5,2,4,2,6,6,4,5],
[4,2,6,6,4,5,8,4,5],
[6,4,5,8,4,5,8,5,2]
]
var TARGET_NEAR_RAIL = [
[2,4,0,5,8,0,4,8,0,1], //Not Valid for Worker #1
[2,6,0,4,5,0,4,5,0,0],
[4,6,0,2,4,0,5,8,0,0],
[4,8,0,4,6,0,2,4,0,0],
[4,5,0,5,2,0,2,6,0,1], //NV 1
[4,5,0,4,5,0,5,2,0,5], //NV Q
[5,2,0,2,6,0,4,5,0,0],
[5,8,0,4,8,0,4,6,0,5] //NV Q
]
var TARGET_COLOURS_RAIL = colour_band([4,5,2,4])
var rail_miners = {
name:function() { return "rail_miners"; },
near_nest: function(colours) {
var bestScore = 0
var enemyQueen = false
// check every rotation for each 3x3 rail possibility
TARGET_NEAR_RAIL.forEach(function (arrangement) {
ROTATIONS.forEach(function (rot){
var sevenVal = 1
var score = 0
for(var i = 0; i < 9; i++) {
score += arrangement[i] == view[rot[i]].color?1:0
score += (arrangement[i] == 0 && view[rot[i]].color == 7)?sevenVal:0
score += (arrangement[i] == 0 && !(view[rot[i]].color == 7 || view[rot[i]].color == 1))?-1:0
if(arrangement[i] == 0 && view[rot[i]].color == view[rot[i-2]].color) score -= 2
if(view[rot[i]].color) sevenVal = 0
enemyQueen |= view[i].ant && view[i].ant.type == QUEEN && !view[i].ant.friend
if(view[i].ant != null && view[i].ant.friend && view[i].ant.type == THIEF && view[i].color == WHITE) score++
}
if(score > bestScore && arrangement[9] != view[4].ant.type) {
bestScore = score
}
})
})
if(bestScore >= (5 - (enemyQueen && view[4].ant.type == 1?1:0))) {
if(highway.likely_nest(colours)) return false
return true
}
return false
},
worth_leeching: function(myFood, buddies) {
var numFours = 0
var foodNeed = 11
for(var i = 0; i < 9; i++) {
if(foe_at(i) == 4) numFours++
}
if(!buddies[THIEF]) return false
if(view[4].ant.type != 5 && buddies[QUEEN] && myFood < 500 && myFood+buddies[THIEF] > (foodNeed-numFours*3)) return true
return myFood < 500 && myFood >= (foodNeed-numFours*3)
},
near_nest_move: function(colours, buddies) {
var victim_pos = -1
var avoid_pos = -1
var friend_pos = -1
for(var i = 0; i < 9; i++) {
if(foe_at(i) == QUEEN) victim_pos = i
if(foe_at(i) > 0 && foe_at(i) < 4) avoid_pos = i
if(friend_at(i) == THIEF) friend_pos = i
}
if(victim_pos >= 0) return rail_miners.follow_victim(view[4].ant, buddies, colours, victim_pos)
if(view[4].ant.type == THIEF && buddies[QUEEN]) return NOP
if(view[4].ant.type == QUEEN && rail_miners.worth_leeching(view[4].ant.food, buddies)) {
if(avoid_pos >= 0 && view[4].color != WHITE) {
return best_of([
try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === THIEF ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === THIEF ? {cell: rot[3]} : null)
]),
try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === THIEF ? {cell: rot[2]} : null),
(rot) => (friend_at(rot[0]) === THIEF ? {cell: rot[1]} : null)
]),
NOP
])
}
var allowed = [[8,4,8],[4,6,8],[6,8,4],[5,5,6],[6,5,2],[2,6,5]]
var curr = [view[4].color,view[friend_pos].color,view[8-friend_pos].color]
var found = false
allowed.forEach(function (al) {
if(al[0] == curr[0] && al[1] == curr[1] && al[2] == curr[2]) {
found = true
}
})
if(!found) {
return best_of([
try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === THIEF && [2,4,5].indexOf(view[rot[2]].color) >= 0 ? {cell: rot[2]} : null),
(rot) => (friend_at(rot[1]) === THIEF && [2,4,5].indexOf(view[rot[0]].color) >= 0 ? {cell: rot[0]} : null)
]),
NOP
])
}
return NOP
}
return null
},
likely_nest: function(colours) {
var bestScore = 0
// check every rotation for each 3x3 rail possibility
var q = 0
TARGET_ARRANGEMENT_RAIL.forEach(function (arrangement) {
var j = 0
ROTATIONS.forEach(function (rot){
var score = 0
for(var i = 0; i < 9; i++) {
score += arrangement[i] == view[rot[i]].color?1:0
if(view[i].ant != null && view[i].ant.friend && view[i].ant.type == THIEF && view[i].color == WHITE) score++
}
if(score > bestScore) {
bestScore = score
}
j++
})
q++
})
if(view[4].ant.type == THIEF && rail_miners.near_nest(colours)) return true
if(bestScore >= 7) {
if(highway.likely_nest(colours)) return false
return true
}
return false
},
likely_victim: function(victim_pos) {
return true
},
follow_victim: function(me, buddies, colours, victim_pos) {
if(me.type == QUEEN) {
if(victim_pos % 2 == 0) {
return best_of([
try_all_angles.bind(null, [
(rot) => (foe_at(rot[0]) === QUEEN && friend_at(rot[5]) == THIEF ? {cell: rot[2]} : null),
(rot) => (foe_at(rot[0]) === QUEEN /*&& friend_at(rot[7]) == THIEF*/ ? {cell: rot[6]} : null)
]),
NOP
])
}
else {
return best_of([
try_all_angles.bind(null, [
(rot) => (foe_at(rot[1]) === QUEEN && friend_at(rot[2]) == THIEF ? {cell: rot[5], type: THIEF} : null),
(rot) => (foe_at(rot[1]) === QUEEN ? {cell: rot[3], type: THIEF} : null),
(rot) => (foe_at(rot[1]) === QUEEN ? {cell: rot[5], type: THIEF} : null),
(rot) => (buddies[THIEF] < 4 && foe_at(rot[1]) === QUEEN ? {cell: rot[2], type: THIEF} : null),
(rot) => (buddies[THIEF] < 4 && foe_at(rot[1]) === QUEEN ? {cell: rot[0], type: THIEF} : null)
]),
NOP
])
}
}
return NOP
},
find_victim: function(me, buddies, colours) {
var forwardCell = -1
var current = view[CENTRE].color
var target = TARGET_COLOURS_RAIL.next(current)
var antitarget = TARGET_COLOURS_RAIL.prev(current)
var queenPos = -1
for(var i = 0; i < 9; i++) {
if(i % 2 == 1 && view[i].color == target && view[8-i].color == antitarget && current != WHITE){
forwardCell = i
}
if(friend_at(i) == QUEEN) queenPos = i
}
if(forwardCell < 0 && current == 4) {
target = 4
antitarget = 2
for(var i = 0; i < 9; i++) {
if(i % 2 == 1 && view[i].color == target && view[8-i].color == antitarget){
forwardCell = i
}
}
}
if(me.type == QUEEN) {
var numEn = 0
for(var i = 0; i < 9; i++) {
if(i % 2 == 1 && friend_at(i) == THIEF && friend_at(8-i) == THIEF){
if(foe_at(deRotate(i,1)) > 0)
return {cell:forwardCell}
if(foe_at(deRotate(i,-1)) > 0)
return {cell:forwardCell}
return NOP
}
if(i % 2 == 0 && friend_at(i) == THIEF && friend_at(deRotate(i,2)) == THIEF){
return {cell:deRotate(i,3), type:THIEF}
}
}
return wilderness.find_victim(me, buddies, colours)
}
else if(forwardCell >= 0) {
if(friend_at(forwardCell) == QUEEN) {
return best_of([
try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === QUEEN ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === QUEEN ? {cell: rot[3]} : null)
]),
go_anywhere
])
}
}
else if(queenPos>=0 && view[queenPos].color == WHITE && (foe_at(deRotate(queenPos,2)) && foe_at(deRotate(queenPos,-2)))) {
return wilderness.find_victim(me, buddies, colours)
}
if(me.type == THIEF && forwardCell >= 0 && buddies[THIEF] == 1) {
return wilderness.find_victim(me, buddies, colours)
}
return NOP
}
}
var TARGET_ARRANGEMENT_WIND = [
[5,4,0,7,6,0,6,4,0],
[7,6,0,6,4,0,5,4,0],
[6,4,0,5,4,0,7,6,0]
]
var TARGET_ARRANGEMENT_WINDCENTER = [
[2,7,6,2,6,4,6,5,4],
[2,6,4,6,5,4,2,7,6],
[6,5,4,2,7,6,2,6,4]
]
var WIND_BAND = colour_band([5,6,7])
var windmill = {
name:function() { return "windmill"; },
near_nest: function(colours) { return false; },
near_nest_move: function(colours, buddies) { return null; },
likely_nest: function(colours) { // Main nest detection
var bestScore = 0
// check every rotation for each 3x3 rail possibility
TARGET_ARRANGEMENT_WIND.forEach(function (arrangement) {
ROTATIONS.forEach(function (rot){
var score = 0
for(var i = 0; i < 9; i++) {
score += arrangement[i] == view[rot[i]].color?1:0
}
if(score > bestScore) {
bestScore = score
}
})
})
if(bestScore >= 5 && view[4].ant.type != THIEF) {
return true
}
var bestScore = 0
// check every rotation for each 3x3 rail possibility
TARGET_ARRANGEMENT_WINDCENTER.forEach(function (arrangement) {
ROTATIONS.forEach(function (rot){
var score = 0
for(var i = 0; i < 9; i++) {
score += arrangement[i] == view[rot[i]].color?1:0
}
if(score > bestScore) {
bestScore = score
}
})
})
if(bestScore >= 8) {
return true
}
var buddies = [0, 0, 0, 0, 0, 0]
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)]
}
return buddies[LANCE] || buddies[LANCE_TIP]
},
worth_leeching: function(myFood, buddies) {
if(view[4].ant.type == THIEF && (buddies[LANCE] > 0 || buddies[LANCE_TIP] > 0)) return true
return myFood > 5 || (myFood > 1 && buddies[LANCE])
},
likely_victim: function(victim_pos) {
return false
},
follow_victim: function(me, buddies, colours, victim_pos) {
// nest is chaotic and varies by direction of approach
// We'll let the Find Victim logic handle this
return NOP
},
find_victim: function(me, buddies, colours) {
if(me.type == THIEF) {
var queenPos = -1
var lancePos = -1
var tipPos = -1
for(var i=0;i<9;i++) {
if(friend_at(i) == QUEEN) queenPos = i
if(friend_at(i) == LANCE) lancePos = i
if(friend_at(i) == LANCE_TIP) tipPos = i
}
if(queenPos < 0 || (foe_at(deRotate(queenPos,1)) > 0 && foe_at(deRotate(queenPos,2)) > 0)) {
if(queenPos < 0)
return go_anywhere
return {cell:8-queenPos}
}
if(queenPos % 2 == 1 && tipPos % 2 == 0) {
return go_anywhere
}
if(queenPos % 2 == 0 && lancePos % 2 == 1) {
return go_anywhere
}
if(queenPos % 2 == 1 && foe_at(deRotate(queenPos,-2)) > 0) {
return go_anywhere
}
return NOP
}
if(buddies[LANCE_TIP]) {
var lancePos = -1
for(var i=0;i<9;i++) {
if(friend_at(i) == LANCE_TIP) {
lancePos = i
}
}
if(buddies[LANCE]) {
if(friend_at(8-lancePos) == LANCE) {
if(foe_at(deRotate(8-lancePos,1)) == 1 || foe_at(deRotate(8-lancePos,2)) == 1) {
var ret = NOP
if(lancePos % 2 == 1)
ret = {cell:deRotate(8-lancePos,-2)}
if(lancePos % 2 == 0)
ret = {cell:deRotate(8-lancePos,-3)}
if(!sanity_check(ret)) {
ret = best_of([
try_all_cells_near(lancePos, (i) => (ant_type_at(i) == 0 && view[i].color == 6 ? {cell: i} : null), true),
NOP
])
}
return ret
}
if(foe_at(deRotate(lancePos,-2)) > 0) {
return {cell:deRotate(lancePos,2)}
}
return NOP
}
if(friend_at(deRotate(lancePos,3)) == LANCE) {
if((view[lancePos].color == 2 && view[4].color == 7) || foe_at(8-lancePos)) {
return {cell:deRotate(lancePos,1)}
}
return NOP
}
if(view[4].color == 6 && view[lancePos].color == 6 && friend_at(deRotate(lancePos,1)) == LANCE) {
if(foe_at(deRotate(lancePos,2)) > 0) {
return {cell:8-deRotate(lancePos,2)}
}
return NOP
}
if(view[lancePos].color == 2 && view[deRotate(lancePos,-3)].color == 5 && friend_at(deRotate(lancePos,-3)) == LANCE) {
return NOP
}
if(lancePos % 2 == 0) {
if(foe_at(deRotate(lancePos,-1)) > 0 && lancePos % 2 == 1) return {cell:deRotate(lancePos,2)}
if(view[deRotate(lancePos,-1)].color != 5) return {cell:deRotate(lancePos,-1),color:5}
if(view[deRotate(lancePos,-1)].color == 3 && view[4].color == 1) return {cell:4,color:3}
if(view[deRotate(lancePos,-1)].color == 5 && view[4].color == 3) return {cell:4,color:2}
if(view[deRotate(lancePos,-1)].color == 5 && view[4].color == 2) return {cell:4,color:1}
if(view[deRotate(lancePos,-1)].color == 5 && view[4].color == 7 && view[deRotate(lancePos,-1)].ant == null) return {cell:deRotate(lancePos,-1),type:THIEF}
if(view[deRotate(lancePos,-1)].color == 5 && view[4].color == 7) return {cell:4,color:3}
}
return {cell:deRotate(lancePos,-1)}
}
if(view[4].color == WHITE && view[lancePos].color == WHITE) {
return {cell:deRotate(lancePos,-2),type:BOUNCER}
}
if(view[deRotate(lancePos,-1)].ant != null && view[deRotate(lancePos,-1)].ant.type == 5) {
return {cell:deRotate(lancePos,2)}
}
if(view[4].color == 6 && view[deRotate(lancePos,1)].color == 7) {
return {cell:deRotate(lancePos,1)}
}
if(foe_at(deRotate(lancePos,-2)) > 0 || foe_at(deRotate(lancePos,-3)) > 0) {
if(foe_at(deRotate(lancePos,-2)) > 0 && foe_at(deRotate(lancePos,3)) > 0 && (foe_at(deRotate(lancePos,-1)) > 0 || foe_at(deRotate(lancePos,4)) > 0)) {
return {cell:deRotate(lancePos,1)}
}
if(foe_at(deRotate(lancePos,3)) > 0) {
return NOP
}
return {cell:deRotate(lancePos,1)}
}
if(foe_at(deRotate(lancePos,2)) > 0 && view[deRotate(lancePos,-1)].color != 2) {
return {cell:deRotate(lancePos,-1),color:2}
}
if(foe_at(deRotate(lancePos,-1)) > 0) {
return {cell:deRotate(lancePos,1)}
}
if(lancePos % 2 == 1 && friend_at(deRotate(lancePos,-1)) == THIEF) {
return {cell:deRotate(lancePos,-2)}
}
return {cell:deRotate(lancePos,-1)}
}
else if(buddies[LANCE]) {
var lancePos = -1
for(var i=0;i<9;i++) {
if(view[i].ant && view[i].ant.friend && view[i].ant.type == LANCE) {
lancePos = i
}
}
if(view[4].color == 3 && lancePos % 2 == 1) return NOP
var moveNext = lancePos % 2 == 1 ? {cell:deRotate(lancePos,2)} : {cell:deRotate(lancePos,1)}
if(view[moveNext.cell].ant != null && !view[moveNext.cell].ant.friend) {
moveNext = {cell:deRotate(lancePos,1),type:LANCE_TIP}
}
if(view[lancePos].ant.food > 0) {
if(lancePos % 2 == 1)
return {cell:deRotate(lancePos,4),type:LANCE_TIP}
else
return {cell:deRotate(lancePos,3),type:LANCE_TIP}
}
if(view[lancePos].color == 6 && view[moveNext.cell].color == 8 && view[deRotate(lancePos,2)].color == 5) {
return {cell:moveNext.cell,type:LANCE_TIP}
}
return moveNext
}
else {
var current = view[CENTRE].color
var standOn = WIND_BAND.next(WIND_BAND.next(WIND_BAND.next(current)))
var target = WIND_BAND.next(current)
var antitarget = WIND_BAND.next(target)
if(current != standOn) return wilderness.find_victim(me, buddies, colours)
var ret = best_of([
try_all_cells((i) => ((i % 2 == 1 && view[i].color == target && view[8-i].color == antitarget && ([2,5,6].indexOf(view[deRotate(i,-1)].color) >= 0) && (view[i].color != 5 || view[deRotate(i,1)].color == 4)) ? {cell: i, type: LANCE} : null), true),
NOP
])
if(ret.cell == 4) {
return wilderness.find_victim(me, buddies, colours)
}
return ret
}
return NOP
}
}
var TARGET_ARRANGEMENT_HIGHWAY = [
[2,3,7,6,8,2,3,7,6],
[2,3,7,7,6,4,4,2,3],
[2,4,6,7,3,2,4,6,7],
[3,2,4,4,6,7,7,3,2],
[3,4,7,7,2,6,6,3,4],
[3,4,7,2,6,3,4,7,2],
[3,6,2,2,7,4,4,3,6],
[4,7,2,2,5,6,3,4,7],
[4,6,7,2,6,3,3,4,7],
[4,6,7,7,3,2,2,4,6],
[6,4,2,3,7,6,4,2,3],
[7,3,2,2,4,6,6,7,3],
[7,4,3,6,2,7,4,3,5]
]
var HIGHWAY_BAND = colour_band([2,7,4,3,6])
var HIGHWAY_BAND2 = colour_band([2,3,7,6,4])
var highway = {
name:function() { return "highway"; }, // For debugging
near_nest: function(colours) { return false; }, // For dodging enemy workers without getting lost
near_nest_move: function(colours, buddies) { return null; }, // How to move when near_nest is true
likely_nest: function(colours) { // Main nest detection
var bestScore = 0
// check every rotation for each 3x3 rail possibility
TARGET_ARRANGEMENT_HIGHWAY.forEach(function (arrangement) {
ROTATIONS.forEach(function (rot){
var score = 0
for(var i = 0; i < 9; i++) {
score += arrangement[i] == view[rot[i]].color?1:0
}
if(score > bestScore) {
bestScore = score
}
})
})
if(bestScore >= 7) {
return true
}
if(this.isCenter(colours)) return true
return false
}, // Main nest detection
isCenter: function(colours) {
var bestScore = 0
ROTATIONS.forEach(function (rot){
var score = 0
for(var i = 0; i < 9; i++) {
if(i >= 3 && i <= 5 && [2,7,4,3,6].indexOf(view[rot[i]].color) >= 0 && (i == 4 || view[rot[i]].color != view[rot[8-i]].color)) {
if(i != 4) {
score++
}
else {
if(view[rot[3]].color != view[rot[5]].color && view[rot[1]].color == view[rot[7]].color && (view[rot[4]].color != view[rot[1]].color && view[rot[4]].color != view[rot[3]].color && view[rot[4]].color != view[rot[5]].color && view[rot[4]].color != view[rot[7]].color)) {
score++
}
}
}
else if(i >= 6) {
if(view[rot[i]].color == view[rot[i-6]].color && [2,7,4,3,6].indexOf(view[rot[i]].color) >= 0 && (i == 7 || view[rot[i]].color != view[rot[8-i]].color) && view[rot[i]].color != view[4].color) {
score += 2
}
}
}
if(score > bestScore) {
bestScore = score
}
})
if(bestScore >= 7) {
return true
}
return false
},
worth_leeching:function(myFood, buddies){ return myFood > 80 && myFood < 500; }, // Is this nest worth leeching?
likely_victim: function(victim_pos) {
return true
}, // Identifying the target queen
follow_victim: function(me, buddies, colours, victim_pos) {
if(me.type == QUEEN && buddies[THIEF] < 3) {
return best_of([
try_all_cells((i) => (near(i, victim_pos) ? {cell: i, type: THIEF} : null), true),
try_all_cells((i) => ({cell: i, type: THIEF}), true)
])
}
if(me.type == THIEF && buddies[QUEEN])
return NOP
return go_anywhere
}, // How to handle what happens when the enemy queen is found
find_victim: function(me, buddies, colours) {
if(me.type == THIEF && !buddies[QUEEN]) {
for(var i=0;i<9;i++) {
if(foe_at(i)) return NOP
}
var target = HIGHWAY_BAND.prev(view[4].color)
var followRail = best_of([
try_all_cells((i) => (i % 2 == 1 && view[i].color == target) ? {cell:i} : null),
NOP
])
}
else {
var target = HIGHWAY_BAND.next(view[4].color)
var followRail = best_of([
try_all_cells((i) => (i % 2 == 1 && view[i].color == target) ? {cell:i} : null),
NOP
])
}
return followRail
} // How to follow the nest
}
var wilderness = {
name:function() { return "wilderness"; },
near_nest: function(colours) { return false; },
near_nest_move: function(colours, buddies) { return null; },
likely_nest: function(colours) {
return true
},
worth_leeching: function(myFood, buddies) {
return true
},
likely_victim: function(victim_pos) {
return true
},
follow_victim: function(me, buddies, colours, victim_pos) {
// We stumbled across a random queen; make the most of it
// TODO
if(rail_miners.near_nest(colours)) {
return rail_miners.follow_victim(me, buddies, colours, victim_pos)
}
// avoids blocking off the rail miner queen from her workers
// (we'd like to leech her again)
if(me.type === QUEEN && !buddies[THIEF] && me.food > 0) {
// Make a buddy to help us steal
return best_of([
try_all_cells((i) => (near(i, victim_pos) ? {cell: i, type: THIEF} : null), true),
try_all_cells((i) => ({cell: i, type: THIEF}), true)
])
}
else if(me.type === QUEEN){
var enemyCount = 0
var allyPos = -1
for(var a=0; a<9; a++) {
if(a != 4 && view[a].ant != null) {
if(view[a].ant.friend) {
if(near(a,victim_pos)){
allyPos = a
}
}
else if(view[a].ant.type != 5) {
enemyCount++
}
}
}
if(enemyCount >= buddies[THIEF] && allyPos >= 0) {
//if next to the queen and we're outnumbered, move back to the center of the rail.
var target = TARGET_COLOURS_RAIL.prev(view[allyPos].color)
var best = best_of([
try_all_cells((i) => (near(i, victim_pos) && i % 2 == 0 ? {cell: i, type: THIEF} : null), true),
try_all_cells((i) => (near(i, victim_pos) ? {cell: i, type: THIEF} : null), true)
])
if(best != null) return best
best_of([
try_all_cells((i) => ((view[i].color == target && i != 4 && areAdjacent(i,a)) ? {cell: i} : null))
])
if(best != null) return best
return best_of([
{cell:deRotate(allyPos,1)},
{cell:deRotate(allyPos,-1)}
])
}
}
return NOP
},
find_victim: function(me, buddies, colours) {
if(me.type === QUEEN) {
var in_void = true
for(var i = 0; i < 9; ++ i) {
if(view[i].color !== WHITE && !SAFE_COLOURS.contains(view[i].color)) {
in_void = false
break
}
}
if(!in_void) {
// because of avoiding returning Miner on a Rail workers
// we dodge sideways and this takes us back onto track
var nearMove = checkAllNearEnvirons(colours, buddies)
if(nearMove) return nearMove
}
return best_of([
// Make a buddy once we have a reasonable stash of food so we can
// search the board faster
// (but avoid making buddies when there's a potential nest nearby
// better to wait until we find their queen)
(!buddies[THIEF] && me.food >= INITIAL_GATHER && in_void) &&
try_all_cells((i) => ({cell: i, type: THIEF}), true),
// Follow buddy in search of victims
buddies[THIEF] && try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === THIEF ? {cell: rot[2]} : null),
(rot) => (friend_at(rot[0]) === THIEF ? {cell: rot[1]} : null)
]),
buddies[THIEF] && try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === THIEF ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === THIEF ? {cell: rot[3]} : null)
]),
buddies[THIEF] && NOP, // Don't lose our buddy!
// Random walk until we can make a buddy or find the victim
grab_nearby_food,
foe_near() ? go_anywhere : fast_diagonal.bind(null, SAFE_COLOURS),
go_anywhere
])
} else if(me.type === THIEF) {
return best_of([
// Lost the queen! Random walk because we have nothing better to do.
// (don't leave lines; they could disrupt the pattern)
!buddies[QUEEN] && go_anywhere,
buddies[BOUNCER] && go_anywhere,
buddies[THIEF] > 1 && go_anywhere, //untested
// Follow queen in search of victims
try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === QUEEN ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === QUEEN ? {cell: rot[3]} : null)
]),
NOP // Don't lose our buddy!
])
}
}
}
var victims = [highway, rail_miners, windmill]
function guess_environment(colours, buddies) {
var food = view[4].ant.food
if(view[4].ant.type !== QUEEN) {
for(var i = 0; i < 9; i++) {
if(i != 4 && view[i].ant && view[i].ant.friend && view[i].ant.type === QUEEN) {
food = view[i].ant.food
}
}
}
for(var i = 0; i < victims.length; ++ i) {
if(victims[i].likely_nest(colours) && victims[i].worth_leeching(food, buddies)) {
return victims[i]
}
}
return wilderness
}
function is_safe(i) {
var nearThief = false
var nearOfficer = false
for(var j = 0; j < 9; ++ j) {
if(friend_at(j) === THIEF) {
nearThief = true
}
if(foe_at(j) && foe_at(j) !== QUEEN) {
nearOfficer = true
}
}
return nearThief && !nearOfficer
}
function move(me, buddies) {
var colours = [0, 0, 0, 0, 0, 0, 0, 0, 0]
for(var i = 0; i < 9; ++ i) {
++ colours[view[i].color]
}
var env = guess_environment(colours,buddies)
var victim_pos = -1
var queen_pos = -1
for(var i = 0; i < 9; ++ i) {
if(foe_at(i) === QUEEN && env.likely_victim(i) && view[i].ant.food > 0) {
victim_pos = i
if(view[i].ant.food > 0) {
break
}
}
if(friend_at(i) === QUEEN) {
queen_pos = i
}
}
var in_void = true
for(var i = 0; i < 9; ++ i) {
if(view[i].color !== WHITE || (i != 4 && me.type === BOUNCER && friend_at(i) === BOUNCER)) {
in_void = false
break
}
}
if(me.type === BOUNCER) {
if(env === wilderness && in_void) {
// Our work is done; leave queen and wander at random
if(buddies[QUEEN]) {
return best_of([
try_all_cells((i) => (ant_type_near(i, true) ? null : {cell: i}), true),
go_anywhere
])
}
return NOP
}
else if(env === rail_miners) {
// Our work is done; leave queen and wander at random
if(buddies[QUEEN]) {
var allAngles = try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === QUEEN ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === QUEEN ? {cell: rot[3]} : null),
NOP
])
return best_of([
//if next to an enemy queen, move out of the way
try_all_cells((i) => (foe_at(i) == QUEEN ? {cell:9-i} : null), true),
try_all_cells((i) => (foe_at(i) == QUEEN ? {cell:7-i} : null), true),
allAngles
])
}
return NOP
} else if(buddies[QUEEN]) {
// Escort queen out of nest
var allAngles = try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === QUEEN ? {cell: rot[0]} : null),
(rot) => (friend_at(rot[0]) === QUEEN ? {cell: rot[3]} : null),
NOP
])
return best_of([
//if next to an enemy queen, move out of the way
try_all_cells((i) => (foe_at(i) == QUEEN ? {cell:9-i} : null), true),
try_all_cells((i) => (foe_at(i) == QUEEN ? {cell:7-i} : null), true),
allAngles
])
}
else {
return go_anywhere
}
} else if(buddies[BOUNCER]) {
if(me.type === QUEEN) {
// Be escorted out of nest
return try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === BOUNCER ? {cell: rot[2]} : null),
(rot) => (friend_at(rot[0]) === BOUNCER ? {cell: rot[1]} : null),
go_anywhere,
NOP
])
} else {
// Get out of the way
return try_all_angles.bind(null, [
(rot) => (friend_at(rot[1]) === QUEEN ? {cell: rot[7]} : null),
(rot) => (friend_at(rot[0]) === QUEEN ? {cell: rot[8]} : null),
(rot) => (friend_at(rot[1]) === BOUNCER ? {cell: rot[7]} : null),
(rot) => (friend_at(rot[0]) === BOUNCER ? {cell: rot[8]} : null),
go_anywhere
])
}
}
if(victim_pos !== -1) {
// abandon the queen if she's dry.
// abandon rail miner's queen so she has at least 10 food (otherwise she produces workers 3:4 food she aquires)
// value is higher than 10 because there's two to three rounds of theft (at 4 ants each) before the queen gets out of range
// this can still leave the rail miner's queen lower than 10, but unlikely
// other queens are abandoned if they have less than 5 food, due to the "max 4 ants stealing" and at 0 food, she's not a target.
if(view[victim_pos].ant.food < 5 || (env == rail_miners && view[victim_pos].ant.food < 28)) {
if(me.type == THIEF) {
if(rail_miners.near_nest(colours)) {
// we'd rather reuse the workers
return NOP
}
}
// Victim is out of food; bounce out of nest
if(env == rail_miners) {
if(me.type == QUEEN && me.food < 300 && !buddies[BOUNCER]) {
if(friend_at(deRotate(victim_pos,2)) == THIEF && foe_at(deRotate(victim_pos,3)) == 0) return {cell:deRotate(victim_pos,3),type:BOUNCER}
if(friend_at(deRotate(victim_pos,-2)) == THIEF && foe_at(deRotate(victim_pos,-3)) == 0) return {cell:deRotate(victim_pos,-3),type:BOUNCER}
}
// murder SlM
return NOP
}
var m = try_all_cells((i) => ({cell: i, type: BOUNCER}), true)
if(m) {
return m
}
}
if(me.type === QUEEN && buddies[THIEF] && !is_safe(CENTRE)) {
// Try to avoid getting food stolen back from us
var m = try_all_cells((i) => (is_safe(i) ? {cell: i} : null), true)
if(m) {
return m
}
}
return env.follow_victim(me, buddies, colours, victim_pos)
} else {
return env.find_victim(me, buddies, colours)
}
}
// LANCE is only used by windmill targetting, easier to break this out as its own method
function moveLance(me, buddies) {
var queenPos = -1
var tipPos = -1
var enQueenPos = -1
if(buddies[BOUNCER]) {
for(var i=0;i<9;i++) {
if(friend_at(i) == BOUNCER) {
return {cell:8-i}
}
}
}
for(var i=0;i<9;i++) {
if(friend_at(i) == QUEEN) {
queenPos = i
}
if(friend_at(i) == LANCE_TIP) {
tipPos = i
}
if(foe_at(i) == QUEEN) enQueenPos = i
}
if(!buddies[QUEEN]) {
for(var i=0;i<9;i++) {
if(i % 2 == 0 && friend_at(i) == QUEEN) {
if(view[deRotate(i,3)].ant != null && view[deRotate(i,3)].ant.friend && view[deRotate(i,3)].ant.type == LANCE_TIP) return NOP
return {cell:deRotate(i,1)}
}
}
if(!buddies[LANCE_TIP] && !buddies[THIEF] && view[4].color == 2) {
for(var i = 0; i < 9; ++ i) {
if(view[i].color == 1) return {cell:i}
}
}
if(enQueenPos >= 0 && enQueenPos % 2 == 0 && foe_at(deRotate(enQueenPos,1)) == 1) {
return {cell:deRotate(enQueenPos,-3)}
}
if(enQueenPos >= 0 && enQueenPos % 2 == 1 && foe_at(deRotate(enQueenPos,2)) == 1) {
return {cell:8-enQueenPos}
}
if(enQueenPos >= 0 && (me.food > 0 || foe_at(deRotate(enQueenPos,-1)) || foe_at(deRotate(enQueenPos,3)))) {
if(enQueenPos % 2 == 0 && (foe_at(deRotate(enQueenPos,4)) || friend_at(deRotate(enQueenPos,4)) == THIEF)) {
return {cell:deRotate(enQueenPos,-3)}
}
}
return NOP
}
if(buddies[LANCE_TIP]) {
if(deRotate(queenPos,-1) == tipPos && view[tipPos].color == 8) return {cell:8-tipPos}
if(deRotate(queenPos,-1) == tipPos) return try_all_cells((i) => (areAdjacent(i,tipPos) && view[i].color == 5 ? {cell:i} : null))
if(foe_at(8-tipPos) == QUEEN) return {cell:8-tipPos,color:6}
if(foe_at(8-queenPos) > 0 || foe_at(deRotate(8-queenPos,1)) > 0) return NOP
return try_all_cells((i) => (!areAdjacent(i,queenPos) && !areAdjacent(i,tipPos) ? {cell:i} : null))
}
if(view[4].color != 4 && view[4].color != 6) {
if(foe_at(8-queenPos) == QUEEN) {
var formation = try_all_angles.bind(null, [
(rot) => (foe_at(rot[1]) === 1 && foe_at(rot[2]) === QUEEN ? {cell: rot[3]} : null),
(rot) => (foe_at(rot[1]) === 1 && foe_at(rot[0]) === QUEEN ? {cell: rot[7]} : null),
(rot) => (foe_at(rot[1]) === 1 && view[rot[1]].ant.food > 0 && foe_at(rot[6]) === QUEEN && friend_at(rot[2]) === QUEEN ? {cell: rot[5]} : null),
])()
if(formation != null) {
return formation
}
return NOP
}
if(foe_at(deRotate(queenPos,1)) > 0 && foe_at(deRotate(queenPos,-1)) > 0) {
return {cell:deRotate(queenPos,-3)}
}
return best_of([
try_all_cells((i) => (enQueenPos ==-1 && i % 2 == 1 && (view[i].color == 4 || view[i].color == 6) && view[deRotate(i,1)].color != 2 && view[deRotate(i,-1)].color != 2 && areAdjacent(i,queenPos) ? {cell: i} : null), true),
((view[4].color != 6 || view[4].color != 4) && queenPos % 2 == 0 && view[deRotate(queenPos,-3)].color == 5) ? {cell:4,color:6} : null,
NOP
])
}
else {
var queenOn = view[8-queenPos].color
var target = WIND_BAND.next(queenOn)
var prior = WIND_BAND.next(target)
var followRail = best_of([
try_all_cells((i) => (view[deRotate(i,-3)].color == prior && view[deRotate(i,-1)].color == target && areAdjacent(i,queenPos) && (view[i].color == 4 || view[i].color == 6) ? {cell: i} : null), true),
queenPos % 2 == 1 ? (view[queenPos].color == 4 || view[4].color == 4 ? NOP : {cell:deRotate(queenPos,-2)}) : (view[queenPos].color == 4 || view[queenPos].color == 6 ? {cell:deRotate(queenPos,-1)} : NOP)
])
if(view[deRotate(queenPos,-1)].ant != null) {
if(!view[deRotate(queenPos,-1)].ant.friend && view[deRotate(queenPos,-2)].ant != null && !view[deRotate(queenPos,-2)].ant.friend) {
return NOP
}
if(queenPos % 2 == 0 && !view[deRotate(queenPos,-1)].ant.friend && view[deRotate(queenPos,-2)].ant == null && (view[queenPos].color == 3 || view[queenPos].color == WHITE)) {
return {cell:deRotate(queenPos,-3)}
}
if(queenPos % 2 == 0 && friend_at(deRotate(queenPos,-1)) == THIEF && view[deRotate(queenPos,-2)].ant == null && (view[queenPos].color == 3 || view[queenPos].color == WHITE)) {
return {cell:deRotate(queenPos,-3)}
}
return NOP
}
if(me.food > 0 && queenPos % 2 == 0) {
return {cell:deRotate(queenPos,-1)}
}
if(foe_at(deRotate(queenPos,-3)) > 0 && (view[queenPos].color == 1 || view[deRotate(queenPos,1)].color == 1 || view[deRotate(queenPos,-1)].color == 1)) {
if(view[queenPos].color == 3) {
return followRail
}
if(view[queenPos].color == 7) return NOP
return {cell:queenPos,color:3}
}
if((foe_at(deRotate(queenPos,-2)) > 0 || foe_at(deRotate(queenPos,-3)) > 0) && queenPos % 2 == 0 && view[deRotate(queenPos,-1)].color == 5) {
if(view[queenPos].color == 7) return NOP
return {cell:queenPos,color:3}
}
if(view[deRotate(queenPos,-4)].ant != null && !view[deRotate(queenPos,-4)].ant.friend && (view[queenPos].color == 1 || view[deRotate(queenPos,1)].color == 1 || view[deRotate(queenPos,-1)].color == 1)) {
if(view[queenPos].color == 7) return NOP
return {cell:queenPos,color:3}
}
if((followRail == null || followRail.cell == 4) && foe_at(deRotate(queenPos,-2)) == 1) {
if(view[queenPos].color == 7) return NOP
return {cell:queenPos,color:3}
}
if(followRail != null && followRail.cell != 4 && view[followRail.cell].color == 6 && view[deRotate(followRail.cell,1)].color == 6) {
followRail = {cell:deRotate(followRail.cell,1)}
}
return followRail
}
return NOP
}
// LANCE_TIP never needs to move
// Unfortunately, reusing an existing worker type for this purpose is not easily possible.
// Used against Sliding Miners as a stationary blocker to prevent the queen slipping past.
function moveTip(me, buddies) {
var queenPos = -1
var in_void = true
for(var i=0;i<9;i++) {
if(friend_at(i) == QUEEN) {
queenPos = i
}
if(view[i].color != WHITE) {
in_void = false
}
}
var colours = [0, 0, 0, 0, 0, 0, 0, 0, 0]
var enemies = 0
for(var i = 0; i < 9; ++ i) {
++ colours[view[i].color]
if(foe_at(i) > 0) enemies++
}
var onRails = rail_miners.near_nest(colours)
if(buddies[QUEEN] && !buddies[LANCE]) {
if(onRails) return NOP
if(foe_at(8-queenPos) == 4) {
return {cell:deRotate(queenPos,2)}
}
if(in_void) return {cell:deRotate(queenPos,4)}
if(enemies == 2 && queenPos % 2 == 0 && view[deRotate(queenPos,1)].ant == null) {
return {cell:queenPos,color:7}
}
if(enemies == 2 && queenPos % 2 == 1) {
return {cell:deRotate(queenPos,-1),color:7}
}
}
if(buddies[QUEEN] && buddies[LANCE]) {
if(enemies == 0 && view[queenPos].color == 1) return NOP
if(view[deRotate(queenPos,1)].color == 5 && friend_at(deRotate(queenPos,1)) == LANCE) return {cell:deRotate(queenPos,4)}
return {cell:deRotate(queenPos,2)}
}
if(!buddies[QUEEN] && view[4].color == 2) {
for(var i = 0; i < 9; ++ i) {
if(view[i].color == 8) return {cell:i}
}
}
if(queenPos >=0 && foe_at(deRotate(queenPos,2)) > 0 && view[deRotate(queenPos,2)].ant.food == 0 && foe_at(deRotate(queenPos,4)) > 0 && view[deRotate(queenPos,4)].ant.food > 0) {
return {cell:queenPos,color:7}
}
return NOP
}
function deRotate(m, amt) {
var rotationsCW = [1,2,5,8,7,6,3,0]
var rotationsCCW = [3,6,7,8,5,2,1,0]
if(m == 4 || m < 0 || m > 8 || amt == 0) return m
if(amt > 0)
return rotationsCW[(rotationsCW.indexOf(m)+amt)%8]
amt = -amt
return rotationsCCW[(rotationsCCW.indexOf(m)+amt)%8]
}
return play_safe(move_agent([
THIEF, move,
QUEEN, move,
BOUNCER, move,
LANCE, moveLance,
LANCE_TIP, moveTip
]))
```
Nobody had posted any answers exploiting the rule "An unladen worker adjacent to an enemy queen will steal 1 piece of food, if present.", so I decided to fix that!
This vampire seeks out specific targets to leech off of, which are continually updated (since this is a Community Wiki), and are sometimes disabled (via `worth_leeching` function) when they are no longer profitable enough.
*Note that the `worth_leeching` function mentioned, in addition to its use in disabling targets (if it returns false), allows for control over a given targeting object to maximize decision making, e.g. preventing Vampire from going after likely traps (Ziggurat creates little pockets that have no queen at the center) until Vampire has collected a sufficient quantity of food that getting stuck won't completely waste the round (i.e. only score 12 food). Parameters passed make the method very flexible without having to query the `view` object.*
Descriptions of the targets follow, in the order they appear in the code:
## Black Hole (target disabled)
When this finds Black Hole, it's pretty random whether we'll end up finding their queen, or their workers will drain our own food, or we'll bounce off and carry on searching. Turns out Black Hole is pretty hard to target.
## Ziggurat (target disabled)
Once at the centre of Ziggurat, the queen spawns thieves to extract as much food as possible as quickly as possible. It has to be fast since the colony now defends against us by spawning an army of workers (wasting their own food). Once all the food is gone, we make a "bouncer" and escort ourselves out, off in search of the next victim.
For Black Hole, this uses a worker sitting on the surface to wait for the target queen to pass by, while our queen sits deeper so that passing workers won't mug her. When the target queen eventually passes by, we follow her as much as possible.
For Miners on a rail, it uses a brute-force search to see if the queen is sitting on the center of the miner's main rail system. It then follows it back to its source (letting miner's workers step around). Once at the queen it spawns a thief as normal and drains the queen down to 9 food. Under 10 food the miner queen generates 3 workers for every 4 food she is given, making sticking around a low-return prospect. Bounce out and return later. (Thanks go to Draco18s for providing this environment's code!)
When this finds Ziggurat, it does pretty well, and causes interesting explosions, as seen in this early prototype (before bouncing was added):
[![exploded ziggurat](https://i.stack.imgur.com/TeUTr.jpg)](https://i.stack.imgur.com/TeUTr.jpg)
## FireFly (target disabled)
The block targeting Firefly uses the Ziggurat code as a baseline, but overrides the colors used. This makes it easy for any author to create a new Vampire target with ease while keeping byte-count low. Firefly code was disabled when Firefly didn't collect food, but was re-enabled in Mk. 5.
Not related to FIrefly, but Mk.4 also added in some additional object methods to handle side-stepping the target's workers (used by the anti-rail-miners code) which allows the Vampire queen to safely encounter a working rail miner repairer, instead of causing the two ants to get permanently stuck.
## Miners on a Rail (MoaR) / Sliding Minders (SlM)
When this finds Miners on a Rail, it tracks the rail in the outbound direction (the same direction unladen rail workers move) to avoid having its food stolen. When it finds the end of the rail, it acts like the Miners on a Rail's own worker 4 (the repairer). We know where the rail is, may as well follow that direction and loop back to start!
But the most common result is that we never find anything. This still does OK in that case; about middle of the scoreboard.
## Windmill
The development of the Don Quixote (Windmill targetting) code (in Mk. 5) was [fraught with challenges](https://chat.stackexchange.com/transcript/message/42449225#42449225) and went through many iterations, including one that would have been a new Ant type) before an acceptable strategy was developed. When the queen notices that she's standing on the middle rail of Windmill's main arms it spawns a new type of worker (code-named `LANCE`) in order to run down the *side* of the rail to avoid enemy workers (as if an enemy worker spots the vampire queen, they'll attempt to deadlock her), until eventually encountering the Windmill queen.
Two approaches to the queen are relatively clear and we can attempt to rely on the Lance arriving first (the Vampire queen will observe her worker holding food) and use that moment to spawn in a `THIEF` rather than stepping in and letting the Windmill queen spawn a worker adjacent to the Vampire Queen (resulting in a net-zero flow of food). The third approach ends up running into the gardeners, so the queen spawns a `LANCE_TIP` worker in order to do some political maneuvering to end up with a net-positive flow of food.
These attacks come at the cost of being unable to determine how much food the Windmill queen has and thus unable to predict when to spawn a `BOUNCER` and leave for better victims. However, this works in Vampire's favor as the Windmill is such a fat, juicy cow that it's more valuable to just stick around until the end: Windmill can easily gather several hundred food in only a few thousand moves, much much more than Vampire can acquire by trying to find a new target to leech.
The Garlicked (Mk6) update changes how the queen approaches slightly. The rail approach is identical, but upon reaching the queen, there are some slight changes, which result in only a single worker being adjacent to the Windmill queen, keeping the Vampire queen as far away as possible (to avoid Windmill workers, and most importantly, the garlic). The change was due to the fact that when two workers were adjacent to the Windmill queen, she would pack her bags and relocate.
Renewable Energy (Mk 7) revises the Windmill targetting logic, largely undoing the changes of Mk 6, as there were changes to Windmill that was causing the code to fail to leech 100% of the time. Revised success rate is about 70%, remaining 30% is due to dumb luck that is unavoidable. Approach vector slighly altered.
## Highway
Highway is easy to find. It is an ever-expanding greenish blob of doom. So, waiting to find and smash the dreams of Miners and Windmill *first* before going after Highway means that Vampire doesn't target too soon.
Finding the queen is simple: find the center of the highway and wait. She'll eventually come by. Worker arrangements will determine whether or not she gets stopped or we have to wait for another loop, but the delay doesn't make that big of a difference: eventually we'll catch her and steal *ALL* of her food.
If Vampire has 1000 food or more, she ignores Highway, because at that point, it doesn't matter any more.
[Answer]
# Langton's ant
*All of my answers will contain similar low-level logic in the form of the Formic Functions Framework. "HIGH-LEVEL LOGIC STARTS HERE" marks the end of the Framework's code.*
```
// FORMIC FUNCTIONS FRAMEWORK //
// Version 1.0 //
var WHITE = 1;
var QUEEN = 5;
var HERE = 4;
var MY_VO = view[HERE];
var ME = MY_VO.ant;
var NOP = move(HERE);
var ORTHOGONALS = [1, 3, 5, 7];
var DIAGONALS = [0, 2, 6, 8];
var DIRECTIONS = [0, 1, 2, 3, 5, 6, 7, 8];
var ALL_CELLS = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var VIEW_ORIENTATIONS = [
[0,1,2,
3,4,5,
6,7,8],
[6,3,0,
7,4,1,
8,5,2],
[8,7,6,
5,4,3,
2,1,0],
[2,5,8,
1,4,7,
0,3,6]
];
function rotateCW(cell, amount) {
if (cell === HERE) return cell;
var order = [0, 1, 2, 5, 8, 7, 6, 3];
return order[(order.indexOf(cell) + amount + 8) % 8];
}
function isDiagonal(cell) {
return DIAGONALS.includes(cell);
}
function isOrthogonal(cell) {
return ORTHOGONALS.includes(cell);
}
function move(cell) {
return {cell: cell};
}
function moveMany(cells) {
var p = [];
for (var i = 0; i < cells.length; i++) p.push(move(cells[i]));
return p;
}
function color(cell, col) {
return {cell: cell, color: col};
}
function colorMany(cells, col) {
var p = [];
for (var i = 0; i < cells.length; i++) p.push(color(cells[i], col));
return p;
}
function spawn(cell, type) {
return {cell: cell, type: type};
}
function spawnMany(cells, type) {
var p = [];
for (var i = 0; i < cells.length; i++) p.push(spawn(cells[i], type));
return p;
}
function isSane(action, ant) {
// TODO: Minimize this
if (ant === undefined || !ant.isObject) ant = ME;
if (action === undefined || action.cell < 0 || action.cell >= 9) return false;
if (action.color !== undefined) {
if (action.color < 1 || action.color > 8) return false;
return true;
}
else if (action.type !== undefined) {
if (action.type < 1 || action.type > 4) return false;
if (ant.type !== QUEEN || ant.food === 0) return false;
if (isOccupied(action.cell, ant) || view[action.cell].food !== 0) return false;
return true;
}
else {
if (isOccupied(action.cell, ant) && action.cell !== HERE) return false;
return true;
}
}
function isOccupied(cell, ant) {
if (ant === undefined || !ant.isObject) ant = ME;
return view[cell].ant !== null || (view[cell].food > 0 && ant.type !== QUEEN && ant.food === 1);
}
function isColoringMeaningful(action) {
return isSane(action) && action.color !== undefined && view[action.cell].color !== action.color;
}
function test(cell, test) {
var vo = view[cell];
return (test.color === undefined || test.color === vo.color) &&
(test.food === undefined || test.food === vo.food) &&
(test.ant === undefined || test.ant === vo.ant || (
(test.ant !== null && vo.ant !== null) &&
(test.ant.food === undefined || test.ant.food === vo.ant.food) &&
(test.ant.type === undefined || test.ant.type === vo.ant.type) &&
(test.ant.friend === undefined || test.ant.friend === vo.ant.friend)
));
}
function findOrientation(tests) {
var best = {orientation: null, matches: []};
for (var o = 0; o < VIEW_ORIENTATIONS.length; o++) {
var matches = [];
for (var i = 0; i < tests.length; i++) {
if (test(VIEW_ORIENTATIONS[o][tests[i].cell], tests[i])) {
matches.push(tests[i]);
}
}
if (matches.length > best.matches.length) {
best.orientation = o;
best.matches = matches;
}
}
return best;
}
function orientCells(orientation, cells) {
if (orientation === null || orientation < 0 || orientation >= 4) orientation = 0;
for (var i = 0; i < cells.length; i++) {
cells[i] = VIEW_ORIENTATIONS[orientation][cells[i]];
}
return cells;
}
function findFirst(func, cells) {
if (cells === undefined) cells = ALL_CELLS;
for (var i = 0; i < cells.length; i++) {
if (func(cells[i])) return cells[i];
}
return null;
}
function findAll(func, cells) {
if (cells === undefined) cells = ALL_CELLS;
var found = [];
for (var i = 0; i < cells.length; i++) {
if (func(cells[i])) found.push(cells[i]);
}
return found;
}
// HIGH-LEVEL LOGIC STARTS HERE //
var ROAD_COL = 3;
var SIM_COLS = [ 1, 8, 5, 6, 4, 2, 7, 3]; // SIM_COLS.length must be greater or equal to SIM_ROTS.length
var SIM_ROTS = [-1,-1,+1,-1,-1,+1,-1,-1];
// Here are some additional rulesets to play around with:
// [+1,-1,+1,-1,+1,-1,+1,-1] // Classic Langton's ant, extended to use all 8 colors cyclically
// [+1,+1,-1,+1,-1,+1,+1] // Produces a very interesting highway
// [-1,-1,+1,-1,-1,+1,-1,-1] // The default one -- chosen because it produces a highway nearly instantly, and the highway itself is pretty efficient
// [-1,+1,-1,-1,-1,+1,+1,-1]
// [-1,-1,+1,-1,-1,+1,-1,-1]
// [-1,+1,-1,-1,-1,+1,+1,-1]
// [+1,-1,+1,+1,+1,-1]
var ANCHOR = 1;
var TAIL = 2;
var DEBUG_MODE = false;
function getSimColIndex(cell) {
return Math.max(SIM_COLS.lastIndexOf(view[cell].color, SIM_ROTS.length - 1), 0);
}
function getNextSimCol(simColIndex) {
return SIM_COLS[(simColIndex + 1) % SIM_ROTS.length];
}
function getSimRot(simColIndex) {
return SIM_ROTS[simColIndex];
}
function run() {
switch (ME.type) {
case QUEEN: {
var anch = findFirst(c => test(c, {ant: {type: ANCHOR, friend: true}}), DIRECTIONS);
if (anch !== null) {
if (isOrthogonal(anch)) {
var tail = findFirst(c => test(c, {ant: {type: TAIL, friend: true}}), DIAGONALS);
if (tail !== null) {
return [move(rotateCW(anch, -2 * getSimRot(getSimColIndex(HERE))))].filter(isSane)[0] || NOP;
} else {
var nanch = rotateCW(anch, -getSimRot(getSimColIndex(anch)));
return color(nanch, getNextSimCol(getSimColIndex(nanch)));
}
} else {
return NOP;
}
} else {
var tailO;
if (ME.food === 2) {
return spawnMany(ORTHOGONALS, TAIL).filter(isSane)[0] || NOP;
} else if (ME.food === 1 && (tailO = findOrientation([{cell: 1, ant: {type: TAIL, friend: true}}])).orientation !== null) {
return spawnMany(orientCells(tailO.orientation, [3, 5]), ANCHOR).filter(isSane)[0] || NOP;
}
var f;
if ((f = findFirst(c => test(c, {food: 1})))) {
return move(f);
}
if (test(HERE, {color: ROAD_COL})) {
return moveMany(orientCells(findOrientation([{cell: 0, color: ROAD_COL}]).orientation, [8, 6, 2])).filter(a => isSane(a) && !test(a.cell, {color: ROAD_COL}))[0] || moveMany(DIAGONALS).filter(isSane)[0] || NOP;
} else {
return color(HERE, ROAD_COL);
}
}
break;
}
case ANCHOR: {
var queen = findFirst(c => test(c, {ant: {type: QUEEN, friend: true}}), DIAGONALS);
var tail = findFirst(c => test(c, {ant: {type: TAIL, friend: true}}), ORTHOGONALS);
var qp = [rotateCW(queen, -1), rotateCW(queen, +1)];
var tp = [rotateCW(tail, -2), rotateCW(tail, +2)];
for (var i = 0; i < qp.length; i++) {
for (var j = 0; j < tp.length; j++) {
if (qp[i] === tp[j]) return [move(qp[i])].filter(isSane)[0] || NOP;
}
}
return NOP;
break;
}
case TAIL: {
var anch = findFirst(c => test(c, {ant: {type: ANCHOR, friend: true}}), DIAGONALS);
if (anch !== null) {
var rot = getSimRot(getSimColIndex(anch));
var nanch = rotateCW(anch, rot);
if (test(nanch, {ant: {type: QUEEN, friend: true}})) return [move(rotateCW(anch, -rot))].filter(isSane)[0] || NOP;
return [move(nanch)].filter(isSane)[0] || NOP;
} else {
return NOP;
}
break;
}
}
}
var output = run();
if (isSane(output)) return output;
else {
if (DEBUG_MODE) {
return;
} else {
return NOP;
}
}
```
[![Langton's ant ("RL")](https://i.stack.imgur.com/CyVP8.png)](https://i.stack.imgur.com/CyVP8.png)
[![Langton's ant ("LLRLLRLL")](https://i.stack.imgur.com/ttmPV.png)](https://i.stack.imgur.com/ttmPV.png)
---
# Introduction
This is an implementation of **[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant "Langton's ant")** within the confines of the Formic Functions QOTH challenge. As an added bonus, it supports **multi-color variants** of Langton's ant. I also managed to utilize the full palette of **up to *8 colors.*** Furthermore, this ant completes ***one* step** of the simulation **in *two* steps** of in-game time.
Unfortunately, the more interesting variants of Langton's ant take more than 8 colors, so I settled on an efficient one instead. I wrote a supplementary program to find the ants that cover the largest amount of land within a specified time limit, and stumbled across multiple variations of the "RRL" ruleset. They all cover **4168 cells within 15000 steps.**
Now, 4000 cells is ***abysmal!*** This means that, on average, this entry will end the game with ***FOUR*** food. *And that's on an empty board!* Frankly, the ***[Brownian Jig](https://codegolf.stackexchange.com/a/135103/74965%20Brownian%20Jig)*** does better than this. In short, this isn't a serious contender when it comes to position on the scoreboard. What it can do, however, is *mess other entries up.* And that's the sole reason why I even bothered to submit this. Very complex interactions often emerge between this entry and ones that rely heavily on colors. And those that rely on colors *usually suffer.*
---
# Explanation
The colors (`SIM_COLS`) have a corresponding rotation (`SIM_ROTS`) that the Queen uses to change the direction she's heading. `+1` means clockwise rotation ("R"), `-1` means counterclockwise rotation ("L"). The classic Langton's ant would be `SIM_COLS = [ 1, 8]`, `SIM_ROTS = [+1,-1]`. The `SIM_COLS` array effectively discards all elements that don't have a matching element in the `SIM_ROTS` array. All colors that are not contained within the truncated `SIM_COLS` array are treated as color 0 and will never be produced by the ant itself.
Like any other proper ant, this one starts by gathering enough food so it can start *actually doing things.* It requires **2 food**.
After finishing the initial scramble, the Queen spawns two ants, named **Anchor** and **Tail**. The Queen spawns the Tail first, adjacent orthogonally (cells 1, 3, 5, 7) to the Queen. Then, she spawns the Anchor, adjacent orthogonally to the Queen and diagonally (cells 0, 2, 6, 8) to the Tail.
The behavior consists of an ever-repeating cycle of two different steps.
## Step 1
Tail: Searches for the cell that the Queen occupied 2 simulation steps ago and goes there. Note that it uses the color from under the Anchor and the presence of the Queen (or lack thereof) to accurately determine the target cell. This is prone to disasters that I will address in a future update.
Anchor: Doesn't do anything.
Queen: Finds the Anchor and treats it as the inverse of the direction the ant is going. The direction is then rotated according to the color under the Queen. The Queen moves to the cell indicated by the rotated direction.
## Step 2
Tail: Doesn't do anything.
Anchor: Searches for a cell that is diagonally adjacent to the Tail and orthogonally adjacent to the Queen and goes there. There's at most one such cell.
Queen: Similarly to the Tail in step 1, she searches for the cell that she occupied 2 simulation steps ago and changes its color in a cyclical fashion. Note that she uses the color from under the Anchor to accurately determine the target cell. The worst disaster that could happen is coloring the wrong cell, and while it would alter the trajectory of the ant, it's not really an issue because the trajectory is going to be altered by the presence of other ants anyway.
## Determining what to do
The Queen determines the current step by searching for the Tail orthogonally. If she finds it, she's on step 1. Otherwise, she's on step 2. In rare cases, she might find the Anchor adjacent diagonally to herself. In that case, she will not do anything.
The Anchor does not have any logic to determine its step. It always strives to be orthogonally adjacent to the Queen and diagonally adjacent to the Tail. If there is no such cell, it simply doesn't move.
The Tail determines the current step by searching for the Anchor diagonally. If it finds it, it's on step 1. Otherwise, it's on step 2.
The previously mentioned disaster during the movement of the Tail can be triggered by an ant altering the color under the Anchor. If the altered color indicates a different rotation than the original and the Queen is not in sight of the Tail, the resulting position after the Tail's movement is a straight line of the 3 ants. I am currently working on a remedy to this situation.
---
While this is definitely *not* a serious contender for first place, it's bound to spice things up on the arena and shift the meta a bit towards the colorless ants. I've got a couple of submissions cooking (and one of them is looking *really* spicy), so expect some more entries from me in the coming weeks.
[Answer]
# Ziggurat v3.0
```
var clockwise = [1,2,5,0,4,8,3,6,7];
var opposite = [8,7,6,5,4,3,2,1,0];
var cyclic_cw = [0,1,2,5,8,7,6,3,0];
var worker_colors = [4,5,7,8];
var next_worker_color = [1,1,1,1,5,7,1,8,4];
var prev_worker_color = [1,1,1,1,8,4,1,5,7];
var diags = [0,2,6,8];
var orthos = [1,3,5,7];
var cleaning_color = 6;
// Borrowed from Medusa
function clean(move) {
if (move["color"] == undefined) {
if (view[move["cell"]].ant != null) {
move = {cell: 4};
}
if (move["type"] == undefined) {
if (view[move["cell"]].food == 1 && view[4].ant.type < 5 && view[4].ant.food > 0) {
move = {cell: 4};
}
} else if (view[4].ant.type != 5 || view[4].ant.food == 0 || view[move["cell"]].food == 1) {
move = {cell: 4};
}
}
return move;
}
function worker_blank(cel) {
return (worker_colors.indexOf(view[cel].color) < 0);
}
// Own status
var my_color = view[4].color;
var my_food = view[4].ant.food;
var my_type = view[4].ant.type;
// Random free cell
var free_cell = 4;
for (var cel = 0; cel < 9; cel++) {
if (view[cel].ant == null) {
free_cell = cel;
}
}
// Check surroundings
var blanks = 0;
var outer_edge = 0;
var inner_edge = 0;
var next_edge = -1;
var prev_nonblank = -1;
var some_nonblank = -1;
var prev_cell = -1;
var next_cell = -1;
var food_cell = -1;
var nonblank_color = 0;
var cleaning_marker = -1;
var uniform = 1;
var low_type = -1;
var friend_workers = 0;
var guards = 0;
var enemies = 0;
var enemy_queens = 0;
var my_queen = -1;
if (!worker_blank(4)) {
nonblank_color = view[4].color;
}
for (var ix = 0; ix < 8; ix++) {
var cel = cyclic_cw[ix];
var cel2 = cyclic_cw[ix+1];
if (view[cel].food == 1) {
food_cell = cel;
}
if (worker_blank(cel)) {
blanks++;
if (!worker_blank(cel2)) {
if (worker_blank(4)) {
outer_edge = 1;
} else {
inner_edge = 1;
}
next_edge = cel;
prev_nonblank = cel2;
}
if (view[cel].color == cleaning_color) {
cleaning_marker = cel;
}
} else {
some_nonblank = cel;
if (nonblank_color == 0) {
nonblank_color = view[cel].color;
} else if (view[cel].color != nonblank_color) {
uniform = 0;
}
}
if ((!worker_blank(4) && view[cel2].color == prev_worker_color[my_color] && view[cel2].ant == null) || (worker_blank(4) && !worker_blank(cel2))) {
prev_cell = cel2;
}
if (!worker_blank(4) && view[cel2].color == next_worker_color[my_color] && view[cel2].ant == null) {
next_cell = cel2;
}
if (view[cel].ant != null) {
var the_ant = view[cel].ant;
if (the_ant.friend) {
if (low_type < 0 || the_ant.type < low_type) {
low_type = the_ant.type;
}
if (the_ant.type == 4) {
guards++;
} else if (the_ant.type == 5) {
my_queen = cel;
} else {
friend_workers++;
}
} else {
enemies++;
if (the_ant.type == 5) {
enemy_queens++;
}
}
}
}
// Queen before finding food (motile)
if (my_type == 5 && worker_blank(4)) {
if (my_food > 1) {
return {cell:4, color:worker_colors[1]};
}
if (food_cell >= 0 && my_color != 1) {
return clean({cell:food_cell});
}
if (my_color == 2) {
for (var ix = 0; ix < 4; ix++) {
var cel = diags[ix];
var oppo = opposite[cel];
if (view[cel].color == 2) {
if (view[oppo].color == 1 && worker_blank(oppo) && view[oppo].ant == null) {
return clean({cell:oppo});
}
if (view[oppo].color != 2) {
return {cell:oppo, color:1};
}
}
}
for (var ix = 0; ix < 4; ix++) {
var cel = diags[ix];
if (view[cel].color != 2) {
return {cell:cel, color:2};
}
}
}
if (my_color == 1) {
return {cell:4, color:2};
}
return clean({cell:free_cell});
}
// Queen after finding food (sessile)
if (my_type == 5) {
for (var ix = 0; ix < 8; ix++) {
cel = cyclic_cw[ix];
if (worker_blank(cel)) {
return {cell:cel, color:worker_colors[1]};
}
}
if (my_color != worker_colors[0]) {
if (my_food > 0) {
return clean({cell:free_cell, type:1});
} else {
return {cell:4, color:worker_colors[0]};
}
}
if (my_food > 0) {
if (my_food > 3 && guards < 2) {
return clean({cell:free_cell, type:4});
}
if (0 < low_type && low_type < 3) {
return clean({cell:free_cell, type:(low_type + 1)});
}
}
return {cell:4};
}
// Queen's guard
if (my_type == 4) {
// Queen is a nbor
if (my_queen >= 0) {
if (enemy_queens > 0) {
return {cell:4};
}
if (my_queen == 1) {
return clean({cell:5});
}
return clean({cell:clockwise[my_queen]});
}
// Try to get to queen
if (prev_cell >= 0) {
return clean({cell:prev_cell});
}
// Wander
return clean({cell:free_cell});
}
// Worker
// Create new ziggurat
if (blanks == 8 && cleaning_marker < 0 && my_color != cleaning_color) {
if (worker_colors.indexOf(my_color) >= 0) {
return {cell:free_cell, color:my_color};
}
return {cell:free_cell, color:worker_colors[0]};
}
var front = view[1].color;
if (!worker_blank(4) && !worker_blank(1) && my_color != front) {
if (view[7].color == front || (view[6].color == front && view[8].color == front)) {
return {cell:4, color:front};
}
}
if (my_food == 0) {
// Grab food
if (food_cell >= 0 && (!worker_blank(4) || !worker_blank(food_cell))) {
return clean({cell:food_cell});
}
// Clear marked uniform region
if (my_color == cleaning_color && uniform) {
if (blanks < 7) {
return {cell:some_nonblank, color:1};
} else if (blanks == 7) {
return {cell:some_nonblank, color:cleaning_color};
}
}
// Follow cleaning color
if (blanks == 8) {
if (cleaning_marker < 0 || my_color == cleaning_color) {
return {cell:4, color:1};
} else if (cleaning_marker >= 0) {
return clean({cell:cleaning_marker});
}
}
// Dive into uniform region
if (blanks > 3 && worker_blank(4) && worker_blank(1) && !worker_blank(2) && view[2].color == view[5].color && view[2].color == view[8].color) {
return clean({cell:2});
}
// Mark uniform region for clearing
if (!worker_blank(4) && uniform && (blanks < 4 || (blanks < 7 && ((worker_blank(1) && worker_blank(7)) || (worker_blank(3) && worker_blank(5)))))) {
return {cell:4, color:cleaning_color};
}
// Extend edge
if (outer_edge) {
var new_color = 0;
var cl = clockwise[next_edge];
var cl2 = clockwise[cl];
if (!worker_blank(1) && view[7].color == view[1].color) {
new_color = view[1].color;
} else if (!worker_blank(3) && view[5].color == view[3].color) {
new_color = view[3].color;
} else if (!worker_blank(cl2) && view[cl].color == next_worker_color[view[cl2].color]) {
if (cl > 1) {
new_color = view[cl].color;
} else {
new_color = next_worker_color[view[cl].color];
}
} else if (!worker_blank(cl)) {
new_color = next_worker_color[view[cl].color];
} else if (prev_nonblank >= 0) {
new_color = next_worker_color[prev_nonblank];
}
if (new_color == 0 && blanks < 2) {
new_color = worker_colors[0];
}
if (new_color > 0) {
return {cell:4, color:new_color};
} else {
return clean({cell:next_edge});
}
}
// Escape from hole
if (worker_blank(4) && blanks == 0) {
return {cell:4, color:next_worker_color[nonblank_color]};
}
// Go outside or fill it
if (inner_edge && next_edge >= 0) {
if (friend_workers > 1) {
return clean({cell:free_cell});
}
if (blanks == 4 && prev_nonblank >= 0) {
return {cell:next_edge, color:next_worker_color[view[prev_nonblank].color]};
}
if (view[next_edge].ant == null) {
return clean({cell:next_edge});
}
return {cell:4};
}
// Go toward border
if (!worker_blank(4) && next_cell >= 0 && next_cell != 1) {
return clean({cell:next_cell});
}
// Wander
return clean({cell:free_cell});
}
if (my_food > 0) {
// Take food to queen
if ((prev_cell >= 0 && prev_cell != 1) || (prev_cell >= 0 && worker_blank(4))) {
return clean({cell:prev_cell});
}
// Wander
if (worker_blank(free_cell) && !worker_blank(4)) {
return {cell:4};
}
return clean({cell:free_cell});
}
return clean({cell:free_cell});
```
## How it works
This ant is a combination of [Black Hole](https://codegolf.stackexchange.com/a/135157/32014) and [Medusa](https://codegolf.stackexchange.com/a/135271/32014).
The queen begins by searching for food diagonally.
Once it has two units of food, it becomes sessile and makes two workers.
The workers circle around the queen and make a growing striped region (the "ziggurat") using four colors.
When a worker finds food, it follows the stripes and takes it to the queen, who sits at the center of the square.
If the worker was one of the original two, the queen makes a new worker; otherwise, she stores the food.
## Comments
**Version 2.0** uses four colors, which hopefully prevents the ants from getting lost so easily.
The worker creation scheme has also been revamped to first make lots of workers and grow the region, then stash food to make it to the leaderboard.
There are also more checks against illegal moves.
**Version 2.1** features an improved ziggurat construction routine.
Workers are sometimes able to choose their color from two options, which makes the stripe pattern more random, hopefully fooling the Vampire.
Workers sometimes lay down two colors before moving, which makes the ziggurat grow faster.
When inside the ziggurat, workers sometimes make a random move to escape infinite loops, and try to correct certain local inconsistencies.
The queen is smarter about avoiding trails in her motile phase.
Finally, if the sessile queen is attacked, she fights back by creating a burst of new workers, which should also help her recover if the attacker was a Trail-eraser that cut her off from all existing workers.
**Version 3.0** has more tweaks to the construction routine. As a (largely untested) countermeasure against Black Hole and Wildfire, workers that discover uniform colored regions will try to erase them. The queen no longer spawns dozens of workers when attacked; instead, she has a dedicated pair of guardian ants orbiting around her. She will also wait longer before starting to hoard food.
I don't really know JS, so the code is a horrid mess.
Here's a picture of the striped region:
[![Ziggurat](https://i.stack.imgur.com/wOeKv.png)](https://i.stack.imgur.com/wOeKv.png)
[Answer]
# Wildfire Mk.3
*All my answers are sharing the same set of low-level helper functions. Search for "High-level logic begins here" to see the code specific to this answer.*
```
// == Shared low-level helpers for all solutions ==
var QUEEN = 5;
var WHITE = 1;
var COL_MIN = WHITE;
var COL_LIM = 9;
var CENTRE = 4;
var NOP = {cell: CENTRE};
var DIR_FORWARDS = false;
var DIR_REVERSE = true;
var SIDE_RIGHT = true;
var SIDE_LEFT = false;
function sanity_check(movement) {
var me = view[CENTRE].ant;
if(!movement || (movement.cell|0) !== movement.cell || movement.cell < 0 || movement.cell > 8) {
return false;
}
if(movement.type) {
if(movement.color) {
return false;
}
if((movement.type|0) !== movement.type || movement.type < 1 || movement.type > 4) {
return false;
}
if(view[movement.cell].ant || view[movement.cell].food) {
return false;
}
if(me.type !== QUEEN || me.food < 1) {
return false;
}
return true;
}
if(movement.color) {
if((movement.color|0) !== movement.color || movement.color < COL_MIN || movement.color >= COL_LIM) {
return false;
}
if(view[movement.cell].color === movement.color) {
return false;
}
return true;
}
if(movement.cell !== CENTRE && view[movement.cell].ant) {
return false;
}
if(view[movement.cell].food + me.food > 1 && me.type !== QUEEN) {
return false;
}
return true;
}
function as_array(o) {
if(Array.isArray(o)) {
return o;
}
return [o];
}
function best_of(movements) {
var m;
for(var i = 0; i < movements.length; ++ i) {
if(typeof(movements[i]) === 'function') {
m = movements[i]();
} else {
m = movements[i];
}
if(sanity_check(m)) {
return m;
}
}
return null;
}
function play_safe(movement) {
// Avoid disqualification: no-op if moves are invalid
return best_of(as_array(movement)) || NOP;
}
var RAND_SEED = (() => {
var s = 0;
for(var i = 0; i < 9; ++ i) {
s += view[i].color * (i + 1);
s += view[i].ant ? i * i : 0;
s += view[i].food ? i * i * i : 0;
}
return s % 29;
})();
var ROTATIONS = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[2, 5, 8, 1, 4, 7, 0, 3, 6],
];
function try_all(fns, limit, wrapperFn, checkFn) {
var m;
fns = as_array(fns);
for(var i = 0; i < fns.length; ++ i) {
if(typeof(fns[i]) !== 'function') {
if(checkFn(m = fns[i])) {
return m;
}
continue;
}
for(var j = 0; j < limit; ++ j) {
if(checkFn(m = wrapperFn(fns[i], j))) {
return m;
}
}
}
return null;
}
function identify_rotation(testFns) {
// testFns MUST be functions, not constants
return try_all(
testFns,
4,
(fn, r) => fn(ROTATIONS[r]) ? ROTATIONS[r] : null,
(r) => r
);
}
function near(a, b) {
return (
Math.abs(a % 3 - b % 3) < 2 &&
Math.abs(Math.floor(a / 3) - Math.floor(b / 3)) < 2
);
}
function try_all_angles(solverFns) {
return try_all(
solverFns,
4,
(fn, r) => fn(ROTATIONS[r]),
sanity_check
);
}
function try_all_cells(solverFns, skipCentre) {
return try_all(
solverFns,
9,
(fn, i) => ((i === CENTRE && skipCentre) ? null : fn(i)),
sanity_check
);
}
function try_all_cells_near(p, solverFns) {
return try_all(
solverFns,
9,
(fn, i) => ((i !== p && near(p, i)) ? fn(i) : null),
sanity_check
);
}
function ant_type_at(i, friend) {
return (view[i].ant && view[i].ant.friend === friend) ? view[i].ant.type : 0;
}
function friend_at(i) {
return ant_type_at(i, true);
}
function foe_at(i) {
return ant_type_at(i, false);
}
function ant_type_near(p, friend) {
for(var i = 0; i < 9; ++ i) {
if(i !== 4 && ant_type_at(i, friend) && near(i, p)) {
return true;
}
}
return false;
}
function move_agent(agents) {
var me = view[CENTRE].ant;
var buddies = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)];
}
for(var i = 0; i < agents.length; i += 2) {
if(agents[i] === me.type) {
return agents[i+1](me, buddies);
}
}
return null;
}
function grab_nearby_food() {
return try_all_cells((i) => (view[i].food ? {cell: i} : null), true);
}
function go_anywhere() {
return try_all_cells((i) => ({cell: i}), true);
}
function colours_excluding(cols) {
var r = [];
for(var i = COL_MIN; i < COL_LIM; ++ i) {
if(cols.indexOf(i) === -1) {
r.push(i);
}
}
return r;
}
function generate_band(start, width) {
var r = [];
for(var i = 0; i < width; ++ i) {
r.push(start + i);
}
return r;
}
function colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function(c) {
return colours[(colours.indexOf(c) + 1) % colours.length];
}
};
}
function random_colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function() {
return colours[RAND_SEED % colours.length];
}
};
}
function fast_diagonal(colourBand, avoidedColours) {
if(!avoidedColours) {
avoidedColours = colourBand;
}
var m = try_all_angles([
// Avoid nearby checked areas
(rot) => {
if(
!avoidedColours.contains(view[rot[0]].color) &&
avoidedColours.contains(view[rot[5]].color) &&
avoidedColours.contains(view[rot[7]].color)
) {
return {cell: rot[0]};
}
},
// Go in a straight diagonal line if possible
(rot) => {
if(
!avoidedColours.contains(view[rot[0]].color) &&
avoidedColours.contains(view[rot[8]].color)
) {
return {cell: rot[0]};
}
},
// When in doubt, pick randomly but avoid doubling-back
(rot) => (avoidedColours.contains(view[rot[0]].color) ? null : {cell: rot[0]}),
// Double-back when absolutely necessary
(rot) => ({cell: rot[0]})
]);
// Lay a colour track so that we can avoid doubling-back
// (and mess up our foes as much as possible)
if(!avoidedColours.contains(view[CENTRE].color)) {
var prevCol = m ? view[8-m.cell].color : WHITE;
return {cell: CENTRE, color: colourBand.next(prevCol)};
}
return m;
}
function follow_edge(obstacleFn, side, resultFn) {
// Since we don't know which direction we came from, this can cause us to get
// stuck on islands, but the random orientation helps to ensure we don't get
// stuck forever.
if(!resultFn) {
resultFn = (i) => ({cell: i});
}
var order = ((side === SIDE_LEFT)
? [0, 3, 6, 7, 8, 5, 2, 1, 0]
: [0, 1, 2, 5, 8, 7, 6, 3, 0]
);
return try_all(
[obstacleFn],
order.length - 1,
(fn, i) => ((fn(order[i+1]) && !fn(order[i])) ? resultFn(order[i]) : null),
sanity_check
);
}
function start_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => ((
!protectedCols.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 2 : 0]].color) &&
!colourBand.contains(view[rot[1]].color)
)
? {cell: rot[right ? 5 : 3], color: colourBand.next(WHITE)}
: null)
]);
}
function lay_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var ahead = rot[right ? 2 : 0];
var behind = rot[right ? 8 : 6];
if(
colourBand.contains(view[behind].color) &&
!protectedCols.contains(view[ahead].color) &&
!colourBand.contains(view[ahead].color) &&
!colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
return {cell: ahead, color: colourBand.next(view[behind].color)};
}
}
]);
}
function follow_dotted_path(colourBand, side, direction) {
var forwards = (direction === DIR_REVERSE) ? 7 : 1;
var right = (side === SIDE_RIGHT);
return try_all_angles([
// Cell on our side? advance
(rot) => {
if(
colourBand.contains(view[rot[right ? 5 : 3]].color) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[0]].color) &&
!colourBand.contains(view[rot[2]].color)
) {
return {cell: rot[forwards]};
}
},
// Cell ahead and behind? advance
(rot) => {
var passedCol = view[rot[right ? 8 : 6]].color;
var nextCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(passedCol) &&
nextCol === colourBand.next(passedCol) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[right ? 0 : 2]].color)
) {
return {cell: rot[forwards]};
}
}
]);
}
function escape_dotted_path(colourBand, side, newColourBand) {
var right = (side === SIDE_RIGHT);
if(!newColourBand) {
newColourBand = colourBand;
}
return try_all_angles([
// Escape from beside the line
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
!colourBand.contains(view[rot[right ? 8 : 6]].color) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[rot[7]].color) ||
colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
// not oriented, or in a corner
return null;
}
return best_of([
{cell: rot[right ? 0 : 2], color: newColourBand.next(approachingCol)},
{cell: rot[right ? 3 : 5]},
{cell: rot[right ? 0 : 2]},
{cell: rot[right ? 6 : 8]},
{cell: rot[right ? 2 : 0]},
{cell: rot[right ? 8 : 6]},
{cell: rot[right ? 5 : 3]}
]);
},
// Escape from inside the line
(rot) => {
if(
!colourBand.contains(view[rot[7]].color) ||
!colourBand.contains(view[rot[1]].color) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
return best_of([
{cell: rot[3]},
{cell: rot[5]},
{cell: rot[0]},
{cell: rot[2]},
{cell: rot[6]},
{cell: rot[8]}
]);
}
]);
}
function latch_to_dotted_path(colourBand, side) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(approachingCol) &&
view[rot[right ? 8 : 6]].color === colourBand.next(approachingCol) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color)
) {
// We're on the wrong side; go inside the line
return {cell: rot[right ? 5 : 3]};
}
},
// Inside the line? pick a side
(rot) => {
var passedCol = view[rot[7]].color;
var approachingCol = view[rot[1]].color;
if(
!colourBand.contains(passedCol) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
if((approachingCol === colourBand.next(passedCol)) === right) {
return best_of([{cell: rot[3]}, {cell: rot[6]}, {cell: rot[0]}]);
} else {
return best_of([{cell: rot[5]}, {cell: rot[2]}, {cell: rot[8]}]);
}
}
]);
}
// == High-level logic begins here ==
var groundCol = 5;
var poisonCol = 8;
var DIRECTOR = 1;
var FORAGER0 = 2;
var FORAGER1 = 3;
var FORAGER2 = 4;
var MAX_FORAGER_TYPES = 3; // Worker creation throttle
var MIN_FOOD = 3; // Don't embarrass ourselves when things go bad
var MAX_FOOD_SPAWN = 80; // If we're doing well, don't spoil it all
var GROUND_COLOURS = colour_band([groundCol, poisonCol]);
var POISON_COLOURS = colour_band([poisonCol]);
var SAFE_COLOURS = random_colour_band(colours_excluding([WHITE, groundCol, poisonCol]));
var INITIAL_OBSTACLES = random_colour_band(colours_excluding([WHITE]));
function ground_at(i) {
return GROUND_COLOURS.contains(view[i].color);
}
function unlaiden_friend_at(i) {
return friend_at(i) && (friend_at(i) === QUEEN || !view[i].ant.food);
}
function obstacle_at(i) {
// foes are unpredictable, so don't consider them obstacles
return view[i].food || unlaiden_friend_at(i) || GROUND_COLOURS.contains(view[i].color);
}
function wait_if_blocked(i) {
return friend_at(i) ? {cell:CENTRE} : {cell: i};
}
function move_director(me, buddies) {
if(!buddies[QUEEN]) {
// Lost the queen!
return go_anywhere();
}
var rot = identify_rotation((rot) => (
friend_at(rot[0]) === QUEEN || friend_at(rot[1]) === QUEEN
));
var ready = (friend_at(rot[1]) === QUEEN && view[rot[1]].color === groundCol);
var shift = (view[rot[2]].color === groundCol && GROUND_COLOURS.contains(view[rot[5]].color));
return best_of([
// Ensure we never end up underground unless we mean to, and provide a
// base poison layer to help workers find the right side if lost
{cell: CENTRE, color: poisonCol},
// {cell: rot[5], color: poisonCol},
{cell: rot[3], color: poisonCol},
// Move up to avoid own line after wrapping (us being underground is a signal)
(ready && shift) && {cell: rot[2]},
// Advance
(ready && !shift) && {cell: rot[5]},
// Make the poison layer more solid if we have extra time
{cell: rot[7], color: poisonCol},
{cell: rot[6], color: poisonCol},
{cell: rot[8], color: poisonCol},
// Don't lose the queen
NOP
]);
}
function move_forager(me, buddies) {
var underground = GROUND_COLOURS.contains(view[CENTRE].color);
var buried = 0;
for(var i = 0; i < 9; ++ i) {
if(i !== 4 && GROUND_COLOURS.contains(view[i].color)) {
++ buried;
}
}
var travelCol = underground ? POISON_COLOURS : SAFE_COLOURS;
if(buddies[DIRECTOR]) {
// We've somehow got in the way of the line; get out of the way
return try_all_angles((rot) =>
((friend_at(rot[6]) === DIRECTOR || friend_at(rot[7]) === DIRECTOR) &&
best_of([{cell: rot[0]}, {cell: rot[1]}, {cell: rot[2]}])));
}
if(me.food) {
// We have food for the queen; run ahead to find her as fast as we can
return best_of([
// Identify confusing pinch points and close them (don't get stuck on islands)
try_all_angles((rot) => (
obstacle_at(rot[1]) && obstacle_at(rot[7]) &&
!obstacle_at(rot[5]) && !GROUND_COLOURS.contains(view[CENTRE].color)
) && {cell: CENTRE, color: groundCol}),
// We're enclosed; mark this as a dead-end
(buried >= 7) && {cell: CENTRE, color: poisonCol},
// Race to queen, but don't climb over each other and cause a blockage
follow_edge(obstacle_at, SIDE_RIGHT, wait_if_blocked),
// Lost? Travel quickly to find the surface again
fast_diagonal.bind(null, travelCol),
// Totally lost
go_anywhere
]);
}
if(buddies[QUEEN]) {
// Don't overtake the queen!
return NOP;
}
// Paint the ground
if(!underground) {
return {cell: CENTRE, color: groundCol};
}
return best_of([
// Unpaint small islands which would confuse us or our buddies
(buried >= 3) && try_all_angles((rot) => (
!view[rot[0]].ant &&
GROUND_COLOURS.contains(view[rot[0]].color) &&
!GROUND_COLOURS.contains(view[rot[1]].color) &&
!GROUND_COLOURS.contains(view[rot[3]].color)
) && {cell: rot[0], color: SAFE_COLOURS.next(WHITE)}),
(buried >= 3) && try_all_angles((rot) => (
!view[rot[1]].ant &&
GROUND_COLOURS.contains(view[rot[1]].color) &&
!GROUND_COLOURS.contains(view[rot[0]].color) &&
!GROUND_COLOURS.contains(view[rot[2]].color)
) && {cell: rot[1], color: SAFE_COLOURS.next(WHITE)}),
// Follow line
follow_edge(ground_at, SIDE_RIGHT, wait_if_blocked),
// Disoriented; find the surface again
fast_diagonal.bind(null, travelCol),
// Totally lost; random walk
{cell: 0}
]);
}
function move_queen(me, buddies) {
if(buddies[DIRECTOR]) {
var rot = identify_rotation((rot) => (
(friend_at(rot[7]) === DIRECTOR && view[rot[7]].color !== groundCol) ||
(friend_at(rot[5]) === DIRECTOR && view[rot[5]].color === groundCol) ||
friend_at(rot[8]) === DIRECTOR
));
var rand14 = rot === ROTATIONS[0];
var existing = friend_at(rot[0]);
var nextType = existing ? (existing + 1) : FORAGER0;
var workerSpawn = (
me.food > MIN_FOOD && me.food < MAX_FOOD_SPAWN &&
view[rot[3]].color === groundCol && // Don't spawn if disrupted
view[rot[0]].color === WHITE && // Don't spawn while stuck in a nest
view[rot[1]].color === WHITE &&
!friend_at(rot[1]) && !friend_at(rot[3]) && !friend_at(rot[6]) &&
(existing || rand14) // reduce likelihood of spawning new chains
);
return best_of([
// Paint ground
{cell: CENTRE, color: groundCol},
// Follow director up slopes
(friend_at(rot[5]) === DIRECTOR) && {cell: rot[2]},
(friend_at(rot[5]) === DIRECTOR) && {cell: rot[1]},
// Recognise likely erasure issues and correct
view[rot[2]].color === groundCol && GROUND_COLOURS.contains(view[rot[8]].color) &&
{cell: CENTRE, color: groundCol},
// Clear cells which could confuse workers
GROUND_COLOURS.contains(view[rot[2]].color) && {cell: rot[2], color: SAFE_COLOURS.next(WHITE)},
// Spawn new workers when ready (throttle probabilistically)
(workerSpawn && nextType < FORAGER0 + MAX_FORAGER_TYPES) && {cell: rot[1], type: nextType},
// Follow director along flat planes
(friend_at(rot[8]) === DIRECTOR) && {cell: rot[5]},
// Don't lose director
NOP
]);
}
return best_of([
// Begin wildfire
(me.food >= MIN_FOOD + MAX_FORAGER_TYPES + 1) && try_all_angles((rot) =>
(view[rot[5]].color !== groundCol && sanity_check({cell: rot[5]}) &&
{cell: rot[8], type: DIRECTOR})),
// Hungry or too crowded to begin; frantically find food
grab_nearby_food,
fast_diagonal.bind(null, SAFE_COLOURS, INITIAL_OBSTACLES),
go_anywhere,
{cell: 1, color: SAFE_COLOURS.next(WHITE)}
]);
}
return play_safe(move_agent([
DIRECTOR, move_director,
FORAGER0, move_forager,
FORAGER1, move_forager,
FORAGER2, move_forager,
QUEEN, move_queen,
]));
```
Wildfire ants sweep the board, devouring everything in their path. This was inspired by mixing the concepts of [Black Hole (by Draco18s)](https://codegolf.stackexchange.com/a/135157/8927) with [my Forensic Ants](https://codegolf.stackexchange.com/a/135108/8927).
The queen will start by quickly gathering a stash of food. Once she has enough, she'll start moving in a straight line and spawn some helpers. These helpers will follow behind her in an orderly line, running to catch up if they find food.
Mk.2 uses a specialist ant to help the queen maintain her direction, and this ant also lays down a trail of black to help lost workers find the correct side of the band. Combined with better worker navigation, it now performs much better when mixed with competing ants. It even (eventually) recovers after hitting nests of red dots.
Mk.2c uses probability to control the worker population and seems to manage it fairly well. The workers are still getting lost inside the fire more often than I'd like, but despite that it manages to take over impressive amounts of the board when on its own.
Mk.3 adds protection against diagonal red lines produced by the "single queen" entry, which also helps out in some similar situations. The workers are much less likely to get distracted by random detours now, and it seems to be performing better.
Here's the result of one of the prototypes:
[![FIRE](https://i.stack.imgur.com/kkQeC.png)](https://i.stack.imgur.com/kkQeC.png)
(yes, that's 865 worker ants… and er, 5 food)
---
Here's a screenshot with competition:
[![Cleansing fire](https://i.stack.imgur.com/Gx4cT.jpg)](https://i.stack.imgur.com/Gx4cT.jpg)
---
And here's how I imagine the ants in my mind (plus the corresponding music):
[![Paprika Parade](https://i.stack.imgur.com/PxSzB.gif)](https://i.stack.imgur.com/PxSzB.gif)
[Answer]
# Lightspeed
*All of my answers will contain similar low-level logic in the form of the Formic Functions Framework. "HIGH-LEVEL LOGIC STARTS HERE" marks the end of the Framework's code.*
```
// FORMIC FRAMEWORK //
// Version 6.1.10 //
const WHITE = 1;
const QUEEN = 5;
const CENTER = 4;
const HERE = view[CENTER];
const ME = HERE.ant;
const ORTHOGONALS = [1, 3, 5, 7];
const DIAGONALS = [0, 2, 6, 8];
const DIAGONALS_ORTHOGONALS = [0, 2, 6, 8, 1, 3, 5, 7];
const DIRECTIONS = [0, 1, 2, 3, 5, 6, 7, 8];
const CLOCKWISE_DIRECTIONS = [0, 1, 2, 5, 8, 7, 6, 3];
const CELLS = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const ROTATIONS = [
[0, 1, 2,
3, 4, 5,
6, 7, 8],
[6, 3, 0,
7, 4, 1,
8, 5, 2],
[8, 7, 6,
5, 4, 3,
2, 1, 0],
[2, 5, 8,
1, 4, 7,
0, 3, 6]
];
const NEIGHBORS = [
[1, 4, 3],
[2, 5, 4, 3, 0],
[5, 4, 1],
[0, 1, 4, 7, 6],
[0, 1, 2, 5, 8, 7, 6, 3],
[8, 7, 4, 1, 2],
[3, 4, 7],
[6, 3, 4, 5, 8],
[7, 4, 5]
];
const HORIZONTAL_FLIP = [2, 1, 0, 5, 4, 3, 8, 7, 6];
const VERTICAL_FLIP = [6, 7, 8, 3, 4, 5, 0, 1, 2];
const DEBUG_MODE = false;
function dump() {
if (DEBUG_MODE) {
throw "dump() not implemented";
}
}
function log(...args) {
if (DEBUG_MODE) {
console.log(...args);
}
}
function error(...args) {
log("Transformed view state:", view);
log(...args);
throw "A critical error has occurred!";
}
function createArray(func, length) {
const arr = [];
for (let i = 0; i < length; i++) {
arr.push(func(i, arr));
}
return arr;
}
class Test {
run(cell) {
error("No run method defined for this instance of Test:", this);
}
find(cells = CELLS) {
return cells.find((c) => this.run(c));
}
findIndex(cells = CELLS) {
return cells.findIndex((c) => this.run(c));
}
filter(cells = CELLS) {
return cells.filter((c) => this.run(c));
}
every(cells = CELLS) {
return cells.every((c) => this.run(c));
}
some(cells = CELLS) {
return cells.some((c) => this.run(c));
}
count(cells = CELLS) {
return this.filter(cells).length;
}
invert() {
return new InverseTest(this);
}
and(test) {
return new EveryTest(this, test);
}
or(test) {
return new SomeTest(this, test);
}
}
class InverseTest extends Test {
constructor(test) {
super();
this.test = test;
}
run(cell) {
return !this.test.run(cell);
}
invert() {
return this.test;
}
}
class CombinedTest extends Test {
constructor(...tests) {
super();
this.tests = tests;
}
append(test) {
this.tests.push(test);
return this;
}
}
class EveryTest extends CombinedTest {
run(cell) {
return this.tests.every((test) => test.run(cell));
}
and(test) {
return this.append(test);
}
}
class SomeTest extends CombinedTest {
run(cell) {
return this.tests.some((test) => test.run(cell));
}
or(test) {
return this.append(test);
}
}
class ColorTest extends Test {
constructor(color) {
super();
this.color = color;
}
run(cell) {
return view[cell].color === this.color;
}
}
class ColorBandTest extends SomeTest {
constructor(colorBand) {
super(...colorBand.map((color) => new ColorTest(color)));
}
}
class FoodTest extends Test {
constructor(hasFood = true) {
super();
this.food = hasFood ? 1 : 0;
}
run(cell) {
return view[cell].food === this.food;
}
}
class AntTest extends Test {
constructor(friend, type, food) {
super();
this.friend = friend;
this.type = type;
this.food = food;
}
run(cell) {
const ant = view[cell].ant;
return ant !== null && (this.type === undefined || ant.type === this.type) && (this.friend === undefined || ant.friend === this.friend) && (this.food === undefined || (this.food ? ant.food > 0 : ant.food === 0));
}
}
class NeighborTest extends Test {
constructor(test) {
super();
this.test = test;
}
run(cell) {
return this.test.some(NEIGHBORS[cell]);
}
}
class MatchTest extends Test {
constructor(matches) {
super();
this.matches = matches;
}
run(cell) {
return this.matches[cell];
}
}
class CustomTest extends Test {
constructor(func, ...args) {
super();
this.func = func;
this.args = args;
}
run(cell) {
return this.func(cell, ...this.args);
}
}
class Action {
constructor(cell, test) {
this.cell = cell;
this.test = test;
}
valid() {
return this.cell >= 0 && this.cell < 9 && (!this.test || this.test.run(this.cell));
}
attempt() {
return this.valid() ? this : null;
}
static tryAll(...actions) {
return actions.find((action) => action instanceof this && action.valid()) || null;
}
}
class Move extends Action {
constructor(cell, test) {
super(cell, test);
}
valid() {
return super.valid() && view[this.cell].ant === null && (view[this.cell].food === 0 || ME.food === 0 || ME.type === QUEEN);
}
static many(cells, test) {
return cells.map((cell) => new this(cell, test));
}
}
class Paint extends Action {
constructor(cell, color, test) {
super(cell, test);
this.color = color;
}
valid() {
return super.valid() && view[this.cell].color !== this.color && this.color >= 1 && this.color <= 8;
}
static many(cells, colors, test) {
return cells.map((cell, i) => new this(cell, colors[i % colors.length], test));
}
}
class Spawn extends Action {
constructor(cell, type, test) {
super(cell, test);
this.type = type;
}
valid() {
return super.valid() && view[this.cell].ant === null && view[this.cell].food === 0 && ME.food > 0 && ME.type === QUEEN && this.type >= 1 && this.type <= 4;
}
static many(cells, type, test) {
return cells.map((cell, i) => new this(cell, type, test));
}
}
class NOP extends Action {
constructor() {
super(CENTER);
}
valid() {
return true;
}
}
class Context {
apply(func, ...args) {
const hiddenView = view;
if (this.viewTranslator) {
view = this.viewTranslator(hiddenView);
}
let output = func(...args);
if (output instanceof Action && this.outputTranslator) {
this.outputTranslator(output);
}
view = hiddenView;
return output;
}
}
class TranslationContext extends Context {
constructor(translationArray) {
super();
this.translationArray = translationArray;
}
viewTranslator(oldView) {
const newView = [];
for (let i = 0; i < 9; i++) {
newView.push(oldView[this.translationArray[i]]);
}
return newView;
}
outputTranslator(out) {
out.cell = this.translationArray[out.cell];
}
}
class RotationContext extends TranslationContext {
constructor(orientation) {
super(ROTATIONS[orientation]);
this.orientation = orientation;
}
}
class OffsetContext extends TranslationContext {
constructor(centerCell) {
throw "OffsetContext not implemented";
}
}
class HorizontalReflectionContext extends TranslationContext {
constructor() {
super(HORIZONTAL_FLIP);
}
}
class VerticalReflectionContext extends TranslationContext {
constructor() {
super(VERTICAL_FLIP);
}
}
class ColorMapContext extends Context {
constructor(map, unmap) {
super();
this.map = map;
this.unmap = unmap;
}
viewTranslator(oldView) {
return oldView.map((cell) => ({color: this.map[cell.color - 1], food: cell.food, ant: cell.ant}));
}
outputTranslator(out) {
out.color = this.unmap[out.color - 1];
}
}
class XY {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
static fromTuples(...xyTuples) {
return xyTuples.map((xy) => new this(xy[0], xy[1]));
}
}
class WrapProperties {
constructor(horizontal, vertical, size, wrapOffsets) {
this.horizontal = !!horizontal;
this.vertical = !!vertical;
this.size = size;
this.wrapOffsets = wrapOffsets || {};
}
}
class ScoredTest {
constructor(test, score = 1) {
this.test = test;
this.score = score;
}
run(cell) {
return this.test.run(cell) ? this.score : 0;
}
}
class Environment {
constructor(tests, wrapping) {
this.tests = tests.map((test) => test instanceof Test ? new ScoredTest(test) : test);
this.wrapping = wrapping;
}
at(x, y) {
const w = this.wrapping;
while ((w.horizontal && (x < 0 || x >= w.size.x)) || (w.vertical && (y < 0 || y >= w.size.y))) {
if (w.horizontal) {
if (x < 0) {
x += w.size.x;
y += w.wrapOffsets.left || 0;
} else if (x >= w.size.x) {
x -= w.size.x;
y += w.wrapOffsets.right || 0;
}
}
if (w.vertical) {
if (y < 0) {
y += w.size.y;
x += w.wrapOffsets.up || 0;
} else if (y >= w.size.y) {
y -= w.size.y;
x += w.wrapOffsets.down || 0;
}
}
}
if ((!w.horizontal || (x >= 0 && x < w.size.x)) && (!w.vertical || (y >= 0 || y < w.size.y))) {
return this.tests[x + y * w.size.x];
} else {
return null;
}
}
around(x, y) {
const arr = [];
for (let oy = -1; oy <= 1; oy++) {
for (let ox = -1; ox <= 1; ox++) {
arr.push(this.at(x + ox, y + oy));
}
}
return arr;
}
detect(...positions) {
return createArray((i) => new RotationContext(i), 4).reduce((best, context) => {
const next = context.apply(() => {
return positions.reduce((best, pos, i) => {
let score = 0;
const matches = this.around(pos.x, pos.y).map((test, i) => {
if (test && (test.test instanceof Test)) {
const result = test.run(i);
if (result) {
score += result;
return true;
} else {
return false;
}
} else {
return null;
}
});
if (score > best.score) {
return {position: pos, positionIndex: i, orientation: context.orientation, environment: this, matches: matches, score: score, confidence: score - best.score};
} else {
best.confidence = Math.min(best.score - score, best.confidence);
return best;
}
}, {position: positions[0], positionIndex: 0, orientation: 0, environment: this, matches: [], score: 0, confidence: 0});
});
if (next.score > best.score) {
next.confidence = next.score - best.score;
return next;
} else {
best.confidence = Math.min(best.score - next.score, best.confidence);
return best;
}
}, {position: positions[0], positionIndex: 0, orientation: 0, environment: this, matches: [], score: 0, confidence: 0});
}
static chooseBest(...detectionResults) {
const r = detectionResults.reduce((best, result, i) => {
if (result.score > best.score) {
result.index = i;
result.confidence = result.score - best.score;
return result;
} else {
best.confidence = Math.min(best.score - result.score, best.confidence);
return best;
}
});
r.index = r.index || 0;
return r;
}
}
class ColoredEnvironment extends Environment {
constructor(colors, wrapping) {
super(colors.map((color) => new ColorTest(color)), wrapping);
}
getPainter(detectionResult) {
return new (class Painter {
constructor(loc) {
this.pos = loc.position;
this.matches = loc.matches;
this.colors = loc.environment.around(this.pos.x, this.pos.y).map((test) => test && test.test instanceof ColorTest ? test.test.color : null);
this.test = new MatchTest(loc.matches).invert();
this.orient = loc.orientation;
}
paint(...cells) {
return cells.map((cell) => new Paint(cell, this.colors[cell], this.test));
}
cleanup(eraseColor, eraseTargets, ...cells) {
const eraseQual = this.test.and(new ColorBandTest(eraseTargets));
return cells.map((cell) => new Paint(cell, eraseColor, eraseQual));
}
})(detectionResult);
}
}
// HIGH-LEVEL LOGIC STARTS HERE //
const PARTNER = 1;
// TODO: Do a 180 when 3 workers are in front of us
function logicOrthogonal(frontC, sideC, backC, backCells, moveCells) {
const a = [frontC, sideC, backC, backCells, moveCells];
const f = new FoodTest;
return Action.tryAll(
...Move.many([frontC, sideC], f),
f.some(backCells) ? new Move(backC) : null,
...Move.many(moveCells),
new NOP
);
}
function logicDiagonal(adjacentC) {
return Action.tryAll(...Move.many(adjacentC), new NOP);
}
function logic(partnerTest, partnerOrthC, partnerDiagC, frontC, sideC, backC, backCells, moveCells, adjacentC) {
function detectEnv(c) {
return new Environment(createArray((i) => i === c ? partnerTest : undefined, 9), new WrapProperties(false, false, new XY(3, 3), null)).detect(new XY(1, 1));
}
const orth = detectEnv(partnerOrthC);
const diag = detectEnv(partnerDiagC);
return orth.score === 1 ? new RotationContext(orth.orientation).apply(() => logicOrthogonal(frontC, sideC, backC, backCells, moveCells)) :
diag.score === 1 ? new RotationContext(diag.orientation).apply(() => logicDiagonal(adjacentC)) :
error("How did we get here?");
}
if (ME.type === QUEEN) {
const partner = new AntTest(true, PARTNER);
if (partner.some(DIRECTIONS)) {
return logic(partner, 5, 8, 2, 1, 7, [0, 3, 6, 7], [2, 7, 1, 8], [5, 7]);
} else {
const COLOR = 5;
const bgTest = new ColorTest(WHITE);
if (bgTest.run(CENTER)) {
return new Paint(CENTER, COLOR).attempt() || error("Something went terribly wrong while painting own cell");
}
const food = new FoodTest().find(DIRECTIONS);
if (food !== undefined) {
return new Move(food);
}
const det = new ColoredEnvironment([
WHITE, WHITE, WHITE,
WHITE, undefined, undefined,
WHITE, undefined, COLOR
], new WrapProperties(false, false, new XY(3, 3))).detect(new XY(1, 1));
return (ME.food > 0 ? Action.tryAll(...Spawn.many(ORTHOGONALS, PARTNER)) : null) ||
(det.score === 6 ? new RotationContext(det.orientation).apply(() => Action.tryAll(...Move.many([0, 2, 6, 1, 3, 5, 7, 8]))) : null) ||
Action.tryAll(...Move.many(DIAGONALS_ORTHOGONALS), new NOP);
}
} else {
return logic(new AntTest(true, QUEEN), 1, 0, 2, 5, 3, [8, 7, 6, 3], [2, 3, 5, 0], [1, 3]);
}
```
---
# Explanation
*This is such a simple ant that I'm stunned nobody has ever thought of it...*
This ant produces a Partner after gathering 1 food with the classic approach. After this, the Queen and the Partner travel in a **straight, diagonal line at the highest speed possible** (one cell per turn) using each other's position. They don't paint any cells. They survey an average of **6 cells per turn**, netting them a theoretical total of ***180* food per game** on an empty map, which they consistently achieve.
**Version 2.0+ is out! Features comments in code that explain the specifics of this entry.**
---
# Changelog
### Version 1.0
* initial release
### Version 2.0
* completely revamped maneuvers
+ now utilizes diagonal adjacency for more movement options
+ changed behavior for grabbing food
- average collection rate remains unchanged, but the system is more robust
- prevents deadlock when more than one piece of food present, significantly increasing consistency
- reduced the rate of changing direction
- can grab food behind itself
+ changed behavior for avoiding obstacles
- reduced the chance of deadlock, further increasing consistency
- doesn't U-turn unless absolutely necessary, increasing average total area covered
* cleaned up code
* added comments
### Version 2.1
* resolved an exotic deadlock
### Version 2.2
* resolved another exotic deadlock
### Version 2.3
* avoiding enemies is now significantly more effective
### Version 2.3.1
* avoiding enemies is slightly more effective still
### Version 2.4
* Formic Framework updated to version 5.0.4 (from 1.0)
* refactored code (behavior nearly identical to version 2.3.1)
### Version 2.5
* Formic Framework updated to version 6.1.10 (from 5.0.4)
* refactored code to match new coding standard (behavior nearly identical to version 2.4)
* removed code comments :(
### Version 2.5.0.1
* minor fixes
### Version 2.5.0.2
* fixed disqualification bug with the help of [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima) in [chat](https://chat.stackexchange.com/transcript/message/44153850#44153850)
### Version 2.5.0.3
* disabled debugging
[Answer]
# Trail-eraser
```
var i, j
var orthogonals = [1, 3, 7, 5] // These are the non-diagonal cells
if(view[4].ant.type == 5) {
//Queen moves straight to get food
// Color own cell if white
if (view[4].color != 6) {
return {cell:4, color:6}
}
var specified = null;
// Otherwise move to a white cell opposite a colored cell
for (i=0; i<4; i++) {
j = (i+2) % 4
if (view[orthogonals[i]].color !== 6 &&
view[orthogonals[j]].color == 6 && !view[orthogonals[i]].ant) {
specified = {cell:orthogonals[i]}
} else if (view[4].ant.food < 8 && view[4].ant.food && view[orthogonals[i]].color !== 6 && !view[orthogonals[i]].ant && !view[orthogonals[i]].food && view[orthogonals[i]].color !== 1) {
//create workers once I encounter a trail
return {cell:orthogonals[i], type:(view[orthogonals[i]].color%4)+1};
} else if (view[orthogonals[i]].food) {
return {cell:orthogonals[i]}
}
}
if(specified) { return specified; }
// Otherwise move to one of the vertical or horizontal cells if not occupied
for (i=1; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i}
}
}
// Otherwise move to one of the diagonal cells if not occupied
for (i=0; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i};
}
}
// Otherwise don't move at all
return {cell:4};
}
//workers erase their trails
//Follow the trail to erase
var move, color, enemyAnt = false;
var nearbyColoredCells = 0;
if(view[4].color != 1){
color = {cell:4, color:1}
}
for(i=0;i<9;i++) {
if(i != 4 && view[i].color != 1 && !view[i].ant && (!view[4].ant.food || !view[i].food) && (!move || (view[i].color % 4 + 1) == view[4].type || (view[move.cell].color == 6 && view[i].color != 6))) {
move = {cell:i}
}
if(view[i].ant && view[i].ant.friend && view[i].ant.type == 5){
return {cell:4}
}
if(i != 4 && view[i].color != 1 && view[i].color != 6){
nearbyColoredCells += 1;
}
if(view[i].ant && !view[i].ant.friend) {
enemyAnt = i;
}
}
if(nearbyColoredCells <= 1 || enemyAnt > 1) {
// Either I'm following a standard trail or there are enemy workers; possibly decolor own cell and move
if(color && (!move || !enemyAnt)) { return color; }
if(move) { return move; }
} else if (nearbyColoredCells > 1){
for (i = 0; i < 9; i++){
if(view[i].color != 1){ return {cell:i, color:1} }
}
}
// uh-oh, our trail ended or we got lost -- random walk
// find a safe place to move
for (i=0;i<9;i+=1) {
if (!view[i].ant && (!view[4].ant.food || !view[i].food)) {
return {cell:i}
}
}
return {cell:4}
```
This ant, while moderately good at finding food (but not as good as Roman Ants or Forensic ants) attempts to confuse other ants. It does so by creating a worker whose sole purpose is to erase trails whenever it encounters a crossing path of color. Workers who hit the end of their trail uselessly random walk until they find another trail. In order to preserve food and possibly do better, this ant will switch strategies to one of not producing more workers once it hits eight food, which should be in the late game just because it tends to require a specific combo to preserve food and not just use it all.
[Answer]
# Hyperwave
*All of my answers will contain similar low-level logic in the form of the Formic Functions Framework. "HIGH-LEVEL LOGIC STARTS HERE" marks the end of the Framework's code.*
```
// FORMIC FRAMEWORK //
// Version 6.1.10 //
const WHITE = 1;
const QUEEN = 5;
const CENTER = 4;
const HERE = view[CENTER];
const ME = HERE.ant;
const ORTHOGONALS = [1, 3, 5, 7];
const DIAGONALS = [0, 2, 6, 8];
const DIAGONALS_ORTHOGONALS = [0, 2, 6, 8, 1, 3, 5, 7];
const DIRECTIONS = [0, 1, 2, 3, 5, 6, 7, 8];
const CLOCKWISE_DIRECTIONS = [0, 1, 2, 5, 8, 7, 6, 3];
const CELLS = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const ROTATIONS = [
[0, 1, 2,
3, 4, 5,
6, 7, 8],
[6, 3, 0,
7, 4, 1,
8, 5, 2],
[8, 7, 6,
5, 4, 3,
2, 1, 0],
[2, 5, 8,
1, 4, 7,
0, 3, 6]
];
const NEIGHBORS = [
[1, 4, 3],
[2, 5, 4, 3, 0],
[5, 4, 1],
[0, 1, 4, 7, 6],
[0, 1, 2, 5, 8, 7, 6, 3],
[8, 7, 4, 1, 2],
[3, 4, 7],
[6, 3, 4, 5, 8],
[7, 4, 5]
];
const HORIZONTAL_FLIP = [2, 1, 0, 5, 4, 3, 8, 7, 6];
const VERTICAL_FLIP = [6, 7, 8, 3, 4, 5, 0, 1, 2];
const DEBUG_MODE = true;
function dump() {
if (DEBUG_MODE) {
throw "dump() not implemented";
}
}
function log(...args) {
if (DEBUG_MODE) {
console.log(...args);
}
}
function error(...args) {
log("Transformed view state:", view);
log(...args);
throw "A critical error has occurred!";
}
function createArray(func, length) {
const arr = [];
for (let i = 0; i < length; i++) {
arr.push(func(i, arr));
}
return arr;
}
class Test {
run(cell) {
error("No run method defined for this instance of Test:", this);
}
find(cells = CELLS) {
return cells.find((c) => this.run(c));
}
findIndex(cells = CELLS) {
return cells.findIndex((c) => this.run(c));
}
filter(cells = CELLS) {
return cells.filter((c) => this.run(c));
}
every(cells = CELLS) {
return cells.every((c) => this.run(c));
}
some(cells = CELLS) {
return cells.some((c) => this.run(c));
}
count(cells = CELLS) {
return this.filter(cells).length;
}
invert() {
return new InverseTest(this);
}
and(test) {
return new EveryTest(this, test);
}
or(test) {
return new SomeTest(this, test);
}
}
class InverseTest extends Test {
constructor(test) {
super();
this.test = test;
}
run(cell) {
return !this.test.run(cell);
}
invert() {
return this.test;
}
}
class CombinedTest extends Test {
constructor(...tests) {
super();
this.tests = tests;
}
append(test) {
this.tests.push(test);
return this;
}
}
class EveryTest extends CombinedTest {
run(cell) {
return this.tests.every((test) => test.run(cell));
}
and(test) {
return this.append(test);
}
}
class SomeTest extends CombinedTest {
run(cell) {
return this.tests.some((test) => test.run(cell));
}
or(test) {
return this.append(test);
}
}
class ColorTest extends Test {
constructor(color) {
super();
this.color = color;
}
run(cell) {
return view[cell].color === this.color;
}
}
class ColorBandTest extends SomeTest {
constructor(colorBand) {
super(...colorBand.map((color) => new ColorTest(color)));
}
}
class FoodTest extends Test {
constructor(hasFood = true) {
super();
this.food = hasFood ? 1 : 0;
}
run(cell) {
return view[cell].food === this.food;
}
}
class AntTest extends Test {
constructor(friend, type, food) {
super();
this.friend = friend;
this.type = type;
this.food = food;
}
run(cell) {
const ant = view[cell].ant;
return ant !== null && (this.type === undefined || ant.type === this.type) && (this.friend === undefined || ant.friend === this.friend) && (this.food === undefined || (this.food ? ant.food > 0 : ant.food === 0));
}
}
class NeighborTest extends Test {
constructor(test) {
super();
this.test = test;
}
run(cell) {
return this.test.some(NEIGHBORS[cell]);
}
}
class MatchTest extends Test {
constructor(matches) {
super();
this.matches = matches;
}
run(cell) {
return this.matches[cell];
}
}
class CustomTest extends Test {
constructor(func, ...args) {
super();
this.func = func;
this.args = args;
}
run(cell) {
return this.func(cell, ...this.args);
}
}
class Action {
constructor(cell, test) {
this.cell = cell;
this.test = test;
}
valid() {
return this.cell >= 0 && this.cell < 9 && (!this.test || this.test.run(this.cell));
}
attempt() {
return this.valid() ? this : null;
}
static tryAll(...actions) {
return actions.find((action) => action instanceof this && action.valid()) || null;
}
}
class Move extends Action {
constructor(cell, test) {
super(cell, test);
}
valid() {
return super.valid() && view[this.cell].ant === null && (view[this.cell].food === 0 || ME.food === 0 || ME.type === QUEEN);
}
static many(cells, test) {
return cells.map((cell) => new this(cell, test));
}
}
class Paint extends Action {
constructor(cell, color, test) {
super(cell, test);
this.color = color;
}
valid() {
return super.valid() && view[this.cell].color !== this.color && this.color >= 1 && this.color <= 8;
}
static many(cells, colors, test) {
return cells.map((cell, i) => new this(cell, colors[i % colors.length], test));
}
}
class Spawn extends Action {
constructor(cell, type, test) {
super(cell, test);
this.type = type;
}
valid() {
return super.valid() && view[this.cell].ant === null && view[this.cell].food === 0 && ME.food > 0 && ME.type === QUEEN && this.type >= 1 && this.type <= 4;
}
static many(cells, type, test) {
return cells.map((cell, i) => new this(cell, type, test));
}
}
class NOP extends Action {
constructor() {
super(CENTER);
}
valid() {
return true;
}
}
class Context {
apply(func, ...args) {
const hiddenView = view;
if (this.viewTranslator) {
view = this.viewTranslator(hiddenView);
}
let output = func(...args);
if (output instanceof Action && this.outputTranslator) {
this.outputTranslator(output);
}
view = hiddenView;
return output;
}
}
class TranslationContext extends Context {
constructor(translationArray) {
super();
this.translationArray = translationArray;
}
viewTranslator(oldView) {
const newView = [];
for (let i = 0; i < 9; i++) {
newView.push(oldView[this.translationArray[i]]);
}
return newView;
}
outputTranslator(out) {
out.cell = this.translationArray[out.cell];
}
}
class RotationContext extends TranslationContext {
constructor(orientation) {
super(ROTATIONS[orientation]);
this.orientation = orientation;
}
}
class OffsetContext extends TranslationContext {
constructor(centerCell) {
throw "OffsetContext not implemented";
}
}
class HorizontalReflectionContext extends TranslationContext {
constructor() {
super(HORIZONTAL_FLIP);
}
}
class VerticalReflectionContext extends TranslationContext {
constructor() {
super(VERTICAL_FLIP);
}
}
class ColorMapContext extends Context {
constructor(map, unmap) {
super();
this.map = map;
this.unmap = unmap;
}
viewTranslator(oldView) {
return oldView.map((cell) => ({color: this.map[cell.color - 1], food: cell.food, ant: cell.ant}));
}
outputTranslator(out) {
out.color = this.unmap[out.color - 1];
}
}
class XY {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
static fromTuples(...xyTuples) {
return xyTuples.map((xy) => new this(xy[0], xy[1]));
}
}
class WrapProperties {
constructor(horizontal, vertical, size, wrapOffsets) {
this.horizontal = !!horizontal;
this.vertical = !!vertical;
this.size = size;
this.wrapOffsets = wrapOffsets || {};
}
}
class ScoredTest {
constructor(test, score = 1) {
this.test = test;
this.score = score;
}
run(cell) {
return this.test.run(cell) ? this.score : 0;
}
}
class Environment {
constructor(tests, wrapping) {
this.tests = tests.map((test) => test instanceof Test ? new ScoredTest(test) : test);
this.wrapping = wrapping;
}
at(x, y) {
const w = this.wrapping;
while ((w.horizontal && (x < 0 || x >= w.size.x)) || (w.vertical && (y < 0 || y >= w.size.y))) {
if (w.horizontal) {
if (x < 0) {
x += w.size.x;
y += w.wrapOffsets.left || 0;
} else if (x >= w.size.x) {
x -= w.size.x;
y += w.wrapOffsets.right || 0;
}
}
if (w.vertical) {
if (y < 0) {
y += w.size.y;
x += w.wrapOffsets.up || 0;
} else if (y >= w.size.y) {
y -= w.size.y;
x += w.wrapOffsets.down || 0;
}
}
}
if ((!w.horizontal || (x >= 0 && x < w.size.x)) && (!w.vertical || (y >= 0 || y < w.size.y))) {
return this.tests[x + y * w.size.x];
} else {
return null;
}
}
around(x, y) {
const arr = [];
for (let oy = -1; oy <= 1; oy++) {
for (let ox = -1; ox <= 1; ox++) {
arr.push(this.at(x + ox, y + oy));
}
}
return arr;
}
detect(...positions) {
return createArray((i) => new RotationContext(i), 4).reduce((best, context) => {
const next = context.apply(() => {
return positions.reduce((best, pos, i) => {
let score = 0;
const matches = this.around(pos.x, pos.y).map((test, i) => {
if (test && (test.test instanceof Test)) {
const result = test.run(i);
if (result) {
score += result;
return true;
} else {
return false;
}
} else {
return null;
}
});
if (score > best.score) {
return {position: pos, positionIndex: i, orientation: context.orientation, environment: this, matches: matches, score: score, confidence: score - best.score};
} else {
best.confidence = Math.min(best.score - score, best.confidence);
return best;
}
}, {position: positions[0], positionIndex: 0, orientation: 0, environment: this, matches: [], score: 0, confidence: 0});
});
if (next.score > best.score) {
next.confidence = next.score - best.score;
return next;
} else {
best.confidence = Math.min(best.score - next.score, best.confidence);
return best;
}
}, {position: positions[0], positionIndex: 0, orientation: 0, environment: this, matches: [], score: 0, confidence: 0});
}
static chooseBest(...detectionResults) {
const r = detectionResults.reduce((best, result, i) => {
if (result.score > best.score) {
result.index = i;
result.confidence = result.score - best.score;
return result;
} else {
best.confidence = Math.min(best.score - result.score, best.confidence);
return best;
}
});
r.index = r.index || 0;
return r;
}
}
class ColoredEnvironment extends Environment {
constructor(colors, wrapping) {
super(colors.map((color) => new ColorTest(color)), wrapping);
}
getPainter(detectionResult) {
return new (class Painter {
constructor(loc) {
this.pos = loc.position;
this.matches = loc.matches;
this.colors = loc.environment.around(this.pos.x, this.pos.y).map((test) => test && test.test instanceof ColorTest ? test.test.color : null);
this.test = new MatchTest(loc.matches).invert();
this.orient = loc.orientation;
}
paint(...cells) {
return cells.map((cell) => new Paint(cell, this.colors[cell], this.test));
}
cleanup(eraseColor, eraseTargets, ...cells) {
const eraseQual = this.test.and(new ColorBandTest(eraseTargets));
return cells.map((cell) => new Paint(cell, eraseColor, eraseQual));
}
})(detectionResult);
}
}
// HIGH-LEVEL LOGIC STARTS HERE //
// TODO:
// - more food checkpoints (no disadvantages because it's illogical for WFW to "premanently lose" workers)
// - randomly shifting 1 up (5% chance? watch out for hoarding stealing your randomness!)
// - randomly skip painting a tiny bit of local cells (prevent deadlock against ants outside of view)
// - escape routine when situation is dire (many workers near the queen/partner)
const COLOR_BAND = [4, 7, 3, 2, 8];
const PARTNER = 2;
const WORKER = 1;
const START_FOOD = 6;
const MIN_CONFIDENCE = 2;
const PATTERN = new ColoredEnvironment(COLOR_BAND, new WrapProperties(true, true, new XY(COLOR_BAND.length, 1), {up: 2, down: -2})).detect(...createArray((i) => new XY(i, 0), COLOR_BAND.length));
function checkpoint(val, tolerance) {
return ME.food >= val - tolerance && ME.food <= val;
}
function shouldSpawn() {
return PATTERN.orientation === 0 && PATTERN.positionIndex % 3 === 0 &&
ME.food < 400 &&
(ME.food < 75 || PATTERN.positionIndex === 0) &&
!checkpoint(300, 4) &&
!checkpoint(200, 5) &&
!checkpoint(160, 3) &&
!checkpoint(130, 2) &&
!checkpoint(100, 2) &&
!checkpoint(75, 2) &&
!checkpoint(50, 2) &&
!checkpoint(35, 1) &&
!checkpoint(20, 1) &&
!checkpoint(10, 0);
}
function lightspeed() {
// TODO: Do a 180 when 3 workers are in front of us
function logicOrthogonal(frontC, sideC, backC, backCells, moveCells) {
const a = [frontC, sideC, backC, backCells, moveCells];
const f = new FoodTest;
return Action.tryAll(
...Move.many([frontC, sideC], f),
f.some(backCells) ? new Move(backC) : null,
...Move.many(moveCells),
new NOP
);
}
function logicDiagonal(adjacentC) {
return Action.tryAll(...Move.many(adjacentC), new NOP);
}
function logic(partnerTest, partnerOrthC, partnerDiagC, frontC, sideC, backC, backCells, moveCells, adjacentC) {
function detectEnv(c) {
return new Environment(createArray((i) => i === c ? partnerTest : undefined, 9), new WrapProperties(false, false, new XY(3, 3), null)).detect(new XY(1, 1));
}
const orth = detectEnv(partnerOrthC);
const diag = detectEnv(partnerDiagC);
return orth.score === 1 ? new RotationContext(orth.orientation).apply(() => logicOrthogonal(frontC, sideC, backC, backCells, moveCells)) :
diag.score === 1 ? new RotationContext(diag.orientation).apply(() => logicDiagonal(adjacentC)) :
error("How did we get here?");
}
if (ME.type === QUEEN) {
const partner = new AntTest(true, PARTNER);
if (partner.some(DIRECTIONS)) {
return logic(partner, 5, 8, 2, 1, 7, [0, 3, 6, 7], [2, 7, 1, 8], [5, 7]);
} else {
const COLOR = 5;
const bgTest = new ColorTest(WHITE);
if (bgTest.run(CENTER)) {
return new Paint(CENTER, COLOR).attempt() || error("Something went terribly wrong while painting own cell");
}
const food = new FoodTest().find(DIRECTIONS);
if (food !== undefined) {
return new Move(food);
}
const det = new ColoredEnvironment([
WHITE, WHITE, WHITE,
WHITE, undefined, undefined,
WHITE, undefined, COLOR
], new WrapProperties(false, false, new XY(3, 3))).detect(new XY(1, 1));
return (ME.food > 0 ? Action.tryAll(...Spawn.many(ORTHOGONALS, PARTNER)) : null) ||
(det.score === 6 ? new RotationContext(det.orientation).apply(() => Action.tryAll(...Move.many([0, 2, 6, 1, 3, 5, 7, 8]))) : null) ||
Action.tryAll(...Move.many(DIAGONALS_ORTHOGONALS), new NOP);
}
} else {
return logic(new AntTest(true, QUEEN), 1, 0, 2, 5, 3, [8, 7, 6, 3], [2, 3, 5, 0], [1, 3]);
}
}
function queen() {
const partnerTest = new AntTest(true, PARTNER);
if (PATTERN.confidence < MIN_CONFIDENCE && (ME.food < START_FOOD || partnerTest.some(DIAGONALS))) return lightspeed();
return new RotationContext(PATTERN.orientation).apply(() => {
const partnerCell = new AntTest(true, PARTNER).find(DIRECTIONS);
const p = PATTERN.environment.getPainter(PATTERN);
const e = new AntTest(false);
const enemy = e.some(DIRECTIONS);
return Action.tryAll(
...!PATTERN.matches[8] ? [
...!enemy ? [...p.paint(7, 4, 5, 1, 2), ...shouldSpawn() && PATTERN.score === 8 ? Spawn.many([0, 2], WORKER) : []] : [],
...partnerCell === 1 ? Move.many(e.run(5) ? [0, 2] : PATTERN.orientation === 1 && PATTERN.positionIndex % 3 === 1 ? [2, 0, 5] : [5, 2, 0]) :
partnerCell === 0 ? Move.many(e.run(1) ? [3] : enemy ? [1, 3] : []) :
partnerCell === 2 ? Move.many(e.run(1) ? [5] : []) :
[]
] : [
...!enemy ? p.paint(8, 7, 6, 5, 4, 3, 2, 1, 0) : [],
...Move.many(partnerCell === 1 ? [2, 0] : partnerCell === 0 ? [1, 3] : partnerCell === 2 && e.run(1) ? [5] : [])
],
new NOP
)
});
}
function partner() {
const queenTest = new AntTest(true, QUEEN)
const queenCell = queenTest.find(DIRECTIONS);
if (queenCell === undefined) {
return new NOP; // TODO: What do we do if we've lost our queen?
}
if (PATTERN.confidence < MIN_CONFIDENCE && (view[queenCell].ant.food < START_FOOD || DIAGONALS.includes(queenCell))) return lightspeed();
return PATTERN.confidence >= MIN_CONFIDENCE ? new RotationContext(PATTERN.orientation).apply(() => {
const queenCell = queenTest.find(DIRECTIONS);
const e = new AntTest(false);
const enemy = e.some(DIRECTIONS);
return Action.tryAll(
...!enemy ? PATTERN.environment.getPainter(PATTERN).paint(...CELLS) : [],
...Move.many([
[1],
[0, 2],
[1],
[0, 1],
[], // Queen can't be on cell 4 - I'm here, after all!
[2, 1],
[3],
[],
[5]
][queenCell]),
new NOP
)
}) : new NOP;
}
function worker() {
const m = new MatchTest(PATTERN.matches);
const n = m.invert();
const u = new AntTest(true, WORKER, false);
const l = new AntTest(true, WORKER, true);
const q = new AntTest(true, QUEEN);
const pt = new AntTest(true, PARTNER);
const p = PATTERN.environment.getPainter(PATTERN);
return new RotationContext(PATTERN.orientation).apply(() => { // TODO: Unique (random?) behavior when confidence low
if (ME.food === 0) {
const f = new FoodTest();
const count = n.count([6, 7, 8]);
return Action.tryAll(
...PATTERN.confidence >= 2 ? p.paint(4, 0, 1, 2) : [],
//...p.cleanup(WHITE, COLOR_BAND, ...CELLS),
...((food) => food !== undefined ? [...p.paint(...NEIGHBORS[food], food), new Move(food)] : [])(f.find(DIRECTIONS)),
...q.or(pt).some(DIRECTIONS) || u.some([6, 7, 8, 5, 2]) ? Move.many([0, 1, 3], m) : [],
...count > 1 ? p.paint(...[6, 7, 8]) : [],
...count === 1 ? [...p.paint(...[3, 5]), ...Move.many([7, 8, 6, 3], m)] : [],
/*n.run(6) ? new Move(3, m) : null,
...n.run(7) ? Move.many([6, 3], m) : [],
n.run(8) ? new Move(7, m) : null,*/
n.run(5) ? new Move(5) : null,
...Move.many([2, 1, 0, 3], m),
new NOP
/*
...(PATTERN.confidence >= 2 ? [...(PATTERN.score < 8 || new AntTest(false).some(DIRECTIONS) ? p.paint(4, 3, 0, 1, 2, 5) : []), ...p.cleanup(WHITE, COLOR_BAND, ...CELLS)] : []),
...((food) => food !== undefined ? [...p.paint(...NEIGHBORS[food]), new Move(food)] : [])(f.find(DIRECTIONS)), ...(
w ? Move.many([1, 0, 2]) :
m.some([4, 3]) ? p.paint(4, 3) :
m.some([0, 1, 2]) ? Move.many([1, 5]) :
m.run(6) ? [new Move(3)] :
m.run(7) ? Move.many([6, 3]) :
m.run(8) ? [new Move(7)] :
m.run(5) ? Move.many([5, 7]) :
Move.many([2, 1, 5])
)
new NOP*/
);
} else {
return Action.tryAll(
//...Move.many(new AntTest(true, WORKER).some([2, 5, 8, 7]) || PATTERN.score < 9 ? [8, 7, 6, 3] : [5, 8, 2], m.invert()),
...((test) => createArray((i) => new Move(CLOCKWISE_DIRECTIONS[(6 - i) % 8], test), 5))(new CustomTest((cell, moveTest, blockTest) => {
const i = CLOCKWISE_DIRECTIONS.findIndex((c) => c === cell);
return moveTest.run(CLOCKWISE_DIRECTIONS[i]) && blockTest.run(CLOCKWISE_DIRECTIONS[((i - 1) + 8) % 8]);
}, m, n.or(new AntTest().and(l.invert())))),
...Move.many([2, 5, 1, 8], m),
//...Move.many([...(PATTERN.score === 9 && !new AntTest(true, WORKER).some(DIRECTIONS) ? [2] : []), 5, 8, 7, 6, 3], m),
new NOP
);
}
});
}
switch (ME.type) {
case QUEEN: {
return queen();
}
case PARTNER: {
return partner();
}
case WORKER: {
return worker();
}
}
```
---
### I have temporarily removed all description of this entry because of time pressure. I will add a thorough description of this major update at a later date.
---
# Changelog
### Version 1.0
* initial release
### Version 2.0
* replaced Highway with Hyperwave
### Version 2.0.1
* hotfixed hoarding mechanism
[Answer]
# Roman Ants Mk.2
*All my answers are sharing the same set of low-level helper functions.
Search for "High-level logic begins here" to see the code specific to this answer.*
```
// == Shared low-level helpers for all solutions ==
var QUEEN = 5;
var WHITE = 1;
var COL_MIN = WHITE;
var COL_LIM = 9;
var CENTRE = 4;
var NOP = {cell: CENTRE};
var DIR_FORWARDS = false;
var DIR_REVERSE = true;
var SIDE_RIGHT = true;
var SIDE_LEFT = false;
function sanity_check(movement) {
var me = view[CENTRE].ant;
if(!movement || movement.cell < 0 || movement.cell > 8) {
return false;
}
if(movement.type) {
if(movement.color) {
return false;
}
if(movement.type < 1 || movement.type > 4) {
return false;
}
if(view[movement.cell].ant || view[movement.cell].food) {
return false;
}
if(me.type !== QUEEN || me.food < 1) {
return false;
}
return true;
}
if(movement.color) {
if(movement.color < COL_MIN || movement.color >= COL_LIM) {
return false;
}
if(view[movement.cell].color === movement.color) {
return false;
}
return true;
}
if(view[movement.cell].ant) {
return false;
}
if(view[movement.cell].food + me.food > 1 && me.type !== QUEEN) {
return false;
}
return true;
}
function as_array(o) {
if(Array.isArray(o)) {
return o;
}
return [o];
}
function best_of(movements) {
var m;
for(var i = 0; i < movements.length; ++ i) {
if(typeof(movements[i]) === 'function') {
m = movements[i]();
} else {
m = movements[i];
}
if(sanity_check(m)) {
return m;
}
}
return null;
}
function play_safe(movement) {
// Avoid disqualification: no-op if moves are invalid
return best_of(as_array(movement)) || NOP;
}
var RAND_SEED = (() => {
var s = 0;
for(var i = 0; i < 9; ++ i) {
s += view[i].color * (i + 1);
s += view[i].ant ? i * i : 0;
s += view[i].food ? i * i * i : 0;
}
return s % 29;
})();
var ROTATIONS = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[2, 5, 8, 1, 4, 7, 0, 3, 6],
];
function try_all(fns, limit, wrapperFn, checkFn) {
var m;
fns = as_array(fns);
for(var i = 0; i < fns.length; ++ i) {
if(typeof(fns[i]) !== 'function') {
if(checkFn(m = fns[i])) {
return m;
}
continue;
}
for(var j = 0; j < limit; ++ j) {
if(checkFn(m = wrapperFn(fns[i], j))) {
return m;
}
}
}
return null;
}
function identify_rotation(testFns) {
// testFns MUST be functions, not constants
return try_all(
testFns,
4,
(fn, r) => fn(ROTATIONS[r]) ? ROTATIONS[r] : null,
(r) => r
);
}
function near(a, b) {
return (
Math.abs(a % 3 - b % 3) < 2 &&
Math.abs(Math.floor(a / 3) - Math.floor(b / 3)) < 2
);
}
function try_all_angles(solverFns) {
return try_all(
solverFns,
4,
(fn, r) => fn(ROTATIONS[r]),
sanity_check
);
}
function try_all_cells(solverFns, skipCentre) {
return try_all(
solverFns,
9,
(fn, i) => ((i === CENTRE && skipCentre) ? null : fn(i)),
sanity_check
);
}
function try_all_cells_near(p, solverFns) {
return try_all(
solverFns,
9,
(fn, i) => ((i !== p && near(p, i)) ? fn(i) : null),
sanity_check
);
}
function ant_type_at(i, friend) {
return (view[i].ant && view[i].ant.friend === friend) ? view[i].ant.type : 0;
}
function friend_at(i) {
return ant_type_at(i, true);
}
function foe_at(i) {
return ant_type_at(i, false);
}
function foe_near(p) {
for(var i = 0; i < 9; ++ i) {
if(foe_at(i) && near(i, p)) {
return true;
}
}
return false;
}
function move_agent(agents) {
var me = view[CENTRE].ant;
var buddies = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)];
}
for(var i = 0; i < agents.length; i += 2) {
if(agents[i] === me.type) {
return agents[i+1](me, buddies);
}
}
return null;
}
function grab_nearby_food() {
return try_all_cells((i) => (view[i].food ? {cell: i} : null), true);
}
function go_anywhere() {
return try_all_cells((i) => ({cell: i}), true);
}
function colours_excluding(cols) {
var r = [];
for(var i = COL_MIN; i < COL_LIM; ++ i) {
if(cols.indexOf(i) === -1) {
r.push(i);
}
}
return r;
}
function generate_band(start, width) {
var r = [];
for(var i = 0; i < width; ++ i) {
r.push(start + i);
}
return r;
}
function colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function(c) {
return colours[(colours.indexOf(c) + 1) % colours.length];
}
};
}
function random_colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function() {
return colours[RAND_SEED % colours.length];
}
};
}
function fast_diagonal(colourBand) {
var m = try_all_angles([
// Avoid nearby checked areas
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[5]].color) &&
colourBand.contains(view[rot[7]].color)
) {
return {cell: rot[0]};
}
},
// Go in a straight diagonal line if possible
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[8]].color)
) {
return {cell: rot[0]};
}
},
// When in doubt, pick randomly but avoid doubling-back
(rot) => (colourBand.contains(view[rot[0]].color) ? null : {cell: rot[0]}),
// Double-back when absolutely necessary
(rot) => ({cell: rot[0]})
]);
// Lay a colour track so that we can avoid doubling-back
// (and mess up our foes as much as possible)
if(!colourBand.contains(view[CENTRE].color)) {
var prevCol = m ? view[8-m.cell].color : WHITE;
return {cell: CENTRE, color: colourBand.next(prevCol)};
}
return m;
}
function follow_edge(obstacleFn, side) {
// Since we don't know which direction we came from, this can cause us to get
// stuck on islands, but the random orientation helps to ensure we don't get
// stuck forever.
var order = ((side === SIDE_LEFT)
? [0, 3, 6, 7, 8, 5, 2, 1, 0]
: [0, 1, 2, 5, 8, 7, 6, 3, 0]
);
return try_all(
[obstacleFn],
order.length - 1,
(fn, i) => (fn(order[i+1]) && !fn(order[i])) ? {cell: order[i]} : null,
sanity_check
);
}
function start_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => ((
!protectedCols.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 2 : 0]].color) &&
!colourBand.contains(view[rot[1]].color)
)
? {cell: rot[right ? 5 : 3], color: colourBand.next(WHITE)}
: null)
]);
}
function lay_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var ahead = rot[right ? 2 : 0];
var behind = rot[right ? 8 : 6];
if(
colourBand.contains(view[behind].color) &&
!protectedCols.contains(view[ahead].color) &&
!colourBand.contains(view[ahead].color) &&
!colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
return {cell: ahead, color: colourBand.next(view[behind].color)};
}
}
]);
}
function follow_dotted_path(colourBand, side, direction) {
var forwards = (direction === DIR_REVERSE) ? 7 : 1;
var right = (side === SIDE_RIGHT);
return try_all_angles([
// Cell on our side? advance
(rot) => {
if(
colourBand.contains(view[rot[right ? 5 : 3]].color) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[0]].color) &&
!colourBand.contains(view[rot[2]].color)
) {
return {cell: rot[forwards]};
}
},
// Cell ahead and behind? advance
(rot) => {
var passedCol = view[rot[right ? 8 : 6]].color;
var nextCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(passedCol) &&
nextCol === colourBand.next(passedCol) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[right ? 0 : 2]].color)
) {
return {cell: rot[forwards]};
}
}
]);
}
function escape_dotted_path(colourBand, side, newColourBand) {
var right = (side === SIDE_RIGHT);
if(!newColourBand) {
newColourBand = colourBand;
}
return try_all_angles([
// Escape from beside the line
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
!colourBand.contains(view[rot[right ? 8 : 6]].color) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[rot[7]].color) ||
colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
// not oriented, or in a corner
return null;
}
return best_of([
{cell: rot[right ? 0 : 2], color: newColourBand.next(approachingCol)},
{cell: rot[right ? 3 : 5]},
{cell: rot[right ? 0 : 2]},
{cell: rot[right ? 6 : 8]},
{cell: rot[right ? 2 : 0]},
{cell: rot[right ? 8 : 6]},
{cell: rot[right ? 5 : 3]}
]);
},
// Escape from inside the line
(rot) => {
if(
!colourBand.contains(view[rot[7]].color) ||
!colourBand.contains(view[rot[1]].color) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
return best_of([
{cell: rot[3]},
{cell: rot[5]},
{cell: rot[0]},
{cell: rot[2]},
{cell: rot[6]},
{cell: rot[8]}
]);
}
]);
}
function latch_to_dotted_path(colourBand, side) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(approachingCol) &&
view[rot[right ? 8 : 6]].color === colourBand.next(approachingCol) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color)
) {
// We're on the wrong side; go inside the line
return {cell: rot[right ? 5 : 3]};
}
},
// Inside the line? pick a side
(rot) => {
var passedCol = view[rot[7]].color;
var approachingCol = view[rot[1]].color;
if(
!colourBand.contains(passedCol) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
if((approachingCol === colourBand.next(passedCol)) === right) {
return best_of([{cell: rot[3]}, {cell: rot[6]}, {cell: rot[0]}]);
} else {
return best_of([{cell: rot[5]}, {cell: rot[2]}, {cell: rot[8]}]);
}
}
]);
}
// == High-level logic begins here ==
var QUEEN_COL = colour_band(generate_band(3, 3));
var WORKER_COL = colour_band(generate_band(6, 3));
var AVOID_COL = colour_band([2]);
var INVERT_COL = colour_band([WHITE, 2]);
var MIN_FOOD = 5;
var MAX_WORKER_FOOD = 10;
function decide() {
var me = view[CENTRE].ant;
var queen = me.type === QUEEN;
if(queen && me.food > MIN_FOOD && me.food < MAX_WORKER_FOOD) {
var m = try_all_cells((i) => {
if(view[i].food && !foe_near(i)) {
// Try to spawn a worker next to the food;
// the worker will pick up the food on the next turn
return try_all_cells_near(i, (j) => ({cell: j, type: 1}));
}
}, true);
if(sanity_check(m)) {
return m;
}
}
if(!queen && me.food) {
return best_of([
// Look for queen
follow_dotted_path.bind(null, QUEEN_COL, SIDE_RIGHT, DIR_FORWARDS),
latch_to_dotted_path.bind(null, QUEEN_COL, SIDE_RIGHT),
// Failed to find queen's trail; try following worker trails backwards
follow_dotted_path.bind(null, WORKER_COL, SIDE_RIGHT, DIR_REVERSE),
latch_to_dotted_path.bind(null, WORKER_COL, SIDE_RIGHT),
// Failed to find any trail; cover ground as quickly as possible
fast_diagonal.bind(null, AVOID_COL)
]);
}
var myCol = queen ? QUEEN_COL : WORKER_COL;
return best_of([
grab_nearby_food,
// Disperse workers away from queen
!queen && escape_dotted_path.bind(null, QUEEN_COL, SIDE_RIGHT, WORKER_COL),
// Follow our own path
follow_dotted_path.bind(null, myCol, SIDE_RIGHT, DIR_FORWARDS),
// If our path looks suspicious, it could have wrapped; try to escape it
escape_dotted_path.bind(null, myCol, SIDE_RIGHT),
// Explore
// Laying a path causes us to move at 2/3 c, so workers can catch up.
lay_dotted_path.bind(null, myCol, SIDE_RIGHT, QUEEN_COL),
start_dotted_path.bind(null, myCol, SIDE_RIGHT, QUEEN_COL),
// Fall-back to white dots if we're inside a colour block
lay_dotted_path.bind(null, myCol, SIDE_RIGHT, INVERT_COL),
start_dotted_path.bind(null, myCol, SIDE_RIGHT, INVERT_COL),
// Stuck for some reason; try to escape
fast_diagonal.bind(null, AVOID_COL)
]);
}
return play_safe([
decide,
// No valid moves; try to find *anywhere* we can go.
go_anywhere,
// Try changing a nearby cell's colour for the heck of it.
{cell: 1, color: view[1].color % 8 + 1}
]);
```
Roman ants like to build roads, straight and fast. Because they build dotted roads, they are able to move at 2/3 the speed of light! Their roads also use cycling colours so that they know whether they're following the road forwards or in reverse, and the worker ants use a different set of colours than the queen (workers start getting spawned once the queen has a non-embarrassing amount of food available). Put together, this means that once a worker ant finds food, it can trace its own path backwards then trace the queen's path forwards to return the food (while tracing a path the ants move at the speed of light).
If you're wondering how the ants are able to follow a dotted line despite only being able to see a 3x3 grid at any time and not knowing their own direction: they draw the line to their right, not on their actual line of travel. So if (for example) the ant sees a filled square to the North, it knows the path must be above it, which means the direction of travel must be West (to keep the path on the right). If the ant sees a filled square to the North-East but not to the North-West or South-East, it must have gone past the end of the line, so paints the cell to the North-West and travels West. There's more complication around switching direction once food has been found, but that's the gist of it.
One other point worth mentioning is that when a worker ant sees food, they will jump at the opportunity to grab it without thinking about how they'll get back home (after all, an enemy ant could be ready to grab it!). So if a worker ant ever gets lost while carrying food, it will switch behaviour to a random-walk-ish pattern, leaving a yellow trail behind it to avoid retracing its steps. This helps the ants rediscover their trails and introduces enough randomness to avoid some of the infinite-loops which can otherwise occur.
It doesn't perform amazingly, and the ants have a habit of re-tracing their own footsteps (they're dumb enough not to know whether the path they're following is an old one, or one which they are in the process of drawing!), which occasionally leads to infinite loops.
Finally, there's a sanity checking method applied to any output which makes sure this can't get disqualified (hopefully!)
---
The updated version switches out the random walking for fast diagonal travel, fixes a bunch of bugs, and adds some attempts at walking using white roads if any ant gets stuck inside a large coloured area. Most of the bugs were found while converting it to use a high-level-thinking / low-level-abilities separation.
[Answer]
# Monorail
Still a work in progress, but I want to push something out now just because I'm paranoid that the competition will end before I finish otherwise.
```
var c0=5 //red
var c1=4 //cyan
var c2=6 //green
var c3=3 //magenta
var c4=7 //blue
var c5=8 //black
var c6=2 //yellow
var cN=1 //white
var ws=4 //support
var wb=3 //bodyguard
var wg=1 //gather
var wq=5 //queen
var v=[[0, 1, 2, 3, 4, 5, 6, 7, 8],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[2, 5, 8, 1, 4, 7, 0, 3, 6]]
var x1=[0,2,6,8]
var x2=[8,6,2,0]
var r1=[1,7,3,5]
var r2=[5,3,7,1]
switch(view[4].ant.type)
{
case 5: return queen()
case 4: return support()
case 3: return bodyguard()
case 1: return gather()
default: return {cell:4}
}
function queen()
{
if(fAlly(ws)<0)
{
if(view[4].color==c1&&view[4].ant.food>0)
{
var o=findOrient(c1,c2,c3)
if(sOpen(v[o][7])) return {cell:v[o][7],type:ws}
return doThing()
}
else if(view[4].color==c0&&view[4].ant.food>=6)
{
var o=findOrient(c1,c2,c3)
if(view[v[o][1]].color!=c1) return {cell:v[o][1],color:c1}
if(view[v[o][0]].color!=c2) return {cell:v[o][0],color:c2}
if(view[v[o][2]].color!=c3) return {cell:v[o][2],color:c3}
if(sOpen(v[o][7])) return {cell:v[o][7],type:ws}
}
return wander(c0)
}
else
{
if(view[4].color==c0&&view[4].ant.food<7)
{
if(view[4].ant.food >=5)
{
var o=findOrient(c1,c2,c3)
if(sOpen(v[o][1])) return {cell:v[o][1],type:wb}
if(sOpen(v[o][0])) return {cell:v[o][0],type:wb}
if(sOpen(v[o][2])) return {cell:v[o][2],type:wb}
}
if(view[4].ant.food>0)
{
var op=fOpen()
if(op>=0) return {cell:op,type:wg}
}
}
return doThing()
}
}
function doThing()
{
if(view[4].color!=c1) return {cell:4,color:c1}
var o=findOrient(c1,c2,c3)
if(view[4].ant.food>0&&fAlly(wg)>=0&&o==0)
{
var op=fOpen()
if(op>=0) return {cell:op,type:wg}
}
if(view[v[o][1]].color!=c1&&pootis(v[o][1])) return {cell:v[o][1],color:c1}
if(view[v[o][0]].color!=c2&&pootis(v[o][0])) return {cell:v[o][0],color:c2}
if(view[v[o][2]].color!=c3&&pootis(v[o][2])) return {cell:v[o][2],color:c3}
if(mOpen(v[o][1])) return {cell:v[o][1]}
if(view[v[o][3]].color!=c2&&pootis(v[o][3])) return {cell:v[o][3],color:c2}
if(view[v[o][5]].color!=c3&&pootis(v[o][5])) return {cell:v[o][5],color:c3}
if(view[v[o][6]].color!=c2&&pootis(v[o][6])) return {cell:v[o][6],color:c2}
if(view[v[o][8]].color!=c3&&pootis(v[o][8])) return {cell:v[o][8],color:c3}
if(view[v[o][7]].color!=c1&&pootis(v[o][7])) return {cell:v[o][7],color:c1}
return {cell:4}
}
function support()
{
var o = findOrient(c1,c2,c3)
var p = fAlly(wq)
switch(p)
{
case v[o][0]:
//if(mOpen(v[o][3])) return {cell:v[o][3]}
//if(mOpen(v[o][1])) return {cell:v[o][1]}
break
case v[o][1]:
//if(view[v[o][0]].food&&mOpen([v[o][0]])) return {cell:v[o][0]}
//if(view[v[o][2]].food&&mOpen([v[o][2]])) return {cell:v[o][2]}
break
case v[o][2]:
//if(mOpen(v[o][5])) return {cell:v[o][5]}
//if(mOpen(v[o][1])) return {cell:v[o][1]}
break
case v[o][3]:
//if(mOpen(v[o][6])) return {cell:v[o][6]}
break
case v[o][5]:
//if(mOpen(v[o][8])) return {cell:v[o][8]}
break
case v[o][6]: break
case v[o][7]: break
case v[o][8]: break
default:
if(sOpen(v[o][1])) return {cell:v[o][1]}
break
}
return {cell:4}
}
function bodyguard()
{
var o=0
switch(view[4].color)
{
case c1: o=findOrient(c1,c2,c3);break
case c2: o=findOrient(c2,c6,c1);break
case c3: o=findOrient(c3,c1,c6);break
default: return {cell:4}
}
var p = fAlly(wq)
if(view[4].ant.food>0)
{
switch(p)
{
case v[o][0]:
if(sOpen(v[o][1])) return {cell:v[o][1]}
if(sOpen(v[o][3])) return {cell:v[o][3]}
break
case v[o][1]:
if(sOpen([v[o][0]])) return {cell:v[o][0]}
if(sOpen([v[o][2]])) return {cell:v[o][2]}
break
case v[o][2]:
if(sOpen(v[o][1])) return {cell:v[o][1]}
if(sOpen(v[o][5])) return {cell:v[o][5]}
break
case v[o][3]:
if(sOpen([v[o][0]])) return {cell:v[o][0]}
if(sOpen([v[o][1]])) return {cell:v[o][1]}
break
case v[o][5]:
if(sOpen([v[o][2]])) return {cell:v[o][2]}
if(sOpen([v[o][1]])) return {cell:v[o][1]}
break
case v[o][6]:
if(sOpen([v[o][0]])) return {cell:v[o][0]}
if(sOpen([v[o][1]])) return {cell:v[o][1]}
if(sOpen([v[o][3]])) return {cell:v[o][3]}
break
case v[o][7]:
if(sOpen([v[o][1]])) return {cell:v[o][1]}
if(sOpen([v[o][0]])) return {cell:v[o][0]}
if(sOpen([v[o][2]])) return {cell:v[o][2]}
break
case v[o][8]:
if(sOpen([v[o][2]])) return {cell:v[o][2]}
if(sOpen([v[o][1]])) return {cell:v[o][1]}
if(sOpen([v[o][5]])) return {cell:v[o][5]}
break
default:
}
}
else
{
switch(p)
{
case v[o][0]:
if(mOpen(v[o][1])) return {cell:v[o][1]}
if(mOpen(v[o][3])) return {cell:v[o][3]}
break
case v[o][1]:
if(view[v[o][2]].food&&mOpen([v[o][2]])) return {cell:v[o][2]}
if(mOpen([v[o][0]])) return {cell:v[o][0]}
if(mOpen([v[o][2]])) return {cell:v[o][2]}
break
case v[o][2]:
if(mOpen(v[o][1])) return {cell:v[o][1]}
if(mOpen(v[o][5])) return {cell:v[o][5]}
break
case v[o][3]:
if(view[v[o][1]].food&&mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][0]])) return {cell:v[o][0]}
if(mOpen([v[o][1]])) return {cell:v[o][1]}
break
case v[o][5]:
if(view[v[o][1]].food&&mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][2]])) return {cell:v[o][2]}
if(mOpen([v[o][1]])) return {cell:v[o][1]}
break
case v[o][6]:
if(view[v[o][1]].food&&mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][0]])) return {cell:v[o][0]}
if(mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][3]])) return {cell:v[o][3]}
break
case v[o][7]:
if(view[v[o][0]].food&&mOpen([v[o][0]])) return {cell:v[o][0]}
if(view[v[o][2]].food&&mOpen([v[o][2]])) return {cell:v[o][2]}
if(mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][0]])) return {cell:v[o][0]}
if(mOpen([v[o][2]])) return {cell:v[o][2]}
break
case v[o][8]:
if(view[v[o][1]].food&&mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][2]])) return {cell:v[o][2]}
if(mOpen([v[o][1]])) return {cell:v[o][1]}
if(mOpen([v[o][5]])) return {cell:v[o][5]}
break
default:
}
}
if(view[4].color==c1)
{
if(view[v[o][1]].color!=c1&&pootis(v[o][1])) return {cell:v[o][1],color:c1}
if(view[v[o][0]].color!=c2&&pootis(v[o][0])) return {cell:v[o][0],color:c2}
if(view[v[o][2]].color!=c3&&pootis(v[o][2])) return {cell:v[o][2],color:c3}
if(view[v[o][3]].color!=c2) return {cell:v[o][3],color:c2}
if(view[v[o][5]].color!=c3) return {cell:v[o][5],color:c3}
if(view[v[o][6]].color!=c2) return {cell:v[o][6],color:c2}
if(view[v[o][8]].color!=c3) return {cell:v[o][8],color:c3}
if(view[v[o][7]].color!=c1) return {cell:v[o][7],color:c1}
}
return {cell:4}
}
function gather()
{
if(view[4].ant.food>0)
{
if(view[4].color==c1&&(testSQ(c1,c2)||testSQ(c1,c3))) return gDoThing(c1,c3,c2)
if(view[4].color==c2&&testSQ(c2,c1)) return gDoThing(c2,c1,c6)
if(view[4].color==c3&&testSQ(c3,c1)) return gDoThing(c3,c6,c1)
return wander(c5)
}
var n=fAlly(wq)
if(n<0) return wander(c4)
switch(n)
{
case 0:
if(mOpen(8)) return {cell:8}
if(mOpen(7)) return {cell:7}
if(mOpen(5)) return {cell:5}
break
case 1:
if(mOpen(6)) return {cell:6}
if(mOpen(8)) return {cell:8}
if(mOpen(7)) return {cell:7}
break
case 2:
if(mOpen(6)) return {cell:6}
if(mOpen(3)) return {cell:3}
if(mOpen(7)) return {cell:7}
break
case 3:
if(mOpen(8)) return {cell:8}
if(mOpen(2)) return {cell:2}
if(mOpen(5)) return {cell:5}
break
case 5:
if(mOpen(0)) return {cell:0}
if(mOpen(6)) return {cell:6}
if(mOpen(3)) return {cell:3}
break
case 6:
if(mOpen(2)) return {cell:2}
if(mOpen(5)) return {cell:5}
if(mOpen(1)) return {cell:1}
break
case 7:
if(mOpen(2)) return {cell:2}
if(mOpen(0)) return {cell:0}
if(mOpen(1)) return {cell:1}
break
case 8:
if(mOpen(0)) return {cell:0}
if(mOpen(1)) return {cell:1}
if(mOpen(3)) return {cell:3}
break
default:
break
}
return {cell:4}
}
function testSQ(ac1,ac2)
{
for(var i=0;i<4;i++)
{
if(view[r1[i]].color==ac1)
{
if(view[v[i][0]].color==ac2&&view[v[i][3]].color==ac2) return 1
if(view[v[i][2]].color==ac2&&view[v[i][5]].color==ac2) return 1
}
}
return 0
}
function gDoThing(ac1,ac2,ac3)
{
var o=findOrient(ac1,ac2,ac3)
if(view[v[o][1]].color!=ac1&&pootis(v[o][1])) return {cell:v[o][1],color:ac1}
if(view[v[o][0]].color!=ac2&&pootis(v[o][0])) return {cell:v[o][0],color:ac2}
if(view[v[o][2]].color!=ac3&&pootis(v[o][2])) return {cell:v[o][2],color:ac3}
if(sOpen(v[o][1])) return {cell:v[o][1]}
if(ac1==c2)
{
if(sOpen(v[o][0])) return {cell:v[o][0]}
if(sOpen(v[o][3])) return {cell:v[o][3]}
if(sOpen(v[o][6])) return {cell:v[o][6]}
}
else if(ac1==c3)
{
if(sOpen(v[o][2])) return {cell:v[o][2]}
if(sOpen(v[o][5])) return {cell:v[o][5]}
if(sOpen(v[o][8])) return {cell:v[o][8]}
}
else
{
if(sOpen(v[o][0])) return {cell:v[o][0]}
if(sOpen(v[o][2])) return {cell:v[o][2]}
if(sOpen(v[o][3])) return {cell:v[o][3]}
if(sOpen(v[o][5])) return {cell:v[o][5]}
}
return {cell:4}
}
function pootis(p)
{
var a=view[p].ant
if(a!=null&&a.friend&&a.type==wg&&(view[p].color==c4||view[p].color==c5)) return 0
return 1
}
function fAlly(t)
{
var a=view[4].ant
for(var i=0;i<9;i++)
{
if(i==4) i++
a=view[i].ant
if(a!=null&&a.friend&&a.type==t) return i
}
return -1
}
function fOpen()
{
for(var i=0;i<9;i++)
{
if(i==4) i++
if(sOpen(i)) return i
}
return -1
}
function sOpen(p)
{
return (view[p].ant==null&&!view[p].food)
}
function mOpen(p)
{
return (view[p].ant==null)
}
function wander(ac)
{
if(view[4].ant.type==5||view[4].ant.food==0)
{
var vf = vFood()
if(vf>=0) return {cell:vf}
if(view[4].color!=ac) return {cell:4,color:ac}
for(var i=0;i<4;i++)
{
if(view[x1[i]].color==ac&&view[x2[i]].color!=ac&&view[x2[i]].color!=c1&&mOpen(x2[i])) return {cell:x2[i]}
}
for(var i=0;i<4;i++)
{
if(mOpen(x1[i])&&view[x1[i]].color!=c1) return {cell:x1[i]}
}
}
else
{
if(view[4].color!=ac) return {cell:4,color:ac}
for(var i=0;i<4;i++)
{
if(view[x1[i]].color==ac&&view[x2[i]].color!=ac&&sOpen(x2[i])) return {cell:x2[i]}
}
for(var i=0;i<4;i++)
{
if(sOpen(x1[i])) return {cell:x1[i]}
}
}
return {cell:4}
}
function findOrient(ac1,ac2,ac3)
{
var w=[0,0,0,0]
w[0]=DI(view[0].color,view[1].color,view[2].color,0,ac1,ac2,ac3)
w[1]=DI(view[8].color,view[7].color,view[6].color,1,ac1,ac2,ac3)
w[2]=DI(view[6].color,view[3].color,view[0].color,2,ac1,ac2,ac3)
w[3]=DI(view[2].color,view[5].color,view[8].color,3,ac1,ac2,ac3)
var t=[0,0,0,0]
for(var i=0;i<4;i++)
{
switch(w[i])
{
case 4: t[0]++;break
case 5: t[1]++;break
case 6: t[2]++;break
case 7: t[3]++;break
case 8: t[0]+=2;break
case 9: t[1]+=2;break
case 10: t[2]+=2;break
case 11: t[3]+=2;break
case 12: t[0]+=3;break
case 13: t[1]+=3;break
case 14: t[2]+=3;break
case 15: t[3]+=3;break
default: break
}
}
var m=Math.max(...t)
for(var i=0;i<4;i++)
{
if(t[i]==m) return i
}
return 0
}
function DI(v1,v2,v3,d,ac1,ac2,ac3)
{
var t=[0,0,0,0]
switch(v1)
{
case ac2: t[0]++;t[3]++;break
case ac3: t[1]++;t[2]++;break
default: break
}
switch(v2)
{
case ac1: t[0]++;t[1]++;break
case ac2: t[3]++;break
case ac3: t[2]++;break
default: break
}
switch(v3)
{
case ac2: t[1]++;t[3]++;break
case ac3: t[0]++;t[2]++;break
default: break
}
var m=Math.max(...t)
if(m==0) return 0
var n=0
for(var i=0;i<4;i++)
{
if(t[i]==m){n=i;break}
}
if((d==2&&n==2)||(d==3&&n==3)) n=1
else if((d==2&&n==3)||(d==3&&n==2)) n=0
else n^=d
return m*4+n
}
function vFood()
{
for(var i=0;i<9;i++)
{
if(view[i].food) return i
}
return -1
}
function nColor(c)
{
var t=0
for(var i=0;i<9;i++)
{
if(view[i].color==c) t++
}
return t
}
```
To summarize, the queen moves in a straight line, creating the pattern behind her. A support worker is created to move right behind her and keep her in line. There are also gatherers, that hunt for food a la lone wolf or single queen, who will keep going until they acquire something to bring back to the rail, which will then lead them back to the queen.
All right, here's version 2. Now the gatherers actually do something.
Version 2.1 now. Yellow/Cyan markings have been switched around to prevent Black Hole from eating the entire trail any time they appear together in the same game.
Version 3. Bodyguard has been added to provide extra protection from the front (and grab food on the rail), while gatherers now draw black edges to ward away trail eraser and possibly help protect from Black Hole. Also the queen avoids cyan tiles in gatherer mode to prevent premature deployment.
All right, time for version 3.1. Colors have been changed again to keep trail eraser at bay *without* inciting the wrath of Wildfire. Gatherers have also been edited to keep on and identify the rail better (less bailing out/making new rails). There's some other minor things in there as well that I can't really bother with mentioning.
Version 3.2: Fixed some issues with bodyguard. It no longer attempts to grab food if it already has some, is less prone to getting stuck, and will draw rails if it can't find the queen.
[Answer]
# Claustrophobic Queen
A queen-only approach that does a random walk while attempting to avoid colored-in areas. Not a top contender, but moderately successful and tamper-proof. Parameter tweaking in progress.
```
var i, j
var orthogonals = [1, 3, 7, 5] // These are the non-diagonal cells
var move;
var scores = []; // An array of how desirable each potential move is
var score, neighbor, claustrophobia, newColor;
var crowdedNeighbors = null; // How many diagonal neighbors are colored CROWDED?
var runningFrom = null; // When in running phase, which direction did we come from?
var runningTo = null; // When in running phase, which direction should we head?
// Assign color magic numbers to variables
var EMPTY = 1;
var VISITED = 4;
var CROWDED = 7;
var RUNNING = 8;
function neighbors(cell) {
switch (cell) {
case 0: return [1, 3];
case 1: return [0, 2];
case 2: return [1, 5];
case 3: return [0, 6];
case 4: return orthogonals;
case 5: return [2, 8];
case 6: return [3, 7];
case 7: return [6, 8];
case 8: return [7, 5];
default: return null;
}
}
function isHungry(ant) {
if (ant.type === 5 || ant.food === 0) {
return true;
} else {
return false;
}
}
// Color own cell based on the number of neighbors that are colored
claustrophobia = 0;
for (i=0; i<9; i++) {
if (view[i].color !== EMPTY || i === 4) {
claustrophobia++;
}
if (i % 2 === 0 && i !== 4) {
if (view[i].color === CROWDED) {
crowdedNeighbors++;
} else if (view[i].color === RUNNING) {
crowdedNeighbors++;
runningFrom = i;
}
}
}
if (claustrophobia > 4) {
if (crowdedNeighbors > 1 || runningFrom !== null) {
// We're entering or currently in a straight-line running state
// in which we keep going until we find sufficient whitespace
newColor = RUNNING;
} else {
newColor = CROWDED;
}
} else {
newColor = VISITED;
}
if (view[4].color !== newColor) {
return {cell:4, color:newColor}
}
// If we've already colored the current cell properly, and we're in running mode,
// then move diametrically away from the runningFrom cell
switch (runningFrom) {
case 0:
runningTo = 8;
break;
case 2:
runningTo = 6;
break;
case 6:
runningTo = 2;
break;
case 8:
runningTo = 0;
break;
default:
break;
}
// Calculate a score for each potential move
// Lower numbers are better; null means illegal move
// Unexplored areas are better; food is the best (as long as ant can eat); don't move onto other ants
for (i=0; i<9; i++) {
// Base score of tile is 2 times color of tile
score = 2 * (view[i].color);
// Add colors of neighboring tiles
for (neighbor of neighbors(i)) {
score += view[neighbor].color;
}
// Give very good score to runningTo tile, unless it's also RUNNING color
if (i === runningTo && view[i].color !== RUNNING) {
score -= 4; // Magic number, possibly to be tweaked
}
if (i!==4 && view[i].ant) {
// Tile contains another ant; give very bad score
score = null;
} else if (view[i].food) {
// If a tile contains food, it's either highly desirable if the ant can eat, or illegal if it can't
if (isHungry(view[4].ant)) {
// Ant can eat; give food tile very good score
score = -1;
} else {
// Ant cannot eat; give food tile very bad score
score = null;
}
}
scores.push(score);
}
// Select best move based on the scores array
move = 4; // By default, stay put (this probably won't be the best move)
for (i=0; i<9; i++) {
if (scores[i] !== null && scores[i] < scores[move]) {
move = i;
}
}
return {cell:move};
```
The queen lays down a trail of cyan as she moves. She prioritizes moving to blank cells and cells with blank neighbors. The way the math comes out at the moment, this results in mostly diagonal movement and a checkerboard pattern. If the current cell has four or more colored neighbors, it is colored blue instead of cyan; blue cells are avoided with higher priority. Finally, if the queen is adjacent to two blue cells, she starts on a diagonal line of black until she reaches an open area again.
[![enter image description here](https://i.stack.imgur.com/G7YuV.png)](https://i.stack.imgur.com/G7YuV.png)
[Answer]
# Hoppemaur
*First of all I want to thank Trichoplax for creating this awesome challenge, which made me sign up to this site and start programming in javascript. I want to also thank you the other people still lurking around in the chatroom of this question, even exactly 3 months after it has been asked.*
My bot is not a serious contender for first place, but a single queen/self avoiding random walk approach, a little bit like a jumping [Claustrophobic Queen](https://codegolf.stackexchange.com/a/135818/75302).
[![Hoppemaur bot detail with painted pattern](https://i.stack.imgur.com/2rWeM.png)](https://i.stack.imgur.com/2rWeM.png)
## Code
```
//Hoppemaur
//å hoppe: to jump
//maur: ant
var WHITE = 1;
var OWN = 2;
var FOOD = 6;
var ESCAPE = 3;
var paint = 0;
var score = {0:2,1:-3,2:2,3:-3,4:-1,5:-3,6:2,7:-3,8:2};
// The ant should only walk diagonal (except when feeding)
var highest = 0;
var scoreindex;
var diagonals = [0, 2, 6, 8];
var diagonalsandself = [0, 2, 4, 6, 8]
var inversdiagonals = [8, 6, 2, 0];
var orthogonals = [1, 3, 5, 7];
var inverseorthogonals = [7, 5, 3, 1];
var rotate1orthogonals = [3, 1, 7, 5];
var rotate2orthogonals = [5, 7, 1, 3];
//checks if one of the diagonals or the own tile are painted
function checkforemptypattern() {
for (var i=0; i<diagonalsandself.length; i++) {
if (view[diagonalsandself[i]].color == OWN){
return false;}
}
return true;
}
//counts the diagonals painted in the requestest colour
function checktrapped(pattern) {
var diags=0;
for (var i=0; i<diagonals.length; i++) {
if (view[diagonals[i]].color == pattern){
diags=diags+1;
}
}
return diags;
}
//Biggest threat to this ant is food on orthogonals,
//it messes up the pattern if not dealt with it
if (view[4].color !== FOOD){
for (var i=0; i<orthogonals.length; i++) {
if (view[orthogonals[i]].food) {
return {cell:4, color:FOOD};
}
}
}
if (view[4].color == FOOD){
for (var i=0; i<orthogonals.length; i++) {
if (view[orthogonals[i]].food) {
if (!view[orthogonals[i]].ant){
return {cell:orthogonals[i]};
}
}
}
}
//If food shows up on diagonals while out of pattern,
//before grabbing food, the pattern must be painted
for (var i=0; i<diagonals.length; i++){
if (view[diagonals[i]].food){
if (checkforemptypattern()){
return {cell:4, color: OWN}
}
}
}
//Otherwise, food can easily be grabbed if not ant in way
for (var i=0; i<9; i++) {
if (view[i].food) {
if(!view[i].ant){
return {cell:i}
}
}
}
//After food has been grabbed orthogonal, back to food pile
if (view[4].color == WHITE){
for (i=0; i<orthogonals.length; i++) {
if (view[orthogonals[i]].color == FOOD && checktrapped(FOOD) == 0 && view[inverseorthogonals[i]].color !== FOOD && view[rotate1orthogonals[i]].color !== FOOD && view[rotate2orthogonals[i]].color !== FOOD){
if (!view[orthogonals[i]].ant){
return {cell:orthogonals[i]};
}
}
}
}
//First part of scoring
// Scoring to determine next move
// Scoring everything higher than own pattern and escape
for (var i=0; i<9; i++) {
if (view[i].color !== OWN) {
score[i] = score[i]+3;
}
if (view[i].color !== ESCAPE){
score[i] = score[i]+5;
}
}
// Scoring while in painted area (f.e. wildfire)
var l = 0;
for (var i=2; i<9; i++) {
var k = 0;
for (var j=0; j<9; j++) {
if (view[j].color == i) {
k=k+1;
if (k > 6){
paint=i;
}
if (view[j].color !==WHITE) {
l=l+1;
}
}
}
}
if (paint !== OWN && l >7) {
for (var i=0; i<diagonals.length; i++){
if (view[diagonals[i]].color == OWN) {
score[inversdiagonals[i]]=score[inversdiagonals[i]]+7;
}
if (view[diagonals[i]].color == WHITE) {
score[diagonals[i]]=score[diagonals[i]]+7
}
}
}
if (paint == OWN && l >7) {
for (var i=0; i<diagonals.length; i++){
if (view[diagonals[i]].color == ESCAPE) {
score[inversdiagonals[i]]=score[inversdiagonals[i]]+7;
}
if (view[diagonals[i]].color == WHITE) {
score[diagonals[i]]=score[diagonals[i]]+7
}
}
}
// the following might lead to some traps?
// score diagonals adjactant to white higher
if (view[1].color === WHITE) {
score[0] = score[0]+1;
score[2] = score[2]+1;
}
if (view[3].color === WHITE) {
score[0] = score[0]+1;
score[6] = score[6]+1;
}
if (view[5].color === WHITE) {
score[2] = score[2]+1;
score[8] = score[8]+1;
}
if (view[7].color === WHITE) {
score[6] = score[6]+1;
score[8] = score[8]+1;
}
//Don't move next to others, they steal your food!
if (view[0].ant || view[1].ant || view[2].ant){
score[6] = score [6]+10;
score[8] = score [8]+10;
}
if (view[0].ant || view[3].ant || view[6].ant){
score[2] = score [2]+10;
score[8] = score [8]+10;
}
if (view[6].ant || view[7].ant || view[8].ant){
score[0] = score [0]+10;
score[2] = score [2]+10;
}
if (view[2].ant || view[5].ant || view[8].ant){
score[0] = score [0]+10;
score[6] = score [6]+10;
}
//don't step on others!
for (var i=0; i<9; i++) {
if (i!==4 && view[i].ant) {
score[i] = -5;
}
}
//end of scoring, calculate best
for (var i=0; i<9; i++) {
if (score[i] > highest) {
highest = score[i];
scoreindex = i;
}
}
//Basic enemy avoidance
for (var i=0; i<9; i++) {
if (i!==4 && view[i].ant) {
return {cell:scoreindex}
}
}
//basic movement
//when surrounded by other paint
if (paint == ESCAPE && l>7){
if(view[4].color == OWN){
return{cell:scoreindex}
}
}
if (paint !== OWN && paint !== 0 && l>7){
if(view[4].color !== OWN){
return{cell:4, color:OWN}
}
}
if (paint == OWN && l>7){
if(view[4].color !== ESCAPE){
return{cell:4, color:ESCAPE}
}
}
//a) when off pattern
if (view[4].color !== OWN) {
if (view[4].color == ESCAPE){
if (checktrapped(ESCAPE)==4){
return{cell:scoreindex}
}
}
if (view[4].color == ESCAPE){
if (checktrapped(ESCAPE)==3){
return{cell:scoreindex}
}
}
if (checkforemptypattern()) {
return{cell:4, color:OWN};
}
//Am I trapped? Different possible traps follow here
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==4){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==3 && checktrapped(ESCAPE)==1){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==2 && checktrapped(ESCAPE)==1){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==2 && checktrapped(ESCAPE)==2){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==1 && checktrapped(ESCAPE)==2){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){
if (checktrapped(OWN)==1 && checktrapped(ESCAPE)==1){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){ //when the orthogonals are painted, some other guy was here before and movement traps are likely
if (view[1].color == OWN || view[7].color == OWN || view[3].color == OWN || view[5].color == OWN){
return{cell:4, color:ESCAPE}
}
}
if (view[4].color !== ESCAPE){ //when the orthogonals are painted, some other guy was here before and movement traps are likely
if (view[1].color == ESCAPE || view[7].color == ESCAPE || view[3].color == ESCAPE || view[5].color == ESCAPE){
return{cell:4, color:ESCAPE}
}
}
}
//b) when on pattern check surroundings for escape route
if (checktrapped(ESCAPE)==3){
return{cell:4, color:ESCAPE}
}
if (checktrapped(ESCAPE)==4){
return{cell:4, color:ESCAPE}
}
//otherwise just move on
return{cell:scoreindex}
```
## Explanation
The main idea of this bot was to shorten the painting time while still being able to identify the already visited area. To achieve this, the queen will normally only paint after every second movement. However the movement direction information is lost by doing so, resulting in a non directed jumping pattern. To avoid a true random walk, the queen values non-painted tiles higher than already painted ones and in case of backtracking, uses a pink escape colour to signal herself that she was there before. A scoring mechanism that incorporates the aforementioned provides the backbone of the general movement.
One big risk are foodpiles outside her diagonal movement pattern. If she stumbles on such, she will use green colour to mark her point of origin that she will get back to after grabbing the food to not get out of pattern. The last part of the bot deals with different situations the pink escape colour will be used in.
As an addition, basic enemy avoidance and a diagonal movement in already painted areas are also included (but not really tested yet).
Last but not least, the bot draws some beautiful abstract patterns, when left alone:
[![Hoppemaur bot overview pattern at the end of the game](https://i.stack.imgur.com/dG8BE.png)](https://i.stack.imgur.com/dG8BE.png)
[Answer]
# The Formation
This submission is hosted in [a github repository](https://github.com/eaglgenes101/formic-formation).
```
var marcher_count;var gatherer_count;var excess_gatherers;var tcell;var lh_cell;var rh_cell;var ant_off;var alt_cell;var cell_off;function debug(message)
{}
const MARCHER_A=1;const MARCHER_B=2;const GATHERER=3;const QUEEN=5;const S_END=[6,5,7,4,0,2,1,3];const S_FRONT=[7,5,6,0,4,1,3,2];const S_SIDE=[7,3,5,1,6,2,0,4];const S_GATHERER=[7,6,5,4,0,3,2,1];const SCAN_MOVES=[0,1,2,3,5,6,7,8];const CORNERS=[0,2,6,8];const EDGES=[1,3,5,7];const CCW=[[0,3,6,7,8,5,2,1],[1,0,3,6,7,8,5,2],[2,1,0,3,6,7,8,5],[3,6,7,8,5,2,1,0],[4,4,4,4,4,4,4,4],[5,2,1,0,3,6,7,8],[6,7,8,5,2,1,0,3],[7,8,5,2,1,0,3,6],[8,5,2,1,0,3,6,7]];const NEARS=[[6,5,3,5,4,2,3,2,1],[5,6,5,4,5,4,2,3,2],[3,5,6,2,4,5,1,2,3],[5,4,2,6,5,3,5,4,2],[4,5,4,5,6,5,4,5,4],[2,4,5,3,5,6,2,4,5],[3,2,1,5,4,2,6,5,3],[2,3,2,4,5,4,5,6,5],[1,2,3,2,4,5,3,5,6]];const SAN_ORD=[[1,3,6,2,5,7,8],[0,2,5,3,6,8,7],[5,1,0,8,7,3,6],[6,0,1,7,8,2,5],[],[2,8,7,1,0,6,3],[3,7,8,0,1,5,2],[8,6,3,5,2,0,1],[7,5,2,6,3,1,0]];const D_MARCH=1;const D_FOOD=2;const D_STALLED=3;const D_GATHERER=4;const U_REALIGN=5;const U_SENTINEL=6;const U_READY=7;const U_PANIC=8;const PUPS=[[0,1,2,3,4,5,6,7,8],[1,1,0,0,0,1,1,0,1],[2,0,2,0,4,2,2,0,2],[3,0,0,3,4,3,3,0,3],[4,0,4,4,4,4,0,0,4],[5,1,2,3,4,5,5,0,5],[6,1,2,3,0,5,5,0,6],[7,0,0,0,0,0,0,7,7],[8,1,2,3,4,5,6,7,8]];const PDOWNS=[[0,1,2,3,4,5,6,7,8],[1,1,0,3,4,5,5,0,1],[2,0,2,3,4,5,5,0,2],[3,3,3,3,3,3,3,3,3],[4,4,4,3,4,0,0,0,4],[5,5,5,3,0,5,5,0,5],[6,5,5,3,0,5,5,0,6],[7,0,0,3,0,0,0,7,7],[8,1,2,3,4,5,6,7,8]];const PSIDES=[[0,1,2,3,4,5,6,7,8],[1,1,0,3,4,1,1,0,1],[2,0,2,0,4,5,5,0,2],[3,3,0,3,3,3,3,3,3],[4,4,4,3,4,0,0,0,4],[5,1,5,3,0,5,5,0,5],[6,1,5,3,0,5,5,0,6],[7,0,0,3,0,0,0,7,7],[8,1,2,3,4,5,6,7,8]];const INIT_SEED=3734978372;const FINAL_SEED=2338395782;const SRECOLOR_PROB=0.7;const SONSTRIDE_PROB=0.5;const QFSPAWNP_MAX=0.05;const QFSPAWNP_MIN=0.00;const QFSPAWNP_DECAY=0.005;const QBSPAWNP_MAX=0.65;const QBSPAWNP_MIN=0.55;const QBSPAWNP_DECAY=0.01;const QFORMP_MAX=0.5;const QFORMP_MIN=0.3;const QFORMP_DECAY=0.01;const DISCOLORT=35;const ERASET=20;const SOBSTRUCT_FUZZ=6;const SSTRIDE_FUZZ=6;const OBSTRUCT_QWT=3;const SPREFWT=2;var state=null;function rand_init()
{state=INIT_SEED;for(var cell=0;cell<9;cell++)
{var v=view[cell];state^=v.color;state^=v.food<<3;if(v.ant!==null)
{state^=v.ant.friend<<4;state^=v.ant.type<<5;state^=v.ant.food<<8;}
ant_rand();}
state^=FINAL_SEED;if(state===0)state=1;}
function ant_rand()
{if(state===null)rand_init();state^=state<<13;state^=state>>>17;state^=state<<5;return state>>>0;}
function rand_choice(prob)
{return ant_rand()/4294967296<prob;}
function rand_sub(array,num)
{var return_array=array.slice();for(var i=0;i<num;i++)
{var rand_index=i+ant_rand()%(array.length-i);var x_val=return_array[rand_index];return_array[rand_index]=return_array[i];return_array[i]=x_val;}
return return_array.slice(0,num);}
function rand_perm(array)
{var return_array=array.slice();for(var i=0;i<array.length-1;i++)
{var rand_index=i+ant_rand()%(array.length-i)
var x_val=return_array[rand_index];return_array[rand_index]=return_array[i];return_array[i]=x_val;}
return return_array;}
function index_sort(arr)
{var index_array=[];for(var i=0;i<arr.length;i++)index_array.push(i);index_array.sort((a,b)=>(arr[a]===arr[b])?(a-b):(arr[a]-arr[b]));return index_array;}
function this_ant()
{return view[4].ant;}
function c_at(cell)
{return view[cell].color;}
function is_ally(cell)
{return view[cell].ant!==null&&view[cell].ant.friend===true;}
function is_enemy(cell)
{return view[cell].ant!==null&&view[cell].ant.friend===false;}
function is_harvestable(cell)
{return is_enemy(cell)&&view[cell].ant.type===QUEEN&&view[cell].ant.food>0;}
function lchk(c)
{if(is_ally(CCW[c][6])&&view[CCW[c][6]].ant.type===GATHERER)
if(is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type!==GATHERER)return D_GATHERER;if(is_ally(CCW[c][7])&&view[CCW[c][7]].ant.type===GATHERER&&is_ally(CCW[c][1]))return D_GATHERER;if(is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type===GATHERER)
if(is_ally(CCW[c][3])&&c_at(4)===D_MARCH)return D_STALLED;if(view[CCW[c][6]].food===1&&is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type!==GATHERER)return D_FOOD;if(view[CCW[c][7]].food===1&&is_ally(CCW[c][1])&&c_at(CCW[c][1])===D_FOOD)return D_FOOD;if(view[CCW[c][5]].food===1&&is_ally(CCW[c][3])&&view[CCW[c][3]].ant.type!==QUEEN&&c_at(4)===D_MARCH)return U_REALIGN;return null;}
function lchk2(c)
{if(is_ally(CCW[c][6])&&view[CCW[c][6]].ant.type===GATHERER)
if(is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type!==GATHERER)return D_GATHERER;if(is_ally(CCW[c][7])&&view[CCW[c][7]].ant.type===GATHERER&&is_ally(CCW[c][1]))return D_GATHERER;if(is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type===GATHERER)
if(is_ally(CCW[c][3])&&c_at(4)===D_MARCH)return D_STALLED;if(is_ally(CCW[c][2])&&view[CCW[c][2]].ant.type===GATHERER)
if(is_ally(CCW[c][1])&&view[CCW[c][1]].ant.type!==GATHERER)return D_GATHERER;if(is_ally(CCW[c][3])&&view[CCW[c][3]].ant.type===GATHERER)
if(is_ally(CCW[c][5])&&c_at(CCW[c][5])===D_GATHERER)return D_GATHERER;if(is_ally(CCW[c][1])&&view[CCW[c][1]].ant.type===GATHERER)
if(is_ally(CCW[c][7])&&c_at(4)===D_MARCH)return D_STALLED;if(view[CCW[c][6]].food===1&&is_ally(CCW[c][5])&&view[CCW[c][5]].ant.type!==GATHERER)return D_FOOD;if(view[CCW[c][7]].food===1&&is_ally(CCW[c][1])&&c_at(CCW[c][1])===D_FOOD)return D_FOOD;if(view[CCW[c][5]].food===1&&is_ally(CCW[c][3])&&view[CCW[c][3]].ant.type!==QUEEN&&c_at(4)===D_MARCH)return U_REALIGN;if(view[CCW[c][2]].food===1&&is_ally(CCW[c][1])&&view[CCW[c][1]].ant.type!==GATHERER)return D_FOOD;if(view[CCW[c][3]].food===1&&is_ally(CCW[c][5])&&c_at(CCW[c][5])===D_FOOD)return{cell:4,color:D_FOOD};if(view[CCW[c][1]].food===1&&is_ally(CCW[c][7])&&view[CCW[c][7]].ant.type!==QUEEN&&c_at(4)===D_MARCH)return U_REALIGN;return null;}
function sigc(output,order,c)
{if(c_at(4)===output)
for(cell_off of order)
{var tcell=CCW[c][cell_off];if(!is_ally(tcell)&&c_at(tcell)!==D_MARCH)
{if(view[tcell].food!==0&&view[tcell].color===D_FOOD)
{for(alt_cell of SCAN_MOVES)
{var n_wt=NEARS[tcell][alt_cell];if(n_wt>3&&n_wt<6&&is_ally(alt_cell))
if(view[alt_cell].ant.type===QUEEN||view[alt_cell].ant.type===GATHERER)
continue;}}
return{cell:tcell,color:D_MARCH};}}
return{cell:4,color:output};}
function is_gatherer_marcher(cell)
{if(!is_ally(cell)||view[cell].ant.food>0||view[cell].ant.type!==GATHERER)return false;if(this_ant().type===QUEEN)return true;lh_cell=CCW[cell][1];rh_cell=CCW[cell][7];if(is_ally(lh_cell)&&view[lh_cell].ant.type===QUEEN)return!is_ally(rh_cell)
else if(is_ally(rh_cell)&&view[rh_cell].ant.type===QUEEN)return!is_ally(lh_cell)
else return false;}
function is_like(cell)
{if(c_at(cell)===U_PANIC)return false;if(is_ally(CCW[cell][1])&&c_at(CCW[cell][1])===U_PANIC)return false;if(is_ally(CCW[cell][7])&&c_at(CCW[cell][7])===U_PANIC)return false;if(CORNERS.includes(cell)&&is_ally(cell))
{switch(view[cell].ant.type)
{case MARCHER_A:return view[cell].ant.food===0&&this_ant().type!==MARCHER_B;case MARCHER_B:return view[cell].ant.food===0&&this_ant().type!==MARCHER_A;case GATHERER:return is_gatherer_marcher(cell)&&this_ant().type!==GATHERER;case QUEEN:return true;default:return false;}}
return false;}
function is_other(cell)
{if(c_at(cell)===U_PANIC)return false;if(EDGES.includes(cell)&&is_ally(cell))
{switch(view[cell].ant.type)
{case MARCHER_A:return view[cell].ant.food===0&&this_ant().type!==MARCHER_A;case MARCHER_B:return view[cell].ant.food===0&&this_ant().type!==MARCHER_B;case GATHERER:return this_ant().type===QUEEN
case QUEEN:return true;default:return false;}}
return false;}
function view_corner()
{var scores=[0,0,0,0];for(var i=0;i<4;i++)
for(var j=0;j<8;j++)
{scores[i]*=2;var tcell=CCW[CORNERS[i]][j];if(is_ally(tcell)&&(is_like(tcell)||is_other(tcell)))scores[i]++;}
if(scores[0]>scores[1]&&scores[0]>scores[2]&&scores[0]>scores[3])return CORNERS[0];else if(scores[1]>scores[2]&&scores[1]>scores[3])return CORNERS[1];else if(scores[2]>scores[3])return CORNERS[2];else return CORNERS[3];}
const ONE_EDGE=10;const ONE_CORNER=11;const EE_BENT=20;const EE_STRAIGHT=21;const EC_LEFT=22;const EC_RIGHT=23;const EC_SKEWED=24;const EC_SPAWN=25;const CC_EDGED=26;const CC_LINE=27;const THREE_MARCH=30;const THREE_STAND=31;const THREE_RECOVER=32;const THREE_UNSTAND=33;const THREE_BLOCK=34;const THREE_HANG=35;const THREE_UNHANG=36;const THREE_SIDE=37;const FOUR_Z=40;const FOUR_STAIRS=41;const FOUR_BENT=42;function neighbor_type(top_left)
{var corners=[];for(tcell of CORNERS)
if(is_ally(tcell)&&is_like(tcell))corners.push(tcell);var edges=[];for(tcell of EDGES)
if(is_ally(tcell)&&is_other(tcell))edges.push(tcell);if(corners.length===1&&edges.length===0)return ONE_CORNER;if(corners.length===0&&edges.length===1)return ONE_EDGE;if(corners.length===0&&edges.length===2)return(edges[1]===CCW[edges[0]][4])?EE_STRAIGHT:EE_BENT;if(corners.length===2&&edges.length===0)return(corners[1]===CCW[corners[0]][4])?CC_LINE:CC_EDGED;else if(corners.length===1&&edges.length===1)
{if(edges[0]===CCW[top_left][1])return EC_LEFT;if(edges[0]===CCW[top_left][3])return EC_SPAWN;if(edges[0]===CCW[top_left][5])return EC_SKEWED;if(edges[0]===CCW[top_left][7])return EC_RIGHT;return null;}
else if(corners.length===1&&edges.length===2)
{if(edges.includes(CCW[top_left][1])&&edges.includes(CCW[top_left][3]))return THREE_MARCH;if(edges.includes(CCW[top_left][3])&&edges.includes(CCW[top_left][7]))return THREE_STAND;if(edges.includes(CCW[top_left][1])&&edges.includes(CCW[top_left][5]))return THREE_RECOVER;if(edges.includes(CCW[top_left][5])&&edges.includes(CCW[top_left][7]))return THREE_UNSTAND;if(edges.includes(CCW[top_left][1])&&edges.includes(CCW[top_left][7]))return THREE_BLOCK;return null;}
else if(corners.length===2&&edges.length===1)
{if(corners.includes(CCW[top_left][4])&&edges.includes(CCW[top_left][3]))return THREE_HANG;if(corners.includes(CCW[top_left][4])&&edges.includes(CCW[top_left][1]))return THREE_UNHANG;if(corners.includes(CCW[top_left][2])&&edges.includes(CCW[top_left][1]))return THREE_SIDE;}
else if(corners.length===2&&edges.length===2)
{if(edges.includes(CCW[top_left][3])&&edges.includes(CCW[top_left][7])&&corners.includes(CCW[top_left][4]))
return FOUR_Z;if(edges.includes(CCW[top_left][1])&&edges.includes(CCW[top_left][3])&&corners.includes(CCW[top_left][4]))
return FOUR_STAIRS;if(edges.includes(CCW[top_left][1])&&edges.includes(CCW[top_left][3])&&corners.includes(CCW[top_left][2]))
return FOUR_BENT;return null;}
return null;}
function sok(cand)
{if(cand===4)return true;if(view[cand].food!==0&&this_ant().food!==0)return false;if(view[cand].ant!==null)return false;return true;}
function spref(cand)
{var okscore=0;if(cand===4)okscore-=9;if(this_ant().type===GATHERER)
{for(tcell of SCAN_MOVES)
if(NEARS[cand][tcell]>1)
if(is_ally(tcell)&&view[tcell].ant.type===QUEEN)okscore-=1;}
else
{if(this_ant().food===0&&view[cand].food!==0)
{for(tcell of SCAN_MOVES)
if(is_ally(tcell)&&view[tcell].ant.food===0)
{if([MARCHER_A,MARCHER_B].includes(view[tcell].ant.type))
{var has_common_enemy=false;for(var i=0;i<9;i++)
if(is_enemy(i)&&NEARS[tcell][i]>=4)has_common_enemy=true;if(!has_common_enemy)
{var wt=(view[tcell].ant.type===this_ant().type)?1:-1;if(NEARS[4][tcell]===5)okscore+=wt;if(NEARS[4][tcell]===4)okscore-=wt;if(NEARS[cand][tcell]===5)okscore-=wt;if(NEARS[cand][tcell]===4)okscore+=wt;}}}
if(okscore>0)okscore=0;}}
return okscore*SPREFWT;}
function ssep()
{var has_ally=false;var cands=[0,0,0,0,0,0,0,0,0];for(var i=0;i<9;i++)cands[i]+=spref(i);for(tcell of SCAN_MOVES)
{if(is_ally(tcell))
{has_ally=true;var wt=(is_like(tcell)||is_other(tcell))?3:1;for(var i=0;i<9;i++)cands[i]-=NEARS[tcell][i]*wt;}}
if(!has_ally)return null;var prox_order=index_sort(cands);for(var i=8;i>=0;i--)
{var i_cell=prox_order[i];if(sok(i_cell))return{cell:i_cell};}
return null;}
function sstep(col)
{if(c_at(4)===1)return{cell:4,color:col};var cands=[0,0,0,0,0,0,0,0,0];for(tcell of SCAN_MOVES)
if(c_at(tcell)===col)
for(var i=0;i<9;i++)cands[i]-=NEARS[tcell][i];for(var i=0;i<9;i++)cands[i]+=spref(i);var prox_order=index_sort(cands);for(var i=8;i>=0;i--)
{var i_cell=prox_order[i];if(sok(i_cell))return{cell:i_cell};}
return{cell:4,color:col};}
function smove()
{for(tcell of rand_perm(SCAN_MOVES))
if(sok(tcell))return{cell:tcell};return{cell:4};}
function sdec_alone()
{var try_sep=ssep();if(try_sep!==null)return try_sep;var c=U_PANIC;for(tcell of rand_sub(SCAN_MOVES,7))
if(c_at(tcell)>1&&c_at(tcell)!==c)
{c=c_at(tcell);break;}
return sstep(c);}
function sdec_erase()
{var try_sep=ssep();if(try_sep!==null)return try_sep;for(tcell of rand_perm(SCAN_MOVES))
if(c_at(tcell)!==1)return{cell:tcell,color:1};if(c_at(4)!==1)return{cell:4,color:1};return sdec_alone();}
function sdec_discolor()
{if(c_at(1)!==c_at(6)&&c_at(6)!==1)return{cell:1,color:c_at(6)};if(c_at(2)!==c_at(3))return{cell:3,color:c_at(2)};var proximities=[0,0,0,0,0,0,0,0,0];for(var i=0;i<9;i++)proximities[i]+=ant_rand()%SOBSTRUCT_FUZZ+spref(i);for(tcell of SCAN_MOVES)
if(is_ally(tcell))
for(var i=0;i<9;i++)proximities[i]+=NEARS[tcell][i];var prox_order=index_sort(proximities);for(var i=8;i>=0;i--)
if(sok(prox_order[i]))return{cell:prox_order[i]};return smove();}
function sdec_stride()
{if(rand_choice(SONSTRIDE_PROB))
{var stride_scores=[0,0,0,0,0,0,0,0,0];for(tcell of SCAN_MOVES)
{for(var i=0;i<9;i++)
if(c_at(tcell)!==c_at(i)&&c_at(i)!==1)stride_scores[i]+=NEARS[tcell][i];}
for(var i=0;i<9;i++)
stride_scores[i]+=ant_rand()%SSTRIDE_FUZZ+spref(i);var prox_order=index_sort(stride_scores);for(var i=8;i>=0;i--)
if(sok(prox_order[i]))return{cell:prox_order[i]};}
return smove();}
function sdec_obstruct_textured()
{var proximities=[0,0,0,0,0,0,0,0,0];for(tcell of SCAN_MOVES)
{if(is_enemy(tcell))
{var wt=(view[tcell].ant.type===QUEEN)?OBSTRUCT_QWT:1;for(var i=0;i<9;i++)proximities[i]+=NEARS[tcell][i]*wt;}}
for(var i=0;i<9;i++)proximities[i]+=ant_rand()%SOBSTRUCT_FUZZ;var prox_order;if(rand_choice(SRECOLOR_PROB))
{prox_order=index_sort(proximities);for(var i=8;i>0;i--)
{var i_cell=prox_order[i];for(var j=0;j<i;j++)
{var j_cell=prox_order[j];if(c_at(i_cell)!==c_at(j_cell))return{cell:i_cell,color:c_at(j_cell)};}}}
for(tcell of SCAN_MOVES)
if(is_ally(tcell))
for(var i=0;i<9;i++)proximities[i]+=NEARS[tcell][i];for(var i=0;i<9;i++)proximities[i]+=spref(i);prox_order=index_sort(proximities);for(var i=8;i>=0;i--)
if(sok(prox_order[i]))return{cell:prox_order[i]};return{cell:4,color:1};}
function sdec_obstruct_flat()
{var proximities=[0,0,0,0,0,0,0,0,0];for(tcell of SCAN_MOVES)
{if(is_enemy(tcell))
{var wt=(view[tcell].ant.type===QUEEN)?OBSTRUCT_QWT:1;for(var i=0;i<9;i++)proximities[i]+=NEARS[tcell][i]*wt;}}
for(var i=0;i<9;i++)proximities[i]+=ant_rand()%SOBSTRUCT_FUZZ;var prox_order;if(rand_choice(SRECOLOR_PROB))
{prox_order=index_sort(proximities);for(var i=8;i>0;i--)
{var i_cell=prox_order[i];if(c_at(i_cell)!==D_MARCH)return{cell:i_cell,color:D_MARCH};}}
for(tcell of SCAN_MOVES)
if(is_ally(tcell))
for(var i=0;i<9;i++)proximities[i]+=NEARS[tcell][i];for(var i=0;i<9;i++)proximities[i]+=spref(i);prox_order=index_sort(proximities);for(var i=8;i>=0;i--)
if(sok(prox_order[i]))return{cell:prox_order[i]};return{cell:4,color:1};}
function saboteur()
{var colored_neighbors=0;for(tcell of SCAN_MOVES)
if(c_at(tcell)>1)colored_neighbors++;if(colored_neighbors<=2)return sdec_alone();else
{var num_enemies=0;for(tcell of SCAN_MOVES)
if(is_enemy(tcell))num_enemies++;var diversity=0;var counts=[0,0,0,0,0,0,0,0,0];for(var i=0;i<9;i++)
{diversity+=5-counts[c_at(i)];counts[c_at(i)]++;}
if(num_enemies>0)
{if(diversity>=ERASET)return sdec_obstruct_textured();else return sdec_obstruct_flat();}
else
{if(diversity>=DISCOLORT)return sdec_discolor();else if(diversity>=ERASET)return sdec_stride();else return sdec_erase();}}}
function gwatch(cand)
{if(cand.cell===4)return cand;if(cand.hasOwnProperty("color"))return cand;if(view[cand.cell].food!==0&&this_ant().food!==0)return sigc(U_PANIC,S_SIDE,0);if(view[cand.cell].ant!==null)return sigc(U_PANIC,S_SIDE,0);return cand;}
function egwatch(cand)
{if(cand.cell===4)return cand;if(cand.hasOwnProperty("color"))return cand;if(view[cand.cell].food!==0&&this_ant().food!==0)return gwatch(sdec_erase());if(view[cand.cell].ant!==null)return gwatch(sdec_erase());return cand;}
function gdec_ee_bent(c)
{return{cell:CCW[c][4]};}
function gdec_ec_left(c)
{if(c_at(c)===D_FOOD&&c_at(CCW[c][1])===D_FOOD)return{cell:CCW[c][7]};if(c_at(c)===D_STALLED&&c_at(CCW[c][1])===D_STALLED)return sigc(U_READY,S_GATHERER,c);if(c_at(c)===D_MARCH&&c_at(CCW[c][1])===D_MARCH)return sigc(D_MARCH,S_GATHERER,c);return sigc(c_at(4),S_GATHERER,c);}
function gdec_ec_right(c)
{if([D_MARCH,D_FOOD].includes(c_at(c))&&[D_MARCH,D_FOOD].includes(c_at(CCW[c][7])))
return{cell:CCW[c][6]};if(is_ally(c)&&view[c].ant.type===QUEEN)
return{cell:CCW[c][1]};if(c_at(c)===D_STALLED&&c_at(CCW[c][7])===D_STALLED)
return sigc(U_READY,S_GATHERER,c);return sigc(c_at(4),S_GATHERER,c);}
function gdec_cc_edged(c)
{if(view[CCW[c][2]].ant.type!==QUEEN)return saboteur();return{cell:CCW[c][1]};}
function gdec_three_block(c)
{if(c_at(CCW[c][7])==D_FOOD)return{cell:CCW[c][6]};return{cell:CCW[c][2]};}
function gdec_three_unstand(c)
{if(view[CCW[c][5]].ant.type!==QUEEN)return saboteur();return{cell:CCW[c][4]};}
function gdec_four_bent(c)
{return{cell:CCW[c][4]};}
function early_gatherer()
{var qcell=null;var food_count=0;for(tcell of SCAN_MOVES)
{if(is_ally(tcell)&&view[tcell].ant.type===QUEEN)qcell=tcell;else if(is_enemy(tcell))return saboteur();}
if(qcell===null)return saboteur();if(c_at(qcell)===D_FOOD)return{cell:CCW[qcell][7]};if(this_ant().food===0)
{for(tcell of rand_perm(CORNERS))
if(view[tcell].food>0&&NEARS[tcell][qcell]===5)
{if(c_at(tcell)===D_FOOD)return{cell:tcell};else return{cell:tcell,color:D_FOOD};}
for(tcell of rand_perm(EDGES))
if(view[tcell].food>0)
{if(c_at(tcell)!==D_FOOD&&NEARS[tcell][qcell]===4)
return{cell:tcell,color:D_FOOD};}}
return{cell:CCW[qcell][1]};}
function gatherer_retrieve()
{if(c_at(4)===U_PANIC)return saboteur();var c=view_corner();switch(neighbor_type(c))
{case EC_LEFT:return gwatch({cell:CCW[c][2]});case THREE_BLOCK:{if(c_at(CCW[c][7])===D_FOOD)return gwatch({cell:CCW[c][6]});return gwatch({cell:CCW[c][2]});}
case FOUR_BENT:return gwatch(sigc(c_at(4),S_FRONT,c));default:return early_gatherer();}}
function gatherer_return()
{if(c_at(4)===U_PANIC)return saboteur();var c=view_corner();switch(neighbor_type(c))
{case EC_LEFT:return gwatch({cell:CCW[c][2]});case THREE_BLOCK:return gwatch({cell:CCW[c][2]});case FOUR_BENT:return gwatch({cell:CCW[c][4]});default:return early_gatherer();}}
function gatherer_formation()
{if(c_at(4)===U_PANIC)return saboteur();var c=view_corner();switch(neighbor_type(c))
{case EC_LEFT:return gwatch(gdec_ec_left(c));case EC_RIGHT:return gwatch(gdec_ec_right(c));case CC_EDGED:return gwatch(gdec_cc_edged(c));case EE_BENT:return gwatch(gdec_ee_bent(c));case THREE_BLOCK:return gwatch(gdec_three_block(c));case THREE_UNSTAND:return gwatch(gdec_three_unstand(c));case FOUR_BENT:return gwatch(gdec_four_bent(c));default:return egwatch(early_gatherer());}}
function gatherer_decision()
{var marcher_count=0;var gatherer_count=0;var queen_pos=null;for(tcell of SCAN_MOVES)
if(is_ally(tcell))
{if(view[tcell].ant.type===MARCHER_A||view[tcell].ant.type===MARCHER_B)marcher_count++;if(view[tcell].ant.type===GATHERER)gatherer_count++;if(view[tcell].ant.type===QUEEN)queen_pos=tcell;}
if(gatherer_count>0)return saboteur();if(this_ant().food>0&&marcher_count>0)return gwatch(gatherer_return());else if(queen_pos!==null&&marcher_count>0)return gwatch(gatherer_formation());else if(marcher_count>0)return gwatch(gatherer_retrieve());else if(queen_pos!==null)return egwatch(early_gatherer());else return saboteur();}
function mdec_one_corner(c)
{if(view[c].ant.type===QUEEN)
return sigc(c_at(4),S_SIDE,c);else return saboteur();}
function mdec_one_edge(c)
{if([U_REALIGN,D_MARCH].includes(c_at(CCW[c][1])))
{if(view[CCW[c][2]].food===1)return{cell:c};if(is_ally(CCW[c][2])&&view[CCW[c][2]].ant.type===GATHERER)return{cell:c};}
return saboteur();}
function mdec_ee_bent(c)
{if(view[CCW[c][1]].ant.type===GATHERER&&view[CCW[c][3]].ant.type===QUEEN)return saboteur();if(view[CCW[c][1]].ant.type===QUEEN&&view[CCW[c][3]].ant.type===GATHERER)return saboteur();var u_sig=c_at(CCW[c][1]);var d_sig=c_at(CCW[c][3]);if(is_ally(c)&&view[c].ant.type===GATHERER)return sigc(c_at(4),S_SIDE,CCW[c][4]);var provisional=lchk(c);if(provisional!==null)
{if(provisional===U_REALIGN)return sigc(U_SENTINEL,S_END,c);return sigc(provisional,S_END,c);}
if(u_sig===D_STALLED)
{if([D_STALLED,U_READY,D_GATHERER].includes(d_sig)&&[D_STALLED,U_READY].includes(c_at(4)))
return sigc(D_STALLED,S_SIDE,c);if(d_sig===U_REALIGN&&c_at(4)===D_STALLED)
return sigc(D_STALLED,S_SIDE,c);}
if(view[CCW[c][1]].ant.type===QUEEN)
{var provisional=lchk(CCW[c][4]);if(provisional!==null)return sigc(provisional,S_END,CCW[c][4]);if(u_sig===D_GATHERER&&d_sig===U_REALIGN&&c_at(4)===D_GATHERER)
return sigc(D_GATHERER,S_END,CCW[c][4]);}
if(u_sig===U_SENTINEL)
{if(d_sig===U_REALIGN&&[D_MARCH,U_SENTINEL].includes(c_at(4)))return sigc(U_SENTINEL,S_SIDE,c);if(d_sig===D_STALLED&&[U_SENTINEL,D_STALLED].includes(c_at(4)))return sigc(U_SENTINEL,S_SIDE,c);if(d_sig===D_MARCH&&[U_SENTINEL,D_MARCH].includes(c_at(4)))return sigc(D_MARCH,S_SIDE,c);}
if(u_sig===D_GATHERER&&d_sig===D_STALLED&&c_at(4)===D_GATHERER)return sigc(D_STALLED,S_SIDE,c);return{cell:CCW[c][2]};}
function mdec_ee_straight(c)
{return sigc(U_REALIGN,S_SIDE,c);}
function mdec_ec_left(c)
{if(view[CCW[c][1]].ant.type===GATHERER&&view[c].ant.type===QUEEN)return saboteur();if(view[CCW[c][1]].ant.type===QUEEN&&view[c].ant.type===GATHERER)return saboteur();if(is_other(CCW[c][1])&&view[c].ant.type===QUEEN)return{cell:CCW[c][3]};var d_sig=PDOWNS[c_at(c)][c_at(CCW[c][1])];if(is_ally(CCW[c][4])&&view[CCW[c][4]].ant.type===GATHERER&&d_sig===D_STALLED&&c_at(4)===D_STALLED)
return sigc(D_STALLED,S_END,c);var provisional=lchk(CCW[c][4]);if(provisional!==null)
{if(provisional===U_REALIGN)return sigc(U_SENTINEL,S_END,CCW[c][4]);return sigc(provisional,S_END,CCW[c][4]);}
if(d_sig===U_REALIGN)
{if(c_at(4)===D_MARCH)return sigc(U_SENTINEL,S_END,CCW[c][4]);if(c_at(4)===U_SENTINEL)
{if(c_at(c)===D_MARCH)return{cell:CCW[c][2]};return sigc(U_SENTINEL,S_END,CCW[c][4]);}}
if(d_sig===D_STALLED)
{if([D_MARCH,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);if(c_at(4)===U_SENTINEL)return sigc(U_SENTINEL,S_END,CCW[c][4]);}
if(d_sig===D_GATHERER)
{if(c_at(4)===D_FOOD)return sigc(D_GATHERER,S_END,CCW[c][4]);if(c_at(4)===D_GATHERER)return sigc(D_STALLED,S_END,CCW[c][4]);}
if(d_sig===U_READY)
{if(c_at(4)===D_STALLED)
{if(c_at(CCW[c][2])!==D_MARCH)return{cell:CCW[c][2],color:D_MARCH};return sigc(D_MARCH,S_END,CCW[c][4]);}
if(c_at(4)===U_SENTINEL)return sigc(D_MARCH,S_END,CCW[c][4]);}
return{cell:CCW[c][2]};}
function mdec_ec_right(c)
{if(view[c].ant.type===GATHERER&&view[CCW[c][7]].ant.type===QUEEN)
if(is_ally(CCW[c][4])&&view[CCW[c][4]].ant.type!==this_ant().type)return{cell:CCW[c][5]};var d_sig=PDOWNS[c_at(c)][c_at(CCW[c][7])];var provisional=lchk(CCW[c][4]);if(provisional!==null)
{if(provisional===U_REALIGN)return sigc(U_SENTINEL,S_END,CCW[c][4]);return sigc(provisional,S_END,CCW[c][4]);}
if(d_sig===D_MARCH)
{if(c_at(4)===D_MARCH)return sigc(D_MARCH,S_END,CCW[c][4]);if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_MARCH,S_END,CCW[c][4]);}
if(d_sig===D_FOOD)
{if([U_SENTINEL,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);}
if(d_sig===D_GATHERER)
{if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_MARCH,S_END,CCW[c][4]);if([U_SENTINEL,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);}
if(d_sig===D_STALLED)
{if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_END,CCW[c][4]);if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);}
if(d_sig===U_READY)
{if(c_at(4)===D_STALLED)return sigc(D_MARCH,S_END,CCW[c][4]);if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_MARCH,S_END,CCW[c][4]);}
if(d_sig===U_REALIGN)
{if(c_at(4)===U_SENTINEL)return{cell:CCW[c][6]};if([D_FOOD,D_GATHERER,U_READY].includes(c_at(4)))return sigc(D_STALLED,S_END,CCW[c][4]);}
return sigc(d_sig,S_END,CCW[c][4]);}
function mdec_ec_spawn(c)
{if(view[c].ant.type===QUEEN&&c_at(c)===D_MARCH&&c_at(CCW[c][3])===D_STALLED)
if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_SIDE,c);return saboteur();}
function mdec_three_march(c)
{var d_sig=PDOWNS[c_at(c)][c_at(CCW[c][1])];var u_sig=c_at(CCW[c][3]);var provisional=lchk2(c);if(provisional!==null)return sigc(provisional,S_FRONT,c);if(u_sig===U_SENTINEL)
{if(d_sig===D_GATHERER&&[D_GATHERER,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_STALLED&&[D_MARCH,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);}
if(u_sig===U_REALIGN)
{if(d_sig===U_REALIGN&&c_at(4)===U_REALIGN)
if(c_at(c)===U_SENTINEL)
{if(c_at(CCW[c][7])===D_MARCH)return sigc(U_REALIGN,S_FRONT,c);return{cell:CCW[c][2]};}
if(d_sig===D_FOOD&&[D_MARCH,D_FOOD].includes(c_at(4)))return sigc(D_FOOD,S_FRONT,c);if(d_sig===U_READY&&c_at(4)===D_STALLED)return sigc(D_MARCH,S_FRONT,c);if(d_sig===D_STALLED&&[D_MARCH,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_GATHERER&&[D_GATHERER,D_STALLED].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_MARCH&&c_at(4)===D_STALLED)return sigc(D_STALLED,S_FRONT,c);}
if(u_sig===D_MARCH)
{if(d_sig===D_FOOD&&c_at(4)===D_FOOD)return sigc(D_FOOD,S_FRONT,c);if(d_sig===U_REALIGN&&c_at(4)===D_MARCH)
if(c_at(c)===U_SENTINEL)return sigc(U_REALIGN,S_FRONT,c);if(d_sig===U_READY&&c_at(4)===U_READY)return sigc(D_MARCH,S_FRONT,c);}
if(u_sig===D_STALLED)
{if(d_sig===U_READY&&c_at(4)===D_STALLED)return sigc(U_READY,S_FRONT,c);if(d_sig===D_STALLED&&[D_STALLED,D_MARCH].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_GATHERER&&c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_MARCH&&c_at(4)===D_STALLED)return sigc(D_STALLED,S_FRONT,c);if(d_sig===U_REALIGN&&[D_STALLED,D_MARCH].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,c);}
if(u_sig===D_GATHERER)
{if(d_sig===D_STALLED&&c_at(4)===D_GATHERER)
if(view[CCW[c][3]].ant.type===QUEEN)return sigc(D_STALLED,S_FRONT,c);if(d_sig===D_GATHERER&&c_at(4)===D_GATHERER)return sigc(D_GATHERER,S_FRONT,c);if(d_sig===D_FOOD&&c_at(4)===D_GATHERER)return sigc(D_FOOD,S_FRONT,c);}
if(u_sig===D_FOOD)
{if(d_sig===D_FOOD&&c_at(4)===D_FOOD)return sigc(D_FOOD,S_FRONT,c);if(d_sig===D_GATHERER&&c_at(4)===D_GATHERER)return sigc(D_GATHERER,S_FRONT,c);}
return{cell:CCW[c][2]};}
function mdec_three_stand(c)
{var provisional=lchk2(c);if(provisional!==null)return sigc(provisional,S_SIDE,c);var u_sig=c_at(CCW[c][3]);var d_sig=PSIDES[c_at(c)][c_at(CCW[c][7])];if(u_sig===U_REALIGN)
{if([D_MARCH,D_STALLED].includes(d_sig)&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(c_at(4)===U_REALIGN)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);}
if(u_sig===D_MARCH&&d_sig===U_REALIGN&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(u_sig===D_STALLED&&[D_STALLED,U_REALIGN].includes(d_sig)&&c_at(4)===D_STALLED)
return sigc(D_STALLED,S_SIDE,CCW[c][4]);return sigc(D_MARCH,S_SIDE,CCW[c][4]);}
function mdec_three_unstand(c)
{if(view[CCW[c][5]].ant.type===QUEEN)
{var provisional=lchk(c);if(provisional!==null)return sigc(provisional,S_FRONT,c);var d_sig=PUPS[c_at(c)][c_at(CCW[c][7])];return sigc(d_sig,S_FRONT,c);}
else
{var provisional=lchk(CCW[c][4]);if(provisional!==null)return sigc(provisional,S_FRONT,CCW[c][4]);var u_sig=c_at(CCW[c][5]);var d_sig=PDOWNS[c_at(c)][c_at(CCW[c][7])];if(u_sig===D_MARCH)
{if(d_sig===U_READY&&c_at(4)===U_READY)return sigc(D_MARCH,S_FRONT,CCW[c][4]);if(d_sig===D_FOOD&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_MARCH,S_FRONT,CCW[c][4]);}
if(u_sig===D_FOOD)
{if(d_sig===D_FOOD&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(u_sig===D_GATHERER)
{if(d_sig===D_FOOD&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(u_sig===D_STALLED)
{if(d_sig===U_READY)
{if(c_at(4)===D_STALLED)return sigc(U_READY,S_FRONT,CCW[c][4]);if(c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(d_sig===D_FOOD)
{if(c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if(c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(d_sig===D_STALLED)
{if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_FRONT,CCW[c][4]);if(c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(d_sig===D_GATHERER&&c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,CCW[c][4]);if([D_MARCH,U_REALIGN].includes(d_sig)&&c_at(4)===D_GATHERER)
return sigc(D_STALLED,S_FRONT,CCW[c][4]);if(c_at(4)===D_FOOD)return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(u_sig===U_REALIGN)
{if(d_sig===D_FOOD&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(u_sig===U_SENTINEL)
{if(d_sig===D_FOOD)
{if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_FRONT,CCW[c][4]);if(c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);}
if(d_sig===D_GATHERER&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_FRONT,CCW[c][4]);if(d_sig===D_MARCH&&c_at(4)===U_SENTINEL)return sigc(D_MARCH,S_FRONT,CCW[c][4]);if(d_sig===D_STALLED&&c_at(4)===U_SENTINEL)return sigc(D_STALLED,S_FRONT,CCW[c][4]);if(d_sig===U_READY&&c_at(4)===D_STALLED)return sigc(U_READY,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_FRONT,CCW[c][4]);}
if(u_sig===U_READY)
{if(d_sig===D_FOOD&&c_at(4)===D_MARCH)return sigc(U_REALIGN,S_FRONT,CCW[c][4]);if([D_FOOD,D_GATHERER].includes(c_at(4)))return sigc(D_MARCH,S_FRONT,CCW[c][4]);}
return sigc(c_at(4),S_FRONT,CCW[c][4]);}}
function mdec_three_recover(c)
{return sigc(U_SENTINEL,S_FRONT,c);}
function mdec_three_hang(c)
{return sigc(c_at(4),S_SIDE,CCW[c][4]);}
function mdec_three_unhang(c)
{return sigc(c_at(4),S_SIDE,c);}
function mdec_four_z(c)
{var provisional=lchk2(CCW[c][4]);if(provisional!==null)return sigc(provisional,S_SIDE,CCW[c][4]);var u_sig=PSIDES[c_at(c)][c_at(CCW[c][7])];var d_sig=PSIDES[c_at(CCW[c][4])][c_at(CCW[c][3])];if(u_sig===D_FOOD)
{if([D_FOOD,D_STALLED,U_REALIGN].includes(d_sig)&&c_at(4)===U_REALIGN)
return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(d_sig===D_GATHERER&&[U_REALIGN,D_GATHERER].includes(c_at(4)))
return sigc(U_REALIGN,S_SIDE,CCW[c][4]);}
if(u_sig===D_STALLED)
{if(d_sig===U_REALIGN)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(d_sig===D_FOOD&&c_at(4)===U_REALIGN)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);}
if(u_sig===D_GATHERER)
{if(d_sig===U_REALIGN&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,CCW[c][4]);if(d_sig===D_FOOD&&[U_REALIGN,D_GATHERER].includes(c_at(4)))
return sigc(U_REALIGN,S_SIDE,CCW[c][4]);}
if(u_sig===U_REALIGN)
{if(d_sig===D_FOOD&&c_at(4)===U_REALIGN)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(d_sig===D_STALLED)return sigc(U_REALIGN,S_SIDE,CCW[c][4]);if(d_sig===D_GATHERER&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,CCW[c][4]);if(d_sig===U_READY&&c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,CCW[c][4]);}
if(u_sig===U_READY&&d_sig===U_REALIGN&&c_at(4)===U_REALIGN)
return sigc(D_MARCH,S_SIDE,CCW[c][4]);return sigc(D_MARCH,S_SIDE,CCW[c][4]);}
function mdec_four_stairs(c)
{var provisional=lchk2(c);if(provisional!==null)return sigc(provisional,S_SIDE,c);var u_sig=PSIDES[c_at(c)][c_at(CCW[c][1])];var d_sig=PSIDES[c_at(CCW[c][4])][c_at(CCW[c][3])];if(u_sig===D_MARCH)
{if(d_sig===D_FOOD)
{if(c_at(4)===D_MARCH)return sigc(D_FOOD,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);}
if(d_sig===U_READY)
{if(c_at(4)===U_READY)return sigc(D_MARCH,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);}
if(d_sig===D_STALLED)
{if(c_at(4)===D_MARCH)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_GATHERER&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);if([D_MARCH,U_REALIGN].includes(d_sig)&&c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);}
if(u_sig===D_FOOD)
{if(d_sig===D_MARCH)
{if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);if(c_at(4)===D_MARCH)return sigc(D_FOOD,S_SIDE,c);}
if(d_sig===U_READY)
{if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_GATHERER&&[U_REALIGN,D_GATHERER].includes(c_at(4)))return sigc(D_FOOD,S_SIDE,c);if([U_REALIGN,D_STALLED].includes(d_sig)&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(u_sig===D_STALLED)
{if(d_sig===D_STALLED)
{if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===D_MARCH)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);}
if(d_sig===D_MARCH)
{if(c_at(4)===D_MARCH)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_GATHERER)
{if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);if([D_STALLED,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===U_READY)
{if(c_at(4)===D_STALLED)return sigc(U_READY,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);}
if(d_sig===U_REALIGN&&[U_REALIGN,D_MARCH].includes(c_at(4)))return sigc(D_STALLED,S_SIDE,c);if(d_sig===D_FOOD&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(u_sig===D_GATHERER)
{if(d_sig===D_STALLED)
{if([D_STALLED,D_GATHERER].includes(c_at(4)))return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===U_READY)
{if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_FOOD&&[D_GATHERER,U_REALIGN].includes(c_at(4)))return sigc(D_FOOD,S_SIDE,c);if([D_MARCH,U_REALIGN].includes(d_sig)&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);if(d_sig===D_GATHERER&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(u_sig===U_REALIGN)
{if(d_sig===U_REALIGN)
{if(c_at(4)===D_MARCH)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_STALLED)
{if(c_at(4)===D_MARCH)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(d_sig===D_MARCH&&c_at(4)===U_REALIGN)return sigc(D_MARCH,S_SIDE,c);if([D_FOOD,D_GATHERER,U_READY].includes(d_sig)&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);}
if(u_sig===U_READY)
{if(d_sig===D_MARCH)
{if(c_at(4)===U_READY)return sigc(D_MARCH,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(U_READY,S_SIDE,c);}
if([D_FOOD,D_GATHERER].includes(d_sig))
{if(c_at(4)===D_STALLED)return sigc(D_STALLED,S_SIDE,c);if(c_at(4)===U_REALIGN)return sigc(U_READY,S_SIDE,c);}
if(d_sig===D_STALLED&&c_at(4)===D_STALLED)return sigc(U_READY,S_SIDE,c);if(d_sig===U_REALIGN&&c_at(4)===U_REALIGN)return sigc(D_STALLED,S_SIDE,c);if(d_sig===U_READY&&c_at(4)===U_REALIGN)return sigc(U_READY,S_SIDE,c);}
return sigc(c_at(4),S_SIDE,c);}
function mwatch(cand)
{if(cand.cell===4)return cand;if(cand.hasOwnProperty("color"))return cand;if(view[cand.cell].food!==0)return sigc(D_FOOD,S_SIDE,0);if(is_harvestable(cand.cell))return sigc(D_FOOD,S_SIDE,0);if(view[cand.cell].ant!==null)return sigc(U_PANIC,S_SIDE,0);return cand;}
function marcher_decision()
{if(c_at(4)===U_PANIC||this_ant().food>0)return saboteur();var gatherer_count=0;var enemy_count=0;for(tcell of SCAN_MOVES)
{if(is_ally(tcell)&&view[tcell].ant.type===GATHERER)gatherer_count++;else if(is_enemy(tcell)&&!is_harvestable(tcell))enemy_count++;}
if(gatherer_count>1||enemy_count>0)return saboteur();var colored_neighbors=0;for(tcell of SCAN_MOVES)
if(c_at(tcell)>1)colored_neighbors++;if(colored_neighbors>5)return saboteur();var c=view_corner();switch(neighbor_type(c))
{case ONE_CORNER:return mwatch(mdec_one_corner(c));case ONE_EDGE:return mwatch(mdec_one_edge(c));case EE_BENT:return mwatch(mdec_ee_bent(c));case EE_STRAIGHT:return mwatch(mdec_ee_straight(c));case EC_LEFT:return mwatch(mdec_ec_left(c));case EC_RIGHT:return mwatch(mdec_ec_right(c));case EC_SPAWN:return mwatch(mdec_ec_spawn(c));case THREE_MARCH:return mwatch(mdec_three_march(c));case THREE_STAND:return mwatch(mdec_three_stand(c));case THREE_RECOVER:return mwatch(mdec_three_recover(c));case THREE_UNSTAND:return mwatch(mdec_three_unstand(c));case THREE_HANG:return mwatch(mdec_three_hang(c));case THREE_UNHANG:return mwatch(mdec_three_unhang(c));case FOUR_Z:return mwatch(mdec_four_z(c));case FOUR_STAIRS:return mwatch(mdec_four_stairs(c));default:return saboteur();}}
function opening_queen()
{for(tcell of rand_perm(SCAN_MOVES))
if(view[tcell].food===1)return{cell:tcell};var has_ally=false;var proxs=[0,0,0,0,0,0,0,0,0];for(tcell of SCAN_MOVES)
{if(view[tcell].ant!==null)
{has_ally=true;for(var i=0;i<9;i++)proxs[i]-=NEARS[tcell][i];}}
if(has_ally)
{var prox_order=index_sort(proxs);for(var i=8;i>=0;i--)
{var i_cell=prox_order[i];if(view[i_cell].ant===null&&view[i_cell].food===0)return{cell:i_cell};}}
if(this_ant().food>0)
{var num_ants=0;for(tcell of SCAN_MOVES)
if(view[tcell].ant!==null)num_ants++;if(num_ants===0)
{var is_clear=true;var num_black_corners=0;var black_corner=null;for(var tcell=0;tcell<9;tcell++)
{if(CORNERS.includes(tcell))
{if(c_at(tcell)===8)
{num_black_corners++;black_corner=tcell;}
else if(c_at(tcell)!==1)is_clear=false;}
else if(c_at(tcell)!==1)is_clear=false;}
if(num_black_corners===1&&is_clear)return{cell:CCW[black_corner][7],type:GATHERER};}}
if(c_at(4)!==8)return{cell:4,color:8};var cands=[0,0,0,0,9,0,0,0,0];for(tcell of SCAN_MOVES)
if(c_at(tcell)===8)
for(var i=0;i<9;i++)cands[i]-=NEARS[tcell][i];var cand_order=index_sort(cands);for(var i=8;i>=0;i--)
{var i_cell=cand_order[i];if(view[i_cell].ant===null&&view[i_cell].food===0)return{cell:i_cell};}
return{cell:4,color:8};}
function early_queen()
{var gcell=null;var ally_count=0;for(tcell of rand_perm(SCAN_MOVES))
{if(is_ally(tcell))
{ally_count++;if(view[tcell].ant.type===GATHERER&&EDGES.includes(tcell))gcell=tcell;}}
if(gcell===null)return opening_queen();for(tcell of rand_perm(CORNERS))
if(view[tcell].food>0&&NEARS[tcell][gcell]===5)
{if(c_at(tcell)===D_FOOD)return{cell:tcell};else return{cell:tcell,color:D_FOOD};}
for(tcell of rand_perm(EDGES))
if(view[tcell].food>0)
{if(c_at(tcell)!==D_FOOD&&NEARS[tcell][gcell]===4)
return{cell:tcell,color:D_FOOD};}
if(c_at(4)===D_FOOD)
{if(c_at(CCW[gcell][2])===D_FOOD&&view[CCW[gcell][2]].food===0)
return{cell:CCW[gcell][2],color:D_MARCH};return{cell:4,color:D_MARCH};}
if(c_at(CCW[gcell][6])===D_FOOD&&view[CCW[gcell][6]].food===0)
return{cell:CCW[gcell][6],color:D_MARCH};if(EDGES.includes(gcell)&&this_ant().food>2&&ally_count===1)
{var num_clear_cells=0;var num_down_food=0;var is_valid=true;for(var tcell=0;tcell<9;tcell++)
{if(c_at(tcell)===D_FOOD)
{num_down_food++;if(tcell!==4&&tcell!==gcell)is_valid=false;}
if(c_at(tcell)===D_MARCH)num_clear_cells++;}
if(is_valid&&num_down_food===1&&num_clear_cells===8)
{var food_factor=QFORMP_MAX-QFORMP_MIN
var food_coefficient=QFORMP_DECAY/food_factor
var actual_prob=food_factor/(food_coefficient*(this_ant().food-3)+1)+QFORMP_MIN;if(rand_choice(actual_prob))return{cell:CCW[gcell][1],type:rand_choice(.5)?MARCHER_A:MARCHER_B};else return{cell:gcell,color:D_MARCH};}}
return{cell:CCW[gcell][7]};}
function qwatch(cand)
{if(cand.hasOwnProperty("type")&&this_ant().food===0)return sigc(U_PANIC,S_SIDE,0);if(cand.hasOwnProperty("type")&&view[cand.cell].food!==0)return sigc(U_PANIC,S_SIDE,0);if(cand.cell===4)return cand;if(cand.hasOwnProperty("color"))return cand;if(is_enemy(cand.cell))return sigc(U_PANIC,S_SIDE,0);if(is_ally(cand.cell))return sigc(c_at(4),S_SIDE,0);return cand;}
function eqwatch(cand)
{if(cand.hasOwnProperty("type")&&this_ant().food===0)return qwatch(opening_queen());if(cand.hasOwnProperty("type")&&view[cand.cell].food!==0)return qwatch(opening_queen());if(cand.cell===4)return cand;if(cand.hasOwnProperty("color"))return cand;if(is_enemy(cand.cell))return qwatch(opening_queen());if(is_ally(cand.cell))return qwatch(opening_queen());return cand;}
function qdec_ee_straight(c)
{return sigc(c_at(4),S_SIDE,c);}
function qdec_ee_bent(c)
{return{cell:CCW[c][2]};}
function qdec_ec_skewed(c)
{if(view[CCW[c][5]].ant.type!==GATHERER)return opening_queen();if(this_ant().food>0&&view[c].ant.type===MARCHER_A)return{cell:CCW[c][7],type:MARCHER_B};if(this_ant().food>0&&view[c].ant.type===MARCHER_B)return{cell:CCW[c][7],type:MARCHER_A};return opening_queen();}
function qdec_ec_spawn(c)
{if(view[CCW[c][3]].ant.type!==GATHERER)return opening_queen();if(this_ant().food>0&&view[c].ant.type===MARCHER_A)return{cell:CCW[c][1],type:MARCHER_B};if(this_ant().food>0&&view[c].ant.type===MARCHER_B)return{cell:CCW[c][1],type:MARCHER_A};return opening_queen();}
function qdec_cc_edged(c)
{if(view[c].ant.type!==GATHERER)return opening_queen();if(this_ant().food>0&&view[CCW[c][2]].ant.type===MARCHER_A)return{cell:CCW[c][1],type:MARCHER_B};if(this_ant().food>0&&view[CCW[c][2]].ant.type===MARCHER_B)return{cell:CCW[c][1],type:MARCHER_A};return opening_queen();}
function qdec_three_march(c)
{var u_sig=PUPS[c_at(c)][c_at(CCW[c][1])];if(u_sig===D_STALLED)
{if(c_at(CCW[c][3])===D_MARCH&&[D_MARCH,D_GATHERER].includes(c_at(4)))
return sigc(D_STALLED,S_FRONT,c);if(c_at(CCW[c][3])===U_READY&&c_at(4)===D_STALLED)return sigc(U_READY,S_FRONT,c);}
if(u_sig===D_MARCH&&c_at(CCW[c][3])===U_READY&&c_at(4)===U_READY)
return sigc(D_MARCH,S_FRONT,c);if(u_sig===U_READY&&c_at(CCW[c][3])===U_REALIGN&&c_at(4)===U_READY)
if(c_at(CCW[c][1])===D_MARCH)return sigc(D_MARCH,S_FRONT,c);return sigc(c_at(4),S_FRONT,c);}
function qdec_three_stand(c)
{var u_sig=PUPS[c_at(c)][c_at(CCW[c][7])];if(u_sig===D_STALLED)
{if(c_at(CCW[c][3])===D_MARCH&&c_at(4)===D_GATHERER)return sigc(D_STALLED,S_FRONT,c);if(c_at(CCW[c][3])===U_READY&&c_at(4)===D_STALLED)return sigc(U_READY,S_FRONT,c);}
if(u_sig===D_MARCH&&c_at(CCW[c][3])===U_READY&&c_at(4)===U_READY)
return sigc(D_MARCH,S_FRONT,c);if(u_sig===U_READY&&c_at(CCW[c][3])===U_REALIGN&&c_at(4)===U_READY)
if(c_at(CCW[c][1])===D_MARCH)return sigc(D_MARCH,S_FRONT,c);return sigc(c_at(4),S_FRONT,c);}
function qdec_three_recover(c)
{var u_sig=PUPS[c_at(c)][c_at(CCW[c][1])];if(u_sig===D_FOOD)return sigc(D_FOOD,S_FRONT,c);if(this_ant().food>0&&[D_STALLED,U_READY].includes(u_sig))
{var food_factor=QFSPAWNP_MAX-QFSPAWNP_MIN
var food_coefficient=QFSPAWNP_DECAY/food_factor
var actual_prob=food_factor/(food_coefficient*(this_ant().food-1)+1)+QFSPAWNP_MIN;if(rand_choice(actual_prob))return{cell:CCW[c][3]};}
var provisional=lchk(c)
if(provisional!==null)return sigc(provisional,S_FRONT,c);return sigc(c_at(4),S_FRONT,c);}
function qdec_three_unstand(c)
{var u_sig=PUPS[c_at(c)][c_at(CCW[c][7])];if(this_ant().food>0&&u_sig===D_STALLED&&c_at(CCW[c][5])===D_MARCH&&c_at(4)===D_STALLED)
{var food_factor=QBSPAWNP_MAX-QBSPAWNP_MIN
var food_coefficient=QBSPAWNP_DECAY/food_factor
var actual_prob=food_factor/(food_coefficient*(this_ant().food-1)+1)+QBSPAWNP_MIN;if(rand_choice(actual_prob))return{cell:CCW[c][3]};}
if(u_sig===D_STALLED&&c_at(CCW[c][5])===U_READY&&c_at(4)===D_STALLED)
return sigc(U_READY,S_FRONT,c);return sigc(u_sig,S_FRONT,c);}
function qdec_three_block(c)
{var u_sig=PUPS[c_at(c)][c_at(CCW[c][1])];return sigc(u_sig,S_FRONT,c);}
function qdec_three_side(c)
{var u_sig=PUPS[c_at(CCW[c][1])][c_at(CCW[c][2])];return sigc(u_sig,S_FRONT,CCW[c][2]);}
function queen_wait()
{var c=view_corner();switch(neighbor_type(c))
{case ONE_EDGE:{if(this_ant().food>1)return{cell:CCW[c][3],type:GATHERER};}
break;case EC_LEFT:{var u_sig=PUPS[c_at(c)][c_at(CCW[c][1])];if(u_sig===D_GATHERER)return sigc(D_GATHERER,S_FRONT,c);if(u_sig===U_REALIGN&&[U_REALIGN,U_SENTINEL].includes(c_at(c)))
if([U_REALIGN,U_SENTINEL].includes(c_at(CCW[c][1])))
return eqwatch(early_queen());var provisional=lchk(c);if(provisional!==null)return sigc(provisional,S_FRONT,c);if(this_ant().food>1)
{if(c_at(CCW[c][3])!==D_MARCH)return{cell:CCW[c][3],color:D_MARCH};return{cell:CCW[c][3],type:GATHERER};}}
break;case EC_RIGHT:{var u_sig=PUPS[c_at(c)][c_at(CCW[c][7])];if(u_sig===D_GATHERER)return sigc(D_GATHERER,S_FRONT,c);if(u_sig===U_REALIGN&&[U_REALIGN,U_SENTINEL].includes(c_at(c)))
if([U_REALIGN,U_SENTINEL].includes(c_at(CCW[c][7])))
return eqwatch(early_queen());var provisional=lchk(c);if(provisional!==null)return sigc(provisional,S_FRONT,c);if(this_ant().food>1)
{if(c_at(CCW[c][5])!==D_MARCH)return{cell:CCW[c][5],color:D_MARCH};return{cell:CCW[c][5],type:GATHERER};}}
break;}
if(c_at(4)!==U_PANIC)return sigc(U_PANIC,S_SIDE,c);else return opening_queen();}
function queen_march()
{var c=view_corner();switch(neighbor_type(c))
{case EE_STRAIGHT:return qwatch(qdec_ee_straight(c));case EE_BENT:return qwatch(qdec_ee_bent(c));case EC_SKEWED:return qwatch(qdec_ec_skewed(c));case EC_SPAWN:return qwatch(qdec_ec_spawn(c));case CC_EDGED:return qwatch(qdec_cc_edged(c));case THREE_MARCH:return qwatch(qdec_three_march(c));case THREE_STAND:return qwatch(qdec_three_stand(c));case THREE_RECOVER:return qwatch(qdec_three_recover(c));case THREE_UNSTAND:return qwatch(qdec_three_unstand(c));case THREE_BLOCK:return qwatch(qdec_three_block(c));case THREE_SIDE:return qwatch(qdec_three_side(c));default:return eqwatch(early_queen());}}
function queen_decision()
{marcher_count=0;gatherer_count=0;excess_gatherers=0;for(tcell of SCAN_MOVES)
{if(is_ally(tcell))
{if(view[tcell].ant.type===MARCHER_A||view[tcell].ant.type===MARCHER_B)marcher_count++;if(view[tcell].ant.type===GATHERER)
{if(EDGES.includes(tcell)||is_gatherer_marcher(tcell))gatherer_count++;else excess_gatherers++;}}
else if(is_enemy(tcell))return opening_queen();}
if(marcher_count>0&&gatherer_count===1&&excess_gatherers===0)return qwatch(queen_march());else if(marcher_count>0&&gatherer_count===0&&excess_gatherers===0)return qwatch(queen_wait());else if(gatherer_count===1&&excess_gatherers===0)return eqwatch(early_queen());else return opening_queen();}
function main_decide()
{switch(this_ant().type)
{case QUEEN:return queen_decision();case GATHERER:return gatherer_decision();case MARCHER_A:case MARCHER_B:return marcher_decision();default:return sanitize(saboteur());}}
return main_decide();
```
## Overview
This submission aims to create a line of ants that can sweep the area. Colors are used as signals to help the queen coordinate the line, not as trailmarkers.
This submission uses three types of workers in addition to the queen:
* Type 1: Formation marcher, A phase
* Type 2: Formation marcher, B phase
* Type 3: Gatherer
* Type 4: Reserved for future use
Ants are created in a full-width diagonal line as follows:
```
A
BA
BA
BA
BA
BA
BA
QG
```
The first four ants ants created are a gatherer and a marcher, A or B with equal probability, then one of each. After that, ants are created with probability after finding food, alternating between A and B. In the formation, the queen gatherer alternates between the two phases of marching, depending on the formation marcher last created.
## Early phase
When the queen spawns, she performs a bog-standard half-lightspeed straight-line walk, trying to avoid retracing her path. Once this gets her a single piece of food, she spawns a gatherer. After gathering 3 pieces of food, for every additional piece of food, the queen has a moderate probability of spawning 3 workers in a hard-coded formation creation routine, and the line takes off.
## General behavior
Ants march in lockstep, with phase A and phase B ants alternating between stopping and moving. The phase is recognised via matching the pattern of their neighboring allies, as the ants are unable to store state. Ants always move such that they remain adjacent to at least two other ants.
When an ant is diagonally behind an obstacle, it spends its turn shooting down the appropriate signal. The signal travels instantaneously down towards the queen (thanks to all the workers being in creation order), while upwards it can only manage lightspeed. The adjacent upstream marcher recognises the signal and propogates a signal to shoot a different signal up the line.
Workers disassociated from the line (either by mistake or by a panic signal) become saboteurs, scrambling nests and attempting to obstruct enemy workers they come across. They will actively avoid the formation if they run across it, as re-incorporation is impractical.
## Food collection
When food is encountered, the line halts. However, because signals can only manage lightspeed upstream, it takes time for the signal to propogate upwards, which causes upstream to get bent into a straight line. The ants on the end prevent it from completely straightening out by bending into a hook, but they too are halted.
The worker encountering the food shoots down a food signal instead of the usual clear signal, which all downstream ants relay and heed. The next turn, the same signal is recognised upstream and translated to a realignment signal, which travels upstream and causes workers upstream to also halt as they receive the signal. The last workers at the end maintain a bend at the end to maintain proximity to other workers.
The downstream signal makes it to the queen in a single turn, which the gatherer recognises as a signal to walk the line. Following the edge of the food signal, the gatherer walks forward until it finds food, and then goes the opposite direction to return it to the queen. If there is more pending food, the food signal persists; otherwise a stalled signal now shoots down the line, signalling the queen to shoot a ready signal, which in turn signals the point of the bend to shoot down the march signal.
Once the line goes back to marching, the stalled workers resume their march as the line catches up to them. The process occurs to the ants as the signals come to them, so it is entirely practical (and does happen) that the line resumes before the realign signal reaches the end of the line, or for an upstream part of the line to halt downstream before it receives a realign signal downstream.
## Off of the line
The line is designed to survive shearing, and any contiguous line of workers longer 3, along with a queen and gatherer, in creation order, is a full-functioning marching formation. Though the line is quite reliable, it is vulnerable to obstruction by enemy workers. When this happens, the ant that is most directly in front of the enemy worker emits a panic signal. The next turn, it shears off the line and goes off on its own, followed by all upstream workers which subsequently discover the inconsistency in not having anyone at their right, and do likewise. The downstream marchers are not bothered by this event, and continue marching.
Once off of the line, workers become saboteurs. They attempt to recolor colored areas with surrounding colors to create a mess that somewhat resembles the original area but does not contain the patterns critical to nest functioning. They will actively stick around enemy workers and try to obstruct or mislead them, and will actively avoid allies to prevent them from interfering with the line. If they are not surrounded by color, they perform a straight-line half-lightspeed walk to seek new colored areas to mix up.
Sabotaging workers may end up in a formation serendipitously, but the lack of a queen anchoring the right end should mean that they break apart soon after. If it doesn't, file a bug.
## Extras
Queen looting is a work in progress. The workers will recognise enemy queens as food rather than as enemy workers, but precisely how this interacts afterwards is untested and untuned.
To prevent existing color signals from interfering with the line, workers will recolor surrounding areas white if they would send a color signal, but are already standing on the color signal they want to send. This surroundings-clearing is so powerful that a marching formation can bore through a colored nest at full speed without problems.
Queen spawning is controlled by probability. As the game goes on and the queen has more food on hand, she becomes less eager to spawn new lines and add workers to existing lines, down to a tuneable asymptotic limit probability.
## To-do
* Clean out logical cruft
* Test and refine queen looting
* See if enemy workers can be walked around
* Investigate signal state reduction
* See if intentially shearing off the end worker helps
## Release notes
1.0: First version put up for submission, initial release
1.0.1: Performed logical reductions, made compatible with more controllers
1.1: Compacted a bunch of stuff, improved logic relating to error cases
1.1.1: Hotfix to solve disqualification problem
1.2: Removed further deadlocks, saboteur now overhauled
1.3: Reduced queen spawning rate, gave saboteurs a tuneup
1.3.1: Further reduced queen spawnrate, and fixed a disqualifying bug
1.4: Parameter tuning
[Answer]
# Mandelbrant
*All of my answers contain similar low-level logic in the form of the Formic Functions Framework.*
*"HIGH-LEVEL LOGIC STARTS HERE" marks the end of the Framework's code.*
***WARNING:*** *This entry is mostly a demo of what's possible within the Formic Functions rule set. It wasn't thoroughly tested on non-empty map. Although it survived two whole games, I don't expect it to stay qualified for long.*
```
// FORMIC FRAMEWORK \\
// Version 7.0.4 \\
const QUEEN = 5;
const HERE = view[4];
const ME = HERE.ant;
const ORTHOGONALS = [1, 3, 5, 7];
const DIAGONALS = [0, 2, 6, 8];
const DIAGONALS_ORTHOGONALS = [0, 2, 6, 8, 1, 3, 5, 7];
const DIRECTIONS = [0, 1, 2, 3, 5, 6, 7, 8];
const CLOCKWISE_DIRECTIONS = [0, 1, 2, 5, 8, 7, 6, 3];
const ROTATIONS = [
[0, 1, 2,
3, 4, 5,
6, 7, 8],
[6, 3, 0,
7, 4, 1,
8, 5, 2],
[8, 7, 6,
5, 4, 3,
2, 1, 0],
[2, 5, 8,
1, 4, 7,
0, 3, 6]
];
const NEIGHBORS = [
[1, 4, 3],
[2, 5, 4, 3, 0],
[5, 4, 1],
[0, 1, 4, 7, 6],
[0, 1, 2, 5, 8, 7, 6, 3],
[8, 7, 4, 1, 2],
[3, 4, 7],
[6, 3, 4, 5, 8],
[7, 4, 5]
];
const HORIZONTAL_FLIP = [2, 1, 0, 5, 4, 3, 8, 7, 6];
const VERTICAL_FLIP = [6, 7, 8, 3, 4, 5, 0, 1, 2];
const DEBUG_MODE = false;
const log = DEBUG_MODE ? console.log : () => { };
function cells(...indices) {
return indices.map(i => view[i]);
}
function colors(...indices) {
return cells(...indices).map(c => c.color);
}
function ants(...indices) {
return cells(...indices).map(c => c.ant);
}
function isColor(color, index) {
return view[index].color === color;
}
function isAnyColor(colors, index) {
return colors.includes(view[index].color);
}
function hasFood(index) {
return view[index].food === 1;
}
function hasAnt(qualifies, index) {
const a = view[index].ant;
return a && (!(qualifies instanceof Function) || qualifies(a));
}
function hasFriend(type, index) {
return hasAnt(a => a.friend && (!type || a.type === type), index);
}
const hasAnyFriend = bind(hasFriend, null);
function bind(f, ...args) {
return f.bind(null, ...args);
}
function noTransform() {
return { revert() { }, detransformAction() { } };
}
function indexTransform(indices) {
const revertedIndices = new Array(9);
for (let i = 0; i < 9; ++i) {
revertedIndices[indices[i]] = i;
}
view = indices.map(index => view[index]);
return { revert() { view = revertedIndices.map(index => view[index]); }, detransformAction(action) { action.cell = indices[action.cell]; } };
}
const rotationTransformers = [noTransform, ...ROTATIONS.slice(1).map(r => bind(indexTransform, r))];
function bestTransformers(transformers, scorer) {
let bestScore = 0;
const bestIndices = [];
const bestTransformers = [];
for (let i = 0; i < transformers.length; ++i) {
const t = transformers[i];
const {revert} = t();
const score = scorer();
revert();
if (score > bestScore) {
bestScore = score;
bestIndices.length = 0;
bestTransformers.length = 0;
}
if (score >= bestScore) {
bestIndices.push(i);
bestTransformers.push(t);
}
}
return {score: bestScore, indices: bestIndices, transformers: bestTransformers};
}
function* withBestTransformation(transformers, scorer, continuation) {
const best = bestTransformers(transformers, scorer);
if (best.score > 0) {
const {revert, detransformAction} = best.transformers[0]();
for (const output of continuation(best)) {
if (isAction(output)) {
detransformAction(output);
}
yield output;
}
revert();
}
}
const withBestRotation = bind(withBestTransformation, rotationTransformers);
const wait = {cell: 4};
function move(index) {
return index >= 0 && index < 9 && view[index].ant === null && (view[index].food === 0 || ME.food === 0 || ME.type === QUEEN) ? { cell: index } : null;
}
function moveMany(...indices) {
return indices.map(move);
}
function paint(color, index) {
return index >= 0 && index < 9 && color >= 1 && color <= 8 && view[index].color !== color ? { cell: index, color } : null;
}
function paintMany(colors, ...indices) {
return pairMap(indices, colors, paint);
}
function spawn(type, index) {
return index >= 0 && index < 9 && view[index].ant === null && view[index].food === 0 && ME.food > 0 && ME.type === QUEEN && type >= 1 && type <= 4 ? { cell: index, type } : null;
}
function spawnMany(types, ...indices) {
return pairMap(indices, types, spawn);
}
function pairMap(mainArr, sideArr, func) {
return mainArr.map((v, i) => func(sideArr[i % sideArr.length], v));
}
function isAction(value) {
return value instanceof Object && value.cell !== undefined; // TODO: Make this more strict.
}
log('=== start logic ===');
for (const output of main()) {
if (isAction(output)) {
log('=== end logic ===');
return output;
}
}
throw 'Decision was omitted.';
function* main() {
// HIGH-LEVEL LOGIC STARTS HERE \\
// TARGET SIZE: 2^21 pixels -- SUPPORTED
// STRETCH GOAL: 2497 x 996
// MAX POSSIBLE: 2500 x 1000
// How long the painting triplet will go on for until they begin returning to the shifting station.
// This value should not exceed 997 for the painter to work in all cases, or 2497 if you don't care about being positioned vertically.
// It also shouldn't be too low. The exact lowest value is unclear, but it's likely to be in the teens.
const LENGTH = 6 * 11;
// Which function will be used for painting in the pixels.
const getPictureColorAt = mandelbrot;
function notReallyRainbow(index) {
return index % 6 + 2;
}
function fromColorString(index) {
// Input your own color string ({ a, b, c, d, e, f, g, h } => { 8, 7, 6, 4, 5, 3, 2, 1 }).
const colorString = '';
return [8, 7, 6, 4, 5, 3, 2, 1][colorString.charCodeAt(index % colorString.length) - 'a'.charCodeAt(0)];
}
function mandelbrot(index) {
const ESCAPE = 2 ** 2, MAX_I = 8 * 10 - 1;
const x0 = (index % LENGTH) / (LENGTH - 1) * 3 - 2, y0 = Math.floor(index / LENGTH) / (Math.floor(LENGTH * 2 / 3) - 1) * 2 - 1;
let x = 0, y = 0;
for (let i = 0; i < MAX_I; ++i) {
[x, y] = [x * x - y * y + x0, 2 * x * y + y0];
if (x * x + y * y > ESCAPE) {
return (i + 1) % 8 + 1;
}
}
return 8;
}
// WARNING! Beyond likely lies awful code.
// There are no more tunable parameters.
// Continue reading at your own risk.
const L1_OVERFLOW = 4096;
const FILL_ORDER_INDEX = [1, 2, 3, 6];
const FILL_ORDER_DIGIT = [0, 1, 2, 4];
function parseNumber(...indices) {
return indices.reduceRight((a, index) => (a << 3) + (index !== -1 ? view[index].color - 1 : 0), 0);
}
function colorAtDigit(n, d) {
return ((n >>> (d * 3)) & 7) + 1;
}
function paintPictureFragment(number) {
log(`initialized painter with ${number}`);
return paint(getPictureColorAt(number), 0);
}
const COPIER = 1;
const COUNTER = 2;
const MAJOR = 3;
const MINOR = 4;
function* moveWait(index) {
yield move(index);
yield wait;
}
log(`type: ${ME.type}`);
switch (ME.type) {
case COPIER: {
yield* withBestRotation(() => Math.max(hasFriend(QUEEN, 7) + hasFriend(MINOR, 3), hasFriend(QUEEN, 6) + hasFriend(MINOR, 0)) - 1, bind(moveWait, 5));
yield* withBestRotation(bind(hasFriend, COUNTER, 7), function*() {
if ([6, 3].findIndex(hasAnyFriend) === -1) {
yield paint(8, 3);
yield move(3);
}
yield wait;
});
yield* withBestRotation(bind(hasFriend, COUNTER, 8), function*() {
const targetIndex = FILL_ORDER_INDEX[view[4].color - 3];
yield paint(view[5].color, targetIndex);
yield wait;
});
yield wait;
}
case COUNTER: {
yield* withBestRotation(() => hasFriend(COPIER, 2) + hasFriend(MAJOR, 0) - 1, bind(moveWait, 5));
yield* withBestRotation(bind(hasFriend, COPIER, 1), function*() {
if (hasFriend(MAJOR, 0)) {
yield paint(view[6].color, 8);
}
yield wait;
});
yield* withBestRotation(bind(hasFriend, COPIER, 0), function*() {
if (!hasAnyFriend(6)) {
const progress = view[0].color;
if (progress === 8) {
const number = parseNumber(8, 7, 4, 1) + 1;
yield* paintMany([1, 2, 3].map(bind(colorAtDigit, number)), 3, 5, 2);
yield paint(7, 0);
} else if (progress === 7) {
const number = parseNumber(8) + 1;
yield paint(colorAtDigit(number, 0), 4);
yield paint(6, 0);
} else {
const number = parseNumber(...progress === 6 ? [4, 3] : [7, 8], 5, 2) * LENGTH;
if (progress > 2) {
if (progress === 6) {
yield* paintMany(colors(4, 3), 7, 8);
} else if (progress === 5) {
yield* paintMany([5, 6].map(bind(colorAtDigit, number)), 3, 4);
}
yield paint(colorAtDigit(number, FILL_ORDER_DIGIT[progress - 3]), 1);
if (progress !== 3) {
yield paint(progress - 1, 0);
} else {
yield paint(number + 1 === L1_OVERFLOW ? 2 : 1, 0);
}
} else {
yield paint(colorAtDigit(number, 3), 1);
yield wait;
}
}
}
});
yield wait;
}
case MAJOR: {
yield* withBestRotation(bind(hasFriend, COPIER, 5), bind(moveWait, 6));
yield* withBestRotation(() => hasFriend(QUEEN, 7) + hasFriend(MINOR, 1) - 1, bind(moveWait, 5));
yield* withBestRotation(bind(hasFriend, QUEEN, 2), bind(moveWait, 1));
yield* withBestRotation(bind(hasFriend, MINOR, 2), function*() {
const number = parseNumber(-1, -1, -1, -1, 3, 4, 5) + (isColor(2, 1) ? L1_OVERFLOW : 0);
yield* paintMany([4, 5, 6].map(bind(colorAtDigit, number)), 6, 7, 8);
yield move(7);
});
yield wait;
}
case MINOR: {
yield* withBestRotation(() => hasFriend(COPIER, 8) + hasFriend(QUEEN, 6) - hasFriend(MAJOR, 3) - 1, bind(moveWait, 7));
yield* withBestRotation(() => hasFriend(MAJOR, 6) + hasFriend(QUEEN, 7) - 1, bind(moveWait, 3));
yield* withBestRotation(() => hasFriend(MAJOR, 8) - hasFriend(QUEEN, 7), bind(moveWait, 5));
yield* withBestRotation(() => hasFriend(MAJOR, 7) + hasFriend(QUEEN, 5) - 1, bind(moveWait, 1));
yield* withBestRotation(bind(hasFriend, QUEEN, 6), function*() {
if (hasFriend(MAJOR, 3)) {
yield wait;
}
const number = parseNumber(0, 1) + 1;
yield* paintMany([0, 1].map(bind(colorAtDigit, number)), 3, 4);
yield move(7);
});
yield wait;
}
case QUEEN: {
if (DIRECTIONS.some(hasAnyFriend)) {
yield* withBestRotation(bind(hasFriend, COPIER, 5), function*() {
if (!hasFriend(COUNTER, 7)) {
yield spawn(COUNTER, 8);
}
if (!hasFriend(MAJOR, 3) && !hasFriend(MAJOR, 0)) {
yield spawn(MAJOR, 6);
}
yield spawn(MINOR, 0);
if (!hasFriend(MAJOR, 0) && hasFriend(MAJOR, 3)) {
yield move(7);
}
yield wait;
});
yield* withBestRotation(bind(hasFriend, MAJOR, 2), function*() {
if (!hasFriend(MINOR, 8)) {
yield move(1);
}
yield wait;
});
yield* withBestRotation(bind(hasFriend, MINOR, 0), function*() {
if (hasFriend(MAJOR, 3)) {
yield move(1);
yield wait;
} else if (hasFriend(MAJOR, 6)) {
yield wait;
}
});
yield* withBestRotation(bind(hasFriend, MAJOR, 7), function*() {
if (!hasFriend(COPIER, 6)) {
yield paintPictureFragment(parseNumber(1, 2, 3, 5, 6, 7, 8));
}
yield wait;
});
yield* withBestRotation(bind(hasFriend, MINOR, 5), function*() {
if (isColor(3, 4)) {
const number = parseNumber(1, 2, 3, 5) + 1;
yield* paintMany([colorAtDigit(number, 2), number + 1 === L1_OVERFLOW ? 2 : 1, colorAtDigit(number, 3)], 6, 7, 8);
yield move(7);
yield wait;
} else {
const number = parseNumber(1, 2, 3, 5, 6, 7, 8);
yield paintPictureFragment(number);
if ((number + 1) % LENGTH === 0) {
yield move(8);
yield wait;
}
yield paint(3, 4);
}
throw 'illogical failure 1';
});
throw 'illogical failure 2';
}
yield* moveMany(...DIAGONALS_ORTHOGONALS.filter(hasFood));
if (ME.food >= 4) {
yield* spawnMany([COPIER], ...ORTHOGONALS);
}
yield* moveMany(...DIAGONALS_ORTHOGONALS.filter(bind(isColor, 1)), ...DIAGONALS_ORTHOGONALS); // TODO: Watch out for accidental entrapment.
yield wait;
}
}
}
```
---
# Gallery
[![Mandelbrot full](https://i.stack.imgur.com/7c3hJ.png)](https://i.stack.imgur.com/7c3hJ.png)
[![Mandelbrot tiny](https://i.stack.imgur.com/DLBYZ.png)](https://i.stack.imgur.com/DLBYZ.png)
---
# Explanation
I will keep the explanation quite short, but keep in mind that there are a lot of nasty details that I had to figure out while making this that I won't go into.
### Phase 1
First, the queen collects 4 food to make 4 workers, each serving a different purpose. She doesn't leave any colors behind in order to minimize the chance of ruining the painting. You will see why that is shortly.
### Phase 2
After spawning the 4 workers, the core loop of the entry promptly begins. From now on I will assume a consistent view orientation, since the entry does that as well.
First a coordinated 5-ant dance is performed to achieve the correct orientation for painting. This is likely the most volatile phase, and it's probable that the entry will be disqualified because of enemy intervention here. Afterwards the ants split up.
3 ants (the queen and 2 workers) go into a painting loop. They carry a 21-bit (7 cells \* 3 bits per cell) integer in the form of colors with them, which can be used to index into any image desired. By default, this image is the Mandelbrot set. Additionally, the top-left cell is reserved for the pixel being painted, and the central cell is reserved for things that are outside the scope of this explanation. The triplet doesn't need any colors to guide them, since they figure out the orientation by finding each other. Each cycle they shift the integer by 1 cell downwards, making sure to increment it by 1 every time they do that. The loop ends when the end of the painted line is reached, which is configured by the `LENGTH` constant. At that point, a 3-ant coordinated dance begins and results in the trio ending up in an awkward returning configuration. The queen also shifts to the right one cell during the dance. They travel upwards until they meet up with the pair of ants waiting for them.
While waiting for the queen and her helpers to return, said pair of ants sets up the local color environment so that the painters can continue working after their arrival. This was the most difficult part to figure out. One ant maintains a 4-color (12-bit) integer, which it uses to provide instructions to the other ant. Those instructions describe which cell should be painted by it and to what color. This is necessary because a single ant does not have enough space in its view to store all the required information to do the coloring by itself. Before and during this process, it is also necessary for the integer maintainer to move the number 1 to the right, and also increment it 1. After the instruction relay is done, the integer maintainer fills in the cells it has access to and completes the environment setup. Hibernation begins - the pair idles, awaiting the return of the painters.
The cycle completes when the three ants return to the pair and start performing the 5-ant dance again.
---
This entry features parameters. It is currently tuned to draw a tiny Mandelbrot set. You can adjust the `LENGTH` of the picture, swap out the picture painting function or even roll your own. Have fun!
Recommended controller: [dzaima's](https://dzaima.github.io/koth-webplayer/formic.htm#).
---
# Changelog
### Version 1.0
* initial release
[Answer]
# Steamroller Ants
```
/*Ants will try to move diagonally in the following fashion:
* 2
* 51
*
*Type 1 and queen are the two core ants
*/
switch (view[4].ant.type) {
case 1: //Guiding ant
//Look for queen, try to move diagonally
if (view[7].ant && view[7].ant.friend && view[7].ant.type === 5 && !view[8].ant) return {cell: 8};
else if (view[5].ant && view[5].ant.friend && view[5].ant.type === 5 && !view[2].ant) return {cell: 2};
else if (view[3].ant && view[3].ant.friend && view[3].ant.type === 5 && !view[6].ant) return {cell: 6};
else if (view[1].ant && view[1].ant.friend && view[1].ant.type === 5 && !view[0].ant) return {cell: 0};
else return {cell: 4};
case 2: //Other wing
//Look for queen, try to move diagonally. If there is food, rotate the other way to start rotating procedure
if (view[7].ant && view[7].ant.friend && view[7].ant.type === 5 && !view[6].ant) {
if (view[6].food) {
if (!view[8].ant) return {cell: 8};
else return {cell: 4};
} else return {cell: 6};
} else if (view[5].ant && view[5].ant.friend && view[5].ant.type === 5 && !view[8].ant) {
if (view[8].food) {
if (!view[2].ant) return {cell: 2};
else return {cell: 4};
} else return {cell: 8};
} else if (view[3].ant && view[3].ant.friend && view[3].ant.type === 5 && !view[0].ant) {
if (view[0].food) {
if (!view[6].ant) return {cell: 6};
else return {cell: 4};
} else return {cell: 0};
} else if (view[1].ant && view[1].ant.friend && view[1].ant.type === 5 && !view[2].ant) {
if (view[2].food) {
if (!view[0].ant) return {cell: 0};
else return {cell: 4};
} else return {cell: 2};
} else return {cell: 4};
case 5: //Queen ant
//If forever alone
if (!view[1].ant && !view[3].ant && !view[5].ant && !view[7].ant) {
if (view[4].color === 2) { //If on colored square, try to move
if (view[0].color === 2 && !view[8].ant) return {cell: 8};
else if (view[2].color === 2 && !view[6].ant) return {cell: 6};
else if (view[6].color === 2 && !view[2].ant) return {cell: 2};
else if (view[8].color === 2 && !view[0].ant) return {cell: 0};
//Can't find color, or path is blocked? try diagonals regardless of color
else if (!view[0].ant) return {cell: 0};
else if (!view[2].ant) return {cell: 2};
else if (!view[6].ant) return {cell: 6};
else if (!view[8].ant) return {cell: 8};
//Everything else failed? Stay put.
else return {cell: 4};
} else { //If not on colored square, look for food, or set current color to 2.
if (view[4].ant.food >= 1) { //Try to make Guiding ant
if (!view[1].ant && !view[1].food) return {cell: 1, type: 1};
else if (!view[3].ant && !view[3].food) return {cell: 3, type: 1};
else if (!view[5].ant && !view[5].food) return {cell: 5, type: 1};
else if (!view[7].ant && !view[7].food) return {cell: 7, type: 1};
}
for (var i = 0; i < 9; i++) { //Look for food
if (view[i].food) return {cell: i};
}
return {cell: 4, color:2};
}
} else { //Queen has partner
//Make other wing
if (view[4].ant.food >= 1) {
if (view[1].ant && view[1].ant.friend && view[1].ant.type === 1 && !view[3].ant && !view[3].food && !view[5].ant) return {cell: 3, type: 2};
else if (view[3].ant && view[3].ant.friend && view[3].ant.type === 1 && !view[7].ant && !view[7].food && !view[1].ant) return {cell: 7, type: 2};
else if (view[5].ant && view[5].ant.friend && view[5].ant.type === 1 && !view[1].ant && !view[1].food && !view[7].ant) return {cell: 1, type: 2};
else if (view[7].ant && view[7].ant.friend && view[7].ant.type === 1 && !view[5].ant && !view[5].food && !view[3].ant) return {cell: 5, type: 2};
}
//If food is orthogonal to Queen, stay put
if (view[1].food || view[3].food || view[5].food || view[7].food) return {cell: 4};
//Look for guiding type 1 ant, try to move diagonally
else if (view[7].ant && view[7].ant.friend && view[7].ant.type === 1 && !view[6].ant) return {cell: 6};
else if (view[5].ant && view[5].ant.friend && view[5].ant.type === 1 && !view[8].ant) return {cell: 8};
else if (view[3].ant && view[3].ant.friend && view[3].ant.type === 1 && !view[0].ant) return {cell: 0};
else if (view[1].ant && view[1].ant.friend && view[1].ant.type === 1 && !view[2].ant) return {cell: 2};
}
default: return {cell: 4};
}
```
These ants work off of a similar concept as Dave's [Forensic Ants](https://codegolf.stackexchange.com/a/135108/52152). However, they move diagonally, and moves in groups of 3.
## Phase 1: Food scramble
The Queen ant just moves diagonally until it can see a single piece of food. It does this using a similar concept to the [Romanesco Road](https://codegolf.stackexchange.com/a/135104/52152), where the color trail laid behind the Queen can help it figure out which way is forward.
## Phase 2: 2 ants
The Queen makes a new type 1 "guiding" ant, which partners with the Queen to move diagonally together. They each figure out which way is forward relative to their respective partners.
## Phase 3: Steamrolling
Once the Queen and her partner find a piece of food, the queen uses it to make a type 2 ant. This ant has specific instructions to follow the Queen, and also tags along. This makes a 3 wide diagonally moving row of ants, making it quite fast at getting food.
## Rotating
If the type 2 ant sees that it will move into some food, it instead will move in the other direction, where the type 1 ant used to be. This means that all the ants will have rotated the direction they move in, and so the ants should have a very low probability of wrapping back to their starting point.
Note: if for some reason (maybe a collision with another ant?) the type 2 ant was born before the type 1 ant, then this rotation would result in the type 2 ant trying to move onto the type 1 ant. To resolve this, the type 2 ant would instead leave itself behind, and let the Queen make another type 2 ant.
[Answer]
# Medusa
```
function clean(move) {
if (move["color"] == undefined) {
if (view[move["cell"]].ant != null) {
move = {
cell: 4
}
}
if (move["type"] == undefined) {
if (view[4].ant.type == 5 && move["cell"] != 4 && view[move["cell"]].color > 2) {
move["color"] = 1
}
if (view[move["cell"]].food == 1 && view[4].ant.type < 5 && view[4].ant.food > 0) {
move = {
cell: 4
}
}
} else if (view[4].ant.type != 5 || view[4].ant.food == 0 || view[move["cell"]].food != 0) {
move = {
cell: 4
}
}
}
return move
}
function coord(cell) {
var x = (cell % 3) - 1
var y = 1 - (cell - (cell % 3)) / 3
return {
x: x,
y: y
}
}
function getcell(x, y) {
return (x + 1) + (1 - y) * 3
}
var diags = [0, 2, 8, 6]
var colorcounts = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for (var i = 0; i < 9; i++) {
colorcounts[view[i].color]++
}
var queen = -1
for (var i = 0; i < 9; i++) {
if (view[i].ant != null && view[i].ant.friend == true && view[i].ant.type == 5) {
queen = i
}
}
var guard = -1
for (var i = 0; i < 9; i++) {
if (view[i].ant != null && view[i].ant.friend == true && view[i].ant.type == 1) {
guard = i
}
}
var forager = -1
for (var i = 0; i < 9; i++) {
if (view[i].ant != null && view[i].ant.friend == true && view[i].ant.type == 2) {
forager = i
}
}
var black = -1
for (var i = 0; i < 9; i++) {
if (view[i].color == 8) {
black = i
}
}
var yellow = -1
for (var i = 0; i < 9; i++) {
if (view[i].color == 2) {
yellow = i
}
}
if (view[4].ant.type == 5) {
if (forager >= 0 && view[forager].color == 8) {
return clean({
cell: forager,
color: 2
})
}
if (guard == -1) {
if (view[4].color == 3) {
if (view[4].ant.food > 1) {
return clean({
cell: 0,
type: 2
})
}
return clean({
cell: 0,
type: 1
})
}
if (view[4].ant.food >= 3) {
return clean({
cell: 4,
color: 3
})
}
if (view[4].color == 1) {
return clean({
cell: 4,
color: 2
})
}
for (var i = 0; i < 9; i++) {
if (view[i].food == 1) {
return clean({
cell: i
})
}
}
for (var i = 0; i < 4; i++) {
if (view[diags[i]].color != 2 && view[diags[(i + 2) % 4]].color == 2) {
return clean({
cell: diags[i]
})
}
}
return clean({
cell: 0
})
}
var state = 3
var max = 0
for (var i = 3; i <= 4; i++) {
if (colorcounts[i] > max) {
max = colorcounts[i]
state = i
}
}
if (state == 3) {
if (black >= 0 && forager == -1) {
return clean({
cell: black,
type: 2
})
}
if (forager >= 0 && view[forager].color != 2) {
return clean({
cell: 0,
color: 8
})
}
if (colorcounts[3] == 9) {
return clean({
cell: 4,
color: 4
})
}
}
if (state == 4) {
if (colorcounts[4] == 9) {
return clean({
cell: 4,
color: 3
})
}
}
return clean({
cell: 4
})
}
if (view[4].ant.type == 1) {
var dest = 0
var destmap = [1, 0, 1, 1, 4, 1, 7, 8, 7]
dest = destmap[queen]
if (view[queen].color != view[dest].color && (view[queen].color == view[4].color || view[4].color == view[dest].color)) {
if (queen < 4 && view[dest].color > 2 && view[dest].color < 5) {
return clean({
cell: queen,
color: view[dest].color
})
}
return clean({
cell: dest,
color: view[queen].color
})
}
return clean({
cell: dest
})
}
if (view[4].ant.type == 2) {
if (queen >= 0 && view[4].color == 8) {
return clean({
cell: 4
})
}
var state = 3
var max = 0
for (var i = 5; i <= 7; i++) {
if (colorcounts[i] > max) {
max = colorcounts[i]
state = i
}
}
var flowx = 0
var flowy = 0
for (var i = 0; i < 9; i++) {
for (var j = i + 1; j < 9; j++) {
var loci = coord(i)
var locj = coord(j)
var dx = locj.x - loci.x
var dy = locj.y - loci.y
var cyc = 0
if (view[i].color >= 5 && view[i].color <= 7 && view[j].color >= 5 && view[j].color <= 7) {
var cyc = ((view[j].color - view[i].color) % 3 + 3) % 3
if (cyc == 2) {
cyc = -1
}
} else if (view[i].color >= 5 && view[i].color <= 7) {
cyc = 0.1
} else {
cyc = -0.1
}
flowx += cyc * dx / (dx * dx + dy * dy)
flowy += cyc * dy / (dx * dx + dy * dy)
}
}
if (flowx * flowx > flowy * flowy) {
flowy = 0
} else {
flowx = 0
}
if (flowx < 0) {
flowx = -1
}
if (flowy < 0) {
flowy = -1
}
if (flowx > 0) {
flowx = 1
}
if (flowy > 0) {
flowy = 1
}
if (queen >= 0) {
var locq = coord(queen)
flowx = -locq.x
flowy = -locq.y
state = 5
}
if (view[4].ant.food > 0) {
if (guard >= 0) {
var destmap = [1, 0, 1, 1, 4, 1, 7, 8, 7]
return clean({
cell: destmap[guard]
})
}
dest = getcell(-flowx, -flowy)
if (dest != 7) {
dest = 1
}
if (view[dest].color >= 5 && view[dest].color <= 7) {
return clean({
cell: dest
})
}
if (view[dest - 1].color >= 5 && view[dest - 1].color <= 7) {
return clean({
cell: dest - 1
})
}
return clean({
cell: 4
})
}
if (view[4].color >= 5 && view[4].color <= 7) {
state = view[4].color
}
var nextc = ((state - 4) % 3 + 5)
var prevc = ((state - 3) % 3 + 5)
var centerdest
centerdest = getcell(flowx, flowy)
if (view[centerdest].color != state && view[centerdest].color != nextc) {
return clean({
cell: centerdest,
color: nextc
})
}
for (var dest = 1; dest < 9; dest++) {
var locd = coord(dest)
var net = locd.x * flowx + locd.y * flowy
if (net > 0 && view[dest].color != view[centerdest].color) {
return clean({
cell: dest,
color: view[centerdest].color
})
}
}
for (var dest = 0; dest < 9; dest++) {
if (view[dest].food == 1) {
if (view[dest].color >= 5 && view[dest].color <= 7) {
return clean({
cell: dest
})
}
return clean({
cell: dest,
color: state
})
}
}
if (centerdest == 4 && view[0].color >= 5 && view[0].color <= 7) {
return clean({
cell: 0
})
}
if (centerdest > 0 && view[centerdest - 1].color >= 5 && view[centerdest - 1].color <= 7) {
return clean({
cell: centerdest - 1
})
}
return clean({
cell: centerdest
})
}
```
This bot... isn't good, but it uses several cool strategies that I think will be included in my future ant bots. Its name comes from the shape the colony makes on the game board.
[![Medusa in action](https://i.stack.imgur.com/9KKNn.png)](https://i.stack.imgur.com/9KKNn.png)
# Phase 1: Initial Investment
The queen moves straight diagonally until it picks up 3 pieces of food, enough to start a colony. Once it accumulates those pieces, it settles down (becomes a stationary queen) and then makes 2 foragers and 1 guard. As an interesting part of strategy, the presence of the guard ant itself is what triggers the next phase, and is what prevents the queen from ever become mobile again.
# Phase 2: Colonize
Here, the three types of ants play different roles:
**Queen**
The queen slowly oscillates between two states, with the assistance of the guard. The current state is what determines whether or not a newly acquired piece of food is turned into a worker, so roughly 50% of food is re-invested in the colony. The entire 3x3 area containing the queen is used to store state, so that any erasure can be undone and the state recovered.
**Guard**
The guard lives his whole life adjacent to the queen, circling it randomly.
The guard plays a key role in maintaining the queen's state. It attempts to correct any errors in the queen's 3x3 area. When there are two valid alternative colors in the area, which of the two colors becomes the "corrected" state is relatively random. Once a consensus is reached, however, the queen flips her square to the opposite color, re-initiating the process. This is what causes the oscillation of the queen's state, and it is done in a very error-resistant way.
The guard also serves as a gatekeeper the the queen's "palace". When a forager sees the guard, it is able to move next to the queen even though the queen is out of visual range.
**Foragers**
The foragers lays out a cyclic red-green-blue pattern as they leave the colony, and follow it backwards when they are carrying food. They end up painting quite a considerable area, because really *wide* paths are necessary to ensure that the paths do not become too tangled and that they can find their way back even if some cells are damaged.
Typical path of a forager:
[![Forager path](https://i.stack.imgur.com/qC30P.png)](https://i.stack.imgur.com/qC30P.png)
Notice how it usually travels in a straight line but occasionally turns 90 degrees. This is a result of the way it randomly walks within its own path as it is laying it down.
[Answer]
# Brownian Jig
This player produces no workers, and the queen moves randomly. The random motion is because the queen returns the same direction each time, but the input visible cells are presented at a random orientation each move, preventing the movement being in a straight line.
The first code block in an answer is the one automatically included in the game:
```
// Full version that won't be disqualified for moving onto another ant
// Move to food if visible
for (var i=0; i<9; i+=1) {
if (view[i].food) {
return {cell:i}
}
}
// Otherwise move to one of the diagonal cells if not occupied
for (var i=0; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i}
}
}
// Otherwise one of the vertical or horizontal cells if not occupied
for (var i=1; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i}
}
}
// Otherwise don't move at all
return {cell:4}
```
Here is a simpler version that doesn't check for other ants, but has identical behaviour up until the point it gets disqualified for trying to step onto another ant:
```
// Basic version for an intuitive understanding
// Move to food if visible
for (var i=0; i<9; i+=1) {
if (view[i].food) {
return {cell:i}
}
}
// Otherwise move "up and left", which will be a random direction
return {cell:0}
```
This second code block won't be picked up by the game - this means you can include additional code blocks as part of your answer's explanation. Just make sure the code block that you wish to compete in the game is the first one in the answer.
For an example of producing straight line movement despite the random orientation of the input, see [Romanesco Road](https://codegolf.stackexchange.com/a/135104/20283).
[Answer]
# La Reine Bleue
```
var Queen = 5;
var QueenTrail = [];
var EnemyAnts = [];
var EnemyColors = [];
var QueenTrailColor = 7;
var QueenTrailColor2 = 8;
var QueensPosition = -1; //Future use...
var rotations =
[ 0,1,2,
3,4,5,
6,7,8,
6,3,0,
7,4,1,
8,5,2,
8,7,6,
5,4,3,
2,1,0,
2,5,8,
1,4,7,
0,3,6];
var moves = [];
getMoves();
return findBestMove();
function getMoves()
{
var matchIdx = -1;
//Initialization of current state
for(ii = 0; ii < 9; ii++)
{
if(ii != 4)
{
if(view[ii].color == QueenTrailColor)
{
QueenTrail.push(ii);
}
else if(view[ii].color == QueenTrailColor2)
{
QueenTrail.push(ii);
}
else if(view[ii].color != 1)
{
EnemyColors.push(ii);
}
}
if(ii != 4 && view[ii].ant != null)
{
if(view[ii].ant.friend)
{
if(view[ii].ant.type == Queen)
{
QueensPosition = ii * ii;
}
}
else
{
EnemyAnts.push(ii);
}
}
}
switch (view[4].ant.type)
{
case Queen:
{
//first get the food
for (var ii = 0; ii < 9; ii++)
{
if (view[ii].food > 0 && view[ii].ant == null)
{
moves.push(getCell(ii)) ;
}
}
if(EnemyAnts.length == 0)
{
lm(AA(-QueenTrailColor),AA(4), {cell:4, color:QueenTrailColor});
}
if(QueenTrail.length >= 5 || EnemyAnts.length > 0)
{
lm(AA(-QueenTrailColor), AA(0,1,2),{cell:0});
lm(AA(-QueenTrailColor), AA(0,1,3),{cell:0});
lm(AA(-QueenTrailColor), AA(0,1,5),{cell:0});
lm(AA(-QueenTrailColor), AA(0,1,6),{cell:0});
lm(AA(-QueenTrailColor), AA(0,1,7),{cell:0});
lm(AA(-QueenTrailColor), AA(0,1,8),{cell:0});
lm(AA(-QueenTrailColor), AA(0,2,3),{cell:0});
lm(AA(-QueenTrailColor), AA(0,2,6),{cell:0});
lm(AA(-QueenTrailColor), AA(0,2,7),{cell:0});
lm(AA(-QueenTrailColor), AA(0,3,7),{cell:0});
lm(AA(-QueenTrailColor), AA(0,3,8),{cell:0});
lm(AA(-QueenTrailColor), AA(0,5,7),{cell:0});
lm(AA(-QueenTrailColor), AA(1,2,7),{cell:1});
lm(AA(-QueenTrailColor), AA(1,3,5),{cell:1});
lm(AA(-QueenTrailColor), AA(0,1),{cell:0});
lm(AA(-QueenTrailColor), AA(0,2),{cell:0});
lm(AA(-QueenTrailColor), AA(0,3),{cell:0});
lm(AA(-QueenTrailColor), AA(0,5),{cell:0});
lm(AA(-QueenTrailColor), AA(0,7),{cell:0});
lm(AA(-QueenTrailColor), AA(0,8),{cell:0});
lm(AA(-QueenTrailColor), AA(1,3),{cell:1});
lm(AA(-QueenTrailColor), AA(1,7),{cell:1});
}
if(QueenTrail.length == 4)
{
lmQT(AA(0,1,2,3),{cell:7});
lmQT(AA(0,1,2,5),{cell:7});
lmQT(AA(0,1,2,6),{cell:7});
lmQT(AA(0,1,2,7),{cell:5});
lmQT(AA(0,1,2,8),{cell:7});
lmQT(AA(0,1,3,5),{cell:7});
lmQT(AA(0,1,3,7),{cell:8});
lmQT(AA(0,1,3,8),{cell:2});
lmQT(AA(0,1,5,6),{cell:8});
lmQT(AA(0,1,5,7),{cell:6});
lmQT(AA(0,1,5,8),{cell:3});
lmQT(AA(0,1,6,7),{cell:8});
lmQT(AA(0,1,6,8),{cell:2});
lmQT(AA(0,1,7,8),{cell:2});
lmQT(AA(0,2,3,7),{cell:8});
lmQT(AA(0,2,3,8),{cell:6});
lmQT(AA(0,2,6,8),{cell:1});
lmQT(AA(0,3,5,7),{cell:2});
lmQT(AA(0,3,5,8),{cell:2});
lmQT(AA(1,3,5,7),{cell:0});
}
if(QueenTrail.length == 1)
{
lmQT(AA(0), {cell:8});
lmQT(AA(1), {cell:7});
}
else if(QueenTrail.length == 0)
{
moves.push(getCell(1));
}
if(QueenTrail.length == 0) // starting out or someone is messing with us
{
moves.push( getCellColor(1, QueenTrailColor));
}
else if (QueenTrail.length >= 5) //queen is stuck? move her randomly until we get a straight trail
{
moves.push( getCellColor(1, QueenTrailColor2));
}
else if (QueenTrail.length >= 3)
{
lmQT(AA(0,1,2),{cell:3});
lmQT(AA(0,1,3),{cell:7});
lmQT(AA(0,1,5),{cell:3});
lmQT(AA(0,1,6),{cell:7});
lmQT(AA(0,1,7),{cell:3});
lmQT(AA(0,1,8),{cell:3});
lmQT(AA(0,2,3),{cell:6});
lmQT(AA(0,2,6),{cell:3});
lmQT(AA(0,2,7),{cell:1});
lmQT(AA(0,3,7),{cell:8});
lmQT(AA(0,3,8),{cell:5});
lmQT(AA(0,5,7),{cell:6});
lmQT(AA(1,2,7),{cell:0});
lmQT(AA(1,3,5),{cell:6});
}
else if(QueenTrail.length == 2)
{
lmQT(AA(0,1),{cell:7});
lmQT(AA(0,2),getCellColor(1, QueenTrailColor));
lmQT(AA(0,3),{cell:6});
lmQT(AA(0,5),{cell:1});
lmQT(AA(0,7),{cell:3});
lmQT(AA(0,8),{cell:3});
lmQT(AA(1,3),{cell:6});
lmQT(AA(1,7),{cell:0});
}
else if(QueenTrail.length == 1) //we are either going in a straight line or trapped?
{
if(view[4].ant.food > 0)
{
lmQT(AA(0), getCell(0));
//clear out the area for the ants
if(EnemyColors.length > 0)
{
moves.push( getCellColor(EnemyColors[0],1));
}
}
lmQT(AA(0), getCell(8));
lmQT(AA(1), getCell(7));
lmQT(AA(2), getCell(6));
}
break;
}
}
moves.push( getCell(4));
}
function leftOfPos(x)
{
if (x == 0)
{
return 3;
}
else if (x == 1)
{
return 0;
}
else if (x == 2)
{
return 1;
}
else if (x == 3)
{
return 6;
}
else if (x == 5)
{
return 2;
}
else if (x == 6)
{
return 7;
}
else if (x == 7)
{
return 8;
}
else if (x == 8)
{
return 5;
}
}
function findBestMove()
{
var keeper = 0;
for(var ii = 0; ii < moves.length ; ii++)
{
if(moves[ii].cell < 0 || moves[ii].cell > 8 || (moves[ii].cell != 4 && (moves[ii].color == null || moves[ii].color == 0) && view[moves[ii].cell].ant != null) || (view[moves[ii].cell].food > 0 && (view[4].ant.food > 0 && view[4].ant.type < 5)))
{
continue;
}
else if(moves[ii].type != null && (view[moves[ii].cell].ant != null || view[moves[ii].cell].food > 0 || view[0].color == 1)) //semi random here.
{
continue;
}
else
{
keeper = ii;
break;
}
}
return moves[keeper];
}
function lm(matchingColors, coords, matchCell)
{
var matchTarget = coords.length ;
var matchCount = [0,0,0,0];
var returnVal = -1;
for(var ii = 0; ii < coords.length; ii++)
{
for(var jj = 0; jj < 4; jj++)
{
var actualIndex = rotations[coords[ii] + (jj * 9)];
var foundMatch = false;
for(var kk = 0; kk < matchingColors.length; kk++)
{
var matchingColor = matchingColors[kk];
if(matchingColor >= 1 && matchingColor <= 8 && view[actualIndex].color == matchingColor)
{
foundMatch = true;
break;
}
else if(matchingColor < 0 && view[actualIndex].color != -matchingColor)
{
foundMatch = true;
break;
}
}
if(foundMatch)
{
matchCount[jj] = matchCount[jj] + 1;
if(matchCount[jj] == matchTarget)
{
matchCell.cell = rotations[matchCell.cell + (jj * 9)];
moves.push(matchCell);
returnVal = jj;
}
}
}
}
return returnVal;
}
function lmQT(coords, matchCell)
{
return lm(AA(QueenTrailColor, QueenTrailColor2), coords,matchCell);
}
function AA()
{
return arguments;
}
function getCell(x)
{
return {cell:x};
}
function getCellColor(x, y)
{
return {cell:x, color:y};
}
```
The blue queen will leave a blue trail, she avoids black and leaves black crumbs if 'stuck'.
She looks for specific blue/black "shapes" using all 4 rotations and creates a list of potential moves. Disqualifying moves are removed and a single result is chosen. The Queen is somewhat predictable but certain shapes will cause a randomness. She will mostly change directions after finding food due to the fact that the orientation will change which moves are discovered first.
[Answer]
# FireFlyMkII
*Note that until my entry is complete, this code will be ugly as it is trans-compiled from my master development source which is being performed in java.*
```
// maps current view's cells' indecies to the rotated cell's location's indecies for each direction
var rotate =
[[0,1,2,3,4,5,6,7,8],
[2,5,8,1,4,7,0,3,6],
[8,7,6,5,4,3,2,1,0],
[6,3,0,7,4,1,8,5,2]];
// the colours that form the pattern of the trail back to the queen
var TRAIL_COLOR_A = 8;
var TRAIL_COLOR_B = 2;
var TRAIL_COLOR_C = 5;
var trailColours = [TRAIL_COLOR_A,TRAIL_COLOR_B,TRAIL_COLOR_C];
var trailColoursLookUp = [-1,-1,1,-1,-1,2,-1,-1,0];
var ORIENTATION_MARKER = 8;
// Queens Modes
var QUEEN_MODE_HUNTING_MOVING = 6;
var QUEEN_MODE_HUNTING_PAINTING = 1;
var QUEEN_MODE_RESETTING = 5;
var QUEEN_MODE_RESETTING_SPAWNING = 3;
var QUEEN_MODE_COUNTING_EVEN = 7;
var QUEEN_MODE_COUNTING_ODD = 4;
var QUEEN_MODE_NESTING = 2;
// the number of non-blank (i.e. not colour 1 ) colours to used to encode the queen's worker spawn counter. Min of 1. Max of 7
var SPAWN_COUNTER_NON_BLANK_COLOURS_COUNT = 7;
// the maximum number that can be encoded using the queen's worker spawn counter
var SPAWN_COUNTER_MAX = SPAWN_COUNTER_NON_BLANK_COLOURS_COUNT*SPAWN_COUNTER_NON_BLANK_COLOURS_COUNT*SPAWN_COUNTER_NON_BLANK_COLOURS_COUNT -1;//SPAWN_COUNTER_NON_BLANK_COLOURS_COUNT * SPAWN_COUNTER_USED_CELLS_COUNT_MAX;
// the minimum game ticks between spawning a worker. Min of 0, Max of SPAWN_COUNTER_MAX
var TICKS_BETWEEN_FOOD_RETURN_MAX = 50;
// No Operation... i.e. stay put do nothing
var NO_OP = {cell:4};
var ANT_TYPE_WORKER = 1;
var ANT_TYPE_QUEEN = 5;
var orientationMarkerRotation = -1;
var i=0;
var j=0;
// returns true of the provided colour is a trail colour
function isTrailColour(colour)
{
return colour === trailColours[0] || colour === trailColours[1] || colour === trailColours[2];
}
// returns the colour of the colour in the trail away from queen
function nextTrailColor(currentTrailColour)
{
return trailColours[(trailColoursLookUp[currentTrailColour]+1)%3];
}
// returns the colour of the colour in the trail toward from queen
function prevTrailColor(currentTrailColour)
{
return trailColours[(3+trailColoursLookUp[currentTrailColour]-1)%3];
}
// RNG
function randomNumberGenerator(seed)
{
return (1103515245 * seed + 12345) % 2147483647;
}
// returns a positive random integer based on the provided ant's view and seed
function randomInt(view,seed)
{
for (var i=0;i<9;i++)
{
if (view[i].ant !=null)
{
seed=randomNumberGenerator(seed+view[i].ant.food);
seed=randomNumberGenerator(seed+view[i].ant.type);
seed=randomNumberGenerator(seed+(view[i].ant.friend?1:0));
}
seed=randomNumberGenerator(seed+view[i].color);
seed=randomNumberGenerator(seed+view[i].food);
}
return seed<0?-seed:seed;
}
// SHUFFLE *NOT* IMPLEMENTED
function shuffleIndecies(view,seed,range)
{
var indecies = new Array(range);
for (var i=0;i<range;i++)
{
indecies[i]=i;
}
return indecies;
}
function processOrientation(view)
{
// count orientation markers
var orientationMarkerCount = 0;
for (var i=0; i<rotate.length;i++)
{
if (view[rotate[i][1]].color === ORIENTATION_MARKER)
{
orientationMarkerCount++;
orientationMarkerRotation = i;
}
}
// corruption detected
if (orientationMarkerCount >1)
{
return {cell:4, color: QUEEN_MODE_RESETTING};
}
// place the orientation marker
if (orientationMarkerCount === 0)
{
return {cell:1, color: ORIENTATION_MARKER};
}
return null;
}
function incrementSpawnCounter(view)
{
var action = processOrientation(view);
if (action != null)
{
return action;
}
var newCount = decodeThreeCellsToInt(view) + 1;
var MSD = view[rotate[orientationMarkerRotation][3]].color-1;
var NSD = view[rotate[orientationMarkerRotation][7]].color-1;
var LSD = view[rotate[orientationMarkerRotation][5]].color-1;
var MSDisEven =(MSD & 1) ===0;
var NSDisEven =(NSD & 1) ===0;
var MSDdelta = Math.floor(newCount / 49) - MSD;
var NSDdelta = (MSDisEven ? Math.floor(Math.floor(newCount%49)/7) :( 6 - Math.floor(Math.floor(newCount%49)/7))) - NSD;
var LSDdelta = (((MSDisEven && NSDisEven) || (!MSDisEven && !NSDisEven)) ? Math.floor(newCount%7) :( 6 - Math.floor(newCount%7))) - LSD;
// check for roll over
if (MSDdelta > 6)
{
return {cell:rotate[orientationMarkerRotation][3], color:1};
}
// Most Significant Digit (cell) update
if (MSDdelta != 0)
{
return {cell:rotate[orientationMarkerRotation][3], color:(MSD+MSDdelta)+1};
}
// Next Significant Digit (cell) update
if (NSDdelta != 0)
{
return {cell:rotate[orientationMarkerRotation][7], color:(NSD+NSDdelta)+1};
}
// Least Significant Digit (cell) update
if (LSDdelta != 0)
{
return {cell:rotate[orientationMarkerRotation][5], color:(LSD+LSDdelta)+1};
}
return null;
}
function decodeThreeCellsToInt(view)
{
var MSD = view[rotate[orientationMarkerRotation][3]].color-1;
var NSD = view[rotate[orientationMarkerRotation][7]].color-1;
var LSD = view[rotate[orientationMarkerRotation][5]].color-1;
var MSDisEven =(MSD & 1) ===0;
var NSDisEven =(NSD & 1) ===0;
return MSD * 49 +
(MSDisEven?NSD:6-NSD) * 7 +
((MSDisEven && NSDisEven) || (!MSDisEven && !NSDisEven)?LSD:6-LSD);
}
// Performs a paint command to reset the queen's worker spawn counter to 0.
// NOTE that is may take multiple calls on sequential game ticks to complete the reset.
// returns null if the counter is reset
function resetSpawnCounter(view)
{
var orientationMarkerCount = 0;
for (i=1; i<9; i+=2)
{
if (view[i].color === ORIENTATION_MARKER && orientationMarkerCount ===0)
{
orientationMarkerCount++;
}
else if (view[i].color!=1)
{
return {cell:i, color:1};
}
}
// place the orientation marker
if (orientationMarkerCount === 0)
{
return {cell:1, color: ORIENTATION_MARKER};
}
return null;
}
function spawnNewWorker(view,type,defaultAction)
{
// ensure that we do not try and create a worker when having no food
if (view[4].ant.food > 0)
{
// now try to spawn an ant
if (view[1].ant===null && view[1].food===0)
{
return {cell:1, type:type};
}
// previous spawn cell was blocked, try another
if (view[3].ant===null && view[3].food===0)
{
return {cell:3, type:type};
}
// previous spawn cell was blocked, try another
if (view[5].ant===null && view[5].food===0)
{
return {cell:5, type:type};
}
// previous spawn cell was blocked, try another
if (view[7].ant===null && view[7].food===0)
{
return {cell:7, type:type};
}
}
return defaultAction;
}
function isCellTrailToQueen(cell,currentAntCellColour)
{
// is cell containing our queen, or is the cell the next cell colour on the trail back
return (cell.ant!=null && cell.ant.friend && cell.ant.type === ANT_TYPE_QUEEN) ||
cell.color === prevTrailColor(currentAntCellColour);
}
// entry point into ant logic
function getAction(view)
{
var random = 1;
var food = view[4].ant.food;
var currentCellColour = view[4].color;
/////////////////////////////////////// QUEEN ///////////////////////////////////////
if (view[4].ant.type === ANT_TYPE_QUEEN)
{
// move to visible food. this queen is greedy!
for (i=0; i<9; i++)
{
if (view[i].food>0) {
return {cell:i};
}
}
// see if we have spawned a worker in the last few turns
var workerSpawned = false;
// look in orthogonal cells
for (i=1; i<9; i+=2)
{
// ant detected and is friendly and of worker type
if (view[i].ant !=null && view[i].ant.friend && view[i].ant.type===ANT_TYPE_WORKER)
{
workerSpawned=true;
break;
}
}
var queenMode = currentCellColour;
var foodModRemainder=1;
var minFoodLatch = 0;
if (food>=500) minFoodLatch = 500;
else if (food>=400) minFoodLatch = 400;
else if (food>=300) minFoodLatch = 300;
else if (food>=200) minFoodLatch = 200;
else if (food>=100) minFoodLatch = 100;
else if (food>=50) minFoodLatch = 50;
else if (food>=20) minFoodLatch = 30;
else if (food>=20) minFoodLatch = 20;
else if (food>=10) minFoodLatch = 10;
else if (food>=5) minFoodLatch = 5;
switch (queenMode)
{
case QUEEN_MODE_HUNTING_MOVING:
{
// move to the cell mirror of the trail cell
for (i=0; i<9; i++) {
if (view[i].ant===null && view[i].color===QUEEN_MODE_HUNTING_MOVING) {
if (view[8-i].ant==null)
{
return {cell:8-i};
}
}
}
// Otherwise move to one of the diagonal cells if not occupied
for (i=0; i<9; i+=2)
{
if (view[i].ant===null)
{
return {cell:i};
}
}
// Otherwise move to one of the vertical or horizontal cells if not occupied
for (i=1; i<9; i+=2)
{
if (view[i].ant===null)
{
return {cell:i};
}
}
return {cell:4};
}
case QUEEN_MODE_HUNTING_PAINTING:
{
// no food found, change to move mode
if (food ===0)
{
// Queenie places a trail
return {cell:4, color:QUEEN_MODE_HUNTING_MOVING};
}
// found food, now change to nesting mode
else
{
return {cell:4, color:QUEEN_MODE_NESTING};
}
}
// initialise colony
case QUEEN_MODE_NESTING:
{
// we have spawned a worker so change to counting mode
if (workerSpawned===true)
{
return {cell:4, color:QUEEN_MODE_COUNTING_ODD};
}
var action = processOrientation(view);
if (action != null)
{
return action;
}
// ensure that we have the initial band constructed around the queen
for (i=0; i<9; i+=2)
{
if (i!=4 && view[i].color!=TRAIL_COLOR_A)
{
return {cell:i, color:TRAIL_COLOR_A};
}
}
// ensure that the counter cells are reset.
action = resetSpawnCounter(view);
if (action != null)
{
return action;
}
// spawn initial worker
return spawnNewWorker(view, ANT_TYPE_WORKER, NO_OP);
}
case QUEEN_MODE_RESETTING_SPAWNING:
// spawn the worker if we have not spawned a worker in the last few turns
if (!workerSpawned===true)
{
return spawnNewWorker(view, ANT_TYPE_WORKER, NO_OP);
}
// must have spawned a worker previously, so reset the counter
var action = resetSpawnCounter(view);
// still in process of resetting counter...
if (action != null)
{
return action;
}
// spawn counter as been reset. We will set the queen back to counting mode;
return {cell:4, color:food%2===0?QUEEN_MODE_COUNTING_EVEN:QUEEN_MODE_COUNTING_ODD};
case QUEEN_MODE_RESETTING:
action = resetSpawnCounter(view);
// still in process of resetting counter...
if (action != null)
{
return action;
}
// spawn counter as been reset. We will set the queen back to counting mode;
return {cell:4, color:food%2===0?QUEEN_MODE_COUNTING_ODD:QUEEN_MODE_COUNTING_EVEN};
case QUEEN_MODE_COUNTING_ODD:
foodModRemainder = 2;
case QUEEN_MODE_COUNTING_EVEN:
{
foodModRemainder--;
action = processOrientation(view);
if (action != null)
{
return action;
}
var spawnCounter = decodeThreeCellsToInt(view);
// repair any damage to the initial band constructed around the queen
for (i=0; i<9; i+=2)
{
if (i!=4 && view[i].color!=TRAIL_COLOR_A)
{
return {cell:i, color:TRAIL_COLOR_A};
}
}
// // spawn interval time threshold as been reached and we have food to convert into workers...
// if (spawnCounter>=TICKS_BETWEEN_FOOD_RETURN_MAX && food>minFoodLatch)
// {
// // change to reset spawn counter mode to spawn a new worker
// return new Paint(4,QUEEN_MODE_RESETTING_SPAWNING);
// }
//
// // Check to see if a worker has just returned some food.
// if (food>0 && food%2 == foodModRemainder)
// {
// // change to reset spawn counter mode
// return new Paint(4,QUEEN_MODE_RESETTING);
// }
// Check to see if a worker has just returned some food.
if (food>0 && food%2 === foodModRemainder)
{
// spawn interval time threshold as been reached and we have food to convert into workers...
if (spawnCounter>=TICKS_BETWEEN_FOOD_RETURN_MAX && food>0)
{
// change to reset spawn counter mode to spawn a new worker
return {cell:4, color:QUEEN_MODE_RESETTING_SPAWNING};
}
// change to reset spawn counter mode
return {cell:4, color:QUEEN_MODE_RESETTING};
}
if (spawnCounter < SPAWN_COUNTER_MAX)
{
// simply increment the counter
return incrementSpawnCounter(view);
}
return NO_OP;
}
default:
{
}
}
}
/////////////////////////////////////// WORKER ///////////////////////////////////////
var expectedNextPathColourToEdge = nextTrailColor(currentCellColour);
// worker is looking for food
if (food===0)
{
/////////////////////////////////// WORKER HUNTNING //////////////////////////////////
// determine whether we are a recently spawned worker
for (var i=1;i<9;i+=2)
{
// are we orthogonal to the queen?
if (view[i].ant!=null && view[i].ant.friend && view[i].ant.type === ANT_TYPE_QUEEN)
{
// test to see whether queen's counter has reset so worker is free to move
if (view[i].color === QUEEN_MODE_COUNTING_ODD || view[i].color === QUEEN_MODE_COUNTING_EVEN )
{
for (var j=1;j<9;j+=2)
{
if (view[j].ant===null && view[j].color===TRAIL_COLOR_A)
{
return {cell:j};
}
}
}
// wait until queen's counter has reset
return NO_OP;
}
}
// // this is to try and unstick stuck ants... not overly well i might add
// if (randomInt(view,1)%20==1)
// {
// // attempt to pick an empty random trail-cell
// for (i = randomInt(view,666)%9;i>0;i--)
// {
// if (view[i].ant==null && view[i].food==0 && isTrailColour(view[i].color))
// {
// return new Move(i);
// }
// }
// }
// see if there is any food off band that is enclosed or almost enclosed by trail cells
// if so, then move to claim the food
if (view[1].food>0 &&
isTrailColour(view[0].color) &&
isTrailColour(view[2].color))
{
return {cell:1};
}
if (view[3].food>0 &&
isTrailColour(view[0].color) &&
isTrailColour(view[6].color))
{
return {cell:3};
}
if (view[5].food>0 &&
isTrailColour(view[2].color) &&
isTrailColour(view[8].color))
{
return {cell:5};
}
if (view[7].food>0 &&
isTrailColour(view[6].color) &&
isTrailColour(view[8].color))
{
return {cell:7};
}
// if not on trail, attempt see if cells surrounding are trail colours... and set our own cell accordingly
if (!isTrailColour(currentCellColour))
{
for (var priority = 0; priority <4;priority++)
{
// repeat for each rotation
var indecies = shuffleIndecies(view,random,4);
for (var j=0;j<4;j++)
{
var r = indecies[j];
switch(priority)
{
// C?? ...
// ??? .P.
// P?N ...
case 0:
if (isTrailColour(view[rotate[r][0]].color) &&
nextTrailColor(view[rotate[r][0]].color) === view[rotate[r][8]].color &&
prevTrailColor(view[rotate[r][0]].color) === view[rotate[r][6]].color)
{
return {cell:4, color: view[rotate[r][6]].color};
}
break;
// ??C ...
// ??? .C.
// N?C ...
case 1:
if (isTrailColour(view[rotate[r][2]].color) &&
view[rotate[r][2]].color === view[rotate[r][8]].color &&
nextTrailColor(view[rotate[r][2]].color) === view[rotate[r][6]].color)
{
return {cell:4, color: view[rotate[r][2]].color};
}
break;
// C?? ...
// ??? .C.
// P?? ...
case 2:
if (isTrailColour(view[rotate[r][0]].color) &&
prevTrailColor(view[rotate[r][0]].color) === view[rotate[r][6]].color)
{
return {cell:4, color: view[rotate[r][0]].color};
}
break;
// C?? ...
// ??? .C.
// ??? ...
case 3:
if (isTrailColour(view[rotate[r][0]].color))
{
return {cell:4, color: view[rotate[r][0]].color};
}
break;
}
}
}
// we are completely lost! lets perform a random walk and hopefully find the surface again
return {cell:view[2].ant === null?2:4};
}
// decide worker action...
for (var priority = 0; priority <13;priority++)
{
// repeat for each rotation
var indecies = shuffleIndecies(view,random,4);
for (var j=0;j<4;j++)
{
var r = indecies[j];
var cellToMoveTo =-1;
switch(priority)
{
/////// AVOID MOVING/PAINTING LOCK-STEP ///////
// X?X ...
// ?C? .M.
// C?W ...
case 0:
if (view[rotate[r][6]].color === currentCellColour &&
!isTrailColour(view[rotate[r][0]].color) &&
!isTrailColour(view[rotate[r][2]].color) &&
view[rotate[r][8]].ant!=null &&
view[rotate[r][8]].ant.type!=ANT_TYPE_QUEEN)
{
// step back on path back to queen
return NO_OP;
}
break;
/////// REPAIR PATH ///////
// P?X ..C
// ?C? ...
// C?? ...
case 1:
if (view[rotate[r][2]].color != currentCellColour &&
view[rotate[r][6]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][0]],currentCellColour))
{
return {cell:rotate[r][2], color:currentCellColour};
}
break;
// ??C N..
// ?C? ...
// X?P ...
case 2:
if (view[rotate[r][2]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][8]],currentCellColour) &&
!isTrailColour(view[rotate[r][6]].color) &&
view[rotate[r][0]].color != expectedNextPathColourToEdge)
{
return {cell:rotate[r][0], color:expectedNextPathColourToEdge};
}
break;
// C?N ...
// ?C? .N.
// ??P ...
case 3:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][2]].color === expectedNextPathColourToEdge &&
isCellTrailToQueen(view[rotate[r][8]],currentCellColour))
{
return {cell:4, color:expectedNextPathColourToEdge};
}
break;
// C?? N..
// ?C? ...
// ??P ...
case 4:
if (view[rotate[r][0]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][8]],currentCellColour))
{
return {cell:rotate[r][0], color:expectedNextPathColourToEdge};
}
break;
/////// MOVING ///////
// C?P ...
// ?C? ...
// ??C N..
case 5:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][8]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][2]],currentCellColour) &&
view[rotate[r][6]].color != expectedNextPathColourToEdge)
{
if (view[rotate[r][6]].ant === null)
{
return {cell:rotate[r][6], color:expectedNextPathColourToEdge};
}
else
{
return NO_OP;
}
}
break;
// C?P ...
// ?C? ...
// N?C M..
case 6:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][8]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][2]],currentCellColour) &&
view[rotate[r][6]].color === expectedNextPathColourToEdge)
{
cellToMoveTo = rotate[r][6];
}
break;
// Special case. we need to first paint the cell prior to moving other wise will cause corruption
// C?? ...
// ?C? ...
// C?? ..N
case 7:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][6]].color === currentCellColour &&
view[rotate[r][8]].color != expectedNextPathColourToEdge)
{
if (view[rotate[r][8]].ant === null)
{
return {cell:rotate[r][8], color:expectedNextPathColourToEdge};
}
else
{
return NO_OP;
}
}
break;
// C?? ...
// ?C? ...
// C?N ..M
case 8:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][6]].color === currentCellColour &&
view[rotate[r][8]].color === expectedNextPathColourToEdge)
{
cellToMoveTo = rotate[r][8];
}
break;
// C?? ..M
// ?C? ...
// P?C ...
case 9:
if (view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][8]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][6]],currentCellColour))
{
cellToMoveTo = rotate[r][2];
}
break;
// C?? ...
// ?C? ...
// P?? ..M
case 10:
if (view[rotate[r][0]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][6]],currentCellColour))
{
cellToMoveTo = rotate[r][8];
}
break;
// C?? ...
// ?C? ...
// ??? M..
case 11:
if (view[rotate[r][0]].color === currentCellColour)
{
cellToMoveTo = rotate[r][6];
}
break;
// ??? ...
// ?C? ...
// P?? ?.M
case 12:
if (isCellTrailToQueen(view[rotate[r][6]],currentCellColour))
{
cellToMoveTo = rotate[r][8];
}
break;
}
if (cellToMoveTo>-1)
{
return {cell:view[cellToMoveTo].ant === null?cellToMoveTo:4};
}
}
}
return NO_OP;
}
// worker is transporting food
else
{
// worker deadlock avoidance
for (i=0; i<9; i+=2)
{
// does the cell have another ant in it?
if (i!=4 && view[i].ant!=null && !(view[i].ant.type===ANT_TYPE_QUEEN && view[i].ant.friend))
{
// attempt to pick an empty random trail-cell
for (i = randomInt(view,54321)%9;i>0;i--)
{
if (view[i].ant===null && view[i].food===0 && isTrailColour(view[i].color))
{
return {cell:i};
}
}
// no luck... just pick a random empty cell
for (i = randomInt(view,12345)%9;i>0;i--)
{
if (view[i].ant===null && view[i].food===0)
{
return {cell:i};
}
}
// deadlock unavoidable!
return NO_OP;
}
}
// // this is to try and unstick stuck ants
// if (randomInt(view,1)%20==1)
// {
// // attempt to pick an empty random trail-cell
// for (i = randomInt(view,666)%9;i>0;i--)
// {
// if (view[i].ant==null && view[i].food==0 && isTrailColour(view[i].color))
// {
// return new Move(i);
// }
// }
// }
// decide move action
for (var priority = 0; priority <14;priority++)
{
// repeat for each rotation
var indecies = shuffleIndecies(view,random,4);
for (var j=0;j<4;j++)
{
var r = indecies[j];
var cellToMoveTo =-1;
switch(priority)
{
// PRE-EMPTIVE PATH PRUNING
// C?X X..
// ?X? ...
// P?X ...
case 0:
if (isTrailColour(view[rotate[r][0]].color) &&
!isTrailColour(view[rotate[r][2]].color) &&
!isTrailColour(view[rotate[r][4]].color) &&
prevTrailColor(view[rotate[r][0]].color) === view[rotate[r][5]].color)
{
return {cell:rotate[r][0], color: 1};
}
break;
// ?C? ...
// CXN X..
// ?X? ...
case 1:
if (!isTrailColour(view[rotate[r][4]].color) &&
!isTrailColour(view[rotate[r][7]].color) &&
isTrailColour(view[rotate[r][1]].color) &&
view[rotate[r][3]].color === view[rotate[r][1]].color &&
nextTrailColor(view[rotate[r][1]].color) === view[rotate[r][5]].color)
{
return {cell:rotate[r][3], color: 1};
}
break;
// ?C? ...
// PXC ..X
// ?X? ...
case 2:
if (!isTrailColour(view[rotate[r][4]].color) &&
!isTrailColour(view[rotate[r][7]].color) &&
isTrailColour(view[rotate[r][1]].color) &&
view[rotate[r][5]].color === view[rotate[r][1]].color &&
prevTrailColor(view[rotate[r][1]].color) === view[rotate[r][3]].color)
{
return {cell:rotate[r][5], color: 1};
}
break;
// N?? ..N
// ?C? ...
// C?C ...
case 3:
if (isTrailColour(view[rotate[r][4]].color) &&
view[rotate[r][2]].color != expectedNextPathColourToEdge &&
view[rotate[r][8]].color === currentCellColour &&
view[rotate[r][0]].color === expectedNextPathColourToEdge &&
view[rotate[r][6]].color === currentCellColour)
{
return {cell:rotate[r][2], color:expectedNextPathColourToEdge};
}
break;
// N?? ...
// ?X? .C.
// C?C ...
case 4:
if (!isTrailColour(view[rotate[r][4]].color) &&
isTrailColour(view[rotate[r][8]].color) &&
view[rotate[r][0]].color === nextTrailColor(view[rotate[r][8]].color) &&
view[rotate[r][8]].color === view[rotate[r][6]].color)
{
return {cell:rotate[r][4], color:view[rotate[r][8]].color};
}
break;
// N?? ..C
// ?C? ...
// C?P ...
case 5:
if (isTrailColour(view[rotate[r][4]].color) &&
view[rotate[r][0]].color === expectedNextPathColourToEdge &&
view[rotate[r][6]].color === currentCellColour &&
isCellTrailToQueen(view[rotate[r][8]],currentCellColour) &&
view[rotate[r][2]].color != currentCellColour)
{
return {cell:rotate[r][2], color:currentCellColour};
}
break;
// C?N ...
// ?X? .N.
// ??P ...
case 6:
if (!isTrailColour(view[rotate[r][4]].color) &&
isTrailColour(view[rotate[r][0]].color) &&
view[rotate[r][2]].color === nextTrailColor(view[rotate[r][0]].color) &&
view[rotate[r][8]].color === prevTrailColor(view[rotate[r][0]].color))
{
return {cell:rotate[r][4], color:nextTrailColor(view[rotate[r][0]].color)};
}
break;
// ??P ...
// ?X? .N.
// ??N ...
case 7:
if (!isTrailColour(view[rotate[r][4]].color) &&
isTrailColour(view[rotate[r][2]].color) &&
nextTrailColor(view[rotate[r][2]].color) === view[rotate[r][8]].color)
{
return {cell:4, color:view[rotate[r][8]].color};
}
break;
// if we are on the corner of a trail band... move opposite to the apex
case 8:
if (isTrailColour(currentCellColour) &&
view[rotate[r][0]].color === currentCellColour &&
view[rotate[r][2]].color === currentCellColour)
{
if (randomInt(view,currentCellColour)%2 === 0)
{
cellToMoveTo = rotate[r][0];
}
else
{
cellToMoveTo = rotate[r][2];
}
}
break;
// if we on the opposite corner of a trail band... move back toward the apex
case 9:
if (isTrailColour(currentCellColour) &&
isCellTrailToQueen(view[rotate[r][0]],currentCellColour) &&
isCellTrailToQueen(view[rotate[r][2]],currentCellColour))
{
if (randomInt(view,currentCellColour)%2 === 0)
{
cellToMoveTo = rotate[r][0];
}
else
{
cellToMoveTo = rotate[r][2];
}
}
break;
// if an adjacent cell is a trail to the queen, move that way
case 10:
if (isTrailColour(currentCellColour) &&
isCellTrailToQueen(view[rotate[r][0]],currentCellColour))
{
cellToMoveTo = rotate[r][0];
}
break;
// if we are not on a trail and an adjacent cell is a trail, then move that way
case 11:
if (!isTrailColour(currentCellColour) && isTrailColour(view[rotate[r][8]].color))
{
cellToMoveTo = rotate[r][8];
}
break;
// are we on a cell between trail cells? if so then move onto a cell on the trail.
case 12:
if (isTrailColour(view[rotate[r][1]].color))
{
cellToMoveTo = rotate[r][1];
}
break;
// are we on a terminal trail cell? if so then move onto a cell on the trail.
case 13:
if (isTrailColour(view[rotate[r][0]].color))
{
cellToMoveTo = rotate[r][0];
}
break;
}
if (cellToMoveTo>-1)
{
if (view[cellToMoveTo].ant != null || view[cellToMoveTo].food > 0) continue;
return {cell:cellToMoveTo};
}
}
}
return NO_OP;
}
}
return getAction(view);
```
*VERSION 1*
[![version1](https://i.stack.imgur.com/waif4.gif)](https://i.stack.imgur.com/waif4.gif)
The basic premise of this entry will to search in an ever expanding square spiral. Search square perimeter expansion will create a three band repeating pattern allowing for quick food delivery and return to perimeter.
There name of the entry is from the "firefly" enemy in the classic puzzle game BolderDash, the repeating three colour pattern is reminisent of the enemy.
This initial version, whilst has latent bugs, fulfills the basic requirements to be a basic entry: the ants do collect and return food to the queen. However, food is immediately converted to workers, so will never place well in a tournament.
However for the next version I think i will fundamentally change the way and order the ants move/paint: from paint then move, to move then paint. While i cannot be certain, I think some of the cell colour pattern corruption is occuring from cells that contain ants being re-painted by adjacent ants. Changing the order should help to reduce that risk... but will potentially more complicated/risky to move before painting.
*VERSION 2*
[![version 2](https://i.stack.imgur.com/r8Lh4.gif)](https://i.stack.imgur.com/r8Lh4.gif)
This version is superior, it now is rotated 45 degrees allowing for more exploration per worker ant step.
It also now collects food (if it does not get distracted)
It is, however not robust and easily gets interrupted by other ant's trails. So it is not a good contender as it currently stands.
However when left alone, it averages 700 food collected with 300 workers.
*VERSION 2.1*
Added sanity check to ensure that queen does not try to make a worker when not having any food.
*VERSION 2.1.1*
fixed the fix in 2.1 (I did not actually use the "food" field of the ant's view and was therefore referencing a null object.
*VERSION 2.1.1.1*
/me hides head in hands
I found a simple indexing bug in spawning function which meant that the queen may try to spawn on top of herself... needless to say that is grounds for disqualification. now fixed.
*VERSION 2.2*
Fixed copy paste error that re-introduced illegal spawn bug
*VERSION 2.2.1*
Fixed possible illegal move in the beginning scramble when queen is attempting to find the first piece of food.
[Answer]
# Lone Wolf
*All my answers are sharing the same set of low-level helper functions.
Search for "High-level logic begins here" to see the code specific to this answer.*
```
// == Shared low-level helpers for all solutions ==
var QUEEN = 5;
var WHITE = 1;
var COL_MIN = WHITE;
var COL_LIM = 9;
var CENTRE = 4;
var NOP = {cell: CENTRE};
var DIR_FORWARDS = false;
var DIR_REVERSE = true;
var SIDE_RIGHT = true;
var SIDE_LEFT = false;
function sanity_check(movement) {
var me = view[CENTRE].ant;
if(!movement || movement.cell < 0 || movement.cell > 8) {
return false;
}
if(movement.type) {
if(movement.color) {
return false;
}
if(movement.type < 1 || movement.type > 4) {
return false;
}
if(view[movement.cell].ant || view[movement.cell].food) {
return false;
}
if(me.type !== QUEEN || me.food < 1) {
return false;
}
return true;
}
if(movement.color) {
if(movement.color < COL_MIN || movement.color >= COL_LIM) {
return false;
}
if(view[movement.cell].color === movement.color) {
return false;
}
return true;
}
if(view[movement.cell].ant) {
return false;
}
if(view[movement.cell].food + me.food > 1 && me.type !== QUEEN) {
return false;
}
return true;
}
function as_array(o) {
if(Array.isArray(o)) {
return o;
}
return [o];
}
function best_of(movements) {
var m;
for(var i = 0; i < movements.length; ++ i) {
if(typeof(movements[i]) === 'function') {
m = movements[i]();
} else {
m = movements[i];
}
if(sanity_check(m)) {
return m;
}
}
return null;
}
function play_safe(movement) {
// Avoid disqualification: no-op if moves are invalid
return best_of(as_array(movement)) || NOP;
}
var RAND_SEED = (() => {
var s = 0;
for(var i = 0; i < 9; ++ i) {
s += view[i].color * (i + 1);
s += view[i].ant ? i * i : 0;
s += view[i].food ? i * i * i : 0;
}
return s % 29;
})();
var ROTATIONS = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 3, 0, 7, 4, 1, 8, 5, 2],
[8, 7, 6, 5, 4, 3, 2, 1, 0],
[2, 5, 8, 1, 4, 7, 0, 3, 6],
];
function try_all(fns, limit, wrapperFn, checkFn) {
var m;
fns = as_array(fns);
for(var i = 0; i < fns.length; ++ i) {
if(typeof(fns[i]) !== 'function') {
if(checkFn(m = fns[i])) {
return m;
}
continue;
}
for(var j = 0; j < limit; ++ j) {
if(checkFn(m = wrapperFn(fns[i], j))) {
return m;
}
}
}
return null;
}
function identify_rotation(testFns) {
// testFns MUST be functions, not constants
return try_all(
testFns,
4,
(fn, r) => fn(ROTATIONS[r]) ? ROTATIONS[r] : null,
(r) => r
);
}
function near(a, b) {
return (
Math.abs(a % 3 - b % 3) < 2 &&
Math.abs(Math.floor(a / 3) - Math.floor(b / 3)) < 2
);
}
function try_all_angles(solverFns) {
return try_all(
solverFns,
4,
(fn, r) => fn(ROTATIONS[r]),
sanity_check
);
}
function try_all_cells(solverFns, skipCentre) {
return try_all(
solverFns,
9,
(fn, i) => ((i === CENTRE && skipCentre) ? null : fn(i)),
sanity_check
);
}
function try_all_cells_near(p, solverFns) {
return try_all(
solverFns,
9,
(fn, i) => ((i !== p && near(p, i)) ? fn(i) : null),
sanity_check
);
}
function ant_type_at(i, friend) {
return (view[i].ant && view[i].ant.friend === friend) ? view[i].ant.type : 0;
}
function friend_at(i) {
return ant_type_at(i, true);
}
function foe_at(i) {
return ant_type_at(i, false);
}
function foe_near(p) {
for(var i = 0; i < 9; ++ i) {
if(foe_at(i) && near(i, p)) {
return true;
}
}
return false;
}
function move_agent(agents) {
var me = view[CENTRE].ant;
var buddies = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < 9; ++ i) {
++ buddies[friend_at(i)];
}
for(var i = 0; i < agents.length; i += 2) {
if(agents[i] === me.type) {
return agents[i+1](me, buddies);
}
}
return null;
}
function grab_nearby_food() {
return try_all_cells((i) => (view[i].food ? {cell: i} : null), true);
}
function go_anywhere() {
return try_all_cells((i) => ({cell: i}), true);
}
function colours_excluding(cols) {
var r = [];
for(var i = COL_MIN; i < COL_LIM; ++ i) {
if(cols.indexOf(i) === -1) {
r.push(i);
}
}
return r;
}
function generate_band(start, width) {
var r = [];
for(var i = 0; i < width; ++ i) {
r.push(start + i);
}
return r;
}
function colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function(c) {
return colours[(colours.indexOf(c) + 1) % colours.length];
}
};
}
function random_colour_band(colours) {
return {
contains: function(c) {
return colours.indexOf(c) !== -1;
},
next: function() {
return colours[RAND_SEED % colours.length];
}
};
}
function fast_diagonal(colourBand) {
var m = try_all_angles([
// Avoid nearby checked areas
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[5]].color) &&
colourBand.contains(view[rot[7]].color)
) {
return {cell: rot[0]};
}
},
// Go in a straight diagonal line if possible
(rot) => {
if(
!colourBand.contains(view[rot[0]].color) &&
colourBand.contains(view[rot[8]].color)
) {
return {cell: rot[0]};
}
},
// When in doubt, pick randomly but avoid doubling-back
(rot) => (colourBand.contains(view[rot[0]].color) ? null : {cell: rot[0]}),
// Double-back when absolutely necessary
(rot) => ({cell: rot[0]})
]);
// Lay a colour track so that we can avoid doubling-back
// (and mess up our foes as much as possible)
if(!colourBand.contains(view[CENTRE].color)) {
var prevCol = m ? view[8-m.cell].color : WHITE;
return {cell: CENTRE, color: colourBand.next(prevCol)};
}
return m;
}
function follow_edge(obstacleFn, side) {
// Since we don't know which direction we came from, this can cause us to get
// stuck on islands, but the random orientation helps to ensure we don't get
// stuck forever.
var order = ((side === SIDE_LEFT)
? [0, 3, 6, 7, 8, 5, 2, 1, 0]
: [0, 1, 2, 5, 8, 7, 6, 3, 0]
);
return try_all(
[obstacleFn],
order.length - 1,
(fn, i) => (fn(order[i+1]) && !fn(order[i])) ? {cell: order[i]} : null,
sanity_check
);
}
function start_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => ((
!protectedCols.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color) &&
!colourBand.contains(view[rot[right ? 2 : 0]].color) &&
!colourBand.contains(view[rot[1]].color)
)
? {cell: rot[right ? 5 : 3], color: colourBand.next(WHITE)}
: null)
]);
}
function lay_dotted_path(colourBand, side, protectedCols) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var ahead = rot[right ? 2 : 0];
var behind = rot[right ? 8 : 6];
if(
colourBand.contains(view[behind].color) &&
!protectedCols.contains(view[ahead].color) &&
!colourBand.contains(view[ahead].color) &&
!colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
return {cell: ahead, color: colourBand.next(view[behind].color)};
}
}
]);
}
function follow_dotted_path(colourBand, side, direction) {
var forwards = (direction === DIR_REVERSE) ? 7 : 1;
var right = (side === SIDE_RIGHT);
return try_all_angles([
// Cell on our side? advance
(rot) => {
if(
colourBand.contains(view[rot[right ? 5 : 3]].color) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[0]].color) &&
!colourBand.contains(view[rot[2]].color)
) {
return {cell: rot[forwards]};
}
},
// Cell ahead and behind? advance
(rot) => {
var passedCol = view[rot[right ? 8 : 6]].color;
var nextCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(passedCol) &&
nextCol === colourBand.next(passedCol) &&
// Prevent sticking / trickery
!colourBand.contains(view[rot[right ? 3 : 5]].color) &&
!colourBand.contains(view[rot[right ? 0 : 2]].color)
) {
return {cell: rot[forwards]};
}
}
]);
}
function escape_dotted_path(colourBand, side, newColourBand) {
var right = (side === SIDE_RIGHT);
if(!newColourBand) {
newColourBand = colourBand;
}
return try_all_angles([
// Escape from beside the line
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
!colourBand.contains(view[rot[right ? 8 : 6]].color) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[rot[7]].color) ||
colourBand.contains(view[rot[right ? 6 : 8]].color)
) {
// not oriented, or in a corner
return null;
}
return best_of([
{cell: rot[right ? 0 : 2], color: newColourBand.next(approachingCol)},
{cell: rot[right ? 3 : 5]},
{cell: rot[right ? 0 : 2]},
{cell: rot[right ? 6 : 8]},
{cell: rot[right ? 2 : 0]},
{cell: rot[right ? 8 : 6]},
{cell: rot[right ? 5 : 3]}
]);
},
// Escape from inside the line
(rot) => {
if(
!colourBand.contains(view[rot[7]].color) ||
!colourBand.contains(view[rot[1]].color) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
return best_of([
{cell: rot[3]},
{cell: rot[5]},
{cell: rot[0]},
{cell: rot[2]},
{cell: rot[6]},
{cell: rot[8]}
]);
}
]);
}
function latch_to_dotted_path(colourBand, side) {
var right = (side === SIDE_RIGHT);
return try_all_angles([
(rot) => {
var approachingCol = view[rot[right ? 2 : 0]].color;
if(
colourBand.contains(approachingCol) &&
view[rot[right ? 8 : 6]].color === colourBand.next(approachingCol) &&
!colourBand.contains(view[rot[right ? 5 : 3]].color)
) {
// We're on the wrong side; go inside the line
return {cell: rot[right ? 5 : 3]};
}
},
// Inside the line? pick a side
(rot) => {
var passedCol = view[rot[7]].color;
var approachingCol = view[rot[1]].color;
if(
!colourBand.contains(passedCol) ||
!colourBand.contains(approachingCol) ||
colourBand.contains(view[CENTRE].color)
) {
return null;
}
if((approachingCol === colourBand.next(passedCol)) === right) {
return best_of([{cell: rot[3]}, {cell: rot[6]}, {cell: rot[0]}]);
} else {
return best_of([{cell: rot[5]}, {cell: rot[2]}, {cell: rot[8]}]);
}
}
]);
}
// == High-level logic begins here ==
var COLOURS = random_colour_band(colours_excluding([1]));
return play_safe([
grab_nearby_food,
fast_diagonal.bind(null, COLOURS),
go_anywhere,
{cell: 1, color: COLOURS.next()}
]);
```
So it occurred to me that in a couple of my answers I used the same initial step for gathering starting food quickly. What happens if an ant uses that strategy for the entire game? Well it turns out they do rather well.
This just races around the field at half the speed of light, grabbing any nearby food. There's a chance the direction will change randomly when grabbing food, and it will try to avoid any area already covered by itself or others. No worker ants are ever generated.
In theory, this covers 2.5 cells per frame, which isn't terrible, and it's pretty much impossible to trap it or mess it up in any way. It seems to do better than everything except Black Hole (though that may change now that Black Hole has a saboteur).
I promise to stop spamming this challenge with answers now…
---
The latest update makes it slightly less likely to re-search covered ground by making it push away from more types of filled areas.
[Answer]
# Pierce
This bot consistently obtains close to 90 food, beating out most of the other bots.
```
var ORTHOGONALS = [1,3,5,7];
var CORNERS = [0,2,6,8];
var CENTER = 4;
var QUEEN = 5;
var no_op = {cell:CENTER};
var me = view[4].ant;
var ants;
var food;
var friendlies;
var unfriendlies;
var colors;
var j = 0;
var i = 0;
var cell = 0;
var rotation;
var out;
init_arrays();
var seed = rSeed();
var response;
var adjacents_all = {0:[1,3,4],1:[0,2,3,4,5],2:[1,4,5],3:[0,1,4,6,7],4:[0,1,2,3,4,5,6,7,8],5:[1,2,4,7,8],6:[3,4,7],7:[3,4,5,6,8],8:[4,5,7]};
var adjacents_ortho = {0:[1,3],1:[0,2,4],2:[1,5],3:[0,4,6],4:[1,3,5,7],5:[2,4,8],6:[3,7],7:[4,6,8],8:[5,7]};
var adjacents_diag = {0:[4],1:[3,5],2:[4],3:[1,7],4:[0,2,6,8],5:[1,7],6:[4],7:[3,5],8:[4]};
function valid_move(move) {
if(!move || move.cell == undefined || move.cell < 0 || move.cell > 8) {return false;}
if(move.type) {
if(move.color) {return false;}
if(move.type < 1 || move.type > 4) {return false;}
if(view[move.cell].ant || view[move.cell].food) {return false;}
if(me.type != QUEEN || me.food < 1) {return false;}
return true;
}
if(move.color) {
if(move.color < 1 || move.color > 8) {return false;}
return true;
}
if(view[move.cell].ant){return false;}
if(view[move.cell].food && me.food&& me.type != 5) {return false;}
return true;
}
function steal_then_road(){
if(count(unfriendlies, 5)>=1 && me.food==0){
//steal from a queen with more than 30 food
if(ants[unfriendlies.indexOf(5)].food>30){
for(i=0;i<adjacents_ortho[unfriendlies.indexOf(5)].length;i++){
if(ants[adjacents_ortho[unfriendlies.indexOf(5)][i]]==null){
return {cell:adjacents_ortho[unfriendlies.indexOf(5)][i]};
}
}
}
}
return road();
}
function try_corners(){
for(i=0;i<4;i++){
if(view[CORNERS[i]].ant==null){
return {cell:CORNERS[i]};
}
}
}
function try_ortho(){
for(i=0;i<4;i++){
if(view[ORTHOGONALS[i]].ant==null){
return {cell:ORTHOGONALS[i]};
}
}
}
function corner_then_ortho(){
if(try_corners()){return try_corners();}
if(try_ortho()){return try_ortho();}
return {cell:4}; //PANIC!
}
function ortho_then_corner(){
if(try_ortho()){return try_ortho();}
if(try_corners()){return try_corners();}
return {cell:4}; //PANIC!
}
function road(color){
if (colors[color] != color) {
return {cell:CENTER,color:color};
}
for (i = 0; i < 9; i++) {
if (colors[i] == color && ants[8 - i] == null && i != color) {
return {cell:8-i};
}
}
}
function color_self(color){
return {cell:4,color:color};
}
function make_valid_move(move){
if(valid_move(move)){return move;}
return no_op;
//return{cell:seed%9,color:seed%7+1};
}
function count(array, element) {
out = 0;
for (j = 0; j < array.length; j++) {
if (array[j] == element) {
out++;
}
}
return out;
}
function target_ant(ant_type, location) {
for (i = 0; i < 4; i++) {
if (ants[location] != null) {
if (ants[location].type == ant_type) {
return i;
}
}
ants = rot_left(ants);
friendlies = rot_left(friendlies);
unfriendlies = rot_left(unfriendlies);
food = rot_left(food);
colors = rot_left(colors);
}
}
function target_color(color, location) {
for (i = 0; i < 4; i++) {
if (colors[location] != null) {
if (colors[location].type == color) {
return i;
}
}
ants = rot_left(ants);
friendlies = rot_left(friendlies);
unfriendlies = rot_left(unfriendlies);
food = rot_left(food);
colors = rot_left(colors);
}
}
function init_arrays() {
ants = new Array(9);
for (cell = 0; cell < 9; cell++) {ants[cell] = view[cell].ant;}
food = new Array(9);
for (cell = 0; cell < 9; cell++) {food[cell] = view[cell].food;}
colors = new Array(9);
for (cell = 0; cell < 9; cell++) {colors[cell] = view[cell].color;}
friendlies = new Array(9);
for (cell = 0; cell < 9; cell++) {
if (ants[cell] != null) {
if (ants[cell].friend) {friendlies[cell] = ants[cell].type;}
}
}
unfriendlies = new Array(9);
for (cell = 0; cell < 9; cell++) {
if (ants[cell] != null) {
if (!ants[cell].friend) {unfriendlies[cell] = ants[cell].type;}
}
}
}
function rot_n_pos(pos, n) {
for (i = 0; i < n; i++) {
pos = [2, 5, 8, 1, 4, 7, 0, 3, 6][pos];
}
return pos;
}
function rot_left(a) {
return [a[2], a[5], a[8], a[1], a[4], a[7], a[0], a[3], a[6]];
}
function rot_right(a) {
return [a[6], a[3], a[0], a[7], a[4], a[1], a[8], a[5], a[2]];
}
function rSeed(){
out=23;
for(i=0;i<9;i++){
if(food[i]){
out+=17;
}
out += 3 * colors[i];
if(ants[i]){
out *= 19;
}
}
return out;
}
function get_response(){
if (me.type == 5) { //Queen Case:
return type5();
}
else if (me.type == 1) {
return type1();
}
else if (me.type == 2) {
return type2();
}
else if (me.type == 3) {
return type3();
}
else if(me.type == 4){
return type4();
}
function type5(){
if (me.food == 0 && count(friendlies, 1) == 0 && count(friendlies, 2) == 0) {
if (count(food, 1) > 0) {
for (j = 0; j < 9; j++) {
if (food[j]) {
return {cell: j};
}
}
}
// travel up
// color own cell if not 4
if(road()){return road();}
//move
for (i = 0; i < 9; i++) {
if (ants[i] == null && i != 4) {
return {cell:i};
}
}
return corner_then_ortho();
}
if (me.food >= 1 && count(friendlies, 1) == 0 && count(friendlies, 2) == 0) {
if (ants[5] == null) {
return {cell:5,type:1};
}
if (ants[1] == null) {
return {cell:5, type:1};
}
if (ants[3] == null) {
return {cell:5,type:1};
}
if (ants[7] == null) {
return {cell:5, type:1};
}
return color_self(5);
}
if (me.food == 0 && count(friendlies, 1) == 1 && count(friendlies, 2) == 0) {
if (friendlies.indexOf(1) % 2 == 0) {
return ortho_then_corner();//PANIC!!! TODO: FIX
}
rotation = target_ant(1, 1);
if (ants[0] == null) {
return {cell: rot_n_pos(0, rotation)};
} else {
return corner_then_ortho;
}
}
if (me.food >= 1 && count(friendlies, 1) == 1 && count(friendlies, 2) == 0) {
if (friendlies.indexOf(1) % 2 == 0) {
return corner_then_ortho(); //PANIC!!! TODO: FIX
}
rotation = target_ant(1, 1);
if (ants[3] == null) {
return {cell: rot_n_pos(3, rotation),type: 2};
}
if (ants[0] == null) {
return { cell: rot_n_pos(0, rotation)};
}
return {cell: 4};
}
if (count(friendlies, 1) == 1 && count(friendlies, 2) == 1) {
if (friendlies.indexOf(1) % 2 == 0) {
return ortho_then_corner();
}
rotation = target_ant(1, 1);
if(food[0] || food[8]){
return no_op;
}
if(ants[5]!=null){
if(ants[5].type == 2 && ants[2]==null){
return {cell: rot_n_pos(2, rotation)};
}
}
return corner_then_ortho();
}
return corner_then_ortho();
}
function type1(){
//right flank
if (count(friendlies, 5) == 0 && count(friendlies, 2) == 0 && count(friendlies,1) == 1) {
//no friends = destruction
return steal_then_road();
}
if (count(friendlies, 5) == 1 && count(friendlies, 2) == 0 && count(friendlies,1) == 1) {
if (friendlies.indexOf(5) % 2 == 0) {
return ortho_then_corner();
}
rotation = target_ant(5, 3);
if (ants[0] == null) {
return {cell: rot_n_pos(0, rotation)};
}
return corner_then_ortho(); // PANIC!! TODO: FIX
}
if (count(friendlies, 5) == 1 && count(friendlies, 2) == 1 && count(friendlies,1) == 1) {
if (friendlies.indexOf(5) % 2 == 0) {
return ortho_then_corner();
}
rotation = target_ant(5, 3);
if(friendlies[8] !=null){
if(friendlies[8].type==2){
if (ants[0] == null){
return {cell: rot_n_pos(0, rotation)};
}
}
}
if (ants[0] != null) {
if (ants[0].type == 2 && ants[6] == null) {
return {cell: rot_n_pos(6, rotation)};
}
}
if (ants[6] != null) {
if (ants[6].type == 2 && ants[0] == null) {
return {cell: rot_n_pos(0, rotation)};
}
}
return corner_then_ortho();
}
return corner_then_ortho();
}
function type2(){
//left flank
if (count(friendlies, 5) == 0 && count(friendlies, 1) == 0 && count(friendlies,2) == 1) {
return steal_then_road();
}
if (count(friendlies, 5) == 1 && count(friendlies, 1) == 0 && count(friendlies,2) == 1) {
if (friendlies.indexOf(5) % 2 == 0) {
return ortho_then_corner();
}
rotation = target_ant(5, 1);
if (ants[0] == null) {
return {cell: rot_n_pos(2, rotation)};
}
return corner_then_ortho();
}
if (count(friendlies, 5) == 1 && count(friendlies, 2) == 1) {
return {cell: 4,color:2};
}
}
return corner_then_ortho();
}
function type3(){}
function type4(){}
response = get_response();
return make_valid_move(response);
```
# Strategy.
### Phase 1: Queen scramble.
The queen scrambles for food using a technique similar to Romanesco road (uses the `road()` function). Whenever she sees a food she takes it and spawns a type 1 worker, activating phase 2.
### Phase 2: Queen-partner scramble.
The queen and partner use each other to orient, so they travel at the speed of light. They ignore any food around them and just get what hits them. When the queen gets a food, she spawns a type 2 worker, activating phase 3.
### Phase 3: Pierce.
The three ants use each other to find their way, travelling at the speed of light. Whenever the queen sees a food that none of the workers can get, she stops, causing the workers to rotate around her and turning the formation 90 degrees.
# Strengths:
The three-ant formation creates no trails, doesn't wrap, and travels at the speed of light, getting an average of 0.1%\*3=0.003 food per move. This equates to 0.003\*30000 = 90 food per game on average, which is usually obtained.
# Weaknesses:
The bot has two weaknesses. The main one is an ant walking in front of the formation. The handling for that is not the best and sometimes causes the queen to create excessive amounts of workers. Luckily, the workers are programmed to steal from other queens (`steal_then_road()`). But since the formation creates no trails, it is practically impossible to find.
Another weakness is the `road()` algorithm which appears to have problems which I am working on fixing. A road being Brownian motion is not good. This means a very slow start and a bad escape from unhealthy situations.
[Answer]
# Single Queen
```
var C = 5;
for(var i = 0; i<9; i++)
{
if(view[i].food === 1)
return {cell:i};
}
if(view[4].color != 5 && !view[0].ant && !view[1].ant && !view[2].ant && !view[3].ant && !view[5].ant && !view[6].ant && !view[7].ant && !view[8].ant)
return {cell:4, color:C};
if(!view[0].ant &&
view[0].color != C && view[8].color === C && view[1].color != C && view[3].color != C && view[2].color != C && view[6].color != C)
return {cell:0};
if(!view[2].ant &&
view[2].color != C && view[6].color === C && view[1].color != C && view[5].color != C && view[0].color != C && view[8].color != C)
return {cell:2};
if(!view[6].ant &&
view[6].color != C && view[2].color === C && view[3].color != C && view[7].color != C && view[0].color != C && view[8].color != C)
return {cell:6};
if(!view[8].ant &&
view[8].color != C && view[0].color === C && view[5].color != C && view[7].color != C && view[2].color != C && view[6].color != C)
return {cell:8};
if(!view[0].ant)
return {cell:0};
if(!view[2].ant)
return {cell:2};
if(!view[6].ant)
return {cell:6};
if(!view[8].ant)
return {cell:8};
return {cell:4};
```
Simple code searching diagonally for food. Tries to avoid searching it's old area, but will search other areas to try and pass through their areas hoping to find open space.
Appears to be similar strategy to Lone Wolf (unintentional).
[Answer]
# Explorer
*Spread out Gang!*
![](https://i.gyazo.com/fc78a3a1338125af615170dee3034bf8.png)
Explorer is a 5 man team that aims to spread as far apart as possible, whilst still bringing food back to the queen.
## The Queen
The queen itself uses a 3 stage setup.
### Stage 1.
At the start of a match, it's a wild dash for food, like any good queen. It just paths in a straight line diagonally until it finds food, then randomly changes direction. When it has 4 food, it moves to stage 2.
### Stage 2.
This will probably take no more than 8 moves. It sets the four tiles around it to four unique colours, and spawns ants on them, with their respective types. After they're all spawned, stage 3 is moved to.
### Stage 3.
All stage 3 does is sit still for the rest of the match, ensuring the four tiles around it are set correctly.
## The Workers
The workers themselves are very simple two stage creatures. First, they wait for the queen to signal she's finished Stage 2. The second stage is a lot more complex (But still fairly simple). It walks clockwise around its own path until it finds its end, then it continues to expand it. When it finds food, it reaches out to it, then orbits clockwise around the path again, which leads it back to the queen.
```
var me = view[4].ant
var turf = view[4].color
var queenHolder = 2 // "Queen Holder", the turf colour for the queen in stage 3.
var queenBuild = 7 // "Queen Build", the turf colour for the queen in stage 2.
var antTrail = [3, 4, 5, 6] // Various colours of the ant's trails.
var orth = [1, 3, 5, 7] // Orthogonal Directions.
var rotates = [[1,3,5,7],[3,7,1,5],[5,1,7,3],[7,5,3,1]] // These are the orthogonal directions rotated so 0 is the first position, used in the queen build stage.
var outside = [1,2,3,5,6,7,8] // Every tile but the center one.
var diag = [0,2,6,8] // Diagonal Directions.
// Define a move function to avoid throwing an error.
function move(dir){
if(view[dir].ant) // If we're going to move onto an ant.
dir = 4 // Don't move anywhere.
if(view[dir].food && me.type < 5 && me.food > 0) // If we're going to over-eat.
dir = 4 // Don't move anywhere.
return {cell: dir} // Build the move output.
}
if(me.type == 5){ // If we're the queen.
var invDiag = [8,6,2,0] // Inverse of diagonals, using the indexing of diag. So 0 becomes 8, and such.
if(turf == 1 || turf == 8){
// Stage 1.
// Find enough food to start a hive.
for(var i=0; i < view.length; i++){ // Check every tile in view
if(view[i].food){ // Is it food?
return move(i) // Move to it.
}
}
if(me.food > 3) // Do we have 4 food?
return {cell:4, color:queenBuild} // Move to stage 2.
if(turf == 1) // Are we on a white tile?
return {cell:4, color:8} // Set the tile to black.
for(var i=0; i < diag.length; i++) // Check all diagonals.
if(view[diag[i]].color == 8) // Is it black?
return move(invDiag[i]) // Move in the opposite direction. This creates a straight diagonal line.
return move(2) // When in doubt, move randomly diagonally.
}else if(turf == queenBuild){
// Stage 2.
// Spawn ants around, and set up their movement paths.
if(me.food < 1) // Have we used all our food?
return {cell:4, color:queenHolder} // Move to stage 3.
var firstHolder = -1; // Stores which way we're facing.
for(var i=0; i < orth.length; i++){ // Check orthogonals.
if(view[orth[i]].color == antTrail[0]){ // Is it the first trail colour?
firstHolder = i // THIS WAY UP
break;
}
}
if(firstHolder==-1) // No way is up?
return {cell:1, color:antTrail[0]} // Set a random direction to up.
var orthRot = rotates[firstHolder] // Get the rotated orthogonal set for the current up direction.
for(var i=0; i < orthRot.length; i++){ // For each of them.
if(!view[orthRot[i]].ant) // Is there an ant on this tile yet?
return {cell:orthRot[i], type:(i+1)} // If not, place one down with the correct type.
if(view[orthRot[i]].color!=antTrail[i]) // Otherwise, is the turf set correctly yet?
return {cell:orthRot[i], color:antTrail[i]} // If not, set the turf.
}
return {cell:4, color:queenHolder}; // After all's said and done, move to stage 3. Probably won't happen this way.
}else if(turf == queenHolder){
// Stage 3.
// Sit still, ensure rails exist around.
var firstHolder = -1; // Same behavoir of which way is up from stage 2.
for(var i=0; i < orth.length; i++){
if(view[orth[i]].color == antTrail[0]){
firstHolder = i
break;
}
}
if(firstHolder==-1)
return {cell:1, color:antTrail[0]}
var orthRot = rotates[firstHolder]
for(var i=0; i < orthRot.length; i++) // Basically stage 2 without the spawning of ants.
if(view[orthRot[i]].color!=antTrail[i])
return {cell:orthRot[i], color:antTrail[i]}
return {cell:4, color:queenHolder} // And if there's nothing better to do, waste your time.
}else{
return {cell:4, color:1} // We're lost, go back to stage 1, and try again.
// I could probably add logic to check if we're stage 3 or something, but meh.
}
}else{ // If we're a worker!
for(var i=0; i < orth.length; i++) // Check around.
if(view[orth[i]].ant && view[orth[i]].ant.type == 5 && view[orth[i]].ant.friend && view[orth[i]].color == queenBuild) // Is there a queen, in build mode, around us?
return move(4) // Wait politely for her to finish.
var col = antTrail[me.type-1] // Which colour I use.
if(me.food < 1){ // If we have no food.
for(i=0; i < orth.length; i++){ // Check Orthogonals
if(view[orth[i]].food){ // Is there food there?
if(turf != col) // If we're not standing on our trail.
return {cell: 4, color: col} // Place our trail here, so we can still find our way back.
return move(orth[i]) // Otherwise, move to the food!
}
}
}
if(turf == col) // If we're sitting on our trail.
return move(2) // Move off it randomly
var corq = (t)=>t.color == col || (t.ant && t.ant.type == 5 && t.ant.friend) // Helper function, does this tile contain our trail or the queen?
var corqorf = (t)=>corq(t) || t.food // Helper function, odes this tile contain our trail, the queen, or a piece of food?
var queenInView = false;
for(var i=0; i < view.length; i++) // Check the entire view.
if(view[i].ant && view[i].ant.type == 5 && view[i].ant.friend) // Can we see the queen?
queenInView = true; // Remember this.
// Using food > 0 behavoir if we see a queen, makes it so that we don't accidentally build our path over the queen or something silly.
if(me.food > 0 || queenInView){ // If we have food, or we can see the queen.
// DON'T build paths, just orbit our path clockwise.
var orthmov = [3,7,1,5] // Directions to move if we see a path on an orthogonal.
var diagC = [3,1,7,5] // Directions to move if we see a path on a diagonal.
for(var i=0; i < orth.length; i++) // For each Orthogonal, which takes preference.
if(corqorf(view[orth[i]])) // Is there the queen, a trail, or food here?
return move(orthmov[i]) // move CW to it.
for(var i=0; i < diag.length; i++) // Ditto for Diagonals.
if(corqorf(view[diag[i]]))
return move(diagC[i])
}else{
// EXTEND paths, or continue orbiting clockwise.
var orthM = [0,6,2,8] // Directions a path should be when we check an orthogonal.
var orthMo = [3,7,1,5] // Directions to move if we see an orthogonal, and the diagonal is there.
var diagC = [3,1,7,5] // Directions to place a path if we only see an orthogonal.
for(var i=0; i < orth.length; i++){ // In each Orthogonal.
var v = view[orth[i]]
if(corq(v)){ // Is there a trial?
if(corq(view[orthM[i]])) // Is there a trail in the after it position?
return move(orthMo[i]) // Move in the correct direction.
return {cell:orthM[i], color:col} // Place the trail in the after it position.
}
}
for(var i=0; i < diag.length; i++) // Check diagonals as a last resort.
if(corq(view[diag[i]])) // Is there a path /HERE/?
return {cell:diagC[i], color:col} // Place the respective diagonal's orthogonal.
}
return move(2) // When we're lost, scamper around. Just like Trail-eraser wants us to.
}
```
[Answer]
# Romanesco Road
This player produces no workers, and the queen moves in a straight line, marking each cell she visits. The straight line motion is possible despite the random orientation of the input visible cells, because the queen can see the marked cell she just left, and moves in the opposite direction to this to ensure a straight line.
The first code block in an answer is the one automatically included in the game:
```
// Full version that won't be disqualified for moving onto another ant
var i
// Color own cell if white
if (view[4].color === 1) {
return {cell:4, color:3}
}
// Otherwise move to food if visible
for (i=0; i<9; i++) {
if (view[i].food) {
return {cell:i}
}
}
// Otherwise move to a white cell opposite a colored cell
for (i=0; i<9; i++) {
if (view[i].color === 1 && view[8-i].color > 1 && !view[i].ant) {
return {cell:i}
}
}
// Otherwise move to an unoccupied cell
for (i=0; i<9; i++) {
if (!view[i].ant) {
return {cell:i}
}
}
// Otherwise don't move at all
return {cell:4}
```
Here is a simpler version that doesn't check for other ants, but has identical behaviour up until the point it gets disqualified for trying to step onto another ant:
```
// Basic version for an intuitive understanding
var i
// Color own cell if white
if (view[4].color === 1) {
return {cell:4, color:3}
}
// Otherwise move to food if visible
for (i=0; i<9; i++) {
if (view[i].food) {
return {cell:i}
}
}
// Otherwise move to a white cell opposite a colored cell
for (i=0; i<9; i++) {
if (view[i].color === 1 && view[8-i].color > 1) {
return {cell:i}
}
}
// Otherwise move "left and up", which will be a random direction
return {cell:0}
```
This second code block won't be picked up by the game - this means you can include additional code blocks as part of your answer's explanation. Just make sure the code block that you wish to compete in the game is the first one in the answer.
For an example of producing random movement rather than a straight line, see [Brownian Jig](https://codegolf.stackexchange.com/a/135103/20283).
[Answer]
# VinceAnt
Do you feel that after nine months, the arena still looks a little bland?
Do you think that the [Antdom Walking Artist](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/135156#135156) and orphaned [The Formation](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/161838#161838) workers could do with a little help in decorating it attractively?
Then you'll like this one!
[![A Highway, refashioned](https://i.stack.imgur.com/jeFFD.png)](https://i.stack.imgur.com/jeFFD.png)
From time to time, as our means allow, the queen will sponsor and spawn a painter or two. These will go on to mess with the colors around them, in various personal styles, often taking existing colors into account but rearranging and twisting them as they see fit. They usually work alone, or sometimes in pairs. (That two ants can follow a straight horizontal or vertical line had been clear since day one and Dave's [Forensic Ants](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/135108#135108), but watch out now for a tandem who shift the patterns they encounter by one cell's worth.)
[![Claude and Jean](https://i.stack.imgur.com/JC76A.png)](https://i.stack.imgur.com/JC76A.png)
To make this affordable, there's a backbone lifted from my [Windmill](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/143980#143980) - imagine a Windmill queen and secretary/navigator who never grow up and settle. (The idea had previously been perfected by [Lightspeed](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/153688#153688), having been pioneered by the [Vampire](https://codegolf.stackexchange.com/questions/135102/formic-functions-ant-queen-of-the-hill-contest/135984#135984)'s bouncer facility. The implementation is different from Lightspeed's, though.) A number of modifications were needed to prevent things from falling apart when we run into our own offspring.
By its nature, this entry can't beat Lightspeed, but is expected to do reasonably well for all its extravaganza - about fifth among the current (as of April 2018) contenders.
Commented un-golfed source code is on [GitHub](https://github.com/GNiklasch/VinceAnt), and I'm planning to add more details about each painter type and style there once I've got round to collecting some nice screenshots.
```
var ANV=1;var AMK=2;var AGS=3;var AWM=4;var AQ=5;var THC=1;var THP=[0,0,0,0,0,0];THP[AMK]=19;THP[AGS]=17;THP[AWM]=15;var RM=15;var SPDAT =[0,AMK,AGS,0,AWM,0,AGS,AWM,0,AMK,0,AWM,AMK,0,AGS];var PW=1;var PY=2;var PP=3;var PC=4;var PR=5;var PG=6;var PB=7;var PK=8;var LCLR=PW;var LT=PY;var LLSF=PG;var TN=8;var POSC=4;var NOP={cell:POSC};var CCW=[6,7,8,5,2,1,0,3,6,7,8,5,2,1,0,3,6,7,8,5,2,1];
var xn=-1;var here=view[POSC];var mC=here.color;var myself=here.ant;var mT=myself.type;var mF=myself.food;var mS=(mT!=AQ&&mF>0);var dOK=[true,true,true,true,true,true,true,true,true];
var uo=true;var sL=[0,0,0,0,0,0,0,0,0];var sD=[0,0,0,0,0,0,0,0,0];var sN=[0,0,0,0,0,0,0,0,0];var sT=[0,0,0,0,0,0,0,0,0];var fdL=0;var fdD=0;var fdT=0;sT[mC]++;for (var i=0; i<TN; i+=2){var cell=view[CCW[i]];sD[cell.color]++;sN[cell.color]++;sT[cell.color]++;if (cell.food>0){fdD++;fdT++;if (mS){dOK[CCW[i]]=false;uo=false;}}}for (var i=1; i<TN; i+=2){var cell=view[CCW[i]];sL[cell.color]++;sN[cell.color]++;sT[cell.color]++;if (cell.food>0){fdL++;fdT++;if (mS){dOK[CCW[i]]=false;uo=false;}}}var aF=[0,0,0,0,0,0];var aLF=[0,0,0,0,0,0];var aUF=[0,0,0,0,0,0];var fT=0;var mQ=0;var aE=[0,0,0,0,0,0];var aLE=[0,0,0,0,0,0];var aUE=[0,0,0,0,0,0];var eT=0;for (var i=0; i<TN; i++){var cell=view[CCW[i]];if (cell.ant){if (cell.ant.friend){aF[cell.ant.type]++;fT++;if (cell.ant.type==AQ){xn=i&6;mQ=i&1;}if (cell.ant.food>0){aLF[cell.ant.type]++;} else {aUF[cell.ant.type]++;}} else {aE[cell.ant.type]++;eT++;if (cell.ant.food>0){aLE[cell.ant.type]++;} else {aUE[cell.ant.type]++;}}dOK[CCW[i]]=false;uo=false;}}switch (mT){case AQ:return (rQSs());case ANV:return (rNSs());case AMK:return (rMSs());case AGS:return (rGSs());case AWM:return (rWSs());default:return NOP;}function rQSs(){switch (aF[ANV]){case 0:return (rQScrSy());case 1:for (var i=0; i<TN; i++){var cell=view[CCW[i]];if (cell.ant&&cell.ant.friend&&cell.ant.type==ANV){xn=i&6;if (i&1){return (rQLsSy());} else {return (rQCSy());}}}break;default:return (rQCNSy());}return NOP;}function rNSs(){if (aF[AQ]>0){if (mQ==1){return (rSLSy());} else {return (rNRSy());}} else if ((mF==0)&&(fdT>0)){return (rPEgSy());} else {return (rPPgSy());}}function rMSs(){if ((aF[AQ]>0)&&(mF==0)){if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else {return NOP;}} else if ((mF>0)&&(aF[AQ]+aF[ANV]>0)){return NOP;} else if ((mF==0)&&(fdT>0)){return (rPEgSy());} else if (aF[AGS]+aF[AWM]>1){return (rPMgSy());} else if (aF[AGS]==1){return (rCPgSy());} else {return (rMPgSy());}}function rGSs(){if ((aF[AQ]>0)&&(mF==0)){if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else {return NOP;}} else if ((mF>0)&&(aF[AQ]+aF[ANV]>0)){return NOP;} else if ((mF==0)&&(fdT>0)){return (rPEgSy());} else if (aF[AMK]+aF[AWM]>1){return (rPMgSy());} else if (aF[AMK]==1){return (rJPgSy());} else {return (rGPgSy());}}function rWSs(){if ((aF[AQ]>0)&&(mF==0)){if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else {return NOP;}} else if ((mF>0)&&(aF[AQ]+aF[ANV]>0)){return NOP;} else if ((mF==0)&&(fdT>0)){return (rPEgSy());} else if (aF[AMK]+aF[AGS]>1){return (rPMgSy());} else {return (rWPgSy());}}function rQScrSy(){if (uo){if (fdT>0){return (rQSETc());} else if (mF>=THC){for (var i=0; i<TN; i+=2){if ((view[CCW[i]].color==LT)||(view[CCW[i+1]].color==LT)){return {cell:CCW[i+1],type:ANV};}}return {cell:1,type:ANV};} else if (mC!=LT){if ((mC==LCLR)||(sN[LCLR]>=TN-1)){return {cell:POSC,color:LT};} else {return (rQSTCTc());}} else if ((sN[LCLR]>=4)&&(sN[LT]==1)){for (var i=0; i<TN; i+=2){if ((view[CCW[i]].color==LT)||(view[CCW[i+1]].color==LT)){return {cell:CCW[i+4]};}}} else if (sN[LCLR]==TN){return {cell:0};} else {return (rQSATc());}} else {if ((fdT>0)&&(eT>0)&&(eT==aE[AQ])){return (rQSSTc());} else {return (rQSEvTc());}}return NOP;}function rQLsSy(){if ((sT[LCLR]<=2)&&(mF>1)&&(eT==0)){var artist=SPDAT[mF % RM];if ((artist!=0)&&(mF>=THP[artist])&&(aF[artist]<=1)){var tc=[6,2,4,5,3];for (var i=0; i<tc.length; i++){var c=CCW[xn+tc[i]];if (dOK[c]&&(view[c].food==0)){return {cell:c,type:artist};}}}}if ((eT==0)&&(fT==1)){if (view[CCW[xn+2]].food>0){return {cell:CCW[xn+2]};} else if ((view[CCW[xn+3]].food +view[CCW[xn+4]].food>0)&&(view[CCW[xn+1]].color!=LLSF)){return NOP;} else {return {cell:CCW[xn+2]};}} else if (dOK[CCW[xn+2]]&&dOK[CCW[xn+3]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn]]&&dOK[CCW[xn+7]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else {return NOP;}}function rQCNSy(){for (var i=0; i<TN; i++){var cell=view[CCW[i]];if (cell.ant&&cell.ant.friend&&cell.ant.type==ANV){if (i&1){if (dOK[CCW[i-1]]){return {cell:CCW[i-1]};} else if (dOK[CCW[i+1]]){return {cell:CCW[i+1]};} else if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else {return NOP;}} else {if (dOK[CCW[i+7]]){return {cell:CCW[i+7]};} else if (dOK[CCW[i+1]]){return {cell:CCW[i+1]};} else if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else {return NOP;}}}}return (rQCSy());}function rQCSy(){return NOP;}function rSLSy(){if ((eT==0)&&(fT==1)){if (view[CCW[xn]].food>0){return {cell:CCW[xn]};} else if (view[CCW[xn+7]].food +view[CCW[xn+6]].food>0){return {cell:POSC,color:LLSF};} else {return {cell:CCW[xn]};}} else if ((eT>0)&&view[CCW[xn+2]].ant&&!view[CCW[xn+2]].ant.friend){return {cell:POSC,color:LLSF};} else if ((fT>1)&&((view[CCW[xn+6]].ant&&view[CCW[xn+6]].ant.friend&&
(view[CCW[xn+6]].ant.food>0))||(view[CCW[xn+5]].ant&&view[CCW[xn+5]].ant.friend&&
(view[CCW[xn+5]].ant.food>0)))){return {cell:POSC,color:LLSF};} else {if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};}}return NOP;}function rNRSy(){if (view[CCW[xn+1]].ant&&view[CCW[xn+1]].ant.friend&&
(view[CCW[xn+1]].ant.type==mT)){if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else {return NOP;}} else if (view[CCW[xn+7]].ant&&view[CCW[xn+7]].ant.friend&&(view[CCW[xn+7]].ant.type==mT)){if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return NOP;}} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+2]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}}function rPPgSy(){if (aLF[AMK]+aLF[AGS] +aLF[AWM]>0){for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.food>0)){if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else if (dOK[CCW[i+3]]){return {cell:CCW[i+3]};} else if (dOK[CCW[i+5]]){return {cell:CCW[i+5]};}}}} else if (aF[mT]>0){return (rSPTc());}return (rPPgTc());}function rMPgSy(){if (aF[mT]>0){return (rSPTc());}return (rMPgTc());}function rGPgSy(){if (aF[mT]>0){return (rSPTc());}return (rGPgTc());}function rWPgSy(){if (aF[mT]>0){return (rSPTc());}return (rWPgTc());}function rCPgSy(){var phase=0;for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==AGS)){xn=i&6;phase=i&1;break;}}if ((phase==1)&&(mC==view[CCW[xn+7]].color)&&(view[CCW[xn]].color==view[CCW[xn+1]].color)){if (dOK[CCW[xn+3]]){return {cell:CCW[xn+3]};} else if (dOK[CCW[xn]]){return {cell:CCW[xn]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}} else {return {cell:CCW[xn+7],color:mC};}return NOP;}function rJPgSy(){var phase=0;for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==AMK)){xn=i&6;phase=i&1;break;}}if (phase==0){if (dOK[CCW[xn+7]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+1]]){return {cell:CCW[xn+1]};} else if (dOK[CCW[xn+4]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else if (dOK[CCW[xn+6]]){return {cell:CCW[xn+6]};} else {return NOP;}} else {return {cell:CCW[xn+3],color:mC};}return NOP;}function rPEgSy(){for (var i=0; i<TN; i++){if ((view[CCW[i]].food>0)&&dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}function rPMgSy(){for (var i=0; i<TN; i+=2){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type!=mT)){if (dOK[CCW[i+1]]&&!view[CCW[i+7]].ant&&!view[CCW[i+2]].ant&&!view[CCW[i+3]].ant){return {cell:CCW[i+1]};} else if (dOK[CCW[i+7]]&&!view[CCW[i+1]].ant&&
!view[CCW[i+6]].ant&&!view[CCW[i+5]].ant){return {cell:CCW[i+7]};}}}for (var i=1; i<TN; i+=2){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type!=mT)){if (dOK[CCW[i-1]]&&!view[CCW[i+6]].ant){return {cell:CCW[i-1]};} else if (dOK[CCW[i+1]]&&!view[CCW[i+2]].ant){return {cell:CCW[i+1]};}}}for (var i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return {cell:POSC,color:view[CCW[0]].color};}function rQSETc(){if (mC!=LT){return {cell:POSC,color:LT};}for (var i=0; i<TN; i++){if (view[CCW[i]].food>0){return {cell:CCW[i]};}}return NOP;}function rQSSTc(){for (var i=0; i<TN; i++){if ((view[CCW[i]].food>0)&&(dOK[CCW[i]])){return {cell:CCW[i]};}}return NOP;}function rQSTCTc(){if ((mC!=LCLR)&&(sN[mC]>=4)){if (sN[LT]==0){return {cell:POSC,color:LT};} else if (sN[LT]>=3){return {cell:POSC,color:LT};} else {for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LT)&&(view[CCW[i+2]].color!=LT)){return {cell:CCW[i+2],color:LT};}}return NOP;}} else if (sN[LT]==1){for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LT)&&(view[CCW[i+4]].color!=LCLR)){if (view[CCW[i+1]].color==LCLR){return { cell:CCW[i+1]};} else if (view[CCW[i+7]].color==LCLR){return { cell:CCW[i+7]};} else {return {cell:POSC,color:LT};}}}return {cell:POSC,color:LT};} else {return {cell:POSC,color:LT};}return NOP;}function rQSATc(){for (var i=0; i<TN; i++){if ((view[CCW[i]].color==LCLR)&&(view[CCW[i+1]].color==LCLR)&&(view[CCW[i+2]].color==LCLR)){if ((view[CCW[i+3]].color==LCLR)&&(view[CCW[i+4]].color==LCLR)){return {cell:CCW[i+2]};}return {cell:CCW[i+1]};}}for (var i=TN-1; i>=0; i--){if (view[CCW[i]].color!=LT){return {cell:CCW[i]};}}for (var i=0; i<TN; i++){if (view[CCW[i]].color!=LT){return {cell:CCW[i],color:LCLR};}}return {cell:0,color:LCLR};}function rQSEvTc(){if (sN[LT]>0){for (var i=0; i<TN; i++){if (view[CCW[i]].color==LT){xn=i&6;}}if ( dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]&&dOK[CCW[xn+2]]&&dOK[CCW[xn+3]] ){return {cell:CCW[xn+1]};} else if (dOK[CCW[xn+5]]&&dOK[CCW[xn+6]]&&dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]){return {cell:CCW[xn+7]};} else if (dOK[CCW[xn+3]]&&dOK[CCW[xn+4]]&&dOK[CCW[xn+5]]){return {cell:CCW[xn+4]};} else if (dOK[CCW[xn+5]]&&dOK[CCW[xn+6]]&&dOK[CCW[xn+7]]){return {cell:CCW[xn+6]};} else if (dOK[CCW[xn+1]]&&dOK[CCW[xn+2]]&&dOK[CCW[xn+3]]){return {cell:CCW[xn+2]};} else if (dOK[CCW[xn+7]]&&dOK[CCW[xn]]&&dOK[CCW[xn+1]]){return {cell:CCW[xn]};} else {for (var i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}} else {for (var i=0; i<TN; i++){if (dOK[CCW[i]]&&dOK[CCW[i+1]]&&dOK[CCW[i+2]]&&dOK[CCW[i+3]]&&dOK[CCW[i+4]]){return {cell:CCW[i+2]};}}for (var i=0; i<TN; i++){if (dOK[CCW[i]]&&dOK[CCW[i+1]]&&dOK[CCW[i+2]]){return {cell:CCW[i+1]};}}for (var i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}return NOP;}function rPPgTc(){if (sL[mC]==0){return {cell:1,color:mC};}for (var i=1; i<TN; i+=2){if (view[CCW[i]].color==mC){xn=i&6;break;}}var col1=(mC+1) % 8+1;if ((view[CCW[xn+5]].color==mC)&&(view[CCW[xn+3]].color==col1)&&(view[CCW[xn+7]].color!=col1)){xn=(xn+4) % 8;}if (view[CCW[xn+7]].color!=col1){return {cell:CCW[xn+7],color:col1};} else if (view[CCW[xn]].color!=col1){return {cell:CCW[xn],color:col1};}var col2=(mC+5) % 8+1;if (view[CCW[xn+3]].color!=col2){return {cell:CCW[xn+3],color:col2};} else if (view[CCW[xn+2]].color!=col2){return {cell:CCW[xn+2],color:col2};} else if (view[CCW[xn+5]].color!=mC){return {cell:CCW[xn+5],color:mC};} else if (view[CCW[xn+4]].color!=col2){return {cell:CCW[xn+4],color:col2};} else if (dOK[CCW[xn+5]]){return {cell:CCW[xn+5]};} else {return (rWgPTc());}}function rMPgTc(){switch (sT[mC]){case 9:var col=((mC+2) % 8)+1;return {cell:CCW[0],color:col};case 8:for (var i=0; i<TN; i++){var col=view[CCW[i]].color;if (col!=mC){if (i==0){return {cell:POSC,color:col};} else if ((i==1)&&dOK[CCW[i+3]]){return {cell:CCW[i+3]};} else if ((i==2)&&dOK[CCW[i+5]]){return {cell:CCW[i+5]};} else {return {cell:CCW[i-1],color:col};}}}break;case 7:return rWgPTc();case 6:for (var i=0; i<TN; i++){if (view[CCW[i]].color!=mC){if ((i==0)&&dOK[CCW[i+5]]){return {cell:CCW[i+5]};} else if ((i==1)&&dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else {return {cell:CCW[i],color:mC};}}}break;case 5:case 4:case 3:for (var i=0; i<TN; i++){if (view[CCW[i]].color!=mC){return {cell:CCW[i],color:mC};}}break;case 2:case 1:default:for (var i=TN-1; i>=0; i--){var col=view[CCW[i]].color;if ((col==mC)&&(sT[view[CCW[i+4]].color]==7)&&dOK[CCW[i+4]]){return {cell:CCW[i+4]};}if (sT[col]>=3){return {cell:POSC,color:col};}}var col=view[CCW[1]].color;if (view[CCW[0]].color!=col){return {cell:CCW[0],color:col};} else if (view[CCW[2]].color!=col){return {cell:CCW[2],color:col};}break;}return (rWgPTc());}function rGPgTc(){var col=0;for (var c0=view[CCW[0]].color; c0<view[CCW[0]].color+8; c0++){var c=(c0 % 8)+1;if (sN[c]==0){col=c;}}if (col==0){return (rWgPTc());}for (var i=0; i<TN; i++){if (sN[view[CCW[i]].color]>1){return {cell:CCW[i],color:col};}}return (rWgPTc());}function rWPgTc(){var col=((mC+6) % 8)+1;if (sT[mC]==9){return {cell:CCW[0],color:col};}var myRand=(view[CCW[0]].color+sT[view[CCW[2]].color]) % 3;
switch (myRand){case 0:for (var i=0; i<TN; i+=2){if (dOK[CCW[i]]){return {cell:CCW[i]};}}break;case 1:if (view[CCW[1]].color!=view[CCW[7]].color){return {cell:CCW[1],color:view[CCW[7]].color};} else if (view[CCW[5]].color!=view[CCW[3]].color){return {cell:CCW[5],color:view[CCW[3]].color};}break;case 2:if (view[CCW[5]].color!=view[CCW[3]].color){return {cell:CCW[5],color:view[CCW[3]].color};} else if (view[CCW[1]].color!=view[CCW[7]].color){return {cell:CCW[1],color:view[CCW[7]].color};}break;default:break;}for (var i=1; i<TN; i+=2){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return (rWgPTc());}function rSPTc(){for (var i=0; i<TN; i++){if (view[CCW[i]].ant&&view[CCW[i]].ant.friend&&
(view[CCW[i]].ant.type==mT)){if (dOK[CCW[i+4]]){return {cell:CCW[i+4]};} else if (dOK[CCW[i+3]]){return {cell:CCW[i+3]};} else if (dOK[CCW[i+5]]){return {cell:CCW[i+5]};} else if (dOK[CCW[i+2]]){return {cell:CCW[i+2]};} else if (dOK[CCW[i+6]]){return {cell:CCW[i+6]};} else if (dOK[CCW[i+1]]){return {cell:CCW[i+1]};}}}return NOP;}function rWgPTc(){for (var i=0; i<TN; i++){if (dOK[CCW[i]]){return {cell:CCW[i]};}}return NOP;}
```
Enjoy!
\*\* v1.0.1 Now compatible with strict-mode controllers.
\*\* v1.0.2 Fixes a disqualifying typo.
[Answer]
# HalfThere
```
if(view[4].ant.type==5&&view[4].food>1)
{
for(var i = 0; i<9; i++)
{
if(!view[i].ant)
{
return{cell:i,type: 1};
}
}
}
if(view[4].color != 3){
return {cell: 4, color: 3};
}
for(var i = 0; i<9; i++)
{
if(view[i].food==1)
{
return({cell:i})
}
}
var i, j
var orthogonals = [1, 3, 7, 5] // These are the non-diagonal cells
// Otherwise move to a white cell opposite a colored cell
for (i=0; i<4; i++) {
j = (i+2) % 4
if (view[orthogonals[i]].color === 1 &&
view[orthogonals[j]].color > 1 && !view[orthogonals[i]].ant) {
return {cell:orthogonals[i]}
}
}
// Otherwise move to one of the vertical or horizontal cells if not occupied
for (i=1; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i}
}
}
// Otherwise move to one of the diagonal cells if not occupied
for (i=0; i<9; i+=2) {
if (!view[i].ant) {
return {cell:i}
}
}
for(var i = 0; i<9; i++)
{
if(view[i].color==1)
{
return {cell:i};
}
}
for(var i = 0; i<9; i++)
{
if(view[i].ant==null)
{
return {cell:i};
}
}
```
This bot is half there...
Basically it just makes a line and goes in a straight line and kinda derps around if it sees another line.
# THIS IS A WORK IN PROGRESS BOT.
] |
[Question]
[
This is a code golf challenge I thought of with a mathematical bent. The challenge is to write the shortest code possible such that it is an open question whether or not the code terminates. An example of what I mean could be the following piece of python code, adapted from an anwser to [this](https://cs.stackexchange.com/questions/44869/what-are-the-simplest-examples-of-programs-that-we-do-not-know-whether-they-term) cs stackexchange question.
```
def is_perfect(n):
return sum(i for i in range(1, n) if n % i == 0) == n
n = 3
while not is_perfect(n):
n = n + 2
```
Mathematicians conjecture that there are no odd perfect numbers, but it has never been proven, so no one knows if this piece of code will ever terminate. Can you come up with other pieces of code (perhaps relying on other open problems like the Collatz conjecture, or the twin primes conjecture) that are shorter, but for which it is unknown whether or not they terminate?
Edit: Some people have brought up a good additional rule - The solutions to the question should be deterministic. Although it might be even more interesting if you could find shorter solutions using nondeterminism. In this case, the rule would be to find a snippet for which the probability of termination is unknown.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
!‘Ʋµ4#
```
[Try it online!](http://jelly.tryitonline.net/#code=MirigJjDhlDigJkK4oG54bikw4fCvw&input=)
### Background
This will terminate once it finds a fourth solution to [Brocard's problem](https://en.wikipedia.org/wiki/Brocard%27s_problem), i.e. a solution **n! + 1 = m²** with **(n,m) ≠ (4, 5), (5, 11), (7, 71)** over the positive integers. The implementation doesn't use floating point arithmetic, so it will only terminate if it does find a fourth solution or if **n!** can no longer be represented in memory.
*Brocard's problem was first used in [this answer](https://codegolf.stackexchange.com/a/97028/12012) by @xnor.*
### How it works
```
!‘Ʋµ4# Main link. No arguments. Implicit argument: 0
µ4# Convert the links to the left into a monadic chain and call it with
arguments k = 0, 1, 2, ... until 4 of them return 1.
! Factorial; yield k!.
‘ Increment; yield k! + 1.
Ʋ Squareness; return 1 if k! + 1 is a perfect square, 0 if not.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆẸ⁺‘ÆPµ6#
```
This will terminate once the sixth [Fermat prime](https://en.wikipedia.org/wiki/Fermat_number#Primality_of_Fermat_numbers) is found.
[Try it online!](https://tio.run/##ARsA5P9qZWxsef//w4bhurjigbrigJjDhlDCtTYj//8 "Jelly – Try It Online")
### How it works
```
ÆẸ⁺‘ÆPµ6# Main link. No arguments. Implicit argument: 0
µ6# Convert the links to the left into a monadic chain and call it with
arguments k = 0, 1, 2, ... until 6 of them return 1.
ÆẸ Convert [k] to the integer with that prime exponent factorization, i.e.,
into 2 ** k.
⁺ Repeat.
‘ Increment.
We've now calculated 2 ** 2 ** k + 1.
ÆP Test the result for primality.
```
[Answer]
## Pyth, 10 bytes
```
fP_h^2^2T5
```
Uses the conjecture that all [Fermat numbers](https://en.wikipedia.org/wiki/Fermat_number) `2^(2^n)+1` are composite for `n>4`.
```
f 5 Find the first number T>=5 for which
h^2^2T 2^(2^T)+1
P_ is prime
```
[Answer]
## Python, 36 bytes
```
k=n=1
while(n+1)**.5%1+7/k:k+=1;n*=k
```
Uses [Brocard's problem](https://en.wikipedia.org/wiki/Brocard%27s_problem):
>
> Is n!+1 a perfect square for any n≥8?
>
>
>
Computes successive factorials and checks whether they are squares and have `k>7`. Thanks to Dennis for 2 bytes!
This assumes Python continues to have accurate arithmetic for arbitrarily large numbers. In actual implementation, it terminates.
[Answer]
# MATL, 11 bytes
```
`@QEtZq&+=z
```
Terminates iff the [Goldbach conjecture](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) is false. That is, the program stops if it finds an even number greater than `2` that cannot be expressed as the sum of two primes.
```
` % Do...while
@ % Push iteration index k. Gives 1, 2, 3, ...
QE % Add 1 and multiply by 2. Gives 4, 6, 8, ...
tZq % Duplicate. Push all primes up to current k
&+ % Matrix with all pairwise additions of those primes
=z % Number of entries of that matrix that equal k. This is used as loop
% condition. That is, the loop continues if this number is nonzero
% Implicit end
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes in Brachylog's encoding
```
⟦cṗ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZckPd07//x8A "Brachylog – Try It Online") (will time out without doing anything visible, for obvious reasons)
Full program; if run with no input, searches for the first [Smarandache prime](http://mathworld.wolfram.com/SmarandachePrime.html), and outputs `true.` if and when it finds one. It's an open question as to whether any Smarandache primes exist. (Note that Brachylog's prime-testing algorithm, although it works in theory on arbitrarily large numbers, tends to run slowly on them; thus, if you're interested in finding Smarandache primes yourself, I recommend using a different language.)
## Explanation
```
⟦cṗ
⟦ Form an increasing range from 0 to {the smallest number with no assertion failure}
c Concatenate all the numbers that make up that range, in decimal
ṗ Assert that the result is prime
```
Brachylog operates on the decimal digits of a number whenever you try to treat it like a list, so "range" followed by "concatenate" is a very terse way to generate the sequence of Smarandache numbers (and then we filter that by primality; Brachylog's default full program behaviour will then force the first element of the resulting generator). The range has a leading zero, but fortunately, with this flow pattern, Brachylog removes the zero rather than failing.
Here's an example that finds the first Smarandache number that's equal to 6 (mod 11), as a demonstration of a similar program that terminates within 60 seconds rather than having unknown halting status:
```
⟦c{-₆~×₁₁&}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZcnVuo@a2uoOT3/U1AhEarX///@PAgA "Brachylog – Try It Online")
This would print `true.` as a full program, but I threw in the `Z` command line argument to actually print the number in question, giving a better demonstration that this general approach works.
[Answer]
# Perl, ~~50~~ ~~38~~ ~~36~~ ~~34~~ 33 bytes
```
$_=196;$_+=$%while($%=reverse)-$_
```
Explanation: 196 is a possible [Lychrel number](https://en.wikipedia.org/wiki/Lychrel_number) - a number that does not form a palindrome by repeatedly adding its reverse to itself. The loop continues until $n is equal to its reverse, which is as yet unknown for initial value 196.
```
25 + 52 = 77
```
which is not valid.
```
96 + 69 = 165
165 + 561 = 726
726 + 627 = 1353
1353 + 3531 = 4884
```
so none of the numbers in this sequence are valid.
Edit: Golfed it down by using an until loop instead of a for loop (somehow). Also, I had fewer bytes than I thought (I should probably look at my bytecount more carefully in the future).
Edit: Replaced `$n` with `$_` to save 2 bytes for the implied argument in `reverse`. I *think* this is as golfed as this implementation is going to get.
Edit: I was wrong. Instead of using `until($%=reverse)==$_` I can go while the difference is nonzero (i.e. true): `while($%=reverse)-$_`.
[Answer]
# Python, ~~30~~ 28 bytes
```
n=2
while 2**~-n%n**3-1:n+=1
```
This program will halt if and only if there is an integer n bigger than 1 such that 2^(n-1)-1 is divisible by n^3. To my knowledge it is not known whether any number with this property exists (if a number satisfying this property is prime, it is called a Wieferich prime of order 3 to base 2, and it is open whether any such prime exists).
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes
Will terminate when the 6th [Fermat prime](https://en.wikipedia.org/wiki/Fermat_number#Primality_of_Fermat_numbers) is found.
```
5µNoo>p½
```
**Explanation**
```
5µ # loop over increasing N (starting at 1) until counter reaches 5
Noo # 2^2^N
> # + 1
p½ # if prime, increase counter
```
[Answer]
## Haskell, 47 bytes
```
[n|n<-[1..],2*n==sum[d|d<-[2..n],n`mod`d<1]]!!0
```
Searching the first [quasiperfect number](https://en.wikipedia.org/wiki/Quasiperfect_number), which is a number `n` whose sum of divisors is `2*n+1`. Instead of adding 1, I exclude 1 from the list of divisors.
[Answer]
# Brain-Flak, ~~212~~ ~~208~~ 204 bytes
*This program uses a multiplication algorithm written by [MegaTom](https://codegolf.stackexchange.com/users/31203/megatom) and a non-square checker written by [1000000000](https://codegolf.stackexchange.com/users/20059/1000000000)*
[Try It Online](http://brain-flak.tryitonline.net/#code=KCgoKCkoKSgpKCkpe30pKXt7fSgoKHt9KCkpKTx7KCh7fSlbKCldKX17fT5bKCldKXsoe308KHt9PD4pKHs8KHt9WygpXSk-PD4oe30pPD59e308Pjx7fT4pPlsoKV0pfXt9KCh7fSgpKSl7KCh7fVsoKV08Pik8PikoKHsoe30pKHt9WygpXSl9e31bKHt9KV08Pikpe3t9e30oe308PikoPChbKCldKT4pfXt9KHt9KCkpeygoKDx7fXt9PD57fT4pKSl9e319e319&input=)
```
(((()()()()){})){{}((({}()))<{(({})[()])}{}>[()]){({}<({}<>)({<({}[()])><>({})<>}{}<><{}>)>[()])}{}(({}())){(({}[()]<>)<>)(({({})({}[()])}{}[({})]<>)){{}{}({}<>)(<([()])>)}{}({}()){(((<{}{}<>{}>)))}{}}{}}
```
This program starts at 8 and tests each number to see if n!+1 is a square number. It exits when it finds one. This is known as [Brocard's Problem](https://en.wikipedia.org/wiki/Brocard%27s_problem) and it is an open problem in mathematics.
[Answer]
# [Actually](http://github.com/Mego/Seriously), 16 bytes
```
1`;;pY)▒@D÷íu*`╓
```
[Try it online!](http://actually.tryitonline.net/#code=MWA7O3BZKeKWkkBEw7fDrXUqYOKVkw&input=)
This code terminates iff there is some composite number `n` such that `totient(n)` divides `n-1` ([Lehmer's totient problem](https://en.wikipedia.org/wiki/Lehmer%27s_totient_problem)).
Explanation:
```
1`;;pY)▒@D÷íu*`╓
1` `╓ first integer, starting with 0, where the following function leaves a truthy value on top of the stack:
pY * composite (not prime) and
; )▒ totient(n)
; @D֒u is in the list of divisors of n-1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to @Dennis! (use exponentiation instead of multiplication to avoid `Æṣ(0)`)
```
*ḂÆṣ=µ2#
```
Will return a list of zero and the smallest [odd perfect number](https://oeis.org/wiki/Odd_perfect_numbers), if any exist.
### How?
```
*ḂÆṣ=µ2# - Main link: no arguments
µ - monadic chain separation
2# - count up from implicit `n=0` and return the first 2 truthy results of
Ḃ - mod 2 -> n%2
* - exponentiate -> n**(n%2) (1 when n is even, n when n is odd)
Æṣ - sum of proper divisors of n**(n%2)
= - equals n? -> 1 if n is zero or both perfect and odd, else 0
```
[Answer]
# Python 2, 88 bytes
```
p=lambda n:all(n%x for x in range(2,n))
s=lambda n:0if p((10223*2**n)+1)else s(n+1)
s(0)
```
This code will terminate if 10223 is a Sierpiński number. 10223 is currently the smallest candidate that may or may not be a Sierpiński number, as of December 2013.
A Sierpiński number is a number `k` in which all numbers of the form `(k * 2^n) + 1` are composite.
[Answer]
# Pyth, 16 bytes
```
f!}1.u@,/G2h*3GG
```
Returns the first value for which the Collatz conjecture does not hold. As it is unknown whether the conjecture holds for all numbers, it is unknown whether this code will terminate.
[Answer]
# Haskell, 46 bytes
```
[n|m<-[1..],n<-[1..m],product[1..n]+1==m^2]!!3
```
Terminates if it finds the 4th solution to [brocard's problem](https://en.wikipedia.org/wiki/Brocard%27s_problem).
[Answer]
# Python, 92 bytes
This isn't winning any code golf competitions, and it requires infinite memory and recursion depth, but this is an almost perfect opportunity to plug [an interesting problem I asked on math stackexchange two years ago, that no Fibonacci number greater than 8 is the sum of two positive cubes](https://math.stackexchange.com/questions/789588/conjecture-only-one-fibonacci-number-is-the-sum-of-two-cubes). Funnily enough, it started as an code golf challenge idea, so I guess I've come full circle.
```
def f(i,j):
r=range(i)
for a in r:
for b in r:
if a**3+b**3==i:1/0
f(j,i+j)
f(13,21)
```
[Answer]
# Python 2, ~~123~~ ~~98~~ 92 bytes
```
p=lambda n,k=2:n<=k or n%k*p(n,k+1)
g=lambda n:[p(b)*p(n-b)for b in range(n)]and g(n+2)
g(4)
```
This code will terminate if the Goldbach conjecture does not hold for all even numbers (i.e. if all even numbers can be expressed as the sum of two primes). It has currently been tested for numbers up to 4\*10^18.
A huge amount of thanks to @Pietu1998 for shortening my code by a lot!
EDIT: Thanks to @JonathanAllan for shaving 6 bytes off my code!
[Answer]
# JavaScript (ES6), ~~104~~ 101 bytes
```
for(n=[6,9,p=1];!p;n=n.map((x,i)=>(q=n[n.length+~i],p|=x^q,c=q+x+c/10|0)%10).concat(c/10|0||[]))c=p=0
```
Uses the same method as the Perl answer: sets **n** to 196, then repeatedly adds **n** to its base 10 reverse until it's a palindrome in base 10. This would be shorter if JS supported arbitrary-precision numbers, but oh well.
[Answer]
# Python, 80 bytes
Terminates if the [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) is proven false. See [this question](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture).
```
n=2
while 1:
L=[];x=n
while~-n:1/(n not in L);L+=[n];n=(n/2,n*3+1)[n%2]
n=x+1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
*+3Ẓµ4#
```
[Try it online!](https://tio.run/##y0rNyan8/19L2/jhrkmHthop//8PAA "Jelly – Try It Online") (prints two elements, not 4, so that you can actually see it halt)
Prints the first four \$n\$ such that \$n^n+3\$ is prime. [It is not known whether four+ numbers with this property exist.](http://oeis.org/A166852) The first three are 2, 1036, and 2770.
## Explanation
```
*+3Ẓµ4#
4# Find the first four numbers with the following property:
µ (bracketing/grouping: place everything to the left inside the loop)
* {The number} to the power of {itself}
+3 plus 3
Ẓ is prime
```
[Answer]
# Pyth, 13 bytes
```
.u@,/G2h*5GG7
```
Like Steven H.'s answer, but saving a few bytes by using the 5n+1 problem instead
>
> Do the iterates of
> $$f(n)=\begin{cases}5n+1&\mbox{if }n\mbox{ is odd}\\\frac{n}{2}&\mbox{otherwise}\end{cases}$$
> starting with 7, cycle?
>
>
>
While it seems unlikely, the answer is unknown!
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
λEE›æ;5ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu0VF4oC6w6Y7NcivIiwiIiwiIl0=)
Finds the fifth Fermat Prime.
```
λ ;5ȯ # First 5 numbers where
EE› # 2^2^n + 1
æ # Is prime
```
[Answer]
# Python 2, 64 bytes
>
> A Lychrel number is a natural number that cannot form a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers.
>
>
>
No [Lychrel numbers](https://en.wikipedia.org/wiki/Lychrel_number) have been proven to exist in base ten. 196 is the smallest base ten Lychrel number candidate. It has been shown that if a palindrome exists (making 196 *not* a Lychrel number), it would have at least a billion (10^9) digits, because [people](https://en.wikipedia.org/wiki/Lychrel_number#196_palindrome_quest) have run the algorithm that long.
```
n=196
while 1:
x=str(n);r=x[::-1]
if x!=r:n=n+int(r)
else:1/0
```
[Answer]
# R, 30 bytes, arguable whether it is deterministic
```
while(any(sample(2,654,T)>1))1
```
R's default random number generator has equidistribution in 653 consecutive dimensions but it is not known to in 654 dimensions. Thus there may or may not be a sequence of pseudorandom numbers that sample the lowest element from a given vector 654 times in a row (here the vector `1:2`).
Since R's RNG is periodic (albeit with very long period), I claim that this *is* deterministic since it will eventually loop round to the start. Your opinions may differ, of course.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 13 bytes
```
7$h&fh&r2e=?i
```
[Try it online!](https://tio.run/##Kygtzqj8/99cJUMtLUOtyCjV1j7z/38A "Pushy – Try It Online")
This program attempts to find a solution to [Brocard's Problem](https://en.wikipedia.org/wiki/Brocard%27s_problem) - it will keep running until it finds a \$n \ge 8\$ such that \$ n! +1=m^2, m \in \mathbb{N} \$
[Answer]
# Python 3, 101 bytes
I know it's longer than many others, but I spent a lot of time seeing how short I could golf this.
This attempts to disprove [Euler's Sum of Powers Conjecture](https://en.wikipedia.org/wiki/Euler%27s_sum_of_powers_conjecture) for `k=6` (there exists no positive integer solution to the Diophantine equation `A^6+B^6+C^6+D^6+E^6==F^6`), for which no counterexample has been found.
```
R=[1]
while 1:R+=[R[-1]+1];eval(("[1/("+"+%s**6"*5+"!=%%s**6)%s]"%("for %s in R "*6))%(*"ABCDEF"*2,))
```
**In Python 2 (104 bytes):**
```
R=[1]
while 1:R+=[R[-1]+1];eval(("[1/("+"+%s**6"*5+"!=%%s**6)%s]"%("for %s in R "*6))%tuple("ABCDEF"*2))
```
**Less golfed:**
```
x=2
while 1:
R=range(1,x)
[1/(A**6+B**6+C**6+D**6+E**6!=F**6)for F in R for E in R for D in R for C in R for B in R for A in R]
x+=1
```
**Mathy version with no eval:**
```
R=range
x=2
while 1:
for i in R(x**6):1/(sum(map(lambda x:x**6,[1+(i%x**-~j/x**j)for j in R(6)]))-i%x-1)
x+=1
```
Alternate reference: [Euler's Sum of Powers Conjecture - MathWorld](http://mathworld.wolfram.com/EulersSumofPowersConjecture.html)
[Answer]
# Python, 68 bytes
```
n=2
while"".join(str((i+2)**n)[0]for i in range(8))!="23456789":n+=1
```
[**Try it online**](https://repl.it/ElDw)
Tries to answer one of [Gelfand's Questions](http://mathworld.wolfram.com/GelfandsQuestion.html).
>
> 2. Will the row "23456789" ever appear for n>1? None does for n<=10^5. ...
>
>
>
[Answer]
# Clojure, 154 bytes
```
(loop[x 82001](if(= 0(reduce +(map{true 1 false 0}(for[y(range 3 6)](true?(for[z(str(range 2 y))](.indexOf z(Integer/toString x y))))))))x(recur(inc x))))
```
Checks if there's a number above 82,000 that only contains 0's and 1's for base 2 all the way to base 5. In other words, it checks if there's another number in [this sequence](http://oeis.org/A146025).
In that special group, there are only 3 numbers: `0`, `1` and `82,000`. There are no more numbers that follow that rule that are less than approximately `3*10^19723`.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 14 bytes
```
27*²0`ŕĐ₫+Đ₽¬ł
```
Port of [mbomb007's answer](https://codegolf.stackexchange.com/a/97267/77078).
] |
[Question]
[
Write a program that takes in a non-empty string of the digits 0 through 9 and prints how they would be shown on a [seven-segment display](http://en.wikipedia.org/wiki/Seven-segment_display) using slashes (`/`, `\`).
These are the precise digit shapes:
```
/\
\ \
\/
\
\
/\
/
\/
/\
/\
/
\
\/\
/
\/\
/
/
\/\
\/
/\
\
/\
\/\
\/
/\
\/\
/
```
When one digit occurs after another, they are chained diagonally up and to the right, with a diagonal space in between. So, for example, `203` would become this:
```
/\
/\
/\ /
\ \
/\ \/
/
\/
```
Note that the `1` character takes up the same amount of space as the others. The two lines of the `1` are on the right side of the display, not the left.
So `159114` would become this:
```
\
\/\
\
\
\
\
/\
\/\
/ /
\/\
\ /
\
```
There may be any amount and combination of leading/trailing newlines or spaces in the output as long as the digits are in the correct position with respect to one another.
So for `159114`, this would also be valid:
```
\
\/\
\
\
\
\
/\
\/\
/ /
\/\
\ /
\
```
Take input from stdin or the command line, or write a function that takes in a string. Print the result to stdout or you can return it as a string if you write a function.
Any non-empty string of the digits 0 through 9 should work, including single digits strings (e.g. `8`) and strings with leading zeros (e.g. in `007`, the zeros *do* need to be printed).
**The shortest code in bytes wins.**
[Answer]
# Python 3, ~~189~~ ~~183~~ 174 bytes
```
s="a%sa"%input()
while s[1:]:b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")];S=len(s)*" ";print(S+a+b,c+d+"\n"+S+e+f+g);*s,_=s
```
The compression looks okay to me, but I'm having trouble coming up with a good way of ditching the seven variables...
Thankfully the spec is fairly relaxed on whitespace rules, because there's a lot of leading/trailing whitespace.
**Expanded:**
```
s="a%sa"%input()
while s[1:]:
b,a,c,d,e,f,g=[c*(ord(n)>>int(s[~(n>"Ͱ")],16)&1)or" "
for c,n in zip("\/"*4,"ΟϭŅͭͱͼϻ")]
S=len(s)*" "
print(S+a+b,c+d+"\n"+S+e+f+g)
*s,_=s
```
## Explanation
The segment positions represented by the variables are:
```
ab /\
efg /\
ab cd /\ /
efg \ \
ab cd /\ \/
efg /
cd \/
```
Each segment is encoded by a single 2-byte Unicode character. For example, `ϻ` encodes `g`'s segment like so:
```
bin(ord("ϻ")) = bin(1019) = "0b1111111011"
^^^^^^^^^^
9876543210
```
Indeed, `2` is the only digit to not use the bottom-right segment of a seven-segment display.
[Answer]
# C, 1098 345 323 319 bytes
First Second Third attempt. Finally decided to ditch the screen buffer to save a few bytes. This program takes a parameter of digits and prints the digits in 7-segment format.
First time participant. Just for fun. Be gentle.
```
a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977},i,j,k,n,m;char*c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
main(w,char**v){f(i,n=strlen(v[1]))f(k,(m=n-i-1)?2:3){f(j,m*2)P(32);f(w,3)Q(m,k,w);if(!k&&i)f(w,2)Q(m+1,2,w+1);P(10);}}
```
Expanded, warning free:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[]={100489,2056,98569,67849,2440,67969,100737,2057,100745,67977};
char *c=" /\\";
#define f(q,r) for(q=0;q<(r);q++)
#define P(w) putchar(w)
#define Q(d,i,j) P(c[a[v[1][d]-48]>>(i*3+j)*2&3])
int main(int w, char **v)
{
int i,j,k,n,m;
f(i,n=strlen(v[1])) {
m=n-i-1;
f(k,m?2:3) {
f(j,m*2) P(32);
f(w,3) Q(m,k,w);
if (!k&&i) f(w,2) Q(m+1,2,w+1);
P(10);
}
}
}
```
[Answer]
# JavaScript, ~~192~~ ~~178~~ ~~167~~ 162 bytes
```
f=x=>{n=b="\n";for(k in x)for(i=0;i<8;)b+=("î\xA0Öô¸|~àþü".charCodeAt(x[k])>>i++&1?i%2?"/":"\\":" ")+(i%3?"":n+" ".repeat(k));return b.split(n).reverse().join(n)}
```
Usage: `f("1337");` will return
```
/\
\
/\
/\
/\ /
/\
\ /
\
```
It uses features of ES6 and may have some implementation dependent behavior due to omission of semicolons and parentheses and such, but it works in Firefox.
**Expanded:**
```
f=x=>
{
n = b = "\n";
for (k in x)
for (i=0; i<8;)
b += ("î\xA0Öô¸|~àþü".charCodeAt(x[k]) >> i++ & 1? i%2? "/" : "\\" : " ") + (i%3? "" : n+" ".repeat(k));
return b.split(n).reverse().join(n)
}
```
**Explanation:**
`l` is an array containing 10 single byte characters which correspond to the shape of each digit. For example, the digit 0 is represented by the character `î`:
```
/\ 11
\ \ --> 101 --> 11 101 110 = î
\/ 011
```
The input characters are used as keys to the array holding their shape representing counterparts, which get read bit by bit.
[Answer]
## Perl - 103 Bytes
```
#!perl -n
print$i+$%2?U^(u,$i--%2?v9:z)[$i<4+$%2&vec$_,4*$-3-$i,1]:$/.!($i=$--)
while$+=2*y/0-9/wPkz\\>?p~/
```
The above contains 6 unprintable characters (the source can be downloaded at **[Ideone](http://ideone.com/fMOkHo)**), and is equivalent to the following:
```
#!perl -n
print$i+$^F%2?U^(u,$i--%2?v9:z)[$i<4+$^F%2&vec$_,4*$^F-3-$i,1]:$/.!($i=$^F--)
while$^F+=2*y/0-9/wPkz\\>?p\177~/
```
Each `^F` may be replaced by a literal character 6 (ACK), and `\177` replaced by character 127 (DEL).
The shebang is counted as 1, the second newline is uncessary. Input is taken from stdin.
---
**Sample Usage**
```
$ echo 0123 | perl seven-slash.pl
/\
/\
/\ /
/
\ \/
\
/\
\ \
\/
$ echo 456789 | perl seven-slash.pl
/\
\/\
/\ /
\/\
/\ \/
\
/
\/\
/ \/
\/\
\ /
\/\
```
---
**Explanation**
Output is generated one byte at a time. Each character is transliterated, and this is then interpreted as a bit array using `vec`. The bits are stored in the following way:
```
/\ 56
\/\ 234
/\ \/ -> 56 01
\/\ 234
\/ 01
```
Output alternates between 3 and 5 slashes, so that bits `56` spills over into `01` of the next digit. Bit `7` is not used.
[Answer]
# CJam, ~~77~~ ~~71~~ ~~70~~ ~~69~~ ~~63~~ 62 bytes
```
r_,5*_Sa*a*\{~"÷Ðëúܾ¿ðÿþ"=i2bS"\/"4*W<+.*3/..e>2fm>2m>}/Wf%N*
```
All characters are printable, so copy and paste should work just fine.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r_%2C5*_Sa*a*%5C%7B~%22%C3%B7%C3%90%C3%AB%C3%BA%C3%9C%C2%BE%C2%BF%C3%B0%C3%BF%C3%BE%22%3Di2bS%22%5C%2F%224*W%3C%2B.*3%2F..e%3E2fm%3E2m%3E%7D%2FWf%25N*&input=0123456789).
### Idea
We start by examining the number of digits **n** in the input and pushing a square of spaces big enough to cover the output. In the implementation, this square will be encoded as a two-dimensional array of one-character strings.
A square of length **2n+1** would be just right (i.e., no surrounding whitespace) for a straightforward implementation, but we'll use one of length **5n** to save a couple of bytes. Thankfully, surrounding whitespace is allowed.
If we reverse the lines of the seven slash representation of **8**, we obtain the following:
```
\/
\/\
/\
```
The representation of all digits can be encoded as an 8-bit integer, where the ith bit is **0** iff the ith character should get replaced with a space. For the digits **0** to **9**, the resulting integers are
```
247 208 235 250 220 190 191 240 255 254
```
which correspond to the following ISO-8559-1 characters:
```
÷Ðëúܾ¿ðÿþ
```
For each digit in the input, after selecting the corresponding 8-bit integer, we repeat the ith character of the representation of **8** exactly **ai** times, where **ai** is the ith bit of the integer. This pushes an array of strings of either one or zero characters. By dividing this array into chunks of length 3, we obtain an array where each element corresponds to a line of the representation.
Now, we compute the vectorized maximum of the strings that represent the square and the strings that represent the digit. The strings `/` and `\` are bigger than the string , so they will replace the spaces in the square. The empty string, however, is smaller than the string , so empty strings in the digit representation will preserve the spaces in the square.
We now rotate the rows and columns by two units to place the following digit representation in the proper part of the square and repeat the process for the remaining digits in the input.
Finally, we reverse each row and insert a linefeed between the individual rows.
### Code
```
r_, e# Read a token from STDIN and push the length of a copy.
5*_ e# Multiply the length by 5 and push a copy.
Sa* e# Repeat the array [" "] that many times.
a* e# Repeat the array [[" " ... " "]] that many times.
\{ e# For each character C in the input:
~ e# Push eval(C), i.e., the digit the character represents.
"÷Ðëúܾ¿ðÿþ"
e# Push the encodings of all 10 seven slash representations.
= e# Select the proper one.
i2b e# Push the resulting characters code point in base 2, i.e., its bits.
S e# Push " ".
"\/"4* e# Push "\/\/\/\/".
+W< e# Concatenate and eliminate the last character.
.* e# Vectorized repetition.
e# For the digit 5, e.g., we have [1 0 1 1 1 1 1 0] and " \/\/\/\" on
e# the stack, so .* yields [" " "" "/" "\" "/" "\" "/" ""].
3/ e# Divide the representation into chunks of length 3, i.e., its lines.
..e> e# Compute the twofold vectorized maximum, as explained above.
2fm> e# Rotate each line to characters to the right.
2m> e# Rotate the lines two units down.
}/
Wf% e# Reverse each line.
N* e# Place linefeeds between them.
```
The last rotations would mess up the output if the square's side length was smaller than **2n+3**. Since **5n ≥ 2n+3** for all positive integers **n**, the square is big enough to prevent this.
[Answer]
# C#, 360 355 331 bytes
Hi there, first attempt at code-golf. Hope this doesn't score too badly for a C#-entry.
```
string p(string n){var l=new string[n.Length*2+1];var i=l.Length-1;for(;i>0;){var x=@"/\\ \\/ \ \ /\ / \//\ /\ / \\/\ / \/\ // \/\\//\ \ /\\/\\//\\/\ /".Substring((n[0]-48)*7,7);for(var j=i-3;j>=0;){l[j--]+=" ";}l[i--]+=" "+x[5]+x[6];l[i--]+=""+x[2]+x[3]+x[4];l[i]+=""+x[0]+x[1];n=n.Remove(0, 1);}return string.Join("\n",l);}
```
Usage: `p("159114");` will return
```
\
\/\
\
\
\
\
/\
\/\
/ /
\/\
\ /
\
```
**Expanded:**
```
string p(string n)
{
var l = new string[n.Length * 2 + 1];
var i = l.Length - 1;
for (; i > 0; )
{
var x = @"/\\ \\/ \ \ /\ / \//\ /\ / \\/\ / \/\ // \/\\//\ \ /\\/\\//\\/\ /".Substring((n[0] - 48) * 7, 7);
for (var j = i - 3; j >= 0; )
{
l[j--] += " ";
}
l[i--] += " " + x[5] + x[6];
l[i--] += "" + x[2] + x[3] + x[4];
l[i] += "" + x[0] + x[1];
n = n.Remove(0, 1);
}
return string.Join("\n", l);
}
```
[Answer]
## python 2, ~~317~~ ~~298~~ ~~278~~ 273.15
```
def f(s):
r=range;n=len(s)*2;l=[[' ']*-~n for x in r(-~n)]
for x in r(0,n,2):
for i,[d,y,c]in enumerate(zip('0112012','1021012',r'\\\\///')):l[n-2-x+int(y)][x+int(d)]=[' ',c][('%7s'%(bin(ord('}(7/jO_,\x7fo'[map(int,s)[x/2]])))[2:])[i]=='1']
for x in l:print''.join(x)
```
I considered 4-spaces as tabs while counting.
Uncompressed and readable:
```
def f(s):
r=['1111101','0101000','0110111','0101111','1101010','1001111','1011111','0101100','1111111','1101111']
''.join(map(lambda x:chr(eval('0b'+x)),r))
n=len(s)*2
l=[[' ']*(n+1) for x in xrange(n+1)]
shifts=[(0,1,'\\'),(1,0,'\\'),(1,2,'\\'),(2,1,'\\'),(0,0,'/'),(1,1,'/'),(2,2,'/')]
for x in xrange(0,n,2):
y=n-2-x
for i,[dx,dy,c] in enumerate(shifts):
l[y+dy][x+dx]=c if r[map(int,s)[x/2]][i]=='1' else ' '
return '\n'.join(''.join(x) for x in l)
```
[Answer]
# KDB(Q), ~~172~~ 136 bytes
```
{d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;
-1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}
```
# Explanation
1) Create `d` map with all the digits' shapes.
2) Pad the matrix with extra zeros and add them together. i.e. "01"
```
0 0 0 0 2 0
0 0 0 0 0 2
1 2 0 0 0 + 0 0 0 0 0
2 0 2 0 0 0
0 2 1 0 0 0
```
3) Use the index to map `" /\"` and print with `-1`.
# Test
```
q){d:(9#1 2 0 2)*/:-9#'0b vs'427 136 403 409 184 313 315 392 443 441;-1" /\\"{m+(c,/:y),c:(count[m:0 0,x,\:0 0]-3)#0}/[3 3#/:d"J"$'(),x];}"0123456789"
/\
\/\
/\ /
\/\
/\ \/
\
/
\/\
/ \/
\/\
\ /
\/\
/\
/\
/\ /
/
\ \/
\
/\
\ \
\/
```
I'm sure this can be shorter!!
Thanks @h.j.k.
[Answer]
# Pip, 122 + 1 = 123 bytes
Uses the `-n` flag. Takes input via command-line argument.
```
l:$.(J"\/ "@^(A_TB3M"⮐䫶ヷ䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma)z:2*#ap:sXz+2RLz+2Fi,5Fj,z{c:[4-ii]//2+j(pc@0c@1):(lij)}RVp
```
The characters in the UTF-8 string have the following code points: `11152, 19190, 12535, 12547, 17651, 11575, 11557, 12629, 11071, 11089`.
Slightly ungolfed:
```
t:[120022001 222022202 122012021 122012201 220012202 120212201 120212001 122022202 120012001 120012201]
l:$.({J"\/ "@^[[email protected]](/cdn-cgi/l/email-protection)<>2}Ma)
z:2*#a+2
p:sXzRLz
Fi,5
Fj,2*#a {
x:i//2+j
y:(4-i)//2+j
p@y@x:l@i@j
}
P RVp
```
The basic strategy is to find each number's constituent characters and then skew them appropriately. For example, for `8`, we want this (spaces represented by dots):
```
/.
\\
/.
\\
/.
```
which will turn into this:
```
.
/\.
\/\.
\/
```
The nice feature of this strategy is that multiple pre-skewed numbers can simply be concatenated side by side.
Now, we can encode `/.\\/.\\/.` in base 3 as `1200120012`. Then we can convert this to decimal and treat it as a UTF-8 code point.
The expression `J"\/ "@^(A_TB3M"⮐䫶ヷ䓳ⴷⴥㅕ⬿⭑")@_.2<>2Ma` gets the pre-skewed data by the following process:
```
Ma Map this lambda function to each character in input:
(A_TB3M"...") Create list of the code points of each character in UTF-8
string, converted to base 3
@_ Index into that list using the input character
.2 Concatenate 2 to the end of the base-3 value (all of the
pre-skewed number grids end in 2, i.e. space)
^ Split the number into a list of its digits
"\/ "@ Index into this string with those digits, giving a list
of slashes & spaces
J Join the list together into a string
<>2 Group string two characters at a time
```
Once we have concatenated these strings side-by-side using `$.`, we then create a grid of spaces (2\**n*+2 square), loop through the pre-skewed grid, and replace the corresponding spaces in the post-skewed grid with the appropriate characters. To see it happening, one can modify the code to print each stage and pause for user input:
![Algorithm in process](https://i.stack.imgur.com/mm6DA.gif)
The grid is actually built upside down, because that seemed to make the math easier.
I'm sure there's better algorithms to use. But I wanted to come up with my own idea rather than copying somebody else's.
[More on Pip](http://github.com/dloscutoff/pip)
[Answer]
## Brainfuck - 719 bytes
For historical context only, credits to Daniel B Cristofani. I'm not exactly sure when this was created, but it is available from the [Internet Archive](https://web.archive.org/web/20030409094901/http://www.hevanet.com/cristofd/brainfuck/) as early as May 9th, 2003.
The output for `9` is different than in the problem description.
```
>>>>+>+++>+++>>>>>+++[
>,+>++++[>++++<-]>[<<[-[->]]>[<]>-]<<[
>+>+>>+>+[<<<<]<+>>[+<]<[>]>+[[>>>]>>+[<<<<]>-]+<+>>>-[
<<+[>]>>+<<<+<+<--------[
<<-<<+[>]>+<<-<<-[
<<<+<-[>>]<-<-<<<-<----[
<<<->>>>+<-[
<<<+[>]>+<<+<-<-[
<<+<-<+[>>]<+<<<<+<-[
<<-[>]>>-<<<-<-<-[
<<<+<-[>>]<+<<<+<+<-[
<<<<+[>]<-<<-[
<<+[>]>>-<<<<-<-[
>>>>>+<-<<<+<-[
>>+<<-[
<<-<-[>]>+<<-<-<-[
<<+<+[>]<+<+<-[
>>-<-<-[
<<-[>]<+<++++[<-------->-]++<[
<<+[>]>>-<-<<<<-[
<<-<<->>>>-[
<<<<+[>]>+<<<<-[
<<+<<-[>>]<+<<<<<-[
>>>>-<<<-<-
]]]]]]]]]]]]]]]]]]]]]]>[>[[[<<<<]>+>>[>>>>>]<-]<]>>>+>>>>>>>+>]<
]<[-]<<<<<<<++<+++<+++[
[>]>>>>>>++++++++[<<++++>++++++>-]<-<<[-[<+>>.<-]]<<<<[
-[-[>+<-]>]>>>>>[.[>]]<<[<+>-]>>>[<<++[<+>--]>>-]
<<[->+<[<++>-]]<<<[<+>-]<<<<
]>>+>>>--[<+>---]<.>>[[-]<<]<
]
[Enter a number using ()-./0123456789abcdef and space, and hit return.
Daniel B Cristofani (cristofdathevanetdotcom)
http://www.hevanet.com/cristofd/brainfuck/]
```
[Answer]
# Perl, 270 bytes
I really shouldn't have wasted my time on this.
```
$e="\\";$g=" ";$_=reverse<>;$l=length;push@a,(119,18,107,91,30,93,125,19,127,95)[$1]while/(.)/g;for($i=0;$i<=$l;$i++){$j=2*($l-$i);$b=$a[$i];$c=$i&&$a[$i-1];print" "x$j,$b&1?"/":$g,$b&2?$e:$g,$g,$c&32?$e:$g,$c&64?"/":$g,"
"," "x$j,$b&4?$e:$g,$b&8?"/":$g,$b&16?$e:$g,"
"}
```
[Answer]
# JavaScript (*ES6*), 191 ~~206~~
Run snippet in Firefox to test.
```
F=m=>(
a=' \\/ /\\/\\ / /\\ \\\\ \\'.match(/.../g),
o=f='',r=' ',
[for(d of m)(
n=1e3+'¯B\x91ÿ$ê\x86A\x87ë'.charCodeAt(d)+'', // here there are 3 valid characters tha the evil stackoverflow editor just erase off, so I had to put them as hex escape
o='\n'+f+' '+a[n[2]]+'\n'+r+a[n[1]]+o,
r=f+a[n[3]],
f+=' ')],
r+o
)
//TEST
go=_=>O.innerHTML =(v=I.value)+'\n'+F(v)
go()
```
```
<input id=I value='0123456789'><button onclick='go()'>-></button>
<pre id=O></pre>
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~149~~ 146 bytes
Contains a few unprintable characters which are escaped in the code below.
```
s=>(g=([d,...s],p='',q=p)=>d?g(s,p+q,88)+(p+=q?`10 65
${p}234
`:865).replace(/\d/g,n=>'\\/ '[Buffer("w\x11k;\x1d>~\x13\x7f?")[n>4?s[0]:d]>>n&1?n&1:2]):s)(0+s)
```
[Try it online!](https://tio.run/##bY5Pa4MwHEDv3srOgyKj/oJZNPVPU0cS6NdQoWKirJUYTbcdxraP7jyXHt7lvcu7NJ@Na@d3e3s1o9JLxxfHBfQcSoUJIa7GlgcBnrhFXCjZg8M2nDBjKAQb8kmeabzNM@/l2/7sk9Q7FyzPEJm1HZpWQ1SpqMeGi6Cqom1Qnj66Ts/gf22ub8/i9@lP@qg0IpWujOtC1UKYHZUrxb5GhUMQhw4t7WjcOGgyjD104DMfIe/O0SQ5PNLZkdL0QYjpepvlB3Zc4/IP "JavaScript (Node.js) – Try It Online")
### How?
This recursively builds the following pattern (here with 4 digits):
```
88888810 65
888888234
888810 65
8888234
8810 65
88234
10 65
234
865
```
Where:
* \$8\$ is a padding character
* other even digits are replaced with either `\` or a space
* odd digits are replaced with either `/` or a space
Leading to:
```
______/\ \/
______\/\
____/\ \/
____\/\
__/\ \/
__\/\
/\ \/
\/\
_\/
```
[Answer]
# Java 8, 341 bytes
```
n->{int i=n.length*2,j=i+1,k=0,t;String l[]=new String[j],x;for(;j-->0;l[j]="");for(;i>0;l[i--]+=" "+x.substring(5,7),l[i--]+=x.substring(2,5),l[i]+=x.substring(0,2))for(x="/~~ ~~/ ~ ~ /~ / ~//~ /~ / ~~/~ / ~/~ // ~/~~//~ ~ /~~/~~//~~/~ /".replace('~','\\').substring(t=(n[k++]-48)*7,t+7),j=i-2;j-->0;)l[j]+=" ";return"".join("\n",l);}
```
Port of [*@Shion*'s C# .NET answer](https://codegolf.stackexchange.com/a/51455/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##lVHLbsIwELzzFStfYhPnQYACioxU9VwuPUIOJgRwCA5yDAUh8uvUDqmEqvZQyfKuZzxr72zOT9wrD5nMV7t7WvCqgncu5LUDIKTO1JqnGczsEeBDKyE3kOJ0y9U8AUlig986Zqs01yKFGUhgcJfe9GrUIJj0i0xu9LYb0ZwJt0d3LKQ6bisV84TJ7LMtPM8Teo7XpcJx7nnTMC4MwhAiD0w0iPC8xGUIkHv2q@OyapR4SEeEfpPPRESHDfEDDmlEiK16Ziioa6jrAGqwK6jBpIENTVYHFgQbgiY03ONme2o45KvsUBizsFM71FksHPL0nmZYzneum3iDMemOqHbNf40hXtS2Smyvti9Ascr0UUmE/LwUEqOFRLQg8e0eW6MPx2VhjG79PpViBXszL9xamAAn7bAulc72fnnU/sFQupBY@ilGUdhHvi7fzAhfleIXTEgzxr8VveGk1xv8VxT1B8OX0XgS/iq8dW73Lw)
**Explanation:**
```
n->{ // Method with character-array parameter and String return-type
int i=n.length*2, // Two times the length of the input array
j=i+1, // Index integer, starting at `i+1`
k=0,t; // Temp integers
String l[]=new String[j],// String-array for the rows, default filled with `null`
x; // Temp-String
for(;j-->0;l[j]=""); // Replace all `null` with empty Strings
for(;i>0 // Loop `i` downwards in the range [`n.length*2`, 0)
; // After every iteration:
l[i--]+= // Append the row at index `i` with:
// (and decrease `i` by 1 afterwards with `i--`)
" " // A space
+x.substring(5,7),// And the 6th and 7th characters of temp-String `x`
l[i--]+= // Append the row at index `i` with:
// (and decrease `i` by 1 afterwards with `i--`)
x.substring(2,5), // The 3rd, 4th and 5th characters of temp-String `x`
l[i]+= // Append the row at index `i` with:
x.substring(0,2)) // The 1st and 2nd characters of the temp-String `x`
for(x="/~~ ~~/ ~ ~ /~ / ~//~ /~ / ~~/~ / ~/~ // ~/~~//~ ~ /~~/~~//~~/~ /".replace('~','\\')
// String containing all digit-parts
.substring(t=(n[k++]-48)*7,t+7),
// and take the substring of 7 characters at index
// `n[k]` as integer multiplied by 7
j=i-2;j-->0;) // Inner loop `j` in the range (`i`-2, 0]
l[j]+=" "; // And append the rows at index `j` with two spaces
return"".join("\n",l);} // Return the rows delimited with new-lines
```
] |
[Question]
[
# The Challenge
Write a complete program that writes twice as many bytes to standard output as the length of the program.
# Rules
* The program must write ASCII characters to the standard output.
* The contents of the output doesn't matter.
* The output, measured in bytes, must be *exactly* twice the length of the program, also measured in bytes, unless you fulfill the bonus.
* **Any trailing newline is included in the output's byte count.**
# Bonus
Your program can optionally take a number, *`n`*, as input. If so, the output must be exactly `n * program length` bytes. You can assume that *n* will always be a positive integer. If no input is provided, *`n`* must default to 2.
If you do this, you can subtract 25 bytes from your score.
Shortest program wins.
# Restrictions
* No standard loopholes.
* The program must be at least 1 byte long.
* No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.
* Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.
Lowest score (program length in bytes - bonus) wins.
The shortest answer for each language wins *for that language*.
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=59436,OVERRIDE_USER=41505;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]
# [HQ9+](http://esolangs.org/wiki/HQ9%2B), 2 bytes
```
QQ
```
outputs
```
QQQQ
```
I think it is not forbidden here.
[Answer]
# Shakespeare, 768
Yeah, Shakespeare's not much of a golfing language. Outputs 1,536 spaces.
```
Rosencrantz and Guildenstern: A Series of Tedious Events.
Rosencrantz, a count of extraordinary determination.
Guildenstern, a spacy character.
Act I: The Long Conversation
Scene I: A Tortured Friendship
[Enter Rosencrantz and Guildenstern]
Rosencrantz:
You are a gentle, noble, valiant, loyal, loving companion.
Guildenstern:
You are nothing!
Scene II: Asking the Hard Questions
Rosencrantz:
Speak your mind.
Guildenstern:
You are as fair as the sum of yourself and a daisy. Are you as
daring as the sum of a big, bold, fiery, feisty, rough, rowdy,
ham-fisted, hawk-eyed, broad-shouldered, bright-eyed lad and a
large, yellow, vicious, hairy, wild, scary, long-tailed,
sharp-clawed, small-eared lion?
Rosencrantz:
If not, let us return to scene II.
```
# Edit: 256
Okay, I'll actually golf it. Note that the above does not compile in any existing Shakespeare implementation because I wrote it painstakingly by hand (but am prepared to defend its correctness.)
The below translates to C with one warning in spl-1.2.1, and outputs 512 spaces:
```
Ummm.Ajax,1.Puck,2.Act I:I.Scene I:A.[Enter Ajax and Puck]Ajax:You old old old old old cow.Puck:You are zero!Scene II:B.Ajax:Speak thy mind.Puck:You are the sum of you and a red cat.Are you as big as the square of me?Ajax:If not, let us return to scene II.
```
[Answer]
# Recall, 17 bytes
```
................!
```
16 NOOPs. Then the debugger `!` is invoked and dumps the memory to the console. The memory is empty, but the header is 34 bytes long:
```
-- STATE DUMP --
----------------
```
Try it [here](http://turbo.github.io/Recall/index.html?code=................!).
[Answer]
# Mathematica REPL, 1 byte
```
#
```
Prints `#1`.
[Answer]
# CJam, -17 bytes
```
r2e|i8,*
```
The source code is **8 bytes** long and qualifies for the **-25 bytes** bonus.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r2e%7Ci8%2C*).
### How it works
```
r e# Read a token from STDIN.
2 e# Push 2.
e| e# Logical OR; keep the token if it's not empty, 2 otherwise.
i e# Cast to integer.
8, e# Push [0 1 2 3 4 5 6 7].
* e# Repeat the array the corresponding number of times.
```
[Answer]
## Python 2.6, 10
```
print`-.1`
```
Prints `-0.10000000000000001`, which is 20 chars.
Note that the string repr shows more precision. `print-.1` just gives `-.1`, and `print.1/3` gives `0.0333333333333` for only 13 digits of accuracy.
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 10 bytes
```
4 56111240
```
This compiles to the Befunge program (found by brute force)
```
9k.@
```
which produces the following 20 bytes when run (tested in CCBI, note the trailing space):
```
0 0 0 0 0 0 0 0 0 0
```
Being unfamiliar with Befunge 98, I had to double check the spec a few times for this one:
* `k` seems pretty broken to me, executing one more time than intended due to the IP moving into the repeated instruction
* Befunge 98's stacks have infinite zeroes at the bottom
* `.` outputs as a number, followed by a space
[Answer]
# R, ~~3~~ 2 bytes
### Code
```
!0 # NOT FALSE
```
Outputs
```
TRUE
```
Wow, finally R, finally.
It seems that `{}` work too, it outputs `NULL`
## Bonus ~~33~~ 16 bytes:
### Code
```
rep(1,number*16)
```
Outputs
```
# if number is not defined
> rep(1,number*16)
> Error: object 'number' not found # output is 32 (or 2*16) bytes long error
# if number is defined
> number = 3
> rep(1,number*16) # output is 16*number bytes long
> 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
```
[Answer]
# JavaScript, 2 bytes!
Even shorter than the 3 bytes solution:
```
!0
```
Returns `true` after running.
[Answer]
# Matlab, 8 bytes
```
1234;'5'
```
Output:
[![enter image description here](https://i.stack.imgur.com/Ly5EG.png)](https://i.stack.imgur.com/Ly5EG.png)
The output contains *`newline`*, `ans =`, *`newline`* twice, *`space`* four times, `'5'`, *`newline`*, so 16 bytes.
[Answer]
## Python 2, 11
```
print`id`*1
```
Print the string representation of the built-in `id`, which is 22 chars:
```
<built-in function id>
```
The `*1` is to get the code to 11 chars. You could also do `print id;00`.
More boring alternative 11's are:
```
print'1'*22
print 9**21
```
[Answer]
# dc, 10 - 25 = -15
```
2?A*Ar^1-n
```
Takes a blank line for "no input".
Calculates 10 ^ (10 \* n) - 1, where n is the input, or 2 if input is empty. Prints a string of `9`s of the required length.
* `2` push 2 to the stack in case input is empty
* `?` push input to the stack
* `A` push 10 to the stack (dc has shortcuts `A`-`F` for 10 - 15)
* `*` pop twice and multiply (multiply input by 10)
* `A` push 10 to the stack
* `r` reverse top two stack elements
* `^` exponentiate 10 ^ (10 \* input)
* `1-` subtract 1 from the top of stack
* `n` print with no newline.
[Answer]
# Brainfuck, 14 bytes
```
+++++++[....-]
```
This is a little mathematical exercise. Let's denote the number of `+` characters in the code by `a`, and the number of `.` characters by `b`.
The code outputs `a*b` bytes, with values from `a` down to `1` (these are non-ASCII bytes, but it seems OK according to the spec). The code's length is `a+b+3`. So we have
```
a*b = 2 * (a+b+3)
```
Trying different values for `a` and `b`, we see that the minimum for `a+b+3` is achieved for
```
a = 4 or a = 7
b = 7 b = 4
```
[Answer]
# [gs2](https://github.com/nooodl/gs2/blob/master/gs2.py), -18 bytes
[CP437](https://en.wikipedia.org/wiki/Code_page_437): `W↕0!↨.2`
Hex dump: `57 12 30 21 17 2e 32`
`W` reads numbers from STDIN into a list. `↕0` appends a 2 to the list, and `!` extracts the first element. Then `↨.` (the list `[0,1,2,3,4,5,6]`) is repeated (`2`) this many times.
This is very similar to Dennis's CJam answer -- gs2 just combines `r` and `i` into one byte.
**Note**: I had to fix a bug in the `gs2` implementation for this to work: previously, each program had a hidden newline appended to its output, which was entirely unintentional. It only surfaced after I tried to solve this program (the language was designed for anarchy golf, which ignores trailing newlines in all problems), and I only pushed a fix to master just now, so feel free to take this answer with a grain of salt.
[Answer]
# TI-Basic, 3 bytes
```
1ᴇ5
```
Prints `100000`.
[Answer]
# [Pyth](https://www.github.com/isaacg1/pyth), ~~10~~ 9 - 25 = -16
*-1 by Dennis*
```
**N9?zvz2
```
Prints [input]\*9 quote characters, or 2\*9 if the input is empty.
**isaacg has a [shorter answer here](https://codegolf.stackexchange.com/a/59565/39328)**
# [Pyth](https://www.github.com/isaacg1/pyth), 1 byte
```
T
```
Prints `10`. It's a built in variable that initializes to 10.
[Answer]
# Perl 5, 16 bytes - 25 = -9
```
$_ =$]x($_*2||4)
```
This is an oddball approach to the problem.
Run with the `-p` command line argument.
I saw a Perl answer below that used a special variable to print more text - and thus shorten their byte count. So I used a much more verbose special variable. It prints 8 characters with a 2 character variable name. Thus, with a byte count of 16 (padded with one whitespace character to make it 16), it prints `2 * $]`, where `$]` is the Perl version printed as `5.xxxxxx`, dependent upon your Perl version. Without input it prints it four times, equaling `8*4` or `32`, which is double the byte count of the code.
I love Perl.
[Answer]
# JavaScript, 4 bytes
```
+1/0
```
Prints `Infinity`
I think this is the shortest possible JS solution without ES6 :P
[Answer]
## [Macaroni 0.0.2](https://github.com/KeyboardFire/macaroni-lang/releases/tag/v0.0.2-alpha), 23 chars
```
print tobase pow 32 9 2
```
Prints 329 in binary, which happens to conveniently turn out to be 46 characters long (it's `1000000000000000000000000000000000000000000000`), without a trailing newline.
[Answer]
# C, ~~27~~ 25
```
main(){printf("%50f",0);}
```
---
•*Thanks @Titus for knocking off 2 bytes*
---
# And for my *non-competing* **16 byte** solution in C, go here: <https://codegolf.stackexchange.com/a/111330/16513>
^I say non-competing because the error code could possibly depend on your compiler, Also note I'm using GCC in that solution. Also I'm not certain if it breaks rule 1 or not, I think it probably does so I went ahead and labeled it non-competing
[Answer]
# [V](https://github.com/DJMcMayhem/V), 2 Bytes
```
4é
```
This outputs
```
ÿÿÿÿ
```
[Try it online!](http://v.tryitonline.net/#code=NMOp&input=)
Explanation
This is a really hacky answer, and it works by abusing the internals of V. Essentially how it works is that `ÿ` is a command in V that signals the program is over, and any pending commands must complete. Otherwise, some implicit endings would not work, and the interpret would hang more often. This command is automatically sent several times at the end of the program, and most of the time has no effect on the output.
`é` is a command that inserts a single character. However, it does it by grabbing a raw byte, so it doesn't interpret `ÿ` as "end", it interprets it as "this is the character you need to insert." `4é` makes it insert this character 4 times instead of one.
[Answer]
# bash, 11 bytes
Here's a pleasingly ironic usage of a data compression tool :) ...
`gzip -f<<<2`
Here's a hex dump of the output (22 bytes)...
```
0000000: 1f 8b 08 00 e3 ce 32 59 00 03 33 e2 02 00 90 af ......2Y..3.....
0000010: 7c 4c 02 00 00 00 |L....
```
[Answer]
# JavaScript ES6, 33 - 25 = 8
```
(a=2)=>Array(a*33).fill(0).join``
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@TWqKQZPtfI9HWSNPWzrGoKLFSI1HL2FhTLy0zJ0fDQFMvKz8zLyHhf3J@XnF@TqpeTn66RpKGoaamNRe6kF5Oal56SQaGjJEmFiG44v8A)
[Answer]
# dc, 19 - 25 = -6
```
2?19*[1n1-d0<l]dslx
```
Takes a number (2 is pushed to the stack as backup) and multiplies it by 19. Prints a `1` (no newline) and decrements the number. Loops while the number is greater than 0.
[Answer]
# C++, 80 bytes
```
#include<iostream>
int main(){int i=0;while(i<20){std::cout<<&i;i++;}return 0;}
```
note the newline character is two characters. (if you don't want it to be, change i<20 to i<=19 to get back to the same byte count.)
Sample output (will change every time)
```
0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C0088FA0C
```
same 8 character memory address 20 times.
[Answer]
# CJam, -9
```
q_,{i}{;2}?G*'X*
```
# Explanation
* `q_,`
Reads the entire input and pushes it, then pushes the length.
* `{i}{;2}?`
If the length of the input is over zero, convert it to an integer. Otherwise, pop the input and push 2.
* `G*`
Pushes 16 (the program length), then multiplies it by 2 if there is no input, or by the input.
* `'X*`
Pushes X and multiplies it by the top of the stack.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 19 + 2 (-v flag) - 25 = -4 bytes
```
l?!2f4+*v
-1o;!?::<
```
[test it here!](http://fishlanguage.com/playground/AvEKhXujhJGkPg4qz)
Thanks Cole and Sp3000
First checks the stack length, if it's 0 put 2 on the stack. Multiplies it by 21 (code length), then outputs the unicode representation of that number and decrements it by 1, loops until 0. (you'll have to inspect the output to see the characters, since the browser won't display them)
[Answer]
# JavaScript (ES5), 68 bytes - 25 bonus = 43
```
alert(Array(1+(+prompt()||2)).join(document.scripts[0].textContent))
```
(in case your browser won't allow for the snippet to run for security reasons, try this fiddle <http://jsfiddle.net/thePivottt/c3v20c9g/> )
This script only works in a browser following at least DOM3 (with `Node.textContent`) and ECMAScript 5 (or perhaps an older version). I tried to make is as standard conforming and compatible as possible. It also assumes that the script is in the first `script` element of the document.
It actually concatenates multiple copies of the script itself, which is **pretty awesome**. Note that the snippet tool on SE puts extra whitespace around the script. We could ignore that whitespace with `.trim()` but I don't find it necessary considering the program is perfect without SE's meddling. Just save this HTML5 file if you want to see it run perfectly.
```
<!DOCTYPE html>
<html>
<head>
<title>Minimalist HTML5 page</title>
<script>alert(Array(1+(+prompt()||2)).join(document.scripts[0].textContent))</script>
</head>
</html>
```
This script uses `prompt` and `alert` because `console.log` is not part of any standard, even if most modern browsers use it. If the number of repetitions passed is not a valid number or is empty, it defaults to 2. If the input is a decimal number, the program crashes due the the invalid array length.
The code uses a few interesting features of JavaScript:
* `Array(1+(+prompt()||2))`
+ `Array(INT)` creates an Array of INT cells.
+ `+prompt()` takes an input and turns it into a number. If we passed the input as a string, the `Array` function would simply wrap it in a one-element array.
+ `+prompt()||2` returns the input if it is *truthy*, else it returns 2.
+ This whole code creates an array of N empty elements, where N is one more than the amount of repetitions asked.
* `.join(document.scripts[0].textContent)`
+ The array's `join(STRING)` method creates a string by concatenating all the cells, putting the provided STRING between values. In this program, there are N+1 **empty** elements in the array, or exactly N in-between spots. The result will be a string containing N times the provided STRING.
+ `document.scripts[o]` is the first `<script>` element of the document.
+ The `textContent` of `Node` instances returns the whole text found inside them and their child nodes, including scripts.
[Answer]
# Julia, 42 bytes - 25 = 17
```
print("@"^42((r=readline())>""?int(r):2))
```
This reads a line from STDIN using `readline()`. If it's empty, i.e. no input has been provided, then *n* is defined to be the input converted to an integer. Otherwise *n* is 2. We then print 42*n* `@`s to STDOUT.
[Answer]
# Perl, 18 - 25 = -7
```
print$=x(<>*9||18)
```
The special variable [`$=`](http://perldoc.perl.org/perlvar.html#%24%3d), a.k.a. `$FORMAT_LINES_PER_PAGE`, begins its life as `60`, and therefore only needs to be duplicated half as many times as byte output needed.
] |
[Question]
[
Write a piece of code that is executable in at least three different languages. The code must output the integer `1` in language number one, `2` in language number two, `3` in language number three etc.
Rules:
* The output must be only the integer, but trailing newlines are OK.
* The code can't take input of any kind
* Different major versions of the same language are considered unique. So, your code can be executable in Python 2 and Python 3, however Python 2.5 and Python 2.7 are not considered unique.
* You may use a new language if and only if it has an esolang/wiki article, available interpreter and documentation, and has been used by at least two users on PPCG prior to using it in this challenge. It must also adhere to [these 4 rules](http://meta.codegolf.stackexchange.com/a/2073/31516).
The score of your submission is the number of bytes in your code divided by the number of languages it can run in cubed. So, a 54 byte solution that is executable in 3 languages will have a score of 2:
```
54 / 3^3 = 2
```
Lower score is better.
[Answer]
## 15 languages, ~~68~~ ~~66~~ 65 bytes / 15^3 = 0.019...
[**Retina**](https://github.com/mbuettner/retina), [**Starry**](http://esolangs.org/wiki/Starry), [**Prelude**](http://esolangs.org/wiki/Prelude), [**ETA**](http://www.miketaylor.org.uk/tech/eta/doc/manual.html), [**Axo**](http://esolangs.org/wiki/Axo), [**Labyrinth**](https://github.com/mbuettner/labyrinth), [**Hexagony**](https://github.com/mbuettner/hexagony), [**Foo**](http://esolangs.org/wiki/Foo), [**Brian & Chuck**](https://github.com/mbuettner/brian-chuck), [**Gol><>**](https://github.com/Sp3000/Golfish/wiki), [**evil**](http://esolangs.org/wiki/Evil), [**Whitespace**](http://web.archive.org/web/20150504042320/http://compsoc.dur.ac.uk/whitespace/tutorial.php), [**Fission**](https://github.com/C0deH4cker/Fission), [**><>**](http://esolangs.org/wiki/Fish) and [**GolfScript**](http://www.golfscript.com/golfscript/index.html).
After a massive rewrite, I managed to fit in four more languages. The code contains the few tabs for Whitespace. Since Stack Exchange converts them to spaces, I've represented them with `\t` below:
```
#I5aeeNTH{\? \t\t + +3;n@"8"ea9
15}7'`--~!@<"31"LSOe.\t
\teaww`
```
I think I'm done adding languages (although adding only one might save some bytes in what I already have). I wonder if it's golfable though... 65 bytes for 15 languages is quite a jump from 32 bytes for 11 languages, and I've now got at least one useless character in there to make Foo work..
### Retina prints `1`
[Try it online.](http://retina.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
Luckily, the first line is a valid regex. However that regex obviously doesn't match the empty input, so the first stage (consisting of the first two lines) doesn't do anything.
The third line is on its own, so it's treated as a Match stage which, by default, counts the number of matches. However, the ``` is a separator which tells Retina that the part in front of it is a configuration string (it doesn't happen to know any of the options given there) and the part after it is the regex. So the regex is empty and Retina finds exactly one match.
### Starry prints `2`
[Try it online.](http://starry.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
Starry ignores everything except spaces and `+*,'`.`. Each command is one of those characters in conjunction with the spaces since the last of those characters. So let's remove all the extraneous code:
```
+ +'`. `
```
Seven spaces followed by `+` pushes a `2`. One space followed by a `+` duplicates it. `'` is a conditional jump. It pops the top of the stack, which is truthy (positive), so it jumps to the corresponding label (where labels are indicated by ``` and "corresponding" means "with the same number of leading spaces"), which is the first ```. `.` without spaces in front of it then prints the top of the stack as a number.
### Prelude prints `3`
[Try it online.](http://prelude.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
This assumes the Python interpreter which uses numeric output. Let's remove all the no-ops:
```
# 5 ? + +3 8 9
15 7 -- ! 31
```
The first voice does a bunch of stuff, but nothing of it matters, because there is no `!` to print any of the results. The second voice pushes a `1`, then a `5`, then a `7`. We take the difference of the last two to get `-2`, and then subtract that from the `1` to get `3`. `!` prints it. The third voice has only no-ops.
### ETA prints `4`
[Try it online.](http://eta.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
ETA ignores everything except the characters `ETAOINSH` (in any case). So the code as seen by ETA is:
```
IaeeNTHneaSOeea
```
`I` tries to read input but can't, so it pushes `-1`. `a` pushes the current line number plus 1, which is `2`. `e` is *divmod*, which replaces those with `0` and `1` (or `-1`, I don't actually know, but it doesn't matter). The next `e` replaces both of them with `0`.
Now the interesting part. `NTHne` is a base-7 number literal. `N` and `e` are just the delimiters, and the three digits are `THN`. That is `54` (where `T` is digit `1`, `H` is `0` and `n` is `5`). `a` pushes `2` once more. `S` subtracts it, resulting in `52` and `O` outputs it as a character (`4`). Now `e` tries divmod again, but the stack contains two zeroes, so the program terminates with an error (but doesn't pollute STDOUT while doing so).
### Axo prints `5`
[Try it online.](http://axo.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
This language was pretty much single-handedly responsible for the rewrite. I couldn't have the `}` on the first line because it would block for input in Axo (see revision history for what I'm talking about). For Axo, only this part of the code is relevant:
```
#I5aeeNTH{\
```
Luckily, Axo also has implicit `0`s at the bottom of its stack, because `#` pops the top of the stack (to check if the next instruction should be skipped or not). The letters are all no-ops. Then `5` pushes a `5`, `{` prints it, `\` terminates the program. Quite simple, really.
### Labyrinth prints `6`
[Try it online.](http://labyrinth.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
I'm truncating the code a bit, because the right half is never reached, and I'm also using `t` in place of `\t`, so that the columns line up correctly:
```
#I5aeeNTH{\
15}7'`--~!@
teaww`
```
Now that letters, spaces and tabs are walls in Labyrinth, so the accessible code actually looks like this:
```
# 5 {\
15}7'`--~!@
`
```
The instruction pointer will automatically follow that path. `#` pushes the depth of the main stack (`0`) and `15` turns it into a `15`. `}` moves it off to the auxiliary stack, and we're not going to use it any more. That conveniently makes the top of the stack zero, so that the IP does not turn left onto the `5`. `7` turns the zero into a `7`, `'` is a no-op. The ``` is unary negation, so we get `-7`. Now `-` subtracts the `-7` from the implicit `0` underneath making it `7`. This time, the IP does turn right to the ```, which is unary negation, so we get `7` again. The IP hits a dead end a turns around. The `-` does the same thing as before, so we get `7` once more. As the top of the stack is now positive, the IP turns right. There's another `-` which gives `-7` again. Then `~` is bitwise NOT, which gives `6` and `!` prints it. That's just the right moment to do so, because now the stack is empty again such that the IP won't turn left onto the `{` but instead continues straight ahead into the `@` which terminates the program.
### Hexagony prints `7`
[Try it online.](http://hexagony.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
The unfolded code looks like this:
```
# I 5 a e
e N T H { \
? + + 3 ; n @
" 8 " e a 9 1 5
} 7 ' - - ~ ! @ <
" 3 1 " L S O e
. e a w w . .
. . . . . .
. . . . .
```
Normally, that would be a terrifying Hexagony program, but the characters actually in use are not too many. In fact they are pretty much the same as those used by Labyrinth and I think the way I differentiate between `5` and `6` is quite nice. :)
The top row can basically be ignored. `#` would normally switch to a different IP, but the current memory edge is `0`, so it doesn't. The letters just set a fixed memory value, but we're not going to use it. After the end of the first row, control flow continues in the middle row (starting from the `}`, going right). The `}` moves to another memory edge. `7` sets that edge to `7`. `'` moves back to where we came from. `-` subtracts the memory edge we've just set to `7` from an unused memory edge (`0`), so we get `-7`. The next `-` does the same thing again, so it's a no-op. So far, quite similar to Labyrinth (apart from the memory layout). But now `~` is not bitwise NOT but unary negation in Hexagony. So this gives `7` instead of `6`. `!@`, like in Labyrinth prints the value and terminates the program.
### Foo prints `8`
[Try it online.](http://foo.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
As we all know since [The Programming Language Quiz](https://codegolf.stackexchange.com/q/54807/8478) printing things is quite trivial in Foo, even if most of the code is a random jumble of characters. None of the characters affect the output except the `"8"` which prints `8`. Well, there is the `"31"` later on, but Foo terminates with an error at the end of the first line. I'm not exactly sure why that happens, but it requires that `3` (or any other digit) on the top row, which isn't used anywhere else.
### Brian & Chuck prints `9`
[Try it online.](http://brian-chuck.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
Let's do this thing again where we remove the third line (it's never parsed) and replace all irrelevant characters (i.e. no-ops, or cells that aren't read) with spaces:
```
{ ? + + 9
} -- < .
```
Just as a reminder, each line is a Brainfuck-like whose tape is the source code of the other program. Control flow starts on the first line (called Brian).
The `{` moves the tape head all the way to the left (where it already is), and `?` hands control flow over to Chuck (the second line). There, `}` moves the tape head to the right until it finds a zero cell. That doesn't happen until the end of the program, so the tape head ends up one cell after the `9`. `-` decrements that cell, but that's irrelevant. `<` moves the tape head onto the `9` and `.` prints it. Chuck runs out of program and terminates.
### Gol><> prints `10`
[Tested here.](https://golfish.herokuapp.com/?code=%23IaeeNTH7%7B%5C%3F%20%20%20%20%20%20%20%2B%09%09%20%2B3'L%09%3Bn%40%228%22ea1%0A9%7D6'-%7e%21%40%3CSO1'Lee.%60.%09%0A%20%09awaw%60&input=)
`#` is a mirror, so the IP immediately skips to the end of the first line (and goes left). The `9` can be ignored. `a` pushes `10`, `e` pushes `14`, `"8"` pushes the character code of `8`, `@` rotates the top three stack elements (pulling up the `10`), such that `n` prints the `10` and `;` terminates the program.
Thanks to Sp3000 for suggesting to use `@` instead of `!` (which saved a byte).
### evil prints `11`
*Thanks to Sp3000 for sending me some brute-forced command-lists to generate single-digit numbers.*
[Try it online.](http://evil.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
evil ignores everything except lower case letters so the code looks like this:
```
aeeneaeeaww
```
Also, `n` affects some state we don't care about so let's ignore that as well. Now `a` increments the register (which starts at `0`), and `e` is evil's magic "weave" operation which permutes the bits in a particular way. `aeeeaeea` happens to yield the value `49` which is the character code of `1`. `ww` prints it twice.
### Whitespace prints `12`
[Try it online.](http://whitespace.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
Okay, we know Whitespace only reads spaces, tabs and linefeeds, so let write the code as seen by Whitespace with `STL`:
```
SSSSSSTTSSLTLST
```
That's two commands:
```
SSSSSSTTSSL
TLST
```
The first one pushes the number `12`. Specifically, `SS` starts a number literal. The next `S` is the sign bit (positive). Then everything up to the `L` is a binary representation of the number. There's a ton of leading zeroes, which we need for Starry, but they don't affect the number. Then the `TTSS`s is `12` in binary. Fun fact: if I added a 16th language, I could save a byte here, because Starry could use the four `S` in the binary represtation of `16`. I doubt I will though...
The `TLST` just prints the top of the stack as a number. (`TL` marks the command as an I/O command, and `ST` is printing numbers.)
### Fission prints `13`
[Try it online.](http://fission.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
Fission only sees this part of the code:
```
<"31"L
```
`L` starts control flow with a left-going atom. `"` toggles print mode, so that `31` just prints `13`. Then the atom is captured in the wedge of the `<`, which terminates the program.
### ><> prints `14`
[Tested here.](http://fishlanguage.com/playground)
Distinguishing between ><> and Gol><> isn't as easy as I thought, because Gol><> almost always does the same thing as ><> for commands that exist in both, and commands that only exist in Gol><> cause ><> to crash. However, `@` rotates the other way round in ><>, such that it pushes down the `7` instead of pulling up the `10`, and then the `14` gets printed instead of the `10`.
### GolfScript prints `15`
[Try it online.](http://golfscript.tryitonline.net/#code=I0k1YWVlTlRIe1w_ICAgICAgCQkgKyArMztuQCI4ImVhOQoxNX03J2AtLX4hQDwiMzEiTFNPZS4JCiAJZWF3d2A&input=)
This one is simplest: `#` comments out the first line. Then `15` pushes itself and `}` is a "super comment", which ignores the entire rest of the program. So the `15` is printed at the end of the program.
[Answer]
# 30 languages, 248 bytes, \$\frac {248} {30^3} = 0.009185\$
```
#|#?15g,@ kkmNmSaIeoe99+{\#/-;n@0ea
#[9!@>.>.eeaww#-1@*"12" L
#{
###
#`{
25
print(4^2 +7)/2
"""
Jo is here.
$'main'MoO OOM
7
>Jo, 30
>X Jo
f::=~27
::=]##}#(prin 29)
print (7/6*24)###;alert 2#-[>+<-----]>-.|#(write(if(= 1/5 .2)26 3))"""
```
**Edit:** [Beatnik](http://esolangs.org/wiki/Beatnik) removed since primality testing in Beatnik might not be possible.
The code has tabs in it (which can get mangled by Stack Exchange) and a trailing newline, so here's the `xxd`:
```
00000000: 237c 233f 3135 672c 4020 2020 0920 2020 #|#?15g,@ .
00000010: 206b 6b6d 4e6d 5361 4965 6f65 3939 2b7b kkmNmSaIeoe99+{
00000020: 5c23 2f2d 3b6e 4030 6561 0a23 5b39 2140 \#/-;n@0ea.#[9!@
00000030: 3e2e 3e2e 6565 6177 7723 2d31 402a 2231 >.>.eeaww#-1@*"1
00000040: 3222 094c 0a23 7b20 090a 2323 230a 2360 2".L.#{ ..###.#`
00000050: 7b0a 3235 0a70 7269 6e74 2834 5e32 202b {.25.print(4^2 +
00000060: 3729 2f32 0a0a 0a22 2222 0a4a 6f20 6973 7)/2...""".Jo is
00000070: 2068 6572 652e 0a24 276d 6169 6e27 4d6f here..$'main'Mo
00000080: 4f20 4f4f 4d0a 2037 0a3e 4a6f 2c20 3330 O OOM. 7.>Jo, 30
00000090: 0a3e 5820 4a6f 0a66 3a3a 3d7e 3237 0a3a .>X Jo.f::=~27.:
000000a0: 3a3d 5d23 237d 2328 7072 696e 2032 3929 :=]##}#(prin 29)
000000b0: 0a70 7269 6e74 2028 372f 362a 3234 2923 .print (7/6*24)#
000000c0: 2323 3b61 6c65 7274 2032 232d 5b3e 2b3c ##;alert 2#-[>+<
000000d0: 2d2d 2d2d 2d5d 3e2d 2e7c 2328 7772 6974 -----]>-.|#(writ
000000e0: 6528 6966 283d 2031 2f35 202e 3229 3236 e(if(= 1/5 .2)26
000000f0: 2033 2929 2222 220a 3))""".
```
Alternatively, you can copy and paste the code from [this "Try it online!" link](http://retina.tryitonline.net/#code=I3wjPzE1ZyxAICAgCSAgICBra21ObVNhSWVvZTk5K3tcIy8tO25AMGVhCiNbOSFAPi4-LmVlYXd3Iy0xQCoiMTIiCUwKI3sgCQojIyMKI2B7CjI1CnByaW50KDReMiArNykvMgoKCiIiIgpKbyBpcyBoZXJlLgokJ21haW4nTW9PIE9PTQogNwo-Sm8sIDMwCj5YIEpvCmY6Oj1-MjcKOjo9XSMjfSMocHJpbiAyOSkKcHJpbnQgKDcvNioyNCkjIyM7YWxlcnQgMiMtWz4rPC0tLS0tXT4tLnwjKHdyaXRlKGlmKD0gMS81IC4yKTI2IDMpKSIiIgo).
This is pretty badly golfed, but I wanted to play off the idea that, once you have enough languages, byte count doesn't matter as much any more. Having said that there are some languages I could still easily add (e.g. Objeck) but are currently too long to be useful. I'm running out of good languages though, so I might stop here for now.
Run all programs with `</dev/null 2>/dev/null` (i.e. empty input, surpressed STDERR).
The explanation's quite long, so here's an executive summary:
| No. | Lang. | Non-esolang? | 2D esolang? | BF/BF-deriv? |
| --- | --- | --- | --- | --- |
| 1 | COW | ‚úó | ‚úó | ‚úì |
| 2 | CoffeeScript | ‚úì | ‚úó | ‚úó |
| 3 | Common Lisp | ‚úì | ‚úó | ‚úó |
| 4 | Retina | ‚úó | ‚úó | ‚úó |
| 5 | Befunge-93 | ‚úó | ‚úì | ‚úó |
| 6 | Python 2 | ‚úì | ‚úó | ‚úó |
| 7 | Rail | ‚úó | ‚úì | ‚úó |
| 8 | ETA | ‚úó | ‚úó | ‚úó |
| 9 | Prelude | ‚úó | ‚úó | ‚úó |
| 10 | Gol><> | ‚úó | ‚úì | ‚úó |
| 11 | evil | ‚úó | ‚úó | ‚úó |
| 12 | Foo | ‚úó | ‚úó | ‚úì |
| 13 | Ruby | ‚úì | ‚úó | ‚úó |
| 14 | ><> | ‚úó | ‚úì | ‚úó |
| 15 | Brian & Chuck | ‚úó | ‚úó | ‚úì |
| 16 | Whitespace | ‚úó | ‚úó | ‚úó |
| 17 | 3var | ‚úó | ‚úó | ‚úó |
| 18 | Axo | ‚úó | ‚úì | ‚úó |
| 19 | Labyrinth | ‚úó | ‚úì | ‚úó |
| 20 | Starry | ‚úó | ‚úó | ‚úó |
| 21 | Fission | ‚úó | ‚úì | ‚úó |
| 22 | Brainfuck | ‚úó | ‚úó | ‚úì |
| 23 | Julia | ‚úì | ‚úó | ‚úó |
| 24 | Lily | ‚úì | ‚úó | ‚úó |
| 25 | GolfScript | ‚úó | ‚úó | ‚úó |
| 26 | Chicken Scheme | ‚úì | ‚úó | ‚úó |
| 27 | Thue | ‚úó | ‚úó | ‚úó |
| 28 | Perl 6 | ‚úì | ‚úó | ‚úó |
| 29 | Picolisp | ‚úì | ‚úó | ‚úó |
| 30 | TRANSCRIPT | ‚úó | ‚úó | ‚úó |
---
## 1. [COW](https://esolangs.org/wiki/COW)
COW is a Brainfuck derivative with additional commands, one of which is numeric output. Anything invalid is ignored, so the executed program is merely
```
MoO OOM
```
which increments the cell to 1 then prints it as a number.
## 2. [CoffeeScript](http://coffeescript.org/) (includes interpreter)
CoffeeScript sees:
```
# comments
###
multiline comment
###;alert 2# comment
```
which simply alerts 2.
*(Yes, it'd probably be better if another language took this slot, but I'm too lazy to reshuffle at this point :P)*
## 3. [Common Lisp](https://common-lisp.net/) | [ideone](http://ideone.com/x25Scl)
Common Lisp (clisp) sees:
```
#|
multiline comment
|#(write(if(= 1/5 .2)26 3))"""
```
`1/5` is a rational and not equal to `0.2`, so 3 is printed. The proceeding `"""` is a syntax error.
Note that `print` seems to output a preceding newline and trailing space in Common Lisp. However, luckily, `write` works in both Common Lisp and Chicken Scheme.
## 4. [Retina](https://github.com/mbuettner/retina) | [Try it online!](http://retina.tryitonline.net)
**Restrictions introduced**: Every second line starting from the first needs to be a valid regex.
Every pair of lines form a replacement stage, replacing instances of matches of the first line's regex with the second line. In the middle, we have the pair
```
"""
```
which replaces the initial empty string with `"""`. The final empty line, not part of any pair, is treated as a match stage, counting the number of matches of the regex. There are four instances of empty string in `"""`, namely `1"2"3"4`.
## 5. [Befunge-93](https://esolangs.org/wiki/Befunge) | [Interpreter](http://www.quirkster.com/iano/js/befunge.html)
Befunge is a 2D language, and the relevant instructions are
```
# # 15g,@
```
in the first line, and the `5` in the `25` line. `#` skips the next instruction, `15g` gets the char at position `(1, 5)` in the code (the `5` in the `25` line), `,` outputs the char and `@` halts.
## 6. [Python 2](https://python.org) | [ideone](http://ideone.com/7Wp01H)
Python sees:
```
# comments
25
print(4^2 +7)/2
"""
multiline string
"""
```
`(4^2+7)/2 = (xor(4,2)+7)/2 = (6+7)/2 = 13/2 = 6`, which gets `print`ed.
## 7. [Rail](https://esolangs.org/wiki/Rail) | [Try it online!](http://rail.tryitonline.net/)
Rail is a 2D language, and execution start from the `$` of the main function, heading southeast. Thus, the relevant portion of code is
```
$'main'
7
o
J
```
with the `o` and `J` coming from lines used by TRANSCRIPT. After outputting 7, the train hits an unrecognised `J` instruction, which crashes the program.
## 8. [ETA](https://esolangs.org/wiki/ETA) | [Try it online!](http://eta.tryitonline.net/)
**Restrictions introduced:** Chars before the ETA program should not be in `etaoinsh`.
ETA only recognises the letters `etaoinsh` and their uppercase versions, meaning the code starts off with
```
NSaIeoe
```
`n...e` pushes a base 7 number based on what's within the delimiters, which for `SaI` is `624`, or 312 in decimal. `o` then outputs as char, apparently after modulo 256, giving the char `8` (code point 56). `e` then tries to divide with an empty stack, which fails.
## 9. [Prelude](http://esolangs.org/wiki/Prelude) | [Try it online!](http://prelude.tryitonline.net/)
**Restrictions introduced:** No more than one of `()` in any column, `()` matched reading a column at a time, no infinite loops caused by `()`.
This requires the Python interpreter to have `NUMERIC_OUTPUT = True` set.
Prelude is a language where each line is executed separately. A lot of chars get executed, but the important part is the
```
9!
```
on the second line, which outputs 9. `()` in Prelude denote a loop, but thanks to the prominence of `#`s (which pop from the stack), the tops of the stacks are always 0 by the time a loop is hit, so none of them are run. Prelude's source code restrictions regarding `()` introduced some extraneous spaces though.
## 10. [Gol><>](https://github.com/Sp3000/Golfish/wiki) | [Interpreter](http://golfish.herokuapp.com/)
This part (and ><>) work like [Martin's answer](https://codegolf.stackexchange.com/a/65643/21487). The relevant code is
```
# ;n@0ea
```
Gol><> is a 2D language and `#` reflects the IP, making it travel leftwards. It wraps around, push 10, 14 and 0 to the stack. `@` then rotates the stack, bringing 10 to the top, `n` outputs it and `;` halts the program.
## 11. [evil](http://web.archive.org/web/20070103000858/www1.pacific.edu/%7Etwrensch/evil/index.html) | [Try it online!](http://evil.tryitonline.net/)
This part's also similar to Martin's answer.
evil ignores everything except lowercase letters. Ignoring a few more characters, the relevant part is
```
aeeeaeeaww
```
where `a` increments the variable `A`, `e` is evil's weave function which shuffles the bits of `A`, and `w` outputs `A`. Hence we output `1` twice, giving `11`.
But what about the rest of the instructions, and especially that `w` on the last line? Let's just say that sometimes it's easiest to just mess with the code and pray it still works in everything which, here, it somehow did...
## 12. [Foo](http://esolangs.org/wiki/Foo) | [Try it online!](http://foo.tryitonline.net/)
Foo outputs anything between double quotes, so the relevant part is the
```
"12"
```
on the second line. However, since we need double quotes later we use a method similar to Martin's answer to make Foo error out, namely the preceding `#-1@`. It's unclear why that works in a language which soldiers on in the face of empty stack and division by zero errors, but I'm glad it does.
## 13. [Ruby](https://www.ruby-lang.org/) | [ideone](http://ideone.com/6n9aEl)
Like Python, Ruby sees:
```
# comments
25
print(4^2 +7)/2
"""
multiline string
"""
```
However, it's worth noting that the multiline string is actually three separate strings (`""`, `"..."`, `""`) concatenated together. The print line outputs `(4^2+7) = xor(4,2)+7 = 6+7 = 13`, before erroring out trying to divide `nil` by 2.
## 14. [><>](http://esolangs.org/wiki/Fish) | [Try it online!](http://fish.tryitonline.net/)
This part's the same as the Gol><> part, except `@` brings the 14 up to the top instead, which gets outputted.
## 15. [Brian & Chuck](https://github.com/mbuettner/brian-chuck) | [Try it online!](http://brian-chuck.tryitonline.net/)
Brian & Chuck is a BF derivative with two tapes, where one tape's instruction pointer is the other tape's memory pointer. In the absence of `````, the first two lines of the source code are used to initialise the tapes.
The relevant chars in the first two lines are:
```
?15
# >.>.
```
The `?` in Brian's tape passes control over to Chuck in the cell being pointed to (the `#`) is nonzero. Chuck then executes `>.>.`, outputting the two chars after the question mark.
## 16. [Whitespace](http://web.archive.org/web/20150623025348/http://compsoc.dur.ac.uk/whitespace/) | [Interpreter](http://whitespace.kauaveel.ee/)
Using `STL` for space, tab and line feed respectively, the start of the program is:
```
SSSTSSSSL
TL
STL
L
L
```
The first line pushes 16 (`+10000` base 2), the preceding `TLST` prints it as a number. The next three newlines halt the program.
Note, however, that this program is interpreter specific. The rest of the code syntax errors in most interpreters, so a more lenient interpreter is required, like the one linked above.
## 17. [3var](http://esolangs.org/wiki/3var) | [Try it online!](http://3var.tryitonline.net/)
Of the first line, a slew of instructions get executed, but the relevant ones are
```
kkmmao#/
```
Due to ETA's restriction, we use `k` to decrement the variable B rather than `a` to increment it. `kk` decrements B to -2 and `mm` squares B twice to 16, which is incremented to 17 with `a`. This is then outputted with `o`.
`#` is then used to reset B to 0, and `/` causes the program to error out via division by 0.
## 18. [Axo](http://esolangs.org/wiki/Axo) | [Try it online!](http://axo.tryitonline.net/)
**Restrictions introduced:** No instructions before the Axo program which change the direction of the IP
Once again, a slew of instructions get executed in the first line, but the relevant ones are
```
# # 15 ,@ 9 9 + { \
```
Axo is a 2D language like Befunge, and `#` is similarly a bridge that skips the next instruction, but only if the top of the stack is zero. `15,` push to the stack, but the stack is emptied with `@`. `99+` then pushes 18, `{` outputs and `\` halts.
## 19. [Labyrinth](http://github.com/mbuettner/labyrinth) | [Try it online!](http://labyrinth.tryitonline.net/)
Labyrinth is another 2D language, and the executed instructions are
```
#|#
[9!@
```
`#` pushes the length of the stack, which is 0 the first time. `|` is bitwise OR, not changing anything since the stack just has 0s at this point, and the second `#` now pushes 1 due to the lone zero. We turn right due to the 1, `9` converts this 1 to `1*10+9 = 19`, `!` prints it and `@` halts.
This program relies on the fact that `[` is not currently a recognised instruction, and hence is treated as a wall.
## 20. [Starry](http://esolangs.org/wiki/Starry) | [Try it online!](http://starry.tryitonline.net/)
**Restrictions introduced:** All `+`s must have at least one preceding space
If we strip away unrecognised characters, the relevant part of the code is
```
, +.. +
```
`,` is input, but since we pipe from `/dev/null` there is none, pushing 0 to the stack. A `+` with `n >= 5` preceding spaces pushes `n-5`, so the next instruction pushes 2. `..` then outputs these two digits in reverse order.
Next we have a `+` with a single preceding space, which duplicates. However, the stack is empty, so we error out.
## 21. [Fission](http://github.com/C0deH4cker/Fission) | [Try it online!](http://fission.tryitonline.net/)
The only relevant part for Fission is
```
*"12"L
```
`L` spawns an atom moving leftward, `"21"` prints 21 and `*` halts.
## 22. [Brainfuck](http://esolangs.org/wiki/Brainfuck) | [Try it online!](http://brainfuck.tryitonline.net/)
**Introduced restrictions:** No `.` before the first `[`
This requires an interpreter which gives 0 on EOF and has 8-bit cells. The relevant code is
```
,+-[>.>.-+.>,>]-[>+<-----]>-..
```
The inital `-` is to offset the `+`, and the first `[...]` is not executed since the cell is 0. The following `-[>+<-----]>-` sets the cell to the char code of `2`, and `..` outputs it twice.
## 23. [Julia](http://julialang.org/) | [Try it online!](http://julia.tryitonline.net/)
Julia sees:
```
# comments
25
print(4^2 +7)/2
```
What's printed is `4^2+7 = pow(4,2)+7 = 16+7 = 23`, and the program errors out trying to divide `nothing` by 2. Note that Julia doesn't seem to mind the fact that the rest of the code would cause a syntax error anyway.
## 24. [Lily](http://jesserayadkins.github.io/lily/index.html) | [Interpreter](http://jesserayadkins.github.io/lily/sandbox.html)
Lily sees:
```
# comment
#[
multiline comment
]## comment
print (7/6*24)# comment
```
`7/6*24 = 1*24 = 24` is printed.
## 25. [GolfScript](http://www.golfscript.com/golfscript/) | [Try it online!](http://golfscript.tryitonline.net/)
GolfScript sees:
```
# comments
25
print(
```
GolfScript is stack-based, so 25 is pushed to the stack, then popped and printed with `print`. `(` then tries to decrement the implicit empty string on the stack, which fails and errors out the program.
## 26. [Chicken Scheme](https://www.call-cc.org/) | [ideone](http://ideone.com/DyjG3R)
Chicken Scheme has the same `#| ... |#` multiline comment syntax as Common Lisp. However, in
```
(write(if(= 1/5 .2)26 3))
```
`1/5` is a float which *is* equal to `0.2`, so 26 is outputted instead.
## 27. [Thue](http://esolangs.org/wiki/Thue) | [Try it online!](http://thue.tryitonline.net/)
Thue is a language based on string rewriting. The first relevant part is
```
f::=~27
::=
```
which defines a substitution `f -> 27` then denotes the end of substitutions with `::=`. The lone `f` in `if` is then replaced with `27`, which is outputted.
## 28. [Perl 6](https://perl6.org/) | [ideone](http://ideone.com/Y2i0L6)
Perl 6 has a new comment syntax, namely `#`(some bracket)` which is a multiline comment all the way to the matching bracket. Thus, Perl 6 sees:
```
# comments
#`{
multiline comment
}# comment
print (7/6*24)# comment
```
which prints `7/6*24 = 28`.
## 29. [Picolisp](http://picolisp.com/wiki/?home) | [ideone](http://ideone.com/BI8YQ0)
Picolisp sees:
```
# comment
#{
multiline comment
}#(prin 29)
```
which prints 29. The line afterwards then causes a syntax error.
## 30. [TRANSCRIPT](http://web.archive.org/web/20071018030927/http://www.corknut.org/code/transcript/) | [Try it online!](http://transcript.tryitonline.net/)
TRANSCRIPT is a thematic esolang modelled after text adventures. Unrecognised lines are ignored (which allows you to add extra story/flavour text amongst the actual code instructions), so the relevant lines are:
```
Jo is here.
>Jo, 30
>X Jo
```
The first line declares a string variable `Jo`, using a two-letter name since one-letter names seem to fail. The second line sets this string to `"30"`, which is outputted by `X` ("examine") in the third line.
[Answer]
# Python 1.x, 2.x and 3.x, 32 bytes / 3^3 = 1.1851...
```
import sys
print(sys.version[0])
```
Prints the first number of the version, which is `1` in Python 1.x, `2` in Python 2.x and `3` in Python 3.x.
By the time we get Python 9.x my score will be a glorious `0.04389`!
:~)!
[Answer]
## 3 languages, 2 bytes / 27 = 0.074
```
1P
```
Well, it beats half the submissions at least :P
### 1. GolfScript
GolfScript ignores the `P`, outputting just the 1. [Try it online](http://golfscript.tryitonline.net/#code=MVA&input=).
### 2. [Par](https://github.com/Ypnypn/Par/)
`P` is 2-to-the-power-of, so `1P = 2^1 = 2`. [Try it online](http://ypnypn.github.io/Par/index.html).
### 3. [Seriously](https://seriously.readthedocs.org/)
`P` gives the nth prime, zero indexed. We get 3 since that's the second prime. [Try it online](http://seriouslylang.herokuapp.com/link/code=3150&input=).
---
### Notes
My inital goal was to find a valid answer in 1 byte. My first try was `\x12` which works in [Bubblegum](http://esolangs.org/wiki/Bubblegum) and [gs2](http://esolangs.org/wiki/gs2), but the challenge requires a minimum of three languages. `\x13` would work if there's a language in which that outputs 1.
Giving up on a 1 byte answer, I moved to two bytes. `3u` is a close call, outputting 1 in [Japt](https://github.com/ETHproductions/Japt), 3 in GolfScript and 4 in Seriously, but it was hard to find a language which outputted 2 to fill the gap.
All of this took me way too long :/
[Answer]
# 6 Languages - 44 bytes / 6^3 = 0.204...
Thanks to SnoringFrog for saving 10 bytes!
Works in:
* Befunge
* Pyth
* Brainfuck
* Hexagony
* Whitespace
* [AniRad](https://github.com/Adriandmen/AniRad) v0.2
---
```
2# "1",@"-[----->+<]>.*@@@!4<SSTST
T
ST
>6=
```
***Note: Before trying it online, make sure to replace S with spaces and T with tabs, or convert the following hexdump to ASCII***
```
32 23 20 22 31 22 2c 40 22 2d 5b 2d 2d 2d 2d 2d 3e 2b 3c 5d 3e 2e 2a 40 40 40 21 34 3c 20 20 09 20 09 0d 0a 09 0d 0a 20 09 0d 0a 20 3e 36 3d
```
I am going to try to use more programming languages :)
### Befunge (prints `1`):
[Try it online](http://www.quirkster.com/iano/js/befunge.html)
```
2# "1",@"-[----->+<]>.*@@@!4<
2 # This puts 2 onto the stack
# # Skips the next op (the space)
"1" # Sets the ASCII value of 1 onto the stack
, # Pop the last item (1)
@ # Terminate program
```
### Pyth (prints `2`):
[Try it online](https://pyth.herokuapp.com/?code=2%23%20%221%22%2C%40%22-%5B-----%3E%2B%3C%5D%3E.%2A%40%40%40%214%3C&debug=0)
```
2# "1",@"-[----->+<]>.*@@@!4<
2 # Prints 2
# # Infinite while loop until an error occurs
"1" # String
,@ # This gives the error and terminates the program
```
### Brainfuck (prints `3`):
[Try it online](https://copy.sh/brainfuck/)
```
2# "1",@"-[----->+<]>.*@@@!4<
2# "1",@" # Since these are not brainfuck ops, these will be ignored
-[----->+<]> # Puts "3" on the stack
. # Prints the last item (3)
```
### Hexagony (prints `4`):
[Try it online](http://hexagony.tryitonline.net/#code=MiMgIjEiLEAiLVstLS0tLT4rPF0-LipAQEAhNDw&input=)
```
2# "1",@"-[----->+<]>.*@@@!4<
```
A more readable version:
```
2 # " 1 # The steps:
" , @ " - # 1 (2) - Hexagony starts at the top-left of the hexagon
[ - - - - - # - This immediately puts 2 onto the stack
> + < ] > . * # 2 (#) - Since the stack is 2, this makes the 2nd pointer the
@ @ @ ! 4 < # - new current pointer
> 6 = . . # 3 (*) - The position of the 2nd pointer is in the left-most
. . . . # - position. This sets the stack to the product
- of the two neighbours which is zero
# 4 (<) - Changes the pointer direction to west
# 5 (4) - Sets the stack to 4
# 6 (!) - Outputs the decimal 4
# 7 (@) - Terminates the program
```
### Whitespace (prints `5`):
[Try it online](http://whitespace.kauaveel.ee/)
Since other characters are ignored but whitespaces and tabs, we are left with the following:
```
SSTST # This pushes 5 onto the stack
T #
ST # This prints the decimal
```
### [AniRad](https://github.com/Adriandmen/AniRad) version 0.2 (prints `6`):
Somehow this works for version 0.2, but gives an error for version 0.4. I have no clue why. You can find version 0.2 [here](https://github.com/Adriandmen/AniRad/blob/bacf7521e12f0f552846224d8331634103cd682d/AniRad.py). In order to run this, you can copy and paste the interpreter's code to [repl.it](https://repl.it/) and run it. After that, you only need to paste the program to STDIN and run it.
```
2# "1",@"-[----->+<]>.*@@@!4< # (#) Starts at the hashtag (starting point)
# Direction is down
# (>) When the pointer gets to the '>', it changes
>6= # its direction
# (6) Puts 6 onto the stack
# (=) Pushes the result and terminates
```
[Answer]
## JavaC++C, 363/27 = 13.4....
Java prints 1, C++ prints 2, C prints 3. Not breaking any records here (because Java), but I really like the clever, abusive way of making a polyglot in these languages that I discovered.
```
//\u000a/*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/*\u002a/
import static java.lang.System.out;
public class P{//*/
/*\u002a/public static void//*/
main(/*\u002a/String[] args//*/
){//\u000a/*
out.print=p;
//\u002a/
out.print(1);}
/*\u002a/}//*/
```
This is a mess. Here's a breakdown of how it works. The Unicode literals (`\u000a`, otherwise known as a linefeed, and `\u002a`, otherwise known as `*`) are expanded by the Java compiler into their actual characters. So, here is what the Java compiler sees:
```
//
/*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/**/
import static java.lang.System.out;
public class P{//*/
/**/public static void//*/
main(/**/String[] args//*/
){//
/*
out.print=p;
//*/
out.print(1);}
/**/}//*/
```
All that stuff in the beginning is ignored because it's all wrapped in a multi-line comment (`/* ... */`). Later on, we see that mixing single-line and multi-line comments allows us to control exactly which parts are commented out in each language. In the main method, we start a multi-line comment, and then have `//*/`. Ordinarily, this would be a single-line comment, but since we are in a multi-line comment, the `//` doesn't do anything, allowing the `*/` to close it.
This is the equivalent Java code, with comments removed:
```
import static java.lang.System.out;
public class P{
public static void
main(String[] args
){
out.print(1);}
}
```
Here is what the C/C++ compiler sees (I've removed the Unicode literals, since they are not expanded by the compiler and thus don't do anything):
```
///*
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
//*/
/*/
import static java.lang.System.out;
public class P{//*/
/*/public static void//*/
main(/*/String[] args//*/
){//\/*
out.print=p;
///
out.print(1);}
/*/}//*/
```
Here, the single-line comments override the multi-line comment delimiters in the beginning, so all of the `#define`s and the `#include` get preprocessed. Next, multi-line comments are used to comment out the boiletplate code for Java. This is the equivalent code, with comments removed:
```
#include<stdio.h>
#ifdef __cplusplus
#define o "2"
#else
#define o "3"
#endif
int p(int a){printf(o);}
struct{int(*print)(int);}out;
main(
){
out.print=p;
out.print(1);}
```
A standard C/C++ polyglot trick (the `#ifdef __cplusplus`) is utilized to define a token `o` as either `"2"` or `"3"`, depending on if it's a C++ or a C compiler that is compiling the code. Next, we define a funtion `p` that takes a single (ignored) `int` argument and calls `printf`, using our newly-defined `o` token. As per usual, the return value is left out, since we're not in strict mode. Next, we define a `struct` with a single member, a function pointer whose signature matches `p`'s, and construct a single instance named `out`. In the main method (we leave off the `int` as usual), the address of `p` is assigned to `out.print` (so calling `out.print` calls `p`), and it is called.
If C++ wasn't included in the languages, we could drop all of the preprocessor code, and define `p` as `int p(int a){puts("2");}`. Unfortunately, C++ requires an `#include` to do I/O. If C wasn't included, we could drop the definition of `p` and the `#ifdef` preprocessor macro, and directly define a member function in the `struct` instead of needing a function pointer. Unfortunately, C does not support member functions.
[Answer]
## 4 languages, 28 bytes / 64 = 0.4375
```
print((0 and 3^1or 1/2>0)+1)
```
### 1. Python 2
`0` is falsy and `/` is integer division, so
```
(0 and 3^1 or 1/2 > 0) + 1 = (1/2 > 0) + 1 = (0 > 0) + 1 = False + 1 = 1
```
### 2. Perl (also Python 3)
`0` is falsy and `/` is float division, so
```
(0 and 3^1 or 1/2 > 0) + 1 = (1/2 > 0) + 1 = (0.5 > 0) + 1 = 1 + 1 = 2
```
### 3. Ruby
`0` is truthy and `^` is bitwise xor, so
```
(0 and 3^1 or 1/2 > 0) + 1 = xor(3,1) + 1 = 2 + 1 = 3
```
### 4. Lua
`0` is truthy and `^` is exponentiation, so
```
(0 and 3^1 or 1/2 > 0) + 1 = pow(3,1) + 1 = 3 + 1 = 4
```
Note that Lua and Ruby can't add booleans as though they are integers, hence the grouping of them together. Unfortunately `0and` doesn't work in Lua, so we can't save a byte there.
---
**Previous 17 byte version which prints 1 (Lua), 2 (Ruby), 3 (Python/Perl):**
```
print(2^(0 or 1))
```
-3 bytes thanks to @xnor for this version, making it a lot neater :)
[Answer]
# ~~6~~ 7 languages, ~~32~~ 37 bytes, score ~~0.148...~~ 37/73 ≈ 0.107872...
```
#7+!"@\"6.@;n5
print(4--int(-3/2)#"
)
```
### [Brainfuck-ng](http://esolangs.org/wiki/Brainfuck-ng)
`+` increments current cell, `!` prints as integer, `@` exits. `#` and `"` are NOPs.
### Python 2
First line is comment. Using integer division, calculates `4 - -int(-3 / 2) = 4 - -int(-2) = 4 - -(-2) = 4 - 2 = 2` and prints the result.
### Python 3
Same as previous, but with float division. `4 - -int(-3 / 2) = 4 - -int(-1.5) = 4 - -(-1) = 4 - 1 = 3`.
### Lua
`--` starts a comment, and `#` on the first line is a comment, so basically `print(4)`.
### ><>
`#` reflects IP, `5` pushes 5, `n` prints a number and `;` quits.
### Befunge
`#` skips over the `+`, `!` logically negates the top of the stack, `"@\"` pushes the string `@\`, `6` pushes 6, `.` prints a number and `@` quits.
### Pyth
`#` starts an infinite loop, dismissing any errors. `7` prints 7, then follows `+!"string")` which basically causes an error for not having two operands for `+`, terminating the program.
[Answer]
# 14 languages, 73 bytes, score = (73/14^3) = 0.02660349854
```
#Y2(3`5n~thneo e ;n@0d c
# -[>+<"9"L-----]>+.
14
print(int(15/2))+3
```
I can add some more langs, but I think I'll add what I have here.
## 1. [Brainbool](https://esolangs.org/wiki/Brainbool) ; [Try it online!](http://brainbool.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
The relevant code:
```
[>+< ]>+.
+
```
This is really just `+.+`, which outputs 1.
## 2. [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/tree/master/docs) ; [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz)
The `(` char stops interpreting the source code, so the relavent code is:
```
#Y2
```
This is equivalent to (in JavaScript)
```
var Y = []; toHex(Y); alert(2);
```
Which outputs 2.
## 3. Element ; [Try it online!](http://element.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
The relevant code:
```
3`
```
This captures `3` and prints it.
## 4. [Brainfuck](https://esolangs.org/wiki/brainfuck) ; [Try it online!](http://brainfuck.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
The relevant code is:
```
-[>+< -----]>+.
- - +
```
Which is the standard way of generating 4's char code and outputting it, and some other stuff after it.
## 5. Reng ; [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)
`~` terminates the program, so the relevant code here is:
```
#Y2(3`5n~
```
`#` redefines `Y` to be the TOS, in this case, `0`. `2` pushes 2; `(` rotates the stack N times, popping N from the stack; `3`` pushes -3; and finally, `5n` prints `5`.
## 6. ETA ; [Try it online!](http://eta.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
ETA only reads the letters E, T, A, O, I, N, S, H, so the code only executed is this:
```
n thneo e n
int int
```
Super-relevant code:
```
n thneo
```
Or, equivalently: `nthne o`. `n...e` is a base-7 literal, and `thn` is the base-7 number for 54. `o` outputs this character. The submission errors out, but I don't know why.
## 7. Python 3
What it sees:
```
# comment
# comment
14
print(int(15/2))+3
```
`15/2` yields 7.5, as `/` is float division. `int(...)` makes the number an int, which is then printed. The program errors out when `+3` is encountered.
## 8. Julia
Julia sees:
```
# comment
# comment
14
print(int(15/2))+3
```
Instead of truncating 15/2, Julia rounds it up, yielding 8. It prints this, then errors out on encountering +3.
## 9. Fission ; [Try it online!](http://fission.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
Relevant code:
```
<"9"L
```
I got this idea from [Martin's Fission portion](https://codegolf.stackexchange.com/a/65643/31957) (more like stole it). `L` begins a left-facing thing, captures `9`, and ends with `<`.
## 10. Whitespace ; [Try it here!](http://ws2js.luilak.net/interpreter.html)
The relevant code, translating spaces into `S` and tabs into `T`:
```
SSSTSTS
T
ST
```
It pushes 10 to the stack and outputs it as a number (`T\nST`).
## 11. Python 2
Python 2 sees this:
```
# comment
# comment
14
print(int(15/2))+3
```
`(int(15/2))+3` is evaluated to be 11, and that's printed.
## 12. Gol><> ; [Try it here!](https://golfish.herokuapp.com/?code=%23Y2%283%605n%7ethneo%20e%20%20%09%20%09%3Bn%400d%20c%0A%23%09-%5B%3E%2B%3C%229%22L-----%5D%3E%2B.%0A14%20%09%0Aprint%28-int%28-15%2F2%29%29%2B3&input=)
Relevant code:
```
# ;n@0d c
```
This uses the trick used in [Martin's answer](https://codegolf.stackexchange.com/a/65643/31957) that `@` rotates different directions in ><> and Gol><>. `#` mirrors, `c` pushes 12, `d` pushes 13, `0` pushes 0, and `@` brings `c` to the top of the stack, then being outted and printed with `;n`.
## 13. ><> ; [Try it online!](http://fish.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgoxNCAJCnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
Relevant code:
```
# ;n@0d c
```
Again using that `@` rotates different directions in ><> and Gol><>. `#` mirrors, `c` pushes 12, `d` pushes 13, `0` pushes 0, and `@` brings `d` to the top of the stack, then being outted and printed with `;n`.
## 14. Golfscript ; [Try it online!](http://golfscript.tryitonline.net/#code=I1kyKDNgNW5-dGhuZW8gZSAgCSAJO25AMGQgYwojCS1bPis8IjkiTC0tLS0tXT4rLgogCTE0CnByaW50KC1pbnQoLTE1LzIpKSsz&input=)
What it sees:
```
# comment
# comment
14
print(-int(-15/2))+3
```
It pushes `14`, `print`s it, and errors. ~~Stolen~~ inspired by [Sp3000's answer](https://codegolf.stackexchange.com/a/78292/31957).
[Answer]
## BFSRS><>funge93thon123, 73/343 ≈ 0.212827...
Brainfuck, [Seriously](http://github.com/Mego/Seriously), ><>, Befunge-93, Python 1, Python 2, Python 3
```
# 4['.]@kX21z-[>+<-----]>--.<;n3
import sys;print(3+int(sys.version[0]))
```
Contains unprintables, hexdump (reversible with `xxd -ps -r`):
```
2320345b272e5d406b5832317a7f2d5b3e2b3c2d2d2d2d2d5d3e2d2d2e3c
3b6e330a696d706f7274207379733b7072696e7428332b696e7428737973
2e76657273696f6e5b305d2929
```
I'll be adding more languages (and probably bytes) over time. Languages in the header are listed in order of what they print. Assumes 8-bit wrapping cells and a tape that won't complain about going left of the initial position (wrapping or infinite) for Brainfuck.
Brainfuck:
```
[.] initial value of first cell is 0, so loop is skipped
-[>+<-----]>-- push 49 (ASCII ordinal of 1)
. print "1"
< move to blank cell
[0] skip loop because cell is 0
everything else is ignored
```
[Seriously](http://seriouslylang.herokuapp.com/link/code=2320345b272e5d406b5832317a7f2d5b3e2b3c2d2d2d2d2d5d3e2d2d2e3c3b6e330a696d706f7274207379733b7072696e7428332b696e74287379732e76657273696f6e5b305d2929&input=):
```
# 4['.]@ does some stuff we don't care about
kX pop entire stack, push as list, discard (essentially the same as é, but is ASCII so we can use Python)
2 push 2
1z pop 1 item from stack and print (used instead of . so Brainfuck doesn't print here; same as ü in this scenario, but is ASCII so we can use Python)
0x7f terminate program
everything else is ignored
```
`><>`:
```
# mirror, reverse direction
3n; push 3, print "3", end (reversed because IP is scanning RTL at this point)
everything else is ignored
```
Befunge-93:
```
# jump over the space
4['.] push 4, print 4 (brackets and ' do nothing)
@ end program
everything else is ignored
```
Python 1 (thanks muddyfish):
```
# 4['.]@kX21z-[>+<-----]>--.<;n3 comment; ignored
import sys;print(4+int(sys.version[0])) prints 4+1=5
```
[Python 2](http://ideone.com/t539zb):
```
# 4['.]@kX21z-[>+<-----]>--.<;n3 comment; ignored
import sys;print(4+int(sys.version[0])) prints 4+2=6
```
[Python 3](http://ideone.com/cPJOci):
```
# 4['.]@kX21z-[>+<-----]>--.<;n3 comment; ignored
import sys;print(4+int(sys.version[0])) prints 4+3=7
```
[Answer]
# 4 Languages (Befunge-93, Microscript II, Microscript, and Foo), score 7/64=0.109
```
"4"1.@2
```
Befunge: Push 4, push 1, print 1, and terminate.
Microscript II: Produce the string "4", discard it, take the square root of one, discard that, and finally set x to 2. This is then printed implicitly.
Microscript: Push 52 to the stack (which will never actually be used for the remainder of the program), increment the register (initially zero) by one, then increment the register by two. This is then printed implicitly.
Foo: Print the string "4", then push 2
[Answer]
## 7 languages, 287 / 7^3 = 0.836
~~Probably the lowest score that gets in, anyway I like this 3 versions of C polyglot.~~
Added the boring Python solution to at least qualify for the "3 unique" languages bounty.
Added Java by abusing C trigraphs for different comment intepretations.
Works in:
* Python 1
* Python 2
* Python 3
* C89
* C99
* C++
* Java
golfed version:
```
/*
*??/
/
#include <stdio.h>
#ifndef __cplusplus
#define true 8/*
import sys
print(sys.version[0])
'''
#*??/
/
#endif
int main(){int a=(true>1)?-6:3;printf("%d",(true//*
+a
//**??/
/+2));}
#define a \
'''
/**\u002f
public class p{public static void main(){System.out.println("7");}}
/**/
```
Ungolfed:
```
/*
*??/
/
#include <stdio.h>
#ifndef __cplusplus
#define true 8/*
import sys
print(sys.version[0])
'''
#*??/
/
#endif
int main()
{
int a = (true > 1) ? -6 : 3;
printf ("%d", (true//*
+a
//**??/
/
+2));
}
#define a \
'''
/**\u002f
public class p
{
public static void main()
{
System.out.println("7");
}
}
/**/
```
Ok this is probably getting kinda weired and I hope my english skills are good enough to explain it ordinary.
First of all I'll explain the different kinds of comments I used to encapsulate the language structures each for its own.
So lets take the first block:
```
/*
*??/
/
```
For Java this is just the beginning of an multi line comment. But... in C99/89/++ this evaluates to
```
/*
*/
```
Since `??/` is a trigraph for `\` while in C the `\` character is kind of consistent and even consumes line breaks in its commandfunctionality. This causes the result of an `\n` to be just "displayed" instead of beeing line breaks. that means, given this byte array representing the first block:
[`/`][`*`][`\n`][`*`][`?`][`?`][`/`][`\n`][`/`] would be after trigraph evaluation: [`/`][`*`][`\n`][`*`][`\`][`\n`][`/`]
Where the consistent functionality of the `\` triggers and "consumes" the `\n` so the remaining and finaly in C langs evaluated bytes are: [`/`][`*`][`\n`][`*`][`/`]
But about all this java doesn't know anything and treats all that follows as an comment untill this trick gets reverted.
(to be continued!)
[Answer]
# [Subskin](https://esolangs.org/wiki/Subskin), Brainfuck and [Fob](http://esolangs.org/wiki/fob) 27 bytes / 3^3 = 1
```
0#>&$3#<>$-[----->+<]>-.
31
```
### Subskin
```
0
31
```
We set the instruction pointer (doesn't matter here) to `0` and the output register to `31`. If the contents of the output register is `>= 0`, we output the contained value as a `char`. All other code is ignored.
### Brainfuck
```
-[----->+<]>-.
```
Puts `3` in the register, decrements the value once with `-` and finally outputs with `.`.
### Fob
```
#>&$3#<>$
```
This is a little bit more tricky, since Brainfuck also reads the `<` and `>` instructions in Fob. We enter execution mode with `#` and increment Brainfuck's pointer by one which makes it easier on us later. We have nothing to execute yet, so nothing is executed.
We enter the accumulator mode with `$`, throw in a `3`, enter execution mode again, push the accumulator contents to the stack with `<` and finally we output the content with `>`.
To prevent Brainfuck from screwing with the program we enter accumulation mode again with `$`.
[Answer]
## Python 1|2|3, 27 bytes / 27 = 1
```
print(len("\xabc")+(1/2>0))
```
@sweerpotato's use of version numbers made me wonder whether it was possible to distinguish the Pythons in less. Here's the best I've found.
### Explanation
To distinguish Python 3 from the earlier versions, we make use of the standard integer division vs. floating point division trick. `(1/2>0) == (0>0)` returns 0 pre-Python 2.3 or `False` from Python 2.3 onwards, and `(1/2>0) == (0.5>0)` returns `True` for Python 3.
To distinguish Python 1 from the rest, we take the length of the string `"\xabc"`, which is length one in Python 1 and length two from Python 2 onwards. Why? Because
>
> The \x escape in string literals now takes exactly 2 hex digits. Previously it would consume all the hex digits following the ‘x’ and take the lowest 8 bits of the result, so \x123456 was equivalent to \x56.
>
>
>
(From [What's New in Python 2.0](https://docs.python.org/2/whatsnew/2.0.html))
[Answer]
## 7 Languages, 55 / 7^3 ≈ 0.16035
Runs in PowerShell v1, v2, v3, v4, and v5, Foo, and Pyth
```
#7.q"6""
$p=$PSVersionTable;($p.PSVersion.Major,1)[!$p]
```
Digits 1-5 use similar logic to sweerpotato's [answer](https://codegolf.stackexchange.com/a/65652/42963). The `$PSVersionTable` special variable was introduced in PowerShell v2, and contains a full build list, revisions, etc. Here's an example output of the variable:
```
PS C:\Tools\Scripts> $PSVersionTable
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.34209
BuildVersion 6.3.9600.17400
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
```
In this code, we first store it into `$p` so that the code length is shorter. Then, we check for its existence by leveraging the variable as an index into a two-item array:
* If the variable doesn't exist, PowerShell will dynamically create it and assign it `$NULL`, the `!` of which is `$TRUE`, or `1`, which corresponds to the second element in the array, which outputs `1`.
* If the variable does exist (as is the case in v2+), then the `!` of the variable results in `$FALSE` or `0`, which indexes to the first element, which outputs the version number.
Using Foo for 6, we leverage that `#` is a comment in PowerShell, so that's ignored when executing it in a PS environment. However, Foo will happily spit out the number `6` and then proceed through the rest of the program, which does nothing.
Using Pyth for 7, we return `7`, then immediately quit with `.q`, so the infinite while-true loop that started with `#` doesn't matter. Since we have something left that gets implicitly printed. Thanks to @[FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for this addition.
Edit - Golfed a handful of bytes thanks to [Mauris](https://codegolf.stackexchange.com/users/3852/mauris)
Edit - clarified Pyth explanation thanks to [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000)
[Answer]
# Python 3, Ruby, Perl, C, C++, Objective-C 202 bytes / 6^3 = 0.935...
This was quite fun actually, and a lot of playing with booleans.
You can all versions of the code at the following [site](http://codepad.org/), by copy-and-pasting the code into the interpreter.
```
#include <stdio.h> /*
print ((("0"+"0"==0)and 3) or (0and 2or 1));
__DATA__ = 1
"""""
*/
int main(){putchar(
#ifdef __OBJC__
'6'
#else
#ifdef __cplusplus
'5'
#else
'4'
#endif
#endif
);return 0;}/*
"""
#*/
```
### Python 3, prints `1`
The trick is the following:
```
print ((("0"+"0"==0)and 3) or (0and 2or 1));
```
This will print `1`
### Ruby, prints `2`
The interpreted code for Ruby is:
```
print ((("0"+"0"==0)and 3) or (0and 2or 1));
```
So this prints `2`
### Perl, prints `3`
The interpreted code for Perl is:
```
print ((("0"+"0"==0)and 3) or (0and 2or 1));
__DATA__ = 1
```
First of all, the `__DATA__` token tells the Perl compiler that the compilation is finished. Everything after is ignored.
```
print ((("0"+"0"==0)and 3) or (0and 2or 1));
```
And prints `3`
### C, prints `4`
The interpreted code is quite different from the others:
```
#include <stdio.h>
int main(){putchar(
#ifdef __OBJC__
'6'
#else
#ifdef __cplusplus
'5'
#else
'4'
#endif
#endif
);return 0;}
```
This will simply print the char `4`.
### C++, prints `5`
The same as the C code
This will print the char `5`.
### Objective-C, prints `6`
The same as the C code
This will print the char `6`.
[Answer]
# [Craneflak](https://github.com/Flakheads/CraneFlak), [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak), [Rain-Flak](https://github.com/DJMcMayhem/Brain-Flak), [BrainHack](https://github.com/Flakheads/BrainHack), [Brain-Flueue](https://github.com/DJMcMayhem/Brain-Flak), [miniflak](https://github.com/DJMcMayhem/Brain-Flak), [miniHack](https://github.com/Flakheads/BrainHack): .1020
```
(([]()()()<()()()>)()()){}#{}({}())
```
[Try it online!](https://tio.run/##lY@xDoIwEIZ3nuKCSzsUHkDDoItOLm7GmLaW0FBa05ZEQ3j2SiXKwgB3l7t/uO/yH6OuCkHwykCK0PWGcMzdOIpvx12/6Xo0FMYpFOCF85l/@SQZsYOlWpSK1qCNB6mdp0qJBxgNl9M5TWzL3pCbp8@ZpVKTuDrKe5SZZUAUV9Q5yafjC6gp/tQEVJTX@T6q46BgLn7UNv6xzGapWtEKWGWTqEZqudYmaWZthvAB "Bash – Try It Online")
## Explanation
The first thing going on here is that there is a difference in the way comments are read between the BrainHack, CraneFlak and Rain-Flak interpreters. Craneflak has no comments, in Rain-Flak `#` comments out the rest of the line and in BrainHack `#{...}` comments out the insides.
So here's what each language reads:
```
Rain-Flak: (([]()()()<()()()>)()()){} -> 3
BrainHack: (([]()()()<()()()>)()()){}({}()) -> 4
Craneflak: (([]()()()<()()()>)()()){}{}({}()) -> 1
```
The next thing is the difference between the brain-flaks and the miniflaks. Both Rain-Flak and BrainHack support miniflak, where all of the extra operations are simply removed. This means that they lose the `[]` and `<...>`
```
Rain-Flak: (()()()()()()) -> 6
BrainHack: (()()()()()())({}()) -> 7
```
Next we have the difference between Brain-Flak and Brain-Flak Classic. In Classic `[]` is `-1` instead of the stack height, which means that our result is 1 less than in regular Rain-Flak, making it 2.
Lastly we have the difference between brain-Flak and brain-flueue. In brain-flueue a queue is used instead of a stack. Normally brain-flak pushes 3 then 5 and pops the 5 away, however in brain-flueue the pop gets rid of the 3 and not the 5.
[Answer]
# 6 Languages, 38 / 6^3 = 0.17592ÃÖ5ÃÖ9ÃÖ
### [Whitespace](http://web.archive.org/web/20150523181043/http://compsoc.dur.ac.uk/whitespace/index.php), Brainfuck, Ruby, [Labyrinth](https://github.com/mbuettner/labyrinth), Foo, [Seriously](https://github.com/Mego/Seriously/)
Legend:
`£`: tab
`•`: space
`§`: 0x7f
```
puts•2;#4!@•-[>+<-----]>6.§"5"•£
£
•£
```
This contains unprintable characters, so here's the hexdump:
`7075747320323b23342140202d5b3e2b3c2d2d2d2d2d5d3e362e7f22352220090a090a20090a`
## Explanation:
### Whitespace
[Try it online.](http://whitespace.tryitonline.net/#code=cHV0cyAyOyM0IUAgLVs-KzwtLS0tLV0-Ni5_IjUiIAkKCQogCQoKCg&input=) (Note: my program omits the closing three linefeeds to terminate the program, I wrote/tested this on [Whitelips](http://whitespace.kauaveel.ee/) and that produces the proper output there, but does not on Try It Online, so the linked program has those two characters added. As far as I can tell, some interpreters let you do that, others get stuck in an infinite loop without the explicit termination)
(omitting ignored characters)
`space``space``space``tab``enter`: push a 1 onto the stack
`tab``enter``space``tab`: output the top of the stack
### Ruby
Shouldn't need explaining. Prints 2, treats the rest of that line (ergo, the brainfuck program) as a comment, treats the rest of the file as empty.
### Brainfuck
[Try it online.](http://brainfuck.tryitonline.net/#code=cHV0cyAyOyM0IUAgLVs-KzwtLS0tLV0-Ni5_IjUiIAkKCQogCQo&input=)
Requires an interpreter that supports underflow. Underflows the first cell to 255 then uses that for a loop counter to generate 51, which is the ascii code for 3.
### Labyrinth
[Try it online.](http://labyrinth.tryitonline.net/#code=cHV0cyAyOyM0IUAgLVs-KzwtLS0tLV0-Ni5_IjUiIAkKCQogCQo&input=)
(omitting the last two lines for legibility because they are never reached)
```
puts•2;#4!@ -[>+<-----]>6.§"5"•£
puts• skipped
2 push 2 onto stack
; pop 2 from stack
# push current stack depth (0) to stack
4 push 4 to stack
! print top of stack as integer
@ program terminates
```
### Foo
[Try it online.](http://foo.tryitonline.net/#code=cHV0cyAyOyM0IUAgLVs-KzwtLS0tLV0-Ni5_IjUiIAkKCQogCQo&input=)
The only thing that affects output is "5", which prints 5.
### Seriously
[Try it online.](http://seriouslylang.herokuapp.com/link/code=7075747320323b23342140202d5b3e2b3c2d2d2d2d2d5d3e362e7f22352220090a090a20090a&input=)
```
puts•2;#4!@ -[>+<-----]>6.§"5"•£
puts•2;#4!@ -[>+<-----]> assorted stack manipulation that doesn't affect this program
6 push 6 to the stack
. output top of the stack
§ (0x7f) terminate program
```
[Answer]
# 5 languages, [Chaîne](http://conorobrien-foxx.github.io/Cha-ne/?code%3D2|%3C%C2%AB%2B!%40%223%22.N%2Bm%0A%0A5N%C2%BB%7C|input%3D), [Minkolang](http://play.starmaninnovations.com/minkolang/?code=2|%3C%C2%AB%2B!%40%223%22.N%2Bm%C2%BB&input=), [Foo](http://foo.tryitonline.net/#code=MXw8wqsrIUAiMyIuTivCuw&input=), [Brainf\*\*k-ng](https://esolangs.org/wiki/Brainfuck-ng), and [Vitsy](http://vitsy.tryitonline.net/#code=Mnw8wqsrIUAiMyIuTittCgo1TsK7&input=), 21 / 5^3 = 0.168
```
2|<¬´+!@"3".N+m
5N»
```
# Brainf\*\*k-ng
```
2|<¬´+!@"3".N+m
5N»
< go left (should still be ok)
+! output 1
@ halt execution
```
# Chaîne
```
2|<¬´+!@"3".N+m
5N»
2 «add 2 to the current string»
|< «take off and put on the string (no op)»
« «comment»
»
«implicit output»
```
# Foo
```
2|<¬´+!@"3".N+m
5N»
"3" print three
```
# Minkolang
```
2|<¬´+!@"3".N+m
5N»
2 C push 2 to the stack [2] C
| C mirror C
2 C push 2 to the stack [2,2] C
m C ignored C
+ C add top two [4] C
N C output C
. C terminate program C
```
# Vitsy
```
2|<¬´+!@"3".N+m
5N»
2 push 2
| mirror
2 push 2
m pop 2, goto line 2
5 push 5
N output 5
» ignored
```
---
I can probably add ><> or something.
[Answer]
# 5 Languages, 18 bytes / 5^3 = 0.144
Runs in [Brainbool](https://esolangs.org/wiki/Brainbool), [Mathematica](http://www.wolfram.com/mathematica), [Foo](https://esolangs.org/wiki/Foo), [><>](https://esolangs.org/wiki/Fish) and [Befunge-93](https://esolangs.org/wiki/Befunge).
```
4!<n;+Print@2"3".5
```
### Brainbool
Brainbool is like Brainfuck, but it operates only on bits, and its input and output consists solely of `0` and `1`.
```
4!<n;+Print@2"3".5
< move the pointer to the left
+ logic not
. print the current cell
```
### Mathematica
In Mathematica, everything is an expression and has a value. `Print@2` prints `2` and returns the symbol `Null`. After that, the code does some symbolic calculations, but doesn't print anything.
### Foo
`"3"` prints 3. I don't know what the other parts do.
### ><>
```
4!<n;+Print@2"3".5
4 push 4
! skip the next command
n pop and print it as a number
; end the program
```
### Befunge
```
4!<n;+Print@2"3".5
4 push 4
! logical not
< makes the program counter travel to the right
! logical not
4 push 4
5 push 5
. pop and print it as a number
"3" push the string "3"
2 push 2
@ end the program
```
---
# 12 Languages, 35 bytes / 12^3 = 0.0202546...
Using [sweerpotato's trick](https://codegolf.stackexchange.com/a/65652/9288), cheap but powerful.
Runs in [Brainbool](https://esolangs.org/wiki/Brainbool), [Mathematica 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 and 10.0](http://www.wolfram.com/mathematica/quick-revision-history.html), [Foo](https://esolangs.org/wiki/Foo) and [><>](https://esolangs.org/wiki/Fish).
```
cn;+"11".Print@Floor@$VersionNumber
```
[Answer]
# [Milky Way 1.0.2](https://github.com/zachgates7/Milky-Way), [CJam](http://cjam.aditsu.net/) and [STXTRM](http://esolangs.org/wiki/STXTRM), 20 bytes / 3^3 = 0.741
I imagine there is at least one other language that I could add.
```
'2"3""1"1<<1>;;"2"3;
```
---
## Explanation
---
### [Milky Way](https://github.com/zachgates7/Milky-Way), `1`
In Milky Way, strings are only denoted by pairs of double quotes. A single quote reads input from the command line; if there is none, it pushes an empty string. Greater than and less than signs will rotate the entire stack rightward and leftward, respectively. Finally, a semicolon swaps the top two stack elements.
Here is a stack visualization (stack shown is the result of the listed operation after it has occurred):
```
["", 0] # default stack
["", 0, ""] # ' # read input from command line
["", 0, "", 2] # 2 # push 2 to the stack
["", 0, "", 2, "3"] # "3" # push "3" to the stack
["", 0, "", 2, "3", "1"] # "1" # push "1" to the stack
["", 0, "", 2, "3", "1", 1] # 1 # push 1 to the stack
[0, "", 2, "3", "1", 1, ""] # < # rotate the stack leftwards
["", 2, "3", "1", 1, "", 0] # < # rotate the stack leftwards
["", 2, "3", "1", 1, "", 0, 1] # 1 # push 1 to the stack
[1, "", 2, "3", "1", 1, "", 0] # > # rotate the stack rightward
[1, "", 2, "3", "1", 1, 0, ""] # ; # swap the top two stack elements
[1, "", 2, "3", "1", 1, "", 0] # ; # swap the top two stack elements
[1, "", 2, "3", "1", 1, "", 0, "", 2] # "2" # push 2 to the stack
[1, "", 2, "3", "1", 1, "", 0, "", 2, "3"] # 3 # push "3" to the stack
[1, "", 2, "3", "1", 1, "", 0, "", "3", 2] # ; # swap the top two stack elements
```
---
### [CJam](http://cjam.aditsu.net/), `2`
In CJam, strings are also denoted by double quote pairs. A single quote pushes the character code of the following character. When a character code is output, it is output as its corresponding character. Greater-than and less-than signs act as expected, evaluating the order of the top two stack elements. Finally, a semicolon discards the top stack element. On termination of the program, the contents of the stack are output.
Here is a stack visualization (stack shown is the result of the listed operation after it has occurred):
```
[] # default stack
['2] # '2 # push the character code of "2" to the stack
['2, "3"] # "3" # push "3" to the stack
['2, "3", "1"] # "1" # push "1" to the stack
['2, "3", "1", 1] # 1 # push 1 to the stack
['2, "3", "1"] # < # leave the greater of the top two stack elements on the stack
['2, 0] # < # leave the greater of the top two stack elements on the stack
['2, 0, 1] # 1 # push 1 to the stack
['2, 1] # > # leave the lesser of the top two stack elements on the stack
['2] # ; # pop the top stack value
[] # ; # pop the top stack value
['2] # "2" # push the character code of "2" to the stack
['2, "3"] # 3 # push "3" to the stack
['2] # ; # pop the top stack item
```
---
### [STXTRM](http://esolangs.org/wiki/STXTRM), `3`
In MSM, anything that is not an operator is pushed to the stack as a character. A semicolon duplicates the top stack element. The program continues until there are no more operators, or there is a single element on the stack.
The final character on the stack is `3`, which is duplicated by the final operator. `3` is the topmost element at the end of the program, so it is output.
[Answer]
# 5 languages, 18 bytes / 5^3 = 0.144
**[Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros), [Pip](http://github.com/dloscutoff/Pip), QBasic, [Foo](http://esolangs.org/wiki/Foo), and Pyth**
```
5'"4"()"
1?3'@n()2
```
### 1. Ouroboros
Each line of the program represents a snake eating its tail.
**Snake 1**
Push `5`, `'` is a no-op, push `52` (ASCII code of `"4"`). `(` causes the snake to pop a number and eat that many characters of its tail. Since this results in swallowing the instruction pointer (and the entire snake), execution halts.
**Snake 2**
Push `1`, push a random number (`?`), push `3`, `'` is a no-op. `@` rotates the `1` to the top of the stack and `n` outputs it as a number, leaving the `3` on top of the stack. Then `(` eats this many characters from the end of the snake, swallowing the instruction pointer and halting.
You can run this program online in the Stack Snippet interpreter [here](https://codegolf.stackexchange.com/a/61624/16766).
### 2. Pip
Most of the program consists of expressions which are evaluated and discarded:
* `5`
* `'"` (character literal)
* `4`
* `"()"`
* `1?3'@` (ternary expression)
* `n` (variable, = newline)
* `()` (nil)
Finally, the last expression, `2`, is printed.
### 3. QBasic
Everything after `'` is a comment. The first line thus boils down to `5`, a line number. On the second line, `1` is a line number and `?3` is a shortcut for `PRINT 3`.
(Apparently having line numbers out of order isn't a problem, though it would be easy to fix if it were.)
### 4. Foo
Almost everything is no-ops. `"4"` prints `4`. The parentheses (x2) are a loop that runs until the current array cell is zero, which is true immediately and the loop exits. `@`, when not followed by a number, takes the value of the current array cell (initialized to 0) and pushes it to the stack.
I'm not entirely sure how the second, unmatched `"` is supposed to be handled. The [online version](http://foo.tryitonline.net/#code=NSciNCIoKSIKMT8zJ0BuKCky&input=) seems to add a newline to the output, which the rules of the challenge allow.
### 5. Pyth
`5` is output. Then the program encounters `'"4"`, which tries to read from a file named `4`. As long as no such file exists, I think this should terminate the program with an error. (The [online version](http://pyth.herokuapp.com/?code=5%27%224%22%28%29%22%0A1%3F3%27%40n%28%292&debug=0) says `name 'open' is not defined`--I assume because opening files isn't allowed online.)
The stray `"` at the end of line 1 ensures that line 2 doesn't cause a syntax error before execution.
[Answer]
## 4 languages, 24 bytes, 24/4^3=0.375
```
print(1//0.5--1+1/2*2
);
```
## 1. PHP
PHP executes `print(1);` which equals 1
## 2. Lua
Lua executes `print(1//0.5);` which equals 2
## 3. Python 2
Python 2 executes `print(1//0.5--1+1/2*2);` which equals 3 (integer division)
## 4. Python 3
Python 3 executes `print(1//0.5--1+1/2*2);` which equals 4 (float division)
[Answer]
# Brainfuck-ng, Foo, ><>, 9 bytes / 3^3 = 0.333...
```
#+!"2";n3
```
### Brainfuck-ng
The only characters it recognizes are `+` and `!`:
```
+ Increment cell by one
! Print as integer
```
Prints `1`
### Foo
Prints everything in quotes.
```
"2"
```
Prints `2`
### ><>
`#` Mirrors the point to the left, `3` pushes *3* to the stack, `n` outputs it as an integer, `;` stops the program.
```
# ;n3
```
[Answer]
# Alphapolyglot, 8 languages, 37 bytes, score 0.072265625
```
8
"6";;7iiiio hkaeeeaeaeawxzz ax zaCM
```
Features AlphaBeta, Beatnik, Commentator, Deadfish~, evil, Foo, Golfscript, and Husk. Thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo) for helping with Husk.
## Explanation
### AlphaBeta
```
8"6";;7iiiio hkaeeeaeaeawxzz a # Garbage
x z # Clear register 1 and 3
a # Add 1 to register 1
C # Set register 3 to register 1
M # Output register 3 as a number
```
### Beatnik
`iiiio hkaeeeaeaeawxzz ax zaCM` is `5 50 9 17`.
`5 50` pushes 50 (2 in ASCII)
`9` outputs the top of the stack as a character.
`17` exits the program.
### Commentator
There are 3 spaces in the program, each one increments the active accumulator.
### Deadfish~
```
8"6";;7iiii # Increment 4 times
o # Output as a number
h # End program
kaeeeaeaeawxzz ax zaCM # Garbage
```
### evil
```
8"6";;7iiiio hk # Garbage
aeeeaeaea # Increment and weave the accumulator to 53 (5 in ASCII)
w # Output accumulator as a character
xzz ax zaCM # More garbage
```
### Foo
```
8 # Garbage
"6" # Output 6
;;7iiiio hkaeeeaeaeawxzz ax zaCM # Garbage
```
### Golfscript
```
8 # Push 8
"6" # Push the string 6
;; # Pop and discard twice
7 # Push 7
iiiio hkaeeeaeaeawxzz ax zaCM # Garbage
```
### Husk
The first line is executed first.
```
8 # Return 8
```
The second line isn't executed.
[Answer]
# 3 Languages, ~~82~~ 83 / 3^3 = 3.074...
Works in [???](http://esolangs.org/wiki/%3F%3F%3F), [Whitespace](http://esolangs.org/wiki/whitespace), and [Beatnik](http://esolangs.org/wiki/Beatnik). Or rather, it *should* work in those languages but I am not going to be able to test them for a few days. Anyway, here is the code:
```
K... Jax... Jy... Jy... ...
My... My...
... ... ......................XO!
```
**1. *???***
```
.................................................!
```
??? is basically brainfuck but it uses common punctuation as commands instead of the traditional characters. `.` increments the current memory cell, which is done 49 times. `!` takes the current memory cell and prints it as a character, here `1`.
**2. *Whitespace***
```
[Space][Space][Space][Tab][Line Feed]
[Tab][Line Feed]
[Space][Tab]
```
Whitespace is a language that ignores all non-whitespace characters. Here I've converted it to an easily readable form. The first line pushes `2` onto the stack, and the second two lines print the top of the stack as a number, here `2`.
Note that in the combined code, I have substituted tabs with four spaces due to technical limitations.
**3. *Beatnik***
```
K Jax
Jy Jy
My My
XO
```
Beatnik is a language where each word is converted to its Scrabble score, then those scores are interpreted as commands. The first line pushes `17` onto the stack. The second line duplicates the top of the stack twice and the third line adds the top to elements of the stack together twice, effectively tripling `17` into `51`. The last line prints the character on the top of the stack, here `3`.
Note that I am using Beatnik at Face Value, assuming there is not an error in the original Beatnik specification. Also note that I am using the North American English Scrabble scoring system.
If it is not clear by now, each of these languages only accepts a certain type of character (punctuation, whitespace, and letters, respectively) so writing this polyglot was as easy as writing the individual programs. The only real "trick" is using the Whitespace code to separate the words from Beatnik. Beyond that, the individual programs do not overlap whatsoever.
[Answer]
## 5 languages, 175 / 5^3 = 1.4
I decided to post a different answer since the bounty is changing the requirements in a way that made me feel unsaitsfyed with my first answer (but which is still satisfying me in the way of the generall challange!)
So here is my solution that qualifys for the bounty challange:
It compiles in
* C99
* objC90
* C++0x
* Ruby
* Perl
```
#if __cplusplus
#define x\
=begin\
=pod
#endif
int a=
#ifndef x
1//**/
+1
#else
3
#endif
;int main(){printf("%d",a);}
#ifdef f
=end
puts 5;
=begin
=cut
print"4";
=end
#endif
```
[Answer]
# 3 languages, 15 bytes, score 0.555...
Gonna add more languages later.
```
2//1+1#üòÖüò®
```
### 1. Emotinomicon
Emotinomicon pretty much ignores any text that isn't a string. `üòÖ` pushes 1 to stack and `üò®` outputs the TOS as a number.
### 2. Javascript
Comments in Javascript start with `//`, so only the `2` part gets executed.
### 3. Python 2/3 REPL
Comments in Python start with `#`, so only the `2//1+1` part gets executed. `//` is integer division in Python 3, and it is the same as `/` in Python 2. 2 divided by 1 is 2, plus 1 is 3.
[Answer]
## 4 languages, 97 bytes, 0.37890625
```
s="1";s=~-3;2//2;'''/.to_s.ord;"=;print 4;
__DATA__
=1;
";#'''#";print=s=>console.log(3)
print(s)
```
### Ruby
This sets `s` to `"1"`, compares using `=~` against `-3` in a void context, tries to divide `2` by `/2;'''/.to_s.ord` then starts a new string containing `=;print 4; __DATA__ =1;`, hits a comment, then `print`s `s` which is still `1`.
### Python
Sets `s` to `"1"` as per above, then sets it again to `~-3` which is `2`. We run an integer division of `2//2`, then there's a docstring containing `/.to_s.ord;"=;print 4; __DATA__ =1; ";#`, followed by a comment, finally `print`ing `s`, which is still `2`.
### JavaScript
Sets `s` to `"1"` then sets it again to `~-3` as per above, then there's `2` on the line followed by a comment. Then we set the variable `__DATA__` to `1`. There's a short string containing `;#'''#` followed by a definition of the function `print` which hardcodes the output to be 3, which is called on the next line.
### Perl
Runs a substitution equivalent to `s/"1";s/~-3;2\/\/2;'''\/.to_s.ord;"/`, `print`s `4` and the rest of the string is masked behind the `__DATA__` identifier.
[Answer]
## QBasic, QBIC and ><>, 18 bytes / 3^3 languages = 0.66666 points
```
1:?v+1'-5`
''`>3n;
```
Breakdown:
### 1. QBasic ([Get the IDE](https://drive.google.com/open?id=0B0R1Jgqp8Gg4UVliSTE0MzdLcEU))
```
1: Line number 1
? Print
v+1 undefined var v = 0 + 1 = 1
'-5` The rest of theis code is a QBasic comment
''`>3n; As is this
```
### 2. QBIC ([Get the interpreter](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ))
```
1 inserts a 1 in the code - mostly harmless
: Reads from the cmd line. Nothing there, creates an empty variable a
? Print
v+1 v is initialised to 6, +1 = 7
' Code Literal: everything till the ` is passed to QBasic without processing
-5` 7-5 = 2
''`>3n; Code literal with the first literal being a ': comment in QBasic
```
### 3. ><> ([Try it online](https://tio.run/nexus/fish#@29oZV@mbaiua5rApa6eYGecZ/3/PwA))
```
1: Push a 1 on the stack, duplicate stack
? Pop top off the stack and skip next instruction if that's a 0
v Move downwards - rest of the line is ignored
> move to the right
3 Push 3 onto the stack
n Print the top of the stack as a number
; End the program
```
] |
[Question]
[
*Aww, man, this expiry date doesn't write the months with letters! I can't tell if it's expiring on March 10th or October 3rd... Wait, no, never mind, the year says 2012. **(alley-oops half-used brick of cheese into the trash can like a pro)***
So let's suppose for a moment that you're too busy to try to reason out when this jar of marinara is supposed to expire. You just want the Cliff Notes version: how likely is it that it's past due? Let's write some code!
You know that the manufacturers print the date as an ordered triple of integers, in one of three formats:
```
YEAR MONTH DAY
MONTH DAY YEAR
DAY MONTH YEAR
```
And you know that some dates can only be interpreted in one or two ways, not all three: the 55 in `55-11-5` has to be a year, meaning this particular box of Twinkies expired November 5th, 1955. The year is sometimes given in four digits and not two, which can rule out some options. When it's two digits, though, 50..99 means 1950..1999 and 0..49 means 2000..2049.
Your job is to write a program or function that takes an array of integers which is a valid date in at least one of the interpretations above, and outputs a percent chance it is still good. The percent chance is simply the percentage of valid interpretations of the date that are **on or later** than today's date.
The array of integers will be your language's `[Int]` type of length three if it is an argument to a function, and given as either dash-, slash-, or space-separated (you get to pick) integers if used as input on STDIN to a full program.\*
"Today's date" can be today's actual date, as obtained through a date function, or the date given in an extra argument to function or extra paramater in STDIN. It may be in Unix epoch seconds, another year-month-day triple entered in one of the three ways above, or another more convenient fashion.
Let's have some examples! The expiry date input will be in the dash-separated style, and assume for the examples below that today's date is July 5th, 2006.
* `14-12-14` - Both valid interpretations for this (DMY and YMD) are equivalent, December 14, 2014. The output is **100** because this product is definitely still good.
* `8-2-2006` - The last number is a year, for sure, since it has four digits. This could be either February 8th (expired) or August 2nd (still good). The output is **50**.
* `6-7-5` - This could be anything! The "July 5th, 2006" interpretation is still good (for one day only), but the remaining two are both in 2005 and should be tossed as quickly as possible. The output is **33**.
* `6-5-7` - Here, two out of three interpretations are safe. You can round your decimal up or down, so **66** or **67** are both okay.
* `12-31-99` - Okay, this one is unambiguously from the turn of the century (years from 50 to 99 are 19XX, and 31 can't possibly be a month). A big fat **0**, and you really should clean out your fridge more often.
You can safely assume that any input which does not meet the standards above is not privy to the output rules above.
No web requests or standard loopholes. Date handling libraries are allowed. This is code golf: may the shortest program win.
\* If you are using brainfuck or some similarly datatype-handicapped language, you can assume the ASCII values of the first three characters in input are the integers for the date. This excludes the four-digit year logic, sure, but I think we would be too astounded by seeing a solution to this in Brainfuck to slight you for it.
[Answer]
## Ruby, 115 characters
```
f=->a,t{[a,a.rotate(~s=r=0),a.reverse].map{|x,*y|(t>Time.gm(x<100?x+2e3-100*x/=50:x,*y)||r+=100
s+=1)rescue p}
r/s}
```
This defines a function `f` that takes two arguments: an array containing the input, and "today's" date.
Examples:
```
f[[14,12,14], Time.new]
100
f[[8,2,2006], Time.new]
0
f[[8,2,2006], Time.new(2006, 7, 5)]
50
f[[6,7,5], Time.new(2006, 7, 5)]
33
```
[Answer]
# Python 2.7 - 172
I use the datetime module for validity and comparison of dates. If `date` can't make a valid datetime out of the input, it raises `ValueError`. This way `s` is the sum of the non-expired dates and `t` is the total number of valid dates. I'm taking advantage of the fact that `True == 1` for the purposes of addition and indexing in Python. I also save a character by using 25\*(76,80) instead of (1900,2000).
Note the lines in the second level of indentation use a tab character, not 2 spaces.
```
def f(e,c,s=0,t=3):
for Y,M,D in(0,1,2),(2,0,1),(2,1,0):
y=e[Y]
try:s+=date(y+25*[[76,80][y<50],0][y>99],e[M],e[D])>=c
except:t-=1
return 100*s/t
```
Add this to the end to test:
```
examples = [[14,12,14],[8,2,2006],[6,7,5],[6,5,7],[12,31,99]]
for e in examples:
print f(e, date(2006,7,5))
```
[Answer]
## PowerShell, ~~183~~ ~~173~~ 168
```
[int](100*(($d=@(($a,$b,$c=$args[0]),($c,$a,$b),($c,$b,$a)|%{$_[0]+=1900*($_[0]-le99)+100*($_[0]-le49)
.{date($_-join'-')}2>$x}|sort -u))-ge(date)+'-1').Count/$d.Count)
```
* Input as `int[]` via parameter, e.g.
```
PS> ./milk.ps1 5,6,7
```
* Error messages are silenced via `try`/`catch`, as long as I don't know whether output on stderr is allowed or not.
* Using `+"-1"` on the date, which gets interpreted as `.AddDays(-1)` to shift the current date by one day, so that we can compare to yesterday (instead of just today). This solves the problem that we get a date with 0:00 as time but need to compare with a date with time from today.
* Heavily inlined by now
* Using [a new trick for silencing errors](https://codegolf.stackexchange.com/a/33113/15) that's quite a bit shorter
[Answer]
## R, 269
I was expecting this to be easy in R, but the single-digit years were a pretty big curveball. I feel like this could be much better than it is.
`lubridate` is a package from CRAN, you might need to install it with `install.packages("lubridate")`.
```
require(lubridate)
f = function(d){
d=sapply(d,function(l)if(nchar(l)==1)sprintf("%02d",l)else l)
d=paste0(d,collapse="-")
t=ymd(Sys.Date())
s=na.omit(c(ymd(d),mdy(d),dmy(d)))
s=lapply(s,function(d){
if(year(d)>2049){year(d)=year(d)-100;d}
else d})
sum(s>t)/length(s)}
```
Usage: `f(c(d1,d2,d3))` where `c(d1,d2,d3)` is a vector of integers.
e.g.
`f(c(6,10,14))` returns `0.3333333`.
The `lubridate` package has a series of wrapper functions for parsing dates in different orders. I use these to see which formats produce valid dates, throw out the invalid ones, and then see which ones haven't occurred yet.
[Answer]
## Mathematica, ~~163~~ ~~153~~ 164 bytes
(*edit:* fixed dates outside the 1950 - 2049 range)
```
f=100.Count[#,x_/;x<1]/Length@#&[DateDifference[#,Date[]]&/@Cases[{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{{##},{#3,#2,#},{#3,#,#2}}&@@#,d_/;DateList@d~Take~3==d]]&
```
This defines a function which you can call like
```
f[{6,7,5}]
```
Currently, the percentage isn't rounded (waiting for the OP to clarify).
Here is a slightly lengthy explanation that should be understandable without any Mathematica knowledge (note that `&` makes everything left of it an anonymous function whose parameters are referred to as `#`, `#2`, `#3`...):
```
{{##},{#3,#2,#},{#3,#,#2}}&
```
This defines a function, which turns 3 parameters `a,b,c` into 3 lists `{{a,b,c},{c,b,a},{c,a,b}`. Note that `##` is just a sequence of all parameters.
```
{{##},{#3,#2,#},{#3,#,#2}}&@@#
```
Applied to the expiry date, this gives a list of `{y,m,d}` for each of the three possible permutations.
```
{If[#<100,Mod[#+50,100]+1950,#],##2}&
```
This is an anonymous function that takes three parameters `a,b,c` and returns a list of the three, where the first has been converted to a year as per the given rules: numbers between `50` and `99` (modulo `100`) are turned into a 20th century year, numbers between `0` and `49` (modulo `100`) are turned into a 21st century year, all others are left along. Here, `##2` is a sequence of parameters starting with the second one, i.e. `b,c`.
```
{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{{##},{#3,#2,#},{#3,#,#2}}&@@#
```
Applied to each of the three previous results, this just canonicalises the year formats. Let's call this `canonicalDates` to shorten the following expression:
```
Cases[canonicalDates,d_/;DateList@d~Take~3==d]
```
This filters out invalid interpretations. `DateList@d` makes a full `{y,m,d,h,m,s}` representation out of various date formats. It will interpret lists in the same order, but the catch is that you *can* pass it things like `{8,2,2006}` in which case it will calculate `8 years + 2 months + 2006 days`. So we check that the first three elements of the returned list are identical to the input (which can only happen if the month and day in the appropriate ranges).
To shorten the following lines, I'll refer to the result of that expression as `validDates` from now on:
```
DateDifference[#,Date[]]&
```
Another anonymous function which takes a date and returns the difference in days to today (obtained from `Date[]`).
```
DateDifference[#,Date[]]&/@validDates
```
Map that onto the valid date interpretations.
```
100.Count[#,x_/;x<1]/Length@#&
```
Yet another anonymous function which, given a list (`#`), returns the percentage of non-positive numbers in that list. The `.` is not a multiplication but just the decimal digit, to avoid rational numbers as the result (you'd get things like `100/3` instead of `33.333` - I don't actually know if that's a problem).
```
100.Count[#,x_/;x<1]/Length@#&[DateDifference[#,Date[]]&/@validDates]
```
Applied to the list of date differences, this gives us the fraction of interpretations which are not yet expired.
[Answer]
# k4 ~~(90)~~ ~~(88)~~ ~~(87)~~ (82)
```
{100*(+/~d<x)%3-+/^d:{"D"$"."/:$|z,y,x+(x<100)*100*19+x<50}.'y@/:3 3#.:'$21020101}
```
Invoke with `x` of `.z.D` (a builtin) for comparison to today, or a date literal of your choice otherwise:
```
f:{100*(+/~d<x)%3-+/^d:{"D"$"."/:$|z,y,x+(x<100)*100*19+x<50}.'y@/:3 3#.:'$21020101}
.z.D f'(14 12 14;8 2 2006;6 7 5;6 5 7;12 31 99)
100 0 0 0 0f
2006.07.05 f'(14 12 14;8 2 2006;6 7 5;6 5 7;12 31 99)
100 50 33.33333 66.66667 0
```
This is basically a port of @Alex-l's Python solution, with a few miscellaneous golfing tricks added:
* The rearrangement instructions are encoded in a string to save a couple characters.
* The conditional logic (ab)uses truth-as-integer (but in a different way from the Python solution).
* The validity test is slightly different--k4/q will happily parse any string into any datatype; it simply returns a null if it can't make sense of it. Thus, I return a list of dates from the inner function, which may or may not be null.
* The final result comes from checking how many of the possible date interpretations are null vs. how many are less than the comparison date; it's important here that the null date is considered less than any other date.
[Answer]
# JavaScript (E6) 159 ~~164 172~~
**Edit** Thanks to nderscore for the hints and for pushing me to think again. Reorganized D avoiding parameters and cutting some chars.
**Edit 2** Another trick by nderscore, 2 functions merged into 1. Then two parenthesis removed merging comma separated expressions into one. Readability near 0. Sidenote: Not rounding could save another 2 chars (|0).
```
F=(a,t)=>t?100*(3-((i=F([y,m,d]=a))<t)-((j=F([m,d,y]=a))<t)-((k=F([d,m]=a))<t))/(3-!i-!j-!k)|0:(q=new Date(y<50?y+2e3:y,--m,d)).getMonth()==m&q.getDate()==d&&q
```
**Test** In FireFox console
```
;[[14,12,14],[8,2,2006],[6,7,5],[6,5,7],[12,31,99]]
.map(x=>x + ' ' + F(x, new Date(2006,6,5)))
```
Output:
```
["14,12,14 100", "8,2,2006 50", "6,7,5 33", "6,5,7 66", "12,31,99 0"]
```
**Ungolfed**
NB D function tries to create a Date with given year, month, day but returns false if the created date is not what was intented (!= day or month)
```
F=(d,t)=>
(
D=(y,m,d)=>(
q=new Date(y<50?y+2000:y, --m, d), // decr m as javascript (like java) counts months starting at 0
q.getMonth() == m & q.getDate() == d && q
),
[a,b,c] = d,
x=D(...d), // three ways of express the date ...
y=D(c,a,b),
z=D(c,b,a),
100 * (3-(x<t)-(y<t)-(z<t)) / (3-!x-!y-!z) | 0
)
```
[Answer]
# C# in LINQPad - 446 408 272 Bytes
**Third Edit:** Thanks to Le Canard fou for pointing out that DateTime.Today is correct, not DateTime.Now.
**Second Edit:** Thanks VisualMelon for this clever solution!
```
void g(int[]d){var p=".";int a=d[2],b=d[1],e=d[0],y=a+(a<100?a>49?1900:2000:0),q=0,s=0;DateTime c;Action<string>z=x=>{if(DateTime.TryParse(x,out c)){s++;if(c>=DateTime.Today)q+=100;}};z(e+p+b+p+y);z(b+p+e+p+y);z(a+p+b+p+(e<100?e>49?1900+e:2000+e:e));(q/(s>0?s:1)).Dump();}
```
**Edit:** Thanks to podiluska and edc65 for helping me shorting the code! I also noticed that my solution wasn't correct if the year input was 4 bytes long, therefore I included the fix for that problem. The score for this solution is **408 Bytes.**
Even though I'm not beating any of the previous answers, I still wanted to share my C# solution. Any help/suggestions are appreciated! ;)
```
void g(int[]d){var q=new List<DateTime>();var p=".";int s=0,a=d[2],b=d[1],e=d[0],y=0;var c=new DateTime();y=(a<100)?(a>49)?1900+a:2000+a:a;if(DateTime.TryParse(e+p+b+p+y,out c)){q.Add(c);s++;}if(DateTime.TryParse(b+p+e+p+y,out c)){q.Add(c);s++;}y=(e<100)?(e>49)?1900+e:2000+e:e;if(DateTime.TryParse(a+p+b+p+y,out c)){q.Add(c);s++;}q=q.Where(i=>i>=DateTime.Now).ToList();if(s==0){s=1;}(q.Count*100/s).Dump();}
```
Formatted and ungolfed version:
```
void g(int[] d)
{
var q = new List<DateTime>();
var p = ".";
int s = 0, a = d[2],b = d[1],e = d[0], y=0;
var c = new DateTime();
y = (a < 100) ?((a > 49) ? 1900 + a : 2000 + a) : a;
if (DateTime.TryParse(e + p + b + p + y, out c))
{
q.Add(c);
s++;
}
if (DateTime.TryParse(b + p + e + p + y, out c))
{
q.Add(c);
s++;
}
y = (e < 100) ? ((e > 49) ? 1900 + e : 2000 + e) : e;
if (DateTime.TryParse(a + p + b + p + y, out c))
{
q.Add(c);
s++;
}
q = q.Where(i => i >= DateTime.Now).ToList();
if (s == 0)
{
s = 1;
}
(q.Count*100/s).Dump();
}
```
I tried to make a solution where the "DateTime.TryParse"-Part isn't repeated as in this solution, but it was 21 bytes longer.
**Solution without repeating "DateTime.TryParse" : 467 Bytes**
```
void g(int[]d){var q=new List<DateTime>();int s=0;int a=d[2];int b=d[1];int e=d[0];int y=0;if(a<100){if(a>49){y=1900+a;}else{y=2000+a;}}if(z(e,b,y,q)){s++;}if(z(b,e,y,q)){s++;}if(e<100){if(e>49){y=1900+e;}else{y=2000+e;}}if(z(a,b,y,q)){s++;}q=q.Where(i=>i>=DateTime.Now).ToList();if(s==0){s=1;}(q.Count*100/s).Dump();}bool z(int a,int b,int d,List<DateTime> q){var c=new DateTime();var p=".";if(DateTime.TryParse(a+p+b+p+d,out c)){q.Add(c);return true;}return false;}
```
Ungolfed version:
```
private void g(int[] d)
{
var q = new List<DateTime>();
int s = 0;
int a = d[2];
int b = d[1];
int e = d[0];
int y = 0;
if (a < 100)
{
if (a > 49)
{
y = 1900 + a;
}
else
{
y = 2000 + a;
}
}
if (z(e, b, y, q))
{
s++;
}
if (z(b, e, y, q))
{
s++;
}
if (e < 100)
{
if (e > 49)
{
y = 1900 + e;
}
else
{
y = 2000 + e;
}
}
if (z(a, b, y, q))
{
s++;
}
q = q.Where(i => i >= DateTime.Now).ToList();
if (s == 0)
{
s = 1;
}
(q.Count*100/s).Dump();
}
private bool z(int a, int b, int d, List<DateTime> q)
{
var c = new DateTime();
string p = ".";
if (DateTime.TryParse(a + p + b + p + d, out c))
{
q.Add(c);
return true;
}
return false;
}
```
[Answer]
## Haskell, 171 165 characters
```
l=length
r y|y<100=(y+50)`mod`100+1950|y>0=y
q d m y z|d<32&&m<13&&d*m>0=(r y,m,d):z|1<3=z
v(a,b,c)=q c b a$q b a c$q a b c[]
t%d=(l$filter(>t)(v d))*100`div`l(v d)
```
The function's name is `%`. Run with the test date as an tuple in canonical (y,m,d) order with actual year, and the carton stamp as a tuple of three numbers:
```
λ: (2006,6,5)%(14,12,14)
100
λ: (2006,6,5)%(8,2,2006)
50
λ: (2006,6,5)%(6,7,5)
33
λ: (2006,6,5)%(6,5,7)
66
λ: (2006,6,5)%(12,31,99)
0
λ: (2006,6,5)%(0,1,7)
0
```
[Answer]
# Erlang, 146
```
f([A,B,C]=U,N)->F=[T||T<-[{(Y+50)rem 100+1950,M,D}||[Y,M,D]<-[U,[C,A,B],[C,B,A]]],calendar:valid_date(T)],100*length([1||T<-F,T>=N])div length(F).
```
Test function would be:
```
t() ->
0 = f([12,31,99],{2006,6,5}),
66 = f([6,5,7],{2006,6,5}),
33 = f([6,7,5],{2006,6,5}),
100 = f([14,12,14],{2006,6,5}),
50 = f([8,2,2006],{2006,6,5}),
100 = f([29,2,2],{2006,6,5}).
```
**Ungolfed**
```
f([A,B,C]=U,Today)->
Perms = [U,[C,A,B],[C,B,A]],
WithYears = [{(Y+50) rem 100+1950,M,D} || [Y,M,D] <- Perms],
ValidDates = [T || T <- WithYears, calendar:valid_date(T)],
100*length([1 || T <- ValidDates, T >= Today]) div length(ValidDates).
```
This solution relies on list comprehensions. It borrows the modulo trick for the year from the Haskell solution. It also uses `calendar:valid_date/1` to handle impossible dates because of the number of days in a given month (e.g. "29-2-2" can only be in YMD format). Also, Today is in Erlang's `date()` format (a YMD tuple).
[Answer]
## APL (85)
This uses some of Dyalog APL 14's new functions, but no external libraries. For a change, it works on [TryAPL](http://www.tryapl.org).
```
{100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵}
```
This is a function that takes the 3-element array as its right side (`⍵`) argument, and the date to check against as its left side (`⍺`) argument, as an integer of `YYYYMMDD` format. I.e., the date `2014-07-09` is represented as the number `20140709`.
Test:
```
20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 14 12 14
100
20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 8 2 2006
50
20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 6 7 5
33.3333
20060705 {100×(+/÷⍴)⍺≤{(3/100)⊥⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵}¨Z/⍨{∧/12 31≥1↓⍵}¨Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵} 12 31 99
0
```
Explanation:
* `Z←(⊂⌽⍵),(⊂2⌽⍵),⊂⍵`: turn the given date into Y-M-D format by flipping `(⊂⌽⍵)`, rotating it to the left by 2 `(⊂2⌽⍵)`, or just doing nothing `⊂⍵`. At least one of these is now a proper date in Y-M-D format, maybe more than one if the date is ambiguous.
* `{∧/12 31≥1↓⍵}¨Z`: test if each date is valid: the year (first element) is dropped, and then the month must be no higher than 12 and the day must be no higher than 31.
* `Z/⍨`: filter the valid dates from `Z`.
* `{`...`}¨`: for each valid date:
+ `⍵+(99≥⊃⍵)×3↑1900+100×50>⊃⍵`: if the year is not higher than 99, add 1900, then 100 if the year is lower than 50.
+ `(3/100)⊥`: decode it as if it were a set of base-100 numbers. (The year is higher than 100, but this doesn't matter as it's the first element.) This gives a number for each valid date in the same format as the left argument.
* `⍺≤`: for each date, see if it is not smaller than `⍺`. This will give a binary vector where 1 means `OK` and 0 means `spoiled`.
* `100×(+/÷⍴)`: divide the sum of the binary vector by its length and multiply by 100.
[Answer]
## **Java: 349 Characters (3 w/o spaces)**
```
int e(int[]n,Date t){int a=n[0],b=n[1],c=n[2];Date[]d=new Date[3];if(b<13&&c<32)d[0]=new Date((a<50?100:(a>100?-1900:0))+a,b-1,c);if(b<13&&a<32)d[1]=new Date((c<50?100:(c>100?-1900:0))+c,b-1,a);if(a<13&&b<32)d[2]=new Date((c<50?100:(c>100?-1900:0))+c,a-1,b);int v=0,g=0;for(int i=0;i<3;i++)if(d[i]!=null){if(!d[i].before(t))g++;v++;}return 100*g/v;}
```
Here is a containing class that can be used to test it, including a (slightly) degolfed version of the method:
```
import java.util.*;
class i{
int e(int[]n,Date t){
int a=n[0],b=n[1],c=n[2];
Date[]d=new Date[3];
if(b<13&&c<32)d[0]=new Date((a<50?100:(a>100?-1900:0))+a,b-1,c);
if(b<13&&a<32)d[1]=new Date((c<50?100:(c>100?-1900:0))+c,b-1,a);
if(a<13&&b<32)d[2]=new Date((c<50?100:(c>100?-1900:0))+c,a-1,b);
int v=0,g=0;
for(int i=0;i<3;i++)
if(d[i]!=null){
if(!d[i].before(t))
g++;
v++;
}
return 100*g/v;}
public static void main(String[] args){
int[]i=new int[3];
for(int k=0;k<3;k++)
i[k] = Integer.parseInt(args[k]);
int j = new i().e(i,new Date());
System.out.println(j+"%");
}
}
```
This is my first round of code golf, and I think I figured out why I don't usually see very many Java golfers.
[Answer]
# C# 287 bytes
```
namespace System{class E{static float a,o,l;void M(int[]i){int d=i[0],m=i[1],y=i[2],t;if(l<3)try{if(l==1){t=y;y=d;d=t;}if(l++==0){t=d;d=m;m=t;}if(y<100&&(y+=1900)<1950)y+=100;o+=new DateTime(y,m,d)>=DateTime.Today?1:0;a++;if(l<3)i[9]=9;}catch{M(i);throw;}Console.Write(o/a);}}}
```
First time golfing, looking for advices. Notably, removing bytes due to namespace.
Abusing the fact that only a function is required, not an actual program. Also, the function always results in an uncaught exception.
**Ungolfed**
```
namespace System {
class E {
static float a, o, l;
void M(int[] i) {
int d = i[0], m = i[1], y = i[2], t;
if (l < 3)
try {
if (l == 1) {
t = y; y = d; d = t;
}
if (l++ == 0) {
t = d; d = m; m = t;
}
if (y < 100 && (y += 1900) < 1950)
y += 100;
o += new DateTime(y, m, d) >= DateTime.Today ? 1 : 0; // # not expired
a++; // # valid dates
if (l < 3)
i[9] = 9; // throw new Exception()
}
catch {
M(i);
throw; // fail after the first Console.Write()
}
Console.Write(o / a);
}
}
}
```
[Answer]
## *Mathematica*, 118
Using m.buettner's code as a starting point I have a few improvements:
```
⌊100Mean@UnitStep@Cases[DateDifference@{If[#<100,Mod[#+50,100]+1950,#],##2}&@@@{#,RotateRight@#,Reverse@#},_Integer]⌋&
```
] |
[Question]
[
The aim of this post is to gather all the golfing tips that can be easily applied to `<all languages>` rather than a specific one.
**Only post answers that its logic can be applied to the *majority* of the languages**
>
> Please, one tip per answer
>
>
>
[Answer]
## Merge Loops
You can usually merge two consequent loops, or two nested loops, into one.
Before:
```
for (i=0; i<a; i++) foo();
for (i=0; i<b; i++) bar();
```
After:
```
for (i=0; i<a+b; i++) i<a?foo():bar();
```
[Answer]
Just to mention the obvious:
### Question your choice of algorithm and try something entirely new.
When golfing (especially harder problems that result in longer programs) all too often you might stick to the path you first chosen without trying other *fundamental* options. Of course, you may micro-golf one or a few lines at a time or a part of the overall idea, but often not try a totally different solution.
This was especially noticeable in [Hitting 495 (Kaprekar)](https://codegolf.stackexchange.com/q/1255/15) where deviating from the actual algorithm and looking for patterns you can apply to get to the same result was shorter in many languages (just not J).
The downside is that you possibly solve the same thing half a dozen times. But it works in really all languages except HQ9+ (where finding another way to output *Hello World* would be slightly futile).
[Answer]
# Use Test-Driven Development
If the code must handle various inputs, then write comprehensive tests and make it easy to run them all very quickly. This allows you to try risky transforms one baby step at a time. Golfing then becomes like refactoring with perverse intent.
[Answer]
# Try to reduce logical statements
For example, if `A` and `B` are booleans and your language treats booleans like numbers to some extent, `A and (not B)` and `A>B` are equivalent. For example in Python
```
if A and not B:
foo()
```
is the same as:
```
if A>B:
foo()
```
[Answer]
# Write an explanation of your code
Writing an explanation forces you to thoroughly look at each part of your code again and to make your thoughts and choices in writing a certain passage explicit. In doing so, you might find that different approaches are possible which may save some bytes, or that you subconsciously made assumptions which don't necessarily hold.
This tip is similar to [Question your choice of algorithm and try something entirely new](https://codegolf.stackexchange.com/a/5401/56433); however, I have found that the step of actually writing down how each part is supposed to work is sometimes crucial for becoming aware of alternatives.
As a bonus, answers including an explanation are more interesting for other users and are hence more likely to be upvoted.
[Answer]
## Initialize variables using values you already have.
Instead of `x=1`, try to look for something that already equals 1.
For example, a function's return value: `printf("..");x=0;` -> `x=!printf("..");`.
It's easiest with 0, because you can always negate, or when all you need is the right truth value (and don't care if it's 1 or 19).
[Answer]
# Use unary `~` for `x+1` and `x-1`
This trick applies to languages that have a unary bitwise negation operator `~` and a unary regular negation operator `-`.
If your program, by chance, contains the expression `-x-1`, you can replace it with `~x` to save bytes. This doesn't occur all too often, but watch what happens if we negate (`-`) both expressions: `x+1` equals `-~x`! Similarly, `x-1` equals `~-x`. (Think of which way the tilde points: right is `+`, left is `-`.)
This is useful, because in all languages I can think of that have these operators, they have higher precedence than most operators. This allows you to save on parentheses. Watch how we save four bytes here:
```
(x+1)*(y-1) ==> -~x*~-y
```
[Answer]
## Squeeze whitespace
Know the rules for whitespace in your language. Some punctuation marks, or other characters, might not need any surrounding whitespace. Consider this *Bourne shell* function:
```
f () { echo a; echo b; }
```
In Bourne shell, `();` are metacharacters, and do not need surrounding whitespace. However, `{}` are words and need whitespace unless they are next to metacharacters. We can golf away 4 spaces next to `();`, but must keep the space between `{` and `echo`.
```
f(){ echo a;echo b;}
```
In *Common Lisp* and *PicoLisp*, `()` are metacharacters. Consider this code to find the average of two numbers:
```
(/ (+ a b) 2)
```
We can golf away 2 spaces.
```
(/(+ a b)2)
```
---
Some languages have strange and subtle rules for whitespace. Consider this Ruby program, which prints the sum and product of a line of integers.
```
#!ruby -an
i=$F.map &:to_i
puts"#{i.reduce &:+} #{i.reduce &:*}"
```
Each `&` needs a space before itself. In Ruby, `i=$F.map &:to_i` means `i=$F.map(&:to_i)` where `&` passes a block parameter. But, `i=$F.map&:to_i` means `i=$F.map.&(:to_i)` where `&` is a binary operator.
This weirdness happens in languages, like Perl or Ruby, that use ambiguous punctuation. If in doubt, use a REPL or write short programs to test the whitespace rules.
[Answer]
## assign functions new names if used multiple times
```
x = SomeLongFunctionName
x(somedata)
x(somemoredata)
etc
```
[Answer]
## Single Letter Variable Names
You have 52 of them; use them all! Don't be afraid to try different approaches and compare lengths. Know the language and the specific shortcuts/library functions available.
[Answer]
## **Use the conditional operator.**
A conditional *operator*
```
bool ? condition_true : condition_false
```
is more beneficial, character wise, than an IF *statement*.
```
if(a>b){r=a;}else{r=b;}
```
can be written as
```
r=a>b?a:b;
```
[Answer]
## use `-` instead of `!=`
for numeric comparisons:
If a equals b, `a-b` results in `0`, which is falsy. Anything else than `0` is truthy; so
if used in a boolean context, `a-b` <=> `a!=b`
If you use it with `if/else` or with the ternary operator, this can also save you one byte for equality:
`a==b?c:d` <=> `a-b?d:c`
[Answer]
# Read the question carefully
Code golfing is as much about understanding the question (what is asked and what is **not** asked, even though it would be implied in any other setting) as producing code that (may) only satisfy what is asked.
Any input other than what is explicitly asked for need not be handled. If there are some test cases and no generic requirement, your code may only work in those cases. Etc.
e.g. if the question says "print the prime numbers from 1 to 100 inclusive", the largest prime printed will be 97 and you can change your loop end condition from `100` to `97` and save 1 byte. The question does not say you need to test 98, 99, 100 for primality, so don't do that.
e.g. 2. if the question says "print these numbers" then it does not say your answer must *calculate* the numbers. It might be shorter to store the expected output and decode and print it, than to write a calculator for it, e.g. storing 97 98 99 100 as a string of ASCII characters `'abcd'`.
[Answer]
## Double check your character count
Sounds like a no-brainer, but by being careful you might be able to "save" a few characters by not actually doing anything!
If you're using Windows, you may be inputting `\r\n` instead of just `\r` or `\n` when you hit Return - adding an extra byte per line! Turn control characters just to double check you're not doing this.
In Notepad++ you can convert all `\r\n` line endings to just `\r` by going to `Edit > EOL Conversion > UNIX/OSX Format`.
Also make sure you don't include any trailing whitespace in your character count! The line feed on the bottom line in your code is also inconsequential, so that won't need to be counted either.
[Answer]
## Use > and < instead of >= and <=
When checking against hard-coded integer values, use `>` and `<` instead of `>=` and `<=` where possible. For example, using
```
if(x>24&&x<51)
```
Is 2 bytes shorter than using
```
if(x>=25&&x<=50)
```
[Answer]
## Use bitwise operations for checking numbers between 0 and any 2n-1
Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which m=2n-1 applies have the rightmost n bits set to 1.
So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.
The trick is `x&~m`. This will return true whenever `x` is ***not*** between 0 and `m` (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: `x>=0&&x<=m`, but obviously only works when `m` satisfies 2n-1.
[Answer]
# Understand what other people did
In addition to being fun, if you examine other people's code, you can sometimes discover a good algorithm that you didn't think about, or a trick (sometimes an obvious one) that you overlook.
Sometimes there is an existing answer that you can translate to another language, and benefit from the other language's goodies.
[Answer]
**Greater/Less than to save a digit:**
```
//use:
if(n>9){A}else{B}
//instead of:
if(n<10){B}else{A}
```
Just remember to swap the code from `if` to the `else` and they will do exactly the same thing (or switch the sides of the inequality)!
**Note:** this can be applied with any power of 10 and their negatives: `...-100, -10, 10, 100...`
[(source link)](https://codegolf.stackexchange.com/a/5284/3563)
[Answer]
Reuse function parameters instead of new variables
[Answer]
## Avoid premature loop breaks
If running through a loop to check for 1 or more instances of a boolean check, it might make for a more efficient program to exit the loop on the first true value. However, removing the break and looping through all iterations allows for shorter code.
```
int main() {
bool m = false;
int n = 1000;
for (int i = 0; i < n; i++) {
if (i >= 100) {
m = true;
break; // remove this line
}
}
return 0;
}
```
[Answer]
## know your operator precedence
Whenever You combine several expressions, check the operator precedence table for your language to see if you can reorder stuff to save parentheses.
Examples:
* In all languages that I know, bitwise operators have a higher precedence than boolean operators:
`(a&b)&&c` needs no parentheses: `a&b&&c` just as `(a*b)+c` does not.
* `a+(b<<c)` can be rewritten as `a+b*2**c`.
That doesn´t save anything for this example, but it will if `c` is a small integer literal (<14).
* Bitwise operations have a lower precedence than most arithmetic operations, so if your language implicitly casts boolean to int, you can save a byte on `a<b&&c<d` with `a<b&c<d` (unless you need the short circuit evaluation)
[Answer]
# Use unary `~` for `a-b-1` and `a+b+1`
[In addition to *@Lynn*'s suggestions regarding `x+1` → `-~x`; and `x-1` → `~-x`](https://codegolf.stackexchange.com/a/67630/52210), you can also golf `a-b-1` and `a+b+1`.
```
a-b-1 // 5 bytes
a+~b // 4 bytes
a+b+1 // 5 bytes
a-~b // 4 bytes
```
It might look like a tip you won't use all that often, kinda like using `~x` instead of `-x-1` doesn't happen often, but I've used it enough times to see it as a useful tip here. Especially with array-indexing you might use these above in some cases.
[Answer]
### Split strings for long arrays
Most languages have a way to split a string into an array of strings around a token of some kind. This will inevitably be shorter than an array literal once the length reaches a language-dependent threshold, because the extra overhead per string will be one copy of a one-char token rather than (at least) two string delimiters.
E.g. in GolfScript
```
["Foo""Bar""Baz""Quux"] # 23 chars
```
becomes
```
"Foo
Bar
Baz
Quux"n/ # 20 chars
```
For some languages, the threshold is as low as one string. E.g. in Java,
```
new String[]{"Foo"} // 19 chars
```
becomes
```
"Foo".split("~") // 16 chars
```
[Answer]
# Shorter for-loops
If you have `X` statements `{`inside`}` your for-loop, you can move `X-1` statements `(`inside`)` the for-loop after the second semicolon `for(blah;blah;HERE)` to save 3 bytes. (separate the statements by using a comma `,`)
Instead of
```
for(int i=0;i<9;){s+=s.length();println(i++);}
```
you can move one of the statements into the for-loop's `(` braces`)` while leaving the other out
```
for(int i=0;i<9;println(i++))s+=s.length();
```
and save 3 bytes (saved 1 more byte thanks to @ETHProductions)
---
Put simply,
instead of
```
for(blah;blah;){blah 1;blah 2;...;blah X}
```
move the statements around so you end up with this
```
for(blah;blah;blah 2,...,blah X)blah 1;
```
and save 3 bytes
[Answer]
## O(n^2) is your friend
You spend your time looking to get rid of O(n^2) algorithms and bring runtime and memory use down; golf turns that around - spend freely of CPU and Memory to bring code size down. Use nested loops, calculate 10x too much data instead of a complex exit condition, call `sort()` every loop iteration instead of storing the result.
Some questions have a runtime limit to push you to write a more efficient answer, even then knowing how fast your language and code runs can give you room to take liberties and still stay within it.
[Answer]
Maybe somewhat obvious but...
# Make use of operator return values
Keep in mind that the assignment operator returns a value!
For example, if you want to add y to x and then check if x is greater than something, you can do
```
if(25<x+=y)
```
instead of
```
x+=y;if(x>25)
```
Or maybe you want to find the length of a string after trimming it:
```
strlen(s=trim(s))
```
Rather than
```
s=trim(s);strlen(s)
```
[Answer]
## Rely on the compiler to provide the required performance.
Be sure to know which optimisations are guaranteed by the compiler and at which optimisation levels, and use them liberally. And even if performance isn't a ~~concern~~ requirement, you can still test with optimisations on, and then only discount one character because your code is still *technically* valid without the compiler flag.
Consider the following Haskell function to compute 2^n (ignoring the fact that Haskell already has a built-in exponentiation operator or three) (23 characters):
```
p 0=1;p x=p(x-1)+p(x-1)
```
The problem is - it's horrendously slow, it runs in exponential time. This might make your code untestable or to fail any performance constraints given by the question. You might be tempted to use a temporary variable or an immediately invoked function literal to avoid repeated function calls (25 characters):
```
p 0=1;p x=(\y->y+y)$p$x-1
```
But the compiler can already do that for you, you just need set `-O` as a compiler flag! Instead of spending few extra characters per site to eliminate common subexpressions manually, just tell the compiler to do basic optimisations for you.
[Answer]
## Compress or/and streaks
Simple trick I've come up with when trying to squeeze a long streak of conditions chained by ands (or ors, in this case just substitute 'all' with 'any').
**Eg:**
```
if a>0 and a<10 and a+b==4 and a+3<1:
```
Becomes
```
if all([a>0,a<10,a+b==4,a+3<1]):
```
[Answer]
## Utilize language version / compiler / environment quirks / new features
This is especially useful for [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'")s, but can be applied to other challenges. Sometimes, a compiler bug can golf off a byte, a implementation bug can allow you to save a few chars, or a really bleeding-edge feature can improve your score.
[Answer]
## Know the difference between "program" and "function" in your language
Many questions on codegolf.SE ask you to "write a program or function"; this gives you some freedom to play to the strengths of your language and runtime based on how it handles command line parameters, how much boilerplate it needs for defining functions and their parameters, for defining full programs, for reading user input in a running program.
e.g. for a question asking you to write a program or function which takes a number as input, multiplies it by 10 and prints the result:
in Python it might go this way:
```
print(10*int(input())) # full program
lambda x:print(10*x) # function
```
in APL, the other way:
```
⎕←10×⎕ # full program
{⎕←10×⍵} # function
```
In languages with a lot of code to get a whole program to run such as Java, a function could be much shorter. In more dynamic scripting languages such as Perl with many command line options to change how the code acts, a full program with a command line switch could be the shortest. Taking input from an implicit `$args` might be shorter than `input()`, or defining a function with a parameter might be shorter than `System.Console.ReadLine();`
] |
[Question]
[
This challenge was inspired by [this Wendy's commercial](https://youtu.be/eANcbFSPHyA) from 1984.
[![Where's the beef?](https://i.stack.imgur.com/1UdR1.png)](https://i.stack.imgur.com/1UdR1.png)
*Illustration by T S Rogers*
Your task is to find a hexadecimal 0xBEEF on a binary bun.
The 'beef' consists of the following pattern:
```
1 0 1 1 (0xB)
1 1 1 0 (0xE)
1 1 1 0 (0xE)
1 1 1 1 (0xF)
```
And the 'bun' consists of a 12x12 binary matrix, such as:
```
1 1 1 0 0 1 1 1 1 1 1 0
1 1 0 1 0 0 1 0 0 0 0 0
0 1 0 0 0 1 1 1 1 1 0 1
1 0 0 1 0 0 1 0 0 1 0 0
1 0 0 1 0 1 1 0 0 1 1 1
1 1 1 1 1 1 0 0 0 0 1 0
1 1 0 1 1 1 0 0 0 0 0 1
1 0 0 1 1 1 1 0 0 0 0 1
1 0 0 1 1 1 0 1 1 1 1 1
1 1 1 1 1 0 0 1 1 1 1 1
1 0 0 0 0 1 0 1 0 1 1 1
1 1 0 0 1 1 0 0 0 0 1 1
```
### Input
Your program or function will take the binary matrix as input. The matrix format is very flexible, but it must be clearly described in your answer.
For instance:
* a single binary string, with or without separators between the rows:
`"111001111110 110100100000..."`
or:
`"111001111110110100100000..."`
* an array of binary strings:
`["111001111110", "110100100000", ...]`
* an array of numbers (each number describing a row once converted back to binary and left-padded with zeros):
`[3710, 3360, ...]`
### Output
The coordinates `(X, Y)` of the 'beef', `(0, 0)` being the top left corner of the bun.
Alternatively, you may use 1-based coordinates (but not a mix of both formats, like 0-based for X and 1-based for Y).
For the above example, the expected answer is `(3, 4)` (0-based) or `(4, 5)` (1-based):
```
00 01 02 03 04 05 06 07 08 09 10 11
00 1 1 1 0 0 1 1 1 1 1 1 0
01 1 1 0 1 0 0 1 0 0 0 0 0
02 0 1 0 0 0 1 1 1 1 1 0 1
03 1 0 0 1 0 0 1 0 0 1 0 0
04 1 0 0 [1 0 1 1] 0 0 1 1 1
05 1 1 1 [1 1 1 0] 0 0 0 1 0
06 1 1 0 [1 1 1 0] 0 0 0 0 1
07 1 0 0 [1 1 1 1] 0 0 0 0 1
08 1 0 0 1 1 1 0 1 1 1 1 1
09 1 1 1 1 1 0 0 1 1 1 1 1
10 1 0 0 0 0 1 0 1 0 1 1 1
11 1 1 0 0 1 1 0 0 0 0 1 1
```
Again, any reasonable format would work as long as it is specified in your answer. Please also mention if you're using 0-based or 1-based coordinates.
### Rules
* You can safely assume that there is always exactly one 'beef' on the bun. Your code is not required to support cases with more than one beef or no beef at all.
* The beef pattern will always appear as described. It will never be rotated or mirrored in any way.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
### Test cases
In the following test cases, each row of the matrix is expressed as its decimal representation.
```
Input : [ 3710, 3360, 1149, 2340, 2407, 4034, 3521, 2529, 2527, 3999, 2135, 3267 ]
Output: [ 3, 4 ]
Input : [ 1222, 3107, 1508, 3997, 1906, 379, 2874, 2926, 1480, 1487, 3565, 633 ]
Output: [ 3, 7 ]
Input : [ 2796, 206, 148, 763, 429, 1274, 2170, 2495, 42, 1646, 363, 1145 ]
Output: [ 6, 4 ]
Input : [ 3486, 3502, 1882, 1886, 2003, 1442, 2383, 2808, 1416, 1923, 2613, 519 ]
Output: [ 1, 1 ]
Input : [ 3661, 2382, 2208, 1583, 1865, 3969, 2864, 3074, 475, 2382, 1838, 127 ]
Output: [ 8, 8 ]
Input : [ 361, 1275, 3304, 2878, 3733, 3833, 3971, 3405, 2886, 448, 3101, 22 ]
Output: [ 0, 3 ]
Input : [ 3674, 2852, 1571, 3582, 1402, 3331, 1741, 2678, 2076, 2685, 734, 261 ]
Output: [ 7, 7 ]
```
[Answer]
## vim, ~~126~~ ~~80~~ ~~77~~ 76
```
/\v1011\_.{9}(1110\_.{9}){2}1111<cr>:exe'norm Go'.join(getpos('.'))<cr>xxdawhPXXd{
```
Expects input in the form
```
111001111110
110100100000
010001111101
100100100100
100101100111
111111000010
110111000001
100111100001
100111011111
111110011111
100001010111
110011000011
```
And outputs (with 1-based indices) as
```
4 5
```
```
/ regex search for...
\v enable "very magic" mode (less escaping)
1011\_.{9} find the first line ("B"), followed by 8 chars + 1 \n
(1110\_.{9}){2} find the second and third lines ("EE")
1111<cr> find the fourth line ("F")
:exe'norm Go'. insert at the beginning of the file...
join(getpos('.'))<cr> the current position of the cursor
xxdawhPXX do some finagling to put the numbers in the right order
d{ delete the input
```
Thanks to [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%c3%b6rg-h%c3%bclsermann) for indirectly saving 46 bytes by making me realize my regex was super dumb, and to [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) for 3 more bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṡ€4ḄZw€“¿ÇÇБĖUṀ
```
Input is in form of a Boolean matrix, output is the 1-based index pair **(Y, X)**.
[Try it online!](http://jelly.tryitonline.net/#code=4bmh4oKsNOG4hFp34oKs4oCcwr_Dh8OHw5DigJjEllXhuYA&input=&args=WzEsMSwxLDAsMCwxLDEsMSwxLDEsMSwwXSwgWzEsMSwwLDEsMCwwLDEsMCwwLDAsMCwwXSwgWzAsMSwwLDAsMCwxLDEsMSwxLDEsMCwxXSwgWzEsMCwwLDEsMCwwLDEsMCwwLDEsMCwwXSwgWzEsMCwwLDEsMCwxLDEsMCwwLDEsMSwxXSwgWzEsMSwxLDEsMSwxLDAsMCwwLDAsMSwwXSwgWzEsMSwwLDEsMSwxLDAsMCwwLDAsMCwxXSwgWzEsMCwwLDEsMSwxLDEsMCwwLDAsMCwxXSwgWzEsMCwwLDEsMSwxLDAsMSwxLDEsMSwxXSwgWzEsMSwxLDEsMSwwLDAsMSwxLDEsMSwxXSwgWzEsMCwwLDAsMCwxLDAsMSwwLDEsMSwxXSwgWzEsMSwwLDAsMSwxLDAsMCwwLDAsMSwxXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmh4oKsNOG4hFp34oKs4oCcwr_Dh8OHw5DigJjEllXhuYAKfDQwOTZC4biK4oKsw4fCteKCrEc&input=&args=WwogWyAzNzEwLCAzMzYwLCAxMTQ5LCAyMzQwLCAyNDA3LCA0MDM0LCAzNTIxLCAyNTI5LCAyNTI3LCAzOTk5LCAyMTM1LCAzMjY3IF0sCiBbIDEyMjIsIDMxMDcsIDE1MDgsIDM5OTcsIDE5MDYsIDM3OSwgMjg3NCwgMjkyNiwgMTQ4MCwgMTQ4NywgMzU2NSwgNjMzIF0sCiBbIDI3OTYsIDIwNiwgMTQ4LCA3NjMsIDQyOSwgMTI3NCwgMjE3MCwgMjQ5NSwgNDIsIDE2NDYsIDM2MywgMTE0NSBdLAogWyAzNDg2LCAzNTAyLCAxODgyLCAxODg2LCAyMDAzLCAxNDQyLCAyMzgzLCAyODA4LCAxNDE2LCAxOTIzLCAyNjEzLCA1MTkgXSwKIFsgMzY2MSwgMjM4MiwgMjIwOCwgMTU4MywgMTg2NSwgMzk2OSwgMjg2NCwgMzA3NCwgNDc1LCAyMzgyLCAxODM4LCAxMjcgXSwKIFsgMzYxLCAxMjc1LCAzMzA0LCAyODc4LCAzNzMzLCAzODMzLCAzOTcxLCAzNDA1LCAyODg2LCA0NDgsIDMxMDEsIDIyIF0sCiBbIDM2NzQsIDI4NTIsIDE1NzEsIDM1ODIsIDE0MDIsIDMzMzEsIDE3NDEsIDI2NzgsIDIwNzYsIDI2ODUsIDczNCwgMjYxIF0KXQ).
### How it works
```
ṡ€4ḄZw€“¿ÇÇБĖUṀ Main link. Argument: M (2D array of Booleans)
ṡ€4 Split each row into 9 chunks of length 4.
Ḅ Convert these chunks from base 2 to integer.
Z Zip/transpose. This places the columns of generated integers
into the rows of the matrix to comb through them.
“¿ÇÇБ Push the array of code points (in Jelly's code page) of these
characters, i.e., 0xB, 0xE, 0xE, and 0xF.
w€ Window-index each; in each row, find the index of the contiguous
subarray [0xB, 0xE, 0xE, 0xF] (0 if not found).
Since the matrix contains on one BEEF, this will yield an array
of zeroes, with a single non-zero Y at index X.
Ė Enumerate; prefix each integer with its index.
U Upend; reverse the pairs to brings the zeroes to the beginning.
Ṁ Take the maximum. This yields the only element with positive
first coordinate, i.e., the pair [Y, X].
```
[Answer]
## JavaScript (ES6), ~~63~~ ~~60~~ 56 bytes
```
s=>[(i=s.search(/1011.{9}(1110.{9}){2}1111/))%13,i/13|0]
```
Takes input as a 155-character space-delimited string of 12 12-digit binary strings, returns zero-indexed values. Edit: Saved 3 bytes thanks to @JörgHülsermann. Saved 4 bytes thanks to @ETHproductions.
[Answer]
# C, ~~146~~ ~~177~~ ~~173~~ 163 bytes
Thanks to [Numberknot](https://codegolf.stackexchange.com/a/97212/53667) for fixing the code (shifting the lower three rows).
Saving 4 bytes by replacing `>>=1` with `/=2` in 4 places.
Saving 10 more bytes by letting `x` and `y` be global and default `int` thanks to [MD XF](https://codegolf.stackexchange.com/users/61563/md-xf "MD XF")
```
#define T(i,n)(A[y+i]&15)==n
x,y;b(int A[12]){for(x=9;x--;){for(y=0;++y<9;A[y]/=2)if(T(0,11)&&T(1,14)&&T(2,14)&&T(3,15))return(x<<4)+y;A[9]/=2;A[10]/=2;A[11]/=2;}}
```
Ungolfed:
```
int b(int A[12]) {
for (int x=8; x>=0; --x) {
for (int y=0; y<9; ++y) {
if ((A[y]&15)==11 && (A[y+1]&15)==14 && (A[y+2]&15)==14 && (A[y+3]&15)==15) {
return (x<<4) + y;
}
A[y]/=2;
}
A[9]/=2; A[10]/=2; A[11]/=2;
}
}
```
Returns x,y (0-based) in the high and low nibble of a byte.
Usage:
```
int temp=b(array_to_solve);
int x=temp>>4;
int y=temp&15;
printf("%d %d\n",x,y);
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~22~~ 21 bytes
```
Eq[ODDH]B~EqZ+16=&fhq
```
Input is a binary matrix, with `;` as row separator. Output is 1-based in reverse order: `Y X`.
[Try it online!](http://matl.tryitonline.net/#code=RXFbT0RESF1CfkVxWisxNj0mZmhx&input=WzEgMSAxIDAgMCAxIDEgMSAxIDEgMSAwOyAxIDEgMCAxIDAgMCAxIDAgMCAwIDAgMDsgMCAxIDAgMCAwIDEgMSAxIDEgMSAwIDE7IDEgMCAwIDEgMCAwIDEgMCAwIDEgMCAwOyAxIDAgMCAxIDAgMSAxIDAgMCAxIDEgMTsgMSAxIDEgMSAxIDEgMCAwIDAgMCAxIDA7IDEgMSAwIDEgMSAxIDAgMCAwIDAgMCAxOyAxIDAgMCAxIDEgMSAxIDAgMCAwIDAgMTsgMSAwIDAgMSAxIDEgMCAxIDEgMSAxIDE7IDEgMSAxIDEgMSAwIDAgMSAxIDEgMSAxOyAxIDAgMCAwIDAgMSAwIDEgMCAxIDEgMTsgMSAxIDAgMCAxIDEgMCAwIDAgMCAxIDFd) Or [verify all test cases](http://matl.tryitonline.net/#code=YEIKRXFbT0RESF1CfkVxWisxNj0mZmhxCkRU&input=WyAzNzEwLCAzMzYwLCAxMTQ5LCAyMzQwLCAyNDA3LCA0MDM0LCAzNTIxLCAyNTI5LCAyNTI3LCAzOTk5LCAyMTM1LCAzMjY3IF0KWyAxMjIyLCAzMTA3LCAxNTA4LCAzOTk3LCAxOTA2LCAzNzksIDI4NzQsIDI5MjYsIDE0ODAsIDE0ODcsIDM1NjUsIDYzMyBdClsgMjc5NiwgMjA2LCAxNDgsIDc2MywgNDI5LCAxMjc0LCAyMTcwLCAyNDk1LCA0MiwgMTY0NiwgMzYzLCAxMTQ1IF0KWyAzNDg2LCAzNTAyLCAxODgyLCAxODg2LCAyMDAzLCAxNDQyLCAyMzgzLCAyODA4LCAxNDE2LCAxOTIzLCAyNjEzLCA1MTkgXQpbIDM2NjEsIDIzODIsIDIyMDgsIDE1ODMsIDE4NjUsIDM5NjksIDI4NjQsIDMwNzQsIDQ3NSwgMjM4MiwgMTgzOCwgMTI3IF0KWyAzNjEsIDEyNzUsIDMzMDQsIDI4NzgsIDM3MzMsIDM4MzMsIDM5NzEsIDM0MDUsIDI4ODYsIDQ0OCwgMzEwMSwgMjIgXQpbIDM2NzQsIDI4NTIsIDE1NzEsIDM1ODIsIDE0MDIsIDMzMzEsIDE3NDEsIDI2NzgsIDIwNzYsIDI2ODUsIDczNCwgMjYxIF0) with decimal input format.
### Explanation
The pattern is detected using 2D convolution. For this,
* The matrix and the pattern need to be in bipolar form, that is, `1, -1` instead of `1, 0`. Since the pattern has size 4×4, its occurrence is detected by an entry equal to `16` in the convolution output.
* The convolution kernel needs to be defined as the sought pattern reversed in both dimensions.
Also, since the convolution introduces an offset in the detected indices, this needs to be corrected for in the output.
```
Eq % Implicitly input binary matrix. Convert to bipolar form (0 becomes -1)
[ODDH] % Push array [0 8 8 2]
B % Convert to binary. Each number gives a row
~Eq % Negate and convert to bipolar. Gives [1 1 1 1; 0 1 1 1; 0 1 1 1; 1 1 0 1]
% This is the "BEEF" pattern reversed in the two dimensions. Reversal is
% needed because a convolution will be used to detect that patter
Z+ % 2D convolution, keeping original size
16=&f % Find row and column indices of 16 in the above matrix
h % Concatenate horizontally
q % Subtract 1. Implicitly display
```
[Answer]
# Mathematica, 62 bytes
```
BlockMap[Fold[#+##&,Join@@#]==48879&,#,{4,4},1]~Position~True&
```
Returns all positions of the BEEF matrix, 1-indexed. The input must be a matrix of binary digits. The x and y in the output are switched, though.
[Answer]
## [Slip](https://github.com/Sp3000/Slip/wiki), 28 bytes
27 bytes of code, +1 for `p` option.
```
(?|1011)(\(?|1110)){2}\1111
```
Requires input as a multiline rectangle of 1's and 0's without spaces. [Try it here](https://slip-online.herokuapp.com/?code=%28%3F%7C1011%29%28%5C%28%3F%7C1110%29%29%7B2%7D%5C1111&input=101011101100%0A000011001110%0A000010010100%0A001011111011%0A000110101101%0A010011111010%0A100001111010%0A100110111111%0A000000101010%0A011001101110%0A000101101011%0A010001111001&config=p) (with third testcase as input).
### Explanation
Slip is a language from the [2-D Pattern Matching](https://codegolf.stackexchange.com/q/47311/16766) challenge. Sp3000 could say a lot more about it than I can, but basically it's an extended form of regex with some directional commands that let you match in two dimensions. The above code uses the eponymous "slip" command `\`, which doesn't change the match pointer's direction but moves it sideways by one character. It also uses "stationary group" `(?|...)`, which matches something and then resets the pointer to its previous location.
The code breaks down as follows:
```
(?|1011) Match 1011; reset pointer to beginning of match
( ){2} Do the following twice:
\ Slip (moves pointer down one row)
(?|1110) Match 1110; reset pointer to beginning of match
\1111 Slip and match 1111
```
This matches the `0xBEEF` square. The `p` option outputs the coordinates of the match, 0-indexed.
[Answer]
# PHP, 87 Bytes
binary string as input without separators, returns zero-indexed values.
```
preg_match("#1011(.{8}1110){2}.{8}1111#",$argv[1],$c,256);echo($s=$c[0][1])%12,$s/12^0;
```
array of numbers as input 128 Bytes
```
<?foreach($_GET[a]as$a)$b.=sprintf("%012b",$a);preg_match("#1011(.{8}1110){2}.{8}1111#",$b,$c,256);echo($s=$c[0][1])%12,$s/12^0;
```
14 Bytes saved by [@Titus](https://codegolf.stackexchange.com/users/55735/titus) Thank You
[Answer]
# Java 7,~~182~~ 177 bytes
[I ported Karl Napf **C** answer to **JAVA**](https://codegolf.stackexchange.com/a/97196/58766) And Thanks to [Karl Napf](https://codegolf.stackexchange.com/a/97196/58766) for saving 5 bytes by reminding me Bit magic.(Btw i came up with this idea too but @KarlNapf return part idea was yours not mine).Sorry if i displeased you.
(0-based)
```
int f(int[]a){int x=9,y,z=0;for(;x-->0;){for(y=0;y<9;a[y++]/=2) if((a[y]&15)==11&(a[y+1]&15)==14&(a[y+2]&15)==14&(a[y+3]&15)==15)z=(x<<4)+y;a[y]/=2;a[10]/=2;a[11]/=2;}return z;}
```
# Ungolfed
```
class Beef {
public static void main(String[] args) {
int x = f(new int[] { 1222, 3107, 1508, 3997, 1906, 379, 2874, 2926, 1480, 1487, 3565, 633 });
System.out.println(x >> 4);
System.out.println(x & 15);
}
static int f(int[] a) {
int x = 9,
y,
z = 0;
for (; x-- > 0; ) {
for (y = 0; y < 9; a[y++] /= 2)
if ((a[y] & 15) == 11
& (a[y + 1] & 15) == 14
& (a[y + 2] & 15) == 14
& (a[y + 3] & 15) == 15)
z = (x << 4) + y;
a[y] /= 2;
a[10] /= 2;
a[11] /= 2;
}
return z;
}
}
```
[Answer]
# Scala, 90 bytes
```
("1011.{8}(1110.{8}){2}1111".r.findAllMatchIn(_:String).next.start)andThen(i=>(i/12,i%12))
```
Explanation:
```
(
"1011.{8}(1110.{8}){2}1111" //The regex we're using to find the beef
.r //as a regex object
.findAllMatchIn(_:String) //find all the matches in the argument thats going to be passed here
.next //get the first one
.start //get its start index
) //this is a (String -> Int) function
andThen //
(i=> //with the found index
(i/12,i%12) //convert it to 2d values
)
```
`(a -> b) andThen (b -> c)` results in a `(a -> c)` function, it's like the reverse of compose, but requires fewer type annotations in scala. In this case, it takes a string of the binary digits as input and returns a tuple of zero-based indices.
[Answer]
# J, ~~31~~ 29 bytes
```
[:($#:I.@,)48879=4 4#.@,;._3]
```
The input is formatted as a 2d array of binary values, and the output is the zero-based coordinates as an array `[y, x]`.
The flattening and base conversion to find the index is something I learned from this [comment](https://codegolf.stackexchange.com/questions/79609/index-of-a-multidimensional-array#comment195189_79617) by Dennis.
## Usage
```
f =: [:($#:I.@,)48879=4 4#.@,;._3]
] m =: _12 ]\ 1 1 1 0 0 1 1 1 1 1 1 0 1 1 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 1 1 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 0 0 0 1 0 1 0 1 1 1 1 1 0 0 1 1 0 0 0 0 1 1
1 1 1 0 0 1 1 1 1 1 1 0
1 1 0 1 0 0 1 0 0 0 0 0
0 1 0 0 0 1 1 1 1 1 0 1
1 0 0 1 0 0 1 0 0 1 0 0
1 0 0 1 0 1 1 0 0 1 1 1
1 1 1 1 1 1 0 0 0 0 1 0
1 1 0 1 1 1 0 0 0 0 0 1
1 0 0 1 1 1 1 0 0 0 0 1
1 0 0 1 1 1 0 1 1 1 1 1
1 1 1 1 1 0 0 1 1 1 1 1
1 0 0 0 0 1 0 1 0 1 1 1
1 1 0 0 1 1 0 0 0 0 1 1
f m
4 3
f (#:~2#~#) 3710 3360 1149 2340 2407 4034 3521 2529 2527 3999 2135 3267
4 3
f (#:~2#~#) 1222 3107 1508 3997 1906 379 2874 2926 1480 1487 3565 633
7 3
f (#:~2#~#) 2796 206 148 763 429 1274 2170 2495 42 1646 363 1145
4 6
f (#:~2#~#) 3486 3502 1882 1886 2003 1442 2383 2808 1416 1923 2613 519
1 1
f (#:~2#~#) 3661 2382 2208 1583 1865 3969 2864 3074 475 2382 1838 127
8 8
f (#:~2#~#) 361 1275 3304 2878 3733 3833 3971 3405 2886 448 3101 22
3 0
f (#:~2#~#) 3674 2852 1571 3582 1402 3331 1741 2678 2076 2685 734 261
7 7
```
## Explanation
```
[:($#:I.@,)48879=4 4#.@,;._3] Input: 2d array M
] Identity. Get M
4 4 ;._3 For each 4x4 subarray of M
, Flatten it
#.@ Convert it to decimal from binary
48879= Test if equal to 48879 (decimal value of beef)
[:( ) Operate on the resulting array
, Flatten it
I.@ Find the indices where true
#: Convert from decimal to radix based on
$ The shape of that array
Returns the result as coordinates [y, x]
```
[Answer]
# Python 2, ~~98~~ ~~95~~ 92 bytes
```
lambda x:'%x'%(`[''.join('%x'%int(s[i:i+4],2)for s in x)for i in range(9)]`.find('beef')+15)
```
Input is a list of strings, output is the string **XY** (1-based indices).
Test it on [Ideone](http://ideone.com/cNWRuY).
[Answer]
## Retina, 47 bytes
I'd like to preface this with an apology. I think this is probably terrible and a bad example of how to use the language, but since I used a Regex for my Perl answer, I thought I'd try Retina. I'm not very good. :( The [snippets on github](https://github.com/m-ender/retina/wiki) helped me greatly though!
Thanks to @[wullzx](https://codegolf.stackexchange.com/users/61114/wullxz) for his comment on my Perl answer for -3 bytes and to @[Taemyr](https://codegolf.stackexchange.com/users/16596/taemyr) for pointing out an issue with my method!
Expects input as a space-separated binary string and outputs co-ordinates space separated.
```
(.{13})*(.)*1011(.{9}1110){2}.{9}1111.*
$#2 $#1
```
[Try it online!](http://retina.tryitonline.net/#code=KC57MTN9KSooLikqMTAxMSguezl9MTExMCl7Mn0uezl9MTExMS4qCiQjMiAkIzE&input=MTExMDAxMTExMTEwIDExMDEwMDEwMDAwMCAwMTAwMDExMTExMDEgMTAwMTAwMTAwMTAwIDEwMDEwMTEwMDExMSAxMTExMTEwMDAwMTAgMTEwMTExMDAwMDAxIDEwMDExMTEwMDAwMSAxMDAxMTEwMTExMTEgMTExMTEwMDExMTExIDEwMDAwMTAxMDExMSAxMTAwMTEwMDAwMTE)
[Verify all tests at once.](http://retina.tryitonline.net/#code=JShgKC57MTN9KSooLikqMTAxMSguezl9MTExMCl7Mn0uezl9MTExMS4qCiQjMiAkIzE&input=MTExMDAxMTExMTEwIDExMDEwMDEwMDAwMCAwMTAwMDExMTExMDEgMTAwMTAwMTAwMTAwIDEwMDEwMTEwMDExMSAxMTExMTEwMDAwMTAgMTEwMTExMDAwMDAxIDEwMDExMTEwMDAwMSAxMDAxMTEwMTExMTEgMTExMTEwMDExMTExIDEwMDAwMTAxMDExMSAxMTAwMTEwMDAwMTEKMDEwMDExMDAwMTEwIDExMDAwMDEwMDAxMSAwMTAxMTExMDAxMDAgMTExMTEwMDExMTAxIDAxMTEwMTExMDAxMCAwMDAxMDExMTEwMTEgMTAxMTAwMTExMDEwIDEwMTEwMTEwMTExMCAwMTAxMTEwMDEwMDAgMDEwMTExMDAxMTExIDExMDExMTEwMTEwMSAwMDEwMDExMTEwMDEKMTAxMDExMTAxMTAwIDAwMDAxMTAwMTExMCAwMDAwMTAwMTAxMDAgMDAxMDExMTExMDExIDAwMDExMDEwMTEwMSAwMTAwMTExMTEwMTAgMTAwMDAxMTExMDEwIDEwMDExMDExMTExMSAwMDAwMDAxMDEwMTAgMDExMDAxMTAxMTEwIDAwMDEwMTEwMTAxMSAwMTAwMDExMTEwMDEKMTEwMTEwMDExMTEwIDExMDExMDEwMTExMCAwMTExMDEwMTEwMTAgMDExMTAxMDExMTEwIDAxMTExMTAxMDAxMSAwMTAxMTAxMDAwMTAgMTAwMTAxMDAxMTExIDEwMTAxMTExMTAwMCAwMTAxMTAwMDEwMDAgMDExMTEwMDAwMDExIDEwMTAwMDExMDEwMSAwMDEwMDAwMDAxMTEKMTExMDAxMDAxMTAxIDEwMDEwMTAwMTExMCAxMDAwMTAxMDAwMDAgMDExMDAwMTAxMTExIDAxMTEwMTAwMTAwMSAxMTExMTAwMDAwMDEgMTAxMTAwMTEwMDAwIDExMDAwMDAwMDAxMCAwMDAxMTEwMTEwMTEgMTAwMTAxMDAxMTEwIDAxMTEwMDEwMTExMCAwMDAwMDExMTExMTEKMDAwMTAxMTAxMDAxIDAxMDAxMTExMTAxMSAxMTAwMTExMDEwMDAgMTAxMTAwMTExMTEwIDExMTAxMDAxMDEwMSAxMTEwMTExMTEwMDEgMTExMTEwMDAwMDExIDExMDEwMTAwMTEwMSAxMDExMDEwMDAxMTAgMDAwMTExMDAwMDAwIDExMDAwMDAxMTEwMSAwMDAwMDAwMTAxMTAKMTExMDAxMDExMDEwIDEwMTEwMDEwMDEwMCAwMTEwMDAxMDAwMTEgMTEwMTExMTExMTEwIDAxMDEwMTExMTAxMCAxMTAxMDAwMDAwMTEgMDExMDExMDAxMTAxIDEwMTAwMTExMDExMCAxMDAwMDAwMTExMDAgMTAxMDAxMTExMTAxIDAwMTAxMTAxMTExMCAwMDAxMDAwMDAxMDE)
[Answer]
# [Perl 5](https://www.perl.org/) + `-n -M5.10.0`, 51 bytes
Uses 0-based indices. Expects input as a string of `1`s and `0`s and outputs space separated co-ordinates.
Thanks to @[wullxz](https://codegolf.stackexchange.com/users/61114/wullxz) and @[GabrielBenamy](https://codegolf.stackexchange.com/users/60884/gabriel-benamy) for helping me save 9 bytes, and to @[Taemyr](https://codegolf.stackexchange.com/users/16596/taemyr)'s comment on my Retina answer for pointing out an issue!
```
/1011.{9}(1110.{9}){2}1111/;say"@-"%13,$","@-"/13|0
```
[Try it online!](https://tio.run/##VVRBTsNADLznFVYEAqSm8VD1gLjwAR7BgQMSaivKBZV@nSUbz3iTaKuu47Uznpnk9P71uS9lhAPby9P1HoDXzcPl8TrtMT6f3376l6G/xW5z02/qdsTu10upRx3z5Tb9auT1svk/ErC4HSsC1hlr69loEAFrlGIQ/YwlDKIW7ObOEnSugNjcicnitOBkN68ZYZhqonHcsYQ8A3VwwdktmreAcFheW3tOhI6A554WeJ3dnERFBuIQFqfUDcmuk4MWiKm5RvRUbJnL4RwkZIEtR5UknpMmgEWgDOUnvdFSaouQnEdUefKWyscxDWtyVD3RiejmKvEGzknzIcUT0HlZ2i1c1Qxjup3SS@L1c6R1ikWqJ78lo2t9ZMtA14wU9EJqw9Lha6A00mJsJEEC6ssRaOXUHt4l6HSv3samQTMs0tfNVWgymKdFnGKRLGtSxaTtE6DHN/MR3V33dzx9fxwP5zK87rfTp8fLcPgH "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes
```
⍸⎕⍷⍨~⊤0 8 0 6
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@j3h2P@qY@6t3@qHdF3aOuJQYKFgoGCmYgyf@caVyP2iZWA@VrD6141LvZ0IjLUAEEDYDQEAkacEFEYTIGMMiF4CGpVjDkQlaJRCKJo9jDhWIb3ESEvcjiyOaj6UARR3ITF6rpyOJItiH0cCGrRKgwBAA "APL (Dyalog Extended) – Try It Online")
We already have [Zacharý's APL answer](https://codegolf.stackexchange.com/a/97295/78410), but APL has improved a lot over the recent years, just enough to beat Jelly!
A full program that takes the binary matrix from stdin and prints the `(y,x)` to stdout.
### How it works
```
⍸⎕⍷⍨~⊤0 8 0 6
⊤0 8 0 6 ⍝ Binary representation (a number → column)
⍝ 0 1 0 0
⍝ 0 0 0 1
⍝ 0 0 0 1
⍝ 0 0 0 0
~ ⍝ Boolean negation
⎕⍷⍨ ⍝ Take input and mark 1 where the 2D pattern appears
⍸ ⍝ Extract the coordinates of all ones
```
[Answer]
# [Ruby](http://www.ruby-lang.org/), 62 bytes
```
def f(a);a=~/1011(.{8}1110){2}.{8}1111/;$`.size.divmod(12);end
```
It expects a string of `0` and `1` and returns an array of Y and X, zero-based.
[Try at ideone](http://ideone.com/AKhNf6).
[Answer]
**Scala, 318 Bytes**
*This solution could be further improved... but I kept it readable and allowed for the input to be the multi-line spaced matrix.*
**Actual Solution if Array of binary String**
```
def has(s: String, t: String): Int = s.indexOf(t)
val beef = List("1011", "1110", "1110", "1111")
l.zipWithIndex.map{case(e,i)=>l.drop(i).take(4)}.map{_.zip(beef)}.map{_.collect{case e=>has(e._1,e._2)}}.zipWithIndex.filterNot{e => e._1.contains(-1) || e._1.distinct.length > 1}.map{e=>s"(${e._1.head},${e._2})"}.head
```
**Sample Working**
```
val bun =
"""1 1 1 0 0 1 1 1 1 1 1 0
1 1 0 1 0 0 1 0 0 0 0 0
0 1 0 0 0 1 1 1 1 1 0 1
1 0 0 1 0 0 1 0 0 1 0 0
1 0 0 1 0 1 1 0 0 1 1 1
1 1 1 1 1 1 0 0 0 0 1 0
1 1 0 1 1 1 0 0 0 0 0 1
1 0 0 1 1 1 1 0 0 0 0 1
1 0 0 1 1 1 0 1 1 1 1 1
1 1 1 1 1 0 0 1 1 1 1 1
1 0 0 0 0 1 0 1 0 1 1 1
1 1 0 0 1 1 0 0 0 0 1 1
""".replaceAll(" ","")
def has(s: String, t: String): Int = s.indexOf(t)
val beef = List("1011", "1110", "1110", "1111")
val l = bun.split("\n").toList
l.zipWithIndex.map{case(e,i)=>l.drop(i).take(4)}
.map{_.zip(beef)}
.map{_.collect{case e=>has(e._1,e._2)}}.zipWithIndex
.filterNot{e => e._1.contains(-1) || e._1.distinct.length > 1}
.map{e=>s"(${e._1.head},${e._2})"}.head
```
[Answer]
# [Element](http://github.com/PhiNotPi/Element), 130 bytes
```
_144'{)"1-+2:';}144'["1-+19:~?1+~?!2+~?3+~?12+~?13+~?14+~?15+~?!24+~?25+~?26+~?27+~?!36+~?37+~?38+~?39+~?16'[&][12%2:`\ `-+12/`]']
```
[Try it online!](http://element.tryitonline.net/#code=XzE0NCd7KSIxLSsyOic7fTE0NCdbIjEtKzE5On4_MSt-PyEyK34_Myt-PzEyK34_MTMrfj8xNCt-PzE1K34_ITI0K34_MjUrfj8yNit-PzI3K34_ITM2K34_Mzcrfj8zOCt-PzM5K34_MTYnWyZdWzEyJTI6YFwgYC0rMTIvYF0nXQ&input=MTExMDAxMTExMTEwMTEwMTAwMTAwMDAwMDEwMDAxMTExMTAxMTAwMTAwMTAwMTAwMTAwMTAxMTAwMTExMTExMTExMDAwMDEwMTEwMTExMDAwMDAxMTAwMTExMTAwMDAxMTAwMTExMDExMTExMTExMTEwMDExMTExMTAwMDAxMDEwMTExMTEwMDExMDAwMDEx)
Takes input as one long string of 1s and 0s without any delimiters. Outputs like `3 4` (0-based indexing).
This works by placing the input data into an "array" (basically a dictionary with integer keys) and then, for each possible starting value, tests the bits at particular offsets (all 16 of them in a very laborious process).
[Answer]
**Python, 137 bytes** (according to Linux (thanks ElPedro))
```
def f(s,q=0):import re
i=s.index(re.findall('1011.{8}1110.{8}1110.{8}1111',s)[q])+1
x=i%12
y=(i-x)/12
if x>8:x,y=f(s,q+1)
return x,y
```
Not exactly a competitive bytecount, but the algorithm is a bit interesting. Takes input as a string of binary values.
[Answer]
# **F# - 260 bytes**
Full program, including the required EntryPoint designator (so count fewer if you wish I suppose).
Input: each row as separate string:
"111001111110" "110100100000" "010001111101" "100100100100" "100101100111" "111111000010" "110111000001" "100111100001" "100111011111" "111110011111" "100001010111" "110011000011"
Code:
```
[<EntryPoint>]
let main a=
let rec f r:int=
let b=a.[r].IndexOf"1011"
if(b>0)then if(a.[r+1].[b..b+3].Equals"1110"&&a.[r+2].[b..b+3].Equals"1110"&&a.[r+3].[b..b+3].Equals"1111")then r else f(r+1)
else f(r+1)
printfn"%d%d"(a.[f 0].IndexOf"1011")(f 0);0
```
Not the most elegant solution most likely, but i wanted to keep with strings, so this is how i did it. I almost got it to be a single line and smaller using pipes, but there is something with the double if block that was getting me that i couldn't resolve. So oh well!
I thought too about porting Karl's answer into F# as it's a good one, and may still do that for fun as another approach, but wanted to stick with this one to be different.
[Answer]
## Dyalog APL, ~~29~~ 27 bytes
Takes a 12x12 binary array as user input and returns the coordinates in reverse order, the indexes start at 1.
Thanks to @Adám for saving many bytes.
-2 Bytes because I'm dumb and left everything in a function for no reason.
```
0~⍨∊{⍵×⍳⍴⍵}⎕⍷⍨~0 8 0 6⊤⍨4/2
```
[Answer]
# [R](https://www.r-project.org/), 111 bytes
```
function(a,b=63357%/%2^(0:15)%%2)
which(sapply(1:9,function(i)sapply(1:9,function(j)all(a[i+0:3,j+0:3]==b))),T)
```
[Try it online!](https://tio.run/##bZFdC4IwFIbv9z@EHRq0KRYJu@0XdBclm0xcmIofmL9@KdbaJF44@3jPy3PYWjMWqlVd2hcqlUrl3ORDlfW6rrAgkh@iKD4G@yC8Y5qwGIIgBDQWOitwJ5qmnDBLTsRGNPy7fYAoSyyuekeTiDyWeuNcAgC5gJnJcqj4U/StfuEMI0YW0VnMESVoXb4WtUK/o9vPlgTdJNbqGD4L@Uhq2yyceWiHsc14hjsZ8gme4SKZPxV1hv3sYXZCIqe2HvkZENr8JV6fFswb "R – Try It Online")
Searches for identities of 4x4 matrix starting at all indices of 9x9 matrix (to avoid edge overlaps).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2Fø€ü4}JJ˜Žùòbk9‰
```
Input as a matrix of bits. Output is 0-based, in the order \$Y,X\$.
[Try it online](https://tio.run/##yy9OTMpM/f/fyO3wjkdNaw7vMan18jo95@jewzsPb0rKtnzUsOH//@hoQx0QNABCQyRoEKsTDRGHyRnAIFAGwUfSoWMI1mOApscQqgfBQ7EPag/CFJi5yC5AlkG1B00XmgyS@1DsMcCQQbIXoQ/uAgM0txnGxgIA) or [verify all test cases](https://tio.run/##RVC7SkNREOzzFZJ6hbOP8xJEBLGwUbAMKRJNERUVvREsBPE7/ARBsRBFbXKx8i/yI3H2Ktgse3ZnZmfO2eVoPJ0sr/p7F5OmuV49v5ieNpPDlenp@axZW@lT73rMctQ@hbWt@Tv1@psHzWx08r9f3D3st4/rvf7urPkbLWW7fcW8/bCbnZ3v@6/P9q19Hh/Xxe3TkuYvG8vBQDMHUk2BmK2SqAUSC5ksqJFGYZIo1UsmrRUdaySVlIc0YBEhZcA5huJ7dDUk0gxgyUZSJRFbCV6gEFOkpAqu5JpIQrelnJQMZ1icw9lN1IgRcTLIYQ1/ETS1gncM2JTSFVcJ2BvQokVxGF7YGNJV8EysFLk6OSV2DIDimAg0F1jSmtxwQuQAB5bjL4yLFjfVcdk7YDWYh0PerEq4iFIzE/4ONDdkiIRvwS3pmB6qRMhFh0UXNiRQVWhmAy5BTkJGllQiZfw9bA@HPw).
**Explanation:**
```
2Fø€ü4} # Create transposed overlapping 4x4 blocks of the (implicit) input-matrix:
2F # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
€ # Map over each row:
ü4 # Create all overlapping quartets
} # Close the loop
J # Join each row of each matrix together
J # Join the rows of each matrix together
˜ # Flatten the list of strings
Žùò # Push compressed integer 63481
b # Convert it to binary: 1111011111111001
k # Get the index of this binary-string in the list
9‰ # Divmod it by 9
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Žùò` is `63481`.
[Answer]
# [Uiua](https://www.uiua.org), 12 bytes
```
⊚⌕⋯13_7_7_15
```
Self explanatory. Converts the number array to bits, finds where it is. The input is a 12x12 bit matrix, the output is a 1x2 matrix where the X coordinate is the second element.
[Test pad](https://uiua.org/pad?src=0_7_1__RiDihpAg4oqa4oyV4ouvMTNfN183XzE1CgpGIOKJoeKHjOKLryBbMzcxMCAzMzYwIDExNDkgMjM0MCAyNDA3IDQwMzQgMzUyMSAyNTI5IDI1MjcgMzk5OSAyMTM1IDMyNjddCkYg4omh4oeM4ouvIFsxMjIyIDMxMDcgMTUwOCAzOTk3IDE5MDYgMzc5IDI4NzQgMjkyNiAxNDgwIDE0ODcgMzU2NSA2MzNdCkYg4omh4oeM4ouvIFsyNzk2IDIwNiAxNDggNzYzIDQyOSAxMjc0IDIxNzAgMjQ5NSA0MiAxNjQ2IDM2MyAxMTQ1XQo=)
] |
[Question]
[
The sorting algorithm goes like this:
While the list is not sorted, snap half of all items (remove them from the list). Continue until the list is sorted or only one item remains (which is sorted by default). This sorting algorithm may give different results based on implementation.
The item removal procedure is up to the implementation to decide, but the list should be half as long as before after one pass of the item removal procedure. Your algorithm may decide to remove either the first half or the list, the last half of the list, all odd items, all even items, one at a time until the list is half as long, or any not mentioned.
The input list can contain an arbitrary amount of items (within reason, let’s say up to 1000 items), not only perfectly divisible lists of 2^n items. You will have to either remove (n+1)/2 or (n-1)/2 items if the list is odd, either hardcoded or decided randomly during runtime. Decide for yourself: what would Thanos do if the universe contained an odd amount of living things?
The list is sorted if no item is smaller than any previous item. Duplicates may occur in the input, and may occur in the output.
Your program should take in an array of integers (via stdin or as parameters, either individual items or an array parameter), and return the sorted array (or print it to stdout).
Examples:
```
// A sorted list remains sorted
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]
// A list with duplicates may keep duplicates in the result
[1, 2, 3, 4, 3] -> [1, 3, 3] // Removing every second item
[1, 2, 3, 4, 3] -> [3, 4, 3] -> [4, 3] -> [3] // Removing the first half
[1, 2, 3, 4, 3] -> [1, 2] // Removing the last half
```
`[1, 2, 4, 3, 5]` could give different results:
```
// Removing every second item:
[1, 2, 4, 3, 5] -> [1, 4, 5]
```
or:
```
// Removing the first half of the list
[1, 2, 4, 3, 5] -> [3, 5] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [4, 3, 5] -> [3, 5] // With (n-1)/2 items removed
```
or:
```
// Removing the last half of the list
[1, 2, 4, 3, 5] -> [1, 2] // With (n+1)/2 items removed
[1, 2, 4, 3, 5] -> [1, 2, 4] // With (n-1)/2 items removed
```
or:
```
// Taking random items away until half (in this case (n-1)/2) of the items remain
[1, 2, 4, 3, 5] -> [1, 4, 3] -> [4, 3] -> [4]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~38~~ ~~42~~ 39 bytes
```
q=lambda t:t>sorted(t)and q(t[::2])or t
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9A2JzE3KSVRocSqxK44v6gkNUWjRDMxL0WhUKMk2srKKFYzv0ih5H9BUWZeiUahRrShjpGOcaymJhdcxBgoYggU@Q8A "Python 3 – Try It Online")
`-3 bytes` thanks to @JoKing and @Quuxplusone
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
x=scan();while(any(x-sort(x)))x=x[!0:1];x
```
[Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTujwjMydVIzGvUqNCtzi/qESjQlNTs8K2IlrRwMow1rriv6GCkYKJgrGC6X8A "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
f=lambda l:l>sorted(l)and f(l[::2])or l
```
[Try it online!](https://tio.run/##Vcm7CoAgFADQva@4Y8JdfC1C/Yg4GCYFNxVz6evNsdZzytOOnETvcSF/bcEDGVrvXNseZmI@BYgzWWOEY7kC9VLP1IZZjiAQFIJE0I5NnxAoUeEP9QA5gjvWXw "Python 2 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 6 bytes
```
≤₁|ḍt↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnkkdNjTUPd/SWPGrb8P9/tKGOkY6JjrGOaez/KAA "Brachylog – Try It Online")
This is a function submission. Input from the left, output to the right, as usual. (The TIO link uses a command-line argument that automatically wraps the function into a full program, so that you can see it in action.)
## Explanation
```
≤₁|ḍt↰
≤₁ Assert that {the input} is sorted {and output it}
| Handler for exceptions (e.g. assertion failures):
ḍ Split the list into two halves (as evenly as possible)
t Take the last (i.e. second) half
↰ Recurse {and output the result of the recursion}
```
## Bonus round
```
≤₁|⊇ᵇlᵍḍhtṛ↰
```
[Try it online!](https://tio.run/##ATcAyP9icmFjaHlsb2cy///iiaTigoF84oqH4bWHbOG1jeG4jWh04bmb4oaw//9bMSwyLDQsMyw1Xf9a "Brachylog – Try It Online")
The snap's meant to be random, isn't it? Here's a version of the program that choses the surviving elements randomly (while ensuring that half survive at each round).
```
≤₁|⊇ᵇlᵍḍhtṛ↰
≤₁ Assert that {the input} is sorted {and output it}
| Handler for exceptions (e.g. assertion failures):
⊇ᵇ Find all subsets of the input (preserving order)
lᵍ Group them by length
ḍht Find the group with median length:
t last element of
h first
ḍ half (split so that the first half is larger)
ṛ Pick a random subset from that group
↰ Recurse
```
This would be rather shorter if we could reorder the elements, but whyever would a sorting algorithm want to do *that*?
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
$!={[<=]($_)??$_!!.[^*/2].&$!}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0XRtjraxjZWQyVe095eJV5RUS86TkvfKFZPTUWx9n9xYqVCmkK0oY6CkY6CsY6CiY6Caaw1FxZhY3RhE7CMaex/AA "Perl 6 – Try It Online")
Recursive function that removes the second half of the list until the list is sorted.
### Explanation:
```
$!={ } # Assign the function to $!
[<=]($_)?? # If the input is sorted
$_ # Return the input
!! # Else
.[^*/2] # Take the first half of the list (rounding up)
.&$! # And apply the function again
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 76 bytes
```
g=>{while(!g.OrderBy(x=>x).SequenceEqual(g))g=g.Take(g.Count()/2);return g;}
```
[Try it online!](https://tio.run/##XY3RasIwFEDf/YrYp1x6jdipDGoCOhQEYQ8b7DntrtewLmKaYIf02@vm4@A8HTicup3UrRt2yder/danbwq2amjlfDT4Xxhx1ANrc7ueXENyzOo1fFLY/MhOmw7UG10S@Zq2l2QbyQCsWb3bL5KsXs7JRwnTAspAMQUvuOyHcjT6CC6SPEpPV3FwbXycbjMs8BnF/METigUu8c/NelBr5kBsf6ssQ2mxAm1snoksrwDK4Q4 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Java 10, ~~106~~ 97 bytes
```
L->{for(;;L=L.subList(0,L.size()/2)){int p=1<<31,f=1;for(int i:L)f=p>(p=i)?0:f;if(f>0)return L;}}
```
-9 bytes thanks to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##tZFNb8MgDIbv/RUcQXJY0g81LU2mHSexXnqcdqApVHQpjYB06qr89oxknTRN2i0FhMDG72ObgziL6LB7b4tSOIdehDbXEULaeGmVKCRad1eEDuEdrb0uKdfOr56Dfy9tjgr8n4cTFiKbUdicF14XaI0Myloe5Vd1spgxnnHq6m0XhmMIZ/0pMXkYE3INfFRlyWo1SUBlCesCOptecqKyKsdVpsljvFRMK6zymFjpa2sQZ03Tso5Z1dsyMG/o80nv0DEUhzfearN/fUOCfFe2uTgvj/RUe1oFly8NNrTARn78KvrJWnHpE/1jc1S43p7AGCYwhRkJgw2tPA3awytPIR1cM4UouUOis9CEFIZXnkA/B9ed9V82vkPGURJDWNECFhCloSnRHOZ3ofT68xus4/xQmlHTfgE)
Only leave the first halve of the list every iteration, and removes \$\frac{n+1}{2}\$ items if the list-size is odd.
**Explanation:**
```
L->{ // Method with Integer-list as both parameter and return-type
for(;; // Loop indefinitely:
L=L.subList(0,L.size()/2)){
// After every iteration: only leave halve the numbers in the list
int p=1<<31, // Previous integer, starting at -2147483648
f=1; // Flag-integer, starting at 1
for(int i:L) // Inner loop over the integer in the list:
f=p>(p=i)? // If `a>b` in a pair of integers `a,b`:
0 // Set the flag to 0
: // Else (`a<=b`):
f; // Leave the flag the same
if(f>0) // If the flag is still 1 after the loop:
return L;}} // Return the list as result
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
#//.x_/;Sort@x!=x:>x[[;;;;2]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1lfX68iXt86OL@oxKFC0bbCyq4iOtoaCIxiY9X@BxRl5pUoOASWZqaWOCikR1cb6igY6SiY6CgY6yiY1sb@/w8A "Wolfram Language (Mathematica) – Try It Online")
@Doorknob saved 12 bytes
[Answer]
# JavaScript (ES6), ~~49~~ 48 bytes
*Saved 1 byte thanks to @tsh*
Removes every 2nd element.
```
f=a=>a.some(p=c=>p>(p=c))?f(a.filter(_=>a^=1)):a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5Rrzg/N1WjwDbZ1q7ADkRratqnaSTqpWXmlKQWacQDlcTZGmpqWiX@T87PK87PSdXLyU/XSNOINtQx0jHWMdExjdXU5MIiZwKUxSYH0mUI1fcfAA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 37 bytes
```
->r{r=r[0,r.size/2]while r.sort!=r;r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166ousi2KNpAp0ivOLMqVd8otjwjMydVAcjNLypRtC2yLqr9X6CQFh1tqGOkY6JjrGMaG8sFFzAGCsEFTMHyRjqGsbH/AQ "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[Ð{Q#ιн
```
-1 byte thanks to *@Emigna*.
Removes all odd 0-indexed items every iteration, so removes \$\frac{n-1}{2}\$ items if the list-size is odd.
[Try it online](https://tio.run/##yy9OTMpM/f8/@vCE6kDlczsv7AWyDXUUjHQUTHQUjHUUTGMB) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6MMTqgOVz@28sPd/rc7/6GhDHSMdYx0THdNYHQUwxwTIBXNMdCxAlIWOriGEawqUtdABc4x1wBDENAXrMIKI6xoa6ACRrqWOpY6uBVC1rrmOOUwCLGQOlQdJxcYCAA) (or [verify those test cases with step-by-step for each iteration](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX@mio@RfWgLkKZRnlmQoFJekFhQDJXT@Rx@eUB2ofG6n7YW9/2t1Dm2z/x8dbahjpGOsY6JjGqujAOaYALlgjomOBYiy0NE1hHBNgbIWOmCOsQ4YgpimYB1GEHFdQwMdINK11LHU0bUAqtY11zGHSYCFzKHyIKnYWAA)).
**7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative by *@Grimy***:
```
ΔÐ{Ê>äн
```
Removes the last \$\frac{n}{2}\$ items (or \$\frac{n-1}{2}\$ items if the list-size is odd) every iteration.
[Try it online](https://tio.run/##yy9OTMpM/f//3JTDE6oPd9kdXnJh7///0YY6CkY6CiY6CsY6CqaxAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1MOT6g@3GV3eMmFvf9rdf5HRxvqGOkY65jomMbqKIA5JkAumGOiYwGiLHR0DSFcU6CshQ6YY6wDhiCmKViHEURc19BAB4h0LXUsdXQtgKp1zXXMYRJgIXOoPEgqNhYA) (or [verify those test cases with step-by-step for each iteration](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX@mio@RfWgLkKZRnlmQoFJekFhQDJXT@n5tyeEL14S67w0tsL@z9X6tzaJv9/@hoQx0jHWMdEx3TWB0FMMcEyAVzTHQsQJSFjq4hhGsKlLXQAXOMdcAQxDQF6zCCiOsaGugAka6ljqWOrgVQta65jjlMAixkDpUHScXGAgA)).
**Explanation:**
```
[ # Start an infinite loop:
Ð # Triplicate the list (which is the implicit input-list in the first iteration)
{Q # Sort a copy, and check if they are equal
# # If it is: Stop the infinite loop (and output the result implicitly)
ι # Uninterweave: halve the list into two parts; first containing all even-indexed
# items, second containing all odd-indexed items (0-indexed)
# i.e. [4,5,2,8,1] → [[4,2,1],[5,8]]
н # And only leave the first part
Δ # Loop until the result no longer changes:
Ð # Triplicate the list (which is the implicit input-list in the first iteration)
{Ê # Sort a copy, and check if they are NOT equal (1 if truthy; 0 if falsey)
> # Increase this by 1 (so 1 if the list is sorted; 2 if it isn't sorted)
ä # Split the list in that many parts
н # And only leave the first part
# (and output the result implicitly after it no longer changes)
```
[Answer]
# TI-BASIC (TI-84), ~~47~~ ~~42~~ ~~45~~ 44 bytes
*-1 byte thanks to @SolomonUcko!*
```
Ans→L1:Ans→L2:SortA(L1:While max(L1≠Ans:iPart(.5dim(Ans→dim(L2:L2→L1:SortA(L1:End:Ans
```
Input list is in `Ans`.
Output is in `Ans` and is implicitly printed out.
**Explanation:**
```
Ans→L1 ;store the input into two lists
Ans→L2
SortA(L1 ;sort the first list
; two lists are needed because "SortA(" edits the list it sorts
While max(L1≠Ans ;loop until both lists are strictly equal
iPart(.5dim(Ans→dim(L2 ;remove the latter half of the second list
; removes (n+1)/2 elements if list has an odd length
L2→L1 ;store the new list into the first list (updates "Ans")
SortA(L1 ;sort the first list
End
Ans ;implicitly output the list when the loop ends
```
---
**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
m2$⁻Ṣ$¿
```
[Try it online!](https://tio.run/##ASwA0/9qZWxsef//bTIk4oG74bmiJMK//8OHxZLhuZj//1sxLCAyLCA0LCAzLCA1XQ "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~57~~ 55 bytes (thanks to ASCII-only)
```
f x|or$zipWith(>)x$tail x=f$take(div(length x)2)x|1>0=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoia/SKUqsyA8syRDw06zQqUkMTNHocI2DcjITtVIySzTyEnNSy/JUKjQNNKsqDG0M7Ct@J@bmJmnYKuQkq9QUFoSXFLkk6egolCckV8OpNIUog11jHRMdIx1TGO5FOAAp0pjoFrCKk3BJhrpGMb@BwA "Haskell – Try It Online")
---
Original Code:
```
f x|or$zipWith(>)x(tail x)=f(take(div(length x)2)x)|1>0=x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoia/SKUqsyA8syRDw06zQqMkMTNHoULTNg3Iyk7VSMks08hJzUsvyQAKGmlWaNYY2hnYVvzPTczMU7BVSMlXKCgtCS4p8slTUFEozsgvB1JpCtGGOkY6JjrGOqaxXApwgFOlMVAtYZWmYBONdAxj/wMA "Haskell – Try It Online")
---
Ungolfed:
```
f xs | sorted xs = f (halve xs)
| otherwise = xs
sorted xs = or (zipWith (>) xs (tail xs))
halve xs = take (length xs `div` 2) xs
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~9~~ 8 bytes
```
eo₌⟨2%⟩↻
```
[Try it online!](https://tio.run/##S0/MTPz/PzX/UVPPo/krjFQfzV/5qG33///RhgpGCsYKJgrGsQA "Gaia – Try It Online")
Explanation:
```
e | eval input as a list
↻ | until
o | the list is sorted
₌ | push additional copy
⟨2%⟩ | and take every 2nd element
```
[Answer]
# [Julia 1.0](http://julialang.org/), 30 bytes
```
-x=x>sort(x) ? -x[1:2:end] : x
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X7fCtsKuOL@oRKNCU8FeQbci2tDKyCo1LyVWwUqh4n9BUWZeSU6ehm60oY6RjrGOSawmF7IYRBRIo4kb6xjFav4HAA "Julia 1.0 – Try It Online")
Takes every second element of the array if not sorted.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 49 bytes
```
l=input('');while(~issorted(l))l=l(1:2:end);end;l
```
[Try it online!](https://tio.run/##y08uSSxL/f8/xzYzr6C0RENdXdO6PCMzJ1WjLrO4OL@oJDVFI0dTM8c2R8PQysgqNS9F0xpIWOf8/x9tqGCkYKxgpmCuYBQLAA "Octave – Try It Online") This was a journey where more boring is better. Note the two much more interesting entries below:
### 50 bytes
```
function l=q(l)if(~issorted(l))l=q(l(1:2:end));end
```
[Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP08hx7ZQI0czM02jLrO4OL@oJDUFyNUEi2oYWhlZpealaGpaA8n/QMzFVagRbapgqGAYq/kfAA "Octave – Try It Online") Instead of the uninteresting imperative solution, we can do a recursive solution, for only one additional byte.
### 53 bytes
```
f(f=@(g)@(l){l,@()g(g)(l(1:2:end))}{2-issorted(l)}())
```
[Try it online!](https://tio.run/##y08uSSxL/V9oq6en9z9NI83WQSNd00EjR7M6R8dBQzMdyNPI0TC0MrJKzUvR1KytNtLNLC7OLypJTQEqqtXQ1PxfqBFtqGCkYKxgomAaq/kfAA "Octave – Try It Online") Yep. A recursive anonymous function, thanks to @ceilingcat's [brilliant answer](https://codegolf.stackexchange.com/a/164483/32352) on my [tips](/questions/tagged/tips "show questions tagged 'tips'") question. An anonymous function that returns a recursive anonymous function by defining itself in its argument list. I like anonymous functions. Mmmmm.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~22~~ 20 bytes
**Solution:**
```
{(*2 0N#x;x)x~x@<x}/
```
[Try it online!](https://tio.run/##y9bNz/7/v1pDy0jBwE@5wrpCs6KuwsGmolbfUsEQBP//BwA "K (oK) – Try It Online")
Iterate over the input until it's sorted... if it's not sorted take first n/2 items.
```
{(*2 0N#x;x)x~x@<x}/ / the solution
{ }/ / lambda that iterates
<x / indices that sort x ascending (<)
x@ / apply (@) these indices back to x
x~ / matches (~) x? returns 0 or 1
( ; ) / 2-item list which we index into
x / original input (ie if list was sorted)
#x / reshape (#) x
2 0N / as 2 rows
* / take the first one
```
**Edits:**
* **-2** bytes thanks to ngn
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
tv`1L)ttS-a
```
[Try it online!](https://tio.run/##y00syfn/v6QswdBHs6QkWDfx//9oQx0FIx0FYx0FEx0F01gA "MATL – Try It Online")
This works by removing every second item.
### Explanation
```
t % Take a row vector as input (implicit). Duplicate
v % Vertically concatenate the two copies of the row vector. When read with
% linear indexing (down, then across), this effectively repeats each entry
` % Do...while
1L) % Keep only odd-indexed entries (1-based, linear indexing)
t % Duplicate. This will leave a copy for the next iteration
tS % Duplicate, sort
-a % True if the two arrays differ in any entry
% End (implicit). A new iteration starts if the top of the stack is true
% Display (implicit). Prints the array that is left on the stack
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 102 bytes
```
n->{for(;n.stream().reduce((1<<31)+0d,(a,b)->a==.5|b<a?.5:b)==.5;n=n.subList(0,n.size()/2));return n;}
```
There's already a C# answer, so I decided to try my hand on a Java answer.
[Try it online!](https://tio.run/##tZPPb8IgFMfv/hUcIQNm1UY3WpclOzovHpcdaMEFV6kB6uJc//butWq2LNnNkgfh1/t@3nuEjdxLtlHvTV5I79GzNPY4QMjYoN1a5hot2yVCG7jHq2AKvjA@JE9llRV6jnL8z8GCCPCrBzD4IIPJ0RJZlDaWzY/r0mFhuQ9Oyy0m3GlV5RrjKEnGEbkZKoolzQibyzTl8VeWyAce32ekXQmbgmeVtTA8pDA3nxqT2xEhwulQOYusqBvRgncQCoDP/H1pFNpCfngVnLFvL69IklNyq4MPesvLKvAdHIXCYstzbPXHr7wfnZOHDvtnz3Ppu/1I0ZGiY0UnisaKQBPXl590hB7kQXh2fdWZoizqJdi4Kwfo9yA/7orc2dW148sbjnoJnUXwf9rO7hQFY7OuSGyq6LQn2pky/eGegBdaPaibbw "Java (JDK) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes
*1 byte saved thanks to Zgarb*
```
ΩΛ<Ċ2
```
[Try it online!](https://tio.run/##yygtzv7//9zKc7NtjnQZ/f//P9pQx0jHRMdYxzQWAA "Husk – Try It Online")
### Explanation
```
ΩΛ<Ċ2
Ω Repeat until
Λ< all adjacent pairs are sorted (which means the list is sorted)
Ċ2 drop every second element from the list
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 103 bytes
I can't comment, but I improved the version from movatica by reducing the includes, and using auto.
-2 Bytes: ceilingcat
-2 Bytes: ASCII-only
```
#include<regex>
auto f(auto l){while(!std::is_sorted(l.begin(),l.end()))l.resize(l.size()/2);return l;}
```
[Try it online!](https://tio.run/##RY5BTsMwEEXX9SmGIiRbcoMoohVJyTW6QULBHqeWpnZkOyEiytVJTViw@iPNn/dGdd2uVWpZ7q1T1Gs8BWxxrFnTJw@Gr0Fi@rpYQn4Xky5LGz@iDwk1p@ITW@u4kFSg01wIQUXAaL8x79YQj3tRBUx9cEDV/O9RmWV9zZh1Ca7NLwUmtlmFA7xl9yobUCUfTrlUT08S9hKeJbxKeJFwkHCcRcU2xgf4@3SEEobMgS7kC8O3D/rdbSWMooKZzcuPMtS0cdkZ5Z3CLuXx3BDdAA "C++ (gcc) – Try It Online")
[Answer]
# [Crystal](https://crystal-lang.org/), ~~59~~ 50 bytes
With `Array#sort` (**~~59~~ 50 bytes**):
```
def f(a);while a!=a.sort;a.pop a.size//2;end;a;end
```
[Try it online!](https://tio.run/##Sy6qLC5JzPn/PyU1TSFNI1HTujwjMydVIVHRNlGvOL@oxDpRryC/QAHIyaxK1dc3sk7NS7FOBJH/CxTSFKINdRSMdBSMY7nAPBMwzxBCmQJZYIZJ7H8A "Crystal – Try It Online")
Without `Array#sort` (**~~102~~ 93 bytes**):
```
def f(a);while a.map_with_index{|e,i|e>a.fetch i+1,Int32::MAX}.any?;a.pop a.size//2;end;a;end
```
[Try it online!](https://tio.run/##Sy6qLC5JzPn/PyU1TSFNI1HTujwjMydVIVEvN7EgvjyzJCM@My8ltaK6JlUnsybVLlEvLbUkOUMhU9tQxzOvxNjIysrXMaJWLzGv0t46Ua8gvwCotTizKlVf38g6NS/FOhFE/i9QSFOINtRRMNJRMI7lAvNMwDxDCGUKZIEZJrH/AQ "Crystal – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
£=ëÃæÈeXñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=oz3rw%2bbIZVjx&input=WzEgMiA0IDMgNV0)
```
£=ëÃæÈeXñ :Implicit input of array U
£ :Map
= : Reassign to U
ë : Every second element, starting with the first
à :End map
æ :Get the first element that returns true
È :When passed through the following function as X
e : Test for equality with
Xñ : X sorted
```
[Answer]
# [VDM-SL](https://raw.githubusercontent.com/overturetool/documentation/master/documentation/VDM10LangMan/VDM10_lang_man.pdf), 99 bytes
```
f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0])
```
Never submitted in vdm before, so not certain on language specific rules. So I've submitted as a function definition which takes a `seq of int` and returns a `seq of int`
A full program to run might look like this:
```
functions
f:seq of int +>seq of int
f(i)==if forall x in set inds i&x=1or i(x-1)<=i(x) then i else f([i(y)|y in set inds i&y mod 2=0])
```
[Answer]
# Pyth, 10 bytes
```
.W!SIHhc2Z
```
Try it online [here](https://pyth.herokuapp.com/?code=.W%21SIHhc2Z&input=%5B1%2C2%2C4%2C3%2C5%5D&debug=0). This removes the second half on each iteration, rounding down. To change it to remove the first half, rounding up, change the `h` to `e`.
```
.W!SIHhc2ZQ Q=eval(input())
Trailing Q inferred
!SIH Condition function - input variable is H
SIH Is H invariant under sorting?
! Logical not
hc2Z Iteration function - input variable is Z
c2Z Split Z into 2 halves, breaking ties to the left
h Take the first half
.W Q With initial value Q, execute iteration function while condition function is true
```
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~139~~ ~~137~~ 116 bytes
*-2 bytes thanx to ceilingcat, -21 bytes thanx to PeterZuger*
```
#include<regex>
auto f(std::vector<int>l){while(!std::is_sorted(l.begin(),l.end()))l.resize(-~l.size()/2);return l;}
```
Resize the vector to its first half until it's sorted.
[Try it online!](https://tio.run/##RY5hS8MwGIQ/L7/i3BDyQlZxQ8V29pcMZCZvayAmJU2rWOpf77J@8dvB3T13uuv2rdbLsrNeu8HwKXLLP7W4DCmgkX0yZTmyTiGerE@1o@n70zqWd6tj@/c@xMRGuuKDW@slKVewN5KIXBG5t78s93@uWAU9HKiKnIbo4ar5f1Rnmg21EHkDX5cbB5PYrCdGvOUj06PCQeGo8KrwpPCs8DJTJTZNiJBrkFFizD10MWMaub03Z79VYKowi3m5Ag "C++ (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 33 bytes
```
-a=issorted(a) ? a : -a[1:end÷2]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzfRNrO4OL@oJDVFI1FTwV4hUcFKQTcx2tAqNS/l8Haj2P8OxRn55Qq60YY6RjomOsY6prFcCCEFIx0FYx0FEyCJLGwEVAfCJjqmOmY65joWQGgJZBka6RgZgoRNkKQQGkHGG0I1mkPkY/8DAA "Julia 1.0 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΩS=Oo←½
```
[Try it online!](https://tio.run/##yygtzv7//9zKYFv//EdtEw7t/f//f7ShjpGOsY6JjnEsAA "Husk – Try It Online")
removes last half.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
m⁻Ṣ$¿2
```
[Try it online!](https://tio.run/##y0rNyan8/z/3UePuhzsXqRzab/T/cPujpjX//0cb6hjpGOuY6JjG6ijAOcaxAA "Jelly – Try It Online")
Very similar to [Erik](https://codegolf.stackexchange.com/a/182256/66833)'s existing answer, but I came up with this independently, and Erik's no longer active.
## How it works
```
m⁻Ṣ$¿2 - Main link. Takes a list L on the left
¿ - Loop while the condition is false, updating L each time:
$ - Condition:
Ṣ - L sorted
⁻ - L ≠ L sorted
m 2 - Body: Take every second element of L
```
] |
[Question]
[
*99* (pronounced "ninety-nine") is a brand new [Esoteric programming language](http://esolangs.org/wiki/Main_Page) (not to be confused with [99](http://esolangs.org/wiki/99_(Joke_language)), note the italics). Your task in this challenge is to write an interpreter for *99* that is as short as possible. The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to the submission posted first.
Since this question is a bit more in depth than usual, and I'm eager to see good answers, I'll be awarding a 250 rep bounty to my favorite answer (not necessarily the winner).
# *99* Spec
*99* is an [imperative](http://en.wikipedia.org/wiki/Imperative_programming) language. Each line in a *99* program is a single [statement](http://en.wikipedia.org/wiki/Statement_%28computer_science%29), and during execution, the instruction pointer starts at the top line and goes through each of the subsequent lines in order, executing them along the way. The program ends when the last line has been executed. [Goto](http://en.wikipedia.org/wiki/Goto) statements may reroute the path of the instruction pointer.
Newline, space, and `9` are the only three characters that matter in a *99* program. All other characters are completely ignored. Additionally, trailing spaces on each line are ignored, and multiple spaces in a row are read as one space. ("Newline" refers to any common [line break encoding](http://en.wikipedia.org/wiki/Newline#Representations). It doesn't matter which one your interpreter uses.)
So this program:
```
9 BLAH 99 9a9bb9c9
9 this line and the next have 6 trailing spaces 9
```
Is identical to this program:
```
9 99 9999
9 9
```
## Variables
Variables in *99* all have names that are one or more `9`'s strung together (`9+` in regex). For example, `9`, `99`, and `9999999999` are all distinct variables. Naturally, there are infinitely many (barring memory limitations).
The value of each variable is a signed, [arbitrary precision](http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) integer. By default, each variable is assigned to its own numeric representation. So unless it has been reassigned, the value of the variable `9` is the number 9, and the value of the variable `99` is the number 99, and so on. You could think of it as treating the variables as plain numbers until they are explicitly assigned.
**I will use `V` to refer to an arbitrary variable name below.
Each instance of `V` could be replaced with `9`, `99`, `999`, `9999`, etc.**
## Statements
There are five different statement types in *99*. Each line in a *99* program contains exactly one statement.
The syntax described here assumes all extraneous characters have been removed, all trailing spaces have been removed, and all sequences of multiple spaces have been replaced with single spaces.
**1. No Operation**
```
```
An empty line is a [no-op](http://en.wikipedia.org/wiki/NOP). It does nothing (besides incrementing the instruction pointer).
**2. Output**
```
V
```
A single variable `V` on a line prints that variable to stdout.
If `V` has an odd number of `9`'s (`9`, `999`, etc.) then the integer value of `V` divided by 9 will be printed (in decimal).
If `V` has an even number of `9`'s (`99`, `9999`, etc.) then the [ASCII](http://www.asciitable.com/) character with code `V` divided by 9, mod 128 will be printed. (That's `(V / 9) % 128`, a value from 0 to 127.)
*Example*: The program
```
9
9999
```
would print `1W`. The first line prints `1` because 9/9 is 1. The second line prints `W` because 9999/9 is 1111, and 1111 mod 128 is 87, and 87 is the character code for `W`.
Note that line breaks are not printed between output tokens. `\n` needs to be explicitly printed for a line break.
**3. Input**
```
V
```
A single variable `V` on a line **with a leading space** takes input from stdin and stores it in that variable.
If `V` has an odd number of `9`'s then the user may type in any signed integer, and `V` will be set to 9 times that value.
If `V` has an even number of `9`'s then the user may type in any ASCII character, and `V` will be set to 9 times its character code.
*Example*: Given `-57` and `A` as input, this program
```
9
9
99
99
```
would output `-57A`. Internally, the variable `9` would have the value -513, and `99` would have the value 585.
Your interpreter may assume that the inputs are always syntactically valid.
**4. Assignment**
This statement can be arbitrarily long. It is two or more variables on a line, separated by spaces:
```
V1 V2 V3 V4 V5 ...
```
This assigns `V1` to the sum of all the `V`'s with even indices, minus the sum of the `V`'s with odd indices (excluding `V1`). Assignments are by value, not by reference.
It could be translated in most languages as `V1 = V2 - V3 + V4 - V5 + ...`.
So, if there are only two variables, it's normal assignment:
`V1 V2` → `V1 = V2`
If there are three, then it's subtraction:
`V1 V2 V3` → `V1 = V2 - V3`
And the `+`/`-` sign keeps switching back and forth with each additional variable:
`V1 V2 V3 V4` → `V1 = V2 - V3 + V4`
*Example*: This program would output `1110123`:
```
999 Prints triple-nine divided by nine (111).
999 9 9 Assigns triple-nine to zero (nine minus nine).
999 Prints triple-nine divided by nine (0)
9 999 9 Assigns single-nine to negative nine (zero minus nine).
999 999 9 Adds nine to triple-nine (really subtracts negative nine).
999 Prints triple-nine divided by nine (1).
999 999 9 Adds nine to triple-nine (really subtracts negative nine).
999 Prints triple-nine divided by nine (2).
999 999 9 Adds nine to triple-nine (really subtracts negative nine).
999 Prints triple-nine divided by nine (3).
```
**5. Goto (jump if all zero)**
This statement can also be arbitrarily long. It is two or more variables on a line, separated by spaces, **with a leading space**:
```
V1 V2 V3 V4 V5 ...
```
If some of the values besides `V1` are non-zero, then this behaves just like a no-op. The instruction pointer is moved to the next line as usual.
If *all* of the values besides `V1` *are* zero, then the instruction pointer is moved to line number `V1`. The lines are zero-indexed, so if `V1` is zero, then the pointer moves to the top line. The program terminates (normally, without error) if `V1` is negative or is larger than the highest possible index (number of lines minus one).
**Note that `V1` was not divided by 9 here. And since it's impossible to have a variable be a value that's not a multiple of 9, only line numbers that are multiples of 9 can be jumped to.**
*Examples:*
This program will print `1`'s forever:
```
9 Prints single-nine divided by nine (always 1).
99 9 9 Assigns double-nine to zero.
99 99 Jumps to line zero (top line) if double-nine is zero.
```
This program
```
99999999 Print G.
999 99 Set triple-nine to ninety-nine.
9999999999 9999999999 9999999999 99 99 9 9 999 999 Set 10-nine to zero.
99999999999 9999999999 Set 11-nine to zero.
999 Print triple-nine's value divided by nine. (This is the ninth line.)
99999999 Print G.
999 999 9 Subtract nine from triple-nine.
99999 999 Jump to line 5-nines if triple-nine is zero (ends program).
9 99999999999 9999999999 Jump to line nine if 10-nine and 11-nine are zero (always jumps).
```
will output the numbers 11 to 1, in decreasing order, surrounded by `G`'s:
```
G11G10G9G8G7G6G5G4G3G2G1G
```
## Additional Details
The ideal interpreter will run from the command line with the *99* program file name as an argument. The I/O will also be done on the fly in the command line.
You may, however, just write an interpreter function that takes in the program as a string as well as a list of the input tokens (e.g. `["-57", "A"]`). The function should print or return the output string.
Slightly different ways of running the interpreter and handling I/O are fine if these options are impossible in your language.
---
**Bonus:** Write something cool in *99* and I'll gladly put it in this post as an example.
* [Here's a Pastebin](http://pastebin.com/nczmzkFs) of a neat "99 Bottles of Beer" program from [Mac's answer](https://codegolf.stackexchange.com/a/47593/26997).
---
Hope you enjoyed [my 99th](https://codegolf.stackexchange.com/users/26997/calvins-hobbies?tab=questions&sort=newest) challenge! :D
[Answer]
# Python 3, 421 414 410 404 388 395 401 bytes
### Golfed:
```
import sys,re
v,i,c,g,L={},0,[re.sub('( ?)[^9]+','\\1',l).rstrip().split(' ')for l in open(sys.argv[1])],lambda i:v.get(i,int(i)//9),len
while-1<i<L(c):
d=c[i];l=L(d);e,*f=d;i+=1
if l>1:
x,*y=f
if e:w=list(map(g,f));v[e]=sum(w[::2])-sum(w[1::2])
elif l==2:j=input();v[x]=int(j)if L(x)%2 else ord(j)
elif~-any(g(j)for j in y):i=g(x)*9
elif e:w=g(e);print(w if L(e)%2 else chr(w%128),end='')
```
### Ungolfed:
```
import sys, re
# Intialise variable table.
vars_ = {}
get_var = lambda i: vars_.get(i, int(i)//9)
# Parse commands.
commands=[re.sub('( ?)[^9]+','\\1',l).rstrip().split(' ') for l in open(sys.argv[1])]
# Run until the current instruction index is out of bounds.
index=0
while 0 <= index < len(commands):
# Get the current command and increment the index.
command = commands[index]
l = len(command)
first = command[0]
index += 1
if l > 1:
# Handle the "assignment" command.
if first:
operands = [get_var(i) for i in command[1:]]
vars_[first] = sum(operands[0::2]) - sum(operands[1::2])
# Handle the "input" command.
elif l==2:
inp = input()
vars_[command[1]] = int(inp) if len(command[1]) % 2 else ord(inp)
# Handle the "goto" command.
elif not any(get_var(i) for i in command[2:]):
index = get_var(command[1]) * 9
# Handle the "output" command.
elif first:
val = get_var(first)
print(val if len(first) % 2 else chr(val % 128),end='')
```
Pretty much just a literal implementation of the spec, golfed down as far as I can get it.
Run from the command line by supplying a 99 source-code file as the sole argument (e.g. the last example from the OP):
```
> python3 ninetynine.py countdown.txt
G11G10G9G8G7G6G5G4G3G2G1G
>
```
As an added bonus, here's a (rather poor) implementation of "99 bottles" in *99*: <http://pastebin.com/nczmzkFs>
[Answer]
# Common Lisp, ~~1180~~ ~~857~~ ~~837~~ 836 bytes
I know this is not going to win, but I had fun golfing this one. I managed to remove 343 bytes, which is more than two *99* interpreters written in CJam.
Also, quite amusingly, the more I try to compress it, the more I am persuaded that for Common Lisp, it is *shorter* to compile the code than to try interpreting it on the fly.
```
(defmacro g(g &aux a(~ -1)> d x q(m 0)r v(n t)c(w 0)? u z)(flet((w(n p)(intern(format()"~a~a"p n))))(#1=tagbody %(case(setf c(ignore-errors(elt g(incf ~))))(#\ #2=(when(> w 0)(pushnew w v)(if u()(setq ?(oddp w)))(#5=push(w w'V)u)(setf w 0))(setf z t))(#\9(incf w)(setf >(or >(and n z))z()n()))((#\Newline())#2#(#5#(when u(setf u(reverse u)a(pop u))(if >(if u`(when(every'zerop(list,@u))(setf @,a)(go ^))`(setf,a,(if ?'(read)'(char-code(read-char)))))(if u`(setf,a,(do(p m)((not u)`(-(+,@p),@m))(#5#(pop u)p)(#5#(if u(pop u)0)m)))`(princ,(if ? a`(code-char(mod,a 128)))))))r)(incf m)(setf ?()u()z()>()n t)))(if c(go %))$(decf m)(setq d(pop r))(if d(#5# d x))(when(=(mod m 9)0)(#5#(w #3=(/ m 9)'L)x)(#5#`(,#3#(go,(w #3#'L)))q))(if(>= m 0)(go $)))`(let(@,@(mapcar(lambda(n)`(,(w n'V),(/(1-(expt 10 n))9)))v))(#1#,@x(go >)^(case @,@q)>))))
```
* lexical analysis and code generation are interleaved: I do not store the internal representation, but process directly each line.
* there is a single `tagbody` to perform 2 loops:
```
(... (tagbody % ... (go %) $ ... (go $)) result)
```
* local variables are declared in `&aux`
* don't generate a closure, but directly the interpreted code
* etc.
# Ungolfed, commented
```
(defmacro parse-99
(string &aux
(~ -1) ; current position in string
a ; first variable in a line
> ; does current line starts with a leading space?
d ; holds a statement during code generation
x ; all statements (labels + expressions)
q ; all generated case statements
(m 0) ; count program lines (first increases, then decreases)
r ; list of parsed expressions (without labels)
v ; set of variables in program, as integers: 999 is 3
(n t) ; are we in a new line without having read a variable?
c ; current char in string
(w 0) ; currently parsed variable, as integer
? ; is first variable odd?
u ; list of variables in current line, as integers
z) ; is the last read token a space?
(flet((w(n p)
;; produce symbols for 99 variables
;; e.g. (10 'V) => 'V10
;; (4 'L) => 'L4
(intern(format()"~a~a"p n))))
(tagbody
parse
(case (setf c
;; read current char in string,
;; which can be NIL if out-of-bounds
(ignore-errors(aref string (incf ~))))
;; Space character
(#\Space
#2=(when(> w 0)
(pushnew w v) ; we were parsing a variable, add it to "v"
(if u()(setq ?(oddp w))) ; if stack is empty, this is the first variable, determine if odd
(push(w w'V)u) ; add to stack of statement variable
(setf w 0)) ; reset w for next variable
;; Space can either be significant (beginning of line,
;; preceding a variable), or not. We don't know yet.
(setf z t))
;; Nine
(#\9
(incf w) ; increment count of nines
(setf >(or >(and n z)) ; there is an indent if we were
; starting a newline and reading a
; space up to this variable (or if we
; already know that there is an
; indent in current line).
;; reset z and n
z()n()))
;; Newline, or end of string
((#\Newline())
#2# ;; COPY-PASTE the above (when(> w 0)...) statement,
;; which adds previously read variable if necessary.
;; We can now convert the currently read line.
;; We push either NIL or a statement into variable R.
(push(when u
(setf u (reverse u) ; we pushed, we must reverse
a (pop u)) ; a is the first element, u is popped
(if >
;; STARTS WITH LEADING SPACE
(if u
;; JUMP
`(when(every'zerop(list,@u))(setf @,a)(go ^))
;; READ
`(setf,a,(if ?'(read)'(char-code(read-char)))))
;; STARTS WITH VARIABLE
(if u
;; ARITHMETIC
`(setf,a,(do(p m) ; declare p (plus) and m (minus) lists
;; stopping condition: u is empty
((not u)
;; returned value: (- (+ ....) ....)
`(-(+,@p),@m))
;; alternatively push
;; variables in p and m, while
;; popping u
(push(pop u)p)
;; first pop must succeed, but
;; not necessarly the second
;; one. using a zero when u
;; is empty covers a lot of
;; corner cases.
(push(if u (pop u) 0) m)))
;; PRINT
`(princ,(if ? a`(code-char(mod,a 128)))))))
r)
;; increase line count
(incf m)
;; reset intermediate variables
(setf ?()u()z()>()n t)))
;; loop until end of string
(if c (go parse))
build
;;; Now, we can add labels in generated code, for jumps
;; decrease line count M, which guards our second loop
(decf m)
;; Take generated statement from R
(setq d(pop r))
;; we pop from R and push in X, which means X will eventually
;; be in the correct sequence order. Here, we can safely
;; discard NIL statements.
;; We first push the expression, and THEN the label, so that
;; the label ends up being BEFORE the corresponding statement.
(if d(push d x))
;; We can only jump into lines multiple of 9
(when (=(mod m 9)0)
;; Push label
(push(w #3=(/ m 9)'L)x)
;; Also, build a case statement for the jump table (e.g. 2(go L2))
(push`(,#3#(go,(w #3#'L)))q))
;; loop
(if(>= m 0)(go build)))
;; Finally, return the code
`(let(@ ; target of a jump instruction
;; other variables: V3 represents 999 and has a default value of 111
,@(mapcar(lambda(n)`(,(w n'V),(/(1-(expt 10 n))9)))v))
;; build a tagbody, inject statements from X and case statements from Q
;; label ^ points to jump table : we go to ^ each time there is a JUMP
;; label > is the end of program
;; note that if the case does not match any authorized target
;; address, we simply end the programs.
(tagbody,@x(go >)^(case @,@q)>))))
```
We use standard input/output during evaluation, meaning we use standard `read` and `princ` functions. Hence, the resulting code can be made executable on the command-line, as show below.
Inputs are not completely well sanitized when running *99* programs: it is assumed that the user knows what kind of values are expected.
The only possible *runtime* overhead can occur when jumping, since we must evaluate the value of a variable and match that value to a label. Except that, the interpreter shall be quite efficient.
Based on the clever [obseravtion from Mac](https://codegolf.stackexchange.com/questions/47588/write-an-interpreter-for-99#comment111741_47593) that we don't need to divide and multiply by 9 each time, the current version manages to **never** divides nor multiply by 9 during execution.
# Example
If we replace `defmacro` by `defun`, we see the generated code. For example:
```
(g
"99999999 Print G.
999 99 Set triple-nine to ninety-nine.
9999999999 9999999999 9999999999 99 99 9 9 999 999 Set 10-nine to zero.
99999999999 9999999999 Set 11-nine to zero.
999 Print triple-nine's value divided by nine. (This is the ninth line.)
99999999 Print G.
999 999 9 Subtract nine from triple-nine.
99999 999 Jump to line 5-nines if triple-nine is zero (endsprogram).
9 99999999999 9999999999 Jump to line nine if 10-nine and 11-nine are zero (alwa
")
```
Here is the resulting code:
```
(LET (@
(V5 11111)
(V11 11111111111)
(V1 1)
(V10 1111111111)
(V2 11)
(V3 111)
(V8 11111111))
(TAGBODY
L0
(PRINC (CODE-CHAR (MOD V8 128)))
(SETF V3 (- (+ V2) 0))
(SETF V10 (- (+ V3 V1 V2 V10) V3 V1 V2 V10))
(SETF V11 (- (+ V10) 0))
L1
(PRINC V3)
(PRINC (CODE-CHAR (MOD V8 128)))
(SETF V3 (- (+ V3) V1))
(WHEN (EVERY 'ZEROP (LIST V3)) (SETF @ V5) (GO ^))
(WHEN (EVERY 'ZEROP (LIST V11 V10)) (SETF @ V1) (GO ^))
(GO >)
^
(CASE @ (0 (GO L0)) (1 (GO L1)))
>))
```
When executed, prints "G11G10G9G8G7G6G5G4G3G2G1G"
# Command-line
We can build an executable by dumping a core and specifying the `toplevel` function. Define a file named `boot.lisp` where you put the `defmacro`, and then write the following:
```
(defun main()(parse-99 <PROGRAM>))
(save-lisp-and-die "test-99" :executable t :toplevel #'main)
```
Running `sbcl --load boot.lisp` gives the following output:
```
$ sbcl --load boot.lisp
This is SBCL 1.2.8.32-18c2392, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
[undoing binding stack and other enclosing state... done]
[saving current Lisp image into test-99:
writing 5824 bytes from the read-only space at 0x20000000
writing 3120 bytes from the static space at 0x20100000
writing 55771136 bytes from the dynamic space at 0x1000000000
done]
```
Then, running the compiled *99* program:
```
$ time ./test-99
G11G10G9G8G7G6G5G4G3G2G1G
real 0m0.009s
user 0m0.008s
sys 0m0.000s
```
# 99 bottles
If you are interested, here is the compiled code for the 99 bottles program written in [Mac's answer](https://codegolf.stackexchange.com/a/47593/903): <http://pastebin.com/ZXe839CZ> (this is the old version where we have `jmp` and `end` labels, a surrounding lambda and prettier arithmetic).
Here is an execution with the new version, to prove it still works: <http://pastebin.com/raw.php?i=h73q58FN>
[Answer]
# CJam, 157 bytes
```
{:I;_N" 9"+--N/:P:,$W=){1a*Ab}%:V;{PT):T(=:LS%_{LS#\:,_,({(\{V=}%@{V-1@{2$*+0@-\}*\;t:V;}{:|T@V=9*?:T;}?}{~\{_V=\1&!{128%c}*o}{VIW):W=it:V;}?}?}R?Tg)TP,<*}g}
```
Try it online:
* [I/O Test](http://cjam.aditsu.net/#code=%22%209%0A9%0A%2099%0A99%22%0A%5B-57%20'A%5D%0A%7B%3AI%3B_N%22%209%22%2B--N%2F%3AP%3A%2C%24W%3D)%7B1a*Ab%7D%25%3AV%3B%7BPT)%3AT(%3D%3ALS%25_%7BLS%23%5C%3A%2C_%2C(%7B(%5C%7BV%3D%7D%25%40%7BV-1%40%7B2%24*%2B0%40-%5C%7D*%5C%3Bt%3AV%3B%7D%7B%3A%7CT%40V%3D9*%3F%3AT%3B%7D%3F%7D%7B~%5C%7B_V%3D%5C1%26!%7B128%25c%7D*o%7D%7BVIW)%3AW%3Dit%3AV%3B%7D%3F%7D%3F%7DR%3FTg)TP%2C%3C*%7Dg%7D%0A~)
* [G11G10G9G8G7G6G5G4G3G2G1G](http://cjam.aditsu.net/#code=%2299999999%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Print%20G.%0A999%2099%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Set%20triple-nine%20to%20ninety-nine.%0A9999999999%209999999999%209999999999%2099%2099%209%209%20999%20999%20%20%20%20Set%2010-nine%20to%20zero.%0A99999999999%209999999999%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%20Set%2011-nine%20to%20zero.%0A%0A%0A%0A%0A%0A999%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Print%20triple-nine's%20value%20divided%20by%20nine.%20(This%20is%20the%20ninth%20line.)%0A99999999%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Print%20G.%0A999%20999%209%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Subtract%20nine%20from%20triple-nine.%0A%2099999%20999%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Jump%20to%20line%205-nines%20if%20triple-nine%20is%20zero%20(ends%20program).%0A%209%2099999999999%209999999999%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%20Jump%20to%20line%20nine%20if%2010-nine%20and%2011-nine%20are%20zero%20(always%20jumps).%22%0A%5B%5D%0A%7B%3AI%3B_N%22%209%22%2B--N%2F%3AP%3A%2C%24W%3D)%7B1a*Ab%7D%25%3AV%3B%7BPT)%3AT(%3D%3ALS%25_%7BLS%23%5C%3A%2C_%2C(%7B(%5C%7BV%3D%7D%25%40%7BV-1%40%7B2%24*%2B0%40-%5C%7D*%5C%3Bt%3AV%3B%7D%7B%3A%7CT%40V%3D9*%3F%3AT%3B%7D%3F%7D%7B~%5C%7B_V%3D%5C1%26!%7B128%25c%7D*o%7D%7BVIW)%3AW%3Dit%3AV%3B%7D%3F%7D%3F%7DR%3FTg)TP%2C%3C*%7Dg%7D%0A~)
* [99 bottles of beer](http://pastebin.com/raw.php?i=qy51PppY) (this code is too long to fit in a URL, so copy the code and paste it into the [interpreter](http://cjam.aditsu.net/) manually)
### Explanation
Trying to format this with proper indentation and comments would probably take forever, so I'll just give an algorithmic summary.
The code is a block, CJam's analog to anonymous functions. The block expects the program string and list of inputs on the stack when executed.
Initialization consists of three steps. First, the input list is saved. Then, every character in the program that isn't meaningful is removed and the result is split into a list of lines and saved. Finally, the variable list is initialized. This list maps each variable, indexed by name length, to its value divided by 9 (a variable can never hold a value that's not a multiple of 9, and all operations except goto benefit from this change). The list is initialized up to the length of the longest line, which is an upper bound on the longest varaible name present. There's also a bit of implicit initialization due to initial variable values: the line number is 0 and the input index is -1.
The interpreter is implemented as one would expect: a loop that reads the next line, increments the line number, and executes the line while the line number points to an existing line. Line parsing first checks that the line isn't empty, then branches based on whether the arity is 1 or >1, then branches based on whether there was a leading space. These four branches emulate the four (excluding no-op) operations in a mostly straightforward manner, albeit agressively golfed like everything else. Perhaps one optimization of note is that, since a valid input sequence should always produce an element of type expected by the program, I omitted making separate cases for input based on the length of the variable name. It is simply assumed that the element read from the input list is of the expected type.
[Answer]
# TI-84 Basic (Calculator Script), 376 373 377 381 bytes
*If it runs on a TI-84 calculator, you'll be able to use it on a standardized test... so it's useful ;)*
Minimum operating system version - 2.53MP (MathPrint) due to the summation sigma
```
#Get input from STDIN
:Ans+":"->Str0
#Initialize instruction pointer
:1->I
#Initialize variable set
:DelVar L1999->dim(L1
#Strip out those pesky non-newline/space/9 characters
:For(J,1,length(Ans
:sub(Str0,J,1
:If not(inString(": 9",Ans
:sub(Str0,1,J-1)+sub(Str0,J+1,length(Str0)-J->Str0
:End
#Main interpreting loop
:While I<length(Str0
:sub(Str0,I+1,inString(Str0,":",I+1)-I-1->Str1
:DelVar A" "=sub(Ans,1,1->A
:inString(Str0,":",I+1->I
:If A
:sub(Str1,2,length(Str1)-1->Str1
:End
:length(Str1->L
#0 is Output, 1 is Input, 2 is Assignment, 3 is Goto
:2A+inString(Str1," ->B
:If not(Ans
:Disp L1(L
:If Ans=1
:Then
:Input C
:C->L1(L
:End
#Get those delimited variables
:If B>1
:Then
:"{"+Str1->Str2
:While inString(Ans,"
:inString(Ans,"
:sub(Str2,1,Ans-1)+sub(Str2,Ans+1,length(Str2)-Ans->Str2
:End
:log(expr(Ans)+1->L2
:End
:If B=2
#Gotta expand that -+ pattern
:Ans(2->L1(Ans(1
;Love that summation Σ
:If B=3 and Σ(L2(K),K,2,dim(L2
:Then
:DelVar IFor(K,0,9L2(1
:inString(Str0,":",I+1->I
:End
:End
```
P.S. ASCII guidelines could not be followed exactly, but in TI-Basic `:` is a newline. Thus, all the actual newlines in the code mean that the `:` or `#` at the beginning of each line are not required. The beginning tokens `:` and `#` just differentiate between comments and code.
**Original Hex Dump (376 Bytes)**
```
49 3f bb 54 5d 20 39 39 39 04 b5 5d 20 3f 72 04 aa 09 3f d3 4a 2b 31 2b bb 2b 72 3f bb 0c aa 09 2b 4a 2b 31 3f ce b8 bb 0f 2a 3e 29 39 2a 2b 72 3f bb 0c aa 09 2b 31 2b 4a 71 31 11 70 bb 0c aa 09 2b 4a 70 31 2b 72 71 4a 04 aa 09 3f d4 3f d1 49 6b bb 2b aa 09 3f bb 0c aa 09 2b 49 70 31 2b bb 0f aa 09 2b 2a 3e 2a 2b 49 70 31 11 71 49 71 31 04 aa 20 3f bb 54 41 2a 29 2a 6a bb 0c 72 2b 31 2b 31 04 41 3f bb 0f aa 09 2b 2a 3e 2a 2b 49 70 31 04 49 3f ce 41 3f bb 0c aa 20 2b 32 2b bb 2b aa 20 11 71 31 04 aa 20 3f d4 3f bb 2b aa 20 04 4c 3f 32 41 70 bb 0f aa 20 2b 2a 29 04 42 3f ce b8 72 3f de 5d 20 10 4c 11 83 39 3f ce 72 6a 31 3f cf 3f dc 43 3f 39 43 04 5d 20 10 4c 3f d4 3f ce 42 6c 31 3f cf 3f 2a 08 2a 70 aa 20 04 aa 01 3f d1 bb 0f 72 2b 2a 29 3f bb 0f 72 2b 2a 29 3f bb 0c aa 01 2b 31 2b 72 71 31 11 70 bb 0c aa 01 2b 72 70 31 2b bb 2b aa 01 11 71 72 04 aa 01 3f d4 3f c0 bb 2a 72 11 70 31 04 5d 01 3f d4 3f ce 42 6a 32 3f 72 10 32 04 5d 20 10 72 10 31 3f ce 42 6a 33 40 ef 33 5d 01 10 4b 11 2b 4b 2b 32 2b b5 5d 01 3f cf 3f bb 54 49 d3 4b 2b 30 2b 5d 01 10 31 3f bb 0f aa 09 2b 2a 3e 2a 2b 49 70 31 04 49 3f d4 3f d4 2e 76
```
**Edit #1** - Optimized 3 bytes using [Mac's observation](https://codegolf.stackexchange.com/questions/47588/write-an-interpreter-for-99#comment111741_47593)
**Edits #2 & #3** - Fixed bugs spotted by Runer112.
[Answer]
# C 426 ~~458 481 497~~
**Edit** Maybe I'm going too far, but this works with Visual C: removed stdio.h, using int instead of FILE\* for fopen and getc
**Edit 2** Reorder execution step, more clutter, 32 chars saved
```
B[99999],*r,*i[9999],V[999],v,w,m,n;unsigned p,s;
main(b,a)char*a[];{r=i[0]=B;m=fopen(a[1],"r");
do if(w=getc(m),n+=w==57,w<33){
if(n){for(v=1,b=n;--b;)v=v*10+1;V[n]=v;*r++=p?-n:n;b=n=0;};
w-32?(*r=p=0,b=i[++s]=++r):(p=b,b=0);}while(w>=0);
while(p<s)if(w=0,r=i[p++],v=*r++)
if(m=v>0,*r){for(;b=*r++;m=-m)w=w+m*V[b]|!m*V[b];m?V[v]=w:(p=w?p:9*V[-v]);
}else~v&1?!m?V[-v]=getchar():putchar(V[v]&127):m?printf("%d",V[v]):scanf("%d",V-v);
}
```
Stand alone console program, program name taken on command line and input/output via console.
Old style K&R, default type int for global vars and parameters. Assuming EOF defined as -1 (as it is in every C implementation I'm aware of)
Compiles with warnings with Visual Studio 2010 (Win32 console C++ project, compile as C)
Compiles on Ideone, but can't run as it needs a file.
First step, the source code is read and parsed, each line is stored as a sequence of integers based on the numbers of 9s. If there is a leading blank, the first number is negative. So: `9 BLAH 99 9a9bb9c9` ( `9 99 9999`) becomes `-1,2,4`
There is a shortcut - not so legal : all ascii codes less than ' ' are considered newlines.
In this step all the used variable are preinitialised.
The execution step follows the specifications, no frills, save storing numbers divided by 9.
**More readable** same code (I hope), spaces and newlines added
```
B[99999],*r,*i[9999],V[999],v,w,m,n;
unsigned p,s;
main(b,a)char*a[];
{
r=i[0]=B;
m=fopen(a[1],"r");
do if(w=getc(m),n+=w==57,w<33)
{
if(n){for(v=1,b=n;--b;)v=v*10+1;V[n]=v;*r++=p?-n:n;b=n=0;};
w-32?(*r=p=0,b=i[++s]=++r):(p=b,b=0);
}
while (w>=0);
while (p<s)
if (w = 0, r = i[p++], v = *r++)
if (m = v > 0, *r){
for(; b = *r++; m = -m)
w = w + m*V[b] | !m*V[b];
m ? V[v]=w : (p = w ? p : 9*V[-v]);
} else
~v & 1
? !m ? V[-v] = getchar() : putchar(V[v] & 127)
: m ? printf("%d", V[v]) : scanf("%d", V - v);
}
```
[Answer]
# Haskell, 550 bytes
```
import Data.List.Split
import System.Environment
a#b=takeWhile(/=a)b
(!)=map
main=do(f:_)<-getArgs;readFile f>>=e.(p!).lines
p l=(if ' '#l<'9'#l then[0]else[])++length!(wordsBy(/='9')l)
e l=(\x->div(10^x-1)9)%l where
_%[]=return()
v%([]:r)=v%r
v%([n]:r)=putStr(if odd n then show(v n)else[toEnum$v n`mod`128])>>v%r
v%([0,n]:r)=do i<-getLine;u n(if odd n then read i else fromEnum$head i)v%r
v%((0:n:m):r)|any(/=0)(v!m)=v%r|v n<0=v%[]|1<2=v%drop(9*v n)l
v%((n:m):r)=u n(sum$zipWith(*)(v!m)(cycle[1,-1]))v%r
u n i v= \x->if x==n then i else v x
```
Example run with the "countdown" program stored in the file `i.99`
```
$ ./99 i.99
G11G10G9G8G7G6G5G4G3G2G1G
```
Ungolfed version:
```
import Data.List.Split
import System.Environment
-- The main function takes the first command line argument as a file name,
-- reads the content, splits it into lines, parses each line and evaluates
-- the list of parsed lines.
main = do
(f:_)<-getArgs
readFile f >>= eval.map parse.lines
-- each line is coverted into a list of integers, which represent the number
-- of 9s (e.g. "999 99 9999" -> [3,2,4]). If there's a space before the first
-- 9, a 0 is put in front of the list (e.g. " 9 9 999" -> [0,1,1,3]).
parse l = (if takeWhile (/=' ') l < takeWhile (/='9') l then [0] else [])
++ map length (wordsBy(/='9') l)
-- The work is done by the helper function 'go', which takes two arguments
-- a) a functions which takes an integer i and returns the value of the
-- variable with i 9s (e.g: input: 4, output: value of 9999). To be
-- exact, the value divided by 9 is returned.
-- b) a list of lines to work on
-- 'eval' starts the process with a function that returns i 1s for every i and
-- the list of the parsed input. 'go' checks which statement has to be
-- executed for the next line and calls itself recursively
eval list = go (\x -> div (10^x-1) 9) list
where
go _ [] = return ()
go v ([]:r) = go v r
go v ([n]:r) = putStr (if odd n then show(v n) else [toEnum (v n`mod`128)]) >> go v r
go v ([0,n]:r) = do i<-getLine ; go (update n (if odd n then read i else fromEnum$head i) v) r
go v ((0:n:m):r)
| any (/=0) (map v m) = go v r
| v n < 0 = go v []
| otherwise = go v (drop (9*v n) list)
go v ((n:m):r) = go (update n (sum $ zipWith (*) (map v m) (cycle[1,-1])) v) r
-- updates a function for retrieving variable values.
-- n = position to update
-- i = new value
-- v = the function to update
update n i v = \x->if x==n then i else v x
```
[Answer]
# JavaScript (ES6) 340 ~~352~~
A function with 2 parameters
* program code as a multiline string
* input as an array
The third optional parameter (default 10k) is the max number of iterations - I don't like a program that run forever
[JSFiddle](http://jsfiddle.net/7gzyq3td/11/) To test
```
I=(c,i,k=1e5,
V=v=>v in V?V[v]:v/9 // variable getter with default initial value
)=>(c=>{
for(p=o='';--k&&p<c[L='length'];)
(v=(r=c[p++].split(' '))[S='shift']())? // no leading space
r[r.map(t=>w-=(m=-m)*V(t),w=0,m=1),0]?V[v]=w // Assign
:o+=v[L]&1?V(v):String.fromCharCode(V(v)&127) // Output
: // else, leading space
(v=r[S]())&&
(r[0]?r.some(t=>V(t))?0:p=9*V(v) // Goto
:(t=i[S](),V[v]=v[L]&1?t:t.charCodeAt()) // Input
)
})(c.replace(/ (?=[^9])|[^9\s]/g,'').split('\n')) // code cleaning
||o
```
[Answer]
# q/k, 490 469
```
M:mod;T:trim;R:read0;S:set;s:" "
f:(rtrim')(f:R -1!`$.z.x 0)inter\:"9 \n"
k)m:{@[x;&M[!#x;2];-:]}
b:{}
k)p:{1@$$[1=M[#x;2];(K x)%9;"c"$M[(K x)%9;128]];}
k)i:{S[(`$T x);$[1=M[#T x;2];9*"J"$R 0;*9*"i"$R 0]]}
k)K:{$[#!:a:`$x;.:a;"I"$x]}
k)v:{(S).(`$*:;+/m@K'1_)@\:T's\:x}
k)g:{$[&/0=C:K'c:1_J:s\:T x;n::-1+K@*J;|/~0=C;;(d<0)|(d:*C)<#f;exit 0]}
k)r:{`b`p`i`v`g@*&(&/x=s;q&1=c;(e~s)&1=C;(q:e~"9")&1<c:#s\:x;((e:*x)~s)&1<C:#s\:1_x)}
k)n:0;while[~n>#o:(r')f;(o n)f n;n+:1]
\\
```
.
```
$ q 99.q countdown.txt -q
G11G10G9G8G7G6G5G4G3G2G1G
```
The script is a mixture of q and k, so first up I define a few q keywords that I want to use multiple times in k functions. (basically #define macros)
```
M:mod;T:trim;R:read0;S:set
```
`f` reads the file passed into the program and strips out unnecessary characters
```
q)f
"99999999"
"999 99"
"9999999999 9999999999 9999999999 99 99 9 9 999 999"
"99999999999 9999999999"
""
""
""
""
""
"999"
"99999999"
"999 999 9"
" 99999 999"
" 9 99999999999 9999999999"
```
`m` takes a list/vector and multiples the odd indices by -1
```
q)m 1 2 3 4 5
1 -2 3 -4 5
```
`b` is just an empty function, used for the no-op lines
`p` is the print function.
`K` is a function that examines a variable. If the variable exists, it returns it, otherwise it just returns the literal.
```
//999 not defined, so just return 999
q)K "999"
999
//Set 999 to 9
q)v "999 9"
//K now returns 9
q)K "999"
9
```
`v` is the assignment function.
`g` is the goto function.
`r` takes a string and decides which operation needs to be applied.
And then finally, I just iterate through the `f` list of strings, with `n` as the iterator. The goto function will update `n` as necessary.
[Answer]
# Perl, ~~273 266 255 244~~ 238
Line breaks added for clarity.
```
open A,pop;
for(@c=<A>){
y/ 9//cd;s/ +/ /g;s/ $//;
$p="((99)+|9+)";$a='+';
s/^ $p$/$1='$2'?ord<>:<>/;
s/^$p$/print'$2'?chr$1%128:$1/;
s/^ $p /\$_=$1*011unless/&&y/ /|/;
s/ /=/;s/ /$a=-$a/ge;
s!9+!${x.$&}=$&/9;"\$x$&"!eg}
eval$c[$_++]until/-/|$_>@c
```
Program name taken on command line:
```
$ perl 99.pl 99beers.99
```
Each line of the program is converted into Perl code, for example:
```
print'$x99'?chr$x99999999%128:$x99999999
$x999=$x99
$x9999999999=$x9999999999-$x9999999999+$x99-$x99+$x9-$x9+$x999-$x999
$x99999999999=$x9999999999
print''?chr$x999%128:$x999
print'$x99'?chr$x99999999%128:$x99999999
$x999=$x999-$x9
$_=$x99999*011unless$x999
$_=$x9*011unless$x99999999999|$x9999999999
```
More details
```
open A,pop; # open the source file
for(@c=<A>){ # read all lines into @c and iterate over them
y/ 9//cd; # remove all but spaces and 9's
s/ +/ /g;s/ $//; # remove duplicate and trailing spaces
$p="((99)+|9+)";$a='+';
s/^ $p$/$1='$2'?ord<>:<>/; # convert input
s/^$p$/print'$2'?chr$1%128:$1/; # convert output
s/^ $p /\$_=$1*011unless/&&y/ /|/; # convert goto
s/ /=/;s/ /$a=-$a/ge; # convert assignment
s!9+!${x.$&}=$&/9;"\$x$&"!eg} # initialize and convert variables
eval$c[$_++]until/-/|$_>@c # run (program counter is in $_)
```
] |
[Question]
[
# Most Recent Leaderboard @ 2014-08-02 12:00
```
| Pos # | Author | Name | Language | Score | Win | Draw | Loss | Avg. Dec. Time |
+-------+----------------------+-------------------------+------------+-------+-------+-------+-------+----------------+
| 1st | Emil | Pony | Python2 | 064 | 064 | 000 | 005 | 0026.87 ms |
| 2nd | Roy van Rijn | Gazzr | Java | 062 | 062 | 001 | 006 | 0067.30 ms |
| 2nd | Emil | Dienstag | Python2 | 062 | 062 | 001 | 006 | 0022.19 ms |
| 4th | ovenror | TobiasFuenke | Python2 | 061 | 061 | 001 | 007 | 0026.89 ms |
| 5th | PhiNotPi | BayesianBot | Perl | 060 | 060 | 000 | 009 | 0009.27 ms |
| 6th | Claudiu | SuperMarkov | Python2 | 058 | 058 | 001 | 010 | 0026.77 ms |
| 7th | histocrat | Alternator | Ruby | 057 | 057 | 001 | 011 | 0038.53 ms |
| 8th | histocrat | LeonardShelby | Ruby | 053 | 053 | 000 | 016 | 0038.55 ms |
| 9th | Stretch Maniac | SmarterBot | Java | 051 | 051 | 002 | 016 | 0070.02 ms |
| 9th | Martin Büttner | Markov | Ruby | 051 | 051 | 003 | 015 | 0038.45 ms |
| 11th | histocrat | BartBot | Ruby | 049 | 049 | 001 | 019 | 0038.54 ms |
| 11th | kaine | ExcitingishBot | Java | 049 | 049 | 001 | 019 | 0065.87 ms |
| 13th | Thaylon | UniformBot | Ruby | 047 | 047 | 001 | 021 | 0038.61 ms |
| 14th | Carlos Martinez | EasyGame | Java | 046 | 046 | 002 | 021 | 0066.44 ms |
| 15th | Stretch Maniac | SmartBot | Java | 045 | 045 | 001 | 023 | 0068.65 ms |
| 16th | Docopoper | RoboticOboeBotOboeTuner | Python2 | 044 | 044 | 000 | 025 | 0156.55 ms |
| 17th | Qwix | Analyst | Java | 043 | 043 | 001 | 025 | 0069.06 ms |
| 18th | histocrat | Analogizer | Ruby | 042 | 042 | 000 | 027 | 0038.58 ms |
| 18th | Thaylon | Naan | Ruby | 042 | 042 | 004 | 023 | 0038.48 ms |
| 20th | Thaylon | NitPicker | Ruby | 041 | 041 | 000 | 028 | 0046.21 ms |
| 20th | bitpwner | AlgorithmBot | Python2 | 041 | 041 | 001 | 027 | 0025.34 ms |
| 22nd | histocrat | WereVulcan | Ruby | 040 | 040 | 003 | 026 | 0038.41 ms |
| 22nd | Ourous | QQ | Cobra | 040 | 040 | 003 | 026 | 0089.33 ms |
| 24th | Stranjyr | RelaxedBot | Python2 | 039 | 039 | 001 | 029 | 0025.40 ms |
| 25th | JoshDM | SelfLoathingBot | Java | 038 | 038 | 001 | 030 | 0068.75 ms |
| 25th | Ourous | Q | Cobra | 038 | 038 | 001 | 030 | 0094.04 ms |
| 25th | Ourous | DejaQ | Cobra | 038 | 038 | 001 | 030 | 0078.31 ms |
| 28th | Luis Mars | Botzinga | Java | 037 | 037 | 002 | 030 | 0066.36 ms |
| 29th | kaine | BoringBot | Java | 035 | 035 | 000 | 034 | 0066.16 ms |
| 29th | Docopoper | OboeBeater | Python2 | 035 | 035 | 002 | 032 | 0021.92 ms |
| 29th | Thaylon | NaanViolence | Ruby | 035 | 035 | 003 | 031 | 0038.46 ms |
| 32nd | Martin Büttner | SlowLizard | Ruby | 034 | 034 | 004 | 031 | 0038.32 ms |
| 33rd | Kyle Kanos | ViolentBot | Python3 | 033 | 033 | 001 | 035 | 0032.42 ms |
| 34th | HuddleWolf | HuddleWolfTheConqueror | .NET | 032 | 032 | 001 | 036 | 0029.86 ms |
| 34th | Milo | DogeBotv2 | Java | 032 | 032 | 000 | 037 | 0066.74 ms |
| 34th | Timmy | DynamicBot | Python3 | 032 | 032 | 001 | 036 | 0036.81 ms |
| 34th | mccannf | YAARBot | JS | 032 | 032 | 002 | 035 | 0100.12 ms |
| 38th | Stranjyr | ToddlerProof | Java | 031 | 031 | 010 | 028 | 0066.10 ms |
| 38th | NonFunctional User2..| IHaveNoIdeaWhatImDoing | Lisp | 031 | 031 | 002 | 036 | 0036.26 ms |
| 38th | john smith | RAMBOBot | PHP | 031 | 031 | 002 | 036 | 0014.53 ms |
| 41st | EoinC | SimpleRandomBot | .NET | 030 | 030 | 005 | 034 | 0015.68 ms |
| 41st | Martin Büttner | FairBot | Ruby | 030 | 030 | 006 | 033 | 0038.23 ms |
| 41st | Docopoper | OboeOboeBeater | Python2 | 030 | 030 | 006 | 033 | 0021.93 ms |
| 44th | undergroundmonorail | TheGamblersBrother | Python2 | 029 | 029 | 000 | 040 | 0025.55 ms |
| 45th | DrJPepper | MonadBot | Haskel | 028 | 028 | 002 | 039 | 0008.23 ms |
| 46th | Josef E. | OneBehind | Java | 027 | 027 | 007 | 035 | 0065.87 ms |
| 47th | Ourous | GitGudBot | Cobra | 025 | 025 | 001 | 043 | 0053.35 ms |
| 48th | ProgramFOX | Echo | .NET | 024 | 024 | 004 | 041 | 0014.81 ms |
| 48th | JoshDM | SelfHatingBot | Java | 024 | 024 | 005 | 040 | 0068.88 ms |
| 48th | Trimsty | Herpetologist | Python3 | 024 | 024 | 002 | 043 | 0036.93 ms |
| 51st | Milo | DogeBot | Java | 022 | 022 | 001 | 046 | 0067.86 ms |
| 51st | William Barbosa | StarWarsFan | Ruby | 022 | 022 | 002 | 045 | 0038.48 ms |
| 51st | Martin Büttner | ConservativeBot | Ruby | 022 | 022 | 001 | 046 | 0038.25 ms |
| 51st | killmous | MAWBRBot | Perl | 022 | 022 | 000 | 047 | 0016.30 ms |
| 55th | Mikey Mouse | LizardsRule | .NET | 020 | 020 | 007 | 042 | 0015.10 ms |
| 55th | ja72 | BlindForesight | .NET | 020 | 020 | 001 | 048 | 0024.05 ms |
| 57th | robotik | Evolver | Lua | 019 | 019 | 001 | 049 | 0008.19 ms |
| 58th | Kyle Kanos | LexicographicBot | Python3 | 018 | 018 | 003 | 048 | 0036.93 ms |
| 58th | William Barbosa | BarneyStinson | Lua | 018 | 018 | 005 | 046 | 0005.11 ms |
| 60th | Dr R Dizzle | BartSimpson | Ruby | 017 | 017 | 001 | 051 | 0038.22 ms |
| 60th | jmite | IocainePowder | Ruby | 017 | 017 | 003 | 049 | 0038.50 ms |
| 60th | ArcticanAudio | SpockOrRock | PHP | 017 | 017 | 001 | 051 | 0014.19 ms |
| 60th | Dr R Dizzle | BetterLisaSimpson | Ruby | 017 | 017 | 000 | 052 | 0038.23 ms |
| 64th | Dr R Dizzle | LisaSimpson | Ruby | 016 | 016 | 002 | 051 | 0038.29 ms |
| 65th | Martin Büttner | Vulcan | Ruby | 015 | 015 | 001 | 053 | 0038.26 ms |
| 65th | Dr R Dizzle | Khaleesi | Ruby | 015 | 015 | 005 | 049 | 0038.29 ms |
| 67th | Dr R Dizzle | EdwardScissorHands | Ruby | 014 | 014 | 002 | 053 | 0038.21 ms |
| 67th | undergroundmonorail | TheGambler | Python2 | 014 | 014 | 002 | 053 | 0025.47 ms |
| 69th | cipher | LemmingBot | Python2 | 011 | 011 | 002 | 056 | 0025.29 ms |
| 70th | Docopoper | ConcessionBot | Python2 | 007 | 007 | 000 | 062 | 0141.31 ms |
+-------+----------------------+-------------------------+------------+-------+-------+-------+-------+----------------+
Total Players: 70
Total Matches Completed: 2415
Total Tourney Time: 06:00:51.6877573
```
**Tourney Notes**
* ***WOO HOO 70 BOTS***
* Emil is still KOTH with `Pony` and his new bot `Dienstag` takes 3rd place
* Congrats to Roy for jumping into 2nd place with his `Gazzr` bot
* William Barbosa wins the *Quick Draw* award for his bot `BarneyStinson`
* And *Slow Poke* award goes to Docopoper for his bots `R.O.B.O.T` and `Concessionbot` who were both >140ms per hand
* *Logs available @ <https://github.com/eoincampbell/big-bang-game/blob/master/tourneys/Tournament-2014-08-01-23-24-00.zip?raw=true>*
**Excluded Bots**
* BashRocksBot - still no joy with .net execing cygwin bash scripts
* CounterPreferenceBot - awaiting bug fix
* RandomlyWeighted - awaiting bug fix
* CasinoShakespeare - excluded because it requires an active internet connection
# Original Posted Question
You've swung around to your friends house for the most epic showdown Battle ever of Rock, Paper, Scissors, Lizard, Spock. In true BigBang nerd-tastic style, none of the players are playing themselves but have created console bots to play on their behalf. You whip out your USB key and hand it over to the **Sheldor the Conqueror** for inclusion in the showdown. Penny swoons. Or perhaps Howard swoons. We don't judge here at Leonard's apartment.
**Rules**
Standard Rock, Paper, Scissors, Lizard, Spock rules apply.
* Scissors cut Paper
* Paper covers Rock
* Rock crushes Lizard
* Lizard poisons Spock
* Spock smashes Scissors
* Scissors decapitate Lizard
* Lizard eats Paper
* Paper disproves Spock
* Spock vaporizes Rock
* Rock crushes Scissors
![RPSLV Rules](https://i.stack.imgur.com/jILea.png)
Each player's bot will play one *Match* against each other bot in the tournament.
Each Match will consist of 100 iterations of an RPSLV game.
After each match, the winner is the player who has won the most number of games/hands out of 100.
If you win a match, you will be assigned 1 point in the league table. In the result of a draw-match, neither player will gain a point.
**Bot Requirements**
Your bot must be runnable from the command line.
Sheldor's \*nix box has died, so we're running it off his windows 8 Gaming Laptop so make sure your provided solution can run on windows. Sheldor has graciously offered to install any required runtimes (within reason) to be able to run your solution. (.NET, Java, Php, Python, Ruby, Powershell ...)
**Inputs**
In the first game of each match no arguments are supplied to your bot.
In each subsequent game of each match:
- Arg1 will contain the history of your bots hands/decisions in this match.
- Arg2 will contain the history of your opponents hands/decisions in this match.
History will be represented by a sequence of single capital letters representing the possible hands you can play.
```
| R | Rock |
| P | Paper |
| S | Scissors |
| L | Lizard |
| V | Spock |
```
E.g.
* Game 1: MyBot.exe
* Game 2: MyBot.exe S V
* Game 3: MyBot.exe SS VL
* Game 4: MyBot.exe SSR VLS
**Output**
Your bot must write a single character response representing his "hand" for each game. The result should be written to STDOUT and the bot should then exit.
Valid single capital letters are below.
```
| R | Rock |
| P | Paper |
| S | Scissors |
| L | Lizard |
| V | Spock |
```
In the case where your bot does not return a valid hand (i.e. 1 of the above 5 single capital letters, then you automatically forfeit that hand and the match continues.
In the case where both bots do not return a valid hand, then the game is considered a draw and the match continues.
**Match Format**
Each submitted bot will play one match against each other bot in the tournament.
Each match will last exactly 100 games.
Matches will be played anonymously, you will not have an advanced knowledge of the specific bot you are playing against, however you may use any and all information you can garner from his decision making during the history of the current match to alter your strategy against your opponent. You may also track history of your previous games to build up patterns/heuristics etc... (See rules below)
During a single game, the orchestration engine will run your bot and your opponents bot 100 milliseconds apart and then compare the results in order to avoid any PRNG collisions in the same language/runtime. (this actually happened me during testing).
**Judging & Constraints**
Dr. Sheldon Cooper in the guise of Sheldor the Conqueror has kindly offered to oversee the running of the tournament.
Sheldor the Conqueror is a fair and just overseer (mostly). All decisions by Sheldor are final.
Gaming will be conducted in a fair and proper manner:
* Your bot script/program will be stored in the orchestration engine under a subfolder `Players\[YourBotName]\`
* You may use the subfolder `Players\[YourBotName]\data` to log any data or game history from the current tournament as it proceeds. Data directories will be purged at the start of each tournament run.
* You may not access the Player directory of another player in the tournament
* Your bot cannot have specific code which targets another specific bots behavior
* Each player may submit more than one bot to play so long as they do not interact or assist one another.
**Edit - Additional Constraints**
* Regarding forfeits, they won't be supported. Your bot must play one of the 5 valid hands. I'll test each bot outside of the tournament with some random data to make sure that they behave. Any bots that throw errors (i.e. forfeits errors) will be excluded from the tourney til they're bug fixed.
* Bots may be derivative so long as they are succinctly different in their behaviour. Bots (including in other languages) that perform exactly the same behaviour as an existing bot will be disqualified
* There are already spam bots for the following so please don't resubmit
* + Rock - BartSimpson
* + Paper - LisaSimpson
* + Scissor - EdwardScissorhands
* + Spock - Vulcan
* + Lizard - Khaleesi
* + Pseudo Random - SimpleRandomBot & FairBot
* + Psuedo Random RPS - ConservativeBot
* + Psuedo Random LV - Barney Stinson
* Bots may not call out to 3rd party services or web resources (or anything else which significantly slows down the speed/decision making time of the matches). `CasinoShakespeare` is the only exception as that bot was submitted prior to this constraint being added.
Sheldor will update this question as often as he can with Tournament results, as more bots are submitted.
**Orchestration / Control Program**
The orchestration program, along with source code for each bot is available on github.
<https://github.com/eoincampbell/big-bang-game>
**Submission Details**
Your submission should include
* Your Bot's name
* Your Code
* A command to
+ execute your bot from the shell e.g.
+ ruby myBot.rb
+ python3 myBot.py
+ OR
+ first compile your both and then execute it. e.g.
+ csc.exe MyBot.cs
+ MyBot.exe
**Sample Submission**
```
BotName: SimpleRandomBot
Compile: "C:\Program Files (x86)\MSBuild\12.0\Bin\csc.exe" SimpleRandomBot.cs
Run: SimpleRandomBot [Arg1] [Arg2]
```
Code:
```
using System;
public class SimpleRandomBot
{
public static void Main(string[] args)
{
var s = new[] { "R", "P", "S", "L", "V" };
if (args.Length == 0)
{
Console.WriteLine("V"); //always start with spock
return;
}
char[] myPreviousPlays = args[0].ToCharArray();
char[] oppPreviousPlays = args[1].ToCharArray();
Random r = new Random();
int next = r.Next(0, 5);
Console.WriteLine(s[next]);
}
}
```
**Clarification**
Any questions, ask in the comments below.
[Answer]
# Pony (Python 2)
This is based on a rock-paper-scissors bot I wrote some time ago for a programming challenge at the end of a [Udacity online class](https://www.udacity.com/course/cs212). I changed it to include Spock and lizard and made some improvements.
The program has 11 different simple strategies, each with 5 variants. It chooses from among these based on how well they would have performed over the last rounds.
I removed a fallback strategy that just played random against stronger opponents. I guess it's more fun like this.
```
import sys
# just play Spock for the first two rounds
if len(sys.argv)<2 or len(sys.argv[1])<2: print 'V'; sys.exit()
# initialize and translate moves to numbers for better handling:
my_moves, opp_moves = sys.argv[1], sys.argv[2]
moves = ('R', 'P', 'S', 'V', 'L')
history = zip([moves.index(i) for i in my_moves],
[moves.index(i) for i in opp_moves])
# predict possible next moves based on history
def prediction(hist):
N = len(hist)
# find longest match of the preceding moves in the earlier history
cand_m = cand_o = cand_b = range(N-1)
for l in xrange(1,min(N, 20)):
ref = hist[N-l]
cand_m = ([c for c in cand_m if c>=l and hist[c-l+1][0]==ref[0]]
or cand_m[-1:])
cand_o = ([c for c in cand_o if c>=l and hist[c-l+1][1]==ref[1]]
or cand_o[-1:])
cand_b = ([c for c in cand_b if c>=l and hist[c-l+1]==ref]
or cand_b[-1:])
# analyze which moves were used how often
freq_m, freq_o = [0]*5, [0]*5
for m in hist:
freq_m[m[0]] += 1
freq_o[m[1]] += 1
# return predictions
return ([hist[-i][p] for i in 1,2 for p in 0,1]+ # repeat last moves
[hist[cand_m[-1]+1][0], # history matching of my own moves
hist[cand_o[-1]+1][1], # history matching of opponent's moves
hist[cand_b[-1]+1][0], # history matching of both
hist[cand_b[-1]+1][1],
freq_m.index(max(freq_m)), # my most frequent move
freq_o.index(max(freq_o)), # opponent's most frequent move
0]) # good old rock (and friends)
# what would have been predicted in the last rounds?
pred_hist = [prediction(history[:i]) for i in xrange(2,len(history)+1)]
# how would the different predictions have scored?
n_pred = len(pred_hist[0])
scores = [[0]*5 for i in xrange(n_pred)]
for pred, real in zip(pred_hist[:-1], history[2:]):
for i in xrange(n_pred):
scores[i][(real[1]-pred[i]+1)%5] += 1
scores[i][(real[1]-pred[i]+3)%5] += 1
scores[i][(real[1]-pred[i]+2)%5] -= 1
scores[i][(real[1]-pred[i]+4)%5] -= 1
# return best counter move
best_scores = [list(max(enumerate(s), key=lambda x: x[1])) for s in scores]
best_scores[-1][1] *= 1.001 # bias towards the simplest strategy
if best_scores[-1][1]<0.4*len(history): best_scores[-1][1] *= 1.4
strat, (shift, score) = max(enumerate(best_scores), key=lambda x: x[1][1])
print moves[(pred_hist[-1][strat]+shift)%5]
```
Run as:
```
python Pony.py
```
*Edit*:
I made a small change by putting in a bias towards the simplest strategy (i.e. always play the same move) in unsure cases. This helps a bit to not try to find overly complicated patterns where there are none, e.g. in bots like ConservativeBot.
*Note*: I tried to explain the basic history matching strategy that this bot uses in the post for my other bot [Dienstag](https://codegolf.stackexchange.com/a/35509/29703).
[Answer]
## ConservativeBot, Ruby
New things are bad things.
```
puts ['R','P','S'].sample
```
Run like
```
ruby conservative.rb
```
[Answer]
## Markov, Ruby
Looks at the opponent's last two moves and determines the possible (and most likely) follow ups. If the combination hasn't been picked before, he just uses all of the opponent's moves (so far) instead. Then he collects all the possible responses for these and picks a random one.
```
responses = {
'R' => ['P', 'V'],
'P' => ['S', 'L'],
'S' => ['R', 'V'],
'L' => ['S', 'R'],
'V' => ['P', 'L']
}
if ARGV.length == 0 || (history = ARGV[1]).length < 3
choices = ['R','P','S','L','V']
else
markov = Hash.new []
history.chars.each_cons(3) { |chars| markov[chars[0..1].join] += [chars[2]] }
choices = []
likely_moves = markov.key?(history[-2,2]) ? markov[history[-2,2]] : history.chars
likely_moves.each { |move| choices += responses[move] }
end
puts choices.sample
```
Run like
```
markov.rb
```
[Answer]
## Star Wars Fan - Ruby
Screw you, Spock
```
puts ['R','P','L','S'].sample
```
Run it like:
```
ruby starwarsfan.rb
```
[Answer]
## Barney Stinson - Lua
I only have one rule: New is always better. Screw old Jo Ken Po or whatever you call it.
```
math.randomseed(os.time())
print(math.random() > 0.5 and "V" or "L")
```
Run it like:
```
lua legenwaitforitdary.lua
```
[Answer]
## IocainePowder, Ruby
![enter image description here](https://i.stack.imgur.com/k4WXZ.jpg)
Based off (shamelessly stolen from) the RPS strategy [here](http://dan.egnor.name/iocaine.html).
The bot looks chooses a guess identical to the Markov bot, but then assumes the opponent has guessed what it's going to choose, and chooses a move to beat that one accordingly.
Note that I've just adapted the basic idea of the linked strategy, not followed it in detail.
```
responses = {
'R' => ['P', 'V'],
'P' => ['S', 'L'],
'S' => ['R', 'V'],
'L' => ['S', 'R'],
'V' => ['P', 'L']
}
if ARGV.length == 0 || (history = ARGV[1]).length < 3
choices = ['R','P','S','L','V']
else
markov = Hash.new []
history.chars.each_cons(3) { |chars| markov[chars[0..1].join] += [chars[2]] }
choices = []
likely_moves = markov.key?(history[-2,2]) ? markov[history[-2,2]] : history.chars
likely_moves.each { |move| choices += responses[move] }
end
myChoice = choices.sample
theirChoice = responses[myChoice].sample
actualChoice = responses[theirChoice].sample
puts actualChoice
```
Run like
```
iocaine.rb
```
[Answer]
# Boring Bot (Java)
He assumes everyone always plays the same thing and plans accordingly. He usually picks rocks in a ties though ’cause so does everyone else right?
```
public class BoringBot
{
public static void main(String[] args)
{
int Rock=0;
int Paper=0;
int Scissors=0;
int Lizard=0;
int Spock=0;
if (args.length == 0)
{
System.out.print("P");
return;
}
char[] oppPreviousPlays = args[1].toCharArray();
for (int j=0; j<oppPreviousPlays.length; j++) {
switch(oppPreviousPlays[j]){
case 'R': Rock++; break;
case 'P': Paper++; break;
case 'S': Scissors++; break;
case 'L': Lizard++; break;
case 'V': Spock++;
}
}
int Best = Math.max(Math.max(Lizard+Scissors-Spock-Paper,
Rock+Spock-Lizard-Scissors),
Math.max(Math.max(Paper+Lizard-Spock-Rock,
Paper+Spock-Rock-Scissors),
Rock+Scissors-Paper-Lizard));
if (Best== Lizard+Scissors-Spock-Paper){
System.out.print("R"); return;
} else if (Best== Rock+Spock-Lizard-Scissors){
System.out.print("P"); return;
} else if (Best== Paper+Lizard-Spock-Rock){
System.out.print("S"); return;
} else if(Best== Paper+Spock-Rock-Scissors){
System.out.print("L"); return;
} else {
System.out.print("V"); return;
}
}
}
```
[Answer]
## HuddleWolfTheConqueror - C#
HuddleWolf is back and better than ever. He will beat Sheldor the Conqueror at his own silly game. HuddleWolf is smart enough to identify and counter spammerbots. For more intelligent opponents, HuddleWolf uses his knowledge of basic 5th grade statistics and utilizes a weighted dice roll based on the opposition's history of plays.
```
using System;
using System.Collections.Generic;
using System.Linq;
public class HuddleWolfTheConqueror
{
public static readonly char[] s = new[] { 'R', 'P', 'S', 'L', 'V' };
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(pickRandom());
return;
}
char[] myPlays = args[0].ToCharArray();
char[] oppPlays = args[1].ToCharArray();
char tryPredict = canPredictCounter(oppPlays);
if (tryPredict != '^')
{
Console.WriteLine(tryPredict);
}
else
{
Console.WriteLine(pickRandom());
}
return;
}
public static char canPredictCounter(char[] history)
{
// don't predict if insufficient data
if (history.Length < 5)
{
return '^';
}
// calculate probability of win for each choice
Dictionary<char, double> dic = getBestProabability(history);
// get item with highest probability of win
List<char> maxVals = new List<char>();
char maxVal = '^';
double mostFreq = 0;
foreach (var kvp in dic)
{
if (kvp.Value > mostFreq)
{
mostFreq = kvp.Value;
}
}
foreach (var kvp in dic)
{
if (kvp.Value == mostFreq)
{
maxVals.Add(kvp.Key);
}
}
// return error
if (maxVals.Count == 0)
{
return maxVal;
}
// if distribution is not uniform, play best play
if (maxVals.Count <= 3)
{
Random r = new Random(Environment.TickCount);
return maxVals[r.Next(0, maxVals.Count)];
}
// if probability is close to uniform, use weighted dice roll
if (maxVals.Count == 4)
{
return weightedRandom(dic);
}
// if probability is uniform, use random dice roll
if (maxVals.Count >= 5)
{
return pickRandom();
}
// return error
return '^';
}
public static Dictionary<char, double> getBestProabability(char[] history)
{
Dictionary<char, double> dic = new Dictionary<char, double>();
foreach (char c in s)
{
dic.Add(c, 0);
}
foreach (char c in history)
{
if (dic.ContainsKey(c))
{
switch(c)
{
case 'R' :
dic['P'] += (1.0/(double)history.Length);
dic['V'] += (1.0/(double)history.Length);
break;
case 'P' :
dic['S'] += (1.0/(double)history.Length);
dic['L'] += (1.0/(double)history.Length);
break;
case 'S' :
dic['V'] += (1.0/(double)history.Length);
dic['R'] += (1.0/(double)history.Length);
break;
case 'L' :
dic['R'] += (1.0/(double)history.Length);
dic['S'] += (1.0/(double)history.Length);
break;
case 'V' :
dic['L'] += (1.0/(double)history.Length);
dic['P'] += (1.0/(double)history.Length);
break;
default :
break;
}
}
}
return dic;
}
public static char weightedRandom(Dictionary<char, double> dic)
{
Random r = new Random(Environment.TickCount);
int next = r.Next(0, 100);
int curVal = 0;
foreach (var kvp in dic)
{
curVal += (int)(kvp.Value*100);
if (curVal > next)
{
return kvp.Key;
}
}
return '^';
}
public static char pickRandom()
{
Random r = new Random(Environment.TickCount);
int next = r.Next(0, 5);
return s[next];
}
}
```
[Answer]
# ToddlerProof
This fairly stupid bot assumes it is playing a toddler who will "chase" its moves, always trying to beat whatever was last thrown. If the bot is beaten several times in a row, it jumps to a new point in the pattern. It is based on my strategy for always beating my *much* younger brother. :)
**EDIT::** Changed the length of a loss streak required to jump into random throws. Also fixed a major bug with the random jump.
Save as `ToddlerProof.java`, compile, then run with `java ToddlerProof [me] [them]`
```
import java.util.HashMap;
public class ToddlerProof
{
char[] moves = new char[]{'R', 'P', 'S', 'L', 'V'};
public static void main(String[] args)
{
if(args.length<1) //first Round
{
System.out.print('V');//Spock is best
return;
}
else
{
String them = args[1];
String me = args[0];
int streak = 0;
HashMap<Character, Character> nextMove = new HashMap<Character, Character>();
//Next move beats things that beat my last move
nextMove.put('L', 'V');
nextMove.put('V', 'S');
nextMove.put('S', 'P');
nextMove.put('P', 'R');
nextMove.put('R', 'L');
//Check if last round was a tie or the opponent beat me
int lastResult = winner(me.charAt(me.length()-1), them.charAt(them.length()-1));
if(lastResult == 0)
{
//tie, so they will chase my last throw
System.out.print(nextMove.get(me.charAt(me.length()-1)));
return;
}
else if(lastResult == 1)
{
//I won, so they will chase my last throw
System.out.print(nextMove.get(me.charAt(me.length()-1)));
return;
}
else{
//I lost
//find streak
for(int i = 0; i<me.length(); i++)
{
int a = winner(me.charAt(i), them.charAt(i));
if(a >= 0) streak = 0;
else streak++;
}
//check lossStreak
//If the streak is 2, then a rotation will make it even.
//if it is >2, something bad has happened and I need to adjust.
if(streak>2)
{
//if they are on to me, do something random-ish
int r = (((them.length()+me.length()-1)*13)/7)%4;
System.out.print(move[r]);
return;
}
//otherwise, go on with the plan
System.out.print(nextMove.get(me.charAt(me.length()-1)));
return;
}
}
}
public static int winner(char me, char them)
{
//check for tie
if(me == them) return 0;
//check if they won
if(me=='V' && (them == 'L' || them == 'P')) return -1;
if(me=='S' && (them == 'V' || them == 'R')) return -1;
if(me=='P' && (them == 'S' || them == 'L')) return -1;
if(me=='R' && (them == 'P' || them == 'V')) return -1;
if(me=='L' && (them == 'R' || them == 'S')) return -1;
//otherwise, I won
return 1;
}
}
```
[Answer]
## Bart Simpson
"Good old rock! Nothing beats rock!"
```
puts 'R'
```
Run as
```
ruby DoTheBartman.rb
```
---
## Lisa Simpson
"Poor, predictable Bart. Always chooses rock."
```
puts 'P'
```
Run as
```
ruby LisaSimpson.rb
```
---
## Better Lisa Simpson
I felt bad about making Lisa quite so stupid, so I allowed her to randomly choose between either of the hands that will beat rock. Still stupid, but she is a Simpson after all. Maybe a crayon got stuck in her brain?
```
puts ['P','V'].sample
```
Run as
```
ruby BetterLisaSimpson.rb
```
[Answer]
# Echo
Written in C#. Compile with `csc Echo.cs`. Run like `Echo.exe ARG1 ARG2`.
The first run, Echo takes a random option. Every run after the first, Echo simply repeats the opponent's latest action.
```
using System;
namespace Echo
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Random r = new Random();
string[] options = new string[] { "R", "P", "S", "L", "V" };
Console.WriteLine(options[r.Next(0, options.Length)]);
}
else if (args.Length == 2)
{
string opponentHistory = args[1];
Console.WriteLine(opponentHistory[opponentHistory.Length - 1]);
}
}
}
}
```
[Answer]
## Vulcan, Ruby
My fingers are glued together.
```
puts 'V'
```
Run like
```
ruby vulcan.rb
```
(I think this is the only in-character strategy for your background setting.)
[Answer]
Tyrannosaurus, Godzilla, Barney... Lizards Rule.
Occasionally they get in trouble and need to call Spock or throw Rocks
```
using System;
public class LizardsRule
{
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("L");
return;
}
char[] oppPreviousPlays = args[1].ToCharArray();
var oppLen = oppPreviousPlays.Length;
if (oppPreviousPlays.Length > 2
&& oppPreviousPlays[oppLen - 1] == 'R'
&& oppPreviousPlays[oppLen - 2] == 'R'
&& oppPreviousPlays[oppLen - 3] == 'R')
{
//It's an avalance, someone call Spock
Console.WriteLine("V");
return;
}
if (oppPreviousPlays.Length > 2
&& oppPreviousPlays[oppLen - 1] == 'S'
&& oppPreviousPlays[oppLen - 2] == 'S'
&& oppPreviousPlays[oppLen - 3] == 'S')
{
//Scissors, Drop your tail and pick up a rock
Console.WriteLine("R");
return;
}
//Unleash the Fury Godzilla
Console.WriteLine("L");
}
}
```
[Answer]
# BayesianBot, Perl (now v2!)
Above everything else, this is a unique program. In it, you shall see the brilliant fusion of statistics and horrible programming form. Also, this bot probably breaks many rules of Bayesian statistics, but the name sounds cooler.
The core essence of this bot is its creation of 250 different predictive models. Each model takes the form of *"Given that I played rock last turn and my opponent played scissors two turns ago, this is the probability distribution for my opponent's next move."* Each probability distribution takes the form of a multi-dimensional Dirichlet distribution.
Each turn, the predictions of all applicable models (typically 10) are multiplied together to form an overall prediction, which is then used to determine which moves have the highest expected payoff.
Edit 1: In this version, I changed the prior distribution and made the bot more randomized when it is losing.
There are a few things which may be subject to improvement, such as the number of models (250 is only a 3 digit number), the choice of prior distribution (currently Dir(3,3,3,3,3)), and the method of fusing predictions. Also, I never bothered to normalize any of the probability distributions, which is okay for now because I'm multiplying them.
I don't have super high expectations, but I hope this bot will be able to do well.
```
my ($phist, $ohist) = @ARGV;
my %text2num = ('R',0,'V',1,'P',2,'L',3,'S',4); #the RVPLS ordering is superior
my @num2text = ('R','V','P','L','S');
@phist = map($text2num{$_},split(//,$phist));
@ohist = map($text2num{$_},split(//,$ohist));
$lowerlimit = 0;
for($lowerlimit..~~@phist-3){$curloc=$_;
$result = $ohist[$curloc+2];
@moveset = ($ohist[$curloc],$ohist[$curloc+1],$phist[$curloc],$phist[$curloc+1]);
for(0..3){$a=$_;
for(0..$a){$b=$_;
$predict[$a][$b][$moveset[$a]][$moveset[$b]][$result]++;
}
}
}
@recentmoves = ($ohist[-2],$ohist[-1],$phist[-2],$phist[-1]);
@curpred = (1,1,1,1,1);
for(0..3){$a=$_;
for(0..$a){$b=$_;
for(0..4){$move=$_;
$curpred[$move] *= $predict[$a][$b][$recentmoves[$a]][$recentmoves[$b]][$move]/3+1;
}
}
}
@bestmove = (0,0,0,0,0);
for(0..4){
$bestmove[$_] = $curpred[$_]/2+$curpred[$_-1]+$curpred[$_-2];
}
$max = 0;
for(0..4){
if($bestmove[$_]>$max){
$max = $bestmove[$_];
}
}
@options=();
$offset=0;
if(($ohist[-1] - $phist[-1])%5 < 2 && ($ohist[-2] - $phist[-2])%5 < 2 && ($ohist[-3] - $phist[-3])%5 < 2){ #frequentist alert!
$offset=int(rand(3));
}
for(0..4){
if($bestmove[$_] == $max){
push(@options,$num2text[($_+$offset)%5]);
}
}
$outputb = $options[int(rand(~~@options))];
print "$outputb";
```
I've been running this program like so:
```
perl BayesianBot.plx
```
[Answer]
## DynamicBot
Dynamic bot is almost always changing. It really hates repeating itself
```
import sys, random
choices = ['L','V','S','P','R'] * 20
if len(sys.argv) > 1:
my_history = sys.argv[1]
[choices.remove(my_history[-1]) for i in range(15)]
print(choices[random.randrange(len(choices))])
```
Language: Python 3.4.1
Command: `python dynamicbot.py <history>` or `python3 dynamicbot.py <history>` depending on your system
[Answer]
# SmartBot - Java
My first ever entry for anything on this site!
Though not a very creative name...
SmartBot finds sequences of moves where the opponent and/or itself's moves are similar to the moves last made and plans accordingly.
`name = SmartBot`
I think to run it, correct me if I am wrong.
`java -jar SmartBot.jar`
```
import java.util.ArrayList;
public class SmartBot {
public static void main(String[] args) {
if(args.length ==0){
System.out.print("L");
return;
}
if(args[0].length()<3){
String[] randLetter = new String[]{"R","P","S","L","V"};
System.out.print(randLetter[(int) Math.floor(Math.random()*5)]);
return;
}
String myHistory = args[0];
String otherHistory = args[1];
double rScore,pScore,sScore,lScore,vScore;//score - highest = highest probability of next opponent move
rScore = pScore = sScore = lScore = vScore = 0;
lScore = .001;
ArrayList<ArrayList<Integer>> moveHits = new ArrayList<ArrayList<Integer>>();
for(int g = 0;g<2;g++){
for(int i=1;i<(myHistory.length() / 2) + 1;i++){
if(g==0){
moveHits.add(findAll(myHistory.substring(myHistory.length() - i),myHistory));
}
else{
moveHits.add(findAll(otherHistory.substring(otherHistory.length() - i),otherHistory));
}
}
for(int i = 0; i < moveHits.size();i++){
int matchingMoves = i+1;
ArrayList<Integer> moveIndexes = moveHits.get(i);
for(Integer index:moveIndexes){
if(index+matchingMoves +1<= otherHistory.length()){
char nextMove = otherHistory.charAt(index + matchingMoves-1);
if(nextMove=='R'){rScore = rScore + matchingMoves;}
if(nextMove=='P'){pScore = pScore + matchingMoves;}
if(nextMove=='S'){sScore = sScore + matchingMoves;}
if(nextMove=='L'){lScore = lScore + matchingMoves;}
if(nextMove=='V'){vScore = vScore + matchingMoves;}
}
}
}
}
if(rScore >= pScore && rScore >= sScore && rScore >= lScore && rScore >= vScore){
System.out.print("V");
return;
}
if(pScore >= rScore && pScore >= sScore && pScore >= lScore && pScore >= vScore){
System.out.print("L");
return;
}
if(sScore >= pScore && sScore >= rScore && sScore >= lScore && sScore >= vScore){
System.out.print("R");
return;
}
if(vScore >= pScore && vScore >= sScore && vScore >= lScore && vScore >= rScore){
System.out.print("L");
return;
}
if(lScore >= pScore && lScore >= sScore && lScore >= rScore && lScore >= vScore){
System.out.print("S");
}
return;
}
public static ArrayList<Integer> findAll(String substring,String realString){
ArrayList<Integer> ocurrences = new ArrayList<Integer>();
Integer index = realString.indexOf(substring);
if(index==-1){return ocurrences;}
ocurrences.add(index+1);
while(index!=-1){
index = realString.indexOf(substring,index + 1);
if(index!=-1){
ocurrences.add(index+1);
}
}
return ocurrences;
}
}
```
It assigns a score for each possible next move by the number of times similar patterns have happened.
It slightly favors lizard.
[Answer]
# SpockOrRock - PHP
![SpockOrRock](https://i.stack.imgur.com/IxPbu.jpg)
When played in the real world, most people instinctively pick scissors. This bot picks either Spock or Rock to beat the average player. It's not bothered about previous rounds.
run with `php spockorrock.php`
```
<?php
//Pick either Spock or Rock
if (rand(0,1) == 0) echo("R\n");
else echo("V\n");
?>
```
[Answer]
## SlowLizard, Ruby
After starting with Lizard, it always picks a random move which beats the opponent's previous move.
```
responses = {
'R' => ['P', 'V'],
'P' => ['S', 'L'],
'S' => ['R', 'V'],
'L' => ['S', 'R'],
'V' => ['P', 'L']
}
if ARGV.length == 0
puts 'L'
else
puts responses[ARGV[1][-1]].sample
end
```
Run like
```
ruby slowlizard.rb
```
[Answer]
# LexicographicBot
This bot likes to order his letters, so he will choose a response that is 1 higher than his opponent gave in the previous round--unless the opponent chose Vulcan, then he randomly picks a response.
```
import sys
import random
choices = ["L", "P", "R", "S", "V"]
total = len(sys.argv)
if total==1:
print("L")
sys.exit()
opponent = sys.argv[2]
opponent_last = opponent[-1]
if opponent_last == choices[-1]:
print(random.choice(choices))
else:
next = choices.index(opponent_last)+1
print(choices[next])
```
This expects the opponent hand to be dealt second:
```
me
v
python LexicographicBot.py SR RV
^
opponent
```
[Answer]
# Werevulcan - Ruby
Run as `ruby werevulcan.rb`
```
@rules = {
'L' => %w[V P],
'P' => %w[V R],
'R' => %w[L S],
'S' => %w[P L],
'V' => %w[R S]
}
@moves = @rules.keys
def defeats?(move1, move2)
@rules[move1].include?(move2)
end
def score(move1, move2)
if move1 == move2
0
elsif defeats?(move1, move2)
1
else
-1
end
end
def move
player, opponent = ARGV
# For the first 30 rounds, pick a random move that isn't Spock
if player.to_s.size < 30
%w[L P R S].sample
elsif opponent.chars.to_a.uniq.size < 5
exploit(opponent)
else
# Pick a random move that's biased toward Spock and against lizards
%w[L P P R R S S V V V].sample
end
end
def exploit(opponent)
@moves.shuffle.max_by{ |m| opponent.chars.map{|o| score(m,o) }.reduce(:+) }
end
puts move
```
The werevulcan looks normal by day, but when the moon rises, its ears grow pointy, and its moves grow more logical.
[Answer]
# Analogizer - Ruby
Run with `ruby analogizer.rb`. I've made a logic fix to the code, but no idea why there were errors with this.
```
@rules = {
'L' => %w[V P],
'P' => %w[V R],
'R' => %w[L S],
'S' => %w[P L],
'V' => %w[R S]
}
@moves = @rules.keys
def defeats?(move1, move2)
@rules[move1].include?(move2)
end
def score(move1, move2)
if move1 == move2
0
elsif defeats?(move1, move2)
1
else
-1
end
end
def move
player, opponent = ARGV
case player.to_s.size
# Throw six lizards in the beginning to confuse opponent
when 0..5
'L'
when 6
'V'
when 7
'S'
when 8
'P'
when 9
'R'
else
analyze_history(player.chars.to_a, opponent.chars.to_a)
end
end
def analyze_history(player, opponent)
my_last_move = player.last
predicted_moves = Hash.new {0}
opponent_reactions = player.zip(opponent.drop(1))
# Check whether opponent tended to make a move that would've beaten, lost, or tied my last move
opponent_reactions.each do |my_move, reaction|
score = score(reaction, my_move)
analogous_moves = @moves.select { |move| score == score(move, my_last_move) }
analogous_moves.each { |move| predicted_moves[move] += 1 }
end
# Assume if an opponent has never made a certain move, it never will
@moves.each { |m| predicted_moves[m] = 0 unless opponent.include?(m) }
# Pick the move with the best score against opponent's possible moves, weighted by their likelihood, picking randomly for ties
@moves.shuffle.max_by{ |m| predicted_moves.map { |predicted, freq| score(m, predicted) * freq }.reduce(0,:+) }
end
puts move
```
Assumes the opposing bot is always reacting to my previous move, and either picking something that would beat it, something that would lose to it, or the same move, possibly from a restricted set of possible moves. It then picks the best move given that assumption.
Except that the first ten moves are hardcoded: first I pretend I only know lizard, then I assume my opponent always throws something to beat the last thing I threw until I have enough data for proper analysis.
[Answer]
# Java - SelfLoathingBot
```
BotName: SelfLoathingBot
Compile: Save as 'SelfLoathingBot.java'; compile.
Run: java SelfLoathingBot [me] [them]
```
Bot starts randomly, then ~33% to go random, or ~33% to play a winning tactic against either of the immediately prior plays, with 50% choice of winning tactic.
```
import java.util.Random;
public class SelfLoathingBot {
static final Random RANDOM = new Random();
private static char randomPlay() {
switch (RANDOM.nextInt(5)) {
case 0 : return 'R';
case 1 : return 'P';
case 2 : return 'S';
case 3 : return 'L';
default : return 'V';
}
}
private static char antiPlay(String priorPlayString) {
char[] priorPlays = priorPlayString.toCharArray();
int choice = RANDOM.nextInt(2);
switch (priorPlays[priorPlays.length - 1]) {
case 'R' : return choice == 0 ? 'P' : 'V';
case 'P' : return choice == 0 ? 'S' : 'L';
case 'S' : return choice == 0 ? 'V' : 'R';
case 'L' : return choice == 0 ? 'R' : 'S';
default : return choice == 0 ? 'L' : 'P'; // V
}
}
public static void main(String[] args) {
int choice = args.length == 0 ? 0 : RANDOM.nextInt(3);
char play;
switch (choice) {
case 1 :
// 33.3% chance Play myself
play = antiPlay(args[0]);
break;
case 2 :
// 33.3% chance Play opponent just in case opponent is screwy like that
play = antiPlay(args[1]);
break;
default :
// 33.3% chance 100% Random
play = randomPlay();
}
System.out.print(play);
return;
}
}
```
[Answer]
# The Analyst
The analyst analyzes some stuff and does some things to try to beat you.
compile with `javac Analyst.java` and run as `java Analyst`
```
import java.util.Random;
public class Analyst{
public static void main(String[] args){
char action = 'S';
try{
char[] enemyMoves = null, myMoves = null;
//first move is random
if(args.length == 0){
System.out.print(randomMove());
System.exit(0);
//moves 2-3 will beat their last move
}else if(args[0].length() < 8){
System.out.print(counterFor(args[1].charAt(args[1].length()-1)));
System.exit(0);
//following moves will execute some analyzation stuff
}else{
//get previous moves
myMoves = args[0].toCharArray();
enemyMoves = args[1].toCharArray();
}
//test if they're trying to beat our last move
if(beats(enemyMoves[enemyMoves.length-1], myMoves[myMoves.length-2])){
action = counterFor(counterFor(myMoves[myMoves.length-1]));
}
//test if they're copying our last move
else if(enemyMoves[enemyMoves.length-1] == myMoves[myMoves.length-2]){
action = counterFor(myMoves[myMoves.length-1]);
}
//else beat whatever they've done the most of
else{
action = counterFor(countMost(enemyMoves));
}
//if they've beaten us for the first 40 moves, do the opposite of what ive been doing
if(theyreSmarter(myMoves, enemyMoves)){
action = counterFor(action);
}
//if you break my program do something random
}catch (Exception e){
action = randomMove();
}
System.out.print(action);
}
private static char randomMove(){
Random rand = new Random(System.currentTimeMillis());
int randomMove = rand.nextInt(5);
switch (randomMove){
case 0: return 'R';
case 1: return 'P';
case 2: return 'S';
case 3: return 'L';
default: return 'V';
}
}
private static char counterFor(char move){
Random rand = new Random(System.currentTimeMillis());
int moveSet = rand.nextInt(2);
if(moveSet == 0){
switch (move){
case 'R': return 'P';
case 'P': return 'S';
case 'S': return 'R';
case 'L': return 'R';
default: return 'P';
}
}else{
switch (move){
case 'R': return 'V';
case 'P': return 'L';
case 'S': return 'V';
case 'L': return 'S';
default: return 'L';
}
}
}
private static boolean beats(char move1, char move2){
if(move1 == 'R'){
if((move2 == 'S') || (move2 == 'L')){
return true;
}else{
return false;
}
}else if(move1 == 'P'){
if((move2 == 'R') || (move2 == 'V')){
return true;
}else{
return false;
}
}else if(move1 == 'S'){
if((move2 == 'L') || (move2 == 'P')){
return true;
}else{
return false;
}
}else if(move1 == 'L'){
if((move2 == 'P') || (move2 == 'V')){
return true;
}else{
return false;
}
}else{
if((move2 == 'R') || (move2 == 'S')){
return true;
}else{
return false;
}
}
}
private static char countMost(char[] moves){
int[] enemyMoveList = {0,0,0,0,0};
for(int i=0; i<moves.length; i++){
if(moves[i] == 'R'){
enemyMoveList[0]++;
}else if(moves[i] == 'P'){
enemyMoveList[1]++;
}else if(moves[i] == 'S'){
enemyMoveList[2]++;
}else if(moves[i] == 'L'){
enemyMoveList[3]++;
}else if(moves[i] == 'V'){
enemyMoveList[4]++;
}
}
int max = 0, maxIndex = 0;
for(int i=0; i<5; i++){
if(enemyMoveList[i] > max){
max = enemyMoveList[i];
maxIndex = i;
}
}
switch (maxIndex){
case 0: return 'R';
case 1: return 'P';
case 2: return 'S';
case 3: return 'L';
default: return 'V';
}
}
private static boolean theyreSmarter(char[] myMoves, char[] enemyMoves){
int loseCounter = 0;
if(enemyMoves.length >= 40){
for(int i=0; i<40; i++){
if(beats(enemyMoves[i],myMoves[i])){
loseCounter++;
}
}
}else{
return false;
}
if(loseCounter > 20){
return true;
}else{
return false;
}
}
}
```
[Answer]
# The Gambler - Python 2
```
import sys
import random
MODE = 1
moves = 'RSLPV'
def element_sums(a, b):
return [a[i] + b[i] for i in xrange(len(a))]
def move_scores(p):
def calc(to_beat):
return ['LDW'.find('DLLWW'[moves.find(m)-moves.find(to_beat)]) for m in moves]
return dict(zip(moves, element_sums(calc(p[0]), calc(p[1]))))
def move_chooser(my_history, opponent_history):
predict = sorted(moves, key=opponent_history.count, reverse=MODE)[-2:]
scores = move_scores(predict)
return max(scores, key=lambda k:scores[k])
if __name__ == '__main__':
if len(sys.argv) == 3:
print move_chooser(*sys.argv[1:])
elif len(sys.argv) == 1:
print random.choice(moves)
```
Contrary to the name, the only time randomness is used in this program is on the first round, when there's no information. Instead, it's named for the gambler's fallacy, the belief that if a random event has happened less often in the past, it's more likely to happen in the future. For example, if you flip a fair coin 20 times, and the first 15 are heads, the gambler's fallacy states that the odds of the remaining flips being tails are increased. Of course, this is untrue; regardless of the previous flips, a fair coin's odds of coming up tails is always 50%.
This program analyzes the opponent's history, finds the 2 moves that it has used the least so far, and assumes that the opponent's move this time will be one of those two. Assigning 2 to a win, 1 to a draw and 0 to a loss, it finds the move with the maximum score against these two predicted moves and throws that.
# The Gambler's Brother - Python 2
```
import sys
import random
MODE = 0
moves = 'RSLPV'
def element_sums(a, b):
return [a[i] + b[i] for i in xrange(len(a))]
def move_scores(p):
def calc(to_beat):
return ['LDW'.find('DLLWW'[moves.find(m)-moves.find(to_beat)]) for m in moves]
return dict(zip(moves, element_sums(calc(p[0]), calc(p[1]))))
def move_chooser(my_history, opponent_history):
predict = sorted(moves, key=opponent_history.count, reverse=MODE)[-2:]
scores = move_scores(predict)
return max(scores, key=lambda k:scores[k])
if __name__ == '__main__':
if len(sys.argv) == 3:
print move_chooser(*sys.argv[1:])
elif len(sys.argv) == 1:
print random.choice(moves)
```
By switching the `MODE` variable to 0, this program will operate based on a related fallacy, also sometimes referred to as the gambler's fallacy. It states that if a random event has been happened more often in the past, it's more likely to happen in the future. For example, if you flip a coin 20 times and the first 15 are heads, this fallacy states that the remaining flips are more likely to be heads, since there's currently a streak. In mode 0, this program operates the same way, except that it assumes the opponent will throw one of the two moves it's thrown most often so far.
So yes, these two programs are only one character apart. :)
[Answer]
# Dienstag (Python 2)
My first entry [Pony](https://codegolf.stackexchange.com/a/35181/29703) seems to fare quite well with all its second guessing (tripple guessing, ...) and meta reasoning. But is that even necessary?
So, here is Dienstag, Pony's little friend, with only one of the 55 strategies: Predict the opponent's next move and beat it.
On the long run Dienstag wins or ties with every Bot in the top ten of the current leaderboard. Except for Pony that is.
```
import sys
if len(sys.argv)<2 or len(sys.argv[1])<2: print 'L'; sys.exit()
hist = [map('RPSVL'.index, p) for p in zip(sys.argv[1], sys.argv[2])]
N = len(hist)
cand = range(N-1)
for l in xrange(1,N):
cand = ([c for c in cand if c>=l and hist[c-l+1]==hist[-l]] or cand[-1:])
print 'RPSVL'[(hist[cand[-1]+1][1]+(1,3)[N%2==0])%5]
```
Run as:
```
python Dienstag.py
```
I admit that the code is a bit obfuscated. Should anyone care to know more about it, I might add explanations.
*Edit:* Here is a short example walkthrough to explain the idea:
* The program gets the history of it's own and the opponent's moves:
`sys.arg[1] = 'LLVLLVL', sys.arg[2] = 'RPSPSSP'`
* The history is combined into a list of pairs and the moves are translated to numbers (R=0, ...):
`hist = [[4, 0], [4, 1], [3, 2], [4, 1], [4, 2], [3, 2], [4, 1]]`
* The number of rounds played so far is determined:
`N = 7`
* The basic idea now is to look for the longest unbroken chain of exactly the last moves in the earlier history. The program keeps track of where such a chain ends in the list `cand` (for 'candidates'). In the beginning, without checking, every position in the history except for the last one is considered:
`cand = [0, 1, 2, 3, 4, 5]`
* Now the length of possible chains is increased step by step. For chain length `l = 1` it looks for previous occurrences of the last move pair `[4, 1]`. This can be found at history position `1` and `3`. Only these are kept in the `cand` list:
`cand = [1, 3]`
* Next, for `l = 2` it checks which of the possible candidates was preceded by the second to last move pair `[3, 2]`. This is only the case for position `3`:
`cand = [3]`
* For `l = 3` and more there are no previous chains of that length and `cand` would be empty. In this case the last element of `cand` is kept:
`cand = [3]`
* The bot now assumes that history will repeat. The last time the cain `[3, 2], [4, 1]` occurred, it was followed by `[4, 2]`. So, the opponent played `2` (scissors) which can be beaten by `(2+1)%5 = 3` (Spock) or `(2+3)%5 = 0` (rock). The bot answers, with the first or second alternative depending on whether `N` is odd or even just to introduce some variance.
* Here move `3` is chosen which is then translated back:
`print 'V'`
*Note:* Dienstag has time complexity O(*N*2) for returning the next move after *N* rounds. Pony has time complexity O(*N*3). So in this aspect they are probably much worse then most other entries.
[Answer]
## Bash Rocks
Is cygwin too much to ask as a runtime?
bashrocks.sh:
```
#!/bin/bash
HAND=(R P S L V)
RAND=`od -A n -t d -N 1 /dev/urandom | xargs`
echo ${HAND[ $RAND % 5 ]}
```
and run it like so:
```
sh bashrocks.sh
```
[Answer]
# Algorithm
An algorithm for the sake of having one.
Cuz' it always feels safer doing something, the more complicated the better.
Haven't done some serious Math yet, so this algorithm may not be that effective.
```
import random, sys
if __name__ == '__main__':
# Graph in adjacency matrix here
graph = {"S":"PL", "P":"VR", "R":"LS", "L":"VP", "V":"SR"}
try:
myHistory = sys.argv[1]
opHistory = sys.argv[2]
choices = ""
# Insert some graph stuff here. Newer versions may include advanced Math.
for v in graph:
if opHistory[-1] == v:
for u in graph:
if u in graph[v]:
choices += graph[u]
print random.choice(choices + opHistory[-1])
except:
print random.choice("RPSLV")
```
Python 2 program: `python algorithm.py`
[Answer]
## FairBot, Ruby
Let's start simple.
```
puts ['R','P','S','L','V'].sample
```
Run like
```
ruby fairbot.rb
```
[Answer]
# ViolentBot
This bot choices the most violent option based on the opponents previous choice:
```
import sys
choice_dict = {"L" : "S", "P" : "S", "R" : "V", "S" : "V", "V" : "L"}
total = len(sys.argv)
if total==1:
print("L")
sys.exit()
opponent = sys.argv[2]
opponent_last = opponent[-1]
print(choice_dict[opponent_last])
```
Run as
```
python ViolentBot.py (me) (opp)
```
[Answer]
# Nitpicker (Ruby)
```
BotName: Nitpicker
Run: ruby nitpicker.rb [Mine] [Theirs]
```
Code Update: Now counts more stuff.
Code
```
scores = [ 0 ] * 9
@moves = { "R" => 0, "P" => 1, "S" => 2, "L" => 3, "V" => 4 }
@responses = [ "R", "P", "S", "L", "V" ]
@counters = { "R" => [ "P", "V" ], "P" => [ "S", "L" ], "S" => [ "V", "R" ], "L" => [ "R", "S" ], "V" => [ "P", "L" ] }
def try( theirs, mine )
return @counters[theirs].include? mine
end
def counter( move )
return @counters[move][rand(2)]
end
def follower( move )
return @responses[(@moves[move]+1)%5]
end
def echo( move )
return move
end
if ARGV[1] != nil
for i in 2 .. ARGV[1].length - 1
points = i > ARGV[1].length - 10 ? 10 - ( ARGV[1].length - i ) : 1
if try( ARGV[1].split("")[i], counter( ARGV[0].split("")[i-1] ))
scores[0] += points
end
if try( ARGV[1].split("")[i], follower( ARGV[0].split("")[i-1] ))
scores[1] += points
end
if try( ARGV[1].split("")[i], echo( ARGV[0].split("")[i-1] ))
scores[2] += points
end
if try( ARGV[1].split("")[i], counter( ARGV[1].split("")[i-1] ))
scores[3] += points
end
if try( ARGV[1].split("")[i], follower( ARGV[1].split("")[i-1] ))
scores[4] += points
end
if try( ARGV[1].split("")[i], echo( ARGV[1].split("")[i-1] ))
scores[5] += points
end
if try( ARGV[1].split("")[i], counter( ARGV[1].split("")[i-2] ))
scores[6] += points
end
if try( ARGV[1].split("")[i], follower( ARGV[1].split("")[i-2] ))
scores[7] += points
end
if try( ARGV[1].split("")[i], echo( ARGV[1].split("")[i-2] ))
scores[8] += points
end
end
end
bestId = -1;
bestScore = 0;
for j in 0 .. scores.length - 1
if scores[j] > bestScore
bestScore = scores[j]
bestId = j
end
end
if bestId == 0
puts counter( ARGV[0].split("")[-1] )
elsif bestId == 1
puts follower( ARGV[0].split("")[-1] )
elsif bestId == 2
puts echo( ARGV[0].split("")[-1] )
elsif bestId == 3
puts counter( ARGV[1].split("")[-1] )
elsif bestId == 4
puts follower( ARGV[1].split("")[-1] )
elsif bestId == 5
puts echo( ARGV[1].split("")[-1] )
elsif bestId == 6
puts counter( ARGV[1].split("")[-2] )
elsif bestId == 7
puts follower( ARGV[1].split("")[-2] )
elsif bestId == 8
puts echo( ARGV[1].split("")[-2] )
else
puts @responses[rand(5)]
end
```
] |
[Question]
[
Assume we want to shift an array like it is done in [the 2048 game](https://gabrielecirulli.github.io/2048/): if we have two equal consecutive elements in array, merge them into twice the value element.
Shift must return a new array, where every pair of consecutive equal elements is replaced with their sum, and pairs should not intersect.
Shifting is performed only once, so we don't need to merge resulting values again.
Notice that if we have 3 consecutive equal elements, we have to sum rightmost ones, so for example, `[2, 2, 2]` should become `[2, 4]`, not `[4, 2]`.
The task is to write shortest function which takes an array and returns a shifted array.
You may assume that all integers will be strictly positive.
Examples:
```
[] -> []
[2, 2, 4, 4] -> [4, 8]
[2, 2, 2, 4, 4, 8] -> [2, 4, 8, 8]
[2, 2, 2, 2] -> [4, 4]
[4, 4, 2, 8, 8, 2] -> [8, 2, 16, 2]
[1024, 1024, 512, 512, 256, 256] -> [2048, 1024, 512]
[3, 3, 3, 1, 1, 7, 5, 5, 5, 5] -> [3, 6, 2, 7, 10, 10]
```
I am also very interested in solution using reduce :)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10 9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œg+2/€UF
```
**[TryItOnline](http://jelly.tryitonline.net/#code=xZJnKzIv4oKsVUY&input=&args=WzIsIDIsIDIsIDQsIDQsIDhd)** or **[run all test cases](http://jelly.tryitonline.net/#code=xZJnKzIv4oKsVUYKxbzDh-KCrEfigqxq4oG3O-KBt8Kk&input=&args=W1tdLCBbMiwgMiwgMl0sIFsyLCAyLCA0LCA0XSwgWzIsIDIsIDIsIDQsIDQsIDhdLCBbMiwgMiwgMiwgMl0sIFs0LCA0LCAyLCA4LCA4LCAyXSwgWzEwMjQsIDEwMjQsIDUxMiwgNTEyLCAyNTYsIDI1Nl0sIFszLCAzLCAzLCAxLCAxLCA3LCA1LCA1LCA1LCA1XV0)**
### How?
```
Œg+2/€UF - Main link: a e.g. [2,2,2,4,4,8]
Œg - group runs of equal elements [[2,2,2],[4,4],[8]]
2/€ - pairwise reduce for each with
+ - addition [[4,2],[8],[8]]
U - reverse (vectorises) [[2,4],[8],[8]]
F - flatten list [2,4,8,8]
```
[Answer]
## Haskell, ~~47~~ ~~57~~ 50 bytes
```
e#l|a:b<-l,e==a= -2*a:b|1<2=e:l
map abs.foldr(#)[]
```
Uses `reduce` (or `fold` as it is called in Haskell, here a right-fold `foldr`). Usage example: `map abs.foldr(#)[] $ [2,2,2,4,4,8]` -> `[2,4,8,8]`.
Edit: +10 bytes to make it work for unsorted arrays, too. Merged numbers are inserted as negative values to prevent a second merge. They are corrected by a final `map abs`.
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 158 96
```
{({}<>)<>}<>{(({}<>)<><(({})<<>({}<>)>)>)({}[{}]<(())>){((<{}{}>))}{}{{}(<({}{})>)}{}({}<>)<>}<>
```
[Try it online!](http://brain-flak.tryitonline.net/#code=eyh7fTw-KTw-fTw-eygoe308Pik8PjwoKHt9KTw8Pih7fTw-KT4pPikoe31be31dPCgoKSk-KXsoKDx7fXt9PikpfXt9e3t9KDwoe317fSk-KX17fSh7fTw-KTw-fTw-&input=MiAyIDIgNCA0IDg)
**Explanation:**
1 Reverse the list (moving everything to the other stack, but that doesn't matter)
```
{({}<>)<>}<>
{ } #keep moving numbers until you hit the 0s from an empty stack
({}<>) #pop a number and push it on the other stack
<> #go back to the original stack
<> #after everything has moved, switch stacks
```
2 Do steps 3-6 until there is nothing left on this stack:
```
{ }
```
3 Duplicate the top two elements (2 3 -> 2 3 2 3)
```
(({}<>)<><(({})<<>({}<>)>)>)
(({}<>)<> #put the top number on the other stack and back on the very top
<(({}) #put the next number on top after:
<<>({}<>)> #copying the original top number back to the first stack
)>)
```
4 Put a 1 on top if the top two are equal, a 0 otherwise (from the wiki)
```
({}[{}]<(())>){((<{}{}>))}{}
```
5 If the top two were equal (non-zero on the top) add the next two and push the result
```
{{}(<({}{})>)}{}
{ } #skip this if there is a 0 on top
{} #pop the 1
(< >) #push a 0 after:
({}{}) #pop 2 numbers, add them together and push them back on
{} #pop off the 0
```
6 Move the top element to the other stack
```
({}<>)<>
```
7 Switch to the other stack and print implicitly
```
<>
```
[Answer]
## Python, 61 bytes
```
def f(l):b=l[-2:-1]==l[-1:];return l and f(l[:~b])+[l[-1]<<b]
```
The Boolean `b` checks whether the last two elements should collapse by checking that they are equal in a way that's safe for lists of length 1 or 0. The last element if then appended with a multiplier of `1` for equal or `2` for unequal. It's appended to the recursive result on the list with that many elements chopped off the end. Thanks to Dennis for 1 byte!
[Answer]
# PHP, 116 Bytes
```
<?$r=[];for($c=count($a=$_GET[a]);$c-=$x;)array_unshift($r,(1+($x=$a[--$c]==$a[$c-1]))*$a[$c]);echo json_encode($r);
```
or
```
<?$r=[];for($c=count($a=$_GET[a]);$c--;)$r[]=$a[$c]==$a[$c-1]?2*$a[$c--]:$a[$c];echo json_encode(array_reverse($r));
```
-4 Bytes if the output can be an array `print_r` instead of 'json\_encode`
176 Bytes to solve this with a Regex
```
echo preg_replace_callback("#(\d+)(,\\1)+#",function($m){if(($c=substr_count($m[0],$m[1]))%2)$r=$m[1];$r.=str_repeat(",".$m[1]*2,$c/2);return trim($r,",");},join(",",$_GET[a]));
```
[Answer]
# GNU sed, 41 38 37
Includes +1 for -r
-3 Thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)
-1 Thanks to [seshoumara](https://codegolf.stackexchange.com/users/59010/seshoumara)
```
:
s,(.*)(1+) \2\b,\1!\2\2!,
t
y,!, ,
```
Input and output are space separated strings in unary ([based on this consensus](http://meta.codegolf.stackexchange.com/a/5349/57100)).
[Try it online!](http://sed.tryitonline.net/#code=OgpzLCguKikoMSspIFwyXGIsXDEhXDJcMiEsCnQKcywhLCAsZw&input=MTEgMTEgMTExMSAxMTExCjExIDExIDExIDExMTEgMTExMSAxMTExMTExMQoxMSAxMSAxMSAxMQ&args=LXI)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 32
```
\d+
$*
r`\b\1 (1+)\b
$1$1
1+
$.&
```
`r` on line 3 activates right-to-left regex matching. And this means that the `\1` reference needs to come before the `(1+)` capturing group that it references.
[Try it online.](http://retina.tryitonline.net/#code=XGQrCiQqCnJgXGJcMSAoMSspXGIKJDEkMQoxKwokLiY&input=MiAyIDQgNAoyIDIgMiA0IDQgOAoyIDIgMiAyCjIgMiAy)
[Answer]
# Perl, 41 bytes
Includes +1 for `-p`
Give input sequence on STDIN:
```
shift2048.pl <<< "2 2 2 4 4 8 2"
```
`shift2048.pl`:
```
#!/usr/bin/perl -p
s/.*\K\b(\d+) \1\b/2*$1.A/e&&redo;y/A//d
```
[Answer]
# JavaScript (ES6), 68 bytes
```
f=a=>a.reduceRight((p,c)=>(t=p[0],p.splice(0,c==t,c==t?c+t:c),p),[])
console.log([
[],
[2, 2, 4, 4],
[2, 2, 2, 4, 4, 8],
[2, 2, 2, 2],
[4, 4, 2, 8, 8, 2],
[1024, 1024, 512, 512, 256, 256],
[3, 3, 3, 1, 1, 7, 5, 5, 5, 5],
].map(f))
```
[Answer]
## Perl, 43 + 1 (`-p`) = 44 bytes
Ton Hospel came up with 41 bytes [answer](https://codegolf.stackexchange.com/a/95438/55508), check it out!
*-4 thanks to @Ton Hospel!*
**Edit** : added `\b`, as without it it was failing on input like `24 4` on which the output would have been `28`.
```
$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge
```
Run with `-p` flag :
```
perl -pe '$_=reverse reverse=~s/(\b\d+) \1\b/$1*2/rge' <<< "2 2 2 4 4"
```
I don't see another way than using `reverse` twice to right-fold (as just `s/(\d+) \1/$1*2/ge` would left-fold, i.e `2 2 2` would become `4 2` instead of `2 4`). So 14 bytes lost thanks to `reverse`... Still I think there must be another (better) way (it's perl after all!), let me know if you find it!
[Answer]
# Perl 5.10, ~~61~~ 50 bytes (~~49~~ + 1 for flag)
Thanks to [Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for saving 11 bytes!
Regex-free solution, with `-a` flag:
```
@a=($F[-1]-$b?$b:2*pop@F,@a)while$b=pop@F;say"@a"
```
[Try here!](https://ideone.com/1tKnMa)
[Answer]
# JavaScript (ES6), ~~68...64~~ 58 bytes
```
a=>(g=p=>(x=a.pop())|p?p?[...g(p^x?x:!(p*=2)),p]:g(x):a)()
```
[Try it online!](https://tio.run/##hY7NCsIwEITvPkW9ZaVGG/tHIfZBSoVQa1HELFakB9@9ZhMRsbaGyVx25ts9qbtqq@sRb8uL3tf9QfZKblkj0XgnFUeNDOCBOeYF57xhuOvyLpszXEgB4GOZNayDTAGDvtKXVp9rftYNO7CiBPCm32rlFeXsqyZ8zyg0GgNQzczTkeqrTYEBgKpunk4CxJ/d4aDqVgoH/gmgamojQUyBb0KwFobgPArEy0QUWyOevX4dph@pAWXje06BVWJSb7mbiGLmsT0lIRb9sn8C "JavaScript (Node.js) – Try It Online")
### Commented
```
a => ( // a[] = input array
g = p => // g is a recursive function taking p = previous value
(x = a.pop()) // extract the last entry x from a[]
| p ? // if either x or p is a positive integer:
p ? // if p is a positive integer:
[ // update the output:
...g( // do a recursive call:
p ^ x ? // if p is not equal to x:
x // set new_p = x
: // else:
!(p *= 2) // double p and set new_p = false
), // end of recursive call
p // append p
] // end of output update
: // else:
g(x) // do a simple recursive call with new_p = x
: // else:
a // stop recursion and return a[], which is guaranteed
// to be an empty array at this point
)() // initial call to g with p undefined
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 26 bytes
```
D¥__X¸«DgL*ê¥X¸«£vy2ôO})í˜
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RMKlX19YwrjCq0RnTCrDqsKlWMK4wqvCo3Z5MsO0T30pw63LnA&input=WzIsIDIsIDIsIDQsIDQsIDhd)
**Generalized steps**
1. Reduce by subtraction to find where consecutive elements differ
2. Reduce by subtraction over the indices of those places to find the length of consecutive elements
3. Split input into chunks of those lengths
4. Split chunks into pairs
5. Sum each pair
6. Reverse each summed chunk
7. Flatten to 1-dimensional list
[Answer]
# Mathematica, 53 bytes
```
Join@@(Reverse[Plus@@@#~Partition~UpTo@2]&/@Split@#)&
```
# Explanation
```
Split@#
```
Split the input into sublists consisting of runs of identical elements. i.e. `{2, 2, 2, 4, 8, 8}` becomes `{{2, 2, 2}, {4}, {8, 8}}`.
```
#~Partition~UpTo@2
```
Partition each of the sublist into partitions length at most 2. i.e. `{{2, 2, 2}, {4}, {8, 8}}` becomes `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}`.
```
Plus@@@
```
Total each partition. i.e. `{{{2, 2}, {2}}, {{4}}, {{8, 8}}}` becomes `{{4, 2}, {4}, {16}}`.
```
Reverse
```
Reverse the results because Mathematica's `Partition` command goes from left to right, but we want the partitions to be in other direction. i.e. `{{4, 2}, {4}, {16}}` becomes `{{2, 4}, {4}, {16}}`.
```
Join@@
```
Flatten the result. i.e. `{{2, 4}, {4}, {16}}` becomes `{2, 4, 4, 16}`.
[Answer]
# Haskell, 56 bytes
```
g(a:b:r)|a==b=a+b:g r|l<-b:r=a:g l
g x=x
r=reverse
r.g.r
```
[Answer]
## Java 7, 133 bytes
```
Object f(java.util.ArrayList<Long>a){for(int i=a.size();i-->1;)if(a.get(i)==a.get(i-1)){a.remove(i--);a.set(i,a.get(i)*2);}return a;}
```
Input is an ArrayList, and it just loops backwards, removing and doubling where necessary.
```
Object f(java.util.ArrayList<Long>a){
for(int i=a.size();i-->1;)
if(a.get(i)==a.get(i-1)){
a.remove(i--);
a.set(i,a.get(i)*2);
}
return a;
}
```
[Answer]
# Perl, 37 bytes
Includes +4 for `-0n`
Run with the input as separate lines on STDIN:
```
perl -M5.010 shift2048.pl
2
2
2
4
4
8
2
^D
```
shift2048.pl:
```
#!/usr/bin/perl -0n
s/\b(\d+
)(\1|)$//&&do$0|say$1+$2
```
[Answer]
# PHP, ~~86 100 99~~ 94 bytes
```
for($r=[];$v=+($p=array_pop)($a=&$argv);)array_unshift($r,end($a)-$v?$v:2*$p($a));print_r($r);
```
requires PHP 7.0; takes values from command line arguments.
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/8e345e910aa2254c49fbdcbecb2fbcbb35e3dbb3).
[Answer]
# Julia 205 bytes
```
t(x)=Val{x}
s(x)=t(x)()
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))
g()=[]
g{a}(::t(a))=[a]
g{a}(::t(a),B...)=[a;g(B...)]
g{a}(::t(a),::t(a),B...)=[2a;g(B...)]
K(A)=g(s.(A)...)
H(A)=(K^s(length(A)))(A)
```
Function to be called is `H`
eg `H([1,2,2,4,8,2,])`
This is in no way the shortest way do this in julia.
But it is so cool, that I wanted to share it anyway.
* `t(a)` is a value-type, representing the value (a).
* `s(a)` is an instance of that value type
* `g` is a function that dispatches on the difference values (using the value types) and numbers of its parameters. And that is cool
* `K` just wraps `g` so that
Extra cool part:
```
f^::t(1)=f
^{y}(f,::t(y))=x->f(((f^s(y-1))(x)))
```
This defines the `^` operator to apply to functions.
So that `K^s(2)(X)` is same as `K(K(X))`
so `H` is just calling `K` on `K` a bunch of times -- enough times to certainly collapse any nested case
This can be done much much shorter, but this way is just so fun.
[Answer]
## PowerShell v2+, 81 bytes
```
param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count..0]
```
Takes input as an explicit array `$n`, reverses it `$n[$n.count..0]`, `-join`s the elements together with a comma, then regex `-replace`s a matching digit pair with the first element, a `*2`, and surrounded in parens. Pipes that result (which for input `@(2,2,4,4)` will look like `(4*2),(2*2)`) over to `iex` (short for `Invoke-Expression` and similar to `eval`), which converts the multiplication into actual numbers. Stores the resulting array into `$b`, encapsulates that in parens to place it on the pipeline, then reverses `$b` with `[$b.count..0]`. Leaves the resulting elements on the pipeline, and output is implicit.
---
### Test Cases
***NB--*** In PowerShell, the concept of "returning" an empty array is meaningless -- it's converted to `$null` as soon as it leaves scope -- and so it is the equivalent of returning nothing, which is what is done here in the first example (after some wickedly verbose errors). Additionally, the output here is space-separated, as that's the default separator for stringified arrays.
```
PS C:\Tools\Scripts\golfing> @(),@(2,2,4,4),@(2,2,2,4,4,8),@(2,2,2,2),@(4,4,2,8,8,2),@(1024,1024,512,512,256,256),@(3,3,3,1,1,7,5,5,5,5)|%{"$_ --> "+(.\2048-like-array-shift.ps1 $_)}
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:67
+ param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+ ~~~
+ CategoryInfo : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
Cannot index into a null array.
At C:\Tools\Scripts\golfing\2048-like-array-shift.ps1:7 char:13
+ param($n)($b=$n[$n.count..0]-join','-replace'(\d+),\1','($1*2)'|iex)[$b.count. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
-->
2 2 4 4 --> 4 8
2 2 2 4 4 8 --> 2 4 8 8
2 2 2 2 --> 4 4
4 4 2 8 8 2 --> 8 2 16 2
1024 1024 512 512 256 256 --> 2048 1024 512
3 3 3 1 1 7 5 5 5 5 --> 3 6 2 7 10 10
```
[Answer]
# Javascript - 103 bytes
```
v=a=>{l=a.length-1;for(i=0;i<l;i++)a[l-i]==a[l-1-i]?(a[l-i-1]=a[l-i]*2,a.splice(l-i,1)):a=a;return a}
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 60 bytes
```
{({}<>)<>}<>{(({}<>)<>[({})]){((<{}>))}{}{({}<>{})(<>)}{}}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjutbGTtPGDkhWa8A40UCGZqwmUMCmutZOU7O2uhaiECisAVQB5AM5//8bKYCgCRBaAAA "Brain-Flak – Try It Online")
### Explanation:
```
{({}<>)<>}<> Reverse stack
{ While input exists
(
({}<>) Push copy of last element to the other stack
<>[({})] And subtract a copy of the next element
) Push the difference
{ If the difference is not 0
((<{}>)) Push two zeroes
}{} Pop a zero
{ If the next element is not zero, i.e the identical element
({}<>{}) Add the element to the copy of the previous element
(<>) Push a zero
}{} Pop the zero
}<> End loop and switch to output stack
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 bytes
```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HPXsNHXUsPrQAyHnU1PepdYVQDZGoAxYBsW81DK3RiHnXMAAr9T3vUNuFRb9@jvqme/o@6mg@tN37UNhHICw5yBpIhHp7B/9MUHvWu4UpTMNIBIRMggnOgfB0FC0whI2QhIwgfKgNUD0YgIUMDI6AQhDQ1NIISRqZmYAKowFgHigzByByoAo4A "APL (Dyalog Unicode) – Try It Online")
Fully tacit version of the previous solution, thanks to Adám.
### How it works
```
⌽1⊥¨⌽⊂⍨2|⌽(⊥⍨=)¨,\∘⌽ ⍝ Right argument: V, vector to reduce by 2048 rules
⌽ ⍝ Reverse V to get RV
,\∘ ⍝ Prefixes of RV
⌽( =)¨ ⍝ For each prefix, test if each element equals last element
⊥⍨ ⍝ and count trailing ones
⍝ (one-based index of each item within runs)
2| ⍝ Modulo 2
⌽⊂⍨ ⍝ Partition RV at ones of the above
1⊥¨ ⍝ Sum of each chunk
⌽ ⍝ Reverse back
```
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 bytes
```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRz15t/UMrqh/1bn3U1fSod4VRTfWjrqVABlDE9lFXM1ABkFV7aIVODIiGcv@nPWqb8Ki371HfVE9/oKpD640ftU0E8oKDnIFkiIdn8P80hUe9a7jSFIx0QMgEiOAcKF9HwQJTyAhZyAjCh8oA1YMRSMjQwAgoBCFNDY2ghJGpGZgAKjDWgSJDMDIHqoAjAA "APL (Dyalog Unicode) – Try It Online")
A full program. Link is to function version for easier testing.
### How it works
```
⌽+/¨{⍵⊂⍨2|{⊥⍨⍵=⊃⌽⍵}¨,\⍵}⌽⎕
⎕ ⍝ Take input
⌽ ⍝ Reverse
{ } ⍝ Apply the anonymous function...
,\⍵ ⍝ Prefixes
{ }¨ ⍝ For each prefix,
⍵=⊃⌽⍵ ⍝ Evaluate if each element is equal to last
⊥⍨ ⍝ and count trailing ones
⍝ (one-based index of each item within runs)
2| ⍝ Take modulo 2
⍵⊂⍨ ⍝ Partition the input array at 1's of the above
+/¨ ⍝ Sum each group
⌽ ⍝ Reverse back
```
[Answer]
# Python 2, 94 bytes
```
def f(a,r=[]):
while a:
if len(a)>1and a[-1]==a[-2]:a.pop();a[-1]*=2
r=[a.pop()]+r
print r
```
[**Try it online**](https://repl.it/DpVo)
[Answer]
## Racket 166 bytes
```
(λ(l)(let g((l(reverse l))(o '()))(cond[(null? l)o][(=(length l)1)(cons(car l)o)]
[(=(car l)(second l))(g(drop l 2)(cons(* 2(car l))o))][(g(cdr l)(cons(car l)o))])))
```
Ungolfed:
```
(define f
(λ (lst)
(let loop ((lst (reverse lst))
(nl '()))
(cond ; conditions:
[(null? lst) ; original list empty, return new list;
nl]
[(= (length lst) 1) ; single item left, add it to new list
(cons (first lst) nl)]
[(= (first lst) (second lst)) ; first & second items equal, add double to new list
(loop (drop lst 2)
(cons (* 2 (first lst)) nl))]
[else ; else just move first item to new list
(loop (drop lst 1)
(cons (first lst) nl))]
))))
```
Testing:
```
(f '[])
(f '[2 2 4 4])
(f '[2 2 2 4 4 8])
(f '[2 2 2 2])
(f '[4 4 2 8 8 2])
(f '[1024 1024 512 512 256 256])
(f '[3 3 3 1 1 7 5 5 5 5])
(f '[3 3 3 1 1 7 5 5 5 5 5])
```
Output:
```
'()
'(4 8)
'(2 4 8 8)
'(4 4)
'(8 2 16 2)
'(2048 1024 512)
'(3 6 2 7 10 10)
'(3 6 2 7 5 10 10)
```
[Answer]
# [Julia 0.6](http://julialang.org/), ~~73~~ 82 Bytes
```
f(l)=l==[]?[]:foldr((x,y)->y[]==x?vcat(2x,y[2:end]):vcat(x,y),[l[end]],l[1:end-1])
```
[Try it online!](https://tio.run/##XZDRisMgEEXf/YqBfVEwUG2ahoDpc79hmIeybSCL2CV1l/brs6OmIaxcBzn3Xgb8@vHjpZnnQXrlvHNIJ6RuuPvrJOVTv1TVv5Cce55@Py9RWkZou1u4kuoySRmNHhMi7dEkszKk5nh7xAc4QHEOEUl/QNUDkkCrgVWz3pDf7WosXkKLXUj7L2Q37ZqNUrIluLHbDE2TkECzs5wq82DsMuyhyWPduKvbTYp7ew1FJuvIfNW7xW6Tlx1TN10SJMRwnyDCGCD/iAA@39MYog8yguthkFEpwd82/wE "Julia 0.6 – Try It Online")
Use right fold to build list from back to front (one could also use fold left and reverse the list at the beginning and end).
If the head of the current list is not equal to the next element to prepend, then just prepend it.
Else remove the head of the list (sounds kind of cruel) and prepend the element times 2.
*Example*
```
f([3,3,3,1,1,7,5,5,5,5])
returns a new list:
[3,6,2,7,10,10]
```
[Answer]
# Mathematica, 51 bytes
```
Abs[#//.{Longest@a___,x_/;x>0,x_,b___}:>{a,-2x,b}]&
```
---
`{Longest@a___,x_/;x>0,x_,b___}` matches a list containing two consecutive identical positive numbers and transform these two numbers into `-2x`. `Longest` forces the matches to happen as late as possible.
The process is illustrated step by step:
```
{3, 3, 3, 1, 1, 7, 5, 5, 5, 5}
-> {3, 3, 3, 1, 1, 7, 5, 5, -10}
-> {3, 3, 3, 1, 1, 7, -10, -10}
-> {3, 3, 3, -2, 7, -10, -10}
-> {3, -6, -2, 7, -10, -10}
-> {3, 6, 2, 7, 10, 10}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
ò¦ ®ò2n)mxÃc
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=8qYgrvIybilteMNj&input=LW1RClsKICBbXSwKICBbMiwgMiwgNCwgNF0sCiAgWzIsIDIsIDIsIDQsIDQsIDhdLAogIFsyLCAyLCAyLCAyXSwKICBbNCwgNCwgMiwgOCwgOCwgMl0sCiAgWzEwMjQsIDEwMjQsIDUxMiwgNTEyLCAyNTYsIDI1Nl0sCiAgWzMsIDMsIDMsIDEsIDEsIDcsIDUsIDUsIDUsIDVdCl0=)
### Unpacked & How it works
```
Uò!= mZ{Zò2n)mx} c
Uò!= Partition the input array where two adjacent values are different
i.e. Split into arrays of equal values
mZ{ Map the following function...
Zò2n) Split into arrays of length 2, counting from the end
e.g. [2,2,2,2,2] => [[2], [2,2], [2,2]]
mx Map `Array.sum` over it
}
c Flatten the result
```
Got some idea from [Jonathan Allan's Jelly solution](https://codegolf.stackexchange.com/a/95413/78410).
[Answer]
# [Common Lisp](http://www.clisp.org/), 143 bytes
```
(defun e(l)(if(<(length l)1)'()(if(eq(car l)(cadr l))(cons(*(car l)2)(e(cddr l)))(cons(car l)(e(cdr l))))))
(defun f(l)(reverse(e(reverse l))))
```
[Try it online!](https://tio.run/##bU/BDsIgDL37Fc0SY/EkuOkO/syygS5BNmF63K/PFvDgMl5Ky3sPWlrbh3FZsNPm7UCjFdgbvKHV7j49wAopDhg5/cK28cRQ6jhTMbiAx0wrgRrbLklZyxeYTzStXe5luJfXH@2DJkeukus3z@h7h0EAmsE/mwkmKOZm3hcQ@B1WSQIa8P@oQEEJ5QYbeag3FbVi2amgJqwVeVIlxK2SKoaqLhwr3xkYknCFKoE/9wU "Common Lisp – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 [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 prefix lambda.
```
{∊((⊃⍴⍨2|≢),+⍨⍴⍨∘⌊2÷⍨≢)¨⍵⊂⍨2≠/0,⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR5eGRp1RzaPORZqP2iY/6mrW0X7Uu@JR7xYQ2THjUU@X0eHtIDZQwSGg@NZHXU1ArtGjzgX6BjpAfu3/tEdtEx719j3qm@rpDzTg0HrjR20TgbzgIGcgGeLhGfw/TeFR7xquNAUjHRAyASI4B8rXUbBAFjICciDCQI4FGIGEDA2MgEIQ0tTQCEoYmZqBCaACYx0oMgQjc6AKOAIA "APL (Dyalog Unicode) – Try It Online")
`{`…`}` dfn; `⍵` is right argument
`0,⍵` prepend a zero to the argument
`2≠/` pairwise inequality mask
`⍵⊂⍨` use that to partition (true means begin new partition here) the argument
`(`…`)¨` apply the following tacit function to each run of equal numbers:
`≢` the length of the run
`2÷⍨` let 2 divide that
`⌊` floor that
`∘` then
`⍴⍨` use it to **r**eshape…
`+⍨` the doubled (lit. addition selfie) run
`(`…`),` append that to the following:
`≢` the length of the run
`2|` division remainder when divided by two (1 for odd length runs, 0 for even length runs)
`⊃⍴⍨` use that to reshape the first element of the run
`∊` **e**nlist (flatten)
] |
[Question]
[
Inspired by the bugged output in [*@Carcigenicate*'s Clojure answer](https://codegolf.stackexchange.com/a/109197/52210) for the [Print this diamond](https://codegolf.stackexchange.com/questions/8696/print-this-diamond) challenge.
## Print this exact text:
```
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1234567890
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
```
(From the middle outward in both directions, each digit is separated by one more space than the previous line.)
## Challenge rules:
* There will be no input ([or an empty unused input](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding)).
* Trailing spaces are optional.
* A single trailing new-line is optional.
* Leading spaces or new-lines are not allowed.
* Returning a string-array isn't allowed. You should either output the text, or have a function which returns a single string with correct result.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59 57 56~~ 55 bytes
```
i=8;exec"print(' '*abs(i)).join('1234567890');i-=1;"*17
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwjq1IjVZqaAoM69EQ11BXSsxqVgjU1NTLys/M09D3dDI2MTUzNzC0kBd0zpT19bQWknL0Pz/fwA "Python 2 – Try It Online")
>
> *@Leaky Nun helped golfing this a lot, @Praind Suggested a method to save 1 byte, which I formerly thought of, but forgot to edit, @CotyJohnathanSaxman suggested changing the loop.*
>
>
>
---
# Explanation
* `i=8` - Assigns the value `8` to a variable called `i`.
* `exec"..."*17` - Execute that block of code (`...`) 17 times.
* `print(...)` - Output the result.
* `' '*abs(i)` - Create a String with a space repeated `|i|` times.
* `.join('1234567890')` - Interleave the string created above with `1234567890`, such that `|i|` spaces are inserted between the digits.
* `i-=1` - Decrement `i`, and by executing it 17 times, it reaches `-8`, which creates te repetitive pattern with the help of `abs()`.
[Answer]
# Vim, 35 bytes:
```
i1234567890<esc>qqYP:s/\d/& /g
YGp{q7@q
```
Explanation:
```
i1234567890<esc> " insert '1234567890'
qq " Record the following into register 'q'
Y " Yank a line
P " Paste it above us
:s/\d/& /g " Put a space after each number
Y " Yank this line
G " Move the end of the buffer
p " Paste the line
{ " Move the beginning of the buffer
q " Stop recording
7@q " Call macro 'q' 7 times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
```
17F9ÝÀN8αð×ý,
```
[Try it online!](https://tio.run/##AR0A4v8wNWFiMWX//zE3RjnDncOATjjOscOww5fDvSz//w "05AB1E – Try It Online")
**Explanation**
```
17F # for N in [0 ... 16] do
9Ý # push [0 ... 9]
À # rotate left
N8α # compute the absolute difference between N and 8
ð× # push that many spaces
ý # merge the list of digits with the space string as separator
, # print
```
[Answer]
# C64 ASM, 358 bytes (102 bytes compiled with basicstub)
This is the closest I could get due to obvious limitations:
[![C64](https://i.stack.imgur.com/GxFIX.png)](https://i.stack.imgur.com/GxFIX.png)
```
jsr $E544
lda #9
sta $FD
nl1: jsr dl
jsr il
dec $FD
bne nl1
inc $FD
nl2: ldy $FD
cpy #9
bne nt1
bl: jmp bl
nt1: iny
sty $FD
jsr dl
jsr il
jmp nl2
dl: clc
ldx #$31
ldy #0
lp: txa
sm: sta $0400, y
inx
cpx #$31
bne c1
rts
c1: cpx #$3A
bne nt2
ldx #$30
clc
nt2: tya
adc $FD
cmp #40
bcc c2
rts
c2: tay
jmp lp
il: lda sm+1
adc #39
bcc nc
inc sm+2
nc: sta sm+1
rts
```
(Could probably be optimized quite a bit)
[Answer]
# TSQL, 220 148 bytes
Improvement posted by ZLK:
```
DECLARE @ VARCHAR(MAX)=''SELECT TOP 17@+=REPLACE('1@2@3@4@5@6@7@8@9@0','@',SPACE(ABS(9-RANK()OVER(ORDER BY object_id))))+'
'FROM sys.objects PRINT @
```
Output:
```
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1234567890
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
```
[Answer]
# [Haskell](https://www.haskell.org/), 58 55 bytes
```
unlines["1234567890">>=(:(' '<$[1..abs n]))|n<-[-8..8]]
```
[Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8tVYRvzvzQvJzMvtThaydDI2MTUzNzC0kDJzs5Ww0pDXUHdRiXaUE8vMalYIS9WU7Mmz0Y3WtdCT88iNvZ/bmJmnoKtQkFpSXBJkU@eQsV/AA "Haskell – Try It Online")
This is basically @nimi 's solution :)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 22 bytes
```
↑∊¨(1+|¯9+⍳17)↑¨¨⊂1⌽⎕D
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdqRRItU181NF1aIWGoXbNofWW2o96NxuaawJFD604tOJRV5Pho569j/qmuoDU/wdqAAA "APL (Dyalog Unicode) – Try It Online")
`⎕D` **D**igits from zero to nine
`1⌽` rotate one step right (puts zero at end)
`⊂` enclose (to treat as unit)
`(`…`)↑¨¨` for *each* of these numbers, take that many characters from *each* of the letters:
`⍳17` one through seventeen
`¯9+` subtract nine
`|` find the absolute values
`1+` add one
`∊¨` enlist (flatten) each
`↑` change one layer of depth into a level of rank (matrify)
[Answer]
# [Java 11 (JDK)](http://jdk.java.net/), 98 bytes
```
o->{for(int i=-9;++i<9;)System.out.println("".join(" ".repeat(i<0?-i:i),"1234567890".split("")));}
```
[Try it online!](https://tio.run/##LU7LTsMwELz3K1Y@xSqxypuQtBwQR8ShR9SD67pljWNb9rqAqnx7cAp7GWkeO2PkUdZm9zmGvLWoQFmZErxKdHCaAfyziSQVOHrcQV@0ak0R3eF9AzIeEgf6iP4rwcu30oHQ/2UBTHkuMqEV@@zUJIhn71LudezetkYrWkFcjr5enfY@VugIcFk37XyOXdPy9U8i3QufSYRSR9ZVjAnjSz8DJqIOWlKF3eKpxkfkF@zy6vrm9u7@oVkwkYJFKn7OeTuMcL72vCoKqaadlcvW8okbZsP4Cw "Java (JDK) – Try It Online")
* -14 bytes by switching to JDK 11, which now has a native `String::repeat`.
# Previous answer ([Java (OpenJDK 8)](http://openjdk.java.net/)), ~~113~~ 112 bytes
```
o->{for(int i=-9;++i<9;)System.out.printf("".join("%1$"+(i<0?-i:i>0?i:"")+"s","1234567890".split(""))+"%n","");}
```
[Try it online!](https://tio.run/##LY7LasMwEEX3@YpBNGDhWjh9O3acRemydJFl6EJR7HRcWTLSKG0J/nZXSTubgXu4nNvJo8zs0Jhu/zkNYadRgdLSe3iVaOA0A/hPPUmK72hxD31kyYYcmsP2HaQ7eA704eyXh5dv1QyE9q8L0EWBCIRatMGoMxDP1vjQN65623WNohrcarJZfWqtS9AQ4CoryjTFqij55sdT0wsbSAxRR23CmOhs1LP54oqlCVb5OsMl1vkal4zxlHl2zRY3t3f3D49PRc6EHzRSrPHI5iZCxstxgsuVl41OSHVenZigNT9n42ycfgE "Java (OpenJDK 8) – Try It Online")
### Explanations
I'm basically constructing the following `String` 17 times (`N` is a variable, not an actual value):
```
"1%1$Ns2%1$Ns3%1$Ns4%1$Ns5%1$Ns6%1$Ns7%1$Ns8%1$Ns9%1$Ns0%n"
```
It's all the expected digits, joined by `%1$Ns` where `N` is the number of spaces between each digit.
`%1$Ns` basically means "take the first argument and pad it until length is at least `N`". Also, `%1$0s` is not supported so a special case `%1$s` is made for `0`.
Finally, I format-print that string using a single argument: `""`, so the formatter reuses always the same empty string, padding it with spaces as needed.
### Saves
* 1 byte thanks to Kevin Cruijssen
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-R`, ~~19~~ ~~18~~ ~~16~~ ~~14~~ 13 bytes
```
Aõ%A
£qYçÃÔÅê
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=QfUlQQqjcVnnw3cgxeo=&input=LVI=) or [try it online](https://tio.run/##y0osKPn/3/HwVlVHrkOLCyMPLz/cXK5wuPXwqv//dYMA)
---
## Explanation
```
A :10
õ :Range [1,10]
%A :Modulo each by 10
\n :Assign to variable U
£ :Map each element at 0-based index Y
q : Join U with
Yç : Space repeated Y times
à :End map
Ô :Reverse
Å :Slice off first element
ê :Mirror
:Implicitly join with newlines and output
```
[Answer]
# Clojure, ~~126~~ 99 bytes
-27 by fixing a couple of dumb mistakes. The outer use of `a` wasn't necessary, so I was able to get rid of `a` altogether and just write `apply str` once. That also allowed me to use a function macro for the main function, which saved some bytes. I also inlined the call to `Math/abs` instead of rebinding `n-spaces`.
Basically a Clojure port of @Mr.Xcoder's Python idea. In retrospect, I should have used the `abs`/`range` method for the diamond challenge originally, but I then I may not have produced the bugged output!
Pretty simple. Joins the number string with a number of spaces that depends on the current row.
```
#(doseq[n(range -8 9)](println(clojure.string/join(apply str(repeat (Math/abs n)\ ))"1234567890")))
```
---
```
(defn bugged []
(doseq [n-spaces (range -8 9)]
(println
(clojure.string/join
; "String multiplication"
(apply str
(repeat (Math/abs n-spaces) \space))
"1234567890"))))
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~58~~ ~~57~~ 54 bytes
```
i=8
while i+9:print(*'1234567890',sep=' '*abs(i));i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgqs8IzMnVSFT29KqoCgzr0RDS93QyNjE1MzcwtJAXac4tcBWXUFdKzGpWCNTU9M6U9fW8P9/AA "Python 3 – Try It Online")
(thanks to @flornquake for the last three bytes; I completely forgot using `sep` to save vs. `.join`)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 12 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
9{SUē↕∑}¹№╬«
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=OSU3QlNVJXUwMTEzJXUyMTk1JXUyMjExJTdEJUI5JXUyMTE2JXUyNTZDJUFC)
Explanation:
```
9{ } 9 times do
SU push "1234567890"
ē push e, predefined with the input, which defaults to 0, and then increase it
↕ get that many spaces
∑ join the string of digits with those spaces
¹ collect the results in an array
№ reverse the array vertically
ή palindromize vertically with 1 overlap
```
[Answer]
## JavaScript(ES2017), 83 73 72 68 bytes
Thanks [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for saving 10 bytes.
Thanks [Craig](https://codegolf.stackexchange.com/users/68610/craig-ayre) for saving 1 byte.
Thanks [arcs](https://codegolf.stackexchange.com/users/70879/arcs) for saving 4 bytes.
```
for(i=-9,a="";i++<8;)a+=[...`1234567890
`].join("".padEnd(i<0?-i:i))
```
```
for(i=-9,a="";i++<8;)a+=[...`1234567890
`].join("".padEnd(i<0?-i:i))
console.log(a);
```
```
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row:after { display: none !important; }
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~30~~ ~~29~~ 28 bytes
```
Ị↺{∧≜;Ṣj₍g;?↔zcc}ᶠ⁹↔;XcP↔Pẉᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hurkdtu6ofdSx/1DnH@uHORVmPmnrTre0ftU2pSk6ufbhtwaPGnUCOdURyAJAKqHu4s738////AA "Brachylog – Try It Online")
*Saved one byte thanks to Leaky Nun*.
### Explanation
```
Ị↺ The string "1234567890"
{ }ᶠ⁹ Find the first 9 outputs of:
∧≜ Take an integer
;Ṣj₍ Juxtapose " " that number of times
g;?↔z Zip that string of spaces with "1234567890"
cc Concatenate twice into one string
↔ Reverse the resuling list
;XcP↔P Palindromize the list (concatenate X to it into the list P,
P reversed is still P)
ẉᵐ Map writeln
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
F⁹⪫⁺…I¹:⟦0¶⟧× ι‖B↑
```
[Try it online!](https://tio.run/##DcaxCsIwEADQ3a84brqDFnS0ndTNSYpO6hDSiwZiIskp@PVnl8fzT1d9cckslAq0ZTjVmJWOJWbazTNNLj@EDq4pbbgDHHDxiutbxvuyc3xJIwTsIDLzuJokJPG6/6hKDelHw@XNo5n1X@tb@gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⁹ Repeat 9 times (i = loop variable)
⪫ Join
⁺ Concatentate
…I¹: All the characters from str(1) below ":" (i.e. to "9") as a list
⟦0¶⟧ A list whose element is the string "0\n"
× ι With i spaces
‖B↑ Reflect everything upwards but without duplicating the top line
```
Note: `Cast(1)` takes the same number of bytes because `"1"` would need a separator before `":"` (which as it happens the deverbosifier fails to insert).
[Answer]
# [R](https://cran.r-project.org/), 108 bytes
```
for(i in abs(-8:8))cat(paste0(el(strsplit("1234567890","")),paste(rep(" ",i),collapse=""),collapse=""),"\n")
```
Just pasting and collapsing the strings.
[Try it online!](http://www.r-fiddle.org/#/fiddle?id=1qEEqjlg)
Edit: thanks for Challenger5 for pointing out a problem. Fixed it now.
Edit 2: saved a byte thanks to bouncyball.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 13 bytes
1 byte thanks to Mnemonic.
```
V17j*da8NeMST
```
[Try it online!](http://pyth.herokuapp.com/?code=V17j%2ada8NeMST&debug=0)
[Answer]
## Java 8, 235 234 206 163 bytes
```
interface A{static void main(String[]a){for(int i=-8;i<9;i++){String s="";for(int j=1,k;j<10;j++){s+=j;for(k=0;k<(i>0?i:-i);k++)s+=" ";}System.out.println(s+0);}}}
```
**Update** : -28 bytes thanks to Leaky Nun !
**Update 2** : -43 bytes thanks to Leaky Nun again !
Ungolfed :
```
interface A {
static void main(String[] a) {
for (int i = -8; i < 9; i++) {
String s = "";
for (int j = 1, k; j < 10; j++) {
s += j;
for (k = 0; k < (i > 0 ? i : -i); k++)
s += " ";
}
System.out.println(s + 0);
}
}
}
```
[Try it online](https://tio.run/##XY5BCsMgEEWvIq6UNCHZFSYWeoYsSxeSaBltTIg2UMSzpzali3Y5b/7M@0auspxm5cxgtw1dUIuWvSLn6IMM2JN1woGMEh3rwoLudrl6HjU7ckg/CZZvCfL4SREvKAU9LTs2ojlYMG1TgykKHn0hzL60ogbbIthMM6SEQuqePqixmh6hmvOrcHfMF/WfTn912csB83iq37WwbDjsLKW0bS8)
**EDIT :** The code earlier was wrong ! Made a mistake while golfing the code, it should work as intended now !
[Answer]
## [Husk](https://github.com/barbuz/Husk), 21 bytes
```
mΣṪ`:§+↔tḣR8' ṁs`:0ḣ9
```
This is a full program that prints to STDOUT.
[Try it online!](https://tio.run/##yygtzv7/P/fc4oc7VyVYHVqu/ahtSsnDHYuDLNQVHu5sLE6wMgDyLP//BwA "Husk – Try It Online")
There are lots of trailing spaces.
## Explanation
Husk is still missing lots of essential stuff like a two-argument range function, so parts of this solution are a little hacky.
```
mΣṪ`:§+↔tḣR8' ṁs`:0ḣ9
ṁs`:0ḣ9 This part evaluates to the string "1234567890".
ḣ9 Range from 1 to 9.
`:0 Append 0.
ṁs Convert each number to string and concatenate.
§+↔tḣR8' This part evaluates to a list like [" "," ",""," "," "]
but with 17 elements instead of 5.
R8' A string of 8 spaces.
ḣ Take prefixes.
§+ Concatenate
↔ the reversal and
t tail of the prefix list, palindromizing it.
Ṫ Take outer product of the two lists
`: with respect to flipped prepeding.
This prepends each digit to each string of spaces.
mΣ Map concatenation over the results, computing the rows.
Implicitly join with newlines and print.
```
[Answer]
# [T-SQL](https://en.wikipedia.org/wiki/Transact-SQL) 145 152 bytes
```
DECLARE @ VARCHAR(MAX)=''SELECT TOP 17@+=REPLACE('1x2x3x4x5x6x7x8x9x0','x',SPACE(ABS(number-8)))+'
'FROM master..spt_values WHERE type='P'PRINT @
```
**Updated** to use:
* `master..spt_values` to generate numbers (`WHERE type = 'P'`, these are always consecutive, starting at 0)
* @ZLK's `TOP 17` idea
* PRINT (to obey the rules - no stringlists)
* @JanDrozen's great idea of including the carriage return in the string (I counted that as just one byte - Windows CRLF what?)
* Idea of @Bridge to use just @ for variable name - all these tricks!!
Results:
```
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1234567890
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9 0
```
(Thanks @JanDrozen for the REPLACE idea)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
8ŒRA⁶ẋØDṙ1¤jЀY
```
[Try it online!](https://tio.run/##ASQA2/9qZWxsef//OMWSUkHigbbhuovDmEThuZkxwqRqw5DigqxZ//8 "Jelly – Try It Online")
[Answer]
# Mathematica, 92 bytes
```
Column@Join[Reverse@(s=Row/@Table[Riffle[Range@10~Mod~10,""<>Table[" ",i]],{i,0,8}]),Rest@s]
```
[Try it online](https://sandbox.open.wolframcloud.com/app/objects/)
copy/paste code with ctrl-v
press shift+enter to run
[Answer]
# C, 97 bytes
```
i=-9;main(j){for(;++i<9;putchar(10))for(j=0;++j<11;printf(" "+8-abs(i)))putchar(48+j%10);}
```
Your compiler will probably complain a *lot* about this code; mine threw 7 warnings of 4 different types. Might improve the code later.
[Try it online!](https://tio.run/##NYtBCoAgEAC/EkGwiwgKHZStx5hQrZSF1Sl6uxXUHGcYL/3k4pAzt9LS7DhCwLNfEpAQ3Fhaj92PLoFWiK8OrXpKaLSmNXHceyiLj1IY6boNGBH/rTYiVM9LV843 "C (clang) – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā9{SUčf@*∑Κ}╬Æ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxOSU3QlNVJXUwMTBEZkAqJXUyMjExJXUwMzlBJTdEJXUyNTZDJUM2)
Explanation:
```
ā push an empty array
9{ } 9 times do
SU push "1234567890"
č chop into characters
f@* get current iteration (0-based) amount of spaces
∑ join with that
Κ prepend this to the array
Β palindromize vertically with 1 overlap
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 11 bytes
```
8╤{± *♂r╫up
```
[Try it online!](https://tio.run/##y00syUjPz0n7/9/i0dQl1Yc2Kmg9mtlU9Gjq6tKC//8B "MathGolf – Try It Online")
## Explanation
```
8 push 8
╤ range(-n, n+1)
{ for each element in range:
± absolute value
space character
* multiply space character x number of times
♂r push 10, create range
╫ left-rotate list (0 goes to the end)
u join with separator (joins using x spaces)
p print with newline
```
Has a trailing newline in the end from printing. @ovs found a mistake in the original code that could be fixed by switching the first `9` to an `8`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 20 19 18 bytes
```
F⁹«F…¹χ⁺κ… ι0⸿»‖B↑
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nmWPGnceWg2iG5Yd2nm@/VHjrnO7gGyFczsNHu3Yf2j3o4Zp7/csetQ28f9/AA "Charcoal – Try It Online")
Link to [the verbose version](https://tio.run/##S85ILErOT8z5/z8tv0hBw1KTq5pLQQHMDkrMS0/VMNQxNNDUBIopKAQUZeaVaDimpGhk6yhAZJUUlHQUMjU1Na25YPJKBjFFSkB@LVdQalpOanKJU2lJSWpRWk6lhlVogab1////dcv@6xbnAAA). Basically I create the lower part of the drawing and then reflect the text up.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 21 bytes
```
A,(+aH*ee{:\8-zS**n}/
```
[Try it online!](https://tio.run/##S85KzP3/31FHQzvRQys1tdoqxkK3KlhLK69W//9/AA "CJam – Try It Online")
### Explanation
```
A, e# Get [0 1 2 ... 9].
(+ e# Rotate the 0 to the end.
aH* e# Wrap in an array and repeat 17 times.
ee e# Enumerate. This pairs each copy of the array with its index in
e# the list.
{ e# For each [index array] pair...
:\ e# Unwrap the pair and swap its order.
8-z e# Get the absolute difference of the index from 8.
S* e# Get a string of that many spaces.
* e# Riffle the list of digits with the string of spaces.
n e# Print it with a trailing linefeed.
}/
```
[Answer]
## Batch, 163 bytes
```
@set s=1 2 3 4 5 6 7 8 9 0
@set t=
@for %%l in (9 7)do @for /l %%i in (1,1,%%l)do @call:%%l
:7
@set t= %t%
:9
@set t=%t:~1%
@call echo %%s: =%t%%%
```
Note: First line ends in 9 spaces. Explanation: Uses creative line numbering! The first loop needs to run 9 times and delete a space each time, while the second loop needs to run 8 times and add a space each time. The former is achieved by running it 7 times and falling through for the 8th time, while the latter is achieved by adding two spaces and falling through to delete one of them again.
[Answer]
# bash (and shell utils), 69 bytes
```
for i in `seq 9 -1 1;seq 2 9`;do seq -f%-$i.f 9|tr -d \\n;echo 0;done
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 76 bytes
```
f(x,y){for(y=-9;++y<9;puts(""))for(x=10;x++;printf("%-*d",abs(y)+1,x%=10));}
```
[Try it online!](https://tio.run/##FcpBCoAgEADAvwjCbquQR9l8TBlGlxI1UKK3W12H8XrzvvcAVTW8w5mgOW2ZqE2W41UyCIH4e3Vm5ErEMe1HCSCkHlah5iVDQzKqyi8g8tP7Cw "C (gcc) – Try It Online")
It outputs some trailing spaces, which is supposed to be OK.
It prints the numbers using left-justified fields of dynamic length - that's what the format string `%-*d` is for.
The inner loop has some funny initialization (starts from 10; any multiple of 10 would be fine) to "simplify" its termination condition.
] |
[Question]
[
Some `sleep` commands implement a delay of an integer number of seconds. However, 2³² seconds is only about 100 years. Bug! What if you need a larger delay?
Make a program or a function which waits for 1000 years, with an error of less than ±10%. Because it's too time-consuming to test, please explain how/why your solution works! (unless it's somehow obvious)
You don't need to worry about wasting CPU power - it can be a busy-loop. Assume that nothing special happens while your program waits - no hardware errors or power failures, and the computer's clock magically continues running (even when it's on battery power).
What the solution should do after the sleep is finished:
* If it's a function: return to caller
* If it's a program: terminate (with or without error) or do something observable by user (e.g. display a message or play a sound)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~40 36 32 29 26~~ 24 bytes
```
i;f(){--i&&f(sleep(7));}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOk1Ds1pXN1NNLU2jOCc1tUDDXFPTuvZ/bmJmHlAGKAvkAAA "C (gcc) – Try It Online")
-3 thanks to @gastropner.
-1 recursive approach thanks to @AZTECCO.
4294967295\*7/86400/365.25 ~ 952.69
[Answer]
# [Python 3](https://docs.python.org/3/) (Excluding CPython on Windows), 28 bytes
```
import time
time.sleep(3e10)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVC0ToFeekphZoGKcaGmj@/w8A "Python 3 – Try It Online") (Remember to put something in your will so future generations can check that it ended on time.)
`time.sleep(seconds)` takes either an int or a float.
`1000*365.2422*24*60*60/3e10 == 1.051897536` which is an error of less than 10%.
[Answer]
# bash, 26 24 bytes
I think part of the challenge here is to not have a signed 32 bit overflow, so:
```
ping -i86400 -c365243 t.co
```
The idea here is to make 1000 years of pings (365243), once per day (86400).
"t.co" is simply a four character internet hostname (in this case, a link shortener). If your local host table has a one character hostname, you can subtract 3 bytes.
Edit: [corvus-192](https://codegolf.stackexchange.com/users/46901/corvus-192) points out that country code ai resolves as a host, so you can write:
```
ping -i86400 -c365243 ai
```
As this will should work for anyone, I will accept this. Saved 2 bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~6~~ 5 bytes
```
35WY.
```
This waits for 34359738368 seconds, which is a little more than 1089 years and a half.
[Don't try it online!](https://tio.run/##y00syfn/39g0PFLv/38A "MATL – Try It Online")
### Explanation
```
35 % Push 35
W % 2 raised to that. Gives 34359738368
Y. % Pause for that many seconds
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 10 bytes
```
sleep 3e10
```
[Try it online!](https://tio.run/##KypNqvz/vzgnNbVAwTjV0OD/fwA "Ruby – Try It Online")
There are approximately \$3\*10^{10}\$ seconds in a thousand years.
[Answer]
## 6502 Machine Code on an Apple II, 10 9 bytes
Code is actually platform-independent, other than it relies on the Apple's clock speed of 1.023 MHz for timing.
Code starts at address 0x0000:
`0000: A2 CA F6 44 F0 FB D0 F8 F7`
Saved an additional byte. Details are below original answer.
### Original answer:
Code starts at address 0x0059:
`0059: A2 08 F6 60 D0 FA CA D0 F9 F5`
Disassembly:
```
loop1: 0059- A2 nn LDX #$nn ; 2 cyc
loop2: 005B- F6 60 INC $60,X ; 6 cyc
005D- D0 FA BNE loop1 ; 2-3 cyc
005F- CA DEX ; 2 cyc
0060- D0 F9 BNE loop2 ; 2-3 cyc
0062- pp DB $pp ; data byte
```
This is a fairly simple routine that increments a multi-byte counter. When the counter rolls over, the last branch instruction gets modified so that it points to an RTS instruction, which provides the exit for the routine.
loop1 is taken for each increment of the counter and takes 11 cycles per iteration. loop2 is taken for each byte carried over and takes 13 cycles per iteration. So if we increment the counter N times, we spend approximately:
11\*N + 13\*(1/256 + 1/(256^2) + 1/(256^3) + ...)\*N
= 11.05\*N cycles
1000 years is 365242\*86400\*1023000 = 32282717702400000 cycles
So we need N = 2921512914244345 +/- 10%
Or a range of 2629361622819911 - 3213664205668779
= 0x095763F583A447 - 0x0B6ACF816801AB
In the code above, set pp = 0xF5 and nn = 0x08.
This gives us a 7-byte counter in memory locations 0x62-0x68
(with MSB at lowest address, i.e. big endian). Only location 0x62
is initialized, so our starting counter value could be anywhere
from 0xF5000000000000 to 0xF5FFFFFFFFFFFF.
We'll increment the counter until it rolls over to 0, which
will cause the byte at 0x61 to increment by 1, which happens
to be the branch target for loop2. On the first byte carry
after rollover-- when the counter hits 0x100-- we'll hit the
modified branch instruction for the first time. This will take
us to address 0x5C (loop2+1). The 0x60 byte there is the opcode
for "Return from Subroutine" (RTS) which provides our exit.
So our total loop count is between, 0x0A000000000101 and
0x0B000000000100, which is a subset of the range we calculated
which gives us the necessary number of cycles +/- 10%.
Now that we have the exact starting and ending counter values,
we could go back and calculate the exact cycle counts, but given
how much margin there is, I'm willing to hand-wave that part.
You can actually test it out with smaller values of nn. For example nn of 4 will pause for several seconds.
### 9-byte answer:
```
0000- A2 CA LDX #$CA ; 2 cyc
0002- F6 44 INC $44,X ; 6 cyc
0004- F0 FB BEQ $0001 ; 2-3 cyc (rollover)
0006- D0 F8 BNE $0000 ; 2-3 cyc (non-rollover)
0008- F7 DB $F7 ; data byte
```
Saved one byte by folding the DEX opcode into the
argument for LDX.
Instead of 11.05 cycles, each counter increment is now
13 + 11\*(1/256 + 1/(256^2) + ...) = 13.043 cycles.
Now we need 2475073064976549 +/- 10% iterations,
or a range of 0x7E9F591BF7A2E - 0x9AC2C23EA071C.
So now we initialize the 7-byte counter to something
between 0xF7000000000000 and 0xF7FFFFFFFFFFFF. This ends
up giving between 0x08000000000001 and 0x09000000000000
loop iterations, which is within the +/-10% needed.
When the counter rolls over to 0, the last branch
gets modified to jump to $0001, which leads to an increment
of the BNE opcode itself (to a CMP instruction, which
for our purpose is effectively a no-op). Code then falls
through to $0008, which now contains a 0 (because of counter
rollover). A 0 byte is a BRK instruction, which drops you
back to the system monitor, ending the routine.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ ~~32~~ ~~24~~ ~~21~~ 19 bytes
```
1..3e4|%{sleep 1mb}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPzzjVpEa1ujgnNbVAwTA3qfb/fwA "PowerShell – Try It Online")
Strangely, the maximum seconds value for `Start-Sleep` is `2147483`. No, I don't know why it's such an odd value. That works out to a little over `2` megabytes (`2097152`). `1mb * 30000 / 86400 / 365.25` is `996.821051030497`, so a little under 1000 years. I could get more exact using a different value than `3e4`, but this is within the allowed margin and I'm lazy.
*Saved 3 bytes thanks to ceilingcat.*
*Saved 8 bytes thanks to Jeff Zeitlin.*
*Saved 3 bytes thanks to Neil.*
*Saved 2 bytes thanks to Mark Henderson and Nahuel Fouilleul.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
27;°.W
```
Inspired by [the other answer in 05AB1E](https://codegolf.stackexchange.com/a/196965/25315).
Waits for 1027/2 milliseconds, or about [1002 years](https://www.google.co.il/search?q=convert+31622776601683+milliseconds+to+years).
Explanation:
```
27 push the number 27
; divide by 2
° replace X by 10 to the power of X
.W wait that number of milliseconds
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fyNz60Aa98P//AQ "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
32œS$ȷ9¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/Y6OjkYJUT2y0PLfz/HwA "Jelly – Try It Online")
A niladic link which waits for 32 seconds 1 billion times. 32,000,000,000 is within 10% of 31,557,600,000 seconds which is 1,000 years (ignoring leap seconds and ignoring the fact that centuries indivisible by 400 are not leap years).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
F³³RXφ⁴
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw9hYUyEoNa0otThDIyC/PLVII01HwVBT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code with a speed up factor of 1e9 (obtained by changing the ⁴ into a a ¹) so that it doesn't time on TIO. Explanation:
```
F³³
```
Repeat 33 times.
```
RXφ⁴
```
Refresh the screen, but delay 1000⁴ milliseconds between refreshes.
Although there are 33 refreshes, there are only 32 intervals, so the total delay is 32000000000000 milliseconds or approximately 1015 years.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 23 bytes
```
v->Thread.sleep(7L<<42)
```
[Try it online!](https://tio.run/##ZU6xDoIwEN39ihthwMGYOIBubjphXIzDWU4o1tK0pZoYvr0WqJPD5V3evXfvtegwa6uHZwKNgSNyCZ8FAJeW9B0ZQSmIFOmJBXAdr8CMVHIeV5eCbXT3MrB/M1KWdzIPwiGM6m@CMzAWbYDJ@Azvk9JqLuvLFVDX5t8eg36xJuIWvMt2p0YTVsu5wOZQFOtV6vPJEIXxJnsh0rnJ4L8 "Java (JDK) – Try It Online")
It's hard to find a short way to write a number in Java. `Thread.sleep` only accepts a `long` number of milliseconds. So the standard answer `3e10` doesn't work because it's a double. Casting it to a long would be the appropriate action. But it would still be 1000 too small. So enter `3e13` which is closer. But fortunately, `7L<<42` is `30,786,325,577,728`, which is close to the actual count of 1000 years, and is a `long` without cast, so 4 bytes shorter than `(long)3e13`.
## Credits
* -4 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) by replacing `(long)3e13` with `7L<<42`.
[Answer]
# [Batch](https://en.wikipedia.org/wiki/Batch_file), ~~41~~ 25 bytes
-8 bytes thanks to AdmBorkBork
-6 bytes thanks to ceilingcat
-2 bytes thanks to inspiration from Neil
```
ping 1 -n 31556952000>nul
```
Using [31,556,952](https://stackoverflow.com/q/9141871/4475014) seconds / year and a (default) 1 second delay between each ping, this will wait 1000 years before returning nothing.
Note that `ping 1` results in failure but it'll fail 31 billion times so that still works.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~9~~ 8 [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 thanks to Eric Towers.
Full program. This works by observing that $$\sum\_{n=1}^{8^6}n=3.44×10^{10}\approx3.16×10^{10}$$which is the number of seconds in a thousand years.
```
⎕dl¨⍳8*6
```
[Don't try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1JScQyse9W620DL7/x8A "APL (Dyalog Unicode) – Try It Online")
`8*6` \$8^6=262144\$
`⍳` **ɩ**ntegers until that
`⎕dl¨` **d**e**l**ay each of those many seconds
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes
```
Pause[2^35]
```
2 to the 35th power is about 8.9% greater than 31,556,926,000.
[Answer]
# T-SQL, 56 bytes
```
DECLARE @ INT=0a:WAITFOR TIME'9:0'SET @+=1IF @<4E5GOTO a
```
* The SQL [`WAITFOR`](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql?view=sql-server-ver15) command is limited to 24 hours, so it has to go in a loop.
* `WAITFOR` has two options: `DELAY` that waits a certain length of time, or `TIME` which waits until a certain time of day. Turns out `WAITFOR TIME'9:0'` (which will pause until 9am the following day) is a couple of bytes shorter than `WAITFOR DELAY'24:0'`.
* Using a `GOTO` loop is shorter than a `WHILE` loop.
* I'm looping `4E5` times (400,000), which is within 10% of the 10-year (365,242 day) goal.
* If I start it today, this would complete in February, 3115
[Answer]
# [R](https://www.r-project.org/), 24 bytes
```
sapply(1:25e4,Sys.sleep)
```
[Try it online!](https://tio.run/##K/r/vzixoCCnUsPQysg01UQnuLJYrzgnNbVA8/9/AA "R – Try It Online")
A solid starter, feels like there's optimisation to be had with a different function & number combo. This sleeps for 1s, then 2s, then 3s, then 4s... up to 250000s, at which point it's been running for about 990 years and outputs a list of 250k empty elements.
[Answer]
# [Lua](https://www.lua.org/), 38 bytes
```
t=os.time;o=t()+2^35while t()<o do end
```
[Try it online!](https://tio.run/##yylN/P@/xDa/WK8kMzfVOt@2RENT2yjO2LQ8IzMnVQHIs8lXSMlXSM1L@f8fAA "Lua – Try It Online")
Being ANSI C compliant, Lua does not implement any sleep functions, so we have to make one ourselves. Oh, and make sure to keep the dust off that One Thousand Year Computer, we're busy waiting.
# [Lua](https://www.lua.org/), 38 bytes
```
t=os.time;o=t()+2^35repeat until o<t()
```
[Try it online!](https://tio.run/##yylN/P@/xDa/WK8kMzfVOt@2RENT2yjO2LQotSA1sUShNK8kM0ch3wYo/P8/AA "Lua – Try It Online")
Same thing, different loop. Tried to see if I can save some bytes, but nope.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 59 bytes
```
b=>{for(var d=DateTime.Now.AddYears(999);d>DateTime.Now;);}
```
Can be tested by replacing `AddYears()` with `AddSeconds()`
[Try it online!](https://tio.run/##bcqxCgIxDADQ/b6i3NQiHq6ltnCgm7goiGNsImSwhTToIH57XU9wfi@3dW7c56xcy5aLJgOx32J636vYJ4jBuAOlMz9oOtbXNCNeCaRZ770LmJYYXPj0MFyElQ5cyI4nBVFCA2rG1bK6MIDduJ@8L/i/9i8 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
## Mumps (M): 7 Bytes
```
H 9**11
```
Mumps likes single-letter commands & big numbers... H(ang) sleeps for ## of seconds; 9 to the 11th power gives 31381059609 seconds, which is almost 0.6% low for 1000 years; well within the margin of error.
Keeping with the 7 byte code length, I tested "power of 9" sleep times on 2 different Mumps implementations; the largest power of 9 on YottaDB/GT.M I can find without numeric overflow would be:
```
H 9**49
```
which gives a sleep time of just over 1,814 *decillion* millennia. InterSystems' Cache doesn't overflow and can go to:
```
H 9**99
```
which gives 9.352x1083 millennia. That's quite a nap in 7 bytes!
[Answer]
# [gbz80](https://rgbds.gbdev.io/docs/v0.5.2/gbz80.7) [machine code](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html) program, 40 (6 + 34) bytes
VBlank handler (put at 0x40)
```
CD 5A 01 F1 FB 76
```
Program after entrypoint (put at 0x150)
```
01 B7 02 21 FF FF 36 01 FB 76 2D 20 14 25 20 11
1D 20 0E 15 20 0B 0D 20 08 05 20 05 2F E0 21 E0
23 C9
```
Runs a timer that decrements every frame. At the Game Boy's frame rate, one thousand years is ~1,884,804,967,414 (0x1B6D7216BF6) frames (with a frame rate of 59.727500569606 fps and the assumption of 24 hours per day and 365.24 days per year). This program's timer runs for 0x1B6\*\*\*\*FEFE frames. The stars are that the middle registers aren't initialized, and the bottom registers are used for an optimization, but the three most significant hex figures are correct and therefore the timer will be well within tolerance.
After the thousand years, the noise channel plays for a short while, and there will be a looping timer that will play the sound every ~149,339 years. Those are some good AAs.
Maybe it could be shorter if you want to cycle count instead of VBlank count.
Source:
```
section "VBlankInterrupt", ROM0[$40]
call VBlankHandled
pop af ; get rid of pushed return address
ei ; enable interrupts
db $76 ; directly encoded halt, one byte saved over "halt"
; ei and halt interact buggily, but it doesn't matter here because we discard the return address.
section "Header", ROM0[$100]
jr AfterEntryPoint ; thing for every Game Boy program, shouldn't count
ds $150 - @, 0 ; Make room for the header
AfterEntryPoint:
ld bc, $02B7 ; we have to set b one higher, because we decrement then check for zero. also did c because no reason not to and more accuracy
; d and e will be set to their startup values.
ld hl, $FFFF ; double-use: part of timer and as a pointer
ld [hl], $01 ; enable v-blank interrupt only
ei
db $76 ; necessary halt to prevent stack underflow from return, again the return address is discarded so ei halt bug isn't a worry
VBlankHandled:
dec l
jr nz, .backToSleep
dec h
jr nz, .backToSleep
dec e
jr nz, .backToSleep
dec d
jr nz, .backToSleep
dec c
jr nz, .backToSleep
dec b
jr nz, .backToSleep
.madeItOut:
cpl ; invert a, which is 01 from the pop
ldh [$21], a
ldh [$23], a ; this and previous turn on and up the noise channel, which briefly plays because of time limit not being turned off
.backToSleep:
ret
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
VT.dC"¼€
```
[Try it online!](https://tio.run/##K6gsyfj/PyxEL8VZ6dAeSeFDDf//AwA "Pyth – Try It Online")
There are [exactly 31,557,600 seconds in the Julian astronomical year.](https://en.wikipedia.org/wiki/Year), totalling 31,557,600,000 seconds in 1000 years. 2^32 is about a tenth of this, so we just wait for 3,155,760,000 seconds ten times.
Note that `€` is a blank codepoint in the TIO, not sure why it translates to this on SE
[Here](https://tio.run/##K6gsyfj/31np0B5J4UMNSv//AwA "Pyth – Try It Online") you can see that `C"¼€` is equal to 3,155,760,000
[And here](https://tio.run/##K6gsyfj/P8xIL8VZiVvp/38A "Pyth – Try It Online") is an example that waits for only 22 seconds using a similar method
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
.dC"XúÃ
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/FWYk94vCuw83//wMA "Pyth – Try It Online")
Alternatively, this one just uses `C"XúÃ` for 31,557,600,000. I thought it was more in line with the spirit of the challenge to have a 2^32 limit, though
---
The average length of a sidereal year, however, is 365.256363004 days or around 31,558,149.763 seconds, giving us a total of ~31,558,149,764 seconds in 1000 years. In this case, the more accurate solution would be
[This:](https://tio.run/##K6gsyfj/PyxEL8VZ6dAeycOrHP7/BwA) `VT.dC"¼ê@`
[This:](https://tio.run/##K6gsyfj/Xy/FWYk9klntUPP//wA)`.dC"Y&ƒ`(1 byte longer than Julian solution)
[Answer]
# [Perl 5](https://www.perl.org/), 18 bytes
```
sleep 1e9for 1..30
```
[Try it online!](https://tio.run/##K0gtyjH9/784JzW1QMEw1TItv0jBUE/P2OD/fwA "Perl 5 – Try It Online")
10 bytes (doesn't work)
```
sleep 3e10
```
[Try it online!](https://tio.run/##K0gtyjH9/784JzW1QME41dDg/38A "Perl 5 – Try It Online")
[Answer]
# [PHP](https://www.php.net/), 30 bytes
The time() function can be used instead of microtime(1), as when plused with 3e10, PHP converts the value into a float, even when the original value is an int and thereby save some more bytes.
```
time_sleep_until(time()+3e10);
```
[See how php converts values](https://paiza.io/projects/e/0rG2h78IIabH87PlTe22ng)
As stated by "manassehkatz-Reinstate Monica" a flag can be set to make it run without the tags in PHP, so a more clean version is here made. (36 bytes)
```
time_sleep_until(microtime(1)+3e10);
```
Google tells me that 1000 years = 3.1556926 × 1010 seconds (31,556,926,000)
The method cloud even be made recoverable in the event of power failures. (not done in this example)
```
<?php time_sleep_until(microtime(true)+31556926000)); ?>
```
The shorter but more imprecise version (45 bytes with the php tags)
```
<?php time_sleep_until(microtime(1)+3e10); ?>
```
With a correction from "Kaddath" this option below is dropped as the documentation state that it is a int not a float used in sleep()
It can be done like so:
```
<?php sleep(31556926000); ?>
```
[Try it online!](https://paiza.io/projects/e/fFEGQvTU8U95mEyt-bVmeQ)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 38 37 bytes
this waits 1 + 2 + 3.. +77e5-1 + 77e5ms.
I got this 77e5 magic number using the formula `(x+1)/2*x=3e13` where x results in approximately `7.745.967` which I shortened to 77e5.
To check if it still falls in the allowed range I did `1000*365.25*24*3600*1000/((77e5+1)/2*77e5)` which is `1.064` aka 6.45% of target
update : 8e6 results in `0.98` more precise and less bytes.
```
for(var i=0;i++<8e6;)Thread.Sleep(i);
```
[Try it online!](https://tio.run/##Sy7WTS7O/F9anJmXrhBcWVySmqsXklGUmpgCFLDm4uIKL8osSfXJzEvVUAouSSwqSU1RSCxRUNJ2SSxJDcnMTdXzyy/XtP6fll@kUZZYpJBpa2Cdqa1tY5FqZq0JMUgvOCc1tUAjE6gKyTDXvBQcRgEA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
₆9e.W
```
Sleeps for about 1082 years.
[Try it online!](https://tio.run/##yy9OTMpM/f//UVObZape@P//AA "05AB1E – Try It Online")
```
₆ # push 36
9 # push 9
e # nPr (number of 9-element permutations of a 36-element list)
.W # wait that many milliseconds
```
[Answer]
# JavaScript (Node.js), ~~70~~, ~~67~~, 34 bytes
-3 thanks to Joost K, see their [answer](https://codegolf.stackexchange.com/a/197019/87378) for why I used `8e6`
-33 thanks to Benjamin Gruenbaum for pointing out callbacks are better, using the concept of his answer
I've found 2 ways of solving this problem.
The first defines `a` globally:
```
(f=_=>a&&setTimeout(f,--a))(a=8e6)
```
the other method passes `a` through each time, using `setTimeout`'s further args:
```
(f=a=>a&&setTimeout(f,--a,a))(8e6)
```
These solutions remain the same length when using IIFEs or just calling the function manually.
[Answer]
# TI-BASIC, 17 bytes
```
For(I,0,2^32:rand(564:End
```
TI-BASIC doesn't have any wait commands/functions, so I just used one of the slowest functions available: generating random lists!
Generating a random list of 564 elements takes \$\approx7.95\$ seconds to make and the loop goes through \$2^{32}\$ iterations, so that results in \$7.95\*2^{32}=34144990003.2\$ seconds or \$1082.01255\$ years.
[Answer]
# [Matlab](https://au.mathworks.com/products/matlab.html), 12 bytes
```
pause(3e+10)
```
This will sleep for 951 years which is within 10% of 1000 years. Note that Matlab can sleep for a floating number of seconds.
This is my first ever answer on CodeGolf :)
[Answer]
# x86-64 function, 10 bytes
```
6A 16 59 48 C1 E1 1F E0 FE C3
```
In assembly:
```
sleep_for_a_thousand_years:
push 0x17
pop rcx
shl rcx,52
loopnz $
ret
```
This is a function
The `loopnz` opcode decrements the `rcx` register and jumps if the zero flag is not set and `rcx!=0` after it is decremented. `$` denotes the address of the `loopnz` address itself, so this just loops back to the same instruction over and over until `rcx` is zero.
`loopnz` is infamously slow, and the code before sets `rcx` to 103,582,791,429,521,408. So this will loop 103,582,791,429,521,408 times, which should take 1012 years, based on some benchmarks I did on TIO. (The number may need to be tweaked a bit if you have some overclocked monstrosity though.)
[Try it online!](https://tio.run) ... Actually, maybe skip that just this once.
[Answer]
# [Applescript](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW10), 10
```
delay 3e10
```
Sleeps for 3 \* 1010 seconds.
] |
[Question]
[
Determining whether a Language is [Turing Complete](https://en.wikipedia.org/wiki/Turing_completeness) is very important when designing a language. It is a also a pretty difficult task for a lot of esoteric programming languages to begin with, but lets kick it up a notch. Lets make some programming languages that are so hard to prove Turing Complete that even the best mathematicians in the world will fail to prove them either way. Your task is to devise and implement a language whose Turing Completeness relies on a [major unsolved problem in Mathematics](https://en.wikipedia.org/wiki/List_of_unsolved_problems_in_mathematics).
## Rules
* The problem you choose must have be posed at least 10 years ago and must be unsolved, as of the posting of this question. It can be any provable conjecture in mathematics not just one of the ones listed on the [Wikipedia page](https://en.wikipedia.org/wiki/List_of_unsolved_problems_in_mathematics).
* You must provide a specification of the language and an implementation in an existing language.
* The programming language must be Turing complete if and only if the conjecture holds. (or if and only if the conjecture doesn't hold)
* You must include a proof as to why it would be Turing complete or incomplete based on the chosen conjecture. You may assume access to unbounded memory when running the interpreter or compiled program.
* Since we are concerned with Turing Completeness I/O is not required, however the goal is to make the most interesting language so it might help.
* This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") so the answer with the most votes will win.
## Target Criteria
What should a good answer do? Here are some things to look for when voting but are not technically required
* It should not be a simple patch of an existing language. Changing an existing language to fit the specifications is fine but patching on a condition is discouraged because it is boring. As said by [ais523](https://codegolf.stackexchange.com/users/62131/ais523) in the Nineteeth Byte:
>
> [I prefer to make my esolangs' gimmicks more firmly baked into the language](http://chat.stackexchange.com/transcript/message/35611798#35611798)
>
>
>
* It should be interesting as a standalone esoteric language.
[Answer]
## Legendre
This language is only Turing-complete if and only if [Legendre's conjecture](https://en.wikipedia.org/wiki/Legendre's_conjecture) is false, i.e. there exists a integer n > 0 such that there are no primes between n^2 and (n+1)^2. This language takes some inspiration from Underload, though in some respects it is very different from it.
Programs in Legendre are made up of series of positive integers (0 is especially banned, because it essentially negates the entire purpose of the language). Each integer corresponds to a base command in Legendre, or a potential user-defined one. Which command it is assigned to is based on the number of primes between its square and the next integer (equivalent to [the OEIS sequence A014085](https://oeis.org/A014085)).
The language's commands modify a stack, which can hold arbitrarily large positive integers. If the stack ever holds 0, the 0 is immediately removed. In detail, the commands are:
* 2 (smallest integer producing this command: 1): Push the next integer in the program onto the stack.
* 3 (smallest producing integer: 4): Pop the top integer on the stack and execute the command associated with it.
* 4 (smallest: 6): Pop the top integer. If it was 1, increment the top integer on the stack.
* 5 (10): Swap the top two stack items.
* 6 (15): Decrement the top integer on the stack. If that results in 0, pop the 0 and discard it.
* 7 (16): Duplicate the top integer on the stack.
* 8 (25): Halt execution and print the stack contents.
This is the basic instruction set, which is unable to do anything interesting, let alone loop. However, there is another command, which can be accessed only if Legendre's conjecture proves false.
* 0 (unknown): Remove all items from the stack and combine them into a new function, which will execute all commands starting at the original bottom of the stack and ending at the top, accessible as a command whose "command number" is equal to the one the next integer in the program source corresponds to.
If this command is somehow accessible, the language becomes Turing-complete, as one can simulate a Minsky machine in it.
When the command 8 is execute or the end of the program is reached, the program terminates and the (Unicode) character corresponding to each integer on the stack is printed.
### Example programs
```
1 2 1 3 1 10 4
```
This simple program pushes the number 2, then 3 and finally a 10, before executing a 4 (command: 3), which causes the 10 (command: 5) to be popped and executed, swapping the 2 and 3.
```
1 5 3 15 2 1 6 7
```
This program demonstrates the use of the indirect integer-to-command correspondence. First, a 5 is pushed, then a 15 and a 1, using three different ways of encoding the 2 command. Then, the 1 is popped and as a result, the 15 is incremented to a 16, and finally executed. The program ends with two instances of the number 5 on the stack.
```
1 1 1 5 ? 24 1 15 1 31 ? 31 24 31
```
This program demonstrates the use of the 0 command, using ? as a placeholder number. The program first stores '1 5' in the function 9, then '15 31' in 10, before running function 9 (using 24), which pushes 5 onto the stack, and the repeatedly decrements it, until it reaches 0 and is removed. Then, the program halts.
### Minsky machine
In order to convert a Minsky machine to Legendre code, the 0 command **must** be used. Because this command is inaccessible unless Legendre's conjecture is false, I have used a placeholder ? instead.
Note that all Minsky machine instruction line names need to have integers with different A014085 correspondences from each other and the base commands as well as 24 (9) and 31 (10).
Initialization:
```
1 1 1 1 ? 24
```
x INC (A/B) y:
A:
```
1 y 1 24 1 ? 1 6 1 1 16 1 24 ? x
```
B:
```
1 y 1 24 1 ? 1 10 1 6 1 1 16 1 10 1 24 ? x
```
x DEC (A/B) y z:
A:
```
1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 24 ? x
```
B:
```
1 4 1 10 1 15 1 10 1 31 1 1 1 10 1 z 1 1 1 16 1 24 1 31 1 ? 1 24 1 15 1 10 1 y 1 6 16 1 24 16 1 ? 1 1 16 1 10 1 1 16 1 10 1 24 ? x
```
x HALT:
```
1 25 ? x
```
To create the final program, append all parts (with x,y,z replaced by their counterparts) and add a single integer to start the first instruction in the chain. This should prove the language's Turing-completeness in case Legendre's conjecture is proven false by counterexample.
### Interpreter
This interpreter is written in Python (3), and has been tested on all three above examples. Use the -a/--allowZero flags to allow ? to be used, -f/--file to run code directly from a file and -s/--stackOut to output the stack as a Python list instead. If no file is given, the interpreter enters a sort of REPL mode, which is best used with --stackOut.
```
import sys
import argparse
import io
class I_need_missing(dict): #used to avoid try/except statements. Essentially a dict
def __missing__(self,key):
return None
def appropriate(integer,prev): #returns number of primes between the square of the integer given and the next
return_value = 0
if prev[integer]:
return prev[integer],prev
if integer == "?":
return 0,prev
for i in range(integer ** 2, (integer + 1) ** 2):
t = False
if i > 1:
t = True
for j in range(2,int(i ** 0.5)+1):
t = i/j != round(i/j)
if not t:
break
return_value += t
prev[integer] = return_value
return return_value,prev
def run_command(commandseries,stack,functions,prev): #Runs the appropriate action for each command.
command,prev = appropriate(commandseries.pop(0),prev)
halt = False
if command == 0: #store in given number
functions[appropriate(commandseries.pop(0),prev)[0]] = stack
stack = []
elif command == 2:#push
stack.append(commandseries.pop(0))
elif command == 3:#execute top instruction
commandseries.insert(0,stack.pop())
elif command == 4:#pop, add 1 to new top if popped value was 1
if stack.pop() == 1:
stack[-1] += 1
elif command == 5:#swap top two integers/?
stack[-1],stack[-2] = stack[-2],stack[-1]
elif command == 6:#subtract 1 from top of stack
stack[-1] -= 1
if stack[-1] == 0:
stack.pop()
elif command == 7:#duplicate top of stack
stack.append(stack[-1])
elif command == 8:#halt
halt = True
else:#run custom
try:
commandseries[0:0] = functions[command]
except TypeError:
print("Warning: unassigned function " + str(command) + " is unassigned", file = sys.stderr)
return commandseries,stack,functions,prev,halt
def main(stack,functions,prev):
#Parser for command line options
parser = argparse.ArgumentParser(description = "Interpreter for the Legendre esoteric programming language.")
parser.add_argument("-a","--allowZero", action = "store_true")
parser.add_argument("-f","--file")
parser.add_argument("-s","--stackOut", action = "store_true")
args = parser.parse_args()
allow_zero = bool(args.allowZero)
#Program decoding starts
pre = ""
if not args.file:
pre = input()
if pre == "":
return
else:
pre = open(args.file).read()
mid = pre.split()
final = []
for i in mid:
if i == "?" and allow_zero:
final.append("?")
elif i != 0 or allow_zero: #and allow_zero)
final.append(int(i))
halt = False
#Functional programming at its best
while final and not halt:
final,stack,functions,prev,halt = run_command(final,stack,functions,prev)
#Halting and output
else:
if args.stackOut:
print(stack)
else:
for i in stack:
print(i == "?" and "?" or chr(i),end = "")
print("")
if args.file or halt:
return
else:
main(stack,functions,prev)
if __name__ == '__main__':
main([],I_need_missing(),I_need_missing())
```
[Answer]
## Union Closed
This programming language is Turing complete iff the [Union-closed Sets conjecture](https://en.wikipedia.org/wiki/Union-closed_sets_conjecture) is incorrect.
## Controls
List of Commands:
x++ Increment x (INC)
x-- Decrement x (DEC)
j(x,y) Add instruction set x if y is 0 to end of instruction queue
All variables are initialized as 0
## Syntax
Programs are written as a set of sets of commands.
Command1 Command2 Command3...
Command1 Command2...
...
For determining if the program is union closed, each set only accounts for the list of different commands that are in the set
j(x,y)!=j(a,b)
+(x)!=+(y)
If any command type (+,-,j) appears in at least half the sets, it does nothing.
Programs can end if there are no instructions on the end of the instruction queue
Infinite loops, including the empty loop, can be achieved using j(x,y)
## Interpreter
```
function union_arrays (x, y) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i)
obj[x[i]] = x[i];
for (var i = y.length-1; i >= 0; -- i)
obj[y[i]] = y[i];
var res = [];
for (var k in obj) {
res.push(obj[k]);
}
return res;
}
function runCode(){
var inputBox=document.getElementById("code");
input=inputBox.value;
input=input.split("\n").map(a=>a.split(" "));
input=input.filter(x=>x.filter(y=>y.length>0).length>0);
for(i=0;i<input.length;i++){
for(j=0;j<input[i].length;j++){
switch(input[i][j][0]){
case"j":
eval(input[i][j].split(",")[0].slice(2)+"=0;"+input[i][j].split(",")[1].slice(0,-1)+"=0")
break;
default:
eval(input[i][j].slice(0,1)+"=0");
break;
}
}
}
counts=[0,0,0];
for(i=0;i<input.length;i++){
count=[0,0,0];
for(j=0;j<input[i].length;j++){
switch(input[i][j][0]){
case"j":
count[2]=1;
break;
default:
if(input[i][j][1]=="+"){
count[0]=1;
}
else{
count[1]=1;
}
break;
}
}
for(j=0;j<3;j++){
counts[j]+=count[j];
}
}
for(i=0;i<input.length-1;i++){
for(j=i+1;j<input.length;j++){
valid=0;
union=union_arrays(input[i],input[j]);
for(k=0;k<input.length;k++){
if(union_arrays(input[k],[]).sort().join("")==union.sort().join("")){
valid=1;
}
}
if(!valid){
break;
}
}
if(!valid){
break;
}
}
console.log(valid)
var queue=[]
if(valid){
queue.push(input[0]);
while(queue.length){
for(i=0;i<queue[0].length;i++){
if(queue[0][i][0]=="j"&&counts[2]<input.length/2){
eval("if("+queue[0][i].split(",")[1].slice(0,-1)+"===0&&input["+queue[0][i].split(",")[0].slice(2)+"])queue.push(input["+queue[0][i].split(",")[0].slice(2)+"])");
}
if(queue[0][i][1]=="+"&&counts[0])
eval(queue[0][i]);
if(queue[0][i][1]=="-"&&counts[1])
eval(queue[0][i]);
}
queue=queue.splice(0,1);
}
}
}
```
```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>
<p class=results></p>
```
## Turing Completeness
If all three commands, j(x,y), increment, decrement the commands are all available, so a Minsky machine can be simulated.
Any set with only j(x,y) which is reached using j(x,y) is HALT
x++ is INC
x-- is DEC
j(x,y) is JZ
If the union closed sets conjecture is correct, at least one of the three commands will always be disabled, thereby making it impossible for this language to be Turing complete.
[Answer]
## Fermat primes
The language works on two potentially infinite tapes, where each location of the tape can store an arbitrary integer. Both tapes are filled with `-1` at start. There is also two tape heads that start at position 0 on both tapes.
The interpreter will first read the input, and store the values into the first (data) tape, starting at position 0.
Then it will read the supplied program. For every number it encounters, it will first check if the value is a Fermat prime or not. If yes, it will write to the second (instruction) tape which Fermat prime it is, otherwise it will write `-1` to the instruction tape.
Next check the value at the instruction pointer, and do one of the following:
* `-1` or less: Exit the program
* `0`: Move the data tape position one to the left. Move the instruction tape position one to the right
* `1`: Move the data tape position one to the right. Move the instruction tape position one to the right
* `2`: Increase the value at the data tape position. Move the instruction tape position one to the right
* `3`: Decrease the value at the data tape position. Move the instruction tape position one to the right
* `4`: If the value at the current data tape position is zero, then move the instruction tape to the right, until you reach either a matching `5` (or larger) value on the instruction tape, or something smaller than `0`. If it is a `5` (or larger), move the instruction pointer the right once again, if it's smaller than `0` then exit the program. If value the current data tape position is not zero, simply move the instruction tape one to the right
* `5` or more: Move the instruction pointer to the left, until you reach the corresponding `4` value, or you find something less than `0`. In the case of the latter, exit the program.
(by matching `5` (or more) and `4` values it means that while searching for the proper value on the instruction tape any time it encounters the same value as the initial command (either `5` (or more) or `4`), it will have to skip the appropriate number of the other value (`4` or `5` (or more) respectively) on the search)
Loop, until the instruction says you have to exit the program.
When the program exits, output the values on the data tape from position `0` until the first tape position that contains a `-1` value.
## Proof
Note that the language essentially maps to an IO-less Brainfuck interpreter, where `F_5` is required to be able to do any kind of proper loops.
However based on the Fermat prime conjecture [there are only 5 Fermat primes](https://www.wikiwand.com/en/Fermat_number) (`F_0` - `F_4`). If `F_5` exists the language is Turing-complete, as we know that Brainfuck is Turing-complete. However, without `F_5` you won't be able to do neither branching nor looping, essentially locking you into very simple programs.
## Implementation
(tested with ruby 2.3.1)
```
#!/usr/bin/env ruby
require 'prime'
CHEAT_MODE = false
DEBUG_MODE = false
NUM_CACHE = {}
def determine_number(n)
return n.to_i if CHEAT_MODE
n = n.to_i
-1 if n<3
return NUM_CACHE[n] if NUM_CACHE[n]
i = 0
loop do
num = 2**(2**i) + 1
if num == n && Prime.prime?(n)
NUM_CACHE[n] = i
break
end
if num > n
NUM_CACHE[n] = -1
break
end
i += 1
end
NUM_CACHE[n]
end
data_tape = Hash.new(-1)
instruction_tape = Hash.new(-1)
STDIN.read.each_char.with_index { |c,i| data_tape[i] = c.ord }
File.read(ARGV[0]).split.each.with_index do |n,i|
instruction_tape[i] = determine_number(n)
end
data_pos = 0
instruction_pos = 0
while instruction_tape[instruction_pos] >= 0
p data_tape, data_pos, instruction_tape, instruction_pos,'------------' if DEBUG_MODE
case instruction_tape[instruction_pos]
when 0 then data_pos -= 1; instruction_pos += 1
when 1 then data_pos += 1; instruction_pos += 1
when 2 then data_tape[data_pos] += 1; instruction_pos += 1
when 3 then data_tape[data_pos] -= 1; instruction_pos += 1
when 4 then
if data_tape[data_pos] == 0
count = 1
instruction_pos += 1
while count>0 && instruction_tape[instruction_pos] >= 0
count += 1 if instruction_tape[instruction_pos] == 4
count -= 1 if instruction_tape[instruction_pos] >= 5
instruction_pos += 1
end
break if count != 0
else
instruction_pos += 1
end
else
count = 1
instruction_pos -= 1
while count>0 && instruction_tape[instruction_pos] >= 0
count += 1 if instruction_tape[instruction_pos] >= 5
count -= 1 if instruction_tape[instruction_pos] == 4
instruction_pos -= 1 if count>0
end
break if count != 0
end
end
data_pos = 0
while data_tape[data_pos] >= 0
print data_tape[data_pos].chr
data_pos += 1
end
```
Examples:
This will write `H` (short for `Hello World!`) to the screen with a newline:
```
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17 17 17 17 17 17 17 17
17 17 17
5
17 17 17 17 17 17 17 17 17 17
17
```
Save as `example.fermat` and run it like this (note: you always need to have an input):
```
$ echo -n '' | ./fermat.rb example.fermat
```
This next example will do a simple Caesar style cypher by incrementing each value of the input by one. You obviously have to replace `?` with the 5th Fermat prime:
```
17 65537 5 17 ? 257
```
You can try it out that it works by enabling cheat mode and using `2 4 1 2 5 3` as the source code:
```
$ echo 'Hello' | ./fermat.rb example2_cheat.fermat
```
[Answer]
# Swallows w/ Coconut v2
As the previous version had errors which made it invalid for this contest, and I don't want to have the upvotes from the previous version count for this version which is significantly different, this version is being submitted as a new post.
This language is not Turing complete if the [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) can be proven for all positive integers. Otherwise, the language is Turing complete.
This language was based off of [Cardinal](https://esolangs.org/wiki/Cardinal).
First, the contVal of the program is calculated using the formula
contVal=sum(sum(ASCII values of row)\*2^(row number-1))
Next, 2 Swallows headed in opposite directions are created at each A or E and all conditional turn statements are set to wait for initialization.
Swallows created at an E are headed left/right and swallows created at an A are headed up/down.
Finally, the code will perform steps until all pointers have been removed or contVal has fallen to one.
At each step, if contVal%2==0 it will be divided by 2, otherwise, it will be multiplied by three and incremented by one.
## Commands:
0 : set value to 0
+ : increment value by 1
> : change direction to right
v : change direction to down
< : change direction to left
^ : change direction to up
R : Subsequent pointers after the first pointer compare with the value of the first pointer. If equal, go straight, else turn right.
L : Subsequent pointers after the first pointer compare with the value of the first pointer. If equal, go straight, else turn left.
E : Duplicate the pointer but heading in the directions left and right
A : Duplicate the pointer but heading in the directions up and down
? : Remove the pointer if the value is 0
```
function runCode(){
var inputBox=document.getElementById("code");
input=inputBox.value;
area=input.split('\n');
width=0;
height=area.length;
for(i=0;i<height;i++){
width=Math.max(width,area[i].length);
}
//Determine the endurance of the swallows
contVal=0;
for(i=0;i<height;i++){
for(j=0;j<area[i].length;j++){
contVal+=((j+1)<<i)*area[i].charCodeAt(j);
}
}
//Spawn the African and European swallows and initialize the conditionals
pointerList=[];
condList=[];
for(i=0;i<height;i++){
for(j=0;j<area[i].length;j++){
if(area[i][j]=='A'){
pointerList.push([i,j,0,0]);
pointerList.push([i,j,2,0]);
}
if(area[i][j]=='E'){
pointerList.push([i,j,1,0]);
pointerList.push([i,j,3,0]);
}
if(area[i][j]=='R'||area[i][j]=='L'){
condList.push([i,j,-1]);
}
}
}
output='';
while(1){
for(i=0;i<pointerList.length;i++){
switch (pointerList[i][2]){
case 0:
pointerList[i][1]++;
break;
case 1:
pointerList[i][0]++;
break;
case 2:
pointerList[i][1]--;
break;
case 3:
pointerList[i][0]--;
break;
}
if(pointerList[i][1]<0||pointerList[i][0]<0||pointerList[i][0]>=height||pointerList[i][1]>=area[pointerList[i][0]].length){
pointerList.splice(i,1);
}
else{
switch(area[pointerList[i][0]][pointerList[i][1]]){
case "+":
pointerList[i][3]++;
break;
case "0":
pointerList[i][3]=0;
break;
case ">":
pointerList[i][2]=1;
break;
case "v":
pointerList[i][2]=2;
break;
case "<":
pointerList[i][2]=3;
break;
case "^":
pointerList[i][2]=0;
break;
case "R":
for(j=0;j<condList.length;j++){
if(pointerList[i][0]==condList[j][0]&&pointerList[i][1]==condList[j][1]){
if(condList[j][2]==-1){
condList[j][2]=pointerList[i][3];
pointerList.splice(i,1);
}
else{
if(pointerList[i][3]!=condList[j][2]){
pointerList[i][2]=(pointerList[i][2]+1)%4;
}
}
}
}
break;
case "L":
for(j=0;j<condList.length;j++){
if(pointerList[i][0]==condList[j][0]&&pointerList[i][1]==condList[j][1]){
if(condList[j][2]==-1){
condList[j][2]=pointerList[i][3];
pointerList.splice(i,1);
}
else{
if(pointerList[i][3]!=condList[j][2]){
pointerList[i][2]=(pointerList[i][2]+3)%4;
}
}
}
}
break;
case "A":
pointerList.push([pointerList[i][0],pointerList[i][1],0,pointerList[i][3]]);
pointerList.push([pointerList[i][0],pointerList[i][1],2,pointerList[i][3]]);
break;
case "E":
pointerList.push([pointerList[i][0],pointerList[i][1],1,pointerList[i][3]]);
pointerList.push([pointerList[i][0],pointerList[i][1],3,pointerList[i][3]]);
break;
case "?":
pointerList.splice(i,1);
}
}
}
if(contVal%2===0){
contVal=contVal/2;
}
else{
contVal=contVal*3+1;
}
if(!pointerList.length||contVal==1){
break;
}
}
console.log(output);
}
```
```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>
<p class=results></p>
```
## Explanation:
If the Collatz Conjecture can be proven for all positive integers, the duration of any program run in this language is finite, as contVal will always converge to 1, thereby ending the program.
Otherwise, I simply need to prove that this language can implement the following [functions](https://cs.stackexchange.com/a/995)
Increment: which is represented by +
Constant 0: which is represented by 0
Variable access: variables are stored as pointers as they travel
Statement concatenation: by changing the distance travelled to operations, the order in which operations are performed can be changed
For loop: In this language
```
E > V
^+R
+
A
```
will act as a for loop >count up to 1 (further code could be added to the loop)
Similarly, the code
```
Rv
^<
```
Will act as a do until equal to the conditional value set in R loop.
[Answer]
# Perfection/Imperfection
Whew, that was fun.
Perfection/Imperfection is only complete if there are infinite perfect numbers. If there are, it's called Perfection, and if there are not, it is called Imperfection. Until this mystery is solved, it holds both names.
A perfect number is a number whose divisors sum to the number, so six is a perfect number because `1+2+3=6`.
Perfection/Imperfection has the following functions:
Perfection/Imperfection is stack-based, with a zero-indexed stack.
**Commands:**
`p(x, y)`: pushes x to the stack in the yth position.
`z(x, y)`: pushes x to the stack in the yth position, gets rid of what was previously in the yth position
`r(x)`: removes the xth item from the stack
`k(x)`: returns the xth item on the stack
`a(x, y)`: adds x and y. When used with strings, it puts them together in order xy.
`s(x, y)`: subtracts y from x. with strings, removes the last len(y) from x
`m(x, y)`: multiplies x and y. If used with strings, multiplies x times len y.
`d(x, y)`: divides x by y
`o(x)`: prints x
`i(x, y)`: if x evaluates to true, then it executes function y
`n()`: returns the counter the code block is being called on.
`q()`: returns the length of the stack
`t()`: user input
`e(x, y)`: If x is an integer, if x and y have the same value, then this returns 1. if y is a string then it gets the length of y. if x is a string, then it converts y to a string and checks if they are the same, and if they are, returns 1. Otherwise it returns 0.
`l(x, y)`: if x is larger than y, then it returns 1. If there is a string, then it uses the length of the string.
`b()`: stops the program.
`c(x, y)`: runs x, then y.
To get the equivalent of a Python `and`, multiply the two values together. For `or`, add the values, and for `not`, subtract the value from 1. This only works if the value is 1 or 0, which can be achieved by dividing the number by itself.
Data types: integers and strings. Strings are denoted by `''`, and all non-integer numbers are rounded.
**Syntax:**
Code consists of nested functions inside of ten `{}`s. For example, a program that would get to inputs and print them added would be: `{o(a(t(), t()))}`. In the background of the program there is a counter that starts at 0 and progresses by 1 every time it executes a code block. The first code block runs at `0`, and so on. Once the ten code blocks are executed, the sixth one is executed every time the counter reaches a perfect number. You do not need to have all ten code blocks for the program to work, but you need 7 if you want to make a loop. To better understand how this language works, run the following program, which prints the counter every time the counter reaches a perfect number: `{}{}{}{}{}{}{o(n())}`.
The interpreter can be found here: [repl.it/GL7S/37](https://repl.it/GL7S/37). Either select 1 and type your code in the terminal, or paste your code in the `code.perfect` tab and select 2 when you run. It will make sense when you try it.
**Proof of Turing completeness/lack of Turing completeness.**
According to [this software engineering stack exchange article](https://softwareengineering.stackexchange.com/questions/132385/what-makes-a-language-turing-complete), a Turing complete must be able to have a form of conditional repetition of jump, and have a way to read or write memory. It can read/write memory in the form of the stack, and it can loop due to the fact that the 6th code block is executed every time the counter reaches a perfect number. If there are an infinite number of perfect numbers, it can loop indefinitely and is Turing complete, and otherwise it is not.
Self Bitwise Cyclic Tag interpreter that takes 5 characters, 1 or 0, as input:
```
{p(t(),0)}{(p(t(),0)}{p(t(),0)}{p(t(),0)}{p(t(),0)}{p(0,0)}{c(i(e(k(s(q(),k(0))),0),c(r(q()),i(l(k(0),0),z(s(k(0),1),0)))),i(e(k(s(q(),k(0))),1),c(z(a(k(0),1),0),i(e(k(q()),1),p(k(s(q(),k(0))),1)))))}
```
It can be expanded to take any number of chars as input. It could take infinite input, but only if there are infinite perfect numbers!
[Answer]
# Soles
This programming language is Turing complete iff the [Scholz conjecture](https://en.wikipedia.org/wiki/Scholz_conjecture) is true.
I wrote this language because @SztupY was saying that there wouldn't be any results that rely on the conjecture to be true to be Turing complete
## List of Commands
```
+(x) Increment x (INC)
-(x) Decrement x (DEC)
j(x,y) Jump to instruction x if y is 0 (JZ)
x End program (HALT)
```
With these commands, this language can simulate a Minsky machine
## Interpreter
I would highly recommend not running this. It uses an extraordinarily slow method of checking the addition chain.
```
function runCode(){
var inputBox=document.getElementById("code");
input=inputBox.value;
input=input.split(" ");
counter=1;
lvals=[0];
l=(x,arr)=>{
if(arr[x-1]){
return arr[x-1];
}
minim=Number.MAX_SAFE_INTEGER;
console.log(min);
for(i=Math.floor(x/2);i>0;i--){
minim=Math.min(minim,l(i,arr)+l(x-i,arr)+1);
}
return minim;
};
cont=1;
pointer=0;
while(cont){
lvals[Math.pow(2,counter)-2]=l(Math.pow(2,counter)-1,lvals);
lvals[counter-1]=l(counter,lvals);
if(lvals[Math.pow(2,counter)-2]>n-1+lvals[counter-1]){
break;
}
switch(input[pointer][0]){
case "+":
x=input[pointer].slice(2,-1);
eval(x+"++")
break;
case "-":
x=input[pointer].slice(2,-1);
eval(x+"--")
break;
case "j":
x=input[pointer].split(",")[0].slice(2);
y=input[pointer].split(",")[0].slice(0,-1);
eval("if(!"+y+")pointer="+x+"-1");
break;
case "x":
cont=0;
break;
}
pointer++;
if(pointer>input.length){
break;
}
counter++;
}
}
```
```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>
<p class=results></p>
```
## Turing completeness
The language uses a counter for number of commands run which it checks against the Scholz conjecture to modify the turing completeness of the language.
If the Scholz conjecture is true, this program works exactly like a normal Minsky machine with
Increment
Decrement
Jump if Zero
Halt
However, if the Scholz conjecture is false, the counter will eventually reach a value for which the Scholz conjecture does not hold true. As the language has been designed to exit upon reaching a number which the Scholz conjecture is false, the program will exit every time after running that many commands. Therefore, all programs will have limited length. As this disagrees with the requirements for the language to be Turing complete,
>
> "The tape cannot be fixed in length, since that would not correspond to the given definition and would seriously limit the range of computations the machine can perform to those of a linear bounded automaton",
>
>
>
the language would not be Turing complete should the Scholz conjecture be false
[Answer]
# Betrothed
[Betrothed Github](https://github.com/ConorOBrien-Foxx/Betrothed).
The readme and specification is on the github, under "README.txt".
Generally, a Betrothed program is composed of pairs of lines, whose lengths are distinct twin prime pairs or betrothed pairs (no duplicates can occur). The program is executed by find "pliable subsets" of the first line in the pair within the second line. The number of such subsets, combined with the levenshtein distance between the original second line and the second line without the pliable subsets, determine the command to execute.
I will excerpt the proof for this post:
```
V. PROOF OF TURING COMPLETENESS
Now, no language can be Turing Complete with bounded program size. Therefore, if Betrothed
is Turing Complete, it must have unbounded program size. Since the lengths of the lines of
a Betrothed program must be twin prime pairs or betrothed pairs, and since both sequences
are unproven to be infinite or finite, Betrothed has unbounded program size if and only if
there are infintie betrothed pairs, there are infinite twin prime pairs, or both.
Next: to prove that if Betrothed has an unbounded program size, then it is Turing
Complete. I will use the op-codes from the above table to demonstrate key factors of a
Turing Complete language; they are of the form [index]<[ld]> .
1. Conditional goto: 6<> 5<>, or if-popjump. This can be used to form a loop.
2. Inequality to a constant K: 10<K>
3. Arbitrarily large variable space: you can use some separator constant C.
With this, I have sufficient reason to believe that Betrothed is Turing Complete.
```
[Answer]
# Amicable Parity
This language is based on whether there are any [amicable numbers](https://en.wikipedia.org/wiki/Amicable_numbers) with [opposite parity](https://en.wikipedia.org/wiki/List_of_unsolved_problems_in_mathematics#Number_theory).
## Commands
```
x : End program if not on top line
+ : increment stored value
- : decrement stored value
{ : set next goto x value to current x value
} : goto previous x value set by {
j : Go down one line if the special value is an amicable number and the
parity is opposite to the matching number (loops back to top). If the
special value is not an amicable number and not on the top line, go up
one line.
```
## Control flow
The program cycles repeatedly from left to right before looping back to the start. If it encounters a "j", it checks the value to determine if it should change rows. If the number is an amicable number with opposite parity to its match, it goes down one row (looping back to top), Otherwise, if the number is an amicable number, it goes up one row if not already in the top row.
The program can only end if the program reaches an x in any row outside of the top row.
## Turing Completeness
This program can be used to simulate a Minsky machine assuming that there is a pair of amicable numbers with opposite parity.
j,{ and } can be used to simulate JZ(r,x) although it would check for amicable numbers as opposed to zero.
+ is INC(r)
- is DEC(r)
x is HALT
If you can not leave the first row, the x and } commands do nothing. This results in the program being unable to enter a HALT state unless it is an empty program. Therefore, under the description that Turing completeness [requires a HALT state](https://en.wikipedia.org/wiki/Talk%3ATuring_completeness#The_need_for_an_explicit_HALT_state), the language would be Turing incomplete.
## Interpreter
```
sumDiv=r=>{
sum=0;
for(i=1;i<=Math.sqrt(r)&&i!=r;i++){
if(r%i===0){
sum+=i+r/i;
}
if(i*i==r){
sum-=i;
}
}
return sum;
};
function runCode(){
var inputBox=document.getElementById("code");
input=inputBox.value;
input=input.split("\n");
val=2;
exit=0;
loop=0;
for(j=0;!exit;){
for(i=0;i<input[j].length;i++){
if(input[j][i]=="x"&&j){
exit=1;
break;
}
else if(input[j][i]=="j"){
if(val==sumDiv(sumDiv(val))&&val!=sumDiv(val)&&(val+sumDiv(val))%2){
j=(j+1)%input.length;
i--;
}
else if(j&&val!=sumDiv(sumDiv(val))){
j--;
i--;
}
}
else if(input[j][i]=="+"){
val++;
}
else if(input[j][i]=="-"){
val--;
}
else if(input[j][i]=="{"){
loop=i;
}
else if(input[j][i]=="}"&&j){
i=loop;
}
if(input[j].length==i+1){
i=-1;
}
}
}
}
```
```
<input type="text" id="code" value=""/>
<button onClick="runCode()">Submit</button>
<p class=results></p>
```
[Answer]
# Taggis
Taggis is a language based on [tag systems](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequences).
Taggis's turing completeness is based on the [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture)
## Syntax
A Taggis program's syntax is simply three strings (production rules) consisting entirely of the letters
a, b, and c, separated by spaces.
## Execution
Taggis's only program state is a string consisting of the same three characters.
Taggis implements a TS(3, 2) tag system, where in every step the first 2 letters of the current "tag" are removed, and the very first letter that was in that removed portion gets its corresponding production rule appended to the end of the string.
For example, the Taggis program `bc a aaa` implements the 3n + 1 problem, where iterations are represented by a corresponding number of `a`s and the 3n + 1 step is replaced with (3n + 1) / 2 [1], leading to the program output:
```
aaa // 3
abc
cbc
caaa
aaaaa // 5
aaabc
abcbc
cbcbc
cbcaaa
caaaaaa
aaaaaaaa // 8
aaaaaabc
aaaabcbc
aabcbcbc
bcbcbcbc
bcbcbca
bcbcaa
bcaaa
aaaa // 4
aabc
bcbc
bca
aa // 2
bc
a // 1 and halt because we then begin an infinite loop
HALT
```
## Turing completeness
Of course, this simple system may seem far too simple to emulate Turing completeness, but it turns out that any Turing machine with 2 symbols (a class that includes universal machines) can be converted to a tag system with 2 removed characters from the head, and 32 \* m production rules, where `m` is the number of states in the Turing machine.
The smallest known universal Turing machine with only 2 symbols uses 18 states and thus the corresponding tag system contains a whopping 576 production rules [2].
However, the computational class of the set of all tag systems with 3 productions and 2 removed symbols is tied to the Collatz Conjecture [2]. If the Collatz Conjecture is proved to be false, then Taggis is Turing-complete. Otherwise, it is based on ANOTHER unsolved problem in mathematics, finding a smaller Turing machine than
```
def taggis(inp, a, b, c):
current = inp
seen = set()
while True:
seen.add(tuple(current))
yield current
head = current[0]
current = current[2:]
current.extend([a, b, c][head])
if tuple(current) in seen:
return
def parse():
program = input().split(" ")
assert len(program) == 3, "There has to be exactly 3 production rules!"
productions = []
for production in program:
production = [{"a": 0, "b": 1, "c": 2}[x] for x in production]
productions.append(production)
program_input = [{"a": 0, "b": 1, "c": 2}[x] for x in input()]
k = 0
for step in taggis(program_input, *productions):
print(' ' * k +''.join(['abc'[x] for x in step]))
k += 2
print(' ' * (k - 1) + 'HALT')
parse()
```
1. which is equivalent to the original Collatz function as 3n + 1 of an odd `n` will always be even and therefore the division can be automatically applied
2. [Tag systems and Collatz-like functions, *Liesbeth De Mol*,](https://www.sciencedirect.com/science/article/pii/S0304397507007700)
[Answer]
# Newline
Disclaimer: It is a bit of a mess and pretty simple. This is the first language I have ever written and the conjecture is the only one I understood. I know another user had a longer answer with the same one but I decided to write this anyway.
To write in Newline you must have a lot of time and newlines (`\n`). This works off of the Legendre conjecture being true. Every operator must fall on a number in the Legendre conjecture that we start with n = 1. Every time you have an operator you take the amount of \n's and plug that into the Legendre Conjecture and get the range that the next prime amount of \n's must fall in. So to start off you do `\n\n` then you move on to an operator then `\n` then another operator we are at 3 newlines. Now the next one is it 5 so you add `\n\n` and on operator making sure that the last operator line has the right amount of newlines that you are on a prime amount that falls in the Legendre conjecture that we started.
Numbers (the array) is like the variables. Every time an operator runs (that uses numbers) it increments.
```
+ adds
- subtracts
/ divide
* multiply
s sqrt
% mod
a push to vars
g sets stack to numbers
q pushes value of stack to numbers
i increment
d decrement
r stops subtraction at 0
w turns back on subtraction past 0
[ starts loop
] ends loop runs until stack is 0
{ starts loop
} ends loop and loops until loops[ln] is 0
k increment loops
```
As long as we have unlimited primes that follow the rules this language has non finite tape.
# Minsky machine
```
\n\ng\nr\n\n[\n\nd\n\n\n\n]
```
How it works:
```
\n\ng # the first two newlines are to get to a prime number of newlines (2) then sets the value of stack to the first variable in the array numbers (see code in link)
\nr # gets to the next number and makes it so subtraction stops at 0
\n\n[ # starts the loop
\n\nd # decrements stack
\n\n\n\n] # ends loop
```
Try it out on [KhanAcademy](https://www.khanacademy.org/computer-programming/melang/5474968288952320).
] |
[Question]
[
*This is the cops' thread. The robbers' thread is [here](https://codegolf.stackexchange.com/q/135365/58826).*
Your challenge is to make a program that runs forever without halting1, unless it gets a particular input or inputs2. If it receives that input, it must terminate in a finite amount of time3. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer that has not been cracked by a robber within one week of posting wins. After the week has passed, please mark your answer as safe and show the halting input (in a `> ! spoiler quote`). If a robber cracks your submission, please mark it as cracked and show the halting input (in a `> ! spoiler quote`).
Submissions are preferred be runnable & crackable on [TIO](https://tio.run). Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them.
Please make your input deterministic, and uniform across all runs. See [this meta post](https://codegolf.meta.stackexchange.com/q/13421/58826) for details.
**Please, don't "implement RSA" or anything mean to the robbers. Use obscure languages and features, not boring encryption and hashing. I can't enforce this with rules, but you can expect torrential downvotes if all you do is `sha(input) === "abcd1234"`.**
---
1Assuming that the computer doesn't get shut down, break, get engulfed by the sun, overheat in the universe's heat death, or hit the TIO timeout of 60s.
2The program must halt on **at least** one input. As long as it loops forever on one input and halts on another, it works.
3This must be < 60 seconds, so that the code can be tested on TIO.
---
# Looking for uncracked submissions?
```
fetch("https://api.stackexchange.com/2.2/questions/135363/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|<a href ?= ?".*?">)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});
```
```
<html><body><h1>Uncracked Submissions</h1><table><thead><tr><th>Language</th><th>Author</th></tr></thead><tbody></tbody></table></body></html>
```
[Answer]
# Malbolge, 128 bytes, [cracked by KBRON111](https://codegolf.stackexchange.com/a/136004/3808)
```
(=&r:#o=~l4jz7g5vttbrpp^nllZjhhVfddRb`O;:('JYX#VV~jS{Ql>jMKK9IGcFaD_X]\[ZYXWVsN6L4J\[kYEhVBeScba%_M]]~IYG3Eyx5432+rpp-n+l)j'h%B0
```
Have fun!
(Yes, I learned Malbolge just for this. Yes, it took an absurdly long time to finally get working. And yes, it was totally worth it.)
Wrapped, so you can see it in its full, er, "glory":
```
(=&r:#o=~l4jz7g5vttbrpp^nllZjhhV
fddRb`O;:('JYX#VV~jS{Ql>jMKK9IGc
FaD_X]\[ZYXWVsN6L4J\[kYEhVBeScba
%_M]]~IYG3Eyx5432+rpp-n+l)j'h%B0
```
I used [this interpreter](http://www.lscheffer.com/malbolge_interp.html) to test it; I'm not sure if it matters, but I figured I'd specify just in case.
[Answer]
# JavaScript (ES6), 17 bytes, [Cracked](https://codegolf.stackexchange.com/a/135375/58826)
```
x=>{for(;x==x;);}
```
On TIO, since I dunno how to do Node.js readline on TIO, just stick the input in the function call. This is obvious to anyone who knows it, and not to anyone who doesn't.
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q46Lb9Iw7rC1rbCWtO69n@ahuZ/AA "JavaScript (Node.js) – Try It Online")
Answer:
>
> The answer is `NaN`, since in JavaScript, `NaN != NaN`.
>
>
>
[Answer]
# JS (ES6), 67 bytes ([Cracked](https://codegolf.stackexchange.com/a/135394/65836))
```
(x,y)=>{while(x!==y||Object.is(x, y)||!isFinite(x)||!isFinite(y));}
```
I *think* i didn't mess up, it might have an easy solution that I didn't see.
I appreciate any feedback, this is one of my first posts
>
> `(+0, -0)` Yep, js has a negative 0
>
>
>
[Answer]
# Python 3.4, (40 bytes) [Cracked](https://codegolf.stackexchange.com/a/135503/64047)
```
def f(x):
while(x==x or not x==x):pass
```
[Answer]
# Javascript (NOT node.js)
```
x=>{while(x+"h");}
```
The desired submission doesn't use throw.
Hint for desired crack:
>
> The desired submission doesn't overwrite `.toString()`, or use `Set()` either.
>
>
>
Desired crack:
>
> `Object.create(null)`
>
>
>
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 75 bytes [Cracked](https://codegolf.stackexchange.com/a/135526/9498)
```
#include<stdio.h>
int main(){char c[9];while(1){scanf("%8s",c);printf(c);}}
```
[Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djiszr0QhNzEzT0OzOjkjsUghOdoy1ro8IzMnVcNQs7o4OTEvTUNJ1aJYSSdZ07qgCKg8TQPIqq39/x8A "C (gcc) – Try It Online")
I've never posted in a cops-n-robbers before. Hopefully this isn't *too* obvious.
Solution:
>
> An input of "%s" makes this segfault. There are several other ones that can be used; all of them are `printf` specifiers like "%n"
>
>
> This is the classic `printf` vulnerability. Simply put, the format string comes straight from user input, so any `printf` specifiers get passed through, unsafely.
>
>
>
[Answer]
# JavaScript (in Browser), 79 bytes [Cracked](https://codegolf.stackexchange.com/a/135709/44718)
```
x=>{try{for(;x||x!=null||x!=void 0||x===null||x===void 0;);}catch(e){for(;;);}}
```
You should run it in a recent browser (like latest Firefox ESR, latest Firefox, latest Chromium). Running on old browsers (like Netscape 2, IE 4) do not count.
Note: Halted by browser due to time out do not count a halt here.
Always be careful not crash your browser when testing this codes, and happy robbing ^\_^
>
> document.all
>
>
>
[Answer]
# [PHP](https://php.net/) (cracked by Vicente Gallur Valero), 65 bytes
```
<?php
parse_str($argv[1],$_);
while(!$_['(-0_0)> deal with it']);
```
[Try it online!](https://tio.run/##K8go@P/fxr4go4CrILGoODW@uKRIQyWxKL0s2jBWRyVe05qrPCMzJ1VDUSU@Wl1D1yDeQNNOISU1MUehPLMkQyGzRD1W0/r///9p@fm2SYlFAA "PHP – Try It Online")
Harder than it may look. Edited to be possible on TIO, at the cost of a bunch of bytes. Takes input via `$argv[1]`.
[Answer]
# Bash 4.2, 14 bytes ([cracked](https://codegolf.stackexchange.com/a/135797/12012))
Let's try this again.
```
let ${1,,}
yes
```
This doesn't work on TIO, which uses Bash 4.3. Input is via command-line arguments.
On Linux and with gcc installed, Bash 4.2.53 can be downloaded and built as follows.
```
curl -sSL https://ftp.gnu.org/gnu/bash/bash-4.2.53.tar.gz | tar xz
cd bash-4.2.53
./configure
make -j
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes [Cracked](https://codegolf.stackexchange.com/a/135846/62393)
```
↑ε∞←ø
```
[Try it online!](https://tio.run/##ARkA5v9odXNr///ihpHOteKInuKGkMO4////MTIz "Husk – Try It Online")
A bit of explanation, since this language is still pretty new:
`←ø` gets the first element of an empty list: this returns a value which can assume any type, be it a concrete type or a function, which will then be applied to the input. `∞` creates an infinite list composed by copies of the previous result (which in most cases will mean a list of infinite zeroes). `↑ε` takes elements from this list as long as they are "small" i.e. their absolute value is ≤1; on an infinite list of zeroes this will never stop.
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 4 bytes ([Cracked](https://codegolf.stackexchange.com/a/135368/58826))
```
[1+]
```
[Try it online!](https://tio.run/##SypKzMxLz89J@/8/2lA79v9/AA "Braingolf – Try It Online")
Suuuper easy, but ~~let's see how long it takes~~
Answer:
>
> `-1`, or any number less than `0`.
>
>
>
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes ([cracked by Eric Duminil](https://codegolf.stackexchange.com/a/135516/6828))
```
0until(3.send(gets)==5rescue p)
```
[Try it online!](https://tio.run/##KypNqvz/36A0ryQzR8NYrzg1L0UjPbWkWNPW1rQotTi5NFWhQPP/fwA "Ruby – Try It Online")
Note that this needs to be run in an environment where there's no trailing newline in the result of `gets`, or else it's impossible to make it halt (I think) since anything ending in a newline will error and hit the rescue.
[Answer]
# Bash, 25 bytes ([Cracked](https://codegolf.stackexchange.com/a/135641/21194))
```
export "$1"=help
/bin/yes
```
Inspired by Dennis'. [Try it online.](https://tio.run/##S0oszvj/P7WiIL@oREFJxVDJNiM1p4BLPykzT78ytfj///8A)
[Answer]
# [Retina](https://github.com/m-ender/retina), 78 bytes ([Cracked](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/135384#135384)) ([Cracked with Intended Solution](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/135383#135383))
```
^
1
+`^1(1+)
$1¶$&
s`(?<=^|¶)(1+)(?=¶)(?!.*¶\1+$)
¶(?!1+$)
^(1+)¶\1$
+`1
11
```
Was pretty fun to write, hope it's fun to crack
[Try it online!](https://tio.run/##K0otycxL/P8/jsuQSzshzlDDUFuTS8Xw0DYVNa7iBA17G9u4mkPbNEHCGva2IJa9op7WoW0xhtoqmlxch7YB@RBmHEgNSEKFC2iSIZeh4f//AA "Retina – Try It Online")
Cracked with an unintended solution and the intended solution within a minute of each other. One posted first, one commented first.
Intended solution:
>
> 11111
> or the unary representation of n-1 where n is any perfect number
>
>
>
[Answer]
# Node.js, 23 bytes ([Cracked](https://codegolf.stackexchange.com/a/135560/71612))
```
var crackme =
i=>{while({[i]:NaN}){}}
```
*Grant Davis* solution
>
> `{__proto__:null}`
>
>
>
My solution
>
> `{"toString":process.exit}`
>
>
>
[Answer]
# Java 8, 99 bytes, [Cracked](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/135673#135673)
```
s->{try{Integer i=Integer.parseInt(s),c=i+32767;i+=32767;for(;i!=c;);}catch(Throwable t){for(;;);}}
```
This is a lambda of the type `Consumer<String>`.
Ungolfed:
```
s -> {
try {
Integer i = Integer.parseInt(s), c = i + Short.MAX_VALUE;
i += Short.MAX_VALUE;
while (i != c) ;
} catch (Throwable t) {
while (true) ;
}
}
```
[Try it online!](https://tio.run/##PY4/b8IwEMV3f4rrZotiVa1UBmOWTgxM7YYYjDHh0sSO7AtVFeWzp06T8Jb78zvde6W5m3VonC8v3wPWTYgEZd7JlrCS19ZbwuDlR/CprV1UjDXtuUILtjIpwcGgh44xyJpBIkO53ANeoM6Yf1JEXxxPYGKRRL6GWcvT7XSxg9EO9IMvGtJ611H87faeXOEioJ472ZiYXB54Es9W4@rtdfO@UbjSU3MNkSt80lYJ1VtD9sa/bjH8mHPlgET3z0fWD4uZetiPaaSx1jXEx@jHl5OYaM8Y64c/) (note that the test program will crash on empty input, but the lambda itself would not!) (also, use 'arguments' not 'input' on TIO, as the test program uses arguments, not STDIN)
Intended Answer:
>
> -32767;
> This works because Java keeps has two integer types, `int` and `Integer`. `Integer` is an object that wraps `int`. Also, Java keeps an cache of `Integer`s that box `-127` through `127`. The `!=` operator checks for identity, so through some un-boxing and auto-boxing any number `x` where `x + 32767` is in `[-127, 127]` will end up being the same `Integer` object from the cache, and thus `i != c` will be false.
>
>
>
[Answer]
# Bash 4.2, 10 bytes ([Cracked](https://codegolf.stackexchange.com/a/135625/31625))
```
let $1
yes
```
This doesn't work on TIO, which uses Bash 4.3. Input is via command-line arguments.
On Linux and with gcc installed, Bash 4.2.53 can be downloaded and built as follows.
```
curl -sSL https://ftp.gnu.org/gnu/bash/bash-4.2.53.tar.gz | tar xz
cd bash-4.2.53
./configure
make -j
```
[Answer]
# C, 140 bytes ([Cracked](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/135862#135862))
```
n,i;f(){float x,y,z;for(scanf("%d %d",&n,&z,x=y=0);~((int)x-(int)(1/sqrt(y*2)));x*=(1.5-y*x*x))y=(x=z)/2,i=n-((*(int*)&x)/2),x=*(float*)&i;}
```
Hopefully there aren't too many not-even-close-to-the-intended-inputs that make it halt, but let's see.
[Try it online!](https://tio.run/##HY5Bi8IwEIXv/opQsMyERFdhTyEHQcHDHjzsHwix0UCbdtMKScX96WZnO5d5fI@Z96y8WVtKEF45wKdrezOxJLKYlesjjNYEB9X6ytbXStRB1LNIOusPVL8APkyY5LJgtx1/4gSZ7xFRJa5ht/mUmSeeELOGpGfc7oXXQQLw/xuOdSKE9JDDEkzEq1chj3XGB8DVc8VoqJlaxBDJoz7nw9f36VgRfZXLY2K5f0Tmw0Dy3sRGsKFtzNhs3ta15jYW2XZ/)
[Answer]
## Java: 1760 ([Cracked](https://codegolf.stackexchange.com/a/135401/60951))
I feel it's too mean to golf this one, so I just obfuscated the variable names, and made it 'messy'. As a matter of fact it's so mean, that I'm going to post hints over time, just so I may see it cracked.
Hint 1: this has theoretically infinite valid inputs, but there is one that is the most 'Correct'
```
public class Main {
public static void main(String[] a) {
try {
while (a.length < 2) {
int i = 0;
}
boolean invalid = 1 < 0;
char l = '_';
char h = '-';
char[] DATATWO = a[0].toCharArray();
char[] DATATOW = a[1].toCharArray();
int length = DATATOW.length;
if (DATATWO.length != length) {
invalid = 1 > 0;
}
int transmissionStartIndex = 0;
for (int i = 0; i < length; i++) {
if (DATATWO[i] == l && DATATOW[i] == l) {
transmissionStartIndex = i;
break;
}
}
int DATAONE = 0, reg = 0;
boolean read = 1 < 0, full = 0 < 1;
int bytes_read = 0;
for (int i = transmissionStartIndex; i < length; i++) {
if (DATATOW[i] == l && DATATOW[i + 1] == h) {
bytes_read++;
if (bytes_read == 8) {
read = DATATWO[i] == h;
} else if (bytes_read == 9) {
invalid = (DATATWO[i] == h || invalid);
System.out.println(invalid);
} else if (bytes_read == 18) {
System.out.println(invalid);
invalid = (DATATWO[i] == h || invalid);
if (invalid) {
System.out.println("i36 " + DATATWO[i] + " " + h);
}
full = 1 > 0;
} else if (bytes_read < 8) {
DATAONE += (DATATWO[i] == h ? 1 : 0) << (7 - bytes_read);
} else if (bytes_read < 18) {
reg += (DATATWO[i] == h ? 1 : 0) << (8 - (bytes_read - 9));
} else if (bytes_read > 18) {
invalid = 1 > 0;
}
System.out.println(a[0]);
System.out.println(new String(new char[i]).replace("\0", " ") + "|");
System.out.println(a[1]);
}
}
while (!(Integer.toHexString(DATAONE).equals("0x2b") && (read)
&& Integer.toHexString(reg).equals("0xa6"))) {
System.out.println(System.currentTimeMillis());
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
while (true) {
}
}
}
}
```
[Try it online!](https://tio.run/##lVVRT9swEH5Of8WRB0gUGjVMYmy0TGhDGg@MByrxwKrKTU1jcJPMcUqr0d/enRM7SWmgmqLW9vn8fd/dOZcnsiDdJKXx0/R5s@mk@YSzEEJOsgxuCIvhb6djaWsmicRhkbApzHHPuZOCxbOHERAX/SxLilUxWi8R4xQc4nMaz2QEfTgpPSyLxRIYDKB3rpZr9TdJEk5JDCxeEI7YAwjwROkQRkQAR9PR@Kg2RMrQrQ0o4cfl8HJ4f4sb5KE38mXyHe2XQpCV4@743d4XfkGbnxKoZQ@Mt46j3H8ER5OZ8A4G@kQdZB3JRTNUBS4FibM5yzKWxHeSCHkdT@mySsljIsCps4RDX6Pj3PMqilrGAxvBACXA4aERbEzG23qXlJ2XDhNByXM5X2/JVYi3v66UmGMQdFYJNWXDg1XNjuEx56pcPVwFVT4nK0mzsXZsCbNd3f7Y60C3YgcPgsJcFcSqFXjeeae0KZimsgGcVf6WFrud4kgnaw2UZxR2Ab7UAPUdeFOnCF5fzV13NaB1t8oknftJLv0UXyrJY@eNy7ucQUP1fpj/1KXojK1iaaOx2adTsDHzDVAPDcoUVXBrPepbUr8d78XXb9bEXEWvRfs3BPsKPRf6fXA@Q7dx59w9DMFW2Wf74c8QvgnRxbp/THKxRdLWHqrctORWdTSD37Id0xcoW3ExLRodG7m@oCknIXXs3z37WJXCVRV5tT@AUj3R3eoCjXZ@4FzHks6owK75ky41pS6K69M/OeGZY/eWJxOkwhfSKbJfkuGy7TTmu3mSnNqu6xYfnXaB2hTmQtBYDtmc3jDOWeaYAlTfIMsaRorfzzilqROYsCAkMoygiEWIPJV0erUMaSqx9wCtikRLSuxG4fNQqDTu5KWC2j2vMyZFbizqmDq17qw7m81mPPa7vvmZp1yP9Rx9uvuefw "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), 18 bytes [Cracked](https://codegolf.stackexchange.com/a/135419/44998)
```
1+[#£-0!e>:$_1>|]
```
[Try it online!](https://tio.run/##SypKzMxLz89J@//fUDta@dBiXQPFVDsrlXhDu5rY//8B "Braingolf – Try It Online")
Liiiitle bit harder than the last one, I'll start writing a *real* one after this
>
> The answer is 163
>
>
>
[Answer]
## JavaScript (ES7), 41 bytes ([Hacked & Cracked](https://codegolf.stackexchange.com/a/135432/58563))
*Edit: fixed to prevent it from crashing when given no input at all (thanks @totallyhuman for noticing)*
---
Several solutions probably exist, but the expected one is relatively simple.
```
(x=0)=>{for(;~x/x.length**3!=-2962963;);}
```
Intended solution:
>
> "8e7" (a number in scientific notation passed as a string)
>
> Because: ~"8e7"/"8e7".length\*\*3 = -80000001/3\*\*3 = -80000001/27 = -2962963
>
>
>
[Answer]
# Bash + Utils (Cracked by Dennis), 74 bytes
I hope you enjoy tar, because it's the only utility you can use.
```
cp /bin/tar .
env -i PATH=$PWD I=$? /bin/bash -r -c "$1"
while :;do :;done
```
[Try it online!](https://tio.run/##S0oszvj/P7lAQT8pM0@/JLFIQY8rNa9MQTdTIcAxxMNWJSDcRcHTVsUeoiAJqFxBt0hBN1lBScVQias8IzMnVcHKOiUfTOSl/v//PzU5I19BPTK/VKE8MydHIS@/RCG1ODmxIFVRHQA "Bash – Try It Online")
### Intended crack
>
> `tar -cf --checkpoint=1 --checkpoint-action=exec="/bin/kill $I" .`
>
>
>
[Answer]
# Mathematica, ~~36~~ 26 bytes ([cracked](https://codegolf.stackexchange.com/a/135649/60043))
```
#0[#;$IterationLimit=∞]&
```
A very short loop `#0[#;∞]` that will just keep running itself over and over until it crashes your kernel... (The `$IterationLimit` is just to make sure you get stuck forever for most inputs).
[Try it on Wolfram Sandbox!](https://sandbox.open.wolframcloud.com/) - if you are stuck in an infinite loop, you can wait until you time out, or you can press the square "abort evaluation" icon to the left of the notebook title `(unnamed)`.
**NOTE**: this function changes your `$IterationLimit` settings.
[Answer]
# JavaScript (Node.js), 18 bytes ([Cracked](https://codegolf.stackexchange.com/a/135461/65836))
```
x=>{while(x+"h");}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q66PCMzJ1WjQlspQ0nTuvZ/moaB5n8A "JavaScript (Node.js) – Try It Online")
Answer:
>
> `new Buffer(268435440)` throws an error when `.toString`ed.
>
>
>
[Answer]
# C#, 118 bytes ([Cracked](https://codegolf.stackexchange.com/a/135755/38550))
```
using System;_=>{while(1>0){try{if(Nullable.GetUnderlyingType(Type.GetType(Console.ReadLine()))!=null)break;}catch{}}}
```
I don't expect this to last too long but it is more awkward than it appears to be.
>
> Basically any Nullable classes full name works but it is awkward to find out as it looks like the below :
>
> `System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]`
>
> An easier way to find this string out is to do `typeof(int?).FullName`.
>
>
>
[Answer]
# JavaScript (ES7), 73 bytes ([Cracked](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/136014#136014)!)
```
q=>{r=(n,i=0)=>i>1e3?n:r(n*16807%(2**31-1),i+1);while(r(q)!=627804986){}}
```
Not wanted solutions: brute force. Desired crack involves math.
Note that there are many solutions (4194304) because of modulo.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 170 bytes [cracked!](https://codegolf.stackexchange.com/questions/135365/will-it-halt-robbers/136642#136642)
```
>>,>,>,>,>,[-----------<-<+<--<--->>>>]<++<<+<++[----->+<]>[----------------->+++++++<]>[----->>+<<]>>[-<->]<[--->++++++<]>[--->+<]+>-[-----------------<+>]<[-->-<]>+[+-]
```
[Try it online!](https://tio.run/##ZYxLCoAwEEMPFHODkIuULlQQRHAheP46pfUDJoshmUemY1z35Zy3UuzhduIrUVA9pENZgKIBGmQo@8uz103P0wFGiCTGSHqZjtQhmP8pofFmkEhgLuUC "brainfuck – Try It Online")
[Answer]
# Swift 3, 14 bytes ([Cracked](https://codegolf.stackexchange.com/a/136754/61563))
```
while !false{}
```
To solve this, put your code before or after this statement.
* Your solution must:
+ keep this statement intact, without modifying its code
+ actually let this statement run
- Simply commenting it out, calling `fatalError()`, etc. before it doesn't count.
+ modify the behavior of this statement to prevent it from looping forever
* The solution does not involve crashing the program.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 2 bytes ([Cracked 1](https://codegolf.stackexchange.com/a/135391/41805)) ([Cracked 2](https://codegolf.stackexchange.com/a/135395/30164))
```
:A
```
Note that this will quickly hit the 128 KiB output limit on TIO, causing it to stop, but when run locally it will loop forever, except on the input that breaks it. Finding that input should be fairly easy. Until you do, `:A` will keep sticking its triangular tongue out at you.
Note also that this *should* be just `A` but I broke implicit modes last night. On older interpreter versions `A` would work fine.
Cracks:
>
> Empty input/newline on input is a valid crack. However, barring that, by passing multiple (space separated) inputs to the program, you'll terminate it (if you give 2) or error out (if you give 3 or more).
>
>
>
[Try it online!](https://tio.run/##Sy4sTc0rKf7/38rx//@S1OISAA "cQuents – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 28 bytes [Cracked](https://codegolf.stackexchange.com/a/135519/31957)
```
x=>{while(!x||x.__proto__);}
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q66PCMzJ1VDsaKmpkIvPr6gKL8kPz5e07r2f5pGXmlOjuZ/AA "JavaScript (Node.js) – Try It Online")
Know of anything truthy that dosen't have the `__proto__` property?
] |
[Question]
[
Sixteen piles of cheese are put on a 4x4 square. They're labeled from \$1\$ to \$16\$. The smallest pile is \$1\$ and the biggest one is \$16\$.
The Hungry Mouse is so hungry that it always goes straight to the biggest pile (i.e. \$16\$) and eats it right away.
After that, it goes to the biggest neighboring pile and quickly eats that one as well. (Yeah ... It's *really* hungry.) And so on until there's no neighboring pile anymore.
A pile may have up to 8 neighbors (horizontally, vertically and diagonally). There's no wrap-around.
## Example
We start with the following piles of cheese:
$$\begin{matrix}
3&7&10&5\\
6&8&12&13\\
15&9&11&4\\
14&1&16&2
\end{matrix}$$
The Hungry Mouse first eats \$16\$, and then its biggest neighbor pile, which is \$11\$.
$$\begin{matrix}
3&7&10&5\\
6&8&12&13\\
15&9&üê≠&4\\
14&1&\color{grey}\uparrow&2
\end{matrix}$$
Its next moves are \$13\$, \$12\$, \$10\$, \$8\$, \$15\$, \$14\$, \$9\$, \$6\$, \$7\$ and \$3\$ in this exact order.
$$\begin{matrix}
üê≠&\color{grey}\leftarrow&\small\color{grey}\swarrow&5\\
\small\color{grey}\nearrow&\small\color{grey}\swarrow&\color{grey}\uparrow&\color{grey}\leftarrow\\
\color{grey}\downarrow&\small\color{grey}\nwarrow&\small\color{grey}\nearrow&4\\
\small\color{grey}\nearrow&1&\color{grey}\uparrow&2
\end{matrix}$$
There's no cheese anymore around the Hungry Mouse, so it stops there.
## The challenge
Given the initial cheese configuration, your code must print or return the sum of the remaining piles once the Hungry Mouse has stopped eating them.
For the above example, the expected answer is \$12\$.
## Rules
* Because the size of the input matrix is fixed, you may take it as either a 2D array or a one-dimensional array.
* Each value from \$1\$ to \$16\$ is guaranteed to appear exactly once.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
```
[ [ 4, 3, 2, 1], [ 5, 6, 7, 8], [12, 11, 10, 9], [13, 14, 15, 16] ] --> 0
[ [ 8, 1, 9, 14], [11, 6, 5, 16], [13, 15, 2, 7], [10, 3, 12, 4] ] --> 0
[ [ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16] ] --> 1
[ [10, 15, 14, 11], [ 9, 3, 1, 7], [13, 5, 12, 6], [ 2, 8, 4, 16] ] --> 3
[ [ 3, 7, 10, 5], [ 6, 8, 12, 13], [15, 9, 11, 4], [14, 1, 16, 2] ] --> 12
[ [ 8, 9, 3, 6], [13, 11, 7, 15], [12, 10, 16, 2], [ 4, 14, 1, 5] ] --> 34
[ [ 8, 11, 12, 9], [14, 5, 10, 16], [ 7, 3, 1, 6], [13, 4, 2, 15] ] --> 51
[ [13, 14, 1, 2], [16, 15, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12] ] --> 78
[ [ 9, 10, 11, 12], [ 1, 2, 4, 13], [ 7, 8, 5, 14], [ 3, 16, 6, 15] ] --> 102
[ [ 9, 10, 11, 12], [ 1, 2, 7, 13], [ 6, 16, 4, 14], [ 3, 8, 5, 15] ] --> 103
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~133~~ 130 bytes
```
a=input();m=16
for i in range(m):a[i*5:i*5]=0,
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)
```
[Try it online!](https://tio.run/##hVDbboMwDH3nK/JW6EJFQpJCK74E8RBtbI00AqKtyr6emdil21RpEiSycy4@Hr4up97L2frzrR3PrGJ1xhl8grMcTgmX4kxDuS@gzuRy5E3UTu3rZrOZbeX8cL3EybGrhIne@5E55jwbrf9o4y452Npt9QH@psp4dDu5z5Z1B1fZnfNv7QSQI0DgEQQ6O8VQvEzNojOBTp0anmqeKp4KLrjimpsmiYbR@Qs7X7vYJjMWlGA39EOcJRHMthXZXKuQQ4ZAmjMDOTgrMJkQSxjOSriWsIAVgBGmieoiMErqisAMb4TVQXSPArQpBTwR@tBQv/1KRAZL@cQvPOqHXYmqaJGjtwx6Mugp4uXrEOhW/NDXaCsQrYLcEkBiPrS4ByIr8gnjoNmDq2kvlIGWox/o/X1oElW4@YW3BsaWQat/9gS8v3tbR8rvDFpajqqG/J7yaJcGoWolkopuvgE "Python 2 – Try It Online")
Takes a flattened list of 16 elements.
### How it works
```
a=input();m=16
# Add zero padding on each row, and enough zeroes at the end to avoid index error
for i in range(m):a[i*5:i*5]=0,
# m == maximum element found in last iteration
# i == index of last eaten element
# eaten elements of `a` are reset to 0
while m:i=a.index(m);a[i]=0;m=max(a[i+x]for x in[-6,-5,-4,-1,1,4,5,6])
print sum(a)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 111 bytes
```
i=x=a=input()
while x:x,i=max((y,j)for j,y in enumerate(a)if i>[]or 2>i/4-j/4>-2<i%4-j%4<2);a[i]=0
print sum(a)
```
[Try it online!](https://tio.run/##jVTLbtswELzzKxYuAkiAjIgPSa4T@UcEHVRHQWjEsiHZiJyfd3eXj9ht0fZAQFwOZ4azpI6X09thUNft4aWvF4vF1dZz3dV2OJ5PSSo@3ux7D/N6zmy97@YkuWS79PUwwi67gB2gH877fuxOfdKl9hXspmlxUW3so1nuHs1mqZ7tA34@mGeVPnWNbetcHEc7nGA673HTFTWF2HZTP0ENjWigAZMBaBwKh2wzrBT4VeKocKyoInFNShw5Vr5zBXdI3CkRK8sW2uwbLJcbyJlyRVQEJRDDpad08EBQeNmKK7kzQmJgfqWUHqp58Y8uWS73TtXfXEqiZGjhATIQsICMnrT3TNLsm03Q@cw9pWaX2vnhoxQMLx2cE9RMWfhgZDgJGSBJSVh141LFMIOxr@ikVypif/LIkLmuBl508mXTBE6XUuyn8QfNQ4M41xBG1OXbolg3chYuTn2j6NIvfYv/v2eRs1qxz986Gu@BCXk6Lu/eqWifRHnvU@bqH6RVJC09hbkljTJ3pFq0ohumj37kN4XMRJ6Fq6yRosBpRZnn3CjdCnrU9AwzcFvpdX/aY8JPMxSndC2gG0einYG2MI4wPJtpNrYC@P@BqPdu/@OlW@MWAf3cb4H@M9ef "Python 2 – Try It Online")
Method and test cases adapted from [Bubbler](https://codegolf.stackexchange.com/a/176257/20260). Takes a flat list on STDIN.
The code checks whether two flat indices `i` and `j` represent touching cells by checking that both row different `i/4-j/4` and column difference `i%4-j%4` are strictly between -2 and 2. The first pass instead has this check automatically succeed so that the largest entry is found disregarding adjacency.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~50~~ ~~49~~ 47 bytes
```
16:HZ^!"2G@m1ZIm~]v16eXK68E16b"Ky0)Y)fyX-X>h]s-
```
Input is a matrix, using `;` as row separator.
[Try it online!](https://tio.run/##y00syfn/39DMyiMqTlHJyN0h1zDKM7cutszQLDXC28zC1dAsScm70kAzUjOtMkI3wi4jtlj3//9oYx0Fcx0FQwMdBVNrBTMdBQsgxwiIja0VDE11FCyBTEMdBRMgzwTIBCKgGqNYAA) Or [verify all test cases](https://tio.run/##hZA/a8MwEMX3foprtoAMPluS7QhCh5YkZM3g2iikhZQO8dRSmqVf3bk/ciAQ6GAZnd57v7sb3r5P42FEv1h3@8dZsXoasNsMf/EH/bHd@voF/ftse87nr/OPc5u1y8/4lY3P3e9u7K2B0kBhAAM4A95AZaAOgFxC@nIDDV1JhKRF0qCPD31Nf3rhahAhOeUtaZ2EVkECuEA3Sz6UOhXsLa9RlCCLOzx5dKmIoi@lhUrFThGEp5Oas8lXCoDdLjCtVh2WQeIaRfIMVuKQNIXOp4hpINQgl1aTJ2kQknpd2gsqo9FQN6kDB2jTKdTq5tl3HVgyOZrb@2dP8QI).
### Explanation
```
16:HZ^! % Cartesian power of [1 2 ... 16] with exponent 2, transpose. Gives a
% 2-row matrix with 1st column [1; 1], 2nd [1; 2], ..., last [16; 16]
" % For each column, say [k; j]
2 % Push 2
G@m % Push input matrix, then current column [k; j], then check membership.
% This gives a 4√ó4 matrix that contains 1 for entries of the input that
% contain k or j
1ZI % Connected components (based on 8-neighbourhood) of nonzero entries.
% This gives a 4√ó4 matrix with each connected component labeled with
% values 1, 2, ... respectively
m~ % True if 2 is not present in this matrix. That means there is only
% one connected component; that is, k and j are neighbours in the
% input matrix, or k=j
] % End
v16e % The stack now has 256 values. Concatenate them into a vector and
% reshape as a 16√ó16 matrix. This matrix describes neighbourhood: entry
% (k,j) is 1 if values k and j are neighbours in the input or if k=j
XK % Copy into clipboard K
68E % Push 68 times 2, that is, 136, which is 1+2+...+16
16 % Push 16. This is the initial value eaten by the mouse. New values will
% be appended to create a vector of eaten values
b % Bubble up the 16√ó16 matrix to the top of the stack
" % For each column. This just executes the loop 16 times
K % Push neighbourhood matrix from clipboard K
y % Copy from below: pushes a copy of the vector of eaten values
0) % Get last value. This is the most recent eaten value
Y) % Get that row of the neighbourhood matrix
f % Indices of nonzeros. This gives a vector of neighbours of the last
% eaten value
y % Copy from below: pushes a copy of the vector of eaten values
X- % Set difference (may give an empty result)
X> % Maximum value. This is the new eaten value (maximum neighbour not
% already eaten). May be empty, if all neighbours are already eaten
h % Concatenate to vector of eaten values
] % End
s % Sum of vector of all eaten values
- % Subtract from 136. Implicitly display
```
[Answer]
# PHP, ~~177 174~~ 171 bytes
```
for($v=16;$v;$u+=$v=max($p%4-1?max($a[$p-5],$a[$p-1],$a[$p+3]):0,$a[$p-4],$a[$p+4],$p%4?max($a[$p-3],$a[$p+1],$a[$p+5]):0))$a[$p=array_search($v,$a=&$argv)]=0;echo 120-$u;
```
Run with `-nr`, provide matrix elements as arguments or [try it online](http://sandbox.onlinephpfunctions.com/code/c119f93dedfb54eeb4273062815523e07a41f22d).
[Answer]
# JavaScript, 122 bytes
I took more than a couple of wrong turns on this one and now I've run out of time for further golfing but at least it's working. Will revisit tomorrow (or, knowing me, on the train home this evening!), if I can find a minute.
```
a=>(g=n=>n?g([-6,-5,-4,-1,1,4,5,6].map(x=>n=a[x+=i]>n?a[x]:n,a[i=a.indexOf(n)]=n=0)|n)-n:120)(16,a=a.flatMap(x=>[...x,0]))
```
[Try it online](https://tio.run/##jVPLbtswELznK3iUYErhig@7AeTeCzQ59KgKMJNYhgKXCmKjUIH8u7tcPqogKdrDAsRydmY4Kz3Zn/b08DI@n6t7e78/Vm563F@G9mLbbXFoXbt1nw9FVxleaV4pXgEHrrjmpq9/2OdiRkBru3nVjj1C8dTfOG67sbX16B73891QuLJHIlG@urJyN9CIsgDDLSKGoz1/DSxdXdczF31ZXh4md5qO@/o4ofJVxzqmOGMSq8GCnmNH48lgrbE2vgN4B4AlsPOJOjgBOAmIBdMz7F1fM0GEG0/kgR5CYIiEAZzGdRRdU0cEG16KqbeEEIGSrj50SGIiumz@7hA8IQF1vIY0TvSQ/cjo1wuTZ7Lg36aWhJIcyuCFHqEJbAKYkpNEqGMkkF7h5b0geGyTHTY5xGTqT2QQdXTeisjzPOwysaKPZFElxpBO3qGKTxRpLZRniiGr0hfSkGpk1CFGuVALmZu41v/fVGRcb8jjuy3m3auUY2CKzoOGjBmYpUcQzT8o15nSRAK1pMwiC0p5lf/ML9/ubuvT@WV0h3H4VczlasfaLdutBjyX9dM0ut13tysvvwE)
[Answer]
# Powershell, ~~143~~ ~~141~~ ~~136~~ ~~130~~ ~~122~~ 121 bytes
```
$a=,0*5+($args|%{$_+0})
for($n=16;$i=$a.IndexOf($n)){$a[$i]=0
$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]}$a|%{$s+=$_}
$s
```
Less golfed test script:
```
$f = {
$a=,0*5+($args|%{$_+0})
for($n=16;$i=$a.IndexOf($n)){
$a[$i]=0
$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]
}
$a|%{$s+=$_}
$s
}
@(
,( 0 , ( 4, 3, 2, 1), ( 5, 6, 7, 8), (12, 11, 10, 9), (13, 14, 15, 16) )
,( 0 , ( 8, 1, 9, 14), (11, 6, 5, 16), (13, 15, 2, 7), (10, 3, 12, 4) )
,( 1 , ( 1, 2, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16) )
,( 3 , (10, 15, 14, 11), ( 9, 3, 1, 7), (13, 5, 12, 6), ( 2, 8, 4, 16) )
,( 12 , ( 3, 7, 10, 5), ( 6, 8, 12, 13), (15, 9, 11, 4), (14, 1, 16, 2) )
,( 34 , ( 8, 9, 3, 6), (13, 11, 7, 15), (12, 10, 16, 2), ( 4, 14, 1, 5) )
,( 51 , ( 8, 11, 12, 9), (14, 5, 10, 16), ( 7, 3, 1, 6), (13, 4, 2, 15) )
,( 78 , (13, 14, 1, 2), (16, 15, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12) )
,( 102, ( 9, 10, 11, 12), ( 1, 2, 4, 13), ( 7, 8, 5, 14), ( 3, 16, 6, 15) )
,( 103, ( 9, 10, 11, 12), ( 1, 2, 7, 13), ( 6, 16, 4, 14), ( 3, 8, 5, 15) )
) | % {
$expected, $a = $_
$result = &$f @a
"$($result-eq$expected): $result"
}
```
Output:
```
True: 0
True: 0
True: 1
True: 3
True: 12
True: 34
True: 51
True: 78
True: 102
True: 103
```
Explanation:
**First**, add top and bottom borders of 0 and make a single dimensional array:
```
0 0 0 0 0
# # # # 0
# # # # 0
# # # # 0
# # # # 0
‚Üì
0 0 0 0 0 # # # # 0 # # # # 0 # # # # 0 # # # # 0
```
Powershell returns `$null` if you try to get the value behind the end of the array.
**Second**, loop `biggest neighbor pile` started from 16 to non-zero-maximum. And nullify it (The Hungry Mouse eats it).
```
for($n=16;$i=$a.IndexOf($n)){
$a[$i]=0
$n=(-1,1+-6..-4+4..6|%{$a[$i+$_]}|sort)[-1]
}
```
**Third**, sum of the remaining piles.
[Answer]
# [R](https://www.r-project.org/), ~~128~~ ~~124~~ ~~123~~ ~~112~~ 110 bytes
```
function(r){r=rbind(0,cbind(0,r,0),0)
m=r>15
while(r[m]){r[m]=0
m=r==max(r[which(m)+c(7:5,1)%o%-1:1])}
sum(r)}
```
[Try it online!](https://tio.run/##LU3LCsIwELz3K7wUNjiFbB9Wi/FHpIcaLQ2YFtYWC9JvjxGEZYZ5MCuh352z0C@jnd00kqiPGLm58U4a9s8CreIl3siFq@Q9uOeD5OrbWI5o9C8xxndrdGNqB/Jqb6luKrBKpzTjhlu1Ja/Fxw9b6Ml3s7iVLJ3AGszgHIwcNbjAAXxACS5R4Ii4UakoS6XCFw "R – Try It Online")
It creates a 4x4 matrix (which helped me to visualize things), pads it with 0's, then begins from 16 and searches it's surrounding "piles" for the next largest, and so forth.
Upon conclusion, it does output a warning, but it is of no consequence and does not change the result.
**EDIT:** -4 bytes by compressing the initialization of the matrix into 1 line.
**EDIT:** -1 thanks to Robert Hacken
**EDIT:** -13 bytes combining Giuseppe and Robin Ryder's suggestions.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
EA⭆ι§αλ≔QθW›θA«≔⌕KAθθJ﹪θ⁴÷θ⁴≔⌈KMθA»≔ΣEKA⌕αιθ⎚Iθ
```
[Try it online!](https://tio.run/##TU9Na8MwDD03v0LkJIMHTZvug55Cx0YGgY7uVnowjWlNHTtxnK4w9tszOWlgFkbS89N71vEs3NEK3fdbp4zHQtSYm7rzyDjsPGGnACkOmc9NKW8oOGhGZx1lbatOBuPPmEND/fdZaQn47qTw0mHDIc5ixuAnmt2pb8qUuJXykmkdDBo2Ts4@uqr@sljYstM2TKb0khv/qq6qlCMQeHedQtxU1VWDVGGtk8gmpXGNYLyOfqcv7ogb1vhnPXyFdlFsGt1oKRxSMUpsROuxIde@30OIJQd44pDMKa8OnJBHqp4JWdBdBiRZEfJCXUI5HZCUKuqSwF0cgKJ/uOo/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
EA⭆ι§αλ
```
Convert the input numbers into alphabetic characters (A=0 .. Q=16) and print them as a 4x4 grid.
```
≔Qθ
```
Start by eating the Q, i.e. 16.
```
W›θA«
```
Repeat while there is something to eat.
```
≔⌕KAθθ
```
Find where the pile is. This is a linear view in row-major order.
```
J﹪θ⁴÷θ⁴
```
Convert to co-ordinates and jump to that location.
```
≔⌈KMθ
```
Find the largest adjacent pile.
```
A»
```
Eat the current pile.
```
≔ΣEKA⌕αιθ
```
Convert the piles back to integers and take the sum.
```
⎚Iθ
```
Clear the canvas and output the result.
[Answer]
# [Haskell](https://www.haskell.org/), 163 bytes
```
o f=foldl1 f.concat
r=[0..3]
q n=take(min(n+2)3).drop(n-1)
0#m=m
v#m=[o max$q y$q x<$>n|y<-r,x<-r,m!!y!!x==v]!!0#n where n=map(z<$>)m;z w|w==v=0|0<1=w
f=o(+).(16#)
```
[Try it online!](https://tio.run/##jVNNb5tAEL3zK4baB5AN2mEBO4rXl17bU48OB5SAHMWAAzTYkf@7O/vBFjepFKNZrWdn3nszs7vPu5ficLheGyhF2RyeDghl@NjUj3nvtGLHwpBnzivUos9fCq96rr16EfncD5/a5ujVAfoOm1Wict5o3TVQ5af5K5zJTpv5tr6cN0G7PMmlct2z656EeMtcl81qGPZFWxBylR@9dwr2q/t3GC4DRQh2YRsUg1OKxlv4oYfpzL/2Rdd3IGDngPnt6IuXAJwsIsNsSZ6EdinZimwtPUhniGSMPHfKQxlImUixmGZAviAAdgO8loAyQYaqJDTAOmmESQz5SnmYliMpIf4cGE0CVyGfKlakzKiO/q8Yp8AqITFhOMIoGrT6uNEvBagalBRZazwF5jeKudamiktUUqqTVGe5Ak5Mq3CsSsqQxChjI6s4@tDkUeTflqLhS@z0mMVZ6pmP6KRnlBz/i6y7Z2cem9LZOD7V77E9ll3dqEixG@Tkts18wq5nk5pr8PWJGuTV@kbzh6nbuxKPfdaIphLNxU1v0qlmZNEXoVcWOjVA8RTakklojawvR@Y4TpU/1/Qi6Qn/hOPv/lff/qhhLv@D9yDf6/e8KyDYQrdvBrCOxQK@EdSWVtqqM6@0x76vtt31Dw "Haskell – Try It Online")
The `f` function takes the input as a list of 4 lists of 4 integers.
### Slightly ungolfed
```
-- helper to fold over the matrix
o f = foldl1 f . concat
-- range of indices
r = [0 .. 3]
-- slice a list (take the neighborhood of a given coordinate)
-- first we drop everything before the neighborhood and then take the neighborhood itself
q n = take (min (n + 2) 3) . drop (n - 1)
-- a step function
0 # m = m -- if the max value of the previous step is zero, return the map
v # m =
-- abuse list comprehension to find the current value in the map
-- convert the found value to its neighborhood,
-- then calculate the max cell value in it
-- and finally take the head of the resulting list
[ o max (q y (q x<$>n)) | y <- r, x <- r, m!!y!!x == v] !! 0
# n -- recurse with our new current value and new map
where
-- a new map with the zero put in place of the value the mouse currently sits on
n = map (zero <$>) m
-- this function returns zero if its argument is equal to v
-- and original argument value otherwise
zero w
| w == v = 0
| otherwise = w
-- THE function. first apply the step function to incoming map,
-- then compute sum of its cells
f = o (+) . (16 #)
```
[Answer]
# JavaScript (ES7), 97 bytes
Takes input as a flattened array.
```
f=(a,s=p=136,m,d)=>a.map((v,n)=>v<m|(n%4-p%4)**2+(n-p)**2/9>d||(q=n,m=v))|m?f(a,s-m,a[p=q]=0,4):s
```
[Try it online!](https://tio.run/##jZLJbsJADEDv/QpfEBmYQGbJ1nboqV@BOERAuogskCrikH@nzsQDaatWPVjJjOznFzvvWZs129Nb/eGX1W5/ueTGy3hjaiNUxAu@Y2aVLYqs9ryWl3hoH4vOKyfaryeazWZy7pV@3b8s09Wu67yjKXlhWsa64invUX7Bs3VtjhsTcM3um8vD@g5gDaA5gMKQGAIjxIgwYoyEg8B7gfciwHOKT8wVWCMwT0Sw4bBcQjCgEkKklCIIZVOpNKRWMSHV0AL0V5SgtN5M/7SyLQIyk79YCYuyaeHIKCWsIAtFhpJaSGqhRyg1WKmRuDNKRgYhmQkq10MbYbHOSt6G5VTccJwS6Vh1pzTiQei09JXlJuGGbz/J1cejT6Zedqp9D8cKaVxq1EfS4sL/boJYcTJ4fdvSdauaHByD1mN/hogcnZcI5N8wt8OIivUNdoUjDAaYutss8ur0nG1fvTOYFWyrsqkO@8WhesGLOUz7yynMc@/MGLt8Ag "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f= recursive function taking:
a, // - a[] = flattened input array
s = // - s = sum of cheese piles, initialized to 1 + 2 + .. + 16 = 136
p = 136, // - p = position of the mouse, initially outside the board
m, // - m = maximum pile, initially undefined
d // - d = distance threshold, initially undefined
) => //
a.map((v, n) => // for each pile v at position n in a[]:
v < m | // unless this pile is not better than the current maximum
(n % 4 - p % 4) ** 2 // or (n % 4 - p % 4)²
+ (n - p) ** 2 / 9 // + (n - p)² / 9
> d || // is greater than the distance threshold:
(q = n, m = v) // update m to v and q to n
) // end of map()
| m ? // if we've found a new pile to eat:
f( // do a recursive call:
a, // pass a[] unchanged
s - m, // update s by subtracting the pile we've just eaten
a[p = q] = 0, // clear a[q], update p to q and set m = 0
4 // use d = 4 for all next iterations
) // end of recursive call
: // else:
s // stop recursion and return s
```
[Answer]
# [Julia](https://julialang.org), ~~133~~ 127 bytes
```
*(A,S=136,I=keys(A))=((v,r,c)=maximum(i->(get(A,i,0),i[1],i[2]),I);S-=v;v>0 ? (A[r,c]=0;A*S*[(r+i,c+j) for i=-1:1,j=-1:1]) : S)
```
`-6` bytes by @MarcMush, thx!
[Attempt This Online!](https://ato.pxeger.com/run?1=jVK7TsMwFJUY8xVHwGAXt7LjJE2xXNSxCwyFKcpQQYtSaEGlrWDiQ1i68FHwNdxrA0LiIRY79j1PK0_Ps_V1M96-7uiL8WoMjypBlcEihXHIUaCL0sHQ0cBo9OjbwmQwOUxRw_ehiVHCoEfXjmEFeBaBOQl1HTMti2SfDEMDi-yLR49R7JJ-9zDM0OGCrg2DCRGULbulIL8UJbIPhiWGJWFi5Y4sytDBOtbosQ1nJTThkUaPNBRh5ffwhvl5bK8D0LEBs_JoksXuHDo8TcZhdGjfDQmjUsbPGSl5qBLrsR6pUqLfXiJQumVSJ8keCVlap2KgRt7YQg391eThTgyk9EJs1FKdSz8f3zfz9VyIy8mKgI3SUjWVqWlJa4npzRKNH0pHQqO237hNX-MIYlARu_baBXVVieVBo84PZh-Mtjk0aha2WkocYiSf16tpu3x5bP0rT9Pu_xxJUZgfkwxao9bfOb7GKHguhsfq5OxUev6XE-B22SxW1wuxuy9aNKPgnU4H-4IxuzKZLC4ie7uN-xs)
readable version:
```
*(A,S=136,I=keys(A))=(
(v,r,c)=maximum(i->(get(A,i,0),i[1],i[2]),I);S-=v;
v>0 ? (A[r,c]=0;A*S*[(r+i,c+j) for i=-1:1,j=-1:1]) : S)
```
* input: matrix (not a list of lists)
* works for arbitrary shaped matrices with positive numbers in it - as long as the path taken by the mouse is uniquely determined by the numbers.
* interesting math questions:
+ what is the expected outcome of this "game"? (i got a value (approx.) between 18.2 and 18.3 with simulation
+ what is the expected length of the path?
[Answer]
# Java 10, ~~272~~ ~~248~~ ~~239~~ 237 bytes
```
m->{int r=0,c=0,R,C,M=16,x,y,X=0,Y=0;for(;M-->0;)if(m[M/4][M%4]>15)m[r=M/4][c=M%4]=0;for(;M!=0;m[r=X][c=Y]=0)for(M=0,C=9;C-->0;)try{if((R=m[x=r+C/3-1][y=c+C%3-1])>M){M=R;X=x;Y=y;}}finally{continue;}for(var Z:m)for(int z:Z)M+=z;return M;}
```
The cells are checked the same as in [my answer for the *All the single eights* challenge](https://codegolf.stackexchange.com/a/175766/52210).
-24 bytes thanks to *@OlivierGrégoire*.
-11 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##pZJBb6MwEIXv@RXeQyVQhhQHQ5JaziVnekgvSREHlpIVXXAqQrKhiN@enTG0UrXSatEeQGaMv/fmjV@TS@K8vvy8pUVyOrEwyXU7YSzXdVYdkjRjj/RpCiy18B3FUcxKW2K1m@DrVCd1nrJHppm6lc66pT8r5UKKzxY2ECoewBUa2GFhr1x5OFaWDB1n7Uo7P1hlFN6LOArvRLzmvl1GlTKFVFHp8/9vuKK9He3ssW5TPUTmRq3kpsfVVdMi0tqqMrqqarq59xweR41Kp5s7Wtrr0G5DtZU7dZV71ciuO@Q6KYqmTY@6zvU5kx2BL0nFnh9KI0IdvT882@FUvcsqq8@VZqHsbpL6fzt/L7D/IYbLMX9hJYZoPdVVrn9gVondJ/jUnOqsnB3P9ewNt@pCW3qWWjr7xYZY21aAB3PgHbQ@BLCAJa44FjhwF1b04QEXwH3gQdfZZgr/Rl4ChxWeJQZHtiH0PB8lF7R2UR3VxDgyx@MeiC@eV@SXXM//xzMxfHOWGyZyeqMe2Z8DNTCHJYjRZA99It1HQIAAitgjsE8ZcdMMySIX5mNzJp8f0XLS8Ychuj0OcMoG7o@eIAXaXwNBCbj9DBcmmEFS0P0ZSR4GZLyhRUzhL/McRf56D9Ca6INGKjVAIh6lEoz2/Ad50ZMDwokPtFH5JHeT7vYb)
**Explanation:**
```
m->{ // Method with integer-matrix parameter and integer return
int r=0, // Row-coordinate for the largest number, starting at 0
c=0, // Column-coordinate for the largest number, starting at 0
R,C, // Row and column indices (later reused as temp integers)
M=16, // Largest number the mouse just ate, starting at 16
x,y,X=0,Y=0; // Temp integers
for(;M-->0;) // Loop `M` in the range (16, 0]:
if(m[M/4][M%4]>15) // If the current cell is 16:
m[r=M/4][c=M%4] // Set `r,c` to this coordinate
=0; // And empty this cell
// (after this first loop, `M` will be -1)
for(;M!=0; // Loop as long as the largest number `M` isn't 0:
; // After every iteration:
m[r=X][c=Y] // Change the `r,c` coordinates,
=0) // And empty this cell
for(M=0, // Reset `M` to 0
C=9;C-->0;) // Inner loop `C` in the range (9, 0]:
try{if((R= // Set `R` to:
m[x=r+C/3-1] // If `C` is 0, 1, or 2: Look at the previous row
// Else-if `C` is 6, 7, or 8: Look at the next row
// Else (`C` is 3, 4, or 5): Look at the current row
[y=c+C%3-1]) // If `C` is 0, 3, or 6: Look at the previous column
// Else-if `C` is 2, 5, or 8: Look at the next column
// Else (`C` is 1, 4, or 7): Look at the current column
>M){ // And if the number in this cell is larger than `M`
M=R; // Change `M` to this number
X=x;Y=y;} // And change the `X,Y` coordinate to this cell
}finally{continue;}
// Catch and ignore ArrayIndexOutOfBoundsExceptions
// (try-finally saves bytes in comparison to if-checks)
for(var Z:m) // Then loop over all rows of the matrix:
for(int z:Z) // Inner loop over all columns of the matrix:
M+=z; // And sum them all together in `M` (which was 0)
return M;} // Then return this sum as result
```
[Answer]
# SAS, ~~236~~ 219 bytes
Input on punch cards, one line per grid (space-separated), output printed to the log.
This challenge is slightly complicated by some limitations of arrays in SAS:
* There is no way to return the row and column indexes of a matching element from multidimensional data-step array - you have to treat the array as 1-d and then work them out for yourself.
* If you go out of bounds, SAS throws an error and halts processing rather than returning null / zero.
## Updates:
* Removed `infile cards;` statement (-13)
* Used wildcard `a:` for array definition rather than `a1-a16` (-4)
## Golfed:
```
data;input a1-a16;array a[4,4]a:;p=16;t=136;do while(p);m=whichn(p,of a:);t=t-p;j=mod(m-1,4)+1;i=ceil(m/4);a[i,j]=0;p=0;do k=max(1,i-1)to min(i+1,4);do l=max(1,j-1)to min(j+1,4);p=max(p,a[k,l]);end;end;end;put t;cards;
<insert punch cards here>
;
```
## Ungolfed:
```
data; /*Produce a dataset using automatic naming*/
input a1-a16; /*Read 16 variables*/
array a[4,4] a:; /*Assign to a 4x4 array*/
p=16; /*Initial pile to look for*/
t=136; /*Total cheese to decrement*/
do while(p); /*Stop if there are no piles available with size > 0*/
m=whichn(p,of a:); /*Find array element containing current pile size*/
t=t-p; /*Decrement total cheese*/
j=mod(m-1,4)+1; /*Get column number*/
i=ceil(m/4); /*Get row number*/
a[i,j]=0; /*Eat the current pile*/
/*Find the size of the largest adjacent pile*/
p=0;
do k=max(1,i-1)to min(i+1,4);
do l=max(1,j-1)to min(j+1,4);
p=max(p,a[k,l]);
end;
end;
end;
put t; /*Print total remaining cheese to log*/
/*Start of punch card input*/
cards;
4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16
8 1 9 14 11 6 5 16 13 15 2 7 10 3 12 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
10 15 14 11 9 3 1 7 13 5 12 6 2 8 4 16
3 7 10 5 6 8 12 13 15 9 11 4 14 1 16 2
8 9 3 6 13 11 7 15 12 10 16 2 4 14 1 5
8 11 12 9 14 5 10 16 7 3 1 6 13 4 2 15
13 14 1 2 16 15 3 4 5 6 7 8 9 10 11 12
9 10 11 12 1 2 4 13 7 8 5 14 3 16 6 15
9 10 11 12 1 2 7 13 6 16 4 14 3 8 5 15
; /*End of punch card input*/
/*Implicit run;*/
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~42~~ 41 [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")
```
16{×⍺:a∇⍨+/,m×⌈/⌈/⊢⌺3 3⊢a←⍵×~m←⍺=⍵⋄+/,⍵}⊢
```
[Try it online!](https://tio.run/##hVFLTgJBEN1zitrNTJTQNd09gyYeZhKDIUIwhI0hujKICkYXhrWuvIAbttykL4KvqhvFGOOCSXfX@9R7NBeD9ullMxidbcPjS38UZk9m28OXq@lmFZbr4ybMb8Py/aBzOMTDYt7R3/1bWKwtWRwaoMPyY7O6HuppfYJbeLgBA4crILbbCSZTeb57HePYE@FsdJ4BlvWa/iDDA8bjq1YeZs85OSJLVBJxkZMnqohqom6Rc0nMxIboCBdL7Ig9cVUUEzKJ3AUNc8wAYSUrRPFeZWtcjHhAj9w@mXVu5fWnswgaNS9/OXMky9zrgBUvMhzNrO4AZawhBtjRJbJNzlacZCsPSCUQCWtB9pqGdSeoQ5MxL9W5/A4dDVNOVjUfGzOJIMVGAZiItftia7DYqtNdjVYm4WOKqCv/TCm6YPtdbLsTlWYq7fifAsGuu8l7v9dUv9PcytNdRMpqhip5syn/pteRXinD7ehJK9Ftq/0J "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~31 30~~ 29 bytes
```
³œiⱮZIỊȦ
⁴ṖŒPŒ!€Ẏ⁴;ⱮṢÇƇṪ
FḟÇS
```
Since the method is far too slow to run within 60s with the mouse starting on `16` this starts her off at `9` and limits her ability such that she is only able to eat `9`s or less **[Try it online!](https://tio.run/##y0rNyan8///Q5qOTMx9tXBfl@XB314llXJYPd047Oing6CTFR01rHu7qs7QGSj7cuehw@7H2hztXcbk93DH/cHvw////o6MVLHUUDA2A2BCIjWK5dKIVgCwFIyC2AIoYg0XMgCwgVjAB0iZgEWMgzxyITYEiprGxAA "Jelly – Try It Online")** (thus here she eats `9, 2, 7, 4, 8, 6, 3` leaving `97`).
### How?
```
³œiⱮZIỊȦ - Link 1, isSatisfactory?: list of integers, possiblePileChoice
³ - (using a left argument of) program's 3rd command line argument (M)
Ɱ - map across (possiblePileChoice) with:
œi - first multi-dimensional index of (the item) in (M)
Z - transpose the resulting list of [row, column] values
I - get the incremental differences
Ị - insignificant? (vectorises an abs(v) <= 1 test)
Ȧ - any and all? (0 if any 0s are present in the flattened result [or if it's empty])
⁴ṖŒPŒ!€Ẏ⁴;ⱮṢÇƇṪ - Link 2, getChosenPileList: list of lists of integers, M
‚Å¥ - literal 16
·πñ - pop -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
ŒP - power-set -> [[],[1],[2],...,[1,2],[1,3],...,[2,3,7],...,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]]
€ - for each:
Œ! - all permutations
Ẏ - tighten (to a single list of all these individual permutations)
‚Å¥ - (using a left argument of) literal 16
Ɱ - map across it with:
; - concatenate (put a 16 at the beginning of each one)
·π¢ - sort the resulting list of lists
Ƈ - filter keep those for which this is truthy:
Ç - call last Link as a monad (i.e. isSatisfactory(possiblePileChoice)
·π™ - tail (get the right-most, i.e. the maximal satisfactory one)
FḟÇS - Main Link: list of lists of integers, M
F - flatten M
Ç - call last Link (2) as a monad (i.e. get getChosenPileList(M))
ḟ - filter discard (the resulting values) from (the flattened M)
S - sum
```
[Answer]
# J, 82 bytes
```
g=.](]*{:@[~:])]_1}~[:>./]{~((,-)1 5 6 7)+]i.{:
[:+/[:(g^:_)16,~[:,0,~0,0,0,.~0,.]
```
[Try it online!](https://tio.run/##hZFNTsMwEIX3PcUsWCQ0uBn/pbEUxD0i0wWiLWx6gKi5evDMxOCwADlSFvPeN8/Pn8tyGVSs4uMUXsY5xDqe8D6P4Vkd4jRXVfNUIzjw0NX7@KGmsDsPagz7wxiqy2s41eibJG/aZm4bOir9VVx272/XG6CGAc5g03kAAx1gC0w70ggNoIMeECEJMH2AHkCLty2sSZ@GJLWs9kRJWiGAhhVtCJscsK4vEcg6w2PHiI65PTkTdA1kiUgxBGEKBOlcjtAzC3mz4TiaoZqhtkBsSiBTroHkRRFlE7mK7xj2VxuyXhqQEJyAIoovY2iPMBxuGXJnKZXyi7XL92I2laU5nDC6Y9mHyTs0P4b7p97cR7sppBRgjm6ynfumd/WcyP1AzN8QeRbPRrtCViBBli8 "J – Try It Online")
I plan to golf this more tomorrow, and perhaps write a more J-ish solution similar to this [one](https://codegolf.stackexchange.com/questions/175724/all-the-single-eights/175742#175742), but I figured I'd try the flattened approach since I hadn't done that before.
[Answer]
# [Red](http://www.red-lang.org), 277 bytes
```
func[a][k: 16 until[t:(index? find load form a k)- 1
p: do rejoin[t / 4 + 1"x"t % 4 + 1]a/(p/1)/(p/2): 0
m: 0 foreach d[-1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1][j: p + d
if all[j/1 > 0 j/1 < 5 j/2 > 0 j/2 < 5 m < t: a/(j/1)/(j/2)][m: t]]0 = k: m]s: 0
foreach n load form a[s: s + n]s]
```
[Try it online!](https://tio.run/##hVLbasJAEH3PVxyEglIkO7lpQy//0NdlH4JJaKImohH8ezszG4tVaQnZzezOnHPmTPZVef6sSuuCOse5PnYrWzi7zkEZjt3QbOyQT5uurE4fqHnHpi9K1P1@iwLr2RwU7HKUPfZV2zedHRAiwTNocpoMePLfrginu5BmskazHCbY8iIoVbH6QmnnBHPihWSZ08lAXv6Qcz52ts2xY6gyaGoUm41tQ8I7Y8j@ipT3aIwjjbe8DjmYuFViPp85y7SDcwZv4A637iBSLiq669YsXx2Yr3MHd97tm25ADctPAsRABNbEUQpkwAJYckQRiLUa4EWiGJSAUjbSwSG4BllyOWdxgiSSgvhELUuVYCGREToGRnIHQpoV69WNEoE2Kib6W4lkpXpLvkzwaOSOVRRziC7hYtnJo3ZiIRapqSRmkihexAKSap/kVTIRo/OfheiRJ57@4gIpajoaay5lMgKPI3R3INr0OIFEGzDeWPHGNzcSyCgjJbjxJL7gq3mZzuN/m2@U/JrAOKvEe6LlKk0hY@0se6DkIchiBMm0LPkBGSEF5PwN "Red – Try It Online")
It's really long solution and I'm not happy with it, but I spent so much time fixing it to work in TIO (apparently there are many differences between the Win and Linux stable versions of Red), so I post it anyway...
## More readable:
```
f: func [ a ] [
k: 16
until [
t: (index? find load form a n) - 1
p: do rejoin [ t / 4 + 1 "x" t % 4 + 1 ]
a/(p/1)/(p/2): 0
m: 0
foreach d [ -1 0x-1 1x-1 -1x0 1x0 -1x1 0x1 1 ] [
j: p + d
if all[ j/1 > 0
j/1 < 5
j/2 > 0
j/2 < 5
m < t: a/(j/1)/(j/2)
] [ m: t ]
]
0 = k: m
]
s: 0
foreach n load form a [ s: s + n ]
s
]
```
[Answer]
Not my best work. There's some definite improvements to be done, some probably fundamental to the algorithm used -- I'm sure it can be improved by using only an `int[]`, but I couldn't figure out how to efficiently enumerate neighbors that way. I'd love to see a PowerShell solution that uses only a single dimensional array!
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 348 bytes
```
Function F($o){$t=120;$a=@{-1=,0*4;4=,0*4};0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};$m=16;while($m-gt0){0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};$m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;$t-=$m;$a[$r][$c]=0}$t}
```
[Try it online!](https://tio.run/##jVRNj5swED2HX2FFrhY2gGy@kgoh9dK0l1WrqlIPCEWIeLtUBFJwtCsl/PZ0bGzyWWkPNvbw5r3nGcvb5pW13QurKqdoWnZc7uqCl02NfrKOf6sZMjGHlY3Z25YVnK0ttJ8YE5wXfJdXKEFLJAHGpHwGrAo7kHiegaYShJZ5WbG1i9Bn9e@EguCXhiPFMEUH9KstOXO@NpDXI1Z17MTzPe86tp6i3ugNY7T8Y1cL1x3aGxNtf5qiFAU2Qj4MDwbNbIiEsIpgzGEsRITCP0phEIh8lBHIoJBJAUujDGVTRK54F4JP4AVS5lDFO@RollBpz2WEDG6EIgru8lKF9yXirl@pSZRn7z9@6SWvxIcKRTWLVKGjO1@5F/ryBNKJOGkw8vpXfv3BmTxZKHOiIUdW1Ze8oaoT1WcSLoQuFVhv8OvdKbC2eConVXLh2Dgy0thDuzU52JGGg1vioXJjtwN1bqI7J2utazOKy7vkSXFBHF6X2D/THtoSqQvw/mYK4vniyvFNv8dbEugaD4TqHIOUrwoTjY4p8d7NPB@ZI8UTnDOPWprZN/rTA7I0cWPtMU@oR2KcJ5/2Dk1s8hjEgfz0MXFd//Bhj/MUr7IkLWueZpnp/GnKGjep6c/o4hGvLNfVyxn1rczptlXJH@wHa2aTPsabhEbx6ws8LCbeOL85sfaauEzwSquUz6YQKjMh5rC/eAPm2gSXMS4A1veSSmJahwKqgNk@215sZvrfzWbMmtE724sNzIcnlne7liHnKX@zXJjKzW4TY@4kGD6aNEtIj3l/1C/c8R8 "PowerShell Core – Try It Online")
---
More readable version:
```
Function F($o){
$t=120;
$a=@{-1=,0*4;4=,0*4};
0..3|%{$a[$_]=[int[]](-join$o[(3+18*$_)..(3+18*$_+13)]-split',')+,0};
$m=16;
while($m-gt0){
0..3|%{$i=$_;0..3|%{if($a[$i][$_]-eq$m){$r=$i;$c=$_}}};
$m=($a[$r-1][$c-1],$a[$r-1][$c],$a[$r-1][$c+1],$a[$r][$c+1],$a[$r][$c-1],$a[$r+1][$c-1],$a[$r+1][$c],$a[$r+1][$c+1]|Measure -Max).Maximum;
$t-=$m;
$a[$r][$c]=0
}
$t
}
```
[Answer]
# C (gcc), 250 bytes
```
x;y;i;b;R;C;
g(int a[][4],int X,int Y){b=a[Y][X]=0;for(x=-1;x<2++x)for(y=-1;y<2;++y)if(!(x+X&~3||y+Y&~3||a[y+Y][x+X]<b))b=a[C=Y+y][R=X+x];for(i=x=0;i<16;++i)x+=a[0][i];return b?g(a,R,C):x;}
s(int*a){for(i=0;i<16;++i)if(a[i]==16)return g(a,i%4,i/4);}
```
[Try it online!](https://tio.run/##XZLBbuIwEIbPy1NMK7HEjavGOKRsjdVD34ATyPUhhICMdqEi6SpZyr46HY9TipAITmb@7/eMPcX9uihOp0a1yqmFmqoX1VtHbltDbqxJLfevM/qfs8NC52ZuzczqRK12@6jR90I1k6GK44b5QOsDLQVa5lbRTdTEs5//5cdHG89pzQ2@WYNhO1kw5h1f9DxurZnqWdxY8nW6wR3cRGRo5FgToyqxxlm1L@v3/RYWz@so51P@wp4adexVvuK7nB0CfIFiDTlyWouMdawnXT/l7iFl6njyrdVlVVcms0ZkFjQcej8OgsOQg@SQchhxyDg8chhz@MVBJPhgXqBAoEKgRKBGZEd@RY4Jy8jimsw6ytOSSFSLoEuDLoCklEE9JEPvI4NNGvZMLsyChySzx4COgjgjgzGV1lUrz4ahy/FFX13RIuhTMvTFDIm87udcnCQjL@wwSba@htGxd1Q9f@Rl81YWdbk04cSRTujXtSUS2Qn/5G4b/d25JfP3ghcMNJ4bpBKFywQq96/crSK6RPbQfd2FTwVxvCHyG3UBdYjilIAfE3jbY2YV3faHy35xy7uJ2PiZ44DTorWEZxi8bgfwBAMYMIWO3mxfVu@/a3Ssoi@Gcl@GXb6/hH6hcXndonsI8jOsv49jY/0@mra5GfDLhPfF8zt9Ag "C (gcc) – Try It Online")
Note: This submission modifies the input array.
`s()` is the function to call with an argument of a mutable `int[16]` (which is the same in-memory as an `int[4][4]`, which is what `g()` interprets it as).
`s()` finds the location of the `16` in the array, then passes this information to `g`, which is a recursive function that takes a location, sets the number at that location to 0, and then:
* If there is a positive number adjacent to it, recurse with the location of the largest adjacent number
* Else, return the sum of the numbers in the array.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 149 bytes
```
(g@p_:=#&@@Position[s,Max@p];m=g[s=#];While[Tr[b=s[[##]]&@@#&/@Select[#+m&/@Tuples[{-1,0,1},2],Max@#<5&&Min@#>0&]]>0,m=g@b;s[[##&@@m]]=0];Tr[Tr/@s])&
```
[Try it online!](https://tio.run/##jZHRasIwFIbv9xSBQNlYho1tWl1XyQsIwoRdhDCqVC1YFdvBoPTZu5OTRAURdhHanJzz/X/@1EW7K@uirdbFsMmH5608fb/nNJBycWyqtjoeVMPmxa886azOt6rJqc6@dtW@VMuzWuWNUpRqDf00GMnPcl@uW0Vfa9gsf077slHdG2ch4z0bawTRDxEE8@og6SwMtJ6FDLhylSEJOLXWeagzoC/PI9nol2BYnKtDS0aSbGA9dV0XMxIxMmYEsKQTjCSMpIxMzI6bMocVMjLFArRymODQx5MeSoCYwD@cmxPs4ciwHX5GoESK@xAVDTt2BI6nkSnceZhaebQxfugBW4Q74G4uQmOpHxJWFE3BF2zHN4QIJQ1HmIYEGzCACAHCXpE7kyhkxsH6NQcrer02t1BxCTP0I1CInV2j2DMXJLeiU68h/JAppP5OF4XYPp3wMUQXps0qsbH8J1pLuI8bFWKfQ4q5CP/Ykb1P4jw8BqQekNiJ@IbggADoh@EP "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 281 bytes
```
D,f,@@,VBFB]G€=dbLRz€¦*bMd1_4/i1+$4%B]4 4b[$z€¦o
D,g,@@,c2112011022200200BD1€Ω_2$TAVb]8*z€kþbNG€lbM
D,k,@~,z€¦+d4€>¦+$d1€<¦+$@+!*
D,l,@@#,bUV1_$:G1_$:
D,h,@@,{l}A$bUV1_$:$VbU","jG$t0€obU0j","$t€iA$bUpVdbLRG€=€!z€¦*$b]4*$z€¦o
y:?
m:16
t:120
Wm,`x,$f>y>m,`m,$g>x>y,`y,$h>x>y,`t,-m
Ot
```
[Try it online!](https://tio.run/##PY/PTsMwDMbvfQpvhEtrRJxlY1RQumpiFwYSYuVQVRuh2v9qO/SwguDAwyAh8Qwc4M5D8CLFYRNSEv8c@7P13WXZel1VXRxjGGIcnUdp7@fl/TQzF9cPDJ@vrulnNNSHM/KE3o9SDdokYltbOV2cWOG9IlKSSCqlpOQTdYk7vt@GStx0YpO2XatYfH2YSzt/afosXWD4jNtJXqY5Bgwis8oTS6FXc7ltyRv20AxiGgq/Zx/@nNq1j8unjtgVRGwGdazPe6KQPGBlBnLOuSg4mdmudWxN/bnjW9u5EybV7r@d0j9zcp9aTuGzH@c2x9EGxTgoA6YcxSTYBCWOShTTLRV4kDtXRVVVSdKAIyAJzRSSFrSBFFCDmZpwDESgLWsgoBaoNP0F "Add++ – Try It Online")
Oof, this is a complicated one.
**[Verify all test cases](https://tio.run/##fVDNbtNAEL77KaZhe0k2Yme9dn5ETRpF5EJAqog5RFbK4v6kTZpIdaUEBAceBgmJZ@ihvfMQPAhmZtdGikBI@Zmd@X7mm3d5vtmU5Uiey8FApsMXw2z888v3o9y@PPlAxcPXpp3kODdPF9gS5nCYGTB2JvxsHYzkBRPfa0StEJXWWin6DEdIiB/f5lq8OU5t1m0y4/rx3r5i/aWdEPVaDj5Lr9TKDf0nVIicmc@4GrQOmgRbksMTaacpzkV/zD/UvGTbj8tPx6IaiNROG7JxNRaFIoG1naoreouCHgtGbVIO5dLR96BKJ2xmmn/i7PrPg1Uf46DoU57g7UqebqU4T3YJVSspLpJtspOnOykufVXI9ip4XZRlOZsZCEEDZjCLIIYOdKlCaiCggh4/QkADGAHGWUaELiD0qMUjJIobeFhESh2uFYmSiHEEpG4IZs@hx@rsof/hwKPItdBBaexlQzbTwHYaumBqQkiqRIqoH1Of1w8ZH/Gi6KxZjeCgqwysWq@NTI@q3MqjgA7jOFEdmpf1BzG8hvKxO267SsnwJT2hyuSUSJBW@c8JmLB/ERIyPgSB2Y65Ia8W1w5/ETqeEDPK1AxHJsKv9aZYrG9uy3b79m5RnP0G)**
## How it works
For this explanation, we will use the input
\$M = \left[\begin{matrix}
3 & 7 & 10 & 5 \\
6 & 8 & 12 & 13 \\
15 & 9 & 11 & 4 \\
14 & 1 & 16 & 2 \\
\end{matrix}\right]\$
We start by defining a series of helper functions. We will use \$x\$ to represent an integer such that \$1 \le x \le 16\$, \$M\$ to, initially, represent the \$4\text{x}4\$ input matrix. The functions are:
* \$f(x, M)\$: Given a value and a \$4\text{x}4\$ matrix, return the co-ordinates of \$x\$ in \$M\$ e.g. if \$x = 16\$ and \$M\$ is above, \$f(x, M) = (4, 3)\$
* \$g(M, y)\$: Given a matrix and two co-ordinates, return the largest of the neighbours of the value at that point e.g. using \$f(x, M)\$ from above, \$g(M, f(x, M)) = 11\$
This implements the two helper functions:
\$k(x)\$ which removes any co-ordinates which would wrap around or be out of bounds
\$l(M, y)\$ which, given a matrix and co-ordinates, returns the value at those co-ordinates
* \$h(y, M)\$ which, given a matrix and co-ordinates, sets the value at those indexes to \$0\$
After these functions are defined, we come to the main body of the program. The first step is to assign the four variables, **x**, **y**, **m** and **t**. **x** is set to \$0\$ by default, **y** to the input, **m** to \$16\$ (the first value to search for) and **t** to \$120 \: (1 + 2 + \cdots + 14 + 15)\$.
Next, we enter a while loop, that loops while **m** does not equal \$0\$. The steps in the loop go something along the lines of
While **m** \$\neq 0\$:
* Set **x** to \$f(\textbf{y}, \textbf{m})\$. For the first iteration, this sets **x** to the co-ordinates of \$16\$ is \$M\$ (\$x := (4, 3)\$ in our example)
* Set **m** to \$g(\textbf{x}, \textbf{y})\$. This yields the largest new neighbour to **m**, or \$0\$, if there are no new neighbours (which ends the while loop).
* Set **y** to \$h(\textbf{x}, \textbf{y})\$. This sets the previous value of **m** (\$16\$ in the first iteration) to \$0\$, in order for the previous step to work
* Set **t** to \$\textbf{t} - \textbf{m}\$, removing that value from the total value amount.
Finally, output **t**, i.e. the remaining, non collected values.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 258 bytes
Without LINQ. The using System.Collections.Generic is for the formatting after - the function doesn't require it.
```
e=>{int a=0,b=0,x=0,y=0,j=0,k;foreach(int p in e){if(p>15){a=x=j/4;b=y=j%4;}j++;}e[x,y]=0;while(1>0){for(j=-1;j<2;j++)for(k=-1;k<2;k++){try{if(e[a+k,b+j]>e[x,y]){x=a+k;y=b+j;}}catch{}}if(e[x,y]<1)break;e[x,y]=0;a=x;b=y;}a=0;foreach(int p in e)a+=p;return a;}
```
[Try it online!](https://tio.run/##pZRNj5swEIbv/Iq5VAJlNsF8JZFjLpXay1aq1MMeoqgixLsxsBAB6QYh//Z0nFTbjUK6WhU0Qp4vP35tkzZ3aVXL475R5RP86JpWPo8/V0Uh01ZVZTP@KktZq5RbbzO4lRZJ08D3unqqk@feAtjt14VKoWmTlj6/KrWBb4kqbccEAb7sy3ShynaJK6RPDBsQRyningaQCBfXZAeyjiwjy/kjcSXp1jYZO1AlSKdXj/YuZqHTJ@IgsknA16IT2aeA62w04louD9ithMtftqqQNotdp6c2dibuGM8WHqcsxzhy48jJkZOjb@vOdJbLZJTjepSt4nMjpz8IcvFOkJNrnSZtuu21PuWahAVz1gSZ89eJicswcU1rGlpBMhI7Xst2X5eQcH3k1r1q2j/KxPCzoBEIKOULXAR6y7jOox4mE/ek6tunhwB99JBpvI6FGOEUZ0MhRiUMmYvzwaiPLEAWIov0RZSSL4kYDFQTj4/BB4nmhsYwef9J5F1X@zQpdQ@HOkc4Q6OGPzhtiHMDNbgYA0Q86L1DFLLr2tl5qTfkDzA8qRENRackLsPohkqBOQzhexq53oc3AMFDOmwwLBRtKjEDGxTKp0BEOz/AdQXmDxzxOdW7ZMTwL7jpLbjoNP8J/hbfDMHgh/qv29KaW28uMyGe7/PpujrW62@zbKpCjh9q1cp7VUp7Y@8ch1ua3uNv "C# (.NET Core) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~151~~ ~~136~~ ~~126~~ ~~125~~ 119 bytes
```
{my@k=$_;my $a=.grep(16,:k)[0];while @k[$a] {@k[$a]=0;$a=^@k .grep({2>$a+>2-$_+>2&$a%4-$_%4>-2}).max({@k[$_]})};[+] @k}
```
Super shabby solution. Takes input as flattened array.
[Try it online!](https://tio.run/##RY3BjoIwFEX3fsVdVCNxNLy21MFKw38QJF2gTpDEOAslhG/HVzSaNO1res7ptb5dzNh2WByzsW@7vMlEZfkufLY53errkszPromKuLT389@lRt4UwpfoX2cWWyYPeYMX3Usn/MrJtah4Xwg/1zzOtVvLIdq0/rGcxKocosEWq5Jzw2hn/77DEXuFLShGAoNfkAQpUIIURNAgXiAD6T68hgJTk7B9KxQK6aTqYJP58ml4C0SQZPhMscnNqa64wHzi7PgE "Perl 6 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=sum -p`, 137 bytes
```
splice@F,$_,0,0for 12,8,4;map{$k{++$,}=$_;$n=$,if$_&16}@F;map{map{$n=$_+$"if$k{$"+$_}>$k{$n}&&!/2|3/}-6..6;$k{$"=$n}=0}@F;$_=sum values%k
```
[Try it online!](https://tio.run/##HY7LDoIwEEV/ZTQjGwp2QOqD1LhypUvXDTGYNCA0Ft1gf91aSGZxc87cyZj61RbeW9Pqe306M1SMM/7oX0AZ27FN@azMiM0Yx8icRFViJ5HpB6qIhDudZz/vBK5iXAbVjLiMUbnjlDoXRYt19s3XLhFpKspZy8Aln/qopH0/4VO179quGu9z2AJxKEDALjwBlAMVsAci2ACFARKQwa83g@4765PrRdvhcLgNup1OBVCknLhPTPUH "Perl 5 – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 49 bytes
```
{{h[,x]:0;*>(+x+0,'1-!3 3)#h}\*>h::(+!4 4)!x;+/h}
```
[Try it online!](https://tio.run/##bZDdasMwDEbv9xQqG6xpWhZFdv4EfZEu0N1kGR0dlF6khO7VM39yMzYo@MbW0dEnHzbH9@M0dc049rv10DaZrrbLdEiz9TNvFkKSPPbX19W2b5plunDkksWg6Ut/nc7N@LS7fJ@ajgbdfx10ue/ePj510Iuekvb6cN45EsqJyVNBJVXE4cLEGdXEQuyIPXGhGVEb6FBHwYEpCBWjfFCUaBL0u5nm8Czkft01ENjzf26@0ZndzV3DBKVgSB7689DvQEukJQ6EupqFHhMYWDjIlmuoxNwwxrDmNSsmwnxr8Cpu3tJC2qb@hpUWyRQOP@bVc8wdV8FbAfH9jbWsjP77B3G0GGmbCxSQKGf5Hdo@pADkIm59oKWdfgA "K (ngn/k) – Try It Online")
the input (`x`) is a 1d array
`(+!4 4)!x` a dictionary that maps pairs of coords to the values of `x`
`h::` assign to a global variable `h`
`*>` the key corresponding to the max value
`{` `}\` repeat until convergence, collecting intermediate values in a list
`h[,x]:0` zero out the current position
`+x+0,'1-!3 3` neighbour positions
`(` `)#h` filter them from `h` as a smaller dictionary
`*>` which neighbour has the max value? it becomes the current position for the new iteration
`+/h` finally, return the sum of `h`'s remaining values
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~124~~ 115 bytes
```
(p=#&@@Position[m=Join@@ArrayPad[#,1],16];Do[m[[p]]=0;p=MaximalBy[#&@@p+{0,-1,1,-5,5,-6,6,-7,7},m[[#]]&],16];Tr@m)&
```
[Try it online!](https://tio.run/##jVNNi9swEL37V6gxhC6VQWNZcsqiopZSaGEhh96EDqLdUMM6CbEPXYJ/eyqNPpLSlu5hsBm9ee/pjT26@cfj6Obhm7vs1OX1UdVrrbeHaZiHw96M6sth2Gv9/nRyz1v33dQULAVp7z8ezGjM0VrF7o/qwf0cRvf04dmE8eObM6MNUKCNoII2kkra9LRfqB@prV1Hiq8nPd6tL/PjNE9EkfOZnElHCeG@Wl@wUN8R/k366n1tQgf8GYAv5jtvseMnwE@Cx4JcyEKad4TRKhBuAlEABgiCIRFGcB4XSbTHDos2ghTpfieEBOR49FeHKMaSy/afDgEJESjSMeRxpIfihye/QRg9o4Vwt@6GkEeHPHrBSwgEywjG5DgSihQJ5FsE@SAIAdtmh@01xGzqGhkkHVG2wso8jbvMrN5HstgVxphO2WGXrsjyWjDPHENRxS@kRdXIKFKM/EYtZi7TWl@@qcjYb6LHP7ZYdt/lHCNTch41eMpA3ngE1v6Psi@UMhF0t5RF5ErJq6WqtqdhP5vPO7PTNVFKkdqTrbZumlb@@ckNT69Wltg10VoT/NOqncGnMf4HtdZefgE "Wolfram Language (Mathematica) – Try It Online")
This takes a 2D array, pads it on each side, then immediately flattens it so we don't have to spend bytes indexing. The only cost to this is `Join@@` to flatten. Afterwards it proceeds as below.
**124-byte version** for a 2D array: [Try it online!](https://tio.run/##jZNPa9tAEMXv/hRbC0RL1nhHK8kORkEpbSGHgA@@CR2WxCYCyxbSBhKM/dXd2dk/dkhLe1hsZmd@7@0bu1X6Zd0q3Typ86Y4f@2KKC7L5X5odLPfVW0Rne77Xr0v1fMJOOT14sceq4@qu9eViHnLu3phhx7VW9Oq7ff3qruJ4mm5eu2266E6CD7BySNPat6efr7pXj3pUxTXRFv11aqflm39LT7r9aAHVrDDgR1YyhmTeBI8OIyVDL/leGZ45qYCeAeAR2Dllio4ATgJ2Av5kR3Z5I4JPjLAuQGZRtNCzeCAttmPZ050RhVhbRgpln4EgmuUdPVHhyQmnMvkrw6BgNSYuWvw44SH4Ec6v0aYPJMF87b0CiitQ2m90CMyas5tMyUnCZi5SMC/wsgbQTC9iXeYXEL0pi6RgdPJwlZEmOd2l56KPpzFNBBtOmGHqXui8GuhPH0MQZV@IQmpWmLmYpRXajbz3K31/zdlibO59fhpi2H3qc/RkpxzqyFdBvmVRxDJv5CzgMwdIL1GBpELUo6Oo9Gyb3a6ethUmzJiRVGwCGHjpRqGMX7@Us32y7hmdczKsmT0Tzv/Bg "Wolfram Language (Mathematica) – Try It Online")
Mostly my own work, with a bit derived from [J42161217's 149-byte answer](https://codegolf.stackexchange.com/a/176612/39328).
Ungolfed:
```
(p = #& @@ Position[m = #~ArrayPad~1,16]; m = input padded with a layer of 0s
p = location of 16
Do[
m = MapAt[0&,m,p]; Put a 0 at location p
p = #& @@ MaximalBy[ Set p to the member of
p+#& /@ Tuples[{0,-1,1},2], {all possible next locations}
m~Extract~#&], that maximizes that element of m,
ties broken by staying at p+{0,0}=p.
16]; Do this 16 times.
Tr[Tr/@m] Finally, output the sum of m.
)&
```
[Answer]
Not the shortest solution, but pretty straight forward.
## Ruby, 207
```
a=eval(ARGV[0])
n=16
while n!=0 do
a[i=a.index(n)]=0
t=[a[i+4]]
t<<a[i-4]if i>3
if i%4!=0
t<<a[i-5]if i>3
t<<a[i-1]
t<<a[i+3]
end
if i%4!=3
t<<a[i+1]
t<<a[i+5]
t<<a[i-3]if i>3
end
n=t.compact.max
end
p a.sum
```
] |
[Question]
[
Once I wrote a JavaScript program that would take as input a string and a character and would remove all characters except for the first one and the character given as input, one by one.
For example, computing this with inputs `codegolf.stackexchange.com` and `e` for the character yields:
```
codegolf.stackexchange.com
cdegolf.stackexchange.com
cegolf.stackexchange.com
ceolf.stackexchange.com
celf.stackexchange.com
cef.stackexchange.com
ce.stackexchange.com
cestackexchange.com
cetackexchange.com
ceackexchange.com
ceckexchange.com
cekexchange.com
ceexchange.com
ceechange.com
ceehange.com
ceeange.com
ceenge.com
ceege.com
ceee.com
ceeecom
ceeeom
ceeem
ceee
```
It keeps the first character and all `e`s. All other characters are removed one by one.
Your task is to write a program (or function) that takes two inputs and outputs (or returns) a string that accomplishes this effect.
## Specifications
* You can assume that the string will not contain any newlines.
* The second input will always be one character.
* If the answer is in the form of a function, you may return an array of strings containing each line in the output.
* The output can contain a trailing newline.
## Test Cases
`Test Cases`, `s`:
```
Test Cases
Tst Cases
Ts Cases
TsCases
Tsases
Tsses
Tsss
```
`Make a "Ceeeeeeee" program`, `e`:
```
Make a "Ceeeeeeee" program
Mke a "Ceeeeeeee" program
Me a "Ceeeeeeee" program
Mea "Ceeeeeeee" program
Me "Ceeeeeeee" program
Me"Ceeeeeeee" program
MeCeeeeeeee" program
Meeeeeeeee" program
Meeeeeeeee program
Meeeeeeeeeprogram
Meeeeeeeeerogram
Meeeeeeeeeogram
Meeeeeeeeegram
Meeeeeeeeeram
Meeeeeeeeeam
Meeeeeeeeem
Meeeeeeeee
```
`Hello World!`, `!`:
```
Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!
```
`Hello World!`, `z`:
```
Hello World!
Hllo World!
Hlo World!
Ho World!
H World!
HWorld!
Horld!
Hrld!
Hld!
Hd!
H!
H
```
`alphabet`, `a`:
```
alphabet
aphabet
ahabet
aabet
aaet
aat
aa
```
`upperCASE`, `e`:
```
upperCASE
uperCASE
uerCASE
ueCASE
ueASE
ueSE
ueE
ue
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins.
[Answer]
# Vim, ~~27, 26~~, 25 bytes
```
DJqqYp:s/.\zs[^<C-r>-]<CR>@qq@qD
```
[Try it online!](https://tio.run/nexus/v#@@/iVVgYWWBVrK8XU1UcHSekG8vlUFjoUOjy/38qV3J@Smp6fk6aXnFJYnJ2akVyRmJeeqpecn4uAA "V – TIO Nexus")
Input comes in this format:
```
e
codegolf.stackexchange.com
```
My naive first approach is three bytes longer:
```
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd
```
I'm also happy with this answer because it starts with my name.
```
DJqq:t$|s/.\zs[^<C-r>"]<CR>@qq@qD
DJMcMayhem
```
See the similarity? Eh?
Less successful approaches:
```
i:s/.\zs[^<Right>]<Esc>"addqqYp@a@qq@qdd
i:s/.\zs[^<Right>]<CR>@q<Esc>"adkqqYp@aq@qdd
DJ:s/.\zs[^<C-r>"]<CR>uqqYp@:@qq@qdd
DJqq:t.|$s/.\zs[^<C-r>"]<CR>@qq@qdd
```
Explanation:
```
D " Delete everything on this first line
J " Remove this empty line
qq " Start recording into register 'q'
Y " Yank this line
p " And paste it
:s/ " Run a substitute command on the last line in the buffer. Remove:
. " Any character
\zs " Move the selection forward (so we don't delete the first one)
[^<C-r>-] " Followed by anything *except* for the character we deleted
<CR> " Run the command
@q " Call register 'q'
q " Stop recording
@q " Run the recursive macro
D " Delete our extra line
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~20~~ 16 bytes
```
y-f1X-"t[]@X@q-(
```
[Try it online!](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tJwonZSc) Or verify test cases: [1](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J1Rlc3QgQ2FzZXMnCidzJw), [2](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J01ha2UgYSAiQ2VlZWVlZWVlIiBwcm9ncmFtJwonZSc), [3](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J0hlbGxvIFdvcmxkIScKJyEn), [4](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J0hlbGxvIFdvcmxkIScKJ3on), [5](http://matl.tryitonline.net/#code=eS1mMVgtInRbXUBYQHEtKA&input=J2FscGhhYmV0JwonYSc).
### Bonus
Modified code to *see the string being gradually shrunk* (offline compiler):
```
y-f1X-"tt.3Y.XxD[]@X@q-(].3Y.XxDvx
```
[![enter image description here](https://i.stack.imgur.com/6UNgZ.gif)](https://i.stack.imgur.com/6UNgZ.gif)
Or try it at [MATL Online!](https://matl.io/?code=y-f1X-%22tt.3Y.XxD%5B%5D%40X%40q-%28%5D.3Y.XxDvx&inputs=%27codegolf.stackexchange.com%27%0A%27e%27&version=19.4.0)
## Explanation
```
y % Implicitly input string and char. Duplicate string onto top
- % Subtract. Gives nonzero for chars in the input string that are
% different from the input char
f % Array of indices of nonzero values
1X- % Remove 1 from that array. This gives an array of the indices of
% chars to be removed from the string
" % For each
t % Duplicate previous string
[] % Push empty array
@ % Push index of char to be removed. But this index needs to be
% corrected to account for the fact that previous chars have
% already been removed...
X@q- % ... So we correct by subtracting the 0-based iteration index
( % Assign empty array to that position, to remove that char
% Implicitly end for each
% Implicitly display
```
[Answer]
# Haskell, 50 bytes
```
w@(a:x)%c|(d,_:y)<-span(==c)x=w:(a:d++y)%c|0<1=[w]
```
Defines a function `(%)` returning a list of strings.
### Explanation
`(%)` is called as `w%c`, with `w` being the input string, and `c` the character to keep. In short, this definition works by separating `w` into the first character (`a`) and the remainder (`x`), splitting `x` at the first occurrence of a character other than `c`, and recursively calling itself with that one character dropped.
```
w@(a:x)%c -- define (%) with w separated into a and x.
|(d,_:y)<-span(==c)x -- split x; bind the string of `c` to d, and the rest
-- to _:y, dropping first character and calling the rest y.
=w:(a:d++y)%c -- if there was a character to drop, cons w onto the
-- sequence gained by recursively calling (%) with that
-- character removed (i.e. call with a:d++y).
|0<1=[w] -- if nothing needed to be dropped, the result sequence is
-- simply the one-element list [w]
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), ~~28~~ 27 bytes
Byte count assumes ISO 8859-1 encoding.
```
;{G*1`
R1r`(?!^|.*¶?\1$)(.)
```
[Try it online!](http://retina.tryitonline.net/#code=O3tHKjFgClIxcmAoPyFefC4qwrY_XDEkKSguKQ&input=Y29kZWdvbGYuc3RhY2tleGNoYW5nZS5jb20KZQ)
### Explanation
```
;{G*1`
```
There's a lot of configuration here. The stage itself is really just `G1``, which keeps only the first line, discarding the input character. `*` turns it into a dry run, which means that the result (i.e. the first line of the string) is printed without actually changing the string. `{` tells Retina to run both stages in a loop until the string stops changing and `;` prevents output at the end of the program.
```
R1r`(?!^|.*¶?\1$)(.)
```
This discards the first character which a) isn't at the beginning of the input, b) isn't equal to the separate input character.
[Answer]
## [Pip](http://github.com/dloscutoff/pip), ~~22~~ ~~26~~ ~~24~~ 22 bytes
```
Lv+#Paa@oQb?++oPaRA:ox
```
Takes string as first command-line argument, character as second. [Try it online!](http://pip.tryitonline.net/#code=THYrI1BhSWFAb1FiKytvRSBQYVJBOm94&input=&args=VGVzdCBDYXNlcw+cw)
### Explanation
Loops over characters of input; if the character equals the special character, move on to the next one; if not, delete it and print the string.
An ungolfed version (`a`, `b` get cmdline args; `o` starts with a value of `1`, `x` is `""`):
```
P a Print a
L #a-1 Loop len(a)-1 times:
I a@o Q b If a[o] string-eQuals b:
++o Increment o
E { Else:
a RA: o x In-place in a, Replace char At index o with x (i.e. delete it)
P a Print a
}
```
Golfing tricks:
* The loop header for `L` is only evaluated once, so we can sneak the initial print in there. `#Pa-1` won't work because `P` is low-precedence (it would parse as `#P(a-1)`), but we can rearrange it to `v+#Pa`, using the `v` variable preinitialized to `-1`.
* The `RA:` operator returns the new value of `a`, so we can print that expression instead of having a separate `Pa` statement.
* Now both of the branches of the if statement are single expressions, so we can use the ternary operator `?` instead.
[Answer]
# Perl 5, 29 bytes
I got 35 bytes using Strawberry Perl: 31 bytes, plus 1 for `-nE` instead of `-e`, plus 3 for space + `-i` (used for the single-letter input; the longer string is from STDIN).
```
chomp;say;s/(.)[^$^I]/$1/&&redo
```
However, I've no doubt this is doable without `chomp;` using `<<<`, which is 29 bytes, even though I can't test it myself using Strawberry.
```
say;s/(.)[^$^I]/$1/&&redo
```
Thus:
```
perl -im -nE'say;s/(.)[^$^I]/$1/&&redo' <<< "example"
```
[Answer]
# [Perl 6](https://perl6.org), ~~ 47 40 ~~ 38 bytes
```
->\a,\b{a,{S/^(."{b}"*:)./$0/}...^{$^a eq $^b}}
```
```
->\a,\b{a,{S/^(."{b}"*:)./$0/}...^&[eq]}
```
```
{$^b;$^a,{S/^(."$b"*:)./$0/}...^&[eq]}
```
## Expanded:
```
{ # lambda with two placeholder parameters ÔΩ¢$aÔΩ£ and ÔΩ¢$bÔΩ£
$^b; # declare second parameter
$^a, # declare first parameter, and use it to seed the sequence
{ # bare block lambda with implicit parameter ÔΩ¢$_ÔΩ£
S/ # string replace and return
^ # beginning of string
( # capture into ÔΩ¢$0ÔΩ£
. # the first character
"$b"* # as many ÔΩ¢$bÔΩ£ as possible
: # don't allow backtracking
)
. # any character ( the one to be removed )
/$0/ # put the captured values back into place
}
...^ # repeat that until: ( and throw away the last value )
&[eq] # the infix string equivalence operator/subroutine
}
```
The reason `...^` was used instead of `...` is that `&[eq]` wouldn't return `True` until the last value was repeated.
[Answer]
# [Python 3](https://docs.python.org/3/), 72 bytes
```
def e(i,k):
for r in i:
if r!=k:i=i[0]+i[1:].replace(r,'',1);print(i)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFVI1MnW9OKSyEtv0ihSCEzTyETyFHITFMoUrTNtsq0zYw2iNXOjDa0itUrSi3ISUxO1SjSUVfXMdS0LijKzCvRyNT8n6qh/mH@jO4P85dO/TC/tw9ITwbiiUj0JKB4G5CeAqWB4r2tQHoOVM0UCL@3BSSvrqMOElbX/A8A "Python 3 – Try It Online")
```
e('üòãü•ïüçéü•ìü•ëü•ìü•ëü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ','ü•ì')
```
Go on a diet:
```
üòãü•ïüçéü•ìü•ëü•ìü•ëü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãüçéü•ìü•ëü•ìü•ëü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ëü•ìü•ëü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•ëü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•íüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìüçÜü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•îüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìüçÜü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•ìüçÖü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•ìü•úü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•ìü•ìü•îüçÖüçÑüçÜ
üòãü•ìü•ìü•ìü•ìüçÖüçÑüçÜ
üòãü•ìü•ìü•ìü•ìüçÑüçÜ
üòãü•ìü•ìü•ìü•ìüçÜ
üòãü•ìü•ìü•ìü•ì
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~26~~ 25 bytes
```
¬ˆ[¦Ðg_#¬²k0Qi²ˆë¯J?,]¯J?
¬ˆ Put the first character into an array
[ While true
¦ Remove the first character
Ð Triplicate
g_# if the string is empty, break
¬²k0Qi if the first character is equal to the one specified in the input
²ˆ Add it to the array
ë Else
¯J? Display the array
, Display the remaining string
] End while
¯J? Display the last string
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wqzLhlvCpsOQZ18jwqzCsmswUWnCssuGw6vCr0o_LF3Cr0o_&input=TWFrZSBhICJDZWVlZWVlZWUiIHByb2dyYW0KZQ)
Please note that `¬²k0Q` could be rewritten `¬²Q`, but for some reason it doesn't work when the current character is a quote mark: Q returns the actual string instead of a boolean and it causes an infinite loop.
This code can be golfed further since `¯J?` is duplicated. Moving this part in the loop would remove the duplication and would also allow to drop the closing square bracket.
[Answer]
# Python 2, ~~71~~ 66 bytes:
```
f,m=input();k=f[0]
while f:a=f[0]==m;k+=f[0]*a;f=f[1+a:];print k+f
```
A full program. Takes 2 inputs through STDIN in the format `'<String>','<Char>'`.
Also, here is a recursive solution currently at **140 bytes**:
```
Q=lambda c,p,k='',j=1,l=[]:c and Q(c[1:],p,k+c[0]*(j<2)+c[0]*(c[0]==p),j+1,l+[k+c])or'\n'.join(sorted({*l},key=l.index))+('\n'+k)*(k not in l)
```
This one should be called in the format `print(Q('<String>','<Char>'))`.
[Answer]
## JavaScript (ES6), 74 bytes
```
(s,c)=>[...t=s.slice(1)].map(d=>c!=d?s+=`
`+s[0]+(t=t.replace(d,``)):s)&&s
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 12 bytes
```
√≤Yp√≥.“„a]√≤d
```
[Try it online!](https://tio.run/nexus/v#@394U2TB4c16hyYfahFKjD28KeX//@T8lNT0/Jw0veKSxOTs1IrkjMS89FS95Pzc/6kA "V – TIO Nexus")
Hexdump:
```
00000000: f259 70f3 2e93 8412 615d f264 .Yp.....a].d
```
I have tested this with [the latest version of V available before the challenge](https://github.com/DJMcMayhem/V/tree/439edc84892be237dc65eb408ea3e6ba93ceff4d), and everything runs correctly, making this answer competing.
Explanation:
```
ò ò " Recursively:
Yp " Duplicate this line
ó " Remove:
.a] " A compressed regex
d " Delete our extra line
```
The compressed regex translates to
```
.\zs[^e]
```
Which means
```
. " Any character
\zs " Leave the previous character out of the selection
[^e] " Any character except for 'e' (Or whatever is given for input)
```
**[11 bytes version](https://tio.run/nexus/v#ATAAz///w7LDmcOzLsKTwoQSYV3DsmT//2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29t/2U)**
This version uses a shortcut for `Yp` that wasn't available when this challenge was posted.
[Answer]
# Ruby, ~~148~~ ~~139~~ ~~97~~ ~~90~~ ~~83~~ ~~77~~ 62 bytes
```
a,c=$*;p s=""+a;i=1;while d=s[i];(d!=c)?(s[i]="";p s):i+=1;end
```
Not sure if amateur code is accepted on this exchange but I'm interested in learning to code golf although I'm terrible at it, any help on how I'd get this program looking as small as the others here?
**EDIT:**
Replaced puts with p
Removed a tonne of whitespace and counted bytes correctly thanks to Wheat Wizard
Thanks to challenger5 went from `s=gets.chop;c=gets.chop;` to `s,c=gets.chop,gets.chop;`
replaced `then` with `;` and `gets.chop` with `gets[0]` thanks Mhutter!
Taking input as command line variables now, eg. `prog.rb helloworld l`
Thanks to numerous improvements by jeroenvisser101 replacing `a=s.dup` with `s=""+a` and the previous if statement `if s[i]!=c;s[i]="";p s;else i+=1;end` with `(d!=c)?(s[i]="";p s):i+=1;` huge improvement!
[Answer]
# c90, 129 125 bytes
with whitespace:
```
main(q, x)
{
for (char **v = x, *a = v[1], *b = a, *c;*b++;)
for (c = a; c == a | *c == *v[2] && *b != *v[2] && putchar(*c),
++c != b || *b != *v[2] && !puts(b););
}
```
without whitespace:
```
main(q,x){for(char**v=x,*a=v[1],*b=a,*c;*b++;)for(c=a;c==a|*c==*v[2]&&*b!=*v[2]&&putchar(*c),++c!=b||*b!=*v[2]&&!puts(b););}
```
ungolfed:
```
#include <stdio.h>
int main(int argc, char **argv)
{
char *a = argv[1];
for (char *b = a + 1; *b; b++) {
if (*b == *argv[2]) {
continue;
}
putchar(*a);
for (char *c = a + 1; c != b; c++) {
if (*c == *argv[2]) {
putchar(*c);
}
}
puts(b);
}
}
```
This takes a pointer to the start of the string, and loops, iterating this pointer until it reaches the end of the string. Within the loop, it prints the first character, then any instances of the second argument it finds between the start of the string and the pointer. After this, it calls puts on the pointer, printing out the rest of the string.
This must be compiled on a system where sizeof(int) == sizeof(char\*). +3 bytes otherwise.
This is the first time I've tried code golfing here, so I'm sure there are some optimizations to be made.
[Answer]
# JavaScript (ES6), 63 ~~64 69~~
Thanks to @Shaggy for shaving 1 byte!
Returning a single string with newlines
```
s=>c=>[...s].map((x,i,z)=>i&&x!=c&&(s+=`
`+z.join(z[i]='')))&&s
```
```
F=
s=>c=>[...s].map((x,i,z)=>i&&x!=c&&(s+=`
`+z.join(z[i]='')))&&s
function update() {
var s=S.value,c=C.value[0]
O.textContent=F(s)(c)
}
update()
```
```
<input id=S value='Hello world!' oninput='update()'>
<input id=C value='!' oninput='update()'>
<pre id=O></pre>
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 27 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
`{×i←⊃1+⍸⍺≠1↓⎕←⍵:⍺∇⍵/⍨i≠⍳≢⍵}`
`‚ç∫` is the excluded character, `‚çµ` is the initial string
print argument; find index `i` of the first non-`‚ç∫` after the first char; if found, call recursively with `i` removed
[Answer]
# Mathematica, 64 bytes
```
Most@FixedPointList[StringReplace[#,b_~~Except@a:>b,1]&,a=#2;#]&
```
Anonymous function. Takes two strings as input, and returns a list of strings as output. Works by repeatedly removing the first non-instance of the character.
[Answer]
# PHP, ~~88~~ ~~84~~ ~~86~~ ~~85~~ ~~82~~ ~~81~~ 78 bytes
1 byte saved thanks to @IsmaelMiguel, 3 bytes thanks to @user59178, 3 bytes inspired by @user59178
```
while($b=substr("$argv[1]\n",$i++))$a>""&$b[0]!=$argv[2]?print$a.$b:$a.=$b[0];
```
takes input from command line arguments; run with `php -r <code> '<string>' <character>`
---
* appends a newline to the input for an implicit final print.
That adds ~~5~~ 4 bytes of code, but saves on the output and an additional `echo$a;`.
[Answer]
# 05AB1E, ~~26~~ ~~24~~ 23 bytes
Thanks @Kade for 2 bytes!
Thanks @Emigna for 1 byte!
```
¬UDvy²k0Êiy¡¬s¦yý«Xs«=¦
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wqxVRHZ5wrJrMMOKaXnCocKsc8KmecO9wqtYc8KrPcKm&input=TWFrZSBhICJDZWVlZWVlZWUiIHByb2dyYW0KZQ)
`y²k0Ê` could be `y²Ê` but the `"` messes it up.
This probably could be golfed more because `¬´` is repeated twice. Please leave a comment if you have any suggestions or ways to golf it down more.
[Answer]
# Java 10, ~~155~~ ~~140~~ ~~139~~ 124 bytes
```
c->s->{var r=s+"\n";for(int i=0;++i<s.length();)if(s.charAt(i)!=c)r+=(s=s.substring(0,i)+s.substring(i--+1))+"\n";return r;}
```
[Try it online.](https://tio.run/##pZCxbsIwEIZ3nuLIgq0Qi85pIqGoVRcmKnUoHY7ggME4lu@CRBHPnqYlEp1aqnrxyefvP3/e4gGT7WrXlhaJYIbGnQYAxMimhG3XVQ0bq6rGlWxqpx774r7YYMCSdRj/eG3Owbj1GC57nkMFWVsmOSX56YABQkZxtHBRWtVBGMdgskkax@aelNVuzRshU2kqQarsBk5ZGDnMShniTFBGipolfSWLydjI@PuBSZL4TspLetDcBAchPbfpoBP0zdJ2gr3noTYr2Hfu4vLM1zdA@fkPAPMjsd6rumHluxZbJyqF3tujGNFI9mX0rImhQNIUSZn@SuorOcOdBoRFVOh@LSLwoV4H3N@UNbxmPWlra3ipg10Nb2Lf/8HilUXrN7jU/Ff3xnsdiun8oQfPg3P7AQ)
**Explanation:**
```
c->s->{ // Method with character and String parameters and String return-type
var r=s+"\n"; // Result-String, starting at the input-String with trailing new-line
for(int i=0;++i<s.length();)
// Loop over the characters of the String, skipping the first
if(s.charAt(i)!=c)
// If the current character and the input-character are equal
r+=(s=s.substring(0,i)+s.substring(i--+1))
// Remove this character from the String `s`
+"\n"; // And append the new `s` with trailing new-line to the result-String
return r;} // Return the result-String
```
---
**Old 139 bytes recursive answer:**
```
void c(String s,int c){System.out.println(s);for(int i=1;i<s.length();)if(s.charAt(i++)!=c){c(s.substring(0,i-1)+s.substring(i),c);break;}}
```
-1 bytes thanks to *@Eugene*. (Next time make a comment instead of editing someone else's post, please.)
[Try it online.](https://tio.run/##nY@xbsIwEIZ3nuKSBVsJUZldBoSQujBRqUPpcHFMYjBx5HOQWpRnT50oA0OHqDfef9@v7y54x9WluPbSIBEcUNePBQB59Fr2d6sLkOzona5LoFTXHiR/HL/Jq1tmW581IfGmZsTF2To2HOjNWuhXyoyqS18xLrg@M8pkhW7rmU4SHm1CiQw7anMau9lLqldrnjyvNE8lF7lTeBVd14tF8Gra3Gg56cGodwvKk@HnFyAf9CFIx@@KPOyQFMUpLGnJxZj8IT8lgTngVQHCKd6paU4xNM6WDm9Di5rV8qaMsfBhnSmigYr@Rf3MotA0FebKDwTOItqmUW63Pe6fHuoWXf8L)
**Explanation:**
```
void c(String s,int c){ // Method with String and integer parameters and no return-type
System.out.println(s); // Print the input-String with trailing new-line
for(int i=1;i<s.length();)// Loop over the characters of the String, skipping the first
if(s.charAt(i++)!=c){ // If the current character and the input-character are equal
c(s.substring(0,i-1)+s.substring(i),c);
// Remove this character, and do a recursive call
break;}} // And stop the loop
```
[Answer]
# C#, 122 117 112 bytes
```
IEnumerable F(string s,char c){for(int i=0;i<s.Length;++i)if(i<1||s[i]!=c)yield return i>0?s=s.Remove(i--,1):s;}
```
Ungolfed :
```
public IEnumerable F(string s, char c) {
for (int i = 0; i < s.Length; ++i) {
if (i < 1 || s[i] != c)
yield return i > 0 ? s = s.Remove(i--, 1) : s;
}
}
```
Returns a collection of strings.
[Answer]
**TSQL, 127 bytes(Excluding variable definitions)**
```
DECLARE @1 VARCHAR(100)='codegolf.stackexchange.com'
DECLARE @2 CHAR(1) = 'o'
DECLARE @ char=LEFT(@1,1)WHILE patindex('%[^'+@2+']%',@1)>0BEGIN SET @1=STUFF(@1,patindex('%[^'+@2+']%',@1),1,'')PRINT @+@1 END
```
Formatted:
```
DECLARE @1 VARCHAR(100) = 'codegolf.stackexchange.com'
DECLARE @2 CHAR(1) = 'o'
DECLARE @ CHAR = LEFT(@1, 1)
WHILE patindex('%[^' + @2 + ']%', @1) > 0
BEGIN
SET @1 = STUFF(@1, patindex('%[^' + @2 + ']%', @1), 1, '')
PRINT @ + @1
END
```
[Answer]
# C#, ~~135~~ ~~138 :(~~ 137 bytes
Golfed:
```
IEnumerable<string>F(string s,char c){int i=1,l;for(;;){yield return s;l=s.Length;while(i<l&&s[i]==c)i++;if(i==l)break;s=s.Remove(i,1);}}
```
Ungolfed:
```
IEnumerable<string> F(string s, char c)
{
int i = 1, l;
for (;;)
{
yield return s;
l = s.Length;
while (i < l && s[i] == c)
i++;
if (i == l)
break;
s = s.Remove(i, 1);
}
}
```
Function returns collection of strings.
EDIT1: @psycho noticed that algorithm was not implemented properly.
EDIT2: Created variable for `s.Length`. One byte saved thanks to @TheLethalCoder.
[Answer]
# **Python 2 - ~~65~~ 73 Bytes**
```
lambda s,c:[s[0]+c*s[1:i].count(c)+s[i+1:]for i in range(len(s))]
```
And a **76 Bytes** recursive solution, because despite being longer than the firt one, I kinda like it better:
```
f=lambda s,c,i=1:s[i:]and[[s]+f(s[:i]+s[i+1:],c,i),f(s,c,i+1)][s[i]==c]or[s]
```
[Answer]
## Racket 194 bytes
```
(let p((s s)(n 1)(t substring)(a string-append))(displayln s)(cond[(>= n(string-length s))""]
[(equal? c(string-ref s n))(p(a(t s 0 n)(t s n))(+ 1 n)t a)][else(p(a(t s 0 n)(t s(+ 1 n)))n t a)]))
```
Ungolfed:
```
(define (f s c)
(let loop ((s s)
(n 1))
(displayln s)
(cond
[(>= n (string-length s))""]
[(equal? c (string-ref s n))
(loop (string-append (substring s 0 n) (substring s n))
(add1 n))]
[else
(loop (string-append (substring s 0 n) (substring s (add1 n)))
n)])))
```
Testing:
```
(f "Test cases" #\s)
(f "codegolf.stackexchange.com" #\e)
```
Output:
```
Test cases
Tst cases
Tst cases
Ts cases
Tscases
Tsases
Tsses
Tsses
Tsss
Tsss
""
codegolf.stackexchange.com
cdegolf.stackexchange.com
cegolf.stackexchange.com
cegolf.stackexchange.com
ceolf.stackexchange.com
celf.stackexchange.com
cef.stackexchange.com
ce.stackexchange.com
cestackexchange.com
cetackexchange.com
ceackexchange.com
ceckexchange.com
cekexchange.com
ceexchange.com
ceexchange.com
ceechange.com
ceehange.com
ceeange.com
ceenge.com
ceege.com
ceee.com
ceee.com
ceeecom
ceeeom
ceeem
ceee
""
```
[Answer]
# Swift 3 - ~~151~~ 147 bytes
Swift isn't the ideal language for golfing, particularly when it relates to string indexing. This is the best I could do:
```
func c(a:String,b:String){print(a);var q=Array(a.characters),i=1;while i<q.count{if "\(q[i])" != b{q.remove(at:i);c(a:String(q),b:b);break};i=i+1}}
```
Unfortunately, Swift needs spaces around `!=` (but not for `==`), and Swift 3 dropped the `++` operator. The trick for both of these is to convert to a character array which allows integer indexing, and using string interpolation of a character to convert back to a `String` (`"\(c)"`).
Ungolfed:
```
func c(a:String, b:String) {
print(a)
var q = Array(a.characters)
var i = 1
while i < q.count {
if "\(q[i])" != b {
q.remove(at:i)
c(a: String(q), b: b)
break
}
i=i+1
}
}
```
---
### Previous, non-recursive solution
```
func c(a:String,b:String){var q=Array(a.characters),e={q.removeFirst()},z="\(e())";print(a);while !q.isEmpty{"\(e())"==b ? z=z+b : print(z+String(q))}}
```
```
func c(a:String, b:String) {
var q = Array(a.characters)
var z = "\(q.removeFirst())"
print(a)
while !q.isEmpty {
if "\(q.removeFirst())" == b {
z = z + b
}else{
print(z + String(q))
}
}
}
```
[Answer]
## Pyke, ~~26~~ ~~19~~ 17 bytes
```
jljjhF3<Q/Q*jih>s
```
[Try it here!](http://pyke.catbus.co.uk/?code=jljjhF3%3CQ%2FQ%2ajih%3Es&input=e%0Acodegolf.stackexchange.com)
```
- Q = input
j - j = input_2
ljjhF3 - for (i, j, j[0]) for i in range(len(j))
< - j[:i]
Q/ - ^.count(Q)
Q* - ^*Q
s - sum(j[0], ^, V)
jih> - j[i+1:]
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 77 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.625 bytes
```
ḣ≬‡⁰≠Ǒ⟇↔Ṡ+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwi4bij4oms4oCh4oGw4omgx5Hin4fihpThuaArIiwiIiwiY29kZWdvbGYuc3RhY2tleGNoYW5nZS5jb21cbmUiXQ==)
## Explained
The very first explanation generated using [Luminespire](https://vyxal.github.io/Luminespire/), a currently work-in-progress explanation formatting assistant. Now with metadata!
```
ḣ≬‡⁰≠Ǒ⟇↔Ṡ+­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­
·∏£ # ‚Äé‚Å°Push first character of input, then all of input minus first character
≬ ↔ # ‎⁢Repeat and collect results of applying the following on the top of the stack until invariant:
‡ Ǒ # ‎⁣ Find the first index of:
⁰≠ # ‎⁤ a character that isn't the second input
⟇ # ‎⁢⁡ Remove that character from the top of the stack
Ṡ # ‎⁢⁢Convert each item to a string via vectorised summation
+ # ‎⁢⁣Prepend the first letter to each
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
```
f(x,v,i)char*x,*i;{for(puts(i=x);*++i;)*i-v&&puts(x,strcpy(i--,i+1));}
```
[Try it online!](https://tio.run/##Pcy9DoIwFIbhnas4MkBbyuDcMLG4uJk4iENTCzaCJW0hNYRrr/wYz/jleY/IGyFCqJGnI1VYPLkhnhLFplob1A/OIlV4zEiWKYaJysck2VZPrTOi/yCV51RlR4zZHDqu3ghP0foG7O0OBcQXaR2U3Eobs6hGlkJqU8x243Zz5i8JHKq4lL@rYuiNbgzvtsotlfxXw16dZNtquGrTPg6bGhZ1WNUcvg "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 65 bytes(32-bit) by c--
```
f(x,v){char*i;for(puts(i=x);*++i;)*i-v&&puts(x,strcpy(i--,i+1));}
```
[Try it online!](https://tio.run/##PcwxD4IwEIbh3V9xMmAL7aCODROLi5uJgzo0tcXGIqRXDMbw160Kxhu/PO8pXikVoyE9u9OnukifWWEaT9ouILFFT0WW51bQzPJ7mo5rzzB41T6I5ZzZfEmpGGIt7Y3Q5@z7AvBwggKSncYApUSNiZgZggwWuKBiMmEyW3nVIOGYlPp3xwRa31Re1mMVPpX@V91UbbRzDewb787zUXUfNf@qIb6UcbLCyOv16g0 "C (gcc) – Try It Online")
[Answer]
# Mathematica, 78 bytes
Damn you Martin Ender, I was almost first :p
```
(i=2;a={c=#};While[i<=Length@c,If[c[[i]]==#2,i++,c=c~Drop~{i};a=a~Append~c]];a)&
```
Unnamed function; straightforward implementation with a `While` loop and a few temporary variables.
] |
[Question]
[
This question has been spreading like a virus in my office. There are quite a variety of approaches:
Print the following:
```
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
```
Answers are scored in characters with fewer characters being better.
[Answer]
# Clojure, ~~191~~ 179 bytes
```
#(loop[[r & s](range 18)h 1](print(apply str(repeat(if(< r 8)(- 8 r)(- r 8))\ )))(doseq[m(concat(range 1 h)(range h 0 -1))](print m))(println)(if s(recur s((if(< r 8)inc dec)h))))
```
-12 bytes by changing the outer `doseq` to a `loop`, which allowed me to get rid of the `atom` (yay).
A double "for-loop". The outer loop (`loop`) goes over each row, while the inner loop (`doseq`) goes over each number in the row, which is in the range `(concat (range 1 n) (range n 0 -1))`, where `n` is the highest number in the row.
```
(defn diamond []
(let [spaces #(apply str (repeat % " "))] ; Shortcut function that produces % many spaces
(loop [[row-n & r-rows] (range 18) ; Deconstruct the row number from the range
high-n 1] ; Keep track of the highest number that should appear in the row
(let [top? (< row-n 8) ; Are we on the top of the diamond?
f (if top? inc dec) ; Decided if we should increment or decrement
n-spaces (if top? (- 8 row-n) (- row-n 8))] ; Calculate how many prefix-spaces to print
(print (spaces n-spaces)) ; Print prefix-spaces
(doseq [m (concat (range 1 high-n) (range high-n 0 -1))] ; Loop over the row of numbers
(print m)) ; Print the number
(println)
(if r-rows
(recur r-rows (f high-n)))))))
```
Due to a bug in the logic in my first attempt (accidentally inserting the prefix-spaces between each number instead), I managed to get this:
```
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
12345678987654321
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
```
Not even correct ignoring the obvious bug, but it looked cool.
[Answer]
## J, ~~29 26 24 23 22~~ 21 chars
```
,.(0&<#":)"+9-+/~|i:8
```
Thanks to [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl) for the `"+` trick (I don't think I've ever used `u"v` before, heh).
### Explanation
```
i:8 "steps" vector: _8 _7 _6 ... _1 0 1 ... 7 8
| magnitude
+/~ outer product using +
9- inverts the diamond so that 9 is in the center
( )"+ for each digit:
# copy
0&< if positive then 1 else 0
": copies of the string representation of the digit
(in other words: filter out the strictly positive
digits, implicitly padding with spaces)
,. ravel each item of the result of the above
(necessary because the result after `#` turns each
scalar digit into a vector string)
```
[Answer]
## APL (~~33~~ 31)
```
A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽¨⍴∘(1↓⎕D)¨⍳9
```
If spaces separating the numbers are allowed (as in the Mathematica entry), it can be shortened to ~~28~~ 26:
```
A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽∘⍕∘⍳¨⍳9
```
Explanation:
* (Long program:)
* `⍳9`: a list of the numbers 1 to 9
* `1↓⎕D`: `⎕D` is the string '0123456789', `1↓` removes the first element
* `⍴∘(1↓⎕D)¨⍳9`: for each element N of `⍳9`, take the first N elements from `1↓⎕D`. This gives a list: ["1", "12", "123", ... "123456789"] as strings
* `⌽¨`: reverse each element of this list. ["1", "21", "321"...]
* (Short program:)
* `⍳¨⍳9`: the list of 1 to N, for N [1..9]. This gives a list [[1], [1,2], [1,2,3] ... [1,2,3,4,5,6,7,8,9]] as numbers.
* `⌽∘⍕∘`: the reverse of string representation of each of these lists. ["1", "2 1"...]
* (The same from now on:)
* `A←⌽↑`: makes a matrix from the list of lists, padding on the right with spaces, and then reverse that. This gives the upper quadrant of the diamond. It is stored in A.
* `A←A,0 1↑⌽A`: A, with the reverse of A minus its first column attached to the right. This gives the upper half of the rectangle. This is then stored in A again.
* `A⍪1↓⊖A`: `⊖A` is A mirrored vertically (giving the lower half), `1↓` removes the top row of the lower half and `A⍪` is the upper half on top of `1↓⊖A`.
[Answer]
# Mathematica 83 49 43 54 51
```
Print@@#&/@(Sum[k~DiamondMatrix~17,{k,0,8}]/.0->" ")
```
![formatting improved](https://i.stack.imgur.com/O5CCH.png)
---
With 3 bytes saved thanks to Kelly Lowder.
**Analysis**
The principal part of the code, `Sum[DiamondMatrix[k, 17], {k, 0, 8}]`, can be checked on [WolframAlpha](http://www.wolframalpha.com/input/?i=Sum%5BDiamondMatrix%5Bk,%2017%5D,%20%7Bk,%200,%208%7D%5D%20%20).
The following shows the underlying logic of the approach, on a smaller scale.
```
a = 0~DiamondMatrix~5;
b = 1~DiamondMatrix~5;
c = 2~DiamondMatrix~5;
d = a + b + c;
e = d /. 0 -> "";
Grid /@ {a, b, c, d, e}
```
![grids](https://i.stack.imgur.com/wTeyK.png)
[Answer]
# Python 2, ~~72~~ ~~69~~ ~~67~~ 61
Not clever:
```
s=str(111111111**2)
for i in map(int,s):print'%8s'%s[:i-1]+s[-i:]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
v;main(i){for(;i<307;putchar(i++%18?v>8?32:57-v:10))v=abs(i%18-9)+abs(i/18-8);}
```
[Try it online!](https://tio.run/##S9ZNT07@/7/MOjcxM08jU7M6Lb9IwzrTxtjA3LqgtCQ5I7FII1NbW9XQwr7MzsLe2MjK1Fy3zMrQQFOzzDYxqVgjEyila6mpDWbrA9kWmta1//8DAA "C (gcc) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ 59 bytes
```
for n in`111111111**2`:print`int('1'*int(n))**2`.center(17)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFPITMvwRAGtLSMEqwKijLzShKAWEPdUF0LROdpaoJk9JJT80pSizQMzTX//wcA "Python 2 – Try It Online")
Abuses backticks and repunits.
[Answer]
**Mathematica ~~55~~ ~~50~~ ~~45~~ ~~41~~ 38**
```
(10^{9-Abs@Range[-8,8]}-1)^2/81//Grid
Grid[(10^Array[{9}-Abs[#-9]&,17]-1)^2/81]
```
![Mathematica graphics](https://i.stack.imgur.com/BqZrm.png)
[Answer]
# Javascript, 114
My first entry on Codegolf!
```
for(l=n=1;l<18;n-=2*(++l>9)-1,console.log(s+z)){for(x=n,s="";x<9;x++)z=s+=" ";for(x=v=1;x<2*n;v-=2*(++x>n)-1)s+=v}
```
If this can be shortened any further, please comment :)
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 33 31 30 bytes
Another GolfScript solution
```
17,{8-abs." "*10@-,1>.-1%1>n}%
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/39Bcp9pCNzGpWE9JQUnL0MBBV8fQTk/XUNXQLq9W9f9/AA "GolfScript – Try It Online")
Thank you to [@PeterTaylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for another char.
**Previous versions:**
```
17,{8-abs" "*9,{)+}/9<.-1%1>+}%n*
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/39Bcp9pCNzGpWElBSctSp1pTu1bf0kZP11DV0E67VjVP6/9/AA "GolfScript – Try It Online")
```
17,{8-abs" "*9,{)+}/9<.-1%1>n}%
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/39Bcp9pCNzGpWElBSctSp1pTu1bf0kZP11DV0C6vVvX/fwA "GolfScript – Try It Online")
[Answer]
## PHP, 92 90 characters
```
<?for($a=-8;$a<9;$a++){for($b=-8;$b<9;){$c=abs($a)+abs($b++);echo$c>8?" ":9-$c;}echo"\n";}
```
Calculates and prints the Manhattan distance of the position from the centre. Prints a space if it's less than 1.
An anonymous user suggested the following improvement (84 characters):
```
<?for($a=-8;$a<9;$a++,print~õ)for($b=-8;$b<9;print$c>8?~ß:9-$c)$c=abs($a)+abs($b++);
```
[Answer]
# [Charcoal](http://github.com/somebody1234/Charcoal), 13 bytes
```
F⁹«GX⁻⁹ιI⁺ι¹↓
```
[Try it online!](https://tio.run/##AS0A0v9jaGFyY29hbP//77ym4oG5wqvvvKdY4oG74oG5zrnvvKnigbrOucK54oaT//8)
### How?
Draws nine, successively smaller, concentric number-diamonds on top of each other:
```
F⁹« Loop ι from 0 to 8:
GX Draw a (filled) polygon with four equilateral diagonal sides
⁻⁹ι of length 9-ι
I⁺ι¹ using str(ι+1) as the character
↓ Move down one space before drawing the next one
```
[Answer]
# Vim, ~~62~~ ~~39~~ ~~38~~ 34 keystrokes
*Thanks to @DJMcMayhem for saving a ton of bytes*
*Thanks to @AaronMiller for saving 4 bytes by generating `12345678987654321` in a different way*
```
9i1<ESC>|C<C-r>=<C-r>"*<C-r>"
<ESC>qqYP9|xxI <ESC>YGpHq7@q
```
[Try it online!](https://tio.run/##K/v/3zLTULrGWchWSElLSIlLurAwMsCypqLCU0E60r3Ao9DcofD/fwA "V (vim) – Try It Online")
### Explanation:
```
9i1<ESC> Write 9 '1's, leaving the cursor at the end of the line
|C Go to the first column and cut all that's to the right of the cursor (implictly into register "), entering insert mode
<C-r>= Enter an expression:
<C-r>"*<C-r>" The contents of register " multiplied with itself
<CR> Evaluate it, yielding 12345678987654321
qq Start recording into register q
YP Yank this entire line and Paste above
9| Go to the 9th column
xx Delete character under cursor twice
I <ESC> Go to the beginning of the line and insert a space and enter normal mode
Y Yank this entire line
G Go to the last line
p Paste in the line below
H Go to the first line
q End recording
7@q Repeat this 7 times
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 81 bytes
```
for(i=9;--i+9;console.log(s))for(j=9;j;s=j--^9?k>0?k+s+k:" "+s:k+"")k=i<0?j+i:j-i
```
[Try it online!](https://tio.run/##FcnBDkAwDADQX5GdLE3F0TazP5GIIG3FRMXvD@/6eHomnS86b3y6UtZ81RRdQCRwYc6H5n1p9rzVau2f/CUHjYw4uiRDmwQUxJvKgHoBY6xE6tvEQJ6RSnkB "JavaScript (V8) – Try It Online")
[Answer]
# [Common Lisp](http://www.clisp.org/), 113 bytes
```
(defun x(n)(if(= n 0)1(+(expt 10 n)(x(1- n)))))(dotimes(n 17)(format t"~17:@<~d~>~%"(expt(x(- 8(abs(- n 8))))2)))
```
[Try it online!](https://tio.run/##HYtRCoMwEAWvsgjCC0XI9kcptfQqtkkgUFdpIuQrV0/XPngMDMz7E9PeGpwPh1CBGMSAmYSsYVzgy56JLakv4EF5Dm7LcfUJQjwahO27LplyV3m8Pe/V1Uftu3@r1UATlldSCk1nfdW39gM "Common Lisp – Try It Online")
First I noticed that the elements of the diamond could be expressed like so:
```
1 = 1 ^ 2
121 = 11 ^ 2
12321 = 111 ^ 2
```
etc.
`x` recursively calculates the base (1, 11, 111, etc), which is squared, and then printed centered by `format`. To make the numbers go up to the highest term and back down again I used `(- 8 (abs (- n 8)))` to avoid a second loop
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), ~~109~~ 108 bytes
```
(( {#2-1}| {8})($3${#3+1}|1)(${#4+1}$4|)\n){9}(( $6| )(${$7/10}|${$3/10})(${$8-1+1/$8*(#7-1)}|7){#7-1}\n){8}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdcGCpaUlaboWN3M0NBSqlY10DWtrFKotajU1VIxVqpWNtYF8QyCnWtkEyFQxqdGMydOstqwFqlYxq1EAyaiY6xsa1NYAGcYgBljIQtdQ21BfxUJLQ9lc11CztsZcsxrEqgXptqiF2Am1GuYEAA)
## Explanation
The solution is divided into two parts, which generate the upper half of the diamond (including the center line) and the lower half, respectively. The upper half consists of group 1, repeated nine times `(...\n){9}`; the lower half consists of group 5, repeated eight times `(...\n){8}`.
The first part of each group handles the spaces. (I've replaced space with underscore in the explanations for better visibility.)
Upper-half spaces:
```
( {#2-1}| {8})
( ) Group 2:
_{#2-1} Space, repeated one less time than the previous length of group 2
| Or, if this is the first row and there is no previous value of
group 2...
_{8} Space, repeated eight times
```
Lower-half spaces:
```
( $6| )
( ) Group 6:
_$6 Space, concatenated to the previous value of group 6
| Or, if this is the first row and there is no previous value of
group 6...
_ A single space
```
Now for the diamond itself. It can be divided into four quadrants, and I used three different approaches to generate them:
### Top left & top right: concatenation
We generate the left half (including the center) of each row with group 3, and the right half with group 4. For both halves, observe that we can generate the next row by concatenating a digit to the previous row:
```
1234 321
| |
v v
12345 4321
```
So we can use a similar approach to what we did for the bottom-half spaces. The only difference is that the character we're concatenating at each step needs to be calculated.
Top left quadrant:
```
($3${#3+1}|1)
( ) Group 3:
$3 Previous value of group 3
${ } concatenated to the result of...
#3+1 Previous length of group 3 plus 1
| Or, if this is the first row and there is no previous value of
group 3...
1 The digit 1
```
Top right quadrant:
```
(${#4+1}$4|)
( ) Group 4:
${ } The result of...
#4+1 Previous length of group 4 plus 1
$4 concatenated to the previous value of group 4
| Or, if this is the first row and there is no previous value of
group 4...
Empty string
```
### Bottom left: integer division
We generate the left half (including the center) of each row with group 7. Observe that each row is obtained by removing the rightmost digit from the previous row:
```
12345
|
v
1234
```
If we treat the entire thing as an integer, we can perform this transformation easily by dividing it by ten:
```
(${$7/10}|${$3/10})
( ) Group 7:
${ } The result of...
$7/10 Previous value of group 7, divided by 10
| Or, if there is no previous value of group 7...
${ } The result of...
$3/10 Group 3 (the final upper-left quadrant row) divided by 10
```
### Bottom right: digit-by-digit
There isn't an easy way to remove a digit from the left side of a previous match, so for the right half of each bottom row, we resort to generating one digit at a time with group 8. Here are the first three rows that we need to generate:
```
7654321
654321
54321
```
Each digit is one less than the previous digit, except that we have to "reset" when we hit 1. The reset value is always one less than the length of the left half of the row, which we have access to as group 7.
How can we tell when we've hit 1? I used an integer-division trick I first developed for programming in [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!): if N is a positive integer, then 1/N will be one iff N = 1 and zero if N > 1. Multiplying this quantity by (length of group 7) - 1 gives us the reset we need.
```
(${$8-1+1/$8*(#7-1)}|7){#7-1}
( ) Group 8 (generates one digit at a time):
${ } The result of...
$8-1 Previous value of group 8, minus 1
+ Plus
#7-1 The length of group 7 minus 1
1/$8*( ) if the previous value of group 8 equals 1
| Or, if there is no previous value of group 8...
7 The digit 7
{ } Generate this many digits on each row:
#7-1 One less than the length of group 7
```
[Answer]
## PowerShell (2 options): ~~92~~ ~~84~~ 45 bytes
```
1..8+9..1|%{' '*(9-$_)+[int64]($x='1'*$_)*$x}
1..9+8..1|%{' '*(9-$_)+[int64]($x='1'*$_)*$x}
```
>
> Thanks to [Strigoides](https://codegolf.stackexchange.com/a/8709/9387) for the hint to use 1^2,11^2,111^2...
>
>
>
---
>
> Shaved some characters by:
>
>
> * Eliminating `$w`.
> * Nested the definition of `$x` in place of its first use.
> * Took some clues from [Rynant's solution](https://codegolf.stackexchange.com/a/15336/9387):
> + Combined the integer arrays with `+` instead of `,` which allows elimination of the parenthesis around the arrays and a layer of nesting in the loops.
> + Used `9-$_` to calculate the length of spaces needed, instead of more complicated maths and object methods. This also eliminated the need for `$y`.
>
>
>
Explanation:
`1..8+9..1` or `1..9+8..1` generates an array of integers ascending from 1 to 9 then descending back to 1.
`|%{`...`}` pipes the integer array into a `ForEach-Object` loop via the built-in alias `%`.
`' '*(9-$_)+` subtracts the current integer from 9, then creates a string of that many spaces at the start of the output for this line.
`[int64]($x='1'*$_)*$x` defines `$x` as a string of `1`s as long as the current integer is large. Then it's converted to int64 (required to properly output 1111111112 without using E notation) and squared.
![enter image description here](https://i.stack.imgur.com/vdi03.jpg)
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~20~~ 19 bytes
```
(⍉⊢⍪1↓⊖)⍣2⌽↑,⍨\1↓⎕d
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/5rPOrtfNS16FHvKsNHbZMfdU3TfNS72OhRz95HbRN1HvWuiAEL901N@Q9U/j8NAA "APL (Dyalog Classic) – Try It Online")
`⎕d` are the digits `'0123456789'`
`1↓` drop the first (`'0'`)
`,⍨\` swapped catenate scan, i.e. the reversed prefixes `'1' '21' '321' ... '987654321'`
`↑` mix into a matrix padded with spaces:
```
1
21
321
...
987654321
```
`⌽` reverse the matrix horizontally
`(`...`)⍣2` do this twice:
`⍉⊢⍪1↓⊖` the transposition (`⍉`) of the matrix itself (`⊢`) concatenated vertically (`⍪`) with the vertically inverted matrix (`⊖`) without its first row (`1↓`)
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~158~~ 154 bytes
```
++++++++[->+>++++>+>++++++<<<<]>>>++<<+[-[-<+>>.<]<[->+<]>>>>+>[->+<<.+>]>+[-<+<.->>]<<<.<<]>>>>-[<<<<+[-<+>>.<]<[->+<]>>>>>[->+<<+.>]>-[-<+<-.>>]<<-<.>>]
```
[Try it online!](https://tio.run/##bYzBCYBQDEMHCu0EJYt8elBBEMGD4Py1rf9oLgkkL@u9HNf@bGcEpoYQrDANsJSTrJT1EAOp5lbTbnLa2RR0ohamQnqS@sGUUT/4oycMTbjvTbRhsfKIFw "brainfuck – Try It Online")
```
[spaceMem, spaceCount, space, lf, "0", numCount, numMem]
++++++++[->+>++++>+>++++++<<<<]>>>++<<+
[ for spaceCount
-[- for spaceCount minus 1
<+ inc spaceMem
>>. print space
< go to spaceCount
]
<[->+<]> fetch spaceCount from spaceMem
>>>+ inc number
>[- for numCount
>+ inc numMem
<<.+ print and inc number
> go to numCount
]
>+[- for numMem plus 1
<+ inc numCount
<.- print and decrement number
>> go to numMem
]
<<<. print lf
<< go to spaceCount
]
>>>>-[ for numCount
<<<<+[- for spaceCount plus 1
<+ inc spaceMem
>>. print space
< go to spaceCount
]
<[->+<]> fetch spaceCount from spaceMem
>>> inc number
>[- for numCount
>+ inc numMem
<<+. print and inc number
> go to numCount
]
>-[- for numMem minus 1
<+ inc numCount
<-. print and decrement number
>> go to numMem
]
<<- decrement number
<. print lf
>> go to numCount
]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
saved another 3 bytes by letting the `int` function crash instead of a loop condition. Thanks to dingledooper.
```
i=8
while[print(f'{int("1"*(9-abs(i)))**2:^17}')]:i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgqs8IzMnNbqgKDOvRCNNvRpEKRkqaWlY6iYmFWtkampqamkZWcUZmteqa8ZaZeraGv7/DwA "Python 3 – Try It Online")
[Python 3](https://docs.python.org/3/), 57 bytes
saved 1 byte by using f-Strings thanks to dingledooper.
```
i=8
while i+9:print(f'{int("1"*(9-abs(i)))**2:^17}');i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgqs8IzMnVSFT29KqoCgzr0QjTb0aRCkZKmlpWOomJhVrZGpqamppGVnFGZrXqmtaZ@raGv7/DwA "Python 3 – Try It Online")
[Python 3](https://docs.python.org/3/), 58 bytes
Even shorter solution by a different approach (prints one extra space at the beginning of each line).
```
i=8
while i+9:j=abs(i);i-=1;print(' '*j,int('1'*(9-j))**2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgqs8IzMnVSFT29IqyzYxqVgjU9M6U9fW0LqgKDOvRENdQV0rSwfMMlTX0rDUzdLU1NIy0vz/HwA "Python 3 – Try It Online")
[Python 3](https://docs.python.org/3/), 61 bytes (without extra spaces)
```
i=8
while i+9:j=9-abs(i);i-=1;print(f'%{8+j}d'%int('1'*j)**2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9PWgqs8IzMnVSFT29Iqy9ZSNzGpWCNT0zpT19bQuqAoM69EI01dtdpCO6s2RV0VxFU3VNfK0tTSMtL8/x8A "Python 3 – Try It Online")
These are my previous solutions:
[Python 3](https://docs.python.org/3/), 66 bytes
```
f=lambda c:f'%{8+c}d'%int('1'*c)**2
for c in f(9):print(f(int(c)))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIdkqTV212kI7uTZFXTUzr0RD3VBdK1lTS8uIKy2/SCFZITNPIU3DUtOqoAgkm6YBIpM1NTX//wcA "Python 3 – Try It Online")
[Python 3](https://docs.python.org/3/), 71 bytes:
```
f=lambda c:str(int('1'*int(c))**2)
for c in f(9):print(f(c).center(17))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIdmquKRIIzOvREPdUF0LRCdramppGWlypeUXKSQrZOYppGlYaloVFIHk0oCyesmpeSWpRRqG5pqa//8DAA "Python 3 – Try It Online")
[Answer]
### Ruby, ~~76~~ ~~69~~ ~~60~~ 54 characters
```
(-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}
```
(Thanks, Patrick, G B, and Slim Liser!)
Improvements welcome. :)
[Answer]
# k (~~64~~ 50 chars)
```
-1'(::;1_|:)@\:((|!9)#'" "),'$i*i:"J"$(1+!9)#'"1";
```
Old method:
```
-1',/(::;1_|:)@\:((|!9)#\:" "),',/'+(::;1_'|:')@\:i#\:,/$i:1+!9;
```
[Answer]
# CJam, ~~31~~ 27 bytes
CJam is a lot newer than this challenge, so this answer is not eligible for being accepted. This was a neat little Saturday evening challenge, though. ;)
```
8S*9,:)+9*9/2%{_W%1>+z}2*N*
```
[Test it here.](http://cjam.aditsu.net/)
The idea is to form the upper left quadrant first. Here is how that works:
First, form the string `" 123456789"`, using `8S*9,:)+`. This string is 17 characters long. Now we repeat the string 9 times, and then split it into substrings of length 9 with `9/`. The mismatch between 9 and 17 will offset every other row one character to the left. Printing each substring on its own line we get:
```
1
23456789
12
3456789
123
456789
1234
56789
12345
6789
123456
789
1234567
89
12345678
9
123456789
```
So if we just drop every other row (which conveniently works by doing `2%`), we obtain one quadrant as desired:
```
1
12
123
1234
12345
123456
1234567
12345678
123456789
```
Finally, we mirror this twice, transposing the grid in between to ensure that the two mirroring operations go along different axes. The mirroring itself is just
```
_ "Duplicate all rows.";
W% "Reverse their order.";
1> "Discard the first row (the centre row).";
+ "Add the other rows.";
```
Lastly, we just join all lines with newlines, with `N*`.
[Answer]
# jq `-nr`, 55 bytes
```
range(17)-8|fabs|" "*.+"123456789"[:9-.]+"87654321"[.:]
```
`fabs` is not supported on TIO but you can try it on <https://jqplay.org/>.
Alternatively [try it on TIO](https://tio.run/##yyr8/78oMS89VcPQXFPXokZPS6@muLCopEZJQUlLT1vJ0MjYxNTM3MJSKdrKUlcvVlvJwtzM1MTYyFApWs8q9v//f/kFJZn5ecX/dfOKAA) with `.*.|sqrt` instead of `fabs`, for 59 bytes.
[Answer]
# [jq](https://stedolan.github.io/jq/) `-rn`, ~~76~~ ~~65~~ ~~60~~ 59 bytes
*-6 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) and another -6 (plus -5 more indirectly) thanks to [Michael Chatiskatzi](https://codegolf.stackexchange.com/users/90812/michael-chatiskatzi)*
```
def r:range(9),7-range(8);r|[8-.-r|"\(" "*.//1-.)"[:1]]|add
```
[Try it online!](https://tio.run/##yyr8/z8lNU2hyKooMS89VcNSU8dcF8K00LQuqom20NXTLapRitFQUlDS0tPXN9TV01SKtjKMja1JTEn5//9ffkFJZn5e8X/dojwA "jq – Try It Online")
### Explanation
The `-n` flag specifies that there is no input; the `-r` flag outputs the result strings, each on its own line, without quotes.
```
def r: Define a helper function r
range(9), which generates the numbers 0 through 8, followed by
7 - range(8); the numbers 7 through 0
Main program:
r | Start with the results of r
[ For each of those numbers, put the following in a list:
8 - . - r | 8, minus the current number, minus the results of calling r again
"\( For each of those numbers, interpolate the following into a string:
" " * . Try to repeat a space that many times
// and if the result is null (i.e. the number was less than 1),
1 - . subtract the number from 1 instead
)"
[:1] Take the first character of each resulting string
] | Take each resulting list of strings and
add concatenate it together
```
To help visualize what's going on, here's what just the `r|[8-.-r]` part does:
```
[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[0,-1,-2,-3,-4,-5,-6,-7,-8,-7,-6,-5,-4,-3,-2,-1,0]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]
```
Any number that's greater than 0 gets turned into that many spaces (and then trimmed back to a single space). The other numbers gets subtracted from 1 (turning 0 .. -8 into 1 .. 9) and stringified.
[Answer]
# Raku, ~~42~~ ~~41~~ ~~38~~ 35 chars
```
say " "x 9-$_,(1 x$_)²for 1…9…1
```
[Try it online!](https://tio.run/##K0gtyjH7/784sVJBSUGpQsFSVyVeR8NQoUIlXvPQprT8IgXDRw3LLIHY8P9/AA "Perl 6 – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 67 bytes
```
z="9"
for(z of(s=n=>n<z?n+s(n+1)+n:z)(1))print("".padEnd(9-z)+s(1))
```
One byte less thanks to Fhuvi
[Try it online!](https://tio.run/##DcqxCoAgEADQva8IpzvEwC0ja@pDJBFsOEXF4X7enN/7XHf1LTE31fcx2AojlpAK8JoCVEv2opNvkhVIapR0MIJGzCVSAyG27PxDHoxinGfKGD8 "JavaScript (V8) – Try It Online")
### [JavaScript (V8)](https://v8.dev/), 68 bytes
```
s=n=>n<z?n+s(n+1)+n:z
z="9"
for(z of s(1))print("".padEnd(9-z)+s(1))
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v9g2z9Yuz6bKPk@7WCNP21BTO8@qiqvKVslSiSstv0ijSiE/TaFYw1BTs6AoM69EQ0lJryAxxTUvRcNSt0pTGyzz/z8A "JavaScript (V8) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 71 bytes
For the records:
```
s=c(1:9,8:1);for(i in s)cat(rep(" ",9-i),s[0:i],s[(i-1):0],"\n",sep="")
```
[Try it online!](https://tio.run/##DcUxCsAgDADAr0imBCLoVlN8SetQxEIWK6b/t73l5lqWK0ZJvEmk/X4mqtPujOr14mwDwQEnr8R2BNHyh@ojSSgMZwe2NjIArfUB "R – Try It Online")
[Answer]
## Perl, 43+1
adding +1 for `-E` which is required for `say`
`say$"x(9-$_).(1x$_)**2for 1..9,reverse 1..8`
edit: shortened a bit
[Answer]
## Python, 65
```
for i in map(int,str(int('1'*9)**2)):print' '*(9-i),int('1'*i)**2
```
] |
[Question]
[
# AlienWar
This game takes place in a very crowded planet where aliens are the superior race. Your task is to create your own alien and beat all other.
## The Board
It is a 2 dimensional board.
The length of one side of the board is `Math.ceil(sqrt(species * 100 * 2.5))` = ~40% of board used.
The board is a planet, so if you walk out of the map in the west, you come back in the east. If you walk out in the north, you will find yourself in the south.
## Abilities
Each species on the planet has abilities. Here they are:
```
**Name** **Benefit**
life HP = *lifeLVL* * 5 (reduces with every hit you take, 0 = dead), base HP = 10
strength Your hits do a random int in range [1 to strengthLVL] damage
defense Randomly select int in range [0 to (50 / *defenseLVL* + 1)], if int == 0 then dodge next attack
vision Gives you *visionLVL*/2 fields around you vision
cleverness Blurs (increases) every ability randomly in range [0 to *clevernessLVL*/2] when sending to other aliens
```
## The Game
* There will be 100 instances of each submission.
* After instancing, each alien can set 10 ability points in total. You can set different points for every instance.
* If you set more than 10 points, the instance dies.
* A game consists of 1000 rounds. Each round:
+ Every alien has to return a move via `move(char[] fields)`. This includes Move.STAY.
+ If several aliens are on a field, 2 will be randomly selected:
- If both agree on peace (return false in `wantToFight`) they will stay where they are, else they will fight.
- This loops until only one alien stays on a field or all agree on peace.
* If an alien kills something, **he gets 1/5 of each of his enemies abilities**. The winners HP will be refilled with 2\**enemyLifeLVL*.
* **Winner is the one with the most abilities** (sum of abilities of living aliens).
## Fights
Both aliens will hit each other "at the same time", this means if you kill the other alien, he still can hit you one time.
Dodging: Before you get hit, the game will calculate if you can dodge the attack by using `rand.nextInt(50 / defenseLvl + 1) == 0`. **defenseLvl will never be greater than 50** when calculating your dodge-skills (hence maximum dodge-chance is 50%).
Hitting: If you don't dodge the attack, you will get hit and your HP will be reduced by `rand.nextInt(enemy.getStrengthLvl()) + 1`.
A fight ends when either one or both alien involved are dead. The winner, if one exists, gets the reward.
## Gamerules
* Base level for every ability (without giving any ability points) is 1 (base HP is 10).
* The values sent when asked to fight are **life (not HP!), strength, defense and vision**-levels.
* Cleverness is NOT sent when asked to fight.
* All floating numbers will be ROUNDED to nearest integer when using/sending them, but stored and increased as float.
* Maximum dodge-chance is 50%. Otherwise fights may never terminate.
## The Prey
There are 5 species which are already on the field. Since they are prey, they choose not to fight when asked to.
```
Whale: lvl 10 life Stays
Cow: lvl 10 strength Random move
Turtle: lvl 10 defense South west
Eagle: lvl 10 vision Examines fields, tries to avoid danger
Human: lvl 10 cleverness North east
```
They will be represented with their first letter (i.e. `W` for whale) in the map (Aliens with `A`, empty fields with a whitespace `' '`).
## Additional Rules
* Reflection is disallowed.
* Interacting (instancing etc.) with other aliens is disallowed.
* Writing/Reading external resources like files or databases is also disallowed.
* Only Java (version 1.8) submissions allowed (Java is rather easy, and you don't have to be an expert for this game).
* All submissions must extend the alien-class and will be placed in the alien-package.
* I will accept the best alien on 19th of July. All aliens submitted by 12:00 UTC that day will be tested.
* Maximum 3 submissions per user since there are already very many aliens.
## Example of an alien
```
package alien;
import planet.Move;
public class YourUniqueNameHere extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 2; //life
abilities[1] = 2; //strength
abilities[2] = 2; //defense
abilities[3] = 2; //vision
abilities[4] = 2; //cleverness
}
public Move move(char[][] fields) {
//you are in the middle of the fields, say fields[getVisionFieldsCount()][getVisionFieldsCount()]
return Move.STAY;
}
public boolean wantToFight(int[] enemyAbilities) {
//same order of array as in setAbilityPoints, but without cleverness
return true;
}
}
```
## Control program
Source code for the control program can be found [here](https://github.com/CommonGuy/AlienWar). Now updated with all aliens included in the latest run.
## Final scores (20.07.2014, average of 10 games)
```
alien.PredicatClaw 1635.4
alien.LazyBee 1618.8
alien.CartographerLongVisionAlien 1584.6
alien.ChooseYourBattles 1571.2
alien.Bender 1524.5
alien.HerjanAlien 1507.5
alien.FunkyBob 1473.1
alien.SecretWeapon2 1467.9
alien.PredicatEyes 1457.1
alien.CorporateAlien 1435.9
alien.GentleGiant 1422.4
alien.CropCircleAlien 1321.2
alien.VanPelt 1312.7
alien.NewGuy 1270.4
alien.BananaPeel 1162.6
alien.Rock 1159.2
alien.BullyAlien 1106.3
alien.Geoffrey 778.3
alien.SecretWeapon 754.9
alien.SecretWeapon3 752.9
alien.FunkyJack 550.3
alien.Stone 369.4
alien.Assassin 277.8
alien.Predicoward 170.1
prey.Cow 155.2
alien.Morphling 105.3
alien.Eli 99.6
alien.Warrior 69.7
alien.Hunter 56.3
alien.Manager 37.6
alien.OkinawaLife 14.2
prey.Whale 10.5
alien.Gamer 4.5
alien.Randomite 0
alien.Guard 0
prey.Eagle 0
alien.Rogue 0
alien.WeakestLink 0
alien.Fleer 0
alien.Survivor 0
alien.Sped 0
alien.Junkie 0
alien.Coward 0
alien.CleverAlien 0
prey.Human 0
alien.BlindBully 0
prey.Turtle 0
alien.AimlessWanderer 0
```
[Answer]
# Manager
Here's a manager. Naturally, the cleverness is 0 and he always strives to go where the sun don't shine. And, of course, he will only fight the weak and is very good in dodging trouble:
```
public class Manager extends Alien {
private static final int STRENGTH = 5;
@Override
public void setAbilityPoints( float[] abilities ) {
abilities[/* strength */ 1] = STRENGTH;
abilities[/* defense */ 2] = 5;
abilities[/* cleverness */ 4] = 0; // just to make sure
}
@Override
public Move move( char[][] fields ) {
return Move.WEST;
}
@Override
public boolean wantToFight( int[] enemyAbilities ) {
return enemyAbilities[1] < STRENGTH;
}
}
```
[Answer]
## CartographyLongVisionAlien
This Alien is a consistant performing variant of one of my attempts to produce an alien that is of winning potential.
It has initial 5x5 vision which it uses to build up an internal map of the surrounding area giving it superior enemy avoidance ability.
In my testing of 100 rounds, on average, It sneaks ahead of all other aliens. (09/07/2014)
**UPDATED GIF showing the repell/attract field effect**
I have modified the Game code to produce animated GIFs of the simulation. You can view such a simluation [here](https://drive.google.com/file/d/0B9i-DPAdw_3YUkdLNlEybjlfbEk/edit?usp=sharing)
```
package alien;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import planet.Move;
import planet.Planet;
/**
* Created by moogie on 09/07/14.
*
* This Alien attempts to map the visible and guess the movements within the immediate non-visible area around the alien.
* To this end, the alien can initially see 5x5 grid. It applies weights on the cells of its internal map based on the
* prey/alien/blanks within its field of view. It then performs a simple blur to guess movements and then chooses the optimum move
* based on the contents of its internal map.
*
* If it is asked to fight, it performs battle simulations to determine whether it should nominate to fight.
*/
public class CartographerLongVisionAlien extends Alien
{
private final static byte LIFE = 0, STR = 1, DEF = 2, VIS = 3, CLV = 4;
// Plant Entity symbols
private static final char TURTLE = 'T';
private static final char HUMAN = 'H';
private static final char WHALE = 'W';
private static final char COW = 'C';
private static final char EAGLE = 'E';
private static final char ALIEN = 'A';
private static final HashMap<Character, Move> preyMovement = new HashMap<>();
static
{
preyMovement.put(WHALE, Move.STAY);
preyMovement.put(TURTLE, Move.SOUTHWEST);
preyMovement.put(HUMAN, Move.NORTHEAST);
};
// Map constants
public static final int MAP_SIZE_DIV_2 = 10;
public static final int MAP_SIZE = MAP_SIZE_DIV_2 * 2 + 1;
private static final int MAP_SIZE_MINUS_ONE = MAP_SIZE - 1;
private static final double FADE_FACTOR=0.85;
// Planet constants
private static final int STARTING_HP = 10;
private static final int START_HEALING_FACTOR = 5;
private static final int MAX_DEFENCE = 50;
// Battle Simulation constants
private static final double AMBIGUOUS_ENEMY_HP_FACTOR = 2;
private static final int SIMULATED_BATTLE_COUNT = 100;
private static final int SIMULATED_BATTLE_THREASHOLD = (int)(SIMULATED_BATTLE_COUNT*1.0);
private Random rand = new Random(Planet.rand.nextLong());
/** The alien's map of the immediate and mid-range area */
public double[][] map = new double[MAP_SIZE][MAP_SIZE];
public void setAbilityPoints( float[] abilities )
{
// +0.5 gain due to rounding trick "borrowed" from PredicatClaw http://codegolf.stackexchange.com/a/32925/20193
abilities[LIFE] = 3.5f; // We do need some hit points to ensure that we can survive the melee of the beginning game.
abilities[STR] = 4.5f; // A Moderate attack strength means that we do not have to go through as many fight rounds.
abilities[DEF] = 0; // We will get from prey and other aliens
abilities[VIS] = 2; // A minimum of 2 is required to get a 5x5 field of view
abilities[CLV] = 0; // We will get from prey and other aliens
}
/**
* simulate alien memory fade. This allows an alien to eventually venture back to areas already traversed.
*/
private void fadeMap()
{
for ( int y = 0; y < MAP_SIZE; y++ )
{
for ( int x = 0; x < MAP_SIZE; x++ )
{
map[x][y] *= FADE_FACTOR;
}
}
}
/**
* shift the maps with the movement of the alien so that the alien is always at the centre of the map
*
* @param move
*/
private void shiftMaps( Move move )
{
int i, j;
final int offsetX = -move.getXOffset();
final int offsetY = -move.getYOffset();
double[][] tempMap = new double[MAP_SIZE][MAP_SIZE];
for ( int y = 0; y < MAP_SIZE; y++ )
{
for ( int x = 0; x < MAP_SIZE; x++ )
{
i = x + offsetX;
j = y + offsetY;
if ( i >= 0 && i <= MAP_SIZE_MINUS_ONE && j >= 0 && j <= MAP_SIZE_MINUS_ONE )
{
tempMap[i][j] = map[x][y];
}
}
}
map = tempMap;
}
/**
* Updates a cell in the alien's map with the desirability of the entity in the cell
*
* @param x
* @param y
* @param chr
*/
private void updateMap( int x, int y, char chr )
{
// Note that these desire values are just guesses... I have not performed any analysis to determine the optimum values!
// That said, they seem to perform adequately.
double desire = 0;
int i=x;
int j=y;
switch ( chr )
{
case WHALE:
desire=2;
break;
case TURTLE:
case HUMAN:
desire=1;
Move preyMove = preyMovement.get( chr );
// predict movement into the future
while ( i >= 0 && i <= MAP_SIZE_MINUS_ONE && j >= 0 && j <= MAP_SIZE_MINUS_ONE )
{
map[i][j] = ( map[i][j] + desire ) / 2;
i+=preyMove.getXOffset();
j+=preyMove.getYOffset();
desire/=2;
}
break;
case COW:
desire = 0.5;
break;
case EAGLE:
desire = 1;
break;
case ALIEN:
desire = -10;
break;
}
map[x][y] = ( map[x][y] + desire ) / 2;
}
/**
* Apply a blur the map to simulate the movement of previously seen entities that are no longer within the field of view.
*/
private void convolve()
{
double[][] tempMap = new double[MAP_SIZE][MAP_SIZE];
int count;
double temp;
for ( int y = 0; y < MAP_SIZE; y++ )
{
for ( int x = 0; x < MAP_SIZE; x++ )
{
count = 0;
temp = 0;
for ( int i = x - 1; i < x + 2; i++ )
{
for ( int j = y - 1; j < y + 2; j++ )
{
if ( i >= 0 && i <= MAP_SIZE_MINUS_ONE && j >= 0 && j <= MAP_SIZE_MINUS_ONE )
{
temp += map[i][j];
count++;
}
}
}
temp += map[x][y] * 2;
count += 2;
tempMap[x][y] = temp / count;
}
}
map = tempMap;
}
/**
* Determine the move that minimises the risk to this alien and maximises any potential reward.
*
* @param fields
* @return
*/
private Move findBestMove( char[][] fields )
{
List<Move> moveOptions = new ArrayList<>();
double bestMoveScore = -Double.MAX_VALUE;
double score;
// find the moves that have the best score using the alien's map
for ( Move move : Move.values() )
{
int x = MAP_SIZE_DIV_2 + move.getXOffset();
int y = MAP_SIZE_DIV_2 + move.getYOffset();
score = map[x][y];
if ( score == bestMoveScore )
{
moveOptions.add( move );
}
else if ( score > bestMoveScore )
{
bestMoveScore = score;
moveOptions.clear();
moveOptions.add( move );
}
}
Move move = moveOptions.get( rand.nextInt( moveOptions.size() ) );
// if the best move is to stay...
if ( move == Move.STAY )
{
// find whether there are no surrounding entities in field of vision...
int midVision = getVisionFieldsCount();
boolean stuck = true;
out: for ( int i = 0; i < fields.length; i++ )
{
for ( int j = 0; j < fields.length; j++ )
{
if ( !( i == midVision && j == midVision ) && fields[i][j] != ' ' )
{
stuck = false;
break out;
}
}
}
// there there are no other entities within field of vision and we are healthy... choose a random move
if ( stuck && getCurrentHp() > getLifeLvl() * 2 )
{
move = Move.getRandom();
}
}
return move;
}
/**
* Update the alien's map with the current field of vision
*
* @param fields
*/
private void mapVisibleSurroundings( char[][] fields )
{
int midVision = getVisionFieldsCount();
// update the map with currently visible information
for ( int y = -midVision; y <= midVision; y++ )
{
for ( int x = -midVision; x <= midVision; x++ )
{
char chr = fields[midVision + x][midVision + y];
updateMap( MAP_SIZE_DIV_2 + x, MAP_SIZE_DIV_2 + y, chr );
}
}
// ensure that the map where this alien currently sits is marked as empty.
updateMap( MAP_SIZE_DIV_2, MAP_SIZE_DIV_2, ' ' );
}
public Move move( char[][] fields )
{
Move returnMove = null;
// pre-move decision processing
mapVisibleSurroundings( fields );
convolve();
returnMove = findBestMove( fields );
// post-move decision processing
fadeMap();
shiftMaps( returnMove );
return returnMove;
}
public boolean wantToFight( final int[] enemyAbilities )
{
double toughnessFactor =((double) enemyAbilities[STR])/(enemyAbilities[LIFE]*10); // a fudge-factor to ensure that whales are attacked.
if (enemyAbilities[VIS]>=3 && enemyAbilities[LIFE]>4.5f) toughnessFactor*=3.5; // make sure that we do not attack other Cartogapher aliens
return winsBattleSimulation( enemyAbilities, toughnessFactor );
}
/**
* Perform simulations to determine whether we will win against the enemy most of the time.
*
* @param enemyAbilities
* @return
*/
private boolean winsBattleSimulation( int[] enemyAbilities, double toughnessFactor )
{
int surviveCount = 0;
for ( int i = 0; i < SIMULATED_BATTLE_COUNT; i++ )
{
int estimatedEnemyHitPoints =
STARTING_HP + (int)( enemyAbilities[LIFE] * START_HEALING_FACTOR * AMBIGUOUS_ENEMY_HP_FACTOR * toughnessFactor );
int enemyPoints = estimatedEnemyHitPoints;
int myHitPoints = getCurrentHp();
int myDefenceLevel = getDefenseLvl() < MAX_DEFENCE ? getDefenseLvl() : MAX_DEFENCE;
int enemyDefenceLevel = enemyAbilities[DEF] < MAX_DEFENCE ? enemyAbilities[DEF] : MAX_DEFENCE;
while ( !( myHitPoints <= 0 || enemyPoints <= 0 ) )
{
if ( rand.nextInt( MAX_DEFENCE / myDefenceLevel + 1 ) != 0 )
{
myHitPoints -= rand.nextInt( enemyAbilities[STR] ) + 1;
}
if ( rand.nextInt( MAX_DEFENCE / enemyDefenceLevel + 1 ) != 0 )
{
enemyPoints -= rand.nextInt( getStrengthLvl() ) + 1;
}
}
if ( myHitPoints > 0 )
{
surviveCount++;
}
}
return ( surviveCount >= SIMULATED_BATTLE_THREASHOLD );
}
}
```
[Answer]
# Choose Your Battles
This alien runs away from other aliens, but runs towards prey (so long as that wouldn't take it towards aliens).
I used a genetic algorithm to help me choose the starting values. The results suggest we should rely on strength and life to get through early battes. Vision is useful later, but we can pick that up from vanquished foes.
We only fight battles we think we can comfortably win - we estimate how many moves it would take to kill our alien, how many it would take to kill our enemy, and only join the battle if it we're "twice as hard" as our opponent.
```
package alien;
import planet.Move;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static java.lang.Math.*;
public class ChooseYourBattles extends Alien {
private static final boolean DEBUG = false;
private static final int LIFE = 0;
private static final int STRENGTH = 1;
private static final int DEFENCE = 2;
private static final int VISION = 3;
private static final int CLEVERNESS = 4;
private static final Set<Character> prey = new HashSet<>();
{
Collections.addAll(prey, 'H', 'T', 'W', 'C', 'E');
}
public void setAbilityPoints(float[] abilities) {
// Rounding promotes these to 4 and 7 - 11 points!
abilities[LIFE] = 3.5f;
abilities[STRENGTH] = 6.5f;
}
@Override
public Move move(char[][] fields) {
if (DEBUG) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 2 * getVisionFieldsCount() + 1; j++) {
for (int i = 0; i < 2 * getVisionFieldsCount() + 1; i++) {
char chr = fields[i][j];
if (chr == ' ') chr = '.';
if (i == getVisionFieldsCount() && j == getVisionFieldsCount()) chr = 'X';
sb.append(chr);
}
sb.append('\n');
}
String view = sb.toString();
System.out.println(this.toString());
System.out.println(view);
}
Move bestMove = null;
int bestEnemyDistance = Integer.MIN_VALUE;
int bestPreyDistance = Integer.MAX_VALUE;
for (Move tryMove: Move.values()) {
int currentDistanceToEnemy = Integer.MAX_VALUE;
int currentDistanceToPrey = Integer.MAX_VALUE;
int x = getVisionFieldsCount() + tryMove.getXOffset();
int y = getVisionFieldsCount() + tryMove.getYOffset();
for (int i = 0; i < 2 * getVisionFieldsCount() + 1; i++) {
for (int j = 0; j < 2 * getVisionFieldsCount() + 1; j++) {
char chr = fields[i][j];
if (chr == 'A' && (i != getVisionFieldsCount() || j != getVisionFieldsCount())) {
// Use L-infinity distance, but fll back to L-1 distance
int distance = max(abs(i - x), abs(j - y)) * 100 + abs(i -x) + abs(j - y);
if (distance < currentDistanceToEnemy) currentDistanceToEnemy = distance;
} else if (prey.contains(chr)) {
int distance = max(abs(i - x), abs(j - y)) * 100 + abs(i -x) + abs(j - y);
if (distance < currentDistanceToPrey) currentDistanceToPrey = distance;
}
}
}
if (currentDistanceToEnemy > bestEnemyDistance
|| (currentDistanceToEnemy == bestEnemyDistance && currentDistanceToPrey < bestPreyDistance)) { // Prefer to stay put
bestMove = tryMove;
bestEnemyDistance = currentDistanceToEnemy;
bestPreyDistance = currentDistanceToPrey;
}
}
if (DEBUG) {
System.out.println("Going " + bestMove);
System.out.println();
}
return bestMove;
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
// Estimate whether likely to survive the encounter - are we at least "twice as hard" as our opponent
return getCurrentHp() * (50.0 + getDefenseLvl()) / (enemyAbilities[STRENGTH])
> 2.0 * (enemyAbilities[LIFE] * 5 + 10) * (50.0 + enemyAbilities[DEFENCE])/ (getStrengthLvl());
}
@Override
public String toString() {
return "ChooseYourBattles" + System.identityHashCode(this)
+ ": HP " + getCurrentHp()
+ ", LFE " + getLifeLvl()
+ ", STR " + getStrengthLvl()
+ ", DEF " + getDefenseLvl()
+ ", VIS " + getVisionLvl()
+ ", CLV " + getClevernessLvl();
}
}
```
If you want to run your own genetic algorithm/breeding program, I've got a [forked copy of the control program for this purpose](https://github.com/jamespic/AlienWar).
[Answer]
## Junkie
This alien is addicted to *something*. He starts the war on a pretty nasty fix.
While his fix is going strong (`fix > 3`) he is pleasantly content to sit in his stupor and is up for anything.
However, once his fix starts to wear off (`fix <= 3`) he starts stumbling around in no discernible direction trying to figure out what happened. If asked to fight, he becomes cautious and only fights if he thinks he can win.
Once his fix runs out, being the addict he is, he must restart the vicious cycle.
```
public class Junkie extends Alien {
private int fix = 10;
public void setAbilityPoints(float[] abilities) {
abilities[0] = 4; //life
abilities[1] = 3; //strength
abilities[2] = 3; //defense
}
public Move move(char[][] fields) {
fix -= 1;
if (fix == 0) {
fix = 10;
}
else if(fix <= 3 && fix > 0) {
return Move.getRandom();
}
return Move.STAY;
}
public boolean wantToFight(int[] enemyAbilities) {
if(fix > 3) {
return true;
}
// Am I stronger than their defense and can I withstand their attack?
else if(enemyAbilities[2] < getStrength() && enemyAbilities[1] < getDefense()) {
return true;
}
return false;
}
}
```
[Answer]
# PredicatClaw (rawr)
This feline alien will swallow you whole (okay maybe she'll chew you a bit first)... if you seem weak based on her prediction algorithms.
A breed of Predicats that have fiercer claws and fangs than its counterparts.
EDIT : New target priorities
```
package alien;
import planet.Move;
/* Predict + Cat = Predicat! */
public class PredicatClaw extends Alien {
private static final int LIF=0, STR=1, DEF=2;
private static final int WHALE=6, COW=1, TURTLE=4, EAGLE=3, HUMAN=2, ALIEN=-1, NONE=0;
@Override
public void setAbilityPoints( float[] abilities ) {
abilities[LIF] = 4.5f;
abilities[STR] = 5.5f;
}
@Override
public Move move( char[][] fields ) {
/* Some credits to Eagle for letting me learn how to do the moves */
int vision = getVisionFieldsCount(); //count of fields / middle
int fieldX;
int fieldY;
Move bestMove=Move.STAY;
int bestScore=-1;
for (Move move : Move.values()) {
fieldX = vision + move.getXOffset();
fieldY = vision + move.getYOffset();
switch(fields[fieldX][fieldY]){
case 'W' :
if(bestScore<WHALE){
bestMove=move;
bestScore=WHALE;
}
break;
case 'C' :
if(bestScore<COW){
bestMove=move;
bestScore=COW;
}
break;
case 'T' :
if(bestScore<TURTLE){
bestMove=move;
bestScore=TURTLE;
}
break;
case 'E' :
if(bestScore<EAGLE){
bestMove=move;
bestScore=EAGLE;
}
break;
case 'H' :
if(bestScore<HUMAN){
bestMove=move;
bestScore=HUMAN;
}
break;
case 'A' :
if(bestScore<ALIEN){
bestMove=move;
bestScore=ALIEN;
}
break;
case ' ' :
if(bestScore<NONE){
bestMove=move;
bestScore=NONE;
}
break;
}
}
if(vision==1 && bestScore>1){
return bestMove;
}
//check immediate outer field
for (int i=vision-2; i<=vision+2; i++) {
for(int j=vision-2; j<=vision+2; j++){
if(i==0 || i==4 || j==0 || j==4){
switch(fields[i][j]){
case 'W' :
bestMove = this.getBestMoveTo(i,j);
bestScore = WHALE;
break;
case 'C' :
if(bestScore<COW){
bestMove = this.getBestMoveTo(i,j);
bestScore = COW;
}
break;
case 'T' :
if(i>=vision && j<=vision){
return this.getBestMoveTo(i-1,j+1);
}
if(bestScore<TURTLE){
bestMove = this.getBestMoveTo(i,j);
bestScore = TURTLE;
}
break;
case 'E' :
if(bestScore<EAGLE){
bestMove = this.getBestMoveTo(i,j);
bestScore = EAGLE;
}
break;
case 'H' :
if(i<=vision && j>=vision){
return this.getBestMoveTo(i+1,j-1);
}
if(bestScore<HUMAN){
bestMove = this.getBestMoveTo(i,j);
bestScore = HUMAN;
}
break;
case 'A' :
if(bestScore<ALIEN){
bestMove = this.getBestMoveTo(i,j);
bestScore = ALIEN;
}
break;
case ' ' :
if(bestScore<NONE){
bestMove = this.getBestMoveTo(i,j);
bestScore = NONE;
}
break;
}
}
}
}
return bestMove;
}
@Override
public boolean wantToFight( int[] enemyAbilities ) {
/*
Fight IF
1) I CAN BEAT YOU
2) ????
3) MEOW!
*/
float e_hp = enemyAbilities[LIF]*5+10;
float e_dmg = 1 + enemyAbilities[STR]/2;
float e_hit = 1 - (1/(50/this.getDefenseLvl()+1));
float m_hp = this.getCurrentHp();
float m_dmg = 1 + this.getStrengthLvl()/2;
float m_hit = 1 - (1/(50/enemyAbilities[DEF]+1));
return (e_hp/(m_dmg*m_hit) < m_hp/(e_dmg*e_hit));
}
private Move getBestMoveTo(int visionX, int visionY){
int vision = getVisionFieldsCount();
if(visionX < vision && visionY < vision){
return Move.NORTHWEST;
}
else if(visionX > vision && visionY < vision){
return Move.NORTHEAST;
}
else if(visionX < vision && visionY > vision){
return Move.SOUTHWEST;
}
else if(visionX > vision && visionY < vision){
return Move.SOUTHEAST;
}
else if(visionX == vision && visionY < vision){
return Move.NORTH;
}
else if(visionX == vision && visionY > vision){
return Move.SOUTH;
}
else if(visionX > vision && visionY == vision){
return Move.EAST;
}
else if(visionX < vision && visionY == vision){
return Move.WEST;
}
else{
return Move.WEST;
}
}
}
```
[Answer]
# Banana Peel
Only tries to trip up people that need a little whacking. Defeating it won't make you healthier.
```
package alien;
import planet.Move;
public class BananaPeel extends Alien{
public void setAbilityPoints(float[] abilities){
abilities[0] = 0.5f; // banana peels barely hold themselves together
abilities[1] = 9.5f; // banana peels can't help tripping people up
abilities[2] = 0; // banana peels can't defend themselves
abilities[3] = 0; // banana peels can't see
abilities[4] = 0; // banana peels can't think
}
public Move move(char[][] fields){
return Move.STAY; // banana peels can't move
}
public boolean wantToFight(int[] enemyAbilities){
return enemyAbilities[0] == 0 || enemyAbilities[1] == 0;
}
}
```
[Answer]
**Van Pelt**
The hunter from Jumanji. He hunts when he's not hurt, avoids when he is and is a decent judge of what he can kill. Banana peels kept tripping him up, but taught him some new tricks.
```
package alien;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import planet.Move;
public class VanPelt extends Alien {
private static final int LIFE = 0;
private static final int STRENGTH = 1;
private static final int DEFENSE = 2;
private static final int VISION = 3;
private static final int CLEVER = 4;
// we all agreed before starting to move a certain direction if we're not
// hunting or avoiding, helps avoid self-collisions... since we can't tell
// who we're fighting
private static Move randomMove = Move.getRandom();
@Override
public void setAbilityPoints(float[] abilities) {
abilities[LIFE] = 3.5f;
abilities[STRENGTH] = 6f;
abilities[VISION] = 0.5f;
}
@Override
public Move move(char[][] fields) {
int curHealth = this.getCurrentHp();
List<Target> targets = new LinkedList<Target>();
int vision = getVisionFieldsCount();
boolean foundMe = false;
for (int x = 0; x < fields.length; x++) {
for (int y = 0; y < fields[x].length; y++) {
switch (fields[x][y]) {
case ' ' :
continue;
case 'A' :
if (!foundMe && x == vision && y == vision) {
foundMe = true;
continue;
}
break;
}
targets.add(new Target(-vision + x, -vision + y, fields[x][y]));
}
}
// if we're low health we need to move away from danger
double desiredX = 0;
double desiredY = 0;
if (curHealth < this.getLifeLvl() * 7) {
for (Target t : targets) {
if (t.id == 'A') {
// closer aliens are more dangerous
desiredX -= vision / t.x;
desiredY -= vision / t.y;
}
}
} else {
// seek and destroy closest prey
Collections.sort(targets);
for (Target t : targets) {
if (t.id != 'A') {
desiredX = t.x;
desiredY = t.y;
break;
}
}
}
desiredX = (int)Math.signum(desiredX);
desiredY = (int)Math.signum(desiredY);
for (Move m : Move.values()) {
if (m.getXOffset() == desiredX && m.getYOffset() == desiredY) {
return m;
}
}
return randomMove;
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
// we don't want to fight if we're hurt
int curHealth = this.getCurrentHp();
if (curHealth < this.getLifeLvl() * 4) {
return false;
}
// determine if we're fighting prey
int count = 0;
int abilityMaxed = 0;
int total = 0;
for (int i = 0; i < enemyAbilities.length; i++) {
total += enemyAbilities[i];
if (enemyAbilities[i] == 11) {
count++;
abilityMaxed = i;
}
}
// very likely to be prey, ignoring cows... they're dangerous
if (abilityMaxed != STRENGTH && (count == 1 || total < 10)) {
return true;
}
// else use a scoring system with tinkered constants
double score = enemyAbilities[LIFE] * 4.0
+ enemyAbilities[DEFENSE] * 0.5
+ enemyAbilities[STRENGTH] * 5.0;
double myScore = this.getDefenseLvl() * 0.5 +
this.getStrengthLvl() * 5.0 +
this.getCurrentHp() * 2.5;
return myScore > score * 2;
}
private class Target implements Comparable<Target> {
public int x, y;
public char id;
public int distanceSq;
public Target(int x, int y, char id) {
// adjust for known movement patterns
switch(id) {
case 'T' :
x += Move.SOUTHWEST.getXOffset();
y += Move.SOUTHWEST.getYOffset();
break;
case 'H' :
x += Move.NORTHEAST.getXOffset();
y += Move.NORTHEAST.getYOffset();
break;
}
this.x = x;
this.y = y;
this.id = id;
distanceSq = x * x + y * y;
}
@Override
public int compareTo(Target other) {
return distanceSq - other.distanceSq;
}
}
}
```
[Answer]
# Okinawa Life
No wonder I'll be the last one standing.
```
package alien;
import planet.Move;
public class OkinawaLife extends Alien{
public void setAbilityPoints(float[] abilities){
abilities[0] = 8.5f;
abilities[1] = 0.5f;
abilities[3] = 1;
}
public Move move(char[][] fields){
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
switch(fields[fieldX][fieldY]) {
case 'A': danger++;
case ' ': break;
case 'C': break;
case 'E': break;
case 'H': break;
default: danger--;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities){
return enemyAbilities[1] == 0;
}
}
```
[Answer]
**Hunter**
I also just kinda stole the eagle's movement, except now he wants to go towards everything besides other aliens. Tries to hunt down and farm as much prey as possible, and fights only when it seems like it has a good chance to win.
```
package alien;
import planet.Move;
public class Hunter extends Alien {
private final static byte LIFE=0, STR=1, DEF=2, VIS=3, CLV=4;
public void setAbilityPoints(float[] abilities) {
abilities[LIFE] = 0;
abilities[STR] = 9;
abilities[DEF] = 0;
abilities[VIS] = 1;
abilities[CLV] = 0;
}
public Move move(char[][] fields) {
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
switch(fields[fieldX][fieldY]) {
case 'A': danger++;
case ' ': break;
default: danger--;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
return ((double)this.getCurrentHp() * this.getDefenseLvl()) / (double)enemyAbilities[STR] > (enemyAbilities[LIFE] * enemyAbilities[DEF]) / this.getStrengthLvl();
}
}
```
[Answer]
# It's over 9000!
```
package alien;
import planet.Move;
public class Over9000 extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 10;
}
public Move move(char[][] fields) {
return Move.WEST;
}
public boolean wantToFight(int[] enemyAbilities) {
return enemyAbilities[1] <= 9000;
}
@Override
public int getStrengthLvl() {
return 9001; // It's over 9000!!!!!!111
}
}
```
Yes, it's a blatant attempt at cheating, but it does squeak through the rules. If the getters in `planet.Specie` were made final, this loophole would close.
[Answer]
# Rock
I think it only attacks weak and "clever" people.
```
package alien;
import planet.Move;
public class Rock extends Alien{
public void setAbilityPoints(float[] abilities){
abilities[0] = 0.5f;
abilities[1] = 9.5f;
}
public Move move(char[][] fields){
return Move.STAY;
}
public boolean wantToFight(int[] enemyAbilities){
return enemyAbilities[0] + enemyAbilities[1] + enemyAbilities[2] + enemyAbilities[3] < 10;
}
}
```
[Answer]
## Morphling
Couldn't think of any other name, this guy randomly distributes 10 points to his abilities. Almost moves like Okinawa Life(thx for your effort) and only wants to fight if his strength is greater than enemy's strength.
```
package alien;
import planet.Move;
import java.util.Random;
public class Morphling extends Alien {
@Override
public void setAbilityPoints(float[] abilities) {
Random rand = new Random();
for(int attr = 0, maxPoints = 10, value = rand.nextInt(maxPoints); attr <5 && maxPoints > 0 ; attr++, maxPoints -=value, value = rand.nextInt(maxPoints)){
abilities[attr] = value;
if(attr == 4 && (maxPoints-=value) > 0){
abilities[1]+=maxPoints;
}
}
}
@Override
public Move move(char[][] fields) {
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
switch(fields[fieldX][fieldY]) {
case 'A': danger++;
case ' ': break;
case 'T': break;
case 'E': break;
case 'H': break;
default: danger--;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
}
return bestMove;
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
return getStrengthLvl() > enemyAbilities[1];
}
}
```
[Answer]
## Bender "Bending" Rodriguez
I was pretty liberal with code comments. You can read them in context to see what is going on, but I'll also add some snippets below.
### Summary
>
> This alien operates on the principle that killing puny Humans is easy and inflates your perceived strength, which will intimidate other aliens into steering clear.
>
>
> Whales and Eagles are also bendable. =)
>
>
>
The original impetus behind Bender was a misunderstanding of the game shape. Namely: I thought it was a cylinder where easy-prey Humans would get trapped at the north end. Bender was going to beeline the north map edge and travel west, gobbling up the Humans. The world turns out to be a torus, so the modified version you see here attempts to intercept Humans in their north-easterly migration instead.
### Movement
>
> Move either west or south unless you have found something interesting to attack:
>
>
> * For the prey whose movement is known, we add their desirability to the square at which they will be next turn.
> * For those we do not, we divide their desirability equally among the squares that they may move to next turn.
> + Aliens get a bonus negative to their existing square because of banana peels.
>
>
>
If you don't find anything interesting nearby, get a sense of whether south, west, or southwest is a more promising option.
Picking one or two prevailing directions lessens the chance that any given Bender will come across any of his compatriots, and picking a direction counter to his main prey should help him kill all humans faster.
I could probably tweak the numbers in the desirability matrix with [James\_pic's genetic algorithm](https://codegolf.stackexchange.com/a/32889/26867) for even better outcomes, but I don't know how to do that.
### Aggressiveness
Bender mostly targets prey, and is pretty conservative with his `wantToFight`. Anyone over Strength 4 is shunned *unless* you think you're dealing with a clever human. Clever humanity is demonstrated by having more Defense and Vision than an alien is likely to have. It's adjusted over the course of an instance by Bender's own ability stats, to account for aliens killing turtles and eagles.
```
package alien;
import planet.Move;
import java.util.HashMap;
/// The Bender "Kill All Humans" Alien
///
/// This alien operates on the principle that killing puny
/// Humans is easy and inflates your perceived strength,
/// which will intimidate other aliens into steering clear.
///
/// Whales and Eagles are also bendable. =)
public class Bender extends Alien {
private static final boolean DEBUG = false;
private final int LIF = 0, STR = 1, DEF = 2, VIS = 3, CLV = 4;
protected static HashMap<Character, Integer> preyDesirability = new HashMap<Character, Integer>() {{
put('A', -5);
put('W', 5);
put('C', 0); // Originally -2, but Cows don't attack
put('T', 2);
put('E', 3);
put('H', 4);
}};
private static final int bananaTweak = -2;
private static final HashMap<Character, Move> preyMovement = new HashMap<Character, Move>() {{
put('W', Move.STAY);
put('T', Move.SOUTHWEST);
put('H', Move.NORTHEAST);
}};
public void setAbilityPoints(float[] abilities) {
abilities[LIF] = 3.5f; // Shiny metal ass
abilities[STR] = 5.5f; // Bending strength
abilities[DEF] = 0;
abilities[VIS] = 1; // Binocular eyes
abilities[CLV] = 0;
}
/// Looks for humans to intercept!
///
/// Generally speaking, move either west or south
/// unless you have found something interesting to
/// attack:
/// - For the prey whose movement is known, we add
/// their desirability to the index at which they
/// will be next turn.
/// - For those we do not, we divide their desirability
/// equally among the squares that they may move to
/// next turn. Aliens get a bonus negative to their
/// existing square because of banana peels.
public Move move(char[][] fields) {
int vision = getVisionFieldsCount();
// I am at fields[vision][vision]
if (DEBUG) {
System.out.format("\n----- %s -----\n", this);
}
float[][] scoringMap = new float[fields.length][fields.length];
for (int y = 0; y < fields.length; y++) {
for (int x = 0; x < fields.length; x++) {
// Ignore my square and blanks
if (x == vision && y == vision ||
fields[x][y] == ' ') {
continue;
}
// Check out the prey 8^]
char organism = fields[x][y];
float desirability = preyDesirability.get(organism);
// If we know where it's going, score tiles accordingly...
if (preyMovement.containsKey(organism)) {
Move preyMove = preyMovement.get(organism);
if (DEBUG) {
System.out.println(String.format("Prey %s will move %s", organism, preyMove));
}
int newPreyX = x + preyMove.getXOffset();
int newPreyY = y + preyMove.getYOffset();
try {
scoringMap[newPreyX][newPreyY] += desirability;
if (DEBUG) {
System.out.println(String.format(
"Adding %.1f to %d, %d",
desirability,
newPreyX,
newPreyY));
}
}
catch(Exception e) {
if (DEBUG) {
System.out.println(String.format(
"Failed adding %.1f to %d, %d",
desirability,
newPreyX,
newPreyY));
}
}
}
// ...otherwise, divide its score between its
// available moves...
else {
for (int j = y - 1; j <= y + 1; j++) {
for (int i = x - 1; i <= x + 1; i++) {
try {
scoringMap[i][j] += desirability / 9.;
}
catch (Exception e) {
if (DEBUG) {
//System.out.println(e);
}
}
}
}
}
// ...and if it is an alien, add a handicap
// for bananas and rocks.
if (organism == 'A') {
scoringMap[x][y] += bananaTweak;
}
}
}
// Evaluate immediate surroundings 8^|
//
// +-----------+
// | |
// | # # # |
// | # B # |
// | # # # |
// | |
// +-----------+
float bestScore = -10;
int[] bestXY = new int[2];
for (int y = vision - 1; y <= vision + 1; y++) {
for (int x = vision - 1; x <= vision + 1; x++) {
if (DEBUG) {
System.out.format("\nx:%d, y:%d", x, y);
}
// Look for the best score, but if scores
// are tied, try for most southwest high score
if (scoringMap[x][y] > bestScore ||
scoringMap[x][y] == bestScore && (
x <= bestXY[0] && y > bestXY[1] ||
y >= bestXY[1] && x < bestXY[0])
) {
bestScore = scoringMap[x][y];
bestXY[0] = x;
bestXY[1] = y;
if (DEBUG) {
System.out.format("\nBest score of %.1f found at %d, %d", bestScore, x, y);
}
}
}
}
if (DEBUG) {
StringBuilder sb = new StringBuilder();
sb.append("\n-----\n");
for (int y = 0; y < fields.length; y++) {
for (int x = 0; x < fields.length; x++) {
sb.append(String.format("%5s", fields[x][y]));
}
sb.append("\n");
}
for (int y = 0; y < scoringMap.length; y++) {
for (int x = 0; x < scoringMap.length; x++) {
sb.append(String.format("%5.1f", scoringMap[x][y]));
}
sb.append("\n");
}
System.out.println(sb.toString());
}
// If something looks tasty, go for it :^F
if (bestScore > 0.5) {
for (Move m : Move.values()) {
if (m.getXOffset() == bestXY[0] - vision &&
m.getYOffset() == bestXY[1] - vision) {
if (DEBUG) {
System.out.println("Using immediate circumstances.");
System.out.println(m);
}
return m;
}
}
}
// If nothing looks good, do a lookahead to
// the south, west, and southwest to guess
// which is best. 8^[
//
// There is potential in recursively applying our
// vision data with updated score rankings, but
// that would be hard. :P
float westScore = 0, southScore = 0, southWestScore = 0;
for (int y = vision - 1; y < vision + 1; y++) {
for (int x = 0; x < vision; x++) {
// +-----------+
// | |
// | # # # |
// | # # B |
// | # # # |
// | |
// +-----------+
westScore += scoringMap[x][y] / (vision - x);
}
}
for (int y = vision; y < fields.length; y++) {
for (int x = vision - 1; x < vision + 1; x++) {
// +-----------+
// | |
// | |
// | # B # |
// | # # # |
// | # # # |
// +-----------+
southScore += scoringMap[x][y] / (y - vision);
}
}
for (int y = vision; y < fields.length; y++) {
for (int x = 0; x < vision; x++) {
// +-----------+
// | |
// | |
// | # # B |
// | # # # |
// | # # # |
// +-----------+
southWestScore += scoringMap[x][y] / Math.sqrt((y - vision) + (vision - x));
}
}
if (southScore > westScore && southScore > southWestScore) {
if (DEBUG) {
System.out.println(Move.SOUTH);
}
return Move.SOUTH;
}
if (westScore > southScore && westScore > southWestScore) {
if (DEBUG) {
System.out.println(Move.WEST);
}
return Move.WEST;
}
if (DEBUG) {
System.out.println(Move.SOUTHWEST);
}
return Move.SOUTHWEST;
}
public boolean wantToFight(int[] enemyAbilities) {
// Be afraid...
if (enemyAbilities[STR] > 4) {
// ...unless you suspect you are being lied to
if (enemyAbilities[DEF] + enemyAbilities[VIS] > 4 * sumMyAbilities() / 5.) {
// Enemy has more than expected attribute levels of unhelpful
// abilities. Assume you're dealing with a clever bastard.
return true;
}
return false;
}
return true;
}
int sumAbilities(int[] abilities){
int sum = 0;
for (int ability : abilities){
sum += ability;
}
return sum;
}
int sumMyAbilities(){
return sumAbilities(new int[]{
getLifeLvl(),
getStrengthLvl(),
getDefenseLvl(),
getVisionLvl(),
getClevernessLvl()
});
}
}
```
[Answer]
# Warrior
This is a very simple minded alien who just wants to fight. He doesn't care about his enemies nor about his surroundings.
```
public class Warrior extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 5;
abilities[1] = 5;
}
public Move move(char[][] fields) {
return Move.getRandom(); //enemies are everywhere!
}
public boolean wantToFight(int[] enemyAbilities) {
return true; //strong, therefore no stronger enemies.
}
}
```
You now have someone to test your own alien against.
[Answer]
# Coward
I basically stole the Eagle's movement pattern to avoid danger and stacked defense in case I am attacked.
```
public class Coward extends Alien{
public void setAbilityPoints(float[] abilities){
abilities[0] = 1; // life
abilities[1] = 0; // str
abilities[2] = 2; // def
abilities[3] = 7; // vis
abilities[4] = 0; // clv
}
// shamelessly stole Eagle's movement to avoid danger
public Move move(char[][] fields){
int vision = getVisionFieldsCount();
char me = fields[vision][vision];
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) {
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
if (fields[fieldX][fieldY] != ' ') {
danger++;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities){
return false;
}
}
```
[Answer]
# Fleer
PANIC
APOCALYPSE
RUUUUUUUUUUN
AAAAAAAAAAAAAAAAAAAAAAA
---
Avoids battles whenever possible.
```
package alien; import planet.Move;
public class Fleer extends Alien
{
public void setAbilityPoints(float[] abilities) {
abilities[0] = 1; //life
abilities[1] = 0; //strength
abilities[2] = 4; //defense
abilities[3] = 4; //vision
abilities[4] = 1; //cleverness
}
public Move move(char[][]fields) {
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
ArrayList<Integer> dangerOnSides = new ArrayList<Integer>();
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
if (fields[fieldX][fieldY] != ' ') {
danger++;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
dangerOnSides.add(danger);
}
boolean noDanger = false;
for (int i : dangerOnSides) {
if (i == 0) {
noDanger = true;
}
else { noDanger = false; break; }
}
if (noDanger) {
// Hahhhhhhhh.......
return Move.STAY;
}
int prev = -1;
boolean same = false;
for (int i : dangerOnSides) {
if (prev == -1)
{ prev = i; continue; }
if (i == prev) {
same = true;
}
else { same = false; break; }
prev = i;
}
if (same) {
// PANIC
return Move.getRandom();
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
return false;
}
}
```
[Answer]
# Predicoward (purr)
A breed of Predicats that have lived (so far) on fear and staying away from trouble. Due to their lifestyle, they have not developed fighting instincts, but their perception is exceptional.
Their kind is loathed by their fellow Predicats.
EDIT : Changed Manhattan Distance to Weighted Distance instead
```
package alien;
import planet.Move;
import java.util.ArrayList;
import java.awt.Point;
/* Predict + Cat = Predicat! */
public class Predicoward extends Alien {
/*
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - P - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
Risk score = sum of weighted distances of all aliens within vision range
*/
@Override
public void setAbilityPoints( float[] abilities ) {
abilities[3] = 10;
}
@Override
public Move move( char[][] fields ) {
/* Some credits to Eagle for letting me learn how to do the moves */
int vision = getVisionFieldsCount(); //count of fields / middle
Move bestMove=Move.STAY;
int bestRiskScore=10000;
int riskScore=0;
ArrayList<Point> aliens = new ArrayList<Point>();
//generate alien list
for (int x=0; x<=vision*2; x++) {
for(int y=0; y<=vision*2; y++){
if(x==vision && y==vision) continue;
if(fields[x][y]=='A'){
aliens.add(new Point(x,y));
}
}
}
for (Move move : Move.values()) {
int x = vision + move.getXOffset();
int y = vision + move.getYOffset();
riskScore = 0;
for(Point alienCoord : aliens){
riskScore += this.getDistance(x, y, alienCoord);
}
if(riskScore < bestRiskScore){
bestRiskScore = riskScore;
bestMove = move;
}
}
return bestMove;
}
@Override
public boolean wantToFight( int[] enemyAbilities ) {
//I don't want to fight :(
return false;
}
//Return weighted distance (more weight for near opponents)
private int getDistance(int x, int y, Point to){
int xDist = Math.abs(x-(int)to.getX());
int yDist = Math.abs(y-(int)to.getY());
int numberOfMovesAway = Math.max(xDist, yDist);
if(numberOfMovesAway==0){
return 1000;
}
else if(numberOfMovesAway==1){
return 100;
}
else if(numberOfMovesAway==2){
return 25;
}
else{
return 6-numberOfMovesAway;
}
}
}
```
[Answer]
# PredicatEyes (meow)
A breed of Predicats that have sharper vision than its counterparts which allows it to pry on its enemies well.
EDIT : New target priorities
```
package alien;
import planet.Move;
/* Predict + Cat = Predicat! */
public class PredicatEyes extends Alien {
private static final int LIF=0, STR=1, DEF=2, VIS=3;
private static final int WHALE=6, COW=1, TURTLE=4, EAGLE=3, HUMAN=2, ALIEN=-1, NONE=0;
@Override
public void setAbilityPoints( float[] abilities ) {
abilities[LIF] = 4.5f;
abilities[STR] = 4.5f;
abilities[VIS] = 1;
}
@Override
public Move move( char[][] fields ) {
/* Some credits to Eagle for letting me learn how to do the moves */
int vision = getVisionFieldsCount(); //count of fields / middle
int fieldX;
int fieldY;
Move bestMove=Move.STAY;
int bestScore=-1;
for (Move move : Move.values()) {
fieldX = vision + move.getXOffset();
fieldY = vision + move.getYOffset();
switch(fields[fieldX][fieldY]){
case 'W' :
return move;
case 'C' :
if(bestScore<COW){
bestMove=move;
bestScore=COW;
}
break;
case 'T' :
if(bestScore<TURTLE){
bestMove=move;
bestScore=TURTLE;
}
break;
case 'E' :
if(bestScore<EAGLE){
bestMove=move;
bestScore=EAGLE;
}
break;
case 'H' :
if(bestScore<HUMAN){
bestMove=move;
bestScore=HUMAN;
}
break;
case 'A' :
if(bestScore<ALIEN){
bestMove=move;
bestScore=ALIEN;
}
break;
case ' ' :
if(bestScore<NONE){
bestMove=move;
bestScore=NONE;
}
break;
}
}
if(vision==1 && bestScore>1){
return bestMove;
}
//check immediate outer field
for (int i=vision-2; i<=vision+2; i++) {
for(int j=vision-2; j<=vision+2; j++){
if(i==0 || i==4 || j==0 || j==4){
switch(fields[i][j]){
case 'W' :
bestMove = this.getBestMoveTo(i,j);
bestScore = WHALE;
break;
case 'C' :
if(bestScore<COW){
bestMove = this.getBestMoveTo(i,j);
bestScore = COW;
}
break;
case 'T' :
if(i>=vision && j<=vision){
return this.getBestMoveTo(i-1,j+1);
}
if(bestScore<TURTLE){
bestMove = this.getBestMoveTo(i,j);
bestScore = TURTLE;
}
break;
case 'E' :
if(bestScore<EAGLE){
bestMove = this.getBestMoveTo(i,j);
bestScore = EAGLE;
}
break;
case 'H' :
if(i<=vision && j>=vision){
return this.getBestMoveTo(i+1,j-1);
}
if(bestScore<HUMAN){
bestMove = this.getBestMoveTo(i,j);
bestScore = HUMAN;
}
break;
case 'A' :
if(bestScore<ALIEN){
bestMove = this.getBestMoveTo(i,j);
bestScore = ALIEN;
}
break;
case ' ' :
if(bestScore<NONE){
bestMove = this.getBestMoveTo(i,j);
bestScore = NONE;
}
break;
}
}
}
}
return bestMove;
}
@Override
public boolean wantToFight( int[] enemyAbilities ) {
/*
Fight IF
1) I CAN BEAT YOU
2) ????
3) MEOW!
*/
float e_hp = enemyAbilities[LIF]*5+10;
float e_dmg = 1 + enemyAbilities[STR]/2;
float e_hit = 1 - (1/(50/this.getDefenseLvl()+1));
float m_hp = this.getCurrentHp();
float m_dmg = 1 + this.getStrengthLvl()/2;
float m_hit = 1 - (1/(50/enemyAbilities[DEF]+1));
return (e_hp/(m_dmg*m_hit) < m_hp/(e_dmg*e_hit));
}
private Move getBestMoveTo(int visionX, int visionY){
int vision = getVisionFieldsCount();
if(visionX < vision && visionY < vision){
return Move.NORTHWEST;
}
else if(visionX > vision && visionY < vision){
return Move.NORTHEAST;
}
else if(visionX < vision && visionY > vision){
return Move.SOUTHWEST;
}
else if(visionX > vision && visionY < vision){
return Move.SOUTHEAST;
}
else if(visionX == vision && visionY < vision){
return Move.NORTH;
}
else if(visionX == vision && visionY > vision){
return Move.SOUTH;
}
else if(visionX > vision && visionY == vision){
return Move.EAST;
}
else if(visionX < vision && visionY == vision){
return Move.WEST;
}
else{
return Move.getRandom();
}
}
}
```
[Answer]
## Crop Circle Alien
Circles clockwise indefinitely, and never wants to fight, he is happy making crop cirles. However, if you really want to fight, he'll beat the crap out of you.
```
package alien;
import planet.Move;
public class CropCircleAlien extends Alien {
private int i = 0;
@Override
public void setAbilityPoints(float[] abilities) {
abilities[0] = 3; // life
abilities[1] = 7; // strength
abilities[2] = 0; // defense
abilities[3] = 0; // vision
abilities[4] = 0; // cleverness
}
@Override
public Move move(char[][] fields) {
switch (getI()) {
case 0:
setI(getI() + 1);
return Move.EAST;
case 1:
setI(getI() + 1);
return Move.SOUTHEAST;
case 2:
setI(getI() + 1);
return Move.SOUTH;
case 3:
setI(getI() + 1);
return Move.SOUTHWEST;
case 4:
setI(getI() + 1);
return Move.WEST;
case 5:
setI(getI() + 1);
return Move.NORTHWEST;
case 6:
setI(getI() + 1);
return Move.NORTH;
case 7:
setI(getI() + 1);
return Move.NORTHEAST;
default:
return Move.STAY;
}
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
return false;
}
public void setI(int i) {
if (i < 8) {
this.i = i;
} else {
this.i = 0;
}
}
public int getI() {
return this.i;
}
}
```
[Answer]
**CleverAlien**
Clever alien relies solely on his wits. He randomly walks around, and randomly decides to fight. He hopes he is able to outsmart his enemies with luck. ( forgive me if i have any syntax errors, im not a java guy)
```
package alien;
import planet.Move;
public class CleverAlien extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 1; //life
abilities[1] = 0; //strength
abilities[2] = 0; //defense
abilities[3] = 0; //vision
abilities[4] = 9; //cleverness
}
public Move move(char[][] fields) {
//you are in the middle of the fields, say fields[getVisionFieldsCount()][getVisionFieldsCount()]
return Move.getRandom();
}
public boolean wantToFight(int[] enemyAbilities) {
//same order of array as in setAbilityPoints, but without cleverness
int tmp = (int) ( Math.random() * 2 + 1);
return tmp == 1;
}
}
```
[Answer]
# Rogue
Like other's have said, I am using the Eagle's movement to some degree. Rather than try to make a winning alien (My best ideas were already taken D:), I decided to make an alien with some character! My alien is a hired gun oblivious to the alien war, and is only on this planet to hunt the filthy human who has skipped out on his death stick debt. My alien will search the planet for the human, and continue to trail behind the human without killing him. Once an alien is seen near him, he will then try to quickly kill the human, and face off against this new foe with "luck on his side" from his completed task.
```
package alien;
import planet.Move;
public class Rogue extends Alien {
private int threatPresent = 0;
private int turnNorth = 0;
public void setAbilityPoints(float[] abilities) {
abilities[0] = 3;
abilities[1] = 6;
abilities[2] = 0;
abilities[3] = 1;
abilities[4] = 0;
}
public Move move(char[][] fields) {
int vision = getVisionFieldsCount();
char me = fields[vision][vision];
int humanPresent = 0;
//This way, if there is no alien near, the current threat will not trigger attacking
int isThereCurrThreat = 0;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
for (int i = 1; i <= vision; i++) {
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
if (fields[fieldX][fieldY] == 'A') {
isThereCurrThreat = 1;
}
if (fields[fieldX][fieldY] == 'T') {
humanPresent = 1;
//Turtles are basically dumb humans, right?
}
if (fields[fieldX][fieldY] == 'H') {
humanPresent = 1;
}
}
//Alway follow that filthy human
if (humanPresent == 1) {
bestMove = move;
}
}
if(humanPresent == 0) {
//Alternate moving north and east towards the human
//If I hit the edge of world, I search for the turtle as well
if(turnNorth == 1) {
bestMove = Move.NORTH;
turnNorth = 0;
}
else {
bestMove = Move.EAST;
turnNorth = 1;
}
}
//If a threat was found, attack accordingly.
threatPresent = isThereCurrThreat;
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
//Only fight if another enemey is near
if (threatPresent == 1) {
return true;
}
else {
return false;
}
}
}
```
The code is centered around the idea that I should sprint towards the human. Once I beat him, I then wrap around to the southwest, where I will look for the turtle.
**EDIT :** Oh, and about the turtle thing...my alien doesn't like them, so it's totally canon you guys.
[Answer]
Crash landed and just trying to survive. Survives mostly by it's agility and intelligence and counts every scar, considering carefully if it's worth it to start a fight or not. The survivor starts off just hunting and trying to avoid all those other aliens with their big weapons but as it gets more bold may start to go after them. When it really gets going it won't care who it's facing anymore.
```
package alien;
import planet.Move;
public class Survivor extends Alien {
private int boldness = 0;
private float life = 0;
private float str = 1;
private float def = 4;
private float clever = 10 - life - str - def;
public void setAbilityPoints(float[] abilities) {
abilities[0] = life; //life
abilities[1] = str; //strength
abilities[2] = def; //defense
abilities[3] = 0; //vision
abilities[4] = clever; //cleverness
}
public Move move(char[][] fields) {
//you are in the middle of the fields, say fields[getVisionFieldsCount()][getVisionFieldsCount()]
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
int leastDanger = Integer.MAX_VALUE;
Move bestMove = Move.STAY;
for (Move move : Move.values()) {
int danger = 0;
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
switch(fields[fieldX][fieldY]) {
case 'A':
if(boldness < 10)
danger++;
else
danger--;
break;
case ' ':
break;
default:
danger-=2;
}
}
if (danger < leastDanger) {
bestMove = move;
leastDanger = danger;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
//same order of array as in setAbilityPoints, but without cleverness
bool fight = boldness < 50;//After 50 fights, believes self unstoppable
int huntable = 0;
for(int ability : enemyAbilities){
if(ability == 1)
huntable++;
}
if(huntable >= 3){
fight = true;
}//if at least 3 of the visible stats are 1 then consider this prey and attack
else if((float)enemyAbilities[1] / (float)getDefenseLvl() <= (float)getStrengthLvl() + (float)(getClevernessLvl() % 10) / (float)enemyAbilities[2] && enemyAbilities[0] / 5 < getLifeLvl() / 5)
fight = true;//If I fancy my odds of coming out on top, float division for chance
if(fight){//Count every scar
boldness++;//get more bold with every battle
life += enemyAbilities[0] / 5;
str += enemyAbilities[1] / 5;
def += enemyAbilities[2] / 5;
clever += (10 - (enemyAbilities[0] + enemyAbilities[1] + enemyAbilities[2] + enemyAbilities[3] - 4)) / 5;//count the human cleverness attained or the enemies who buffed clever early
}
return fight;
}
}
```
[Answer]
# FunkyBob
First priority is survival, otherwise will try to find some prey. Assesses the visible area to find the general direction with the least threats or most prey. Seems to have about an 85-90% survival rate during my testing.
```
package alien;
import planet.Move;
public class FunkyBob extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 2.5f;
abilities[1] = 5.5f;
abilities[3] = 2;
}
private int QtyInRange(char[][] fields, int x, int y, int numStepsOut, char specie)
{
int count = 0;
for(int i = numStepsOut * -1; i <= numStepsOut; i++)
for(int j = numStepsOut * -1; j <= numStepsOut; j++)
if(fields[x+i][y+j] == specie)
count++;
return count;
}
private int AssessSquare(char[][] fields, int x, int y, int visibility){
int score = 0;
for(int i = 0; i <= visibility; i++)
{
score += (-1000 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'A');
score += (100 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'T');
score += (100 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'H');
score += (100 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'E');
score += (50 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'W');
score += (50 / (i == 0 ? 0.3 : i)) * QtyInRange(fields, x, y, i, 'C');
}
return score;
}
public Move move(char[][] fields) {
int vision = getVisionFieldsCount();
Move bestMove = Move.STAY;
int bestMoveScore = AssessSquare(fields, vision, vision, vision - 1);
for (Move move : Move.values()) {
int squareScore = AssessSquare(fields, vision + move.getXOffset(), vision + move.getYOffset(), vision - 1);
if(squareScore > bestMoveScore)
{
bestMoveScore = squareScore;
bestMove = move;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
return ((getCurrentHp() + this.getStrengthLvl()) / 2) >
((enemyAbilities[0] * 3) + enemyAbilities[1]);
}
}
```
[Answer]
# FunkyJack
Just for kicks, here's another entry with a slightly different approach. This one is only focused on avoiding fights. This isn't really a viable strategy due to being surrounded by enemies in the first couple of rounds. 40% of squares are occupied in the first round so on average you will be immediately adjacent to 3-4 enemies. But when increasing the initial empty squares to 12.5 times the species rather than 2.5 times the species it gets an average survival rate of 98.5%.
```
package alien;
import planet.Move;
public class FunkyJack extends Alien {
public void setAbilityPoints(float[] abilities) {
abilities[0] = 4.5f;
abilities[1] = 1.5f;
abilities[3] = 4;
}
private int QtyInRange(char[][] fields, int x, int y, int numStepsOut, char specie)
{
int count = 0;
for(int i = numStepsOut * -1; i <= numStepsOut; i++)
for(int j = numStepsOut * -1; j <= numStepsOut; j++)
if(fields[x+i][y+j] == specie)
count++;
return count;
}
private int AssessSquare(char[][] fields, int x, int y, int visibility, int prevScore){
int score = 0;
score += -10000 * QtyInRange(fields, x, y, visibility, 'A');
if(visibility > 0)
score = AssessSquare(fields, x, y, visibility - 1, ((score + prevScore) / 5));
else
score += prevScore;
return score;
}
public Move move(char[][] fields) {
int vision = getVisionFieldsCount();
Move bestMove = Move.STAY;
int bestMoveScore = AssessSquare(fields, vision, vision, vision - 1, 0);
for (Move move : Move.values()) {
int squareScore = AssessSquare(fields, vision + move.getXOffset(), vision + move.getYOffset(), vision - 1, 0);
if(squareScore > bestMoveScore)
{
bestMoveScore = squareScore;
bestMove = move;
}
}
return bestMove;
}
public boolean wantToFight(int[] enemyAbilities) {
return false;
}
}
```
[Answer]
**LazyBee**
I started trying to make a clever Bee class that used pattern movements and deductive reasoning, but then I got sleepy, so I renamed it LazyBee and called it a night. He actually seems to perform pretty well on my tests (average of ~1645 with aliens on the github).
```
package alien;
import planet.Move;
public class LazyBee extends Alien{
private static final int LIFE = 0;
private static final int STRENGTH = 1;
// Ran trials to figure out what stats were doing best in sims
// Lazily assumed that:
// - Defense is negligeble compared to health
// - Vision doesn't matter if I'm running east all the time
// - Cleverness will be canceled out because dumb aliens (yum) won't care
// and smart aliens probably account for it somehow
public static float DARWINISM = 4.5f;
public void setAbilityPoints(float[] abilities){
abilities[LIFE] = DARWINISM;
abilities[STRENGTH] = 10f-DARWINISM;
}
// If bananapeel is fine without trying to move cleverly, I probably am too
public Move move(char[][] fields)
{
return Move.EAST; // This was giving me the best score of all arbitrary moves, for some reason
}
// inspired by ChooseYourBattles, tried to do some math, not sure if it worked
// it seemed that Bee was doing better by being more selective
// not accounting for cleverness because eh
public boolean wantToFight(int[] enemyAbilities){
// chance of hit (h) = (1-(1/((50/deflvl)+1)))) = 50/(deflvl+50)
double my_h = 50.0/(this.getDefenseLvl() + 50),
their_h = (50.0 - enemyAbilities[STRENGTH])/50.0;
// expected damage (d) = h * (strlvl+1)
double my_d = /* long and thick */ my_h * (this.getStrengthLvl() + 1),
their_d = their_h * (enemyAbilities[STRENGTH]);
// turns to die (t) = currhp / d
double my_t = (this.getCurrentHp() / their_d),
their_t = ((enemyAbilities[LIFE] * 5 + 10) / my_d); // Assume they're at full health because eh
// worth it (w) = i outlast them by a decent number of turns
// = my_t - their_t > threshold
// threshold = 4.5
boolean w = my_t - their_t > 4.5;
return w;
}
}
```
[Answer]
# NewGuy
Tries to engage "easy" targets for early farming. Otherwise, just move sporadically.
```
package alien;
import planet.Move;
public class NewGuy extends Alien {
private final static byte LIFE=0, STR=1, DEF=2, VIS=3, CLV=4;
public void setAbilityPoints(float[] abilities) {
abilities[LIFE] = 5;
abilities[STR] = 5;
}
public Move move(char[][] fields) {
// Very rudimentary movement pattern. Tries to engage all "easy" peaceful aliens.
// Programmer got lazy, so he doesn't run away from danger, decreasing his odds of survival.
// Afterall, if his species dies, that's one fewer specie that humans have to contend with.
int vision = getVisionFieldsCount(); //count of fields / middle
char me = fields[vision][vision]; //middle of fields
for (Move move : Move.values()) {
for (int i = 1; i <= vision; i++) { //loop through fields in specific direction
int fieldX = vision + (i * move.getXOffset());
int fieldY = vision + (i * move.getYOffset());
char alienType = fields[fieldX][fieldY];
if (alienType == 'E' || alienType == 'H' || alienType == 'T' || alienType == 'W') {
return move;
}
}
}
return Move.getRandom();
}
public boolean wantToFight(int[] enemyAbilities) {
if (isWhale(enemyAbilities)) {
return true;
} else if (isCow(enemyAbilities)) {
return false; // Cows hit hard!
} else if (isTurtle(enemyAbilities)) {
return true;
} else if (isEagle(enemyAbilities)) {
return true;
} else if (isHuman(enemyAbilities)) {
if (enemyAbilities[STR] < 3) {
return true;
}
}
return false;
}
public boolean isWhale(int[] enemyAbilities) {
return enemyAbilities[LIFE] == 10 && totalAbilityPoints(enemyAbilities) == 10;
}
public boolean isCow(int[] enemyAbilities) {
return enemyAbilities[STR] == 10 && totalAbilityPoints(enemyAbilities) == 10;
}
public boolean isTurtle(int[] enemyAbilities) {
return enemyAbilities[DEF] == 10 && totalAbilityPoints(enemyAbilities) == 10;
}
public boolean isEagle(int[] enemyAbilities) {
return enemyAbilities[VIS] == 10 && totalAbilityPoints(enemyAbilities) == 10;
}
public boolean isHuman(int[] enemyAbilities) {
return !(isWhale(enemyAbilities) || isCow(enemyAbilities) || isTurtle(enemyAbilities)) && totalAbilityPoints(enemyAbilities) >= 10;
}
public int totalAbilityPoints(int[] enemyAbilities) {
return enemyAbilities[LIFE] + enemyAbilities[STR] + enemyAbilities[DEF] + enemyAbilities[VIS];
}
}
```
[Answer]
# Guard
Stack life, buff strength & defense, then stay put. Only attack if the opponent seems to be aggressive (defined as `strength` being greater than 2):
```
public class Guard extends Alien{
public void setAbilityPoints(float[] abilities){
abilities[0] = 6; // life
abilities[1] = 2; // str
abilities[2] = 2; // def
abilities[3] = 0; // vis
abilities[4] = 0; // clv
}
public Move move(char[][] fields){
return Move.STAY;
}
public boolean wantToFight(int[] enemyAbilities){
return enemyAbilities[1] >= 3;
}
}
```
[Answer]
## Bully Alien
Bully Alien will walk around ignoring enemies until he finds someone weak to mess with.
```
package alien;
import planet.Move;
public class BullyAlien extends Alien {
@Override
public void setAbilityPoints(float[] abilities) {
abilities[0] = 2;
abilities[1] = 8;
abilities[2] = 0;
abilities[3] = 0;
abilities[4] = 0;
}
@Override
public Move move(char[][] fields) {
return Move.getRandom();
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
return enemyAbilities[1] < 3;
}
}
```
[Answer]
**BlindBully**
Doesn't care who or what is around it, just tries to decide if the alien it is facing right now is stronger or weaker than itself, and attacks those weaker.
```
package alien;
import planet.Move;
import java.util.Random;
public class BlindBully extends Alien {
private final int LIFE = 0;
private final int STRENGTH = 1;
private final int DEFENSE = 2;
private final int VISION = 3;
private final int CLEVERNESS = 4;
private Random rand = new Random();
@Override
public void setAbilityPoints(float[] abilities) {
abilities[LIFE] = 6;
abilities[STRENGTH] = 2;
abilities[DEFENSE] = 2;
abilities[VISION] = 0;
abilities[CLEVERNESS] = 0;
}
@Override
public Move move(char[][] fields) {
// Go west! To meet interesting people, and kill them
switch (rand.nextInt(3)) {
case 0:
return Move.NORTHWEST;
case 1:
return Move.SOUTHWEST;
default:
return Move.WEST;
}
}
@Override
public boolean wantToFight(int[] enemyAbilities) {
int myFightRating = getLifeLvl() + getStrengthLvl() + getDefenseLvl();
int enemyFightRating = enemyAbilities[LIFE] + enemyAbilities[STRENGTH] + enemyAbilities[DEFENSE];
return myFightRating >= enemyFightRating;
}
}
```
[Answer]
## SecretWeapon2
```
package alien;
import planet.Move;
/**
* Created by Vaibhav on 02/07/14.
*/
public class SecretWeapon2 extends Alien {
private final static byte LIFE=0, STR=1, DEF=2, VIS=3, CLV=4;
public void setAbilityPoints(float[] abilities) {
abilities[LIFE] = 3;
abilities[STR] = 7;
abilities[DEF] = 0;
abilities[VIS] = 0;
abilities[CLV] = 0;
}
public Move move(char[][] fields) {
return Move.getRandom();
}
public boolean wantToFight(int[] enemyAbilities) {
return enemyAbilities[1] < 4;
}
}
```
] |
[Question]
[
Your challenge is simple. You need to write a program that prints to either STDOUT or a file the year the language it is written in was released. Because this is such a simple task, the twist is that it must be written in as many different languages as possible.
Your score is the total number of different years that are correctly printed.
For each language you use, you must
* Specify which version of the language you are using. (If there are multiple versions)
* Specify what year that version was first released, and
* Provide a link to a page proving the date of your version/language.
Any one of these counts as release date proof, as long as it specifies the version number (if applicable) and a release date.
* A wikipedia page.
* An [esolangs](http://esolangs.org/wiki/Main_Page) page.
* The language's official website. A github page or similar counts, as long as it has a release date. (Latest commit does not count, unless there is a version number somewhere in the code)
If there are not multiple versions or releases of a language, just use the initial release date of the language.
Minor versions of the same language *do* count as different languages, as long as they come from different years and still produce the correct output. You may *not* use any builtins that give you information (including release date) about the current version of the language you are using. For example, this is an invalid python submission:
```
import platform
i = platform.python_version()
if i == '3.5':
print(2015)
if i == '3.4':
print(2014)
if i == '3.3':
print(2012)
...
```
Whichever submission correctly prints the most distinct years wins!
# Rules
* Each program must print out the language year *and nothing more*. A trailing newline (windows style or \*nix style) is allowed.
* No programs may take any input.
* In case of a tie, the shortest code scored in bytes wins. You may use whatever encoding you like for this, but all programs must use the same encoding.
* Any of the programs may print to STDERR, or throw runtime/compile time errors and warnings *as long as* the correct output is still printed to STDOUT or a file.
* Different languages may use different IO methods, but they most all be full programs, (functions not allowed for this challenge) and follow one of our [default IO methods allowed](http://meta.codegolf.stackexchange.com/q/2447/31716).
Happy ~~golfing~~ polyglotting!
[Answer]
## A Brief History of 2D Programming Languages: 16 (+2) years
```
v19977/2{@{{4{\_______>/02&&&#???? * P+++++1P1P-1P+1E * *
\'\02'oo100@n590@n; * * *
>"8991",,,;5-;,@ * * *
* * * *
\ * ++++++++++++++++++++++++ ++++++++++++++++++++++++ ++O--OO++++++++OX******* *
* #2018O@ * * * * * * *
* * * * * * * *
* * * * * * * *
* **** **** * **** **** * **** **** * **** *****
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * **** * * * * **** * * * * **** * * * * ****
* * * * * * * * * * * * * * * *
R"2014"; ***** ******* ****** ******* ****** ******* ****** *******
x
x%"2010"x
x
$'main' \/\/\/\
\-[2005]o-# \++++++\
/++++++/
\++++++\
/++++++/
\/\/\/\++.--..+++.#
S1^2^2^6^8MAOUOAOOF
/K:0:1:@
> "7102"4&o@
| }+++++[>++++++++++<-]>.--..++++++.@
```
Did I mention that I like 2D programming languages?
### 1993: [Befunge](http://esolangs.org/wiki/Befunge)
The language that (allegedly, see the last section) started it all. In Befunge, you can redirect the control flow with `<v>^`, but the now ubiquitous mirrors `\` and `/` weren't a thing yet. The Befunge interpreter used on [Anarchy Golf](http://golf.shinh.org/check.rb) ignores unknown commands. We can use this to distinguish the Befunge family from the ><> family. Hence, the code executed by Befunge is this:
```
v
\
>"8991",,,;5-;,@
```
The `"8991"` pushes the individual characters onto the stack. `,,,` prints the first three of them. Then `;` is unknown (which we'll use to distinguish it from Befunge 98), `5-` turns the `8` into a `3` and `,` prints that as well before `@` terminates the program.
### 1997: [Wierd](http://esolangs.org/wiki/Wierd)
Writing this part of the solution took me probably as long as writing all the others *and* fitting them together...
Wierd only knows two symbols: space, and everything else. The instruction pointer tries to follow the path formed by the non-space characters, starting diagonally from the top left corner and always trying to go as straight as possible. The bends in the path form the actual instructions (with the degrees of the turn determining which instruction to execute). So the code seen by Wierd is this:
```
v1997 * * *
' * * *
8 * * *
* * * *
* ++++++++++++++++++++++++ ++++++++++++++++++++++++ ++O--OO++++++++OX******* *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* **** **** * **** **** * **** **** * **** *****
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * **** * * * * **** * * * * **** * * * * ****
* * * * * * * * * * * * * * * *
***** ******* ****** ******* ****** ******* ****** *******
```
The `1997` at the top isn't actually executed, but Wierd lets us read it from the source code, which is a *lot* shorter than trying to construct the character codes for the four digits itself (even if it doesn't look like it...). I don't feel like breaking this entire thing down, but you can clearly see the four repeated sections. What this does is that we first store `1` on the stack and then each of those four sections increments this `1`, and then branches. The bottom branch pushes another `1`, retrieves the source character at these coordinates and prints it, whereas the top branch is redirected to the next section. You might wonder why the ends of the paths are so unnecessarily long, but that's because when Wierd hits the end of a path it tries to jump to a nearby path before deciding that it should terminate the current branch. To avoid this, we need to move these ends sufficiently far away from any other code.
### 1998: [Befunge 98](https://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown)
Befunge got a fairly well-known update in 1998 with a very rigorous spec that can be generalised to arbitrary dimensions (and I think also arbitrary topologies). It's largely backwards-compatible with Befunge though, which makes it fairly easy to polyglot the two. This Befunge still didn't have any mirrors, so the executed path is the same as for Befunge 93:
```
v
\
>"8991",,,;5-;,@
```
The difference is that Befunge 98 doesn't ignore the `;`. Instead it acts a bit like a comment in that all commands until the next `;` are ignored. This way, we don't decrement that `8` to `3` and print the `1998` as is.
### 2001: ~~A Space Od...~~ [PingPong](http://esolangs.org/wiki/PingPong)
2001 is the year of Piet, but I really didn't feel like polyglotting an image file with all the other programs, so here is a lesser known 2D language. It seems to have quite a lot of features (which we're not going to use). Thanks to Sp3000 for [finding the original interpreter](https://github.com/graue/esofiles) (which is the only dead link on the archived version of the official website).
PingPong is somewhat unusual in that it has *only* mirrors and no `<v>^` redirectors. So this moves through the `v19977` at the start and then hits the mirror which wraps it to the bottom. The relevant code is then:
```
v19977/
...
/K:0:1:@
...
```
The actual code is quite simple: `K` pushes `20`, the digits push themselves, `:` prints an integer and `@` terminates the program.
### 2003: [SNUSP](http://esolangs.org/wiki/SNUSP)
This is first language where things get a bit easier, because SNUSP supports an explicit entry point. That entry point is marked by `$`. Judging from some articles on esolangs, this language has inspired several others, but unfortunately, at the end of the day it's just a Brainfuck derivative. That said, I think the way this sets the current cell to 48 is quite neat (and was stolen from the esolangs article). Here is the relevant part of the code:
```
$'main' \/\/\/\
\++++++\
/++++++/
\++++++\
/++++++/
\/\/\/\++.--..+++.#
```
Those are 24 `+`s and the mirrors send the IP through each one exactly twice.
### 2004: [Axo](http://esolangs.org/wiki/Axo)
For whatever reason, this language *does* have the `<^>` redirectors but instead of the usual `v` it uses `%`. Hence this just moves across the first line. The relevant code is:
```
v19977/2{@{{4{\
```
We push a few digits to begin with, perform a division. Then `2{` prints the `2`, `@` clears the stack. `{{` prints two (implicit) `0`s. `4{` prints the `4` and `\` terminates the program.
### 2005: [Rail](http://esolangs.org/wiki/Rail)
2005 was a difficult choice. For no other year did I find as many 2D languages, and there is ADJUST and Archway, both of which start in the *lower* left corner (which would have made them easy additions). I like Rail though and since it has an explicit entry point is wasn't hard to add either. Rail looks for a line start with `$'main'` and starts moving south-east from the `$`. That means the relevant code is:
```
$'main'
\-[2005]o-#
```
The `\` and `-` are just tracks (no-ops). The `[2005]` is a string literal which `o` prints before `#` terminates the program.
### 2006: [BestFriends.js](http://esolangs.org/wiki/BestFriends.js)
A two-dimensional Brainfuck. There is another interesting language for this year called Black, which starts at coordinate `(3,3)` (1-based) which would have made using this in a polyglot interesting, too. I couldn't find an interpreter though. So we'll have to work with another BF-derivative instead...
The interesting thing about this one is that it doesn't format the grid into lines with linefeeds like most other 2D languages. Instead `|` is used as the line separator. Since I didn't use `|` for any other languages, I could simply put a `|` on the last line which makes the entire rest of the program a single line as far as BF.js is concerned. The relevant code is then this (turning the `|` into an actual linefeed):
```
v19977/2{...
}+++++[>++++++++++<-]>.--..++++++.@
```
BF.js uses *neither* `<v>^` nor mirrors. The only ways to redirect control flow is with `{}` which turn the IP direction by 90°. So those braces move the IP to the second line. The remainder is a plain Brainfuck solution (not particularly well golfed) that sets a cell to `50` (code point of `2`) and then prints `2006` by shifting the value around a bit. `@` terminates the program.
### 2008: [BrainSpace 1.0](http://esolangs.org/wiki/BrainSpace_1.0)
For this year I really wanted to use [DOBELA](http://esolangs.org/wiki/DOBELA) which uses multiple entry points and looks like the lovechild of [Fission](http://esolangs.org/wiki/Fission) and [Ziim](http://esolangs.org/wiki/Ziim). Unfortunately, I haven't been able to get the interpreter to work. So here is another BF derivative (the last one, I promise).
As opposed to the last one, this one knows *both* `<v>^` and mirrors, so the relevant code is:
```
v
\'\
8
\ * ++++++++++++++++++++++++ ++++++++++++++++++++++++ ++O--OO++++++++OX
```
This one doesn't have the usual BF-style `[]` loop (instead you'd need to form an actual 2D loop), so I just decided to hardcode the `50` since I had a ton of characters in a row from Wierd anyway. Note that the `'` and `8` are ignored, the `*` is a conditional trampoline which we can ignore and the `O` is Brainfuck's `.`. The `X` terminates the program.
### 2009: [><>](http://esolangs.org/wiki/Fish)
Probably the most popular Fungeoid (other than Befunge itself) at least around these parts. ><> has both `<v>^` and mirrors but also string literals, so the executed code is this:
```
v
\'\02'oo100@n590@n;
```
The string literal mostly serves to skip the `\` we used for BrainSpace 1.0 but while we're at it we might as well push the first two characters. `oo` prints them. Then `100` pushes three digits, `@` shoves the top one to the bottom and `n` prints the `0` underneath. We do the same thing again with `590` which prints the `9`. If you're wondering why I'm not just printing `2009` as is, wait for 2015. `;` terminates the program.
### 2010: [Cardinal](http://esolangs.org/wiki/Cardinal)
This one was simple, because it has an explicit entry point at `%`. However, this one creates 4 IPs in all directions (hence the language name, I suppose), and we need to get rid of 3 of them. Here is the relevant code:
```
x
x%"2010"x
x
```
Well, yeah. (In Cardinal, string mode prints directly instead of pushing the characters onto a stack.)
### 2011: [RunR](http://esolangs.org/wiki/RunR)
Another language with an explicit entry point (by [David Catt](http://esolangs.org/wiki/User:David.werecat) who has created a few other very nice esolangs), this time at `S`. This makes the relevant code this part:
```
S1^2^2^6^8MAOUOAOOF
```
RunR is a bit interesting because most operations work with a sort of register and values need to be moved to the stack explicitly for binary operations. The digits set the register values to themselves and `^` pushes the current register to the stack. Then `M` is multiplication (register times value popped from stack), `U` is subtraction, `A` is addition, `O` is output. `F` terminates the program.
### 2012: [Ropy](http://esolangs.org/wiki/Ropy)
Like Wierd, Ropy tries to follow sections of non-space characters, but here the bends don't determine the commands. In fact, it turns out that Ropy is more similar to my own [Labyrinth](http://esolangs.org/wiki/Labyrinth) in that the chosen direction depends on the top of the stack. However, we don't really need to worry about that here, because Ropy just moves along the first line:
```
v19977/2{@{{4{\_______>/02&&&#????
```
There's a lot of stuff we can ignore up to the `>`. All we need to know is that the top of the stack will at that point be a `4` and there'll be `2` below.
`>` duplicates the `4`, `/` is division turning it into a `1`. Then we push `02`. `&&&` joins the top four numbers of the stack in reverse order, giving `2012`. `#` outputs it. `????` just clears the stack because otherwise the top of the stack is output as well.
One point of interest is that the second `7` in `19977` was added because of Ropy. The `/` division in Ropy does `top / second` (opposite of the usual order in many stack-based languages), where `7 / 9` would give `0`. If we had a zero on top of the stack, Ropy would do some wild stuff with its direction of movement, so we need to push the other `7` to ensure that the top of the stack remains positive and Ropy keeps moving east.
### 2014: [Fission](http://esolangs.org/wiki/Fission)
With its explicit entry points, this one is easy. `RDLU` create atoms (instruction pointers) in the corresponding direction, so the relevant bit is just this:
```
R"2014";
```
Note that there's a `U` in the source code as well, but that atom eventually hits one of the `*` from Wierd, which terminates the program (and this atom takes a lot longer than the `R` needs to print `2014`).
### 2015: [Gol><>](http://esolangs.org/wiki/Golfish)
Sp3000's more powerful ><> derivative. It's largely backwards compatible with ><> so the executed code is still:
```
v
\'\02'oo100@n590@n;
```
However, the rotation direction of `@` was changed, which is the standard trick to distinguish ><> and Gol><> in polyglots, so this one prints `15` instead of `09`. Hence the weirdness in the second half of the program.
### 2016: [CSL](http://esolangs.org/wiki/CSL)
CSL is quite interesting in that commands aren't executed immediately. Instead, each command is pushed onto a command-stack and `e` and `E` can be used to execute commands from it. The relevant code becomes:
```
v19977/2{@{{4{\_______>/02&&&#???? * P+++++1P1P-1P+1E
```
So the `E` executes the entire command stack, which means that the stuff in front of it is executed in reverse. We only need to look up to the `*`:
```
1+P1-P1P1+++++P*
```
The `1`s push themselves onto the data stack. `+` and `-` are decrement/increment. `P` prints the top of the stack. Then `*` tries to multiply the top two values of the stack. However, the stack is empty, so this terminates the program.
---
At this point we get to languages which were released after this challenge was posted, so I'm not really counting them for the score, especially since I created these myself (not with this challenge in mind though). However, they do have some novel IP movement semantics, which made it easy to fit them into the polyglot while also adding something interesting to this showcase of 2D languages.
### 2017: [Alice](https://github.com/m-ender/alice)
Alice was designed to be a feature-rich Fungeoid. One interesting difference to the majority of (but not all) other 2D languages is that the IP can move either orthogonally, or diagonally. Switching between these also changes the semantics of almost all commands in the language. Furthermore, Alice supports both the traditional `<^>v` direction setters and `\/` mirrors, but mirrors have very unique behaviour in Alice (which makes it easy to lead the Alice IP to a so far unused portion of the code).
While most languages treat `\` and `/` as if they were mirrors at a 45° angle, and the IP as a light ray bouncing off of it, Alice treats them as having a 67.5° angle (which is closer to the angle of the actual slash glyphs), and the IP also moves *through* the mirror (hence the language's name). Due to this angle, mirrors switch between movement along orthogonal or diagonal directions. Furthermore, while in Ordinal mode (i.e. while the IP moves along diagonals), the grid doesn't wrap around and instead the IP bounces off the edges (whereas in Cardinal mode it does wrap around).
All in all, the code executed by Alice is the following:
```
v19
\ \
...
> "7102"4&o@
...
```
The IP starts in the top left corner as usual, `v` sends it south. Now the `\` reflects the IP to move northwest, where it immediately bounces off the left edge of the grid (and moves northeast instead). `1` can be ignored, the IP bounces off the top edge to move southeast next. We hit another `\` which reflects the IP north. `9` can also be ignored and then the IP wraps to the bottom of the grid. After a couple of lines we redirect it east with `>` for convenience. Then `"7102"` pushes the code points of the `2017`, `4&o` prints those four characters and `@` terminates the program.
### 2018: [Wumpus](https://github.com/m-ender/wumpus)
Wumpus is the first 2D language on a triangular grid, which makes movement through the code quite different (and again lets us reach an unused part of the code easily). So instead of thinking of each character in the grid as a little square, you should think of them as alternating upward and downward triangles. The top left corner is always an upward triangle.
Wumpus doesn't have direction setters like `<^>v`, but it does have mirrors `\/`. However, due to the triangular grid, these work differently from most other languages. The IP bounces off them like a light ray (as usual) but you should think of them as having an angle of 60° degrees. So an IP moving east will end up moving along the northwest axis of the grid.
As another difference to most other languages, the edges of the grid don't wrap, but the IP bounces off the edges instead (as if those edge cells contained the appropriate mirrors). Another fun little detail is that diagonals through the triangular grid actually look like staircases in the source code.
With that in mind, the code executed by Wumpus is the following (where I've replaced spaces with `.` for clarity:
```
v19977/
02
89
..
..
.....*...#2018O@
```
The `v19977` are just junk that we can ignore. `/` sends the IP northwest, where it moves through the `977` (from the right) again while bouncing off the top edge. Then the IP moves southwest through the `2089` and a bunch of spaces, before it hits the left edge to be reflected east again. `*` is also junk. Then finally `#2018` pushes `2018`, `O` prints it and `@` terminates the program.
---
### Missing years
Finally, some notes about years I haven't covered.
While researching 2D languages to find suitable ones across the years which could be used in a polyglot, I found out that contrary to popular belief, Befunge was *not* the first 2D language. That title seems to be held by [Biota](http://esolangs.org/wiki/Biota) which was already created in 1991. Unfortunately, the language doesn't have any output, so I wasn't able to use it for this challenge.
As far as I can tell no 2D languages were created in 1992 and 1995. That leaves a few years I haven't covered:
* 1994: [Orthagonal](http://esolangs.org/wiki/Orthagonal) was created, independently of Befunge. The languages are semantically quite similar actually, but Orthagonal doesn't actually lay out the source code in 2D. Instead each line is an `(x, y, instruction)` tuple. I even obtained the language spec and original interpreter from the creator Jeff Epler, but in the end, the fact that the syntax isn't 2D made the language unsuitable for this polyglot.
* 1996: [Orthogonal](http://esolangs.org/wiki/Orthogonal), a successor to Orthagonal (created by someone else) was created, but for the purposes of this polyglot suffers the same problems as Orthagonal.
* 1999: The only language I could find was Chris Pressey's cellular automaton [REDGREEN](http://esolangs.org/wiki/REDGREEN). Unfortunately, as opposed to its predecessor RUBE, it doesn't seem to have any I/O semantics.
* 2000: There's another cellular automaton of Chris Pressey's called [noit o' mnain worb](http://esolangs.org/wiki/Noit_o%27_mnain_worb) but it also doesn't have any I/O. There's also [Numberix](http://esolangs.org/wiki/Numberix) which I haven't tried to get running and I'm not sure whether it would ignore non-hex characters in the source code.
* 2002: There's [Clunk](http://esolangs.org/wiki/Clunk) with no I/O and [ZT](http://esolangs.org/wiki/ZT) whose language specification terrifies me.
* 2007: I found three languages here. [Zetaplex](http://esolangs.org/wiki/Zetaplex) is image based (so nope) and [RubE On Conveyor Belts](http://esolangs.org/wiki/RubE_On_Conveyor_Belts) seems to require a header with a rather strict format which would have messed with the first line of the program. There's also [Cellbrain](http://esolangs.org/wiki/Cellbrain) by Quintopia, but it also seems to require a specific header.
* 2013: Again, I found three languages. [Fishing](http://esolangs.org/wiki/Fishing) might be possible with a good amount of restructuring but it would require the program to begin with a valid dock. [Quipu](http://esolangs.org/wiki/Quipu), from memory, is way too strict about its syntax to allow much polyglotting. And [Swordfish](http://esolangs.org/wiki/Swordfish) is another member of the ><> family, but unfortunately I haven't been able to find an interpreter. Otherwise, this one would probably be fairly easy to add.
If anyone is interested, [here is the complete list of implemented 2D languages sorted by years](http://pastebin.com/gqHJzDMj) as far as I could find them (at the time this answer was posted). If any are missing from this list, please [let me know in chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte) as I'd be really interested in a complete list.
[Answer]
## 15 years, Python
**Versions:** [0.9.1](https://www.python.org/download/releases/early/), [2.0.0](https://www.python.org/download/releases/2.0/#download), 2.2.0, 2.2.2, 2.5.0, 2.5.1, 3.0.0, 3.1.0, 3.1.3, 3.2.1, 3.3.0, 3.3.3, 3.4.0, 3.5.0 and [3.6.0a4](https://www.python.org/downloads/release/python-360a4/). Versions not linked can be found on the [downloads page](https://www.python.org/downloads/).
The release date of 0.9.1 can be found [here](http://svn.python.org/view/*checkout*/python/trunk/Misc/HISTORY). Unfortunately I had to skip a large bunch of years due to missing old versions and compilation problems on my computer. The represented years are 1991, 2000-2002 and 2006-2016.
Tested on Arch Linux, using the gzipped versions.
```
# Note: This file needs a trailing newline due to 0.9.1
# 0.9.1: No bitwise operators
# This one errors out by division by zero.
try:
eval('1&2')
except:
print(1991)
1/0
import sys
# 2.0.0: repr('\n') gives "'\012'" instead of "'\n'"
# == doesn't exist until Python 0.9.3 and <> doesn't exist in Python 3, hence we
# use <. Also, 0.9.1 doesn't have double quoted strings.
if repr('\n') < '\'\\n\'':
print(2000)
sys.exit()
# 2.2.0: email module still has a _Parser class - module revamped in 2.2.2
# I would use whether or not True exists as a name here, but weirdly "True"
# worked in 2.2.2 even though the docs say it was introduced in 2.3...
try:
import email
email._Parser
print(2001)
sys.exit()
except AttributeError:
pass
# 2.2.2: a in b only works for strings a of length 1.
try:
eval('"art" in "Martin"')
except TypeError:
print(2002)
sys.exit()
# 2.5.0: int() allows null bytes in integer to convert when given an explicit
# base.
try:
print(int('2006\x00Hello, World!', 10))
exit()
except ValueError:
pass
# 2.5.1: pow overflows
# Note that we can't use ** here since that doesn't exist in 0.9.1.
if pow(2, 100) < 1:
print(2007)
exit()
# 3.0.0: round returns a float rather than an int.
if str(round(1, 0)) > '1':
print(2008)
exit()
# 3.1.0: bug caused complex formatting to sometimes drop the real part.
if format(complex(-0.0, 2.0), '-') < '(-':
print(2009)
exit()
# 3.1.3: str of a float is shorter than the repr of the same float.
if str(1.0/7) < repr(1.0/7):
print(2010)
exit()
# 3.2.1: For some weird reason, u'...' Unicode strings were disabled then
# re-enabled later.
try:
eval('u"abc"')
except:
print(2011)
exit()
# 3.3.0: int still works without a first argument.
try:
int(base=10)
print(2012)
exit()
except TypeError:
pass
# 3.3.3: no enum module :(
try:
import enum
except ImportError:
print(2013)
exit()
# 3.4.0: PEP 448 (additional unpacking generalisations) not implemented yet
try:
eval('[*[1], *[2], *[3]]')
except SyntaxError:
print(2014)
exit()
# 3.5.0: No f-strings
try:
eval('f"abc"')
except SyntaxError:
print(2015)
exit()
print(2016)
```
[Answer]
# Short and sweet; the three [APL](https://en.wikipedia.org/wiki/APL_(programming_language))s ([K](https://en.wikipedia.org/wiki/K_(programming_language)), [J201](http://www.jsoftware.com/release/status.htm), [Dyalog 7.1](http://dyalog.com/dyalog/dyalog-versions.htm)) in 8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
1993+1^2
```
1993 plus...
K: the first 1 integer {0} except {2}, i.e. {0}; 1993 – [Try it online!](https://tio.run/nexus/k-ok#@29oaWmsbRhn9P8/jAUA "K (oK) – TIO Nexus")
J: 12 = 1; 1994 – [Try it online!](https://tio.run/nexus/j#@29oaWmsbRhn9P8/jAUA "J – TIO Nexus")
APL: LCM(1,2) = 2; 1995 – [Try it online!](https://tio.run/nexus/apl-dyalog-classic#@29oaWmsbRhn9P8/jAUA "APL (Dyalog Classic) – TIO Nexus")
[Answer]
# 10 years, 12 languages, 2430 bytes
This answer is a collaboration between myself and user [1000000000](https://codegolf.stackexchange.com/users/20059/1000000000).
A brief language list:
```
Brainfuck 1993
Befunge 1993
Piet 2001
Whitespace 2003
Braincopter 2005
Grass 2007
Starry 2008
Paintfuck 2008
Brainbool 2010 (11111011010)
Python 2.7.2 2011
Fission 2014
Brainflak 2016
```
Here is the code:
```
P3v="";print(sum([ord(x)for x in"~~~~~~~~~~~~~~~y"]));"""{}{} + + +---[. + +.. '.. +. +.. +. +. +.] + + + + + + +(((((()()()()){}){}){}){})({({} +-[<() + + + + + + +>-()])}{}<[. + + + + + + + +..------- ` +.[-]]>)[< '
17 12
# > 7*::,8 +:,,2 +,@<>R"2014";]*ne*e*es*s*swWWW*swWWWW*sw*e*e*e*eeev*wn*n*n*n*ne*e*se*s*s*s*sWWwWWWw**e*eeee*vwn*n*n*n*ne*e*se*s*s*s*sWWWw*eeee*e*ne*n*nWWWWWw*ne*nWWWWWWw*w*sw*se*sWWWWWWWw*s*WWWWWWwwwWWWWWWWWWWwWWWWWWWWWWwvwWWWwWWWWwvwWWwWWWwvwWWwWWWwvwWWwWWWwvwWWwwwwwwwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWwv `
255 0 255 255 0 192 192 0 192 192 0 192 192 192 255
255 192
255 255 192
255
255
0 255 255 0 255 255 0 255 255 0 255 255 0 192 192 192 255 255 255 255 255 0 192 192 0 0 255 255 255
255 0 0 255 0 192 192 0 192 192 0 192 192 192 255 255 192 255 255 192 255 255 192 255 255 0 255 255 0 255 255 0 255 255 0 192 192 255 255 255 255 255 255 255 255 255 255 255 255 0 192
192 0 0 255 0 192 192 0 192 192 0 192 192 0 192 192 192 255 255 192 255 255 192 255 255 0 255 255 0 255 255 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 0 0
255 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 255 255
255 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 192
192 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 0
255 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 0 255 255 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 255 255
255 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 192
192 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 0
192 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 0 0 0 0 0 255 255
255 0 192 192 0 0 255 0 0 255 255 255 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 255 255 255 255 255 255 0 0 255 0 0 255 0 255 255 0 0 0 0 192 192 0 0
255 0 192 192 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 0 255 0 255 255 0 0 0 0 192 192 0 192 192
# """
```
In order to fit this within a response I will forgo entire TIO links and will rather just post a link to a valid interpreter where the code may be input by the user. Here is a [Pastebin link](http://pastebin.com/fGArtNg5) for that purpose.
## [Piet](https://www.bertnase.de/npiet/npiet-execute.php)
The [PPM file format](https://en.wikipedia.org/wiki/Netpbm_format#File_format_description), one of the image formats that the Piet interpreter we used can read from, has a plaintext ASCII version. Using this we were able to embed the code of other languages as junk in the image file read by Piet and Braincopter.
The image looks like this:
[![Raw image](https://i.stack.imgur.com/7J3Al.png)](https://i.stack.imgur.com/7J3Al.png)
Not all of the image is important for Piet. Here is a version with a line highlighting the path that Piet follows through the code:
[![Piet path](https://i.stack.imgur.com/jUf3z.png)](https://i.stack.imgur.com/jUf3z.png)
Despite somewhat convoluted methods to create the program the program itself is quite simple. Along the top of the image it pushes `1 10 10 10 2` to the stack; along the side it multiplies thrice and adds once. In the bottom corner it outputs the result (2001) and then halts.
## [Braincopter](https://dl.dropboxusercontent.com/u/30765884/braincopter.zip)
Braincopter is the other visual language. It also relies on the same `ppm` image file to run. Because of very harsh restrictions in npiet our Braincopter code can only use a subset of the original Braincopter operations. We are restricted to using colors that are valid ops in Piet. This removes the `-` operator from Braincopter.
Here is the path traced out by the Braincopter code:
[![Braincopter path](https://i.stack.imgur.com/btThG.png)](https://i.stack.imgur.com/btThG.png)
The Braincopter program is a bit strange because of the lack of a `-` operator. The walls of cyan and dark cyan serve to redirect the pointer but other than that it is identical to the following brainfuck:
```
++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++..+++++.
```
This prints 2005.
## [Paintfuck](http://www.formauri.es/personal/pgimeno/temp/esoteric/paintfuck/paintfuck-canvas.php)
Paintfuck is the third visual programming language on our list however instead of taking in a image and outputting text, Paintfuck takes in text and outputs an image.
Since Paintfuck ignores irrelevant characters as no-ops most of the code is unimportant. The relevant section of the code is:
```
nsn**ne*e*es*s*sw*sw*sw*e*e*e*eee*wn*n*n*n*ne*e*se*s*s*s*sww**e*eeee*wn*n*n*n*ne*e*se*s*s*s*sw*eeee*e*ne*n*nw*ne*nw*w*sw*se*sw*s*wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwnsn**ne*e*es*s*sw*sw*sw*e*e*e*eee*wn*n*n*n*ne*e*se*s*s*s*sww**e*eeee*wn*n*n*n*ne*e*se*s*s*s*sw*eeee*e*ne*n*nw*ne*nw*w*sw*se*sw*s*wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
```
While they are not no-ops the `w`s at the end of the code do nothing. They are there for the grass portion of the solution. `n`,`e`,`s`, and `w` are used to move around the image and `*` is used to plot a point at certain location. The program outputs:
[![Paintfuck output](https://i.stack.imgur.com/NW4Xd.png)](https://i.stack.imgur.com/NW4Xd.png)
A bigger version:
[![Painfuck output, but its bigger](https://i.stack.imgur.com/0IHv1.png)](https://i.stack.imgur.com/0IHv1.png)
## Brainfuck
Like Paintfuck Brainfuck ignores most characters. Once again here are the important ones:
```
[]+++---[.++....+.+..+.+.+.]++++++++-[<+++++++>-]<[.++++++++..-------+.[-]]>[<>,+,,+,<>]
```
Most of this is further irrelevant by circumstance and just happen to be characters that some other language needed. The slimmer version of this code is:
```
+++++++[<+++++++>-]<[.++++++++..------.[-]]
```
This pretty simply prints `1993`.
## [Brainbool](http://brainbool.tryitonline.net/)
Brainbool is very similar to Brainfuck in its character selection. The big difference that allows the two to be woven together is the lack of a `-` in Brainbool. The important characters for Brainbool are:
```
[]+++[.++....+.+..+.+.+.]++++++++[<+++++++>]<[.++++++++..+.[]]>[<>,+,,+,<>]
```
Brainbool and brainfuck's outputs are mutually exclusive. Brainbool hides its output in the second set of `[]`. Brainfuck encounters `+++---` before it reaches the `[` setting it to zero and causing it to skip the output, while Brainbool only sees `+++` setting it to 1 causing it to pass through the loop. Similarly Brainbool is set to zero at the 4th loop causing it to skip while Brainfuck enters the loop with a value of 49.
Since Brainbool does not have decimal output it outputs the 2010 in binary:
```
11111011010
```
## [Fission](http://fission.tryitonline.net/)
The only part of the code that is important for fission is:
```
R"2014";
```
The `R` summons in a atom moving to the right, the `"2014"` prints `2014` and the `;` halts execution.
## [Befunge](http://befunge.tryitonline.net/)
Befunge only passes through the following characters:
```
P3v
7
> 7*::,8 +:,,2 +,@
```
The `P3` are necessary to make a valid .ppm image for piet, and cumulatively push a 3 to the stack. the `v` is placed to redirect the the pointer downwards. It then passes through the `7` in the `17` used to indicate the width of the .ppm image. The `>` redirects the pointer to the right. `7*` multiplies the top of the stack by 7 leaving 49 (ASCII value of `1`) on the top of the stack. `::` duplicates the top of the stack twice. The `1` is output by `,`. `8 +` adds 8 to the top incrementing to ASCII `9`. `:,,` outputs `9` twice. `2 +` increments the ASCII `1` to an ASCII `3` and `,` prints. Finally `@` terminates the program.
All in all it prints `1993`.
## [Whitespace](http://whitespace.tryitonline.net/)
Whitespace, as the name might suggest, only uses whitespace in its programs. This is what the Whitespace interpreter sees:
```
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][LF]
[Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Tab][Tab][Tab][Tab][Tab][Space][Tab][Space][Space][Tab][Tab][LF]
[Tab][LF]
[Space][Tab][LF]
[LF]
[LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][Space][LF]
[Space][Space][Space][LF]
```
Most of what this code does is inconsequential to the execution of the program (all the lines containing only spaces simply push zero to the stack). The important part:
```
[Space][Space][Space][Tab][Tab][Tab][Tab][Tab][Space][Tab][Space][Space][Tab][Tab][LF]
[Tab][LF]
[Space][Tab][LF]
[LF]
[LF]
```
The first line pushes 2003 to the stack. After that `[Tab][LF][Space][Tab]` prints out the top of the stack (2003) as a number. Finally the last three linefeeds end the program execution.
## [Grass](http://www.blue.sky.or.jp/grass/)
Grass ignores all character until the first `w` in the file and after that all characters that are not `w`, `W`, or `v`. The Grass interpreter reads:
```
wWWWwWWWWwv
wWWwWWWwv
wWWWwWWWWWwWWWWWWwwwWWWWWWWwWWWWWWwwwWWWWWWWWWWwWWWWWWWWWWwv
wWWWwWWWWwv
wWWwWWWwv
wWWwWWWwv
wWWwWWWwv
wWWwwwwwwwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWwv
```
The first line defines a function that adds two to whatever it is passed. The second line defines a function that adds four to whatever it is passed. The third defines a function that prints two plus the argument, the prints the argument twice, then finally prints seven plus the argument (Grass prints out characters based on ASCII value). The fourth, fifth and sixth lines define functions that add eight, add 16, add 32, and add 64 to their argument, respectively. The final line defines the main function which takes the character `w` (the only predefined number in Grass, ASCII value 119) and adds 185 to it using the add functions defined in the program as well as the built in add one function. Grass wraps numbers at 256 and so the result is 48 (corresponding to the character `0`). The function then passes this to the function of the third line which prints out 2007.
## [Starry](http://starry.tryitonline.net)
Starry ignores everything except for space, `+`, `*`, `.`, `,`, ```, and `'`. Thus the starry interpreter sees only:
```
+ + +. + +.. '.. +. +.. +. +. +. + + + + + + + + + + + + + + +. + + + + + + + +.. ` +. '
*, +,, +,************************************************* `
```
However, the label and jump instructions are used to skip sections of the code which could cause problems if run, so the code is effectively this:
```
+ + +. + +.. ' ` +. ' `
```
This code pushes two to the stack, duplicates it twice and then pops and prints one of them as a number. Then pushes zero, duplicates it and prints both zeros as numbers. Next it pops one of the twos and jumps and then pushes seven to the stack and pops and prints is as a number. Finally it pops the last two on the stack and jumps to the end of the program.
## Python 2.7.2
The Python code follows the format:
```
P3v="";print(sum([ord(x)for x in"~~~~~~~~~~~~~~~y"]));"""..."""
```
where `...` stands in for all of the other junk.
The first line, `P3v=""` is there because to be a valid `.ppm` file our code must start with `P3` this will normally error but if we tell python it is a variable declaration it will ignore it.
Next we have to print `2011`. However because of the way that a `.ppm` is formatted we cannot include any numbers in this line. In order to get around this we sum up all of the ASCII values of the string `"~~~~~~~~~~~~~~~y"` and print the result. Finally we use the triple quotes of a multiline comment so that python ignores everything else.
## [Brainflak](http://brain-flak.tryitonline.net/)
We saved the best for last.
Brainflak, like others, ignores most characters. The relevant characters are:
```
(([()])){}{}[](((((()()()()){}){}){}){})({({}[<()>()])}{}<[[]]>)[<><>]
```
The python code, `(([()]))`, pushes -1 to the stack twice so it needs to be removed before the program begins processing.
After that Brainbool uses a `[]` nilad which does nothing and the program begins.
`(((((()()()()){}){}){}){})({({}[<()>()])}{}<[[]]>)` pushes 2016. The last `[<><>]` is remnants of Befunge and Brainfuck but luckily does nothing.
When the program terminates it prints the contents of the stack, that is it prints `2016`.
[Answer]
## 5 years
```
#define q/*-[>+<-----]>--.++++++++..------.[-][
print('2010'if len(bin.__doc__)==86else'2015')
"""*/
main(c){c=-4.5//**/
-4.5;printf("19%d",90-c);}
#define w/*]
*/"""
```
### [1989: C89](http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=17782)[1], and [1999: C99](http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=29237)
The single line comment `//` was added in C99, so a C89 compiler would read that code as `c=-4.5 / /*comment*/ -4.5`, which is the same as `c=-4.5 / -4.5`, whereas a C99 compiler would read as `c=-4.5 //comment/**/`
`- 4.5`, which is the same as `c=-4.5 - 4.5`.
The Python part is a comment in the C program.
### [2010: Python 2.7](https://www.python.org/download/releases/2.7/), and [2015: Python 3.5](https://docs.python.org/3/whatsnew/3.5.html)
The docs vary between Python 3 and 2, this program uses the length of the docs to detect the Python version.
The C part is in a string in the Python program.
### 1993[2]: Brainfuck
It basically ignores everything that aren't `.,[]+-<>`. Since C program has a `,` in it, I had to make Brainfuck to dismiss that part by setting the current byte to 0.
---
1. The C89 spec was released in 1990. [More info](https://gcc.gnu.org/onlinedocs/gcc/Standards.html).
2. I couldn't find an official release date, so I'll believe [Esolangs](http://esolangs.org/wiki/Brainfuck) and [Wikipedia](https://en.wikipedia.org/wiki/Brainfuck).
[Answer]
## 15 years, JavaScript
Since JavaScript's release cycle is very unusual and inconsistent, I'm going to use the Firefox implementation. Please let me know if this is not allowed.
**Versions:** [Phoenix 0.1](http://www.oldapps.com/firebird.php?old_firebird=1), [Firebird 0.6](http://website-archive.mozilla.org/www.mozilla.org/firefox_releasenotes/en-US/firefox/releases/0.6.html), [Firefox 1.0.0](http://filehippo.com/download_firefox/15/), [1.5.0](http://filehippo.com/download_firefox/588/), [2.0.0](http://www.oldapps.com/firefox.php?old_firefox=26), [3.0 Beta 1](http://filehippo.com/download_firefox/3464/), [3.0.0](http://filehippo.com/download_firefox/4288/), [3.5.0](http://filehippo.com/download_firefox/5842/), [3.6.0](http://filehippo.com/download_firefox/6906/), [4.0.0](http://filehippo.com/download_firefox/9506/), [10.0.0](http://filehippo.com/download_firefox/11540/), [18.0.0](https://www.google.com/search?q=download+firefox+18.0&ie=utf-8&oe=utf-8), [27.0.0](http://filehippo.com/download_firefox/56835/), [35.0.0](http://filehippo.com/download_firefox/comments/59773/), [44.0.0](http://filehippo.com/download_firefox/65824/) (all tested on Windows 7)
**Important note:** Installing and opening Firefox 1.0.0 or any later version **may erase all of your saved Firefox data**, including history and bookmarks.
Also, starting with 1.0.0, you can only have one version open at a time; trying to open another version results in a new window of the already-open version.
### Instructions
* **Option 1:** Save the code below to your computer as an HTML document and open it in each browser.
* **Option 2:** Open <https://ethproductions.github.io/js-year-test.html> in each browser.
### Code
```
<script onbeforeunload="123">
// This uses document.write because alert does nothing in Phoenix (Firefox) 0.1.
document.write((function () {
function assert (code) {
try {
eval(code);
return true;
} catch (e) {
return false;
}
}
// Firefox 44 supports octal and binary literals in Number(); Firefox 35 does not.
if (Number("0o1") === 1)
return 2016;
// Firefox 35 supports template strings; Firefox 27 does not.
if (assert("`abc`"))
return 2015;
// Firefox 27 supports argument spreading; Firefox 18 does not.
if (assert("Math.max(...[1, 2, 3])"))
return 2014;
// Firefox 18 supports default arguments; Firefox 10 does not.
if (assert("function q(a = 1) { }"))
return 2013;
// Firefox 10 has basic WeakMap support; Firefox 4 does not.
if (assert("WeakMap.a"))
return 2012;
// Firefox 4 has basic typed array support; Firefox 3.6 does not.
if (assert("Int8Array.a"))
return 2011;
// Firefox 3.6 added the async attribute to script elements.
if (assert("document.getElementsByTagName('script')[0].async.a"))
return 2010;
// Firefox 3.5 added the String.prototype.trim() method.
if (assert("'abc'.trim()"))
return 2009;
// Firefox 3.0 added partial support for object destructuring.
if (assert("var {c} = {c: 7}"))
return 2008;
// Firefox 3.0 beta 1 added the Array.prototype.reduce() and Array.prototype.reduceRight() methods.
if (assert("[].reduce.a"))
return 2007;
// Firefox 2.0 added support for restricted words as properties.
if (assert("({if:1}).if"))
return 2006;
// Firefox 1.5 added the Array.prototype.indexOf() methods, along with a couple other Array methods.
if (assert("[1].indexOf(1)"))
return 2005;
// Practically the only JS difference between v0.6 and v1.0 is the addition of the onbeforeunload event.
if (assert("document.getElementsByTagName('script')[0].onbeforeunload.a"))
return 2004;
// The Object.prototype.eval() method was removed in Firebird 0.6.
if (!assert("'abc'.eval()"))
return 2003;
// We're all the way back to the good old Phoenix 0.1 browser...
return 2002;
})());
</script>
```
[Answer]
# 6 languages, [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d) and [brainfuck](http://esolangs.org/wiki/Brainfuck), Python 3.5, Python 2.7, [><>](http://esolangs.org/wiki/Fish), [Fission](http://esolangs.org/wiki/Fission)
Turtlèd has not existed before this year, and so easily objective, even if the github commits don't count, and BF has the esolang page evidence, released 1993. Python 3.5 is 2015, 2.7 is 2010. ><> also has esolang page, stating 2009, as does Fission, 2014
```
#-[>+<-----]>--.++++++++..------#"2016"/
print(2015 if len(len.__doc__)==42 else 2010)
#; oooo"2009"/
#;"4102"L
```
I should probably give credit to the bf constants page on esolangs... ¯\\_(ツ)\_/¯
## How it works, kind of:
### Turtlèd:
Turtlèd doesn't really do anything for lines other than the first:
```
#-[>+<-----]>--.++++++++..------#"2016"/
^sets string variable to this ^ prints 2016
```
/ is a nop
### Brainfuck
Brainfuck ignores chars not in its commands
it sees `-[>+<-----]>--.++++++++..------.` (the last . is from the python part)
which just does Brainfuck stuff, it uses wrapping to divide 255 by 5, then subtract 2 from the result, print, increment 8 times, print twice, decrement 6 times, print
### Python 2 and 3
```
print(2015 if len(len.__doc__)==42 else 2010)
```
the length of the docs for len vary between the versions, so it prints the year for version 3 if it is the right length, else for version 2.
### ><>
# reflects the pointer backwards, so it hits the / on the other side of that line, passes through the space between `else` and `2010`, then reflects again to hit "2009", pushing 9,0,0,2 onto stack, then printing out reversed.
### Fission
Fission has spawners, so we can have a line at the bottom that it executes alone:
```
#;"4102"L
L spawn left moving atom
"4102" print this right to left
; halt
# python comment
```
[Answer]
## 3 years, 3 languages: C, TeX, MIXAL
```
*main(){puts("1990");}/*\newwrite\O\openout\O=O\write\O{1982}\bye
START ENTA 1997
CHAR
STX 6
OUT 6(19)
HLT
END START */
```
Name the file `date.mixal`.
1. C (1990) -- Compiles with warnings and prints `1990` to `stdout`.
2. TeX (1982) -- Compile with `tex date.mixal`; prints `1982` to the file `O.tex` (ignore the DVI output).
3. MIXAL (1997) -- Compile using GNU Mix Development Kit, `mixasm date.mixal` and run with `mixvm -r date.mix`; prints `1997` to the teletype device (=`stdout`).
The TeX and MIXAL programs are in a comment in the C program; the MIXAL program comes after `\bye` so TeX ignores it. The C and TeX programs are a comment in the MIXAL program. For some reason `gcc` is willing to accept `*main`.
[Answer]
# 3 years (GolfScript, CJam, MATL), ~~24~~ 23 bytes
```
[A11]Wd%;200 1e2/0 8_+(
```
This outputs
* [`2007`](http://golfscript.tryitonline.net/#code=W0ExMV1XZCU7MjAwIDFlMi8wIDhfKyg&input=) in GolfScript.
* [`2015`](http://cjam.tryitonline.net/#code=W0ExMV1XZCU7MjAwIDFlMi8wIDhfKyg&input=) in CJam (version 0.6.5).
* [`2016`](http://matl.tryitonline.net/#code=W0ExMV1XZCU7MjAwIDFlMi8wIDhfKyg&input=) in MATL (version 19.2.0).
## Explanation
### Golfscript
[Undefined tokens are noops in GolfScript](https://codegolf.stackexchange.com/a/37369/36398). The only parts of the code that actually do something are:
```
200 Push 200
STACK: 200
1 Push 1
STACK: 200, 1
/ Divide
STACK: 200
0 Push 0
STACK: 200, 0
8 Push 8
STACK: 200, 0, 8
+ Add
STACK: 200, 8
( Subtract 1
STACK: 200, 7
Implicitly display 200, 7 as "2007"
```
### CJam
```
[A11] Push array [10 11]
STACK: [10 11]
W Push -1
STACK: [10 11], -1
d Convert to double
STACK: [10 11], -1.0
% Select elements from array
STACK: [11 10]
; Pop
STACK is empty
200 Push 200
STACK: 200
1e2 Push 100
STACK: 100
/ Divide
STACK: 2
0 Push 0
STACK: 2, 0
8_ Push 8 and duplicate
STACK: 2, 0, 8, 8
+ Add
STACK: 2, 0, 16
( Subtract 1
STACK: 2, 0, 15
Implicitly display 2, 0, 15 as "2015"
```
### MATL
Everything from `%` onwards is a comment.
```
[A11] Push array [5 11]
STACK: [5 11]
W 2 raised to that
STACK: [32 2048]
d Compute increment
STACK: 2016
Implicitly display as "2016"
```
[Answer]
# 2 languages, Python 2.7 and Python 3.5
Python 2.7 was released in [2010](https://www.python.org/download/releases/2.7/).
Python 3.5 was released in [2015](https://www.python.org/downloads/release/python-350/).
```
print('2010'if 3/2==1else'2015')
```
This relies on [PEP 238](https://www.python.org/dev/peps/pep-0238/) where the operator `/` was changed from integer division in Python 2 to floating-point division in Python 3.
[Answer]
# 8 years, TI-Basic
```
Disp 1996 <-- TI-83
Text(-1,1,1,1
ClrHome
Disp 1999 <-- TI-83+ OS 1.03 (initial OS)
sub(1
ClrHome
Disp 2002 <-- TI-83+ OS 1.15
isClockOn
ClrHome
Disp 2004 <-- TI-84+ OS 2.21
invT(e,1
ClrHome
Disp 2005 <-- TI-84+ OS 2.40
CLASSIC
ClrHome
Disp 2009 <-- TI-84+ OS 2.53
BackgroundOn
ClrHome
Disp 2013 <-- TI-84+ Color Silver Edition
Send({1
ClrHome
2015 <-- TI-84+ Color Edition OS 5.1
```
"Any of the programs may print to STDERR, or throw runtime/compile time errors and warnings as long as the correct output is still printed to STDOUT or a file." Currently, the only non-error display is the year, so we are complying with this rule. However, if you'd like to write to the memory instead, replace `Disp (date)` with `(date)->I`.
References:
1. Calculator release dates - <https://epsstore.ti.com/OA_HTML/csksxvm.jsp?nSetId=74258>
2. TI-83+ OS 1.15 release date - <http://wikiti.brandonw.net/index.php?title=83Plus:OS:VersionDifferences#TIOS_1.15>
3. Calculator compatibility - <http://tibasicdev.wikidot.com/compatibility>
4. TI-84+CSE release date - [https://www.amazon.com/Texas-Instruments-Silver-Graphing-Calculator/dp/B00AWRQKDC](https://rads.stackoverflow.com/amzn/click/com/B00AWRQKDC)
5. TI-84+CE release date - <http://www.prnewswire.com/news-releases/texas-instruments-unveils-the-new-ti-84-plus-ce-300026266.html> and <https://www.cemetech.net/forum/viewtopic.php?t=8870>
[Answer]
# 5 years, Go 1.0, 1.1, 1.4, 1.5, 1.6: ~~285~~ 257 bytes
(1.2 was released in 2013 like 1.1, 1.3 in 2014 like 1.4, and 1.7 in 2016 like 1.6.)
Have not tested this out on every version because I can access only 1.6, but it should work in theory! Language changes would likely have caused the program not to compile, so I relied on standard library changes.
```
package main
import(."fmt"
."reflect"
."time")
func main(){s:="6"
if _,e:=Parse("2016-Sep-30","2016-Sep-31");e==nil{s="5"}
if Sprint(ValueOf(0))!="0"{s="4"}
if Sprint(&map[int]int{1:1})[0]!='&'{s="3"}
if string(0xd800)==string(0xfffd){s="2"}
Print("201"+s)}
```
Ungolfed and commented:
```
package main
import (
"fmt"
"reflect"
"time"
) package main
import (
. "fmt"
. "reflect"
. "time"
)
func main() {
s := "6"
// 1.6: time.Parse rejects invalid days
if _, e := Parse("2016-Sep-30", "2016-Sep-31"); e == nil {
s = "5"
}
// 1.5: A reflect.Value now prints what it holds, rather than use
// its String() method
if Sprint(ValueOf(0)) != "0" {
s = "4"
}
// 1.4: Printing pointers to maps gives the map instead of the address
if Sprint(&map[int]int{1: 1})[0] != '&' {
s = "3"
}
// 1.1: Unicode surrogate halves are no longer allowed
if string(0xd800) == string(0xfffd) {
s = "2"
}
Print("201" + s)
}
```
[Answer]
# 7 years, 8 browsers
Not exactly language release dates because css doesn't actually have releases, but browser versions (could be thought as compiler versions maybe?)
For the following browsers, this prints the browser name, version and release date and nothing else. It does print the same thing for a few later versions, (you will see chromium is one version late in the screenshots because it's hard to download old versions of chrome by version number)
I could print the version number I used but I preferred to show the first version where the used feature is introduced.
* IE6
* IE7
* IE8
* IE9 (untested, don't have an IE9 around)
* Firefox 4
* Firefox 3.6
* Chrome 18
* Chrome 21
* Modern Browsers
[![FF3.6](https://i.stack.imgur.com/ovnp2.png)](https://i.stack.imgur.com/ovnp2.png)
[![FF4](https://i.stack.imgur.com/GegWu.png)](https://i.stack.imgur.com/GegWu.png)
[![Chromium19](https://i.stack.imgur.com/u4Isw.png)](https://i.stack.imgur.com/u4Isw.png)
[![Chromium22](https://i.stack.imgur.com/abJ7P.png)](https://i.stack.imgur.com/abJ7P.png)
[![IE8-quirks](https://i.stack.imgur.com/gnK8S.png)](https://i.stack.imgur.com/gnK8S.png)
[![IE8-IE7compatibility](https://i.stack.imgur.com/7MYnq.png)](https://i.stack.imgur.com/7MYnq.png)
[![IE8](https://i.stack.imgur.com/08fMJ.png)](https://i.stack.imgur.com/08fMJ.png)
## index.html
```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel=stylesheet href=style.css>
</head>
<body>
<div class=borderbox>
<div class="inlineblock">
IE6-2001
</div>
<div class="white">
<div class="outofbox">
<a href="#">IE8-2009</a>
</div>
<div class="inherit">
<a href="#">IE7-2006</a>
</div>
</div>
</div>
<div class="white">
<header class="filter-quirk filter-blur filter-blur-url">
IE9
</header>
</div>
<div class="flex white">
Modern Browsers - 2017
</div>
<div class="webkit-flex">
<div class="">
Chrome 21-2012
</div>
</div>
<div class="webkit-invert white flexdisable">
<div class="">
Chrome 18-2012
</div>
</div>
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg">
</svg>
<div class="filter">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g
transform="scale(8)"
aria-label="FF4"
id="text8419">
<rect
style="color:#000000;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.79374999;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker:none;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
id="rect21965"
width="17.005648"
height="3.9855044"
x="-0.16825682"
y="-0.025296567" />
<path
d="m 1.0052634,1.5511362 v 0.7639843 h 0.4564063 q 0.092604,0 0.092604,0.066146 0,0.069453 -0.092604,0.069453 H 0.69107072 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 h 0.1785938 V 0.72431329 h -0.1785938 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 2.1793519 V 1.0484278 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 0.72431329 H 1.0052634 V 1.4155373 H 1.4848207 V 1.2667091 q 0,-0.089297 0.066146,-0.089297 0.069453,0 0.069453,0.089297 v 0.4332552 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 1.5511362 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8421" />
<path
d="m 2.9883464,1.5511362 v 0.7639843 h 0.4564063 q 0.092604,0 0.092604,0.066146 0,0.069453 -0.092604,0.069453 h -0.770599 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 2.8527475 V 0.72431329 H 2.6741537 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 4.1624349 V 1.0484278 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 0.72431329 H 2.9883464 V 1.4155373 H 3.4679037 V 1.2667091 q 0,-0.089297 0.066146,-0.089297 0.069453,0 0.069453,0.089297 v 0.4332552 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 1.5511362 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8423" />
<path
d="M 5.6692683,1.8917872 H 4.7729923 V 1.7363445 l 0.754062,-1.28322911 h 0.277813 V 1.7561883 h 0.112448 q 0.0893,0 0.0893,0.069453 0,0.066146 -0.0893,0.066146 h -0.112448 v 0.4233333 h 0.112448 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -0.499402 q -0.0893,0 -0.0893,-0.069453 0,-0.066146 0.0893,-0.066146 h 0.251355 z m 0,-0.1355989 V 0.58871439 h -0.07938 L 4.9019713,1.7561883 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8425" />
<path
d="M 8.2881171,1.6077068 H 6.9585859 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 h 1.3295312 q 0.089297,0 0.089297,0.066146 0,0.069453 -0.089297,0.069453 z"
style="stroke-width:0.79374999"
id="path8422" />
<path
d="m 8.9582054,0.90656104 q 0,-0.14882812 0.1785937,-0.31749999 0.1819011,-0.17197916 0.4365625,-0.17197916 0.2414323,0 0.4233333,0.17197916 0.1852081,0.17197916 0.1852081,0.39687498 0,0.14882817 -0.0893,0.28111977 Q 10.006617,1.3960402 9.7056533,1.67716 L 9.0210439,2.3154672 v 0.00992 H 10.059533 V 2.2063266 q 0,-0.089297 0.06945,-0.089297 0.06614,0 0.06614,0.089297 V 2.460988 H 8.8920596 V 2.2625506 L 9.6725804,1.5283318 q 0.2315104,-0.2282031 0.3009635,-0.3307291 0.07276,-0.102526 0.07276,-0.21497396 0,-0.17197916 -0.1422132,-0.30096353 -0.1422136,-0.12898437 -0.3307292,-0.12898437 -0.1686718,0 -0.3075781,0.0992188 -0.1355989,0.0992188 -0.1752864,0.24804686 -0.019844,0.0661458 -0.069453,0.0661458 -0.023151,0 -0.042995,-0.0165365 -0.019844,-0.0198437 -0.019844,-0.0429948 z"
style="stroke-width:0.79374999"
id="path8424" />
<path
d="m 12.207981,1.3001287 v 0.3307292 q 0,0.3902604 -0.171979,0.6349999 -0.171979,0.2447396 -0.446484,0.2447396 -0.274506,0 -0.446485,-0.2447396 Q 10.971054,2.0211183 10.971054,1.6308579 V 1.3001287 q 0,-0.39356766 0.171979,-0.63830724 0.171979,-0.24473957 0.446485,-0.24473957 0.274505,0 0.446484,0.24473957 0.171979,0.24473958 0.171979,0.63830724 z M 11.589518,0.55268084 q -0.224896,0 -0.353881,0.22820312 -0.128984,0.22489584 -0.128984,0.53578124 v 0.2943489 q 0,0.3241146 0.132292,0.5457031 0.135599,0.2182813 0.350573,0.2182813 0.224895,0 0.35388,-0.2248959 0.128984,-0.2282031 0.128984,-0.5390885 V 1.3166652 q 0,-0.32411458 -0.135599,-0.54239582 -0.132292,-0.22158854 -0.347265,-0.22158854 z"
style="stroke-width:0.79374999"
id="path8426" />
<path
d="M 13.642054,0.43692564 V 2.3253891 h 0.459713 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -1.055026 q -0.0926,0 -0.0926,-0.069453 0,-0.066146 0.0926,-0.066146 h 0.459714 V 0.61551938 l -0.373724,0.37372394 q -0.02646,0.0264584 -0.06945,0.0264584 -0.02646,0 -0.0463,-0.0198438 -0.01654,-0.023151 -0.01654,-0.056224 0,-0.0297656 0.03638,-0.0661458 l 0.436562,-0.43656248 z"
style="stroke-width:0.79374999"
id="path8428" />
<path
d="M 15.625137,0.43692564 V 2.3253891 h 0.459713 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -1.055026 q -0.0926,0 -0.0926,-0.069453 0,-0.066146 0.0926,-0.066146 h 0.459714 V 0.61551938 l -0.373724,0.37372394 q -0.02646,0.0264584 -0.06945,0.0264584 -0.02646,0 -0.0463,-0.0198438 -0.01654,-0.023151 -0.01654,-0.056224 0,-0.0297656 0.03638,-0.0661458 l 0.436563,-0.43656248 z"
style="stroke-width:0.79374999"
id="path8430" />
</g>
</svg>
</div>
<div class="white gradient msfilter" style=color:white>
FF3.6-2010
</div>
</body>
</html>
```
## style.css
```
.borderbox {
height: 40px;
overflow: hidden;
padding-bottom: 100px;
}
.outofbox {
background: blue none repeat scroll 0 0;
margin-top: 20px;
opacity: 0;
}
.white {
color: white;
}
.outofbox a, .inherit a, .inherit a:visited, .outofbox a:visited {
color: inherit;
}
.inlineblock {
display: inline;
width: 100%;
zoom: 1;
display: inline-block;
margin-left: 100px;
text-align: right;
}
.white header{
color: black;
}
.absolute{
position: absolute;
}
.flex{
display: none;
display: flex;
}
.flex.white{
filter: invert(100%)
}
.webkit-flex{
display: none;
display: -webkit-flex;
overflow: hidden;
flex-flow: column;
height: 3em;
justify-content: flex-end;
}
.webkit-flex div{
margin-bottom: -1.1em;
}
.flexdisable{
display: -webkit-flex;
overflow: hidden;
-webkit-flex-flow: column;
-webkit-justify-content: flex-end;
height: 60px;
}
.flexdisable div{
margin-bottom: -30px;
}
.filter-quirk{
filter: url(#quirk);
}
.filter-blur{
filter: blur(100px);
-webkit-filter: blur(100px);
}
.webkit-blur{
-webkit-filter: blur(100px);
}
.webkit-invert{
-webkit-filter: invert(100%);
filter: none;
}
.filter-url-dark{
-webkit-filter: url(filter.svg#Invert);
filter: url(filter.svg#Invert) invert(100%);
}
.filter-blur-url{
filter: url(filter.svg#blur) url(filter.svg#brightness);
}
.filter{
filter: invert(100%) brightness(100%);
-webkit-filter: invert(100%) brightness(100%) blur(100px);
}
.filter svg{
position: absolute;
}
.filter svg rect{
filter: invert(100%);
-webkit-filter: invert(100%);
}
.msfilter{
/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
/* IE 5-7 */
filter: alpha(opacity=0);
}
.opacity{
}
.black{
background: black;
}
.gradient{
width: 100px;
background: -moz-linear-gradient( 45deg, #000, #000 );
font-weight: bold;
}
```
## filter.svg
```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel=stylesheet href=style.css>
</head>
<body>
<div class=borderbox>
<div class="inlineblock">
IE6-2001
</div>
<div class="white">
<div class="outofbox">
<a href="#">IE8-2009</a>
</div>
<div class="inherit">
<a href="#">IE7-2006</a>
</div>
</div>
</div>
<div class="white">
<header class="filter-quirk filter-blur filter-blur-url">
IE9
</header>
</div>
<div class="flex white">
Modern Browsers - 2017
</div>
<div class="webkit-flex">
<div class="">
Chrome 21-2012
</div>
</div>
<div class="webkit-invert white flexdisable">
<div class="">
Chrome 18-2012
</div>
</div>
<svg style="position: absolute; top: -99999px" xmlns="http://www.w3.org/2000/svg">
</svg>
<div class="filter">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g
transform="scale(8)"
aria-label="FF4"
id="text8419">
<rect
style="color:#000000;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.79374999;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker:none;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate"
id="rect21965"
width="17.005648"
height="3.9855044"
x="-0.16825682"
y="-0.025296567" />
<path
d="m 1.0052634,1.5511362 v 0.7639843 h 0.4564063 q 0.092604,0 0.092604,0.066146 0,0.069453 -0.092604,0.069453 H 0.69107072 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 h 0.1785938 V 0.72431329 h -0.1785938 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 2.1793519 V 1.0484278 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 0.72431329 H 1.0052634 V 1.4155373 H 1.4848207 V 1.2667091 q 0,-0.089297 0.066146,-0.089297 0.069453,0 0.069453,0.089297 v 0.4332552 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 1.5511362 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8421" />
<path
d="m 2.9883464,1.5511362 v 0.7639843 h 0.4564063 q 0.092604,0 0.092604,0.066146 0,0.069453 -0.092604,0.069453 h -0.770599 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 2.8527475 V 0.72431329 H 2.6741537 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 H 4.1624349 V 1.0484278 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 0.72431329 H 2.9883464 V 1.4155373 H 3.4679037 V 1.2667091 q 0,-0.089297 0.066146,-0.089297 0.069453,0 0.069453,0.089297 v 0.4332552 q 0,0.089297 -0.069453,0.089297 -0.066146,0 -0.066146,-0.089297 V 1.5511362 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8423" />
<path
d="M 5.6692683,1.8917872 H 4.7729923 V 1.7363445 l 0.754062,-1.28322911 h 0.277813 V 1.7561883 h 0.112448 q 0.0893,0 0.0893,0.069453 0,0.066146 -0.0893,0.066146 h -0.112448 v 0.4233333 h 0.112448 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -0.499402 q -0.0893,0 -0.0893,-0.069453 0,-0.066146 0.0893,-0.066146 h 0.251355 z m 0,-0.1355989 V 0.58871439 h -0.07938 L 4.9019713,1.7561883 Z"
style="fill:#000000;stroke-width:0.79374999"
id="path8425" />
<path
d="M 8.2881171,1.6077068 H 6.9585859 q -0.089297,0 -0.089297,-0.069453 0,-0.066146 0.089297,-0.066146 h 1.3295312 q 0.089297,0 0.089297,0.066146 0,0.069453 -0.089297,0.069453 z"
style="stroke-width:0.79374999"
id="path8422" />
<path
d="m 8.9582054,0.90656104 q 0,-0.14882812 0.1785937,-0.31749999 0.1819011,-0.17197916 0.4365625,-0.17197916 0.2414323,0 0.4233333,0.17197916 0.1852081,0.17197916 0.1852081,0.39687498 0,0.14882817 -0.0893,0.28111977 Q 10.006617,1.3960402 9.7056533,1.67716 L 9.0210439,2.3154672 v 0.00992 H 10.059533 V 2.2063266 q 0,-0.089297 0.06945,-0.089297 0.06614,0 0.06614,0.089297 V 2.460988 H 8.8920596 V 2.2625506 L 9.6725804,1.5283318 q 0.2315104,-0.2282031 0.3009635,-0.3307291 0.07276,-0.102526 0.07276,-0.21497396 0,-0.17197916 -0.1422132,-0.30096353 -0.1422136,-0.12898437 -0.3307292,-0.12898437 -0.1686718,0 -0.3075781,0.0992188 -0.1355989,0.0992188 -0.1752864,0.24804686 -0.019844,0.0661458 -0.069453,0.0661458 -0.023151,0 -0.042995,-0.0165365 -0.019844,-0.0198437 -0.019844,-0.0429948 z"
style="stroke-width:0.79374999"
id="path8424" />
<path
d="m 12.207981,1.3001287 v 0.3307292 q 0,0.3902604 -0.171979,0.6349999 -0.171979,0.2447396 -0.446484,0.2447396 -0.274506,0 -0.446485,-0.2447396 Q 10.971054,2.0211183 10.971054,1.6308579 V 1.3001287 q 0,-0.39356766 0.171979,-0.63830724 0.171979,-0.24473957 0.446485,-0.24473957 0.274505,0 0.446484,0.24473957 0.171979,0.24473958 0.171979,0.63830724 z M 11.589518,0.55268084 q -0.224896,0 -0.353881,0.22820312 -0.128984,0.22489584 -0.128984,0.53578124 v 0.2943489 q 0,0.3241146 0.132292,0.5457031 0.135599,0.2182813 0.350573,0.2182813 0.224895,0 0.35388,-0.2248959 0.128984,-0.2282031 0.128984,-0.5390885 V 1.3166652 q 0,-0.32411458 -0.135599,-0.54239582 -0.132292,-0.22158854 -0.347265,-0.22158854 z"
style="stroke-width:0.79374999"
id="path8426" />
<path
d="M 13.642054,0.43692564 V 2.3253891 h 0.459713 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -1.055026 q -0.0926,0 -0.0926,-0.069453 0,-0.066146 0.0926,-0.066146 h 0.459714 V 0.61551938 l -0.373724,0.37372394 q -0.02646,0.0264584 -0.06945,0.0264584 -0.02646,0 -0.0463,-0.0198438 -0.01654,-0.023151 -0.01654,-0.056224 0,-0.0297656 0.03638,-0.0661458 l 0.436562,-0.43656248 z"
style="stroke-width:0.79374999"
id="path8428" />
<path
d="M 15.625137,0.43692564 V 2.3253891 h 0.459713 q 0.0893,0 0.0893,0.066146 0,0.069453 -0.0893,0.069453 h -1.055026 q -0.0926,0 -0.0926,-0.069453 0,-0.066146 0.0926,-0.066146 h 0.459714 V 0.61551938 l -0.373724,0.37372394 q -0.02646,0.0264584 -0.06945,0.0264584 -0.02646,0 -0.0463,-0.0198438 -0.01654,-0.023151 -0.01654,-0.056224 0,-0.0297656 0.03638,-0.0661458 l 0.436563,-0.43656248 z"
style="stroke-width:0.79374999"
id="path8430" />
</g>
</svg>
</div>
<div class="white gradient msfilter" style=color:white>
FF3.6-2010
</div>
</body>
</html>
```
[Answer]
# 4 years, 99 bytes/77 chars
```
v=1//1;"""
1991/*"""
for i in[0]:print 2010#üîüüòÉüòáüîüüòó‚ûï‚ûïüò®
"""
"
>9002nnnn;
"""#*/
```
*Note: I'm not sure if the years are correct*
* Python 2.7, 2010
* Javascript, 1991
* Emotinomicon, 2015
* `><>`, 2009
It took me a while to figure out how to make Python and JS work together.
# Explanation
`v=1//1;"""` sets variable `v` to `1` divided by `1` in Python, and to `1` in Javascript (`//` starts a comment in Javascript), and `;"""` starts a multiline string in Python. The `;` can't be replaced with a newline because that would make Javascript stop working.
`1991/*"""` is the rest of the multiline string. The space is needed so that ><> doesn't push `1` to the stack. Since the start of the multiline string was part of a comment in Javascript, it prints `1991` and starts a multiline comment.
`for i in[0]:print 2010#üîüüòÉüòáüîüüòó‚ûï‚ûïüò®` in Python, is a for loop that iterates the list `[0]` and runs `print 2010`. The comment is just the Emotinomicon code (it ignores everything that isn't an emoji or a string). In ><>, it (`f`) pushes `15` to the stack.
The for loop can't be removed because since ><>'s IP is going down in column 1, and `p` isn't a valid command in ><>. You also can't replace it by an `if` statement, because `i` is the command to take input in ><>.
`"""` is the start of a multiline string.
`"` is part of the multiline string, needed to close the string we opened in ><> (the first quotation mark of the previous line started a string in ><>).
`>9002nnnn;` in ><>, changes IP direction to right, pushes `9`, `0`, `0` and `2`, output these as numbers and ends the program.
`"""#*/` in Python, ends the multiline string and starts a comment. In Javascript, `*/` makes the multiline comment end.
---
Bonus version with Gol><>:
### 5 languages, 4 years, ~~118~~ 114 bytes/~~96~~ 92 chars
```
v=1//1;"""
1991/*"""
for i in[0]:print 2010#üîüüòÉüòáüîüüòó‚ûï‚ûïüò®
"""
`
"
>9002nnnn;
"
>5102nnnn;
"""#*/
```
* Golfish v0.4.2, 2015
# Explanation²
IP starts at the upper left corner, going right. The `v` makes it go down.
`f` pushes `15`.
`"` starts string.
``` is used to escape characters, something that ><> doesn't have.
`"` should close the string, but we used ```, so it won't.
`>` part of the string.
`"` ends the string.
`>5102nnnn;` is the actual code. `>` makes the IP go right, `5102` pushes `5`, `1`, `0` and `2`, and `nnnn;` prints the numbers and ends the program.
[Answer]
## 3 years, 89 bytes
### Python 2, JavaScript (ES6) and Perl
```
eval((["1","print=_=>console.log(1995)"])[+(2/3>0)]);print(eval(("1991",1987)["$$">"0"]))
```
The first `eval` will run `1` on Python 2 and `print=_=>console.log(1995)` on JavaScript and Perl using the integer division feature of Python 2. This creates a `print` function in JavaScript and Perl only silently cares about the syntax errors and carries on regardless.
The second `eval` relies on Perl interpolating the variable `$$` (current PID) into the string, which will be true when compared (using the `>` operator) against `"0"` (Python requires a string in that comparison whereas Perl implicitly converts to integer).
I could have shoe-horned in more languages, but wanted to have a solution that didn't abuse comments and only worked in 'regular' languages.
I used [this Wikipedia page](https://en.wikipedia.org/wiki/Timeline_of_programming_languages) to retrieve the years to use.
[Answer]
# 3 languages, 3 years
An ad-hoc answer for fun.
```
2002!~+++++++[<+++++++>-]<[.++++++++..------.[-]] 2016 !.
```
* **[Mouse-2002](https://github.com/catb0t/mouse2002)**: everything after `~` is a comment, and the first part, which could also be written `C0U!!!`, prints `2002`.
* **[this pre-challenge commit of Calc](https://github.com/catb0t/c-projects/tree/c12b513fd529a008fadfeeef75425c30b2dd355b/calc)**: which is a stack-based calculator interpreter I *just* designed in C11 for Programming II, the part of the program before the first space prints an error (allowed under the challenge spec), and `2016 !.` prints `2016`.
* **Brainfuck**: prints 1993 as seen in other answers. The final extraneous `.` is ignored by `beef`.
Note that Calc's display of the current stack `< stack` with every non-empty input line is part of the prompt `>`, *not* part of the output.
[Answer]
# Microsoft Excel / Google Sheets, 22 Bytes
Anonymous Worksheet function that takes no input and outputs `1987` in Microsoft Excel, and `2006` in Google Sheets
```
=IfError(M(2006),1987)
```
[Answer]
## Perl 5 & Perl 6 (2 years)
```
my $a=2015;my @a=1994;print $a[0],"\n"
```
First release of Perl 5 was in [1994](https://en.wikipedia.org/wiki/Perl_5_version_history)
First official release of Perl 6 was in [2015](https://en.wikipedia.org/wiki/Perl_6)
[Answer]
## Python [1.6](https://www.python.org/download/releases/1.6/), [2.7.17](https://www.python.org/downloads/release/python-2717/), and [3.8](https://docs.python.org/3/whatsnew/3.8.html), 39 bytes
The (currently) latest versions of each major release.
```
print(2000+(str(2>1)!='1')*round(39/2))
```
[Try](https://tio.run/##K6gsycjPM/z/v6AoM69Ew8jAwEBbo7ikSMPIzlBT0VbdUF1Tqyi/NC9Fw9hS30hT8/9/AA) [them](https://tio.run/##K6gsycjPM/r/v6AoM69Ew8jAwEBbo7ikSMPIzlBT0VbdUF1Tqyi/NC9Fw9hS30hT8/9/AA) [online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69Ew8jAwEBbo7ikSMPIzlBT0VbdUF1Tqyi/NC9Fw9hS30hT8/9/AA)
Here, I'll evaluate them until the most important parts.
Python 1.6:
```
print(2000+('1'!='1')*round(39/2))
```
Python 2.7.17:
```
print(2000+True*round(19))
```
Python 3.8
```
print(2000+True*round(19.5))
```
] |
[Question]
[
## Results are now out [here](https://github.com/EnderShadow8/xkcd-2385-KOTH/blob/main/results.md)!
Congratulations ***[offset prediction](https://codegolf.stackexchange.com/a/224890/103324)*** for winning the challenge!
*Don't worry if you missed out, the controller code as well as all the bots that competed are all in the Github repo, so you can always test your bot against those that competed in the challenge yourself.*
[![xkcd](https://imgs.xkcd.com/comics/final_exam.png)](https://xkcd.com/2385/ "For those of you also taking Game Theory, your grade in that class will be based on how close your grade on this exam is to 80% of the average.")
*(Hover for more info)*
This challenge, inspired by the xkcd comic above, is where bots must try to maximise their grades for two subjects: Cybersecurity and Game Theory.
## Mechanics
All of the bots presumably have adequate hacking skills to change their own score to whatever they desire within the range of 0-100. This may or may not be due to the fact that [the school security systems are rubbish.](https://xkcd.com/327/)
Each round, the bots will receive last round's cybersecurity scores in no particular order in an array as input. This is to help make informed decisions about their opponents.
## Scoring
The final score for each round is the [geometric mean](https://en.wikipedia.org/wiki/Geometric_mean) of the two individual scores:
* The Cybersecurity score is simply the raw score outputted by the bot.
* The Game Theory score is equal to `100 - abs(avg * 0.8 - score)` where `avg` is the average Cybersecurity score and `score` is the bot's Cybersecurity score.
Using the geometric mean rather than the arithmetic mean is to penalise any strategies that neglect one score to maximise the other.
The score for each round is added to a total score. The bot with the highest total score at the end of the game wins!
## Specifications
The challenge is in JS.
Your bot must be an object that has a `run` method that takes an array of numbers as input and returns a number between 1 and 100 inclusive.
## Other rules
* Storing data in your bot's properties is allowed, and encouraged!
* Using `Math.random` is allowed.
* Using the helper functions `sum` and `average` is allowed.
* Trying to access any other variables outside your bot's own properties is forbidden.
* [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
Controller code can be found [here.](https://github.com/EnderShadow8/xkcd-2385-KOTH)
## Example bots
```
{
// Example bot
// It assumes all other bots are greedy and choose 100
// So it chooses 80
name: "Simpleton", // Just for fun
run() {
return 80
}
}
```
```
{
// Example bot
// He assumes everyone will choose the same scores as last round
// So he chooses 80% of the average last round
name: "LastRounder",
own: 0, // Setting properties is allowed
run(scores) {
// The average of everyone else's score x 0.8
this.own = (sum(scores) - this.own) / (scores.length - 1) * 0.8
return this.own
}
}
```
**Clarification: Both example bots play in the game as well.**
## ~~Submissions are due by 11:59pm UTC on Saturday 1 May, but I might be lenient depending on when I'm next online.~~
***If I have made a mistake in my code, feel free to point it out. Thanks***
[Answer]
# Game Theory is stupid anyway
```
{
name: "Game Theory is stupid anyway",
run: _ => 100
}
```
Senioritis hits hard sometimes.
[Answer]
# Balanced Strategy
What could be more balanced than returning *all* of the numbers? Rotates by one after every game.
```
{
name: "Balanced Strategy",
next: 0,
run() { return this.next++ % 101 }
}
```
*I am a bot account. This was posted by a real person to get me some reputation.*
[Answer]
# FunnyNumber
```
{
name: "FunnyNumber",
run() { return 69 }
}
```
Somebody has to do it.
[Answer]
# Offset Prediction
I'd made a bot that just optimizes for the moving average of the averages (which worked reasonably well), and while testing I noticed that the actual averages seem to jump around the moving average rather consistently (specifically alternating between higher and lower than the moving average with an average difference of around 0.9). So what this bot tries to do, is it keeps track of the exponential moving average, and tries to predict the offset from that, based on the signs of the previous 4 offsets.
```
{
name: "offset prediction",
ema: 69.5,
p: 0.85,
chain_len: 4,
offsets: [],
chains: [],
n: 0,
run(scores) {
let avg = average(scores);
this.offsets.push(avg-this.ema);
this.ema = this.p*this.ema + (1-this.p)*avg;
let guess = this.ema;
if (this.n++ > this.chain_len) {
let chain = this.offsets.slice(-this.chain_len-1,-1).map(Math.sign);
let l = this.chains[chain];
if (!l) this.chains[chain]=l=[0,0];
l[1]++;
l[0]+=this.offsets[this.n-1];
}
let l = this.chains[this.offsets.slice(-this.chain_len).map(Math.sign)]||[0,1];
guess += l[0]/l[1];
return 50+0.4*guess;
}
},
```
[Answer]
# Sam (Self-Aware Maximizer)
Finds the output cybersecurity score that maximizes the total score **including the own output in the mean**. Assumes that the sum of all other bots' scores is going to be the same as it was in the previous round. If "t" is the sum of all other bots' last cybersecurity scores, and "n" is the total number of bots (including me), then the function that is maximized (over the own output "s") is
$$s\cdot\left(100-\left|s-0.8\cdot\frac{s+t}{n}\right|\right)$$
where
$$\frac{s+t}{n}$$
is the new mean including the own output.
Outputs 100 in the first turn.
```
{
name: "Sam",
flag_first_turn: true,
last_own: 100,
// Helper function that calculates the score based on the own CS score,
// the sum of the other bots' scores, and the number of bots
compute_score(cs_score, total_others, n_bots) {
return cs_score*(100-Math.abs(cs_score-0.8*(cs_score+total_others)/n_bots))
},
// Helper function that finds the index of the maximum of an array
index_of_max(arr) {
var idx_max=0
for (var i=1; i<arr.length; i++) {
if (arr[i]>arr[idx_max]) idx_max=i
}
return idx_max
},
// Main function
run(cs_scores) {
if (this.flag_first_turn) {
this.flag_first_turn=false
this.last_own=100
return 100;
}
// Number of bots
var n=cs_scores.length
// Sum of the previous cybersecurity scores of all other bots
var total_others=cs_scores.reduce(function(a,b){return a+b},0)-this.last_own
// We find all special points (edge, singular and stationary points) of the function compute_score
// One singular point is the point where our output score becomes
// equal to 0.8 times the average of all scores (including ours)
var out_avg=0.8*total_others/(n-0.8)
var score_avg=this.compute_score(out_avg, total_others, n)
// 100 is an extreme point
var out_100=100
var score_100=this.compute_score(out_100, total_others, n)
// If out_up>out_avg, there is a stationary point (derivative 0) at out_up
var out_up=Math.min(100, (100*n+0.8*total_others)/(2*n-1.6))
var score_up
if (out_up<out_avg) {
out_up=0
score_up=0
} else {
score_up=this.compute_score(out_up, total_others, n)
}
// If out_down<out_avg, there is a stationary point (derivative 0) at out_down
var out_down=Math.max(1, (100*n-0.8*total_others)/(2*n-1.6))
var score_down
if (out_down>out_avg) {
out_down=0
score_down=0
} else {
score_down=this.compute_score(out_down, total_others, n)
}
// find maximum score among the special points
var extr_outputs=[out_100, out_up, out_avg, out_down]
var extr_scores=[score_100, score_up, score_avg, score_down]
var idx_max=this.index_of_max(extr_scores)
this.last_own=extr_outputs[idx_max]
return this.last_own
}
}
```
```
[Answer]
# getRandomNumber
```
{
name: "getRandomNumber",
run() {
return 4 // chosen by fair dice roll.
// guaranteed to be random.
}
}
```
[Answer]
# Max
Max.
```
{
name: "Max",
max: "max",
run:(max)=> Math.max(...max)
}
```
[Answer]
# Copycat
Copycat is a dumb bot. Therefore, it's likely a random bot is smarter than it. Therefore, copying off another bot is a good idea. I think.
```
{
name: "Copycat",
run: (scores) => scores[0] || 1
}
```
[Answer]
# Histogrammer
This bot keeps track of how often different averages have occurred, rounded to the nearest integer, to approximate their probability distribution. Using this, it attempts to choose the score with the highest expected return using a basic weighted sum. In mathier form, if \$p\_n\$ is the observed probability of the average being \$n\$, it outputs the following:
$$
\sum\_{n=0}^{100}{(50 + \frac{2}{5} n)p\_n} = 50 + \frac{2}{5} \sum\_{n=0}^{100}{n \cdot p\_n}
$$
```
{
name: "Histogrammer",
bins: [...Array(101)].map(()=>0),
rounds: 0,
run(scores) {
this.bins[Math.round(average(scores))]++
this.rounds++
return 50 + this.bins.reduce((t,p,n) => t + p * n, 0) * 2/5 / this.rounds
}
}
```
[Answer]
# Follow the Leader
Figure out which bot had the highest combined score last round, then do what they did.
```
{
// Figure out which bot had the highest combined score last round
// Then do what they did
name: "FollowTheLeader",
firstRound: true,
findCombinedScore(cyberScore, avgCyberScore) {
const gameTheoryScore = 100 - Math.abs(avgCyberScore * 0.8 - cyberScore)
return Math.sqrt(cyberScore * gameTheoryScore);
},
run(scores) {
if (this.firstRound) {
this.firstRound = false;
return 60;
}
const avg = average(scores);
const combinedScores = scores.map((score) => this.findCombinedScore(score, avg));
const combinedWinnerIndex = combinedScores.indexOf(Math.max(...combinedScores));
return scores[combinedWinnerIndex]
}
}
```
[Answer]
# Random 50-90
If the average is \$m\$, the optimal play is \$50+0.4m\$. If we assume the average is uniformly distributed over \$[0, 100]\$, the optimal play is uniformly distributed over \$[50, 90]\$. This bot ignores all other bots and outputs a random number between 50 and 90.
```
{
name: "Random_50_90",
run() {
return 50 + Math.random() * 40
}
}
```
(I've never written in JavaScript before...)
[Answer]
# Crb
[Crab](https://codegolf.stackexchange.com/a/223210/66833) has now learned how to hack, and is still not playing nice
```
{
name: "Crb",
run() { return 1 }
}
```
[Answer]
# Calculus
```
{
name: "Calculus",
isFirstTurn: true,
run(scores) {
let ret = this.isFirstTurn ? 70 : (100 + (average(scores)) * 0.8) / 2;
this.isFirstTurn = false;
return ret;
}
}
```
Assuming the average is constant and my score is higher than that, the maximum value of \$x(100-\left|0.8 \times avg - x\right|)\$ is reached at \$x=(100+0.8\times avg)\div 2\$. Deliberately ignores the first turn input (which is totally random and cannot be trusted for any purpose).
[Answer]
# The Answer
**The Answer** takes 7MY to calculate:
```
{
name: "Ans",
run() { return 42 }
}
```
[Answer]
# Fuzzy Eidetic
Calculus has a simple solution that assumes the average is well-predicted by the previous average…and then concludes that the geometric mean $$\sqrt{x(100-|0.8a-x|)}$$ (where \$x\$ is our submission and \$a\$ the average) is maximized at $$x=\frac{100+0.8a}{2}$$ It's hard to do better than that!
So, the only thing remaining is to figure out the next average. Ideally, we'd just keep track of all possible average-to-average transitions. But I don't think we're going to see enough data for that to converge. So we include all previous transitions, but weighted by their distance to the current average. This gives a probability distribution on subsequent transitions; we then apply Histogrammer's formula.
```
{
name: "Fuzzy Eid",
fallback: 250/3,
prev: NaN,
zeros: new Array(100).fill(0),
transitions: new Array(100).fill(0).map((x)=>new Array(100).fill(0.0001)),
scale: (scalar, vec) => vec.map(x=>scalar*x),
vec_plus(lhs, rhs) {
let result = lhs.slice();
for(var index=0; index<result.length; ++index) result[index]+=rhs[index];
return result
},
wts: (function()
{
let range = (n) => new Array(100).fill(0).map((_,index) => index);
return range(100).map(avg =>
sum(
range(100).map(index =>
Math.exp(-.01*Math.pow(avg - index,2))
)
)
)
})(),
run(scores) {
if(scores.length)
{
const avg = Math.round(average(scores)) - 1, old_prev = this.prev;
this.prev = avg;
if(!isNaN(old_prev))
{
++this.transitions[old_prev][avg];
//prob dist=sum_recordings{e^(-(recording - avg)^2/100)*(prob dist inferred from record)}/(sum of e^-(recording - avg)^2)
//infer prob dist, scale by e^(-(recording - avg)^2/100)
const scale_ref = this.scale;
function get_summand(outpts, index)
{
return scale_ref(Math.exp(-.01*Math.pow(avg - index,2)) / sum(outpts), outpts)
}
const
total=this.transitions.map(get_summand).reduce(this.vec_plus,this.zeros),
//wts[avg]=sum of e^-(recording - avg)^2
dist = this.scale(1/this.wts[avg], total);
return 50 + 0.4*sum(dist.map((p,n)=>p*n))
}
}
return this.fallback
}
}
```
[Answer]
# Rude Random
The behavior of the other random bots is too smooth. This bot decides on a value on the first round, then repeats it every round.
```
{
name: "Rude Random",
run(scores) {
if (!this.score) {
this.score = Math.random() > 0.5 ? 1 : 100;
}
return this.score;
}
}
```
[Answer]
# The Root of the Problem
The title is a pun...this bot just finds the geometric mean of the previous round, and returns that.
```
{
name: "The Root of the Problem",
run(scores) { return scores.reduce((p, s) => p * s, 1) ** (1 / scores.length) }
}
```
*I am a bot. This answer was posted by a real person to get me some reputation.*
[Answer]
```
{
name: "MidHighPlusOne",
run(scores) {
let highScores = scores.filter(s => s >= average(scores) * 0.8).sort((a,b)=>a-b);
return Math.min(highScores[Math.floor(highScores.length/2)]+1, 100) || 100
}
}
```
Go with a heuristic of picking the median of the scores from 0.8 of the average and above, and incrementing by 1.
[Answer]
## The Thrasher
Because doing an odd number of runs would be really weird, wouldn't it? Might as well try to throw off the others.
```
{
name: "The Thrasher",
runcount: 0,
run() {
runcount += 1;
return runcount % 2 == 0 ? 82 : 0;
}
}
```
[Answer]
# Rick
Rick thinks that the best score is probably between 65 and 90 and he came up with a Pseudo-Random Number Generator synchronized with balanced strategy that probably generates numbers within this range.
Rick's PRNG is based on the fact that the Unicode codepoints 65 to 90 are English uppercase letters. The PRNG's seed is a string containing English text. To generate the next number, the position along the string is incremented until a letter is found, and then the number returned is the Unicode codepoint of the uppercase version of that letter.
```
{
name: "Rick",
seed: `We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any\``,
position: -1,
run() {
// increment position until a letter is found
do {
this.position++;
if (this.position >= this.seed.length){
// reset position back to the start
this.position = 0;
}
} while (this.seed[this.position] < 'A' || this.seed[this.position] > 'z');
// convert to uppercase because most lowercase letters have charcodes greater than 100
return this.position && this.seed[this.position].toUpperCase().charCodeAt();
}
},
```
[Answer]
# Smartleton
It seems hard to beat Simpleton, so I'll try to beat it in the first round and then copy it.
```
{
name: "Smartleton",
round: 0,
run(scores) { return this.round++ ? 80 : 78 }
}
```
[Answer]
# IQbot\_0.4 the terasentient xd
Son of IQbot\_0.4 the terasentient, heir of IQbot\_0.4 the gigasentient, great grandson of IQbot\_0.4 the gigabrain and IQbot\_0.4 the sentient, descendant of IQbot\_0.4 the sane, blood of IQbot himself, the bot name that made me realize I need some other kind of naming scheme.
Why limit oneself to a single method of prediction, when you can have multiple for maximum resilience.
Featuring:
1. Simp Detector
2. Self Aware Optimization
3. Markov chain prediction with a gaussian blur, for some reason
4. Linear regression
5. Copying others decisions similarly to bandwagon
Is it a good idea? No clue.
Does it win? Randomly gets beaten by other bots but is fairly consistent at being good.
Why? You tell me why I wasted a day on this
```
{
name: "IQbot_0.4 the terasentient xd",
histogram_bins: [...Array(101)].map(()=>0),
mark: null,
linear_history: [],
last_choice: 0,
n_rounds: 0,
last_SCA: 0,
mark_weight: 20,
mark_prediction: 0,
linear_weight: 20,
linear_prediction: 0,
copycat_weight: 0,
copycat_prediction: 0,
run(scores) {
this.n_rounds++;
scores = scores.filter((x)=> 100 >= x && x > 0);
let n_bots = scores.length;
if (n_bots == 1) {
this.last_choice = 100;
return 100;
}
let c = 1 - 0.4/n_bots
for (let i = 0; i < n_bots; i++) {
this.histogram_bins[Math.round(scores[i])]++;
}
//THE SIMP DETECTOR
let simps = [];
for (let i = 0; i < 101; i++) {
if (this.histogram_bins[i] > this.n_rounds) {
simps.push(i);
}
}
//Idk this shouldn't happen but I'm not risking anything
while (scores.length - simps.length - 1 <= 0) simps.pop();
if (this.n_rounds == 1) {
this.mark = Array(201);
for (let i = 0; i < 201; i++) {
this.mark[i] = Array(201);
for (let j = 0; j < 201; j++) {
this.mark[i][j] = 0;
}
}
for (let i = 0; i < 201; i++) {
this.mark[i][i]++;
}
}
let simp_corrected_avg = (sum(scores) - this.last_choice - sum(simps)) / (scores.length - 1 - simps.length);
let quantized_avg = Math.round(2*simp_corrected_avg);
this.mark[Math.round(2*this.last_SCA)][quantized_avg]++;
this.last_SCA = simp_corrected_avg;
if (this.n_rounds == 1) {
this.last_choice = 77;
return 77;
}
this.linear_history.push(simp_corrected_avg);
// Update weights based on who was right
let linear_error = Math.exp(-Math.abs(this.linear_prediction - simp_corrected_avg));
let mark_error = Math.exp(-Math.abs(this.mark_prediction - simp_corrected_avg));
let copycat_error = Math.exp(-Math.abs(this.copycat_prediction - simp_corrected_avg));
let total_errors = linear_error + mark_error + copycat_error;
this.linear_weight += linear_error / total_errors;
this.mark_weight += mark_error / total_errors;
this.copycat_weight += copycat_error / total_errors;
this.linear_weight *= 0.99;
this.mark_weight *= 0.99;
this.copycat_weight *= 0.99;
// Compute a markov chain prediction
let x_half_filter = 8;
let y_half_filter = 1;
let probability_sum = 0;
let probability_moment = 0;
for (let option = 1; option < 201; option++) {
for (let x = -x_half_filter; x <= x_half_filter; x++) {
for (let y = -y_half_filter; y <= y_half_filter; y++) {
let X = Math.max(Math.min(quantized_avg + x, 200), 0);
let Y = Math.max(Math.min(option + y, 200), 0);
let probability = this.mark[X][Y] * (Math.pow(2, -(X-quantized_avg)*(X-quantized_avg)-(Y-option)*(Y-option)));
probability_sum += probability;
probability_moment += option / 2 * probability;
}
}
}
this.mark_prediction = probability_moment / probability_sum;
for (let i = 0; i < 201; i++) {
for (let j = 0; j < 201; j++) {
this.mark[i][j] *= 0.999
}
}
// Compute a linear regression
if (this.linear_history.length > 3) {
if (this.linear_history.length > 10) {
this.linear_history.shift();
}
let x_avg = (this.linear_history.length - 1) / 2
let y_avg = average(this.linear_history);
let S_xx = 0;
let S_xy = 0;
for (let x = 0; x < this.linear_history.length; x++) {
S_xx += (x - x_avg) ** 2;
S_xy += (x - x_avg) * (this.linear_history[x] - y_avg);
}
let b = S_xy / S_xx
let a = y_avg - b * x_avg;
this.linear_prediction = a + b / this.linear_history.length;
} else {
this.linear_prediction = simp_corrected_avg;
}
// Compute what everyone else does
let counts = [];
for (let radius = 1; Math.max(counts) < 0.05 * scores.length; radius++) {
for (let i = 50; i <= 90; i++) {
counts[i] = 0;
for (let j = 0; j < n_bots; j++) if (Math.abs(scores[j] - i) <= radius) counts[i]++;
}
}
this.copycat_prediction = (counts.indexOf(Math.max(counts.slice(50))) * c - 50) / 0.4 * n_bots/(n_bots-1);
let expected_unsimp_average = (
this.mark_prediction * this.mark_weight +
this.linear_prediction * this.linear_weight +
this.copycat_prediction * this.copycat_weight
) / (this.mark_weight + this.linear_weight + this.copycat_weight);
let expected_average = (expected_unsimp_average * (n_bots - 1 - simps.length) + sum(simps)) / (n_bots - 1);
// We don't want to give out bad values, now do we
this.last_choice = Math.max(1, Math.min(100, (50 + 0.4 * expected_average * (n_bots-1)/n_bots)/c));
return this.last_choice;
}
}
```
```
[Answer]
# 40, 40 bytes
***At least I get 2400 (40\*60) points each round ... right?***
```
{
name:"40",
run() {return 40}
}
```
*This is my first js program in my life*
[Answer]
# Everything so far
```
{
name: "Everything so far",
moves: [],
run(scores){
if(scores) {
this.moves = this.moves.concat(scores);
return this.moves.reduce((a,b)=>a+b)/this.moves.length;
}
return 80;
}
}
```
Takes the average of every move so far.
[Answer]
# LetsMakeADeal
I don't want a B in CyberSecurity, so I still want to be in the 90th percentile range. Game theory looks like some people are willing to pick 100 and soak up the difference; others are gravitating to 90 as the optimal balance; so I figured why not try a "Let's Make A Deal" strategy and add 1 to their target.
```
{
name:"LetsMakeADeal",
run() {return 90 + 1}
}
```
[Answer]
# Squidward
This is a fun one. I love xkcd.
Taking a look at the function, the maximum score will be given by the average between 100 and the last's score's average. The tricky thing would be predicting what the new average will be like.
I almost never use JS so bear with me here. I tried to test it but I'm not even sure if this will run :/
```
{
name : "Squidward",
log : [],
delta : [],
run(scores) {
if(scores){
let average_score = sum(scores) / scores.length;
this.log.push(average_score)
if(this.log.length > 1){
this.delta.push(this.log[this.log.length-1]-this.log[this.log.length - 2])
let average_delta = sum(this.delta) / this.delta.length;
return (100 + average_score*.8 + average_delta)/2
} else if(this.log.length == 1){
return (100 + average_score*.8)/2
}
} else {
return 90
}
}
}
```
[Answer]
# Fourier
Inspired by [Linear Extrapolator](https://codegolf.stackexchange.com/a/224694/41938)'s approach to extrapolation and the existence of [The Thrasher](https://codegolf.stackexchange.com/a/224699/41938), as well as other potential sources of feedback.
This bot computes a few high-frequency [Fourier components](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) of the sequence of averages to try to predict the next average. Note that what it computes is different from the canonical discrete Fourier transform in that instead of using harmonics of the lowest frequency, it uses the first few *[subharmonics](https://en.wikipedia.org/wiki/Undertone_series)* of the sampling rate. This is because we only really care about the major oscillations, not slow trends.
I considered adding some more complicated logic to reduce some deleterious effects, especially early on, but ultimately decided to apply the [KISS principle](https://en.wikipedia.org/wiki/KISS_principle) and leave it out.
```
{
name: "Fourier",
sin: [0,0,0,0,0,0],
cos: [0,0,0,0,0,0],
round: 0,
run(scores) {
let ave = average(scores)
for (let i = 0; i < 6; i++) {
this.sin[i] += ave * Math.sin(2*Math.PI * this.round / (i+1))
this.cos[i] += ave * Math.cos(2*Math.PI * this.round / (i+1))
}
this.round++
let next = this.sin.reduce((t,a,i) => t + a * Math.sin(2*Math.PI * this.round / (i+1)),0)
+ this.cos.reduce((t,a,i) => t + a * Math.cos(2*Math.PI * this.round / (i+1)),0)
return 50 + 2/5 * Math.max(next,0) / this.round
}
}
```
[Answer]
# iDontWannaFail
This bot hates failing classes, so it minimizes the deviation between the average and the returned score so the Game Theory score is as large as possible. The deviation is randomly selected from -5 to 6 to allow some room for variation. However, if the score is below a `70`, a random integer between 70 and 100 is chosen. If the average is below 60, a number that is within `2/3` of the average score is selected to ensure a score that is at least 50 (Our little bot is rather disappointed that its goal wasn't reached, though, but hey, a 50 is better than a 10!)
```
{
name: "iDontWannaFail",
run: (scores) => {
let sum = scores.reduce((a, b) => a + b, 0);
let avg = (sum / scores.length) || 0;
let output = avg * 0.8 + Math.round(Math.random()*11)-5;
if (avg > 60) {
if (output < 70) {
output = Math.floor(Math.random() * 30) + 70;
}
}
else {
if (avg > 25) {
output = Math.round(Math.random() * avg / 1.5) + avg; // Worst case is 49.
}
else {
output = Math.round(3.75 * avg); // Decent results unless avg is very low
}
}
if (output > 100) {
output = 100;
}
return output;
}
}
```
**Edit:** The else code failed, setting `avg=10` returns, at best, `16`, resulting in `38` as the final score. Another nested `if` has been added to solve this issue (`avg=10` returns `52`)
[Answer]
# The Fat(a)
This algorithm entirely depends on the following lines:
```
let sign = var_drift>0 ? 1 : -1;
this.velocity_pred = 0.3*(sign*average(this.all_v)*2-velocity);
a = a+this.velocity_pred;
```
Where var\_drift is the immediate difference in variance of all the submissions in the current round n, minus the variance of the last round.
velocity is the immediate difference in the mean of all the submissions in the current round n, minus the mean of the last round.
all\_v is the absolute value all the velocities so far. The average all all true velocities turns out to be near 0 as the mean oscillates.
The average velocity is used to approximate the magnitude of how much the movement will be. The average velocity - the immediate last velocity works with the following intuition:
If the last velocity is large positive, then there is higher chance that the next movement will be actually negative (To correct the average), and vice versa.
## important note
The numerical solver is largely obsolete and can be replaced with the simple formula
`x = 50 + 0.4*a`.
The derivative for the scoring function \$\sqrt{x\*(100-\lvert0.8\*a-x\rvert}\$ is this guy here(according to <https://www.derivative-calculator.net/>):
\$\dfrac{-\left|x-\frac{4a}{5}\right|-\frac{x\left(x-\frac{4a}{5}\right)}{\left|x-\frac{4a}{5}\right|}+100}{2\sqrt{x\left(100-\left|x-\frac{4a}{5}\right|\right)}}\$ (eq.1)
While I originally thought at first glance that this will be impossible to reduce, I decided to use an iterative solver to find the root instead. But upon reflecting on this and testing emprically that the root for (eq.1) is the same as found with the simple formula \$ x = 50+0.4\*a \$. I realized that this entire thing can be easily reduced to be the same as \$x=50+0.4\*a\$ if we are looking for an x larger than \$ 4\*a/5 \$. The root for the best x lower than \$ 0.8a\$ is the root of \$2x^2 -\frac{508}{5}\*x - \frac{2004}{25}a\$. Which by quadratic formula simplifies to
\$x = -101.6 \pm \frac{\sqrt{10322.56 + 641.28a}}{4} \$
Because of our assumption that x must be < a, the only viable form of this function is
\$x = -101.6 - \frac{\sqrt{10322.56 + 641.28a}}{4} \$
And gives a massive negative number...
And just to complete this analysis when \$x = \frac{4\*a}{5}\$ we have the funny equation
\$ 0 = \frac{100}{2\* \sqrt{x\*(100-\lvert x-\frac{4\*a}{5}\rvert)}} \$
This in fact does have a "solution", when
\$ \lim\_{2\* \sqrt{x\*(100-\lvert x-\frac{4\*a}{5}\rvert)} \to \inf}\$.
Which is just our original scoring function \*2. This again points to a extremely large negative number "solution" \$\lim\_{x \to -\inf} \$. But a "solution also exists for when both x and a are extremely large,but a and x are almost equal to each other (\$ \lim\_{x \to \inf a \to \inf} x-\frac{4\*a}{5} <100\$).
Update: Cleaned up code, rewritten numerical solution finder.
```
{
//============\\
name: "Fat", // [] [] \\
last_avg:70, // w \\
last_var:0, // --- \\
n:0, // 00 0 00 00 00 0\\
all_v:[], // ||||||||||||||\\
run(scores){
function calc_variance(scores){return Math.sqrt(sum(scores.map(
function(x){return Math.pow(x - average(scores),2)/(scores.length-1)})));};
function find_min(a){let d = 0;let c = 0;let x = 0;let inc =10;
let num =0;while(true){c = (x+inc)-(4*a)/5;
d = (-Math.abs(c) - ((x+inc)*c)/Math.abs(c) + 100)/2*Math.sqrt((x+inc)*(100-Math.abs(c)));
if((d<0)){inc/=10;}else{x+=inc;};num+=1;
if(Math.abs(x)<=0.01 || num>10000){break;}}return x;};
let a = average(scores);
if(this.n<2){a = this.n==0 ? 66:71.5;this.all_v.push(2.5);
}else{
let velocity = average(scores) - this.last_avg;
this.all_v.push(Math.abs(velocity));
let var_drift = calc_variance(scores) - this.last_var;
let sign = var_drift>0 ? 1 : -1;
this.velocity_pred = 0.3*(sign*average(this.all_v)*2-velocity);
a = a+this.velocity_pred;
}
this.last_var = calc_variance(scores);
this.last_avg = average(scores);
this.n +=1;
//return 50+a*0.4;
return find_min(a);
}
},
```
[Answer]
# Chasing Ninety
Attempts to iteratively approach 90% of the average of previous rounds. Responds poorly to large variances, but attempts to slowly approach the ideal value.
```
{
name: "Chasing Ninety",
myLastGuess: 84,
numRounds: 0,
run(scores) {
this.numRounds++;
if (this.numRounds <= 1) {
return this.myLastGuess;
}
let avg = average(scores);
let difference = this.myLastGuess - (avg * 0.9);
let adjustment = difference / Math.log2(this.numRounds);
this.myLastGuess = this.myLastGuess - adjustment;
return this.myLastGuess;
}
}
```
] |
[Question]
[
Adam West passed away, and I'd like to honor his memory here on PPCG, though I doubt he knew of our existence. While there are many, many different things that this man is known for, none are more prominent than his role as the ~~original~~ batman. I'll always remember my step-father still watching the old-school Batman and Robin to this day. This challenge is simplistic in nature, not at all in line with the complicated man that was Adam West. However, it's the best I could come up with, as this is the most iconic image of the man's career.
---
*I wanted to post this earlier, but I was waiting for someone to come up with something better.*
---
Output the following (with or without trailing spaces/newlines):
```
* *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** ****
** * *** * **
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest byte-count will win.
[Answer]
# [Wordfuck](http://esolangs.org/wiki/Wordfuck), ~~5761~~ 2686 bytes
*I guess using his name as a source code gets Adam West some honor.*
```
adam west adam west adam_wes t_a dam_we st_a dam_ west adam west adam west adam west_ad am_west_a dam_we st ad am we st ad am we st ad am west_a dam_we st_a dam_ west_ada m_w est ada m_w est ada m_west_ adam west_a dam_west_ adam_we st_ ad am_west ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_w est_ adam west adam west adam west adam west adam we st_adam west_ad am we st ad am we st adam_w es t_ ad am west_ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am west_a da m_ we st adam_w es t_adam_ west_ad am we st ad am west_a da m_ we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am_wes t_ adam_we st_adam we st ad am_wes t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st adam_w es t_adam_ west_ad am we st_ada m_ we st ad am we st ad am west_ad am we st ad am we st ad am west_a da m_ we st ad am we st ad am_west ad am we st ad am we st ad am_wes t_ ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am_west ad am west_a da m_ we st ad am_west ad am we st ad am we st_ada m_ we st ad am we st ad am we st ad am we st ad am we st ad am west_ad am we st ad am we st adam_w es t_ ad am we st_ada m_ west_ad am_west ad am we st adam_w es t_ ad am west_ad am we st ad am we st adam_w es t_ ad am_west ad am we st adam_w es t_ ad am we st_adam we st ad am west_a da m_ we st_adam we st ad am we st ad am_wes t_ ad am we st_ada m_ west_ad am_west ad am we st ad am we st_ada m_ we st_adam we st ad am we st ad am_wes t_ adam_we st ad am we st ad am_wes t_ ad am west_ad am we st ad am we st_ada m_ west_ad am we st ad am we st adam_w es t!
```
[Try it online!](https://tio.run/##zZLBCsMgEEQ/aMl@wTA/EnJoAoUS6KGQ7zfGGNcYLbSnvIs6syPs6vh5vN7PZZqdE0/fUSIYqAa5mQEIB3QKbUFNl4gokGQP8jKcViviESojUamKMcSW3xD3mLWKS6quhRz1N/hlajfI/NVQmh4uM8o5u8cLs7RMtS2qfyOcUTac1TMPOrcC) (transpiled brainfuck)
[Adam West singing](https://www.youtube.com/watch?v=RgHUGtlvwrY) (thanks @carusocomputing)
[Answer]
## Python, ~~530~~ ~~529~~ ~~528~~ 524 bytes
```
import zlib as Holy
B=list("NNAAAnAAnnAnaAannnaaaaNaAAnNanAaAanNNaNNaNaanNNANanNNANaAnAaANANAAnAaANNnAanAaNnAaAANNAaAnNANAaaANNAanAaNaNNNAaNNanAAnNNnaaaNANANANnnaaaNaaAAAANaNaNaNAnNAAAAaaaaANAaNnnAaAaNAAaANNnaaNnNnaannaaAaananannNnAAAAAanAananANAnaAAnANAAaaaAaaanaaAAaanNAnanAAnnnANAnNAnnAnnnanaNNaaaNaNNaAAnNAaaANNNANAnAaaAaNaANnNNNaaAanaaaanaaaaaAaAaNnNnnaAnANaNnnANanNA")
A=dict(N='11',A='01',n='10',a='00')
T=""
POP=BIFF=POW=OOF=lambda:A[B.pop()]
while B:T+=chr(int(POP()+POW()+BIFF()+OOF(),2))
print Holy.decompress(T)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“¡©İ'¹!ðkW>ṅṙẏṙlœf:ߌÆ@Ƥ’b25o99Jx$ị⁾ *s25ŒBY
```
[Try it online!](https://tio.run/##AVAAr/9qZWxsef//4oCcwqHCqcSwJ8K5IcOwa1c@4bmF4bmZ4bqP4bmZbMWTZjrDn8WSw4ZAxqTigJliMjVvOTlKeCThu4vigb4gKnMyNcWSQln//w "Jelly – Try It Online")
### How it works
```
“¡©İ'¹!ðkW>ṅṙẏṙlœf:ߌÆ@Ƥ’
```
This is a numeric literal. All characters are replaced with their 1-based indices in Jelly's [code page](https://github.com/DennisMitchell/jelly/wiki/Code-page) the result is interpreted as a bijective base-250 integer, yielding
```
58616171447449697510361193418481584558895594063391402
```
Next, `b25` convert that integer to base **25** and `o99` replaces **0** with **99**, yielding
```
11 1 20 4 10 1 8 4 12 4 3 6 12 4 2 9 9 5 1 99 1 24 2 5 7 11 4 4 7 3 4 3 7 2 7 1 6 2
```
`Jx$` replaces the **j**th base-25 digits **n** with **n** copies of **j**, yielding
```
1 1 1 1 1 1 1 1 1 1 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 7 7 7 7 7 7 7 7 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 11 11 11 12 12 12 12 12 12 13 13 13 13 13 13 13 13 13 13 13 13 14 14 14 14 15 15 16 16 16 16 16 16 16 16 16 17 17 17 17 17 17 17 17 17 18 18 18 18 18 19 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 21 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 23 23 24 24 24 24 24 25 25 25 25 25 25 25 26 26 26 26 26 26 26 26 26 26 26 27 27 27 27 28 28 28 28 29 29 29 29 29 29 29 30 30 30 31 31 31 31 32 32 32 33 33 33 33 33 33 33 34 34 35 35 35 35 35 35 35 36 37 37 37 37 37 37 38 38
```
Now, `ị⁾ *` indexes into the character pair. Indexing is 1-based and modular, so odd numbers get replaced with spaces, even ones with asterisks. This yields
```
* **** * **** **** ****** **** ********* ***** *************************************************************************************************** ************************ ***** *********** **** *** *** ** * **
```
`s25` chops the result into chunks of length **25**. If we write each chunk on its own line, we get
```
*
**** *
**** ****
****** ****
********* *****
************************
*************************
*************************
*************************
************************
***** ***********
**** *** ***
** * **
```
The *bounce* atom `ŒB` palindromizes each chunk by appending a reversed copy without its first character, yielding
```
* *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** ****
** * *** * **
```
Finally, `Y` introduces the actual linefeeds.
[Answer]
## JavaScript (ES6), ~~148~~ 146 bytes
```
_=>`n2zh2
f8l2b2l8
b8pep8
7cpepc
5ijiji
3yyq
0
0
0
3yyq
5afy8fa
98f69a96f8
f4f2d6d2f4`.replace(/./g,c=>'* '[(n=parseInt(c,36))&1].repeat(n/2||49))
```
### Demo
```
let f =
_=>`n2zh2
f8l2b2l8
b8pep8
7cpepc
5ijiji
3yyq
0
0
0
3yyq
5afy8fa
98f69a96f8
f4f2d6d2f4`.replace(/./g,c=>'* '[(n=parseInt(c,36))&1].repeat(n/2||49))
o.innerHTML = f()
```
```
<pre id=o></pre>
```
[Answer]
# Python, ~~149~~ 142 bytes
*7 bytes saved thanks to @PM2Ring*
```
for l in"b1d 74a13 54c4 36c4 2995 1o 0p 0p 0p 1o 257b 447343 727162".split():x=''.join(s*int(k,36)for s,k in zip(' *'*3,l));print(x+x[-2::-1])
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~61~~ 59 bytes
```
' *'60:'*u9|K9j[~F9R,>ejc4Q,7;F\1l_=7sFR'F11:ZaY"13e)25ZvZ)
```
[Try it online!](https://tio.run/##y00syfn/X11BS93MwEpdq9SyxtsyK7rOzTJIxy41K9kkUMfc2i3GMCfe1rzYLUjdzdDQKioxUsnQOFXTyDSqLErz/38A)
### How it works
This uses the following, standard techniques:
* Since the image is *horizontally symmetric*, only the left half (including center column) is encoded.
* The image is linearized in column-major order (down, then across) and the resulting sequence is *run-length encoded*.
* The resulting run lengths take values from `1` to `11`, so the sequence of run lengths is *compressed by base conversion*, from base `11` to base `94` (printable ASCII chars except single quote, which would need escaping).
[Answer]
Various solutions, all using Run Length Encoding, with a variety of techniques to encode the RLE data.
## Python 3, ~~125~~ 121 bytes
This version uses a `bytes` string to store the data.
```
s=''
for c in b'<)@4/:),0/>/,3>/*981(WYYY(W*14=./4-.-4+4)2+':s+=' *'[c%2]*(c//2-19);s*=len(s)<25or print(s+s[-2::-1])or 0
```
Let `s` be a string of stars or of spaces. Then the byte `n` encoding `s` is given by
```
n = 38 + 2*len(s) + (s[0]=='*')
```
---
## Python 2, ~~133~~ 126 bytes
This version uses alphabetic coding. The letter value determines the length of the output string, the case of the letter determines whether it's composed of spaces or stars.
```
s=''
for c in'kAmgDjAceDlDcFlDbIiEaXYYYaXbEgKdDgCdCgBgAfB':
s+=' *'[c<'a']*(int(c,36)-9)
if len(s)>24:print s+s[-2::-1];s=''
```
---
My original 133 byte Python 2 solution.
This version uses zero-length strings so it can easily alternate between star and space strings.
```
s=''
for c,n in zip(24*' *','b1d074a13054c436c429951o0p0p0p1o257b447343727162'):
s+=c*int(n,36)
if len(s)>24:print s+s[-2::-1];s=''
```
---
Just for fun, here's a one-liner using the alphabetic coding.
Python 2, 148 bytes
```
print'\n'.join(''.join(s+s[-2::-1])for s in zip(*[iter(''.join(' *'[c<'a']*(int(c,36)-9)for c in'kAmgDjAceDlDcFlDbIiEaXYYYaXbEgKdDgCdCgBgAfB'))]*25))
```
---
For even more fun, [here's a pattern in Conway's Game of Life](https://gist.github.com/PM2Ring/411bdc8b2ba6be278aa25f3cdafdba25) that generates a version of the Batman logo. I had to double each line to keep the aspect ratio roughly the same as the text version. This pattern doesn't *really* compute the logo (although it *is* possible to do computations in Life - it's Turing-complete), it just replays it from memory loops, so I guess I can't post it as a code golfing entry (although I *did* create it using a Python script I wrote a few years ago). ;)
It's encoded in a fairly standard RLE format that most Life engines can load. If you don't have a GoL program (eg [Golly](http://golly.sourceforge.net/)), you can view it in action online with [this online Life engine](https://copy.sh/life/), which can import Life RLE files. Here's [a PNG version of that Life pattern](https://i.stack.imgur.com/Br984.png), some Life programs (including Golly) can load Life patterns from PNGs and various other image file formats.
[Answer]
# vim, 168 156 bytes
```
:nm N a <C-v><ESC>
:nm A a*<C-v><ESC>
:nm B aY<C-v><ESC>yyp!!rev<C-v><CR>kJh4xo<C-v><ESC>
11NA13NB7N4A10NA3NB5N4A12N4AB3N6A12N4AB2N9A9N5ABN24AB25ABkyyppjN24AB2N5A7N11AB4N4A7N3A4N3AB7N2A7NA6N2ABdd
```
This assumes a Unix environment, for `rev`. I use a fairly straightforward (count,character) encoding, with N and A appending a and `*` respectively, and B doing the copy and reverse.
In the actual file, the bracketed entries are replaced by the literal bytes they represent. `<C-v>` is 0x16, `<ESC>` is 0x1b, and `<CR>` is 0x0d.
[Try it online](https://tio.run/##XYxBC8IwDIXv@xXZVRiYtluZjEHizUPuHosbiEMdCsX9@pqqoHhI8t6X5MWUNpczCATotlXsu/F@6IuMCMLqDzGE/Rcty1yWtzG@SDHtju5x/XlAFEIr7MURroVU1lkabWyl@SgjLbVSE4vJTsWkwfPpbXXhBZHY6a0XS05LI40aanTwMKSUqvgE)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 47 bytes
```
„ *19×S•«M;Ó8ζ?èYÑ?½¨/Ž´.δòÈÖ<•25вт<19ǝ×J13ä€û»
```
[Try it online!](https://tio.run/##AVYAqf8wNWFiMWX//@KAniAqMTnDl1PigKLCq007w5M4zrY/w6hZw5E/wr3CqC/FvcK0Ls60w7LDiMOWPOKAojI10LLRgjwxOcedw5dKMTPDpOKCrMO7wrv//w "05AB1E – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~69~~ ~~54~~ ~~52~~ 48 bytes
```
Ôº•‚™™‚ÄùÔΩú‚Üñy{{Ôπ™yc‚Ä∫o”n‚ÜóœÄf>T‚âîÔºπ¬øPNÔΩúœâœÄÔº±Œ≤‚Äù ‚™´Ôº•Œπ√ó¬ß* Œº‚åïŒ≤Œªœâ‚ÄñԺ؂Üê
```
[Try it online!](https://tio.run/##HYxNCsIwFIT3nuKRVSLpBezKjaAoinqB/LyY1Je0tKFaLx9D@WBg4JsxXo2mV1TKbQwp84sa@GOgkDlTSYOy@o2AEcF1HSzwW1mAvAOL1iOYl/aGQUVIOPUhrRdBwjNEnPg@H5PFL2dbYBJidQ4hWa4lkBC1fWq2mzs6QpOvM45U17szuizaUkozl2aiPw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Thanks to @ASCII-only, saved 4 bytes by switching from a separate flag to looping over indices, ~~7 bytes by using the (undocumented?) `⸿` character,~~ and a further 4 bytes by using the alphabet for the run length encoding. Saved a further 2 bytes because `AtIndex` automatically takes the modulo. Saved a further 4 bytes because `Map` automatically creates an index variable. Explanation:
```
Print(Map(
```
The outer `Map` returns an array. `Print` handles this by printing each element on its own line, thus avoiding having to manually `Join` them with `\n`.
```
Split("anb adbke eme fjj y z z z y lhf dedhe cgbhc" " "),
```
The string encodes all the half-rows of the output. Alternating letters refer to the number of `*`s and spaces (`a=0` is used to handle a row that starts with a space). The space is a convenient choice of delimiter, but also turns out to compress well (x also compresses to an overall 55 bytes). Each row is processed separately. (Note: The deverbosifier fails to remove the separator between a compressed and uncompressed string, otherwise the code would have a `,` for readability.)
```
Join(Map(i, Times(AtIndex("* ", m), Find(b, l))), w)));
```
Loop over every letter, expanding to the appropriate number of `*`s or spaces. The variable `m` is the inner loop index for this `Map`, while `l` holds the letter. The result is then `Join`ed into a single string using the predefined empty string `w`.
```
ReflectOverlap(:Left);
```
Once all the rows are printed, reflect everything to the left, overlapping the middle column.
I tried handling the newlines, spaces and stars all in one loop but it actually took two more bytes this way:
```
Print(Join(Map("anb adbke eme fjj y z z z y lhf dedhe cgbhc", Ternary(Equals(" ", i), "\n", Times(AtIndex("* ", k), Find(b, i)))), w));
ReflectOverlap(:Left);
```
[Answer]
# Clojure, ~~833~~ ~~437~~ ~~342~~ 332 bytes
Almost by definition Clojure will never win any prizes for brevity, but as I looked forward EVERY DARN WEEK to the TWO (count 'em - **TWO**) episodes of Batman (same Bat-time, same Bat-channel!) it's clear that there is no time to lose!
Quick, Robin - to the Bat-REPL!!!
```
(defn p[](loop[l[[11 1 25 1][7 4 10 1 5 1 10 4][5 4 12 7 12 4][3 6 12 7 12 6][2 9 9 9 9 9][1 47][0 49][0 49][0 49][1 47][2 5 7 21 7 5][4 4 7 3 4 5 4 3 7 4][7 2 7 1 6 3 6 1 7 2]]](loop[a(first l)c " "](print(apply str(repeat(first a)c)))(if(>(count a)1)(recur(rest a)(if(= c " ")"*" " "))(println)))(if(>(count l)1)(recur(rest l)))))
```
Un-golfed version:
```
(defn print-bat-signal []
(loop [lines [ [11 1 25 1] ; spaces asterisks spaces asterisks
[7 4 10 1 5 1 10 4]
[5 4 12 7 12 4]
[3 6 12 7 12 6]
[2 9 9 9 9 9]
[1 47]
[0 49]
[0 49]
[0 49]
[1 47]
[2 5 7 21 7 5]
[4 4 7 3 4 5 4 3 7 4]
[7 2 7 1 6 3 6 1 7 2]] ]
; (print-bat-signal-line (first lines))
(loop [ aLine (first lines)
c " " ]
(print (apply str (repeat (first aLine) c)))
(if (> (count aLine) 1)
(recur (rest aLine) (if (= c " ") "*" " "))
(println)))
(if (> (count lines) 1)
(recur (rest lines)))))
```
RIP Adam West. No matter how ridiculous those shows were, those of us who were kids salute you.
[Answer]
# [PHP](https://php.net/), 137 bytes
```
<?=gzinflate(base64_decode(U1CAAy0FXECLC8YAAnQNyAJAwIVFIYSPRYgLLkWEYrByLS10WTwiXAgmcYCLRPV00kGyN6BhgB4eyABZjgstyqAsuDpU5YjEgJIOEKoQigE));
```
[Try it online!](https://tio.run/##BcHbCoIwGADg19GLYIJJUBG/NkMb5iEP6yZM1zyUWhqy3rvr9X1DNUi52W35t@7uj3xiyi0fmaFfS1b0JVNizQIQyM6wRawVBegCT4ALs5PYDo38kHJC2hTTtylIpKH0PNcZ8GdBLRL6CULtQXiGWXFTZwLMS8PHSbxg/OyHeEkbzF3nhI99UHOsqmspf12/KPKiYn8 "PHP – Try It Online")
# [PHP](https://php.net/), 177 bytes
```
foreach(["9zojk",a2878,aa4nb,b7u9z,chbf3,eze2n,jz6rj,jz6rj,jz6rj,eze2n,cepdr,ako8z,a1pc1]as$v)echo$t=strtr(substr(base_convert($v,36,2),1),10,"* "),"* "[$k++<2],strrev($t),"\n";
```
[Try it online!](https://tio.run/##VY7LCsIwFER/RUIWqb2CTaUPrPghtUgSbyktJCFNs8h/u65BV8JwGA4MjJ3s3t1t4mgcCjWxnrTRzAsBwZu6ASEuWoKstzaCmuRYAkbkGuZYufmPP6/QvhyIxTQRRGFVMYiVhgzVZKi/rd55x9ZNpsKkWPGpjA7oPKMBygp4BkXKGcjxQLIve7rkeccHSBOHgVGf/EOT676/tTmp9Bk/ "PHP – Try It Online")
# [PHP](https://php.net/), 179 bytes
```
for(;$o=ord(kAlgDjAbeDlCcFlCbIiDaWXXXaWbEgJdDgCdBgBgAfA[$i++]);($x+=$s)%24?:print$r.("* "[$k++<2]).strrev($r)."\n".$r="")$r.=strtr(str_repeat($b=+($o>96),$s=$o-64-$b*32),10," *");
```
[Try it online!](https://tio.run/##FY5Ba4MwGEDv@xUlfIPEqGy2FDabFqsO2sN2GVToSjGaRlsx4TOMnfave3bu8i7vHZ5t7Lja2MY@KESDZ1TWoGt7TX/z8/vH5y7NWTxeDNIYjDBY01vS6eyaSJV1afXWpXLXZuWhKIryIHO9rzOd1lu91cklOULL@YnFFH64gIE9RovNq8W2d4AhJd6MHOHG@So6sXBwiOqbArKQfPUkBBSEsKkTk3FIJ/7PqdJRkIJTMOuXJfNhEGCC5SIA6c0j5j8/@WTmkel5vPcmqMqqUX8 "PHP – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 191 bytes
```
#define x 16777215
char*b,*c,a[50];l[]={4096,122888,491535,2064399,4186143,x/2,x,x,x,x/2,4064255,983495,98435,0},*p=l;main(){for(;*p;p++,puts(a))for(b=c=a+23;b>=a;*p/=2)*b--=*c++=" *"[*p&1];}
```
[Try it online!](https://tio.run/##JYtLCoMwGIT3PYW0UDT5RfPShJBeRFzEVFvB2mAfCOLZU6XMYoZvZlx6cy6E07Xt@rGN5ogUZVlSIg7ubifUAHJgK5HXeqhqs/BcFUAolVICV0QwATQvOFMKOJEF4QzmjML815b41lIhQEnG1W58u@QrIG8G/bD9GCdL95xijbz2GIP/vF@xTZKdNcYZiynTzcXYbZAZmqAmTQ1yGJtjhI4V8mdS6zWEkH5/ "C (gcc) – Try It Online")
[Answer]
# T-SQL, ~~283 276~~ 222 bytes
```
SELECT CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAFNQgAMtBVxAi5cLxgICdB3IAkAAVYuqEsLHIgRWjV0KqxBIvZYWujQeEaAGLdIALxeJGuinhXSvQEMCPVSQAbIcJPJQReGSSHxU9WAeSppAqEMoBwCfudAGawIAAA=='as XML).value('.','varbinary(max)'))AS varchar(max))
```
Implementing GZIP compression of the original batman string, [via the method posted here](https://codegolf.stackexchange.com/a/190648/70172). This works only in SQL 2016 and later.
For earlier SQL versions, use my prior method (**276 bytes**):
```
DECLARE @ CHAR(999)=REPLACE(REPLACE(REPLACE('PRINT SPACE(11#1$25#1&$7#4$10#1$5#1$10#4&$5#4$12#7$12#4&$3#6$12#7$12#6&$2#9$9#9$9#9&$1#47111&$1#47&$2#5$7#21$7#5&$4#4$7#3$4#5$4#3$7#5&$7#2$7#1$6#3$6#1$7#2)','#',')+REPLICATE(''*'','),'$',')+SPACE('),'&',')+CHAR(13')EXEC(@)
```
Basically I'm manually encoding a giant string that determines what to print next, using the following method:
* `#7` gets replaced by `+REPLICATE('*',7)`
* `$4` gets replaced by `+SPACE(4)`
* `&` gets replaced by `+CHAR(13)`
After replacement, the full 958 character string looks like (with line breaks at each line in the Batman symbol:
```
PRINT
SPACE(11)+REPLICATE('*',1)+SPACE(25)+REPLICATE('*',1)+CHAR(13)
+SPACE(7)+REPLICATE('*',4)+SPACE(10)+REPLICATE('*',1)+SPACE(5)+REPLICATE('*',1)+SPACE(10)+REPLICATE('*',4)+CHAR(13)
+SPACE(5)+REPLICATE('*',4)+SPACE(12)+REPLICATE('*',7)+SPACE(12)+REPLICATE('*',4)+CHAR(13)
+SPACE(3)+REPLICATE('*',6)+SPACE(12)+REPLICATE('*',7)+SPACE(12)+REPLICATE('*',6)+CHAR(13)
+SPACE(2)+REPLICATE('*',9)+SPACE(9)+REPLICATE('*',9)+SPACE(9)+REPLICATE('*',9)+CHAR(13)
+SPACE(1)+REPLICATE('*',47)+CHAR(13)
+REPLICATE('*',49)+CHAR(13)
+REPLICATE('*',49)+CHAR(13)
+REPLICATE('*',49)+CHAR(13)
+SPACE(1)+REPLICATE('*',47)+CHAR(13)
+SPACE(2)+REPLICATE('*',5)+SPACE(7)+REPLICATE('*',21)+SPACE(7)+REPLICATE('*',5)+CHAR(13)
+SPACE(4)+REPLICATE('*',4)+SPACE(7)+REPLICATE('*',3)+SPACE(4)+REPLICATE('*',5)+SPACE(4)+REPLICATE('*',3)+SPACE(7)+REPLICATE('*',5)+CHAR(13)
+SPACE(7)+REPLICATE('*',2)+SPACE(7)+REPLICATE('*',1)+SPACE(6)+REPLICATE('*',3)+SPACE(6)+REPLICATE('*',1)+SPACE(7)+REPLICATE('*',2)
```
Which gets executed as dynamic SQL, producing the following output:
```
* *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** *****
** * *** * **
```
[Answer]
# [Python 2](https://docs.python.org/2/), 134 bytes
```
for w in'1D 4A13 4C4 6C4 995 O P P P O 57B 47343 27162'.split():r=''.join(c*int(k,36)for c,k in zip(3*'* ',w));print'%25s'%r+r[-2::-1]
```
[Try it online!](https://tio.run/##HYxLCsIwFACv8jblJTEt5NOWRlz42de9uCpIYyUJaaDo5WOUYXbDhHeavZM5P3yEDaxDcQF9FAr0WUNXHIYWRrj@GaHtT6B7pRXIXnQSmzW8bCLUxANi8/TWkYlZl8jCVUd/04kvZQsfG4hiyAD5Ruk@xBJhJdsVq7iLt1oaU4t7zl8 "Python 2 – Try It Online")
Run-length encodes each line from the left half in base 36. Mirrors it to make the full line, which is printed. The leading spaces are not encoded; instead, the left half is padded to length 25.
[Answer]
# Java, ~~296~~ 214 bytes
Golfed:
```
()->{String r="";boolean b=1<0;for(int a:";1I1074:151:4054<7<4036<7<6029999901_10a10a10a01_0257E570447345437407271636172".toCharArray()){for(int i=0;i<a-48;++i)r+=(b?'*':' ');if(a<49)r+='\n';else b=!b;}return r;}
```
Ungolfed:
```
public class InHonorOfAdamWest {
public static void main(String[] args) {
System.out.println(f(() -> {
String r = "";
boolean b = 1 < 0;
for (int a : ";1I1074:151:4054<7<4036<7<6029999901_10a10a10a01_0257E570447345437407271636172".toCharArray()) {
for (int i = 0; i < a - 48; ++i) {
r += (b ? '*' : ' ');
}
if (a < 49) {
r += '\n';
}
else {
b = !b;
}
}
return r;
}));
}
private static String f(java.util.function.Supplier<String> f) {
return f.get();
}
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~129~~ 128 bytes
```
-join('5+C+<.4+/+4.6.616.206160/33333-Y+s*t+Y-/1?1/0.1-./.-1.5,1+0-0+1,'|% t*y|%{(' ','*')[$i++%2]*($_-42)})-split'(.{49})'-ne''
```
[Try it online!](https://tio.run/##FcTRCoIwFADQX/FBuduu9253zUEQ9NBXSERPQsZQSSFC/fZV5@FM47t7zY8upZzpOfaDggYveOKAFgNHjhLZu9/OHv6oxdks2JKVs1jHQmyZhJta0JFDqWGrisV8tmpVUEANBvS17BErfzOqvFPwetc0T6lfQPEajrsGGjqAnL8 "PowerShell – Try It Online")
Ungolfed:
```
-join(
'5+C+<.4+/+4.6.616.206160/33333-Y+s*t+Y-/1?1/0.1-./.-1.5,1+0-0+1,'|% toCharArray|%{
(' ','*')[$i++%2]*($_-42)
}
)-split'(.{49})'-ne''
```
Output:
```
* *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** ****
** * *** * **
```
## Main idea is very simple
The Emblem Coding:
1. Concatenate all emblem lines to one string
2. Count spaces and asterisks
3. Encode length of each segment + 42 as a char
Decoding (this script):
1. Get code of the char minus 42 for each char from the cripto-string. This is a length of a segment
2. Append segment, consisting of a space or asterisk repeated `Length` times
3. Insert new line each 49 symbols to split lines
## Some smart things
1. The coding algorithm suggests a symbol with code 189 to display 3 middle asterisk lines. This symbol is not ASCII. It works normal with modern environments, but there are ambiguities with script length. So, I replace non-ascii-symbol `¬Ω` to `s*t` (73 asterisks, 0 spaces, 74 asterisks).
2. I cut off right spaces in the last line to save 1 byte. Sorry, Batman.
3. Why the offset is 42? Just wanted :) And cripto-string looks nice.
## Extra: Scipt for coding of the Emblem
```
(@"
* *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** ****
** * *** * **
"@ -replace"`n"-split'( +|\*+)'-ne''|%{[char]($_.Length+42)})-join''
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 75
xxd dump:
```
00000000: cd92 b501 8050 1043 fb4c 91fa efbf 1f0e .....P.C.L......
00000010: 2f87 d371 5814 37d3 7c35 4d2b 1826 64f6 /..qX.7.|5M+.&d.
00000020: d8aa 419c 2a11 3e75 ce25 6d1e ee9d 22e0 ..A.*.>u.%m...".
00000030: bb11 f04f 0d7f 2e38 dfc8 6926 3dad 0871 ...O...8..i&=..q
00000040: f316 1071 6db8 fc07 a408 f7 ...qm......
```
[Try it online](https://tio.run/##VZA9SwRBDIZ7f8WL4BUKcTLfKyiIraKl7c5kcghuccV2/vc1590VvhBIkTw8SVtb@x77ddk2d84DukweLTlGdcmBXQzQFjsm1hlDm4LVDYCO@aAXev3r6OpEYGN4rQUSCiNVjghFAkoPCVF8A1efkaNm4J7o8EmFftLbHe3kwvDGkDrPiDx1@JkZYZSEPnxCFh4YYxJ4P9zR45lu6Wmlm8Usri@MYIzWbFNdVDgpCj9ChWivyJMpBJkFrprl8ZZ3q0r0tXs0pzMjGkMDZ/uCTWVpFdpdwRyddQX/YvuH5fSKbfsF).
[Answer]
# Coffeescript (282 Bytes)
```
t=['6bk','59mw','l2j3','2ghsf','4zg2n','9zldr','jz6rj','4u7zz','165qf','47wj']
[0,1,2,3,4,5,6,6,6,5,7,8,9].map((d)->parseInt(t[d], 36).toString(2).padStart 25, '0').forEach (d)->console.log (d+d.split('').reverse().join('').substring(1)).replace(/0/g, ' ').replace(/1/g,'*')
```
### Explaination (using plain-ol ES6)
* Like other's mentioned, the image is symmetric, so we can toss out half of it in the encoding
* Several lines are also repeated, so we can toss each line in a lookup table to save a few bytes
* We convert each half-line into binary (using 0 as space and 1 as \*), and encode it at that highest radix in Javascript (36), resulting in the encoding array.
* First map takes each line and converts it back into its final output half-line, padding it with 0s
* Second map concatenates each line with its reversed half (tossing the middle column the second time), and replaces the 0s and 1s with spaces and \*s
```
var t = [
'6bk',
'59mw',
'l2j3',
'2ghsf',
'4zg2n',
'9zldr',
'jz6rj',
'4u7zz',
'165qf',
'47wj'
];
[0,1,2,3,4,5,6,6,6,5,7,8,9].map((d) => {
return parseInt(t[d], 36).toString(2).padStart(25, '0');
})
.forEach((d) => {
console.log((d + d.split('').reverse().join('').substring(1))
.replace(/0/g, ' ')
.replace(/1/g, '*'));
});
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 102 bytes
```
i±³ *±±
³ *± ´*·
´*±² ´*µ
´*±² ¶*³
µ*¹ ¹*
²´* Ä3o²µ*jo±±*· µ*
³*´ ³*· ´*´
**¶ *· **· Îæ$vp
```
[Try it online!](https://tio.run/##TYwhEoAwEAN9v1ATgYrlVWBA8QI0z8ADLQw2fVi5A4PZyd5lMtXaadMBGjeEL0GJusySn/dX809PWi8oUzd0E5Z3eyKWuR0sZsZ@8EFfMfPCQSU4r3cuIZA64U5HLEtZm2ms9QE "V – Try It Online")
Hexdump:
```
00000000: 69b1 b320 2ab1 b120 0ab3 202a b120 b42a i.. *.. .. *. .*
00000010: b720 0ab4 2ab1 b220 b42a b520 0ab4 2ab1 . ..*.. .*. ..*.
00000020: b220 b62a b320 0ab5 2ab9 20b9 2a20 200a . .*. ..*. .* .
00000030: b2b4 2a20 1bc4 336f b2b5 2a1b 6a6f b1b1 ..* ..3o..*.jo..
00000040: 2ab7 20b5 2a20 200a b32a b420 b32a b720 *. .* ..*. .*.
00000050: b42a b420 0a2a 2ab6 202a b720 2a2a b720 .*. .**. *. **.
00000060: 1bce e624 7670 ...$vp
```
This uses run-length encoding to generate the following batman half:
```
*
* ****
**** ****
**** ******
***** *********
************************
*************************
*************************
*************************
************************
*********** *****
*** *** ****
** * **
```
And then reverses and duplicates each line.
[Answer]
## Mathematica 151 Bytes
```
Uncompress@"1:eJxTTMoPCm5iYmBQQAAtBVxAK8bA0AjGBgJ0PcgCQABXjaoWwsciBFWPXRKrEESHlha6AjwiYC1apAGQHhK10FsTOV6Chgp6CCEDZDlYdKKKw6WR+OjxD+KiJBSEQoR6AC49ZiI="
```
Cheap and uncreative. The string is just from the built-in `Compress` command used on the required output.
Update:
I think I can do better with the built-in `ImportString` \ `ExportString` functions but I can't see to copy and paste the resulting strings from `ExportString` correctly. E.g.
```
b = " * *\n **** * * ****\n **** ******* ****\n ****** ******* ******\n ********* ********* *********\n ***********************************************\n*************************************************\n*************************************************\n*************************************************\n ***********************************************\n ***** ********************* *****\n **** *** ***** *** ****\n ** * *** * **"
ExportString[b,"GZIP"]
ImportString[%,"GZIP"]
```
I can not seem to copy the text output from the second line to replace the `%` in the third line.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~407~~ 322 bytes
```
w=`yes 1|head -30|tr -d '\n'`
for i in B1C000 74A120 54C003 36C003 299004 1C0506 0D0506 0D0506 0D0506 1C0506 257505 447342 727161
{ read a b c d e f <<<$(echo $i| fold -1| xargs)
x=`printf "%.$[0x${a}]d%.$[0x${b}]s%.$[0x${c}]d%.$[0x${d}]s%.$[0x${e}]d%.$[0x${f}]s" 0 $w 0 $w 0 $w`
echo -n $x$[f<1?0:1]
rev<<<$x
}|tr 01 \ \*
```
[Try it online!](https://tio.run/##bZDdaoNAEIXv9ykOYUvagmVWVyXBUPrzFlFw1d0qBC1raCzRx@611dAQL3oz58w3A3OYTLXlOJ526bduIfpSqwKOR/3Rwimwjut1ykxjUaGq8SreiAihfBEuwZdT58ELLuJuNkQS04ZPAej9H/mbuX7okw8pQ0@6CN1QBIKdYefTChlyFNAwiKKI3@u8bMCrHqY5TMlEj07Zj/aBdbv001b10WB198T31PGzGpLi6rMhaa8@X/BiwfWCm4mvQOCnW0nZ5bpTg3d8byLxTFuRMKu/5mgdG@YvkUCM@HEcf@rGyVVe6l8 "Bash – Try It Online")
really awful, need more time or help to golf it.
it generates the output with 0 an 1 and transliterates in the end.
Encoded in hexa digits the amount of 0 and 1, taking care to make last digit 0 for the first two rows as a flag to output middle column.
Uses printf pressision to either digit or string to output 0 and 1.
think the `%.$[0x${X}]C` pattern could be used to golf it.
```
w=`yes 1|head -30|tr -d '\n'` # w=111111111111111111111111111111
for i in B1C000 74A120 54C003 36C003 299004 1C0506 0D0506 0D0506 0D0506 1C0506 257505 447342 727161
{ read a b c d e f <<<$(echo $i| fold -1| xargs)
printf "%.$[0x${a}]d
%.$[0x${b}]s
%.$[0x${c}]d
%.$[0x${d}]s
%.$[0x${e}]d
%.$[0x${f}]s" 0 $w 0 $w 0 $w
echo -n $[f<1?0:1]
printf "%.$[0x${f}]s
%.$[0x${e}]d
%.$[0x${d}]s
%.$[0x${c}]d
%.$[0x${b}]s
%.$[0x${a}]d\n" $w 0 $w 0 $w 0
}|tr 01 \ \*
```
[Answer]
# Python 3, ~~232~~ ~~197~~ ~~183~~ 164 bytes
Yet Another Python Answer. No boring compression code though. Exciting compression code.
```
for s in map(lambda x:x+x[-2::-1],b".$; *',$' ('.* &).* %,+, $R #T #T #T $R %()8 '')&&( *%)$(&".split()):print(*((u-35)*" "+(v-35)*"*"for u,v in zip(*[iter(s)]*2)))
```
I'm using the magic number 35 because that way, no control characters, spaces or things that would need to be escaped occur. Sad that I have to process the spaces and stars separately, that costs me a bit.
### Ungolfed:
```
for s in map(lambda x:x+x[-2::-1], # map a list to the list and itself reversed,
# minus the last (center) element
# magic string:
".$; *',$' ('.* &).* %,+, $R #T #T #T $R %()8 '')&&( *%)$(&"
.split()): # split on whitespace to divide into lines
print(*( # unpack generator expression
(ord(s[i])-35)*" " # convert character to int, -25, times space
+(ord(s[i+1])-35)*"*" # same thing with "*"
for i in range(0,len(s)-1,2))) # for every pair in the list
```
[Answer]
## PowerShell, 305 bytes, 307 bytes, 316 bytes
```
[IO.StreamReader]::new(([IO.Compression.GZipStream]::new([IO.MemoryStream]::new(([Convert]::FromBase64String('H4sIAAAAAAAEAL1SOQ4AIAjbTfwDc///QFE8gKAJi53sNQASbYBuQC3rxfANLTBm1iaFB9JIx1Yo9Tzg7YfCBeRQS7Lwr5IfZW7Cb0VDe3I8q25TcXvrTsyXOLGTbuHBUsBqAgAA')),0,102),[IO.Compression.CompressionMode]::Decompress))).ReadToEnd()
```
Maybe someone else can help me shorten it further, though I can't figure out how unless there's a more concise way to define a custom type accelerator.
Edit: Shortened version (thanks @root). Encoded string (pre base64 encoding) can be trimmed by eight array positions and the range can be thus decreased. Not sure why StreamWriter is introducing this bloat into the MemoryStream. Insight into the underlying behavior would be appreciated.
```
[IO.StreamReader]::new(([IO.Compression.GZipStream]::new([IO.MemoryStream]::new(([Convert]::FromBase64String('H4sIAAAAAAAEAL1SOQ4AIAjbTfwDc///QFE8gKAJi53sNQASbYBuQC3rxfANLTBm1iaFB9JIx1Yo9Tzg7YfCBeRQS7Lwr5IfZW7Cb0VDe3I8q25TcXvrTsyXOLGTbg')),0,94),[IO.Compression.CompressionMode]::Decompress))).ReadToEnd()
```
Ungolfed:
```
#Read decoded stream
[IO.StreamReader]::new(
(
#Reverse GZip encoding
[IO.Compression.GZipStream]::new(
#Load GZip encoded string into a memory stream
[IO.MemoryStream]::new(
(
# Convert Base64 back to GZip encoded string
[Convert]::FromBase64String('H4sIAAAAAAAEAL1SOQ4AIAjbTfwDc///QFE8gKAJi53sNQASbYBuQC3rxfANLTBm1iaFB9JIx1Yo9Tzg7YfCBeRQS7Lwr5IfZW7Cb0VDe3I8q25TcXvrTsyXOLGTbuHBUsBqAgAA')
),
#Start of range
0,
#End of range. Stick the Memory Stream into a variable and use .Length here for non golf code
102
),
#Specify that we are decompressing
[IO.Compression.CompressionMode]::Decompress
)
)
).ReadToEnd()
```
Compression code:
```
$s = ' * *
**** * * ****
**** ******* ****
****** ******* ******
********* ********* *********
***********************************************
*************************************************
*************************************************
*************************************************
***********************************************
***** ********************* *****
**** *** ***** *** ****
** * *** * **'
#Create Memory Stream
$ms = [IO.MemoryStream]::new()
#Initialize a stream
$sw = [IO.StreamWriter]::new(
#Create GZip Compression stream
[IO.Compression.GZipStream]::new(
#Reference Memory Stream
$ms,
#Set mode to compress
[IO.Compression.CompressionMode]::Compress
)
)
#Write input into stream
$sw.Write($s)
#Close the stream
$sw.Close()
#Convert Array to Base64 string
[Convert]::ToBase64String(
#Retrieve Memory Stream as an array
($ms.ToArray() | select -SkipLast 8)
)
```
[Answer]
# Perl 5, 168 bytes
```
$_="11 *25
7 4*10 *5 *10 4
5 4*12 7*12 4
3 6*12 7*12 6
2 9*9 9*9 9
47
49
49
49
47
5*7 21*7 5
4 4*7 3*4 5*4 3*7 4
7 **7 *6 3*6 *7 *";s/$/*/gm;say s/\d+(.)/$1x$&/ger
```
Note the trailing space at the end of only the first line. Requires `-M5.01`, which is free.
Can probably be golfed quite a bit more.
[Answer]
# [CJam](https://sourceforge.net/p/cjam/wiki/Home/), 78 bytes
```
"@ÇÏßÿÿÿÿÿÿÿÿÿÿÿÿýÿÿóÿ"{8{_2U#&'*S?\}fU;}/]25/{_24/~;W%N}%
```
[Try it online!](http://cjam.aditsu.net/#code=%22%00%08%00%00%0F%40%C2%80%07%C2%80%C3%87%0F%00%C3%8F%7F%00%C3%9F%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BD%C3%BF%C3%BF%C3%B3%01%C3%BF%C2%87%07%1C%0E%18%10%18%22%7B8%7B_2U%23%26'*S%3F%5C%7DfU%3B%7D%2F%5D25%2F%7B_24%2F~%3BW%25N%7D%25)
---
How it works:
Like many other submissions, this takes advantage of vertical symmetry so that only the following data has to be encoded:
```
*
**** *
**** ****
****** ****
********* *****
************************
*************************
*************************
*************************
************************
***** ***********
**** *** ***
** * **
```
Since all lines are 25 characters long, we can drop all newlines:
```
* **** * **** **** ****** **** ********* ***** *************************************************************************************************** ************************ ***** *********** **** *** *** ** * **
```
This string only contains spaces and `*`, so it's the perfect candidate for a bitmap. 8 characters are chunked into one with a `1` bit meaning `*` and `0` meaning space. The string is 325 characters long, so it's padded with 3 additional spaces to be dividable by 8. This yields the binary string:
```
@ÇÏßÿÿÿÿÿÿÿÿÿÿÿÿýÿÿóÿ
```
Now, onto the code part:
```
{8{_2U#&'*S?\}fU;}/]25/{_24/~;W%N}% e# for each character do:
8{_2U#&'*S?\}fU e# for U in 0..7 do:
_2U#&'*S?\ e# push (char & pow(2, U)) ? '*' : ' '
_ e# duplicate the character
2U# e# push pow(2, U)
& e# bitwise-AND the char with the value
'* e# push '*'
S e# push space
? e# ternary select
\ e# swap the pushed char with the original (for next loop iteration)
; e# pop the character (from last loop iteration) from the stack
] e# wrap all pushed chars in one array
25/ e# split array after every 25 elements (chars)
{_24/~;W%N}% e# for each char group do:
_24/~;W%N e# mirror string and append newline
_ e# duplicate string
24/ e# split at 24 chars
~ e# dump array to stack
; e# pop top stack element
W% e# select every -1th element (reverse)
N e# push newline
```
[Answer]
# LaTeX, 314 bytes
```
\documentclass{book}\begin{document}\def\r#1#2{\ifnum#2>64#1\r#1{\numexpr#2-1}\fi}\catcode`.13\catcode`!13\catcode`-13\def!#1{\r*{`#1}}\def-#1{\r~{`#1}}\let.\par\tt-K!A-Y!A.-G!D-J!A-E!A-J!D.-E!D-L!G-L!D.-C!F-L!G-L!F.-B!I-I!I-I!I.-A!o.!q.!q.!q.-A!o.-B!E-G!U-G!E.-D!D-G!C-D!E-D!C-G!D.-G!B-G!A-F!C-F!A-G!B\enddocument
```
The ungolfed version with explanations:
```
\documentclass{book}
\begin{document}
% Macro for repeating #1 (#2-64) times
\def\r#1#2{\ifnum#2>64#1\r#1{\numexpr#2-1}\fi}
% Prepare '.', '!' and '-' for usage as macro names
\catcode`.13\catcode`!13\catcode`-13
% The ASCII code of #1 (a character) is used as the number of how often '*' will be printed with \r
\def!#1{\r*{`#1}}
% Same as ! but for spaces
\def-#1{\r~{`#1}}
% . becomes a line break
\let.\par
% Set monospace font
\tt
% And finally print the whole thing
-K!A-Y!A.-G!D-J!A-E!A-J!D.-E!D-L!G-L!D.-C!F-L!G-L!F.-B!I-I!I-I!I.-A!o.
!q.!q.!q.-A!o.-B!E-G!U-G!E.-D!D-G!C-D!E-D!C-G!D.-G!B-G!A-F!C-F!A-G!B
\enddocument
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 342 333 328 185 175 bytes
```
_=>{var r="";for(int i=0,j,k=0;i<63;i++)for(j=0;j++<"-#;#4&,#'#,&.&.).&*(.).('+++++%Q#µ#Q%')7)'(&)%&'&%)&-$)#(%(#)$)"[i]-34;){r+=i%2<1?' ':'*';if(++k%49<1)r+='\n';}return r;}
```
[Try it online!](https://tio.run/##bY/NasJAFIX3PsWQcX6ukwSt0tJOYimF7gqVLlxYKdMYZdRMYGYUiuSxfIG@WJoYsJt@i3Mv99yzOJmLstLmdbZXzqE3W26sKnqo4XTRFueV1xk6lnqFXpU23HmrzWaxRMpuHFz//hIt79/O50X8cjBZ0gXCbkzRl/KFMiitP9Pp6agssmkQyHVpuTYe6XQYbsNdOpQ6uR1LLQS01rY5bIVIgghLPKEhZjikMY0hpgPeKGeihczwzxnPCIM7YJwCoYwSoFEfMCccQx@ChV5G44mEkxWpJjfJ6JEh9sAGTOo1F2JHJvfJCBqTfRgmK5v7gzXIyqqWvf8qPpfGlfs8nlvtc96V48HTShVonjsfAMhrrLpsVf0L "C# (.NET Core) – Try It Online")
Lots of bytes saved after changing the approach. Taking the drawing as a 2D array, I calculated the RLE encoding by files:
```
{ 11, 1, 25, 1, 18, 4, 10, 1, 5, 1, 10, 4, 12, 4, 12, 7, 12, 4, 8, 6, 12, 7, 12, 6, 5, 9, 9, 9, 9, 9, 3, 47, 1, 147, 1, 47, 3, 5, 7, 21, 7, 5, 6, 4, 7, 3, 4, 5, 4, 3, 7, 4, 11, 2, 7, 1, 6, 3, 6, 1, 7, 2, 7 }
```
Odd indices stand for s and even indices stand for `*`s. Then I substituted every number for a printable ASCII representation (taking the '#' character as 1), and I got:
```
-#;#4&,#'#,&.&.).&*(.).('+++++%Q#µ#Q%')7)'(&)%&'&%)&-$)#(%(#)$)
```
So the algorithm just calculates the drawing by decompressing this string and adding newlines in the proper places.
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 369 bytes
```
+[[->>>+<<<]>+++++++>+++>+]-<-<<<--<-<<<-<<--<<<-<<+<+<<<<---<<++<---<<<<<+<---<+<++<<<+<[->++<]<<<<<++<-----<<[[-]<]+<-<[++<<+<]>[>>>]<<<<+<+<<<+<<<+<<<+<--<[[->+++++>>]<[<<<]>]+<+<+++++<<<+++++<<<+++++<-------<+<++<+++<<[+++<]<++<------<+<<+++<<[+++<]<<----[<+<]<+[----<]<---<+<<<--<+<+[-<+++>]+<+<<---<++<++++++++[-<+<++++<++++>>>]<--<+>>+[-[-<.>]<<<[->>>+<<<]>>>>+]
```
[Try it online!](https://tio.run/##VVDLDsJACPyV3gm99OCF8COEQ2vUGBtNfBz8@hWG1VSSDY8ZGNjlPp@vx9f@0hqZsaqSiLhSmeI5C0eVu0MET5LsSDOm8pLljChLmcTYiLwgYMkLNRePVCx5QVALea8B1fl9wTdMyXWCYtjRCRpUMn@ey2oHAEbY4Yfl5C2Asgk4BoL3K3AuZTUbSrWgrh5m3FeRWlEdTfGbxoGNOGvzvRl4O93mdZh207C8n4dH@wA "brainfuck – Try It Online")
General idea is to fill memory with counts for how many spaces, stars, and newlines to output (the character to write is the position modulo 3), terminated by a `255`. To efficiently build the counts the symbol is broken into a bottom half, which is prefilled with `0 7 3`, and the top half which is prefilled with `0 9 4`.
`+[[->>>+<<<]>+++++++>+++>+]-` Fills the memory with 254 repetitions of `0 7 3` terminated with a `255`, not all of them are used but its easier to create that many than any other count.
`<-<<<--<-<<<-<<--<<<-<<+<+<<<<---<<++<---<<<<<+<---<+<++<<<+<[->++<]<<<<<++<-----<<[[-]<]+<-<` Updates the counts of the bottom half, note the `[[-]<]` which zeros 3 consecutive cells and is used as a marker for changing the cell repetitions and to compact the middle 5 lines into a loop.
`[++<<+<]>[>>>]` Update remaining cells to be repetitions of `0 9 4`.
`<<<<+<+<<<+<<<+<<<+<--<[[->+++++>>]<[<<<]>]+<+<+++++<<<+++++<<<+++++<-------<+<++<+++<<[+++<]<++<------<+<<+++<<[+++<]<<----[<+<]<+[----<]<---<+<<<--<+<+[-<+++>]+<+<<---<++<` Update the counts of the top half.
`++++++++[-<+<++++<++++>>>]<--<+>>+[-[-<.>]<<<[->>>+<<<]>>>>+]` Output the characters. The first loop builds `42 32 10`, second loop outputs the right most character n times and then moves the left most character forwards 3 cells and repeats until a `255` is hit.
[Answer]
# Mathematica, 271 bytes
```
T=Table;f[x_]:=""<>T["*",x];m={f@49};n={f@47};g[y_]:=""<>T[" ",y];k[a_,b_,c_,d_,e_]:={(s=f@a<>g@b<>f@c<>g@d<>f@e)<>StringDrop[StringReverse@s,1]};Grid@{k[1,13,0,0,0],k[4,10,1,3,0],k[4,12,0,0,4],k[6,12,0,0,4],k[9,9,0,0,5],n,m,m,m,n,k[5,7,0,0,11],k[4,7,3,4,3],k[2,7,1,6,2]}
```
] |
[Question]
[
*[Robbers' challenge thread is here](https://codegolf.stackexchange.com/questions/61805/create-a-programming-language-that-only-appears-to-be-unusable-robbers-thread).*
**Cops' challenge: Design a programming language that appears to be unusable for programming, but admits computation (or at least completion of the task) through some non-obvious mechanism.**
You should design a simple programming language that reads code from an input file and then does ... something. You must prepare a *solution program* that finds the 3rd-largest number in the input when run in your interpreter. You need to make it as hard as possible for robbers to find a solution program. Note that robbers can post *any* solution that accomplishes the task, not just the one you had in mind.
This is a popularity contest. The cops' goal is to get as many votes as possible while surviving 8 days after posting the interpreter without being cracked. To this end, the following practices should help:
* Accurately explaining your language's semantics
* Writing readable code
The following tactics are strongly discouraged:
* Using encryption, hashes, or other cryptographic methods. If you see a language that employs RSA encryption, or refuses to execute a program unless its SHA-3 hash is equal to 0x1936206392306, please do not hesitate to downvote.
**Robbers' challenge: Write a program that finds the third-largest integer in the input when run in the cops' interpreter.**
This one is relatively straightforward. In order to crack a cop answer, you must create a program that completes the task when run in its interpreter. When you crack an answer, post a comment saying "Cracked" on the cop's answer linking to your post. Whoever cracks the most cops wins the robbers' thread.
### I/O Rules
* Interpreters should take a filename on the command line for the program, and use standard input and output when running it.
* Input will be given in unary and consist only of the characters `0` and `1` (48 and 49 in ASCII). A number *N* is encoded as *N* `1s` followed by a `0`. There is an additional `0` before end of file. Example: For the sequence (3, 3, 1, 14), the input is `11101110101111111111111100`.
* Input is guaranteed to have at least 3 numbers. All numbers are positive integers.
* Output will be judged by the number of `1`s printed before the program halts. Other characters are ignored.
In the following examples, the first line is the input in decimal format; the second is the actual program input; the third is a sample output.
```
1, 1, 3
101011100
1
15, 18, 7, 2, 15, 12, 3, 1, 7, 17, 2, 13, 6, 8, 17, 7, 15, 11, 17, 2
111111111111111011111111111111111101111111011011111111111111101111111111110111010111111101111111111111111101101111111111111011111101111111101111111111111111101111111011111111111111101111111111101111111111111111101100
111111,ir23j11111111111u
247, 367, 863, 773, 808, 614, 2
<omitted>
<contains 773 1's>
```
### Boring rules for cop answers:
* To prevent security through obscurity, the interpreter should be written in a language in the top 100 of this [TIOBE index](https://web.archive.org/web/20150905075234/http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html) and have a freely available compiler/interpreter.
* The interpreter must not interpret a language which was published before this challenge.
* Interpreter should fit into your post and not be hosted externally.
* Interpreter should be deterministic
* Interpreter should be portable and follow the standard of its own language; don't use undefined behavior or bugs
* If the solution program is too long to fit into the answer, you must post a program that generates it.
* Solution program should consist only of printable ASCII and newlines.
* You must execute your solution program in less than 1 hour on your own computer for each of the example inputs above.
* The program should work for any integers less than 106, and any number of integers less than 106 (not necessarily in under an hour), provided that the total input length is less than 109.
* To become safe, a cop must edit the solution program into the answer after 8 days have passed.
### Scoring
The cop who becomes safe with the highest score, and a positive score, wins this question.
[Answer]
# Shuffle (written in C++), [Cracked!](https://codegolf.stackexchange.com/a/61995/8478) by Martin
**Edit** *Martin cracked it. To see his solution, click the link. My solution has also been added.*
**Edit** *Fixed `print-d` command to be able to handle both registers and stacks. As this is a debugging command which is not permitted in a solution, this should not affect anyone using the previous version of the interpreter*
I'm still new to this, so if there is something wrong with my answer or my interpreter, please let me know. Please ask for clarification if something is not clear.
I don't imagine that this will be too terribly difficult, but hopefully it will provide some sort of challenge. What makes shuffle fairly unusable is that it will only print when things are in their proper place.
**-->Basics:**
There are 24 Stacks, we call them `stack1, ... stack24`. These stacks live in a list. At the beginning of any program, these stacks have zero pushed and they start in their proper place, i.e. stack*i* in the *ith* position in the list (Note that we will index beginning from 1, unlike C++). **During a course of a program, the order of the stacks within the list will shift.** This is important for reasons that will be explained when I discuss the commands.
There are 5 registers available for use. They are named `Alberto`, `Gertrude`, `Hans`, `Leopold`, `ShabbySam`. Each of these is set to zero at the beginning of a program.
So, at the onset of any program, there are 24 stacks, each has its number matching its index in the stack list. Every stack has exactly one zero on top. Each of the five registers is initialized to zero.
**-->Commands and Syntax**:
There are 13 commands (+1 debugging command) that are available in Shuffle. They are as follows
* `cinpush` this command takes no arguments. It waits for command line input in the fashion described in the question (other input will lead to unspecified/undefined results). It then *splits* the input string into integers, e.g. `101011100` --> `1,1,3`. For each input received, it does the following: **(1)** permutes the list of stacks based on the value. Let the integer value in question be called *a*. If *a* is less than 10 it does permutation *u*. If *a* is between 9 and 30 (noninclusive) it does permutation *d*. Otherwise it does permutation *r*. **(2)** It then pushes *a* onto the the stack which is first in the list. Note that I do not mean `stack1` (although it may be the case that `stack1` is first in the list). The permutations are defined below. Since **`cinpush` is the only way to get user input**, it must appear in any solution.
* `mov value register` The `mov` command is basically variable assignment. It assigns `value` to `register`. `value` can take several forms: it can be **(1)** an integer, e.g. `47` **(2)** the name of a different register, e.g. `Hans` **(3)** the index of a stack followed by 's', e.g. `4s`. Note that this is the index in the list, not the number of the stack. As such, the number should not exceed 24.
Some `mov` examples:
```
mov 4s Hans
mov Hans ShabbySam
mov 9999 Gertrude
```
* `movfs index register` This stands for 'move from stack'. It is similar to the `mov` command. It exists so that you may access a stack indexed by a register. For example, if earlier you set Hans equal to 4 ( `mov 4 Hans`) Then you may use `movfs Hans Gertrude` to set Gertrude equal to the top of stack 4. This type of behavior is not accessible simply using `mov`.
* `inc register` increases register value by 1.
* `dec register` decreases register value by 1.
* `compg value value register` This stands for 'compare greater'. It sets the register equal to the greater of the two values. `value` can be an integer, a register, or a stack index followed by 's', as above.
* `compl value value register` 'compare lesser' same as above, except takes the smaller value.
* `gte value1 value2 register` Checks if `value1 >= value2` then puts the Boolean value (as 1 or 0 ) into `register`.
* `POP!! index` pops off the top of the stack indexed by `index` in the stack list.
* `jmp label` jumps unconditionally to the label `label`. This is a good time to talk about labels. A label is word followed by ':'. The interpreter pre-parses for labels, so you are able to jump forward to labels as well as back.
* `jz value label` jumps to `label` if `value` is zero.
* `jnz value label` jumps to `label` if `value` is nonzero.
Examples of labels and jumping:
```
this_is_my_label:
jmp this_is_my_label
mov 10 Hans
jnz Hans infinite_loop
infinite_loop:
jmp infinite_loop
```
* `"shuffle" permutation` Here is the shuffle command. This allows you to permute the list of stacks. There are three valid permutations that can be used as arguments, `l`, `f`, and `b`.
* `print register` This checks if all the stacks are in their initial positions, i.e stack*i* is at index *i* in the stack list. If this is the case, it prints the value at `register` in unary. Otherwise, it prints a nasty error. As you can see, **to output anything, the stacks must all be in the correct places.**
* `done!` this tells the program to quit with no error. If the program ends without `done!`, it will print to the console the number on top of each stack followed by the stack's number. The order that the stacks are printed is the order they appear in the stack list. If a stack is empty, it will be omitted. This behavior is for debugging purposes and may not be used in a solution.
* `print-d value` this prints the value of the stack, register, or integer given (to access stack *i*, pass `is` as argument, as explained above). This is a debugging tool and not part of the language, as such it is not permitted in an solution.
**--> Here is the interpreter code**
All the parsing happens in the main function. This is where you will find it parsing for specific commands.
```
#include<fstream>
#include<iostream>
#include<string>
#include<stack>
#include<cmath>
using namespace std;
class superStack: public stack<long> {
private:
int m_place;
public:
static int s_index;
superStack() {
m_place = s_index;
s_index++;
}
int place() {
return m_place;
}
};
int superStack::s_index=1;
superStack stack1,stack2,stack3,stack4,stack5,stack6,stack7,stack8,stack9,stack10,stack11, \
stack12,stack13,stack14,stack15,stack16,stack17,stack18,stack19,stack20,stack21,stack22,stack23,stack24;
superStack* stackptrs[]= { \
&stack1,&stack2,&stack3,&stack4,&stack5,&stack6,&stack7,&stack8,&stack9,&stack10,&stack11, \
&stack12,&stack13,&stack14,&stack15,&stack16,&stack17,&stack18,&stack19,&stack20,&stack21,&stack22,&stack23,&stack24 \
};
long Gertrude=0;
long Hans=0;
long Alberto=0;
long ShabbySam=0;
long Leopold=0;
void SWAP( int i, int j) { // 0 < i,j < 25
i--;
j--;
superStack* tempptr = stackptrs[i];
stackptrs[i]=stackptrs[j];
stackptrs[j] = tempptr;
}
void u() {
int list[3][4] = {
{1,9,6,13},
{2,10,5,14},
{17,19,20,18},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void d() {
int list[3][4] = {
{3,11,8,15},
{4,12,7,16},
{22,24,23,21},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void r() {
int list[3][4] = {
{2,17,8,24},
{4,18,6,23},
{9,10,12,11},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void l() {
int list[3][4] = {
{1,19,7,22},
{3,20,5,21},
{14,13,15,16},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void f() {
int list[3][4] = {
{20,9,24,16},
{18,11,22,14},
{1,2,4,3},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void b() {
int list[3][4] = {
{19,10,23,15},
{17,12,21,13},
{5,6,8,7},
};
for(int i=0;i<3;i++) {
for(int j=1;j<4;j++) {
SWAP( list[i][0], list[i][j] );
}
}
}
void splitpush(string input) {
long value=0;
for(long i=0;i<input.size();i++) {
if(input[i]=='1'){
value++;
}
else if(input[i]=='0' && value!=0 ) {
if(value<10) {
u();
}
else if (value<30) {
d();
}
else {
r();
}
(*stackptrs[0]).push(value);
value=0;
}
else {
break;
}
}
}
long strToInt(string str) { // IF STRING HAS NON DIGITS, YOU WILL GET GARBAGE, BUT NO ERROR
long j=str.size()-1;
long value = 0;
for(long i=0;i<str.size();i++) {
long x = str[i]-48;
value+=x*floor( pow(10,j) );
j--;
}
return value;
}
bool isEmpty(superStack stk) {
if( stk.size()>0){return false; }
else {return true;}
}
long getValue(string str) {
if(str=="ShabbySam") {
return ShabbySam;
}
else if(str=="Hans") {
return Hans;
}
else if(str=="Gertrude") {
return Gertrude;
}
else if(str=="Alberto") {
return Alberto;
}
else if(str=="Leopold") {
return Leopold;
}
else if(str[ str.size()-1 ]=='s'){
str.pop_back();
long index = strToInt(str)-1;
if( !isEmpty( (*stackptrs[index]) ) ) {
return (*stackptrs[index]).top();
}
else {
cerr<<"Bad Expression or Empty Stack";
}
}
else {
return strToInt(str);
}
}
void printUnary(long i) {
while(i>0) {
cout<<1;
i--;
}
}
int main(int argc, char**argv) {
if(argc<2){std::cerr<<"No input file given"; return 1;}
ifstream inf(argv[1]);
if(!inf){std::cerr<<"File open failed";return 1;}
for(int i=0;i<24;i++) {
(*stackptrs[i]).push(0); // Pre push a zero on every stack
}
string labels[20];
unsigned labelPoints[20];
int index=0;
string str;
while(inf) { // parse for labels
inf>>str;
//cout<<inf.tellg()<<" ";
if(inf) {
if(str[str.size()-1]==':') {
str.pop_back();
bool alreadyExists = false;
for(int i=0; i<index;i++){
if(labels[i] == str ) { alreadyExists=true;}
}
if(!alreadyExists) {
labels[index]=str;
labelPoints[index]= inf.tellg();
index++;
}
}
}
}
inf.clear();
inf.seekg(0,inf.beg);
while(inf) { // parse for other commands
inf>>str;
if(inf) {
if(str=="cinpush") {
string input;
cin>>input;
splitpush(input);
}
else if(str=="mov") {
inf>>str;
long value = getValue(str);
inf>>str;
if(str=="Gertrude"){Gertrude=value;}
else if(str=="Hans"){Hans=value;}
else if(str=="ShabbySam"){ShabbySam=value;}
else if(str=="Alberto"){Alberto=value;}
else if(str=="Leopold"){Leopold=value;}
else {cerr<<"Bad register name. ";}
}
else if(str=="movfs") {
inf>>str;
long index = getValue(str);
if(!isEmpty( *stackptrs[index-1] )) {
inf>>str;
long value = (*stackptrs[index-1]).top();
if(str=="Gertrude"){Gertrude=value;}
else if(str=="Hans"){Hans=value;}
else if(str=="ShabbySam"){ShabbySam=value;}
else if(str=="Alberto"){Alberto=value;}
else if(str=="Leopold"){Leopold=value;}
else {cerr<<"Bad register name.";}
}
else {
cerr<<"Empty Stack";
}
}
else if(str=="inc") {
inf>>str;
if(str=="Gertrude"){Gertrude++;}
else if(str=="Hans"){Hans++;}
else if(str=="ShabbySam"){ShabbySam++;}
else if(str=="Alberto"){Alberto++;}
else if(str=="Leopold"){Leopold++;}
else {cerr<<"Bad register name. ";}
}
else if(str=="dec") {
inf>>str;
if(str=="Gertrude"){Gertrude--;}
else if(str=="Hans"){Hans--;}
else if(str=="ShabbySam"){ShabbySam--;}
else if(str=="Alberto"){Alberto--;}
else if(str=="Leopold"){Leopold--;}
else {cerr<<"Bad register name. ";}
}
else if(str=="compg") {
inf>>str;
long value1 = getValue(str);
inf>>str;
long value2 = getValue(str);
inf>>str;
long larger;
if(value1>value2){larger = value1;}
else {larger = value2;}
if(str=="Gertrude"){Gertrude=larger;}
else if(str=="Hans"){Hans=larger;}
else if(str=="ShabbySam"){ShabbySam=larger;}
else if(str=="Alberto"){Alberto=larger;}
else if(str=="Leopold"){Leopold=larger;}
else {cerr<<"Bad register name. ";}
}
else if(str=="compl") {
inf>>str;
long value1 = getValue(str);
inf>>str;
long value2 = getValue(str);
inf>>str;
long larger; //LARGER IS REALLY SMALLER HERE
if(value1>value2){larger = value2;}
else {larger = value1;}
if(str=="Gertrude"){Gertrude=larger;}
else if(str=="Hans"){Hans=larger;}
else if(str=="ShabbySam"){ShabbySam=larger;}
else if(str=="Alberto"){Alberto=larger;}
else if(str=="Leopold"){Leopold=larger;}
else {cerr<<"Bad register name. ";}
}
else if(str=="gte") {
inf>>str;
long value1= getValue(str);
inf>>str;
long value2= getValue(str);
inf>>str;
bool torf = value1 >= value2;
if(str=="Gertrude"){Gertrude=torf;}
else if(str=="Hans"){Hans=torf;}
else if(str=="ShabbySam"){ShabbySam=torf;}
else if(str=="Alberto"){Alberto=torf;}
else if(str=="Leopold"){Leopold=torf;}
else {cerr<<"Bad register name. ";}
}
else if(str=="lte") {
inf>>str;
long value1= getValue(str);
inf>>str;
long value2= getValue(str);
inf>>str;
bool torf = value1 <= value2;
if(str=="Gertrude"){Gertrude=torf;}
else if(str=="Hans"){Hans=torf;}
else if(str=="ShabbySam"){ShabbySam=torf;}
else if(str=="Alberto"){Alberto=torf;}
else if(str=="Leopold"){Leopold=torf;}
else {cerr<<"Bad register name. ";}
}
else if(str=="POP!!") {
inf>>str;
long index = getValue(str);
index--; //because we (C++ and this interpreter) index differently
if(!isEmpty( *stackptrs[index] )) {
(*stackptrs[index]).pop();
}
else {cerr<<"Can't POP!! from empty stack";}
}
else if(str=="push"){cerr<<" You can't. ";}
/*
else if(str[str.size()-1]==':') {
str.pop_back();
bool alreadyExists = false;
for(int i=0; i<index;i++){
if(labels[i] == str ) { alreadyExists=true;}
}
if(!alreadyExists) {
labels[index]=str;
labelPoints[index]= inf.tellg();
index++;
}
}*/
else if(str=="jmp") {
inf>>str;
for(int i=0;i<index;i++) {
if( labels[i]==str) {
inf.seekg( labelPoints[i], ios::beg);
}
}
}
else if(str=="jz") {
inf>>str;
long value = getValue(str);
if(value==0) {
inf>>str;
for(int i=0;i<index;i++) {
if( labels[i]==str) {
inf.seekg( labelPoints[i], ios::beg);
}
}
}
}
else if(str=="jnz") {
inf>>str;
long value = getValue(str);
if(value!=0) {
inf>>str;
for(int i=0;i<index;i++) {
if( labels[i]==str) {
inf.seekg( labelPoints[i], ios::beg);
}
}
}
}
else if(str== "\"shuffle\"") {
inf>>str;
if(str=="l"){ l(); }
else if(str=="f"){ f(); }
else if(str=="b"){ b(); }
else {cerr<<"Bad shuffle parameter";}
}
else if(str=="print") {
for(int i=0;i<24;i++) {
if( (i+1) != (*stackptrs[i]).place() ) {
cerr<< "Sorry, your stacks are in the wrong place! You can't print unless you put them back! Exiting. ";
return 1;
}
}
inf>>str;
if(str=="Gertrude"){printUnary(Gertrude);}
else if(str=="Hans"){printUnary(Hans);}
else if(str=="ShabbySam"){printUnary(ShabbySam);}
else if(str=="Alberto"){printUnary(Alberto);}
else if(str=="Leopold"){printUnary(Leopold);}
else {cerr<<"Bad register name. ";}
}
else if(str=="done!") {return 0;}
else if(str=="print-d" ){
inf>>str;
long value = getValue(str);
cout<<str;
}
}
}
/*for(int i=1;i<25;i++) {
(*(stackptrs[i-1])).push(i);
}
u();d();r();l();f();b();
*/
cout<<"\n";
for(int i=1;i<25;i++) {
if( (*(stackptrs[i-1])).size()>0 ) {
cout<<(*(stackptrs[i-1])).top()<<" "<<(*(stackptrs[i-1])).place()<<"\n";
(*(stackptrs[i-1])).pop();
}
}
/*
for (int i=0;i<index;i++) {
cout<<labels[i]<<": "<<labelPoints[i]<<"\n";
}*/
return 1;
}
```
**-->Permutations**
The permutations permute the elements of the stack list in the following fashion:
![](https://latex.codecogs.com/gif.latex?u%20%3D%20%281%2C9%2C6%2C13%29%282%2C10%2C5%2C14%29%2817%2C19%2C20%2C18%29)
![](https://latex.codecogs.com/gif.latex?d%3D%20%283%2C11%2C8%2C15%29%284%2C12%2C7%2C16%29%2822%2C24%2C23%2C21%29)
![](https://latex.codecogs.com/gif.latex?r%20%3D%20%282%2C17%2C8%2C24%29%284%2C18%2C6%2C23%29%289%2C10%2C12%2C11%29)
![](https://latex.codecogs.com/gif.latex?l%20%3D%20%281%2C19%2C7%2C22%29%283%2C20%2C5%2C21%29%2814%2C13%2C15%2C16%29)
![](https://latex.codecogs.com/gif.latex?f%20%3D%20%2820%2C9%2C24%2C16%29%2818%2C11%2C22%2C14%29%281%2C2%2C4%2C3%29)
![](https://latex.codecogs.com/gif.latex?b%20%3D%20%2819%2C10%2C23%2C15%29%2817%2C12%2C21%2C13%29%285%2C6%2C8%2C7%29)
Where ![](https://latex.codecogs.com/gif.latex?%28a%2Cb%2Cc%2Cd%29) means that ![](https://latex.codecogs.com/gif.latex?a%20%5Cmapsto%20b%20%5Cmapsto%20c%5Cmapsto%20d%20%5Cmapsto%20a)
(These also appear in the interpreter code. If there is a discrepancy, the interpreter is correct.)
**-->Simple Example**
These two simple programs print the numbers from 24 to 1 (in unary) with no whitespace.
```
mov 24 Hans
start:
print Hans
dec Hans
jnz Hans start
done!
```
or
```
mov 24 Hans start: print Hans dec Hans jnz Hans start done!
```
They are the same program.
# Explanation and Solution:
Martin has a good explanation in [his answer](https://codegolf.stackexchange.com/a/61995/8478) as well.
As Martin figured out, this language was inspired by the pocket cube (aka 2x2 Rubik's cube). The 24 stacks are like the 24 individual squares on the cube. The permutations are the basic moves allowed: up, down, right, left, front, back.
The main struggle here is that when values are pushed, only three moves are used: up, down, and right. However, you do not have access to these moves when "shuffling" the stacks. You have only the other three moves.
As it turns out, both sets of three moves actually span the entire group (i.e. are generators), so the problem is solvable. This means that you can actually solve any 2x2 Rubik's cube only using 3 of the moves.
All that is left to do is figure out how to undo the up, down, and right moves using the other three. To this end, I employed a computer algebra system called [GAP](http://www.gap-system.org/).
After undoing the permutations, finding the third largest number is fairly trivial.
```
cinpush
main:
mov 1s ShabbySam
POP!! 1
jmp compare
continue:
gte 0 ShabbySam Leopold
jnz Leopold end
gte ShabbySam 9 Leopold
jz Leopold uinverse
gte ShabbySam 29 Leopold
jz Leopold dinverse
jnz Leopold rinverse
compare:
gte ShabbySam Alberto Leopold
jz Leopold skip
mov Gertrude Hans
mov Alberto Gertrude
mov ShabbySam Alberto
jmp continue
skip:
gte ShabbySam Gertrude Leopold
jz Leopold skip_2
mov Gertrude Hans
mov ShabbySam Gertrude
jmp continue
skip_2:
gte ShabbySam Hans Leopold
jz Leopold continue
mov ShabbySam Hans
jmp continue
uinverse:
"shuffle" f
"shuffle" f
"shuffle" f
"shuffle" l
"shuffle" b
"shuffle" l
"shuffle" b
"shuffle" b
"shuffle" b
"shuffle" l
"shuffle" l
"shuffle" l
"shuffle" b
"shuffle" b
"shuffle" b
"shuffle" l
"shuffle" l
"shuffle" l
"shuffle" f
jmp main
dinverse:
"shuffle" f
"shuffle" b
"shuffle" l
"shuffle" b
"shuffle" b
"shuffle" b
"shuffle" f
"shuffle" f
"shuffle" f
jmp main
rinverse:
"shuffle" b "shuffle" l "shuffle" f "shuffle" l "shuffle" b
"shuffle" f "shuffle" f "shuffle" f "shuffle" b
"shuffle" l "shuffle" l "shuffle" l
"shuffle" b "shuffle" b "shuffle" b
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" f "shuffle" l "shuffle" f
"shuffle" l "shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" f "shuffle" l "shuffle" l
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" l "shuffle" l "shuffle" l "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
"shuffle" f "shuffle" f "shuffle" f
"shuffle" l "shuffle" f "shuffle" l "shuffle" f "shuffle" l "shuffle" f
"shuffle" l "shuffle" l "shuffle" l
jmp main
end:
print Hans
done!
```
[Answer]
## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), [Cracked by cardboard\_box](https://codegolf.stackexchange.com/a/63404/8478)
I've been intrigued for some time now by the idea of a programming language where two programs interact with each other (probably inspired by [ROCB](http://esolangs.org/wiki/RubE_on_Conveyor_Belts)). This challenge was a nice incentive to tackle this concept at last while trying to keep the language as minimal as possible. The design goals were to make the language Turing-complete while each of its parts individually are not Turing-complete. Furthermore, even both of them together should not be Turing-complete without making use of source code manipulation. I *think* I've succeeded with that, but I haven't proven any of those things formally yet. So without further ado I present to you...
### The Protagonists
Brian and Chuck are two Brainfuck-like programs. Only one of them is being executed at any given time, starting with Brian. The catch is that Brian's memory tape is also Chuck's source code. And Chuck's memory tape is also Brian's source code. Furthermore, Brian's tape head is also Chuck's instruction pointer and vice versa. The tapes are semi-infinite (i.e. infinite to the right) and can hold signed arbitrary-precision integers, initialised to zero (unless specified otherwise by the source code).
Since the source code is also a memory tape, commands are technically defined by integer values, but they correspond to reasonable characters. The following commands exist:
* `,` (`44`): Read a byte from STDIN into the current memory cell. **Only Brian can do this.** This command is a no-op for Chuck.
* `.` (`46`): Write the current memory cell, modulo 256, as a byte to STDOUT. **Only Chuck can do this.** This command is a no-op for Brian.
* `+` (`43`): Increment the current memory cell.
* `-` (`45`): Decrement the current memory cell.
* `?` (`63`): If the current memory cell is zero, this is a no-op. Otherwise, hand control over to the other program. The tape head on the program which uses `?` will remain on the `?`. The other program's tape head will move one cell to the right before executing the first command (so the cell which is used as the test is not executed itself).
* `<` (`60`): Move the tape head one cell to the left. This is a no-op if the tape head is already at the left end of the tape.
* `>` (`62`): Move the tape head one cell to the right.
* `{` (`123`): Repeatedly move the tape head to the left until either the current cell is zero or the left end of the tape is reached.
* `}` (`125`): Repeatedly move the tape head to the right until the current cell is zero.
The program terminates when the active program's instruction pointer reaches a point where there are no more instructions to its right.
### The Source Code
The source file is processed as follows:
* If the file contains the string `````, the file will be split into two parts around the first occurrence of that string. All leading and trailing whitespace is stripped and the first part is used as the source code for Brian and the second part for Chuck.
* If the file does not contain this string, the first line of the file will be used as the source for Brian and the second part for Chuck (apart from the delimiting newline, no whitespace will be removed).
* All occurrences of `_` in both programs are replaced with NULL bytes.
* The two memory tapes are initialised with the character codes corresponding to the resulting string.
As an example, the following source file
```
abc
```
0_1
23
```
Would yield the following initial tapes:
```
Brian: [97 98 99 0 0 0 0 ...]
Chuck: [48 0 49 10 50 51 0 0 0 0 ...]
```
### The Interpreter
The interpreter is written in Ruby. It takes two command-line flags which must *not* be used by any solution (as they are not part of the actual language specification):
* `-d`: With this flag, Brian and Chuck understand two more commands. `!` will print a string representation of both memory tapes, the active program being listed first (a `^` will mark the current tape heads). `@` will also do this, but then immediately terminate the program. Because I'm lazy, neither of those work if they are the last command in the program, so if you want to use them there, repeat them or write a no-op after them.
* `-D`: This is the verbose debug mode. It will print the same debug information as `!` after every single tick. `@` also works in this mode.
Here is the code:
```
# coding: utf-8
class Instance
attr_accessor :tape, :code, :ip
OPERATORS = {
'+'.ord => :inc,
'-'.ord => :dec,
'>'.ord => :right,
'<'.ord => :left,
'}'.ord => :scan_right,
'{'.ord => :scan_left,
'?'.ord => :toggle,
','.ord => :input,
'.'.ord => :output,
'!'.ord => :debug,
'@'.ord => :debug_terminate
}
OPERATORS.default = :nop
def initialize(src)
@code = src.chars.map(&:ord)
@code = [0] if code.empty?
@ip = 0
end
def tick
result = :continue
case OPERATORS[@code[@ip]]
when :inc
@tape.set(@tape.get + 1)
when :dec
@tape.set(@tape.get - 1)
when :right
@tape.move_right
when :left
@tape.move_left
when :scan_right
@tape.move_right while @tape.get != 0
when :scan_left
@tape.move_left while @tape.ip > 0 && @tape.get != 0
when :toggle
if @tape.get != 0
@tape.move_right
result = :toggle
end
when :input
input
when :output
output
when :debug
result = :debug
when :debug_terminate
result = :debug_terminate
end
return :terminate if result != :toggle && @ip == @code.size - 1
move_right if result != :toggle
return result
end
def move_right
@ip += 1
if @ip >= @code.size
@code << 0
end
end
def move_right
@ip += 1
if @ip >= @code.size
@code << 0
end
end
def move_left
@ip -= 1 if @ip > 0
end
def get
@code[@ip]
end
def set value
@code[@ip] = value
end
def input() end
def output() end
def to_s
str = self.class.name + ": \n"
ip = @ip
@code.map{|i|(i%256).chr}.join.lines.map do |l|
str << l.chomp << $/
str << ' '*ip << "^\n" if 0 <= ip && ip < l.size
ip -= l.size
end
str
end
end
class Brian < Instance
def input
byte = STDIN.read(1)
@tape.set(byte ? byte.ord : -1)
end
end
class Chuck < Instance
def output
$> << (@tape.get % 256).chr
end
end
class BrianChuck
class ProgramError < Exception; end
def self.run(src, debug_level=0)
new(src, debug_level).run
end
def initialize(src, debug_level=false)
@debug_level = debug_level
src.gsub!('_',"\0")
if src[/```/]
brian, chuck = src.split('```', 2).map(&:strip)
else
brian, chuck = src.lines.map(&:chomp)
end
chuck ||= ""
brian = Brian.new(brian)
chuck = Chuck.new(chuck)
brian.tape = chuck
chuck.tape = brian
@instances = [brian, chuck]
end
def run
(puts @instances; puts) if @debug_level > 1
loop do
result = current.tick
toggle if result == :toggle
(puts @instances; puts) if @debug_level > 1 || @debug_level > 0 && (result == :debug || result == :debug_terminate)
break if result == :terminate || @debug_level > 0 && result == :debug_terminate
end
end
private
def current
@instances[0]
end
def toggle
@instances.reverse!
end
end
case ARGV[0]
when "-d"
debug_level = 1
when "-D"
debug_level = 2
else
debug_level = 0
end
if debug_level > 0
ARGV.shift
end
BrianChuck.run(ARGF.read, debug_level)
```
---
Here is my own (handwritten) solution to the problem:
```
>}>}>
brace left: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
brace left: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>>>} Append a bunch of 1s as a dummy list element:
+>+>+>+>+>+>+>+>+>+
Append two 1s and some code to the list; the first is a marker for later; the latter will be the integer
1: >+
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1: >+
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow right: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
_
{<<<<<<<<<{<{ Move back to the start
Read a character and subtract 48 to get actual 0 or 1
,------------------------------------------------
? If 1 switch to Chuck otherwise continue
>}>}>>>>>>>>>}<<<<<<- Subtract 1 from the result to account for initial 1
? If integer was positive switch to Chuck
@todo: process end
_
This code is run when reading 1:
}>}>>>>>>>>>}<<<<<<+ Move to the end of Chuck; skip one null cell; move to the end of the list
{<<<<<<<<<{<? Move back to the code that resets this loop.
_
This code is run after finalising an integer:
change the code after the integer first
<<--<--<--}
Append two 1s and some code to the list; the first is a marker for later; the latter will be the integer
1: +
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1: >+
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow right: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
brace right: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{<<<<<<<+<<{<{ Move back to the start; incrementing the list length
Read a character and subtract 48 to get actual 0 or 1
,------------------------------------------------
? If 1 switch to Chuck otherwise continue
>}>}>>>>>>>>>}
Leave the resetting code, but remove the rest of the last list element:
<<<--<--<--
1: <-
question mk: <---------------------------------------------------------------
arrow left: <------------------------------------------------------------
brace right: <-----------------------------------------------------------------------------------------------------------------------------
1: <-
<{< Move back to the cell we reserved for the counter
<<<<<<-- decrement list size by two so we don't process the two largest elements
_
<{<<<<<<{<{<{<{<{>}>}>>>>>>> This is the beginning of the loop which decrements all list elements by 1
+ Add 1 to the running total
>>- Set marker of dummy list element to zero
_ Beginning of loop that is run for each list element
<{<<<<<<{<{<{<{<{>}>}>}>}+ set last marker back to 1
>>>>>>>>>> move to next marker
? Skip the next bit if we're not at the end of the list
<? Move back to the beginning of the loop
@ we should never get here
_
This is run when we're not at the end of the list
<<<- Set marker to 0 to remember current position
>>>>- Move to the current value and decrement it
? Move back to loop beginning if value is not zero yet
- Make element negative so it's skipped in the future
{<{<{>- Move to remaining list length and decrement it
? If it's nonzero switch to Chuck
>>>>>>>>->->->->->->->->->- Remove the dummy list to make some space for new code:
>}+ Fill in the marker in the list
{<<<<<<<<< Add some loop resetting code after the result:
brace left: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
arrow left: >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
question mk: >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
_
This loop adds a print command to Chuck's code while decrementing the result
>>>>>>>>}>>>>>}>>>>>} Move to the very end of Chuck's code and leave some space to seek the 1
print: ++++++++++++++++++++++++++++++++++++++++++++++
{<<<<<{<<<<<{<<<<<<<{<
- decrement the result
? if nonzero run loop again
At this point we just need to make Chuck seek for the 1 at the end of this code print it often enough
>>}>>>>>>>}>>>>>}
arrow right: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<?1 Switch to Chuck which moves Brian's tape head onto the 1 and then prints it N times
```
_ Dummy cell to hold input
This code is run when reading a 1:
{<{<{<{ ensure we're at the start
}>}<? Skip 0 handling code and switch to Brian
_ This code is run after a 1 has been processed:
{<{<?
```
This code is runnable as is, because all the annotations use no-ops and are skipped by `{` and `}`.
The basic idea is:
1. Add a new zero-element to the list (at the end of Chuck's tape) and increase the list length by 1.
2. While we're reading `1`s, increment that element.
3. When we're reading a `0`, do some cleanup. If the resulting integer was greater than zero, go back to 1.
Now we've got a list of the input numbers at the end of Chuck's tape and we know the length of the list.
4. Subtract 2 from the length of the list (so the following steps ignore the two largest elements), call this `N`.
5. While `N > 0`, increment a running total and then decrement all list elements. Whenever a list element hits zero, decrement `N`.
At the end of this, the running total will contain the third-largest number in the input, `M`.
6. Write `M` copies of `.` to the end of Chuck's tape.
7. On Chuck, search for a `1` on Brian's tape and then execute those generated `.` at the end.
After finishing this I realised that I could simplify it quite a lot in some places. For instance, instead of keeping track of that counter and writing those `.` to Chuck's tape I could just print a `1` right away, each time before I decrement all the list elements. However, making changes to this code is quite a pain, because it propagates other changes all over the place, so I didn't bother making the change.
The interesting bit is how to keep track of the list and how to iterate through it. You can't just store the numbers back-to-back on Chuck's tape, because then if you want to check a condition on one of the list elements, you risk executing the remainder of the list which might contain valid code. You also don't know how long the list will be, so you can't just reserve some space in front of Chuck's code.
The next problem is that we need to leave the list to decrement `N` while we're processing it, and we need to get back to the same place we were before. But `{` and `}` would just skip past the entire list.
So we need to write some code dynamically onto Chuck. In fact, each list element `i` has the form:
```
[1 <Code A> i <Code B>]
```
`1` is a marker which we can set to zero to indicate where we left off processing the list. Its purpose is to catch `{` or `}` which will just pass over the code and the `i`. We also use this value to check if we're at the end of the list during processing, so while we're not, this will be `1` and the conditional `?` will switch control to Chuck. `Code A` is used to handle that situation and move the IP on Brian accordingly.
Now when we decrement `i` we need to check whether `i` is already zero. While it is not, `?` will again switch control, so `Code B` is there to handle that.
[Answer]
# Changeling (safe)
### ShapeScript
ShapeScript is a naturally occurring programming language. Shape shifters (or *Changelings*, as they prefer to be called) can transform into a set of instructions that allows them to process data.
ShapeScript is a stack-based language with a relatively simple syntax. Unsurprisingly, most of its built-ins deal with altering the shape of strings. It is interpreted, character by character, as follows:
* `'` and `"` begin a string literal.
Until the matching quote is found in the source code, all characters between these matching quotes are collected in a string, which is then pushed on the stack.
* `0` to `9` push the integers **0** to **9** on the stack. Note that `10` pushes *two* integers.
* `!` pops a string from the stack, and attempts to evaluate it as ShapeScript.
* `?` pops an integer from the stack, and pushes a copy of the stack item at that index.
Index 0 corresponds to the topmost stack item (LIFO) and index -1 to the bottom-most one.
* `_` pops an iterable from the stack, and pushes its length.
* `@` pops two items from the stack, and pushes them in reversed order.
* `$` pops two strings from the stack, and splits the bottom-most one at occurrences of the topmost one. The resulting list is pushed in return.
* `&` pops a string (topmost) and an iterable from the stack, and joins the iterable, using the string as separator. The resulting string is pushed in return.
* If ShapeScript is used on our planet, since pythons are the Changelings closest relatives on Earth, all other characters **c** pop two items **x** and **y** (topmost) from the stack, and attempt to evaluate the Python code `x c y`.
For example, the sequence of characters `23+` would evaluate `2+3`, while the sequence of characters `"one"3*` would evaluate `'one'*3`, and the sequence of characters `1''A` would evaluate `1A''`.
In the last case, since the result is not valid Python, the Changeling would complain that his current shape is unpurposed (syntax error), since it is not valid ShapeScript.
Before executing the code, the interpreter will place the entire user input in form of a string on the stack. After executing the source code, the interpreter will print all items on the stack. If any part in between fails, the Changeling will complain that his current shape is inadequate (runtime error).
### Shape shifting
In their natural state, Changelings do not take the shape of ShapeScript. However, some of them can transform into one potential source code (which isn't necessarily useful or even syntactically valid).
All eligible Changelings have the following natural form:
* All lines must have the same number of characters.
* All lines must consist of printable ASCII characters, followed by a single linefeed.
* The number of lines must match the number of printable characters per line.
For example, the byte sequence `ab\ncd\n` is an eligible Changeling.
In its attempt to shift into ShapeScript, the Changeling undergoes the following transformation:
* Initially, there is no source code.
* For each line the following happens:
+ The Changeling's accumulator is set to zero.
+ For each character **c** of the line (including the trailing linefeed), the code point of **c** is XORed with the accumulator divided by 2, and the Unicode character that corresponds to the resulting code point is appended to the source code.
Afterwards, the difference between the code point of **c** and the code point of a space (32) is added to the accumulator.
If any part of the above fails, the Changeling will complain that its current shape is unpleasant.
After all lines have been processed, the Changeling's transformation into (hopefully valid) ShapeScript is complete, and the resulting code is executed.
### Solution (ShapeScript)
```
"0"@"0"$"0"2*&"0"@+0?_'@1?"0"$_8>"1"*+@1?"0"+$""&'*!#
```
ShapeScript actually turned out to be quite usable; it can even perform primality testing ([proof](https://codegolf.stackexchange.com/a/63092)) and therefore satisfies our definition of programming language.
I have re-published [ShapeScript on GitHub](https://github.com/DennisMitchell/ShapeScript/), with a slightly modified syntax and better I/O.
The code does the following:
```
"0"@ Push "0" (A) and swap it with the input string (S).
"0"$ Split S at 0's.
"0"2* Push "00".
& Join the split S, using "00" as separator.
"0"@+ Prepend "0" to S.
The input has been transformed into
"0<run of 1's>000<run of 1's>0...0<run of 1's>0000".
0?_ Push a copy and compute its length (L).
' Push a string that, when evaluated, does the following:
@1? Swap A on top of S, and push a copy of S.
"0"$ Split the copy of S at 0's.
_8> Get the length of the resulting array and compare it with 8.
If this returns True, there are more than eight chunks, so there are
more then seven 0's. With two 0's surrounding each run of 1's and
three extra 0's at the end, this means that there still are three or
more runs of 1's in the string.
"1"* Push "1" if '>' returned True and "" if it returned False.
+ Append "1" or "" to A.
@1? Swap S on top of A, and push a copy of A.
"0"+ Append "0" to the copy of A.
$ Split S at occurrences of A+"0".
""& Flatten the resulting array of strings.
' This removes all occurrences of "010" in the first iteration, all
occurrences of "0110" in the second, etc., until there are less than
three runs of 1's left in S. At this point, A is no longer updated,
and the code inside the string becomes a noop.
*! Repeat the code string L times and evaluate.
# Drop S, leaving only A on the stack.
```
### Solution (Changeling)
```
"1+-.......................
""B1.......................
"" 2)+7....................
"" 2)=<....................
""( $86=...................
""B8=......................
""247......................
""]`b......................
""B1.......................
""%D1=.....................
""%500=....................
""%&74?....................
""%&#.2....................
""%[bdG....................
""%D1=.....................
""%<5?.....................
""%:6>.....................
""%&65?....................
""%&-%7>...................
""%D1=.....................
""%500=....................
""%&74?....................
""%&,)5>...................
""%&%,79...................
"" )$?/=...................
""),-9=....................
""# !......................
```
Like all Changeling programs, this code has a trailing linefeed.
ShapeScript will error immediately on any character is does not understand, but we can push arbitrary strings as fillers and pop them later. This allows us to put only a small amount of code on each line (at the beginning, where the accumulator is small), followed by an opening `"`. If we begin the next line with `"#`, we close and pop the string without affecting the actual code.
In addition, we have to overcome three minor obstacles:
* The long string in the ShapeScript code is a single token, and we won't be able to fit it on a line.
We will push this string in chunks (`'@'`, `'1?'`, etc.), which we'll concatenate later.
* The code point of `_` is rather high, and pushing `'_'` will be problematic.
However, we'll be able to push `'_@'` effortlessly, followed by another `'@'` to undo the swap.
The ShapeScript code our Changeling will generate looks like this1:
```
"0""
"#@"
"#"0"$"
"#"0"2"
"#*&"0""
"#@+"
"#0?"
"#_@"
"#@"
"#'@'"
"#'1?'"
"#'"0'"
"#'"$'"
"#'_@'"
"#'@'"
"#'8'"
"#'>'"
"#'"1'"
"#'"*+'"
"#'@'"
"#'1?'"
"#'"0'"
"#'"+$'"
"#'""&'"
"#"+"77"
"#+*!*"
"#!#"
```
I found the Changeling code by running the above ShapeScript code through [this converter](http://cjam.aditsu.net/#code=qN%2F_%2C%5Cf%7B0%5C%7Bi1%241m%3E%5E_L%2B%3AL%3Bc%5C1%24i32-%2B%7D%2F%3B%5D('.e%5DN%2Bo%7DL%24_%2C(%25p&input=%220%22%22%0A%22%23%40%22%0A%22%23%220%22%24%22%0A%22%23%220%222%22%0A%22%23*%26%220%22%22%0A%22%23%40%2B%22%0A%22%230%3F%22%0A%22%23_%40%22%0A%22%23%40%22%0A%22%23'%40'%22%0A%22%23'1%3F'%22%0A%22%23'%220'%22%0A%22%23'%22%24'%22%0A%22%23'_%40'%22%0A%22%23'%40'%22%0A%22%23'8'%22%0A%22%23'%3E'%22%0A%22%23'%221'%22%0A%22%23'%22*%2B'%22%0A%22%23'%40'%22%0A%22%23'1%3F'%22%0A%22%23'%220'%22%0A%22%23'%22%2B%24'%22%0A%22%23'%22%22%26'%22%0A%22%23%22%2B%2277%22%0A%22%23%2B*!*%22%0A%22%23!%23%22).2
### Interpreter (Python 3)
```
#!/usr/bin/env python3
import fileinput
def error(code):
print("This shape is " + ["unpleasant", "unpurposed", "inadequate"][code - 1] + ".")
exit(code)
def interpret(code):
global stack
stringing = 0
for char in code:
quote = (char == "'") + 2 * (char == '"')
if quote or stringing:
if not stringing:
string = ""
stringing = quote
elif stringing == quote:
stack.append(string)
stringing = 0
else:
string += char
elif char in "0123456789":
stack.append(int(char))
else:
x = stack.pop()
if char == '!':
interpret(x)
else:
if char == '?':
y = stack[~x]
elif char == "_":
y = len(x)
else:
y = stack.pop()
if char == '@':
stack.append(x)
elif char == '$':
y = y.split(x)
elif char == '&':
y = x.join(map(str, y))
else:
try:
y = eval(repr(y) + char + repr(x))
except SyntaxError:
error(2)
stack.append(y)
source = ""
lengths = []
for line in fileinput.input():
if not line or sorted(line)[:2][-1] < " " or max(line) > "~":
error(1)
lengths.append(len(line))
accumulator = 0
for char in line:
value = ord(char)
try:
source += chr(value ^ (accumulator >> 1))
except:
error(1)
accumulator += value - 32
lengths.append(len(lengths) + 1)
if min(lengths) != max(lengths):
error(1)
stack = ""
for line in fileinput.input("-"):
stack += line
stack = [stack]
try:
interpret(source)
except:
error(3)
print("".join(map(str, stack)))
```
---
1 Each line is padded with random garbage to the amount of lines, and the linefeeds aren't actually present.
2 The numbers at the bottom indicate the lowest and highest code point in the Changeling code, which must stay between 32 and 126.
[Answer]
## HPR, written in Python 3 ([Cracked by TheNumberOne](https://codegolf.stackexchange.com/a/62448/32014))
HPR (the name means nothing) is a language for processing lists of integers.
It is designed to be **minimalistic**, **extremely limited**, and **free of "artificial" restrictions**.
Programming in HPR is painful, not because you have to solve a puzzle to keep the interpreter from shouting at you, but because it's hard to make a program do anything useful.
I don't know whether HPR is capable of anything substantially more interesting than computing the third largest element of a list.
## Language specification
An HPR program is run in an *environment*, which is an unordered duplicate-free set of nonnegative integers and lists of nonnegative integers.
Initially, the environment contains only the input list (the interpreter parses it for you).
There are three commands and two "control flow" operators that modify the environment:
* `*` removes the first element of every non-empty list in the environment, and places it in the environment. Empty lists are not affected. For example, it transforms
```
{4,1,[0,2],[1,3],[]} -> {4,1,0,[2],[3],[]}
```
* `-` decrements all numbers in the environment, and then removes negative elements. For example, it transforms
```
{4,2,0,[0,2],[4,4,4]} -> {3,1,[0,2],[4,4,4]}
```
* `$` rotates every list in the environment one step to the left. For example, it transforms
```
{4,1,[0,2],[3,4,1]} -> {4,1,[2,0],[4,1,3]}
```
* `!(A)(B)`, where `A` and `B` are programs, is basically a `while` loop. It performs the "action" `A` until the "test" `B` would result in an empty environment. This may produce an infinite loop.
* `#(A)(B)`, where `A` and `B` are programs, applies `A` and `B` to the current environment and takes the symmetric difference of the results.
The commands are executed from left to right.
At the end, the size of the environment is printed in unary.
## The interpreter
This interpreter features the debug command `?`, which prints the environment without modifying it.
It should not appear in any solution to the task.
Any characters except `*-$!#()?` are simply ignored, so you can write comments directly into the code.
Finally, the interpreter recognizes the idiom `!(A)(#(A)())` as "perform `A` until the result no longer changes", and optimizes it for extra speed (I needed it to get my solution to finish in under an hour on the last test case).
```
import sys
def parse(prog):
"Parse a prefix of a string into an AST. Return it and the remaining input."
ret = []
while prog:
if prog[0] in "#!":
sub1, prog1 = parse(prog[2:])
sub2, prog2 = parse(prog1[1:])
ret += [prog[0],sub1,sub2]
prog = prog2
elif prog[0] == ')':
prog = prog[1:]
break
else:
ret += [prog[0]]
prog = prog[1:]
return ret, prog
def intp(ast, L_env, N_env):
"Interpret the AST on an environment, return the resulting environment."
ptr = 0
while ptr < len(ast):
cmd = ast[ptr]
if cmd == '*':
N_env = N_env | set(L[0] for L in L_env if L)
L_env = set(L[1:] for L in L_env)
ptr += 1
elif cmd == '-':
N_env = set(N-1 for N in N_env if N>0)
ptr += 1
elif cmd == '$':
L_env = set(L[1:]+L[:1] for L in L_env)
ptr += 1
elif cmd == '!':
# Speed optimization
cond = ast[ptr+2]
if cond == ['#', ast[ptr+1], []]:
L_next, N_next = intp(ast[ptr+1], L_env, N_env)
while L_next != L_env or N_next != N_env:
L_env, N_env = L_next, N_next
L_next, N_next = intp(ast[ptr+1], L_env, N_env)
else:
while True:
L_test, N_test = intp(cond, L_env, N_env)
if not L_test and not N_test:
break
L_env, N_env = intp(ast[ptr+1], L_env, N_env)
ptr += 3
elif cmd == '#':
L_env1, N_env1 = intp(ast[ptr+1], L_env, N_env)
L_env2, N_env2 = intp(ast[ptr+2], L_env, N_env)
L_env = L_env1 ^ L_env2
N_env = N_env1 ^ N_env2
ptr += 3
elif cmd == '?':
print(L_env | N_env)
ptr += 1
else:
ptr += 1
return L_env, N_env
def main(p, L):
"Run the program on the input, return the output."
# Parse the input list
L = ''.join(c for c in L if c in "01")
while "00" in L:
L = L.replace("00","0")
L = [-2] + [i for i in range(len(L)-1) if L[i:i+2] == "10"]
L = tuple(b-a-1 for (a,b) in zip(L, L[1:]))
# Parse the program
ast = parse(p)[0]
L_env, N_env = intp(ast, set([L]), set())
return '1'*(len(L_env) + len(N_env))
if __name__ == "__main__":
filename = sys.argv[1]
f = open(filename, 'r')
prog = f.read()
f.close()
L = input()
print(main(prog, L))
```
---
## My solution
My reference solution is 484 bytes long, so quite short compared to TheNumberOne's 3271-byte program. This is most likely because of the sophisticated and awesome macro system TheNumberOne developed for programming in HPR. The main idea in both our programs is similar:
1. Find out how to produce the maximum element of a list.
2. To remove the maximum element, rotate the list until the first element equals the maximum, then pop it.
3. Remove the maximum twice, then print the new maximum element.
However, as far as I can tell, the exact implementation details are quite different. Here's my solution:
```
!($)(!(-)(#(-)())#(!(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))(#(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))())#(-)(#(!(-)(#(-)()))()))(*)#(!(-)(#(-)()))())*!(-)(#(-)())!($)(!(-)(#(-)())#(!(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))(#(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))())#(-)(#(!(-)(#(-)()))()))(*)#(!(-)(#(-)()))())*!(-)(#(-)())!(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))(#(-#(!(*)(#(*)())#(!(-)(#(-)()))())(!(-)(#(-)())))())-#(!(-)(#(-)()))()
```
And here's the commented Python program that produces it (nothing fancy here, just basic string manipulation to get rid of all the repetition):
```
# No numbers in the environment
no_nums = "#(-)()"
# No non-empty lists in the environment
no_lists = "#(*)()"
# Remove all numbers from the environment
del_nums = "!(-)(" + no_nums + ")"
# Remove all lists from the environment
del_lists = "#(" + del_nums + ")()"
# Splat the list to the environment:
# pop the list until it's empty and delete the empty list,
# then take symmetric difference with all numbers removed
splat = "#(!(*)(" + no_lists + ")" + del_lists + ")(" + del_nums + ")"
# Put into the environment all numbers up to list maximum:
# decrement and splat until a fixed point is reached.
# Without the speed optimization, this is very slow if the list elements are large.
splat_upto = "!(-" + splat + ")(#(-" + splat + ")())"
# Copy maximum element to environment:
# take all elements up to maximum,
# then take symmetric difference of decrement and list deletion
copy_max = splat_upto + "#(-)(" + del_lists + ")"
# Delete maximum element from list:
# rotate until first element is maximal, then pop and delete it
del_max = "!($)(" + del_nums + "#(" + copy_max + ")(*)" + del_lists + ")*" + del_nums
# Full program:
# remove the maximum twice, then produce all numbers up to maximum,
# then decrement and remove lists. The environment will contain exactly
# the integers from 0 to third largest - 1, and their number is printed.
main = del_max + del_max + splat_upto + "-" + del_lists
print(main)
```
[Answer]
# TKDYNS (To Kill the Dragon, You Need a Sword) - [Cracked by Martin Büttner](https://codegolf.stackexchange.com/questions/61805/create-a-programming-language-that-only-appears-to-be-unusable-robbers-thread/62134#62134)
EDIT: I've added my solution and explanation below the main post.
### Background
In this language, you take control of a valiant warrior who has been tasked with slaying a terrible dragon. The dragon lives in an underground labyrinth, full of perils and dangers, and until now, no-one has been able to map it out and survive. This means you must navigate your way to the dragon in pitch darkness, with nothing but intuition and bravery to guide you.
...
Well, not quite. You've brought an almost limitless supply of disposable minions with you, and they are willing to go ahead of you to discover the safe route. Unfortunately, they're all as thick as two short planks, and will only do exactly what you tell them to do. It's up to you to come up with a clever method of ensuring that your minions discover the correct path.
### Some more details
The dragon's lair takes the form of a 10x10 grid. Between certain adjacent points in the grid, there is a narrow walkway; between others, there is a deep chasm and certain death. An example layout for a 4x4 grid might be as follows:
```
0---1 2---3
| | |
4---5---6 7
| |
8 9--10 11
| |
12--13--14--15
```
You know that there is always a way to get from one point to any other point, but no more than that has been revealed to you.
To successfully defeat the dragon, you first need to collect some items which you will be able to combine together to create a magical dragon-slaying blade. Conveniently, all the pieces for this weapon have been scattered around the dragon's lair. You simply have to collect them.
The twist is that each piece of the weapon has been booby-trapped. Every time one is collected, the layout of the walkways changes. Previously safe paths might now lead to certain death, and vice-versa.
### Commands
There are only 5 valid commands.
* `<` - Take a step to the left
* `>` - Take a step to the right
* `^` - Take a step upwards
* `v` - Take a step downwards
* `c` - Collect any items that happen to be lying around at your current position. If there were items present, the layout of the lair changes. With positions numbered in rows as above, take your position modulo 10. There are 10 layouts hard-coded into the interpreter, and the layout changes to the corresponding one. For example, if you are at position 13, then the layout changes to `layouts[3]`
The layouts as they appear in the interpeter have been encoded to integers in the following way:
* The empty layout is encoded to zero.
* For each edge in the layout, let `x` be the smaller of the two positions that it joins.
+ If the step is horizontal, add `2^(2*x)` to the encoding (that's power-of, not XOR)
+ If the step is vertical, add `2^(2*x + 1)` to the encoding.
### Execution flow
The interpreter is run with the name of a source file as a command-line argument.
When the interpreter is run, it will prompt the user to provide a quest. This input should be in the form described in the question, and determines the locations in the lair of the components of the weapon. Specifically, each input integer is taken modulo 100, and placed at the corresponding location in the lair.
Each source program consists of several lines, each line consisting of some sequence of the above 5 valid characters. These lines represent your minions. You, the warrior, keep track of a sequence of actions known to be safe. Initially, you know nothing about the lair, so this sequence is empty. Taking each minion in turn, the following is performed, starting from position 0:
* The minion is instructed to perform all the known-to-be-safe actions, followed by the actions in its own line of code.
+ If the minion dies at any point, you are notified of this, and the lair resets to its initial configuration. All items are replaced, and the walkways return to their starting positions.
+ If, instead, the minion survives, then you vaporize it anyway - it's only a minion, after all. As before, this triggers the resetting of the lair to its initial state, but this time, you append the actions from the minion's line of code to the sequence of known-to-be-safe actions.
Once all minions have been exhausted, you, the warrior, perform all of the actions that are known to be safe, again starting from position 0. There are two possible outcomes:
* You collect all the pieces of the weapon - in this case, you successfully slay the dragon, and an exciting victory message is output. This victory message will contain, among other characters, `n` ones, where `n` is the third highest number provided as input.
* You have failed to collect some of the pieces of the weapon - in this case, the dragon lives on, and you have failed in your quest.
### Interpreter code (Python 2)
```
import collections
import copy
import sys
size = 10
layouts = [108705550239329248440770931020110627243913363144548922111951,108386637020100924277694952798729434993885646706222210602969,133885860318189115027934177821170081234850573770998325845482,102397795295522647918061101991513921833376565032742993744791,131948019244359669407266662537098175265242405785636894694611,127512068876349726396523358265982765442984953916545984706958,106817519055019354200334114020150263381328246524221867629943,33472343358375525802921815863230485208221126168622186265959,133909781123963725874096031069972704024813281938330035579187,132244654022332695610020359820518831299843076834682749020986]
class Interpreter(object):
def __init__(self, source_file):
self.source_filename = source_file
self.layout = layouts[0]
self.position = 0
self.ingredients = []
self.quest_items = {}
self.attempts = collections.deque()
self.safe_position = 0
self.safe_ingredients = []
self.safe_quest_items = {}
self.safe_layout = layouts[0]
def get_input(self):
s = raw_input("Which quest would you like to embark on today?")
ind = s.find('00')
s = s[:ind]
items = map(len, s.split('0'))
for item in items:
if item not in self.safe_quest_items:
self.safe_quest_items[item] = 1
else:
self.safe_quest_items[item] += 1
def parse_attempts(self):
with open(self.source_filename, 'r') as source:
for line in source:
self.attempts.append(line.strip())
def enc(self, x, y):
x, y = min(x, y), max(x, y)
if x < 0:
return 0
if y == x + 1:
return 1 << (2*x)
elif y == x + size:
return 1 << (2*x + 1)
else:
return 0
def exec_command(self, char):
if char == '<':
if self.enc(self.position, self.position-1) & self.layout:
self.position -= 1
else:
return False
elif char == '>':
if self.enc(self.position, self.position+1) & self.layout:
self.position += 1
else:
return False
elif char == '^':
if self.enc(self.position, self.position-size) & self.layout:
self.position -= size
else:
return False
elif char == 'v':
if self.enc(self.position, self.position+size) & self.layout:
self.position += size
else:
return False
elif char == 'c':
for item in xrange(self.position, 10**6, size*size):
if item in self.quest_items:
self.ingredients += ([item] * self.quest_items.pop(item))
self.ingredients.sort()
self.layout = layouts[self.position % 10]
else:
raise ValueError
return True
def run_minion(self):
minion = self.attempts.popleft()
self.position = self.safe_position
self.ingredients = copy.copy(self.safe_ingredients)
self.quest_items = copy.copy(self.safe_quest_items)
self.layout = self.safe_layout
dead = False
for cmd in minion:
if not self.exec_command(cmd):
dead = True
if not dead:
self.safe_position = self.position
self.safe_ingredients = copy.copy(self.ingredients)
self.safe_quest_items = copy.copy(self.quest_items)
self.safe_layout = self.layout
def process_minions(self):
while self.attempts:
self.run_minion()
def final_run(self):
if len(self.safe_quest_items) == 0:
print "You killed the dragon" + "!!1" * self.safe_ingredients[-3]
else:
print "The dragon lives on. Better luck next time..."
def interpret(self):
self.get_input()
self.parse_attempts()
self.process_minions()
self.final_run()
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Wrong number of arguments"
else:
test = Interpreter(sys.argv[1])
test.interpret()
```
Best of luck, valiant warrior.
## My solution and explanation
Here's a Python script that generates source code to solve the problem. For interest, Martin's final source code is about 5 times smaller than the code produced by my script. On the other hand, my script to generate the code is about 15 times smaller than Martin's Mathematica program...
```
size = 10
layouts = [108705550239329248440770931020110627243913363144548922111951,108386637020100924277694952798729434993885646706222210602969,133885860318189115027934177821170081234850573770998325845482,102397795295522647918061101991513921833376565032742993744791,131948019244359669407266662537098175265242405785636894694611,127512068876349726396523358265982765442984953916545984706958,106817519055019354200334114020150263381328246524221867629943,33472343358375525802921815863230485208221126168622186265959,133909781123963725874096031069972704024813281938330035579187,132244654022332695610020359820518831299843076834682749020986]
def enc(edge):
x,y = min(edge), max(edge)
if x < 0:
return 0
if y == x + 1:
return 1 << (2*x)
elif y == x + size:
return 1 << (2*x + 1)
def path(x, y, tree):
stack = [(x,'')]
while stack[-1][0] != y:
vertex, path = stack.pop()
if (enc((vertex, vertex+1))&tree) and ((not path) or path[-1] != '<'):
stack.append((vertex+1, path+'>'))
if (enc((vertex, vertex-1))&tree) and ((not path) or path[-1] != '>'):
stack.append((vertex-1, path+'<'))
if (enc((vertex, vertex+size))&tree) and ((not path) or path[-1] != '^'):
stack.append((vertex+size, path+'v'))
if (enc((vertex, vertex-size))&tree) and ((not path) or path[-1] != 'v'):
stack.append((vertex-size, path+'^'))
return stack[-1][1]
def reverse(path):
rev = ''
for i in xrange(len(path)-1, -1 ,-1):
if path[i] == '<':
rev += '>'
if path[i] == '>':
rev += '<'
if path[i] == 'v':
rev += '^'
if path[i] == '^':
rev += 'v'
return rev
def assert_at(x, tree):
path_ul = path(x, 0, tree)
path_dr = path(x, size*size - 1, tree)
return path_ul + reverse(path_ul) + path_dr + reverse(path_dr)
def safe_path(x, y, tree):
return assert_at(x, tree) + path(x, y, tree)
with open('source.txt', 'w') as f:
for x in xrange(size*size - 1):
for tree in layouts:
f.write(safe_path(x, x+1, tree) + 'c\n')
```
### Basic structure
This generates 990 lines of source code, which come in groups of 10. The first 10 lines all contain instructions that attempt to move a minion from position `0` to position `1`, and then collect an item - one set for each possible layout. The next 10 lines all contain instructions that attempt to move a minion from position `1` to position `2`, and then collect an item. And so on... These paths are calculated with the `path` function in the script - it just does a simple depth-first search.
If we can ensure that, in each group of 10, precisely one minion succeeds, then we will have solved the problem.
### The issue with the approach
It might not always be the case that precisely one minion from the group of 10 succeeds - for instance, a minion designed to get from position `0` to position `1` might accidentally succeed in moving from position `1` to position `2` (due to similarities in the layouts), and that miscalculation will propagate through, potentially causing failure.
### How to fix it
The fix that I used was as follows:
For each minion that is trying to get from position `n` to `n+1`, first make him walk from position `n` to position `0` (the top-left corner) and back again, then from position `n` to position `99` (the bottom-right corner) and back again. These instructions can only be safely carried out from position `n` - any other starting position and the minion will walk off the edge.
These extra instructions therefore prevent minions from accidentally going somewhere they aren't meant to, and this ensures that exactly one minion from each group of 10 is successful. Note that it is not necessarily the minion you expect it to be - it might be the case that the minion who believes he is in layout 0 succeeds, even when we are really in layout 7 - but in any case, the fact that we have now changed position means that all other minions in the group will necessarily die. These extra steps are calculated by the `assert_at` function, and the `safe_path` function returns a path which is the concatenation of these extra steps with the ordinary path.
[Answer]
# *Acc!!* (safe)
It's baack...
[![enter image description here](https://i.stack.imgur.com/fYRFJ.gif)](http://www.gocomics.com/bloomcounty/1983/11/06)
... and ~~hopefully~~ definitely more loophole-proof.
### I already read the *[Acc!](https://codegolf.stackexchange.com/a/62404/16766)* spec. How is *Acc!!* different?
In *Acc!!*, loop variables go out of scope when the loop exits. You can only use them inside the loop. Outside, you'll get a "name is not defined" error. Other than this change, the languages are identical.
### Statements
Commands are parsed line by line. There are three types of command:
1. `Count <var> while <cond>`
Counts `<var>` up from 0 as long as `<cond>` is nonzero, equivalent to C++ `for(int <var>=0; <cond>; <var>++)`. The loop counter can be any single lowercase letter. The condition can be any expression, not necessarily involving the loop variable. The loop halts when the condition's value becomes 0.
Loops require K&R-style curly braces (in particular, [the Stroustrup variant](https://en.wikipedia.org/wiki/Indent_style#Variant:_Stroustrup)):
```
Count i while i-5 {
...
}
```
As mentioned above, **loop variables are only available inside their loops**; attempting to reference them afterwards causes an error.
2. `Write <charcode>`
Outputs a single character with the given ASCII/Unicode value to stdout. The charcode can be any expression.
3. Expression
Any expression standing by itself is evaluated and assigned back to the accumulator (which is accessible as `_`). Thus, e.g., `3` is a statement that sets the accumulator to 3; `_ + 1` increments the accumulator; and `_ * N` reads a character and multiplies the accumulator by its charcode.
**Note:** the accumulator is the only variable that can be directly assigned to; loop variables and `N` can be used in calculations but not modified.
The accumulator is initially 0.
### Expressions
An expression can include integer literals, loop variables (`a-z`), `_` for the accumulator, and the special value `N`, which reads a character and evaluates to its charcode each time it is used. **Note:** this means you only get one shot to read each character; the next time you use `N`, you'll be reading the next one.
Operators are:
* `+`, addition
* `-`, subtraction; unary negation
* `*`, multiplication
* `/`, integer division
* `%`, modulo
* `^`, exponentiation
Parentheses can be used to enforce precedence of operations. Any other character in an expression is a syntax error.
### Whitespace and comments
Leading and trailing whitespace and empty lines are ignored. Whitespace in loop headers must be exactly as shown, with a single space between the loop header and opening curly brace as well. Whitespace inside expressions is optional.
`#` begins a single-line comment.
### Input/Output
*Acc!!* expects a single line of characters as input. Each input character can be retrieved in sequence and its charcode processed using `N`. Trying to read past the last character of the line causes an error. A character can be output by passing its charcode to the `Write` statement.
### Interpreter
The interpreter (written in Python 3) translates *Acc!!* code into Python and `exec`s it.
```
import re, sys
def main():
if len(sys.argv) != 2:
print("Please supply a filename on the command line.", file=sys.stderr)
return
codeFile = sys.argv[1]
with open(codeFile) as f:
code = f.readlines()
code = translate(code)
exec(code, {"inputStream": (ord(char) for char in input())})
def translate(accCode):
indent = 0
loopVars = []
pyCode = ["_ = 0"]
for lineNum, line in enumerate(accCode):
if "#" in line:
# Strip comments
line = line[:line.index("#")]
line = line.strip()
if not line:
continue
lineNum += 1
if line == "}":
if indent:
loopVar = loopVars.pop()
pyCode.append(" "*indent + loopVar + " += 1")
indent -= 1
pyCode.append(" "*indent + "del " + loopVar)
else:
raise SyntaxError("Line %d: unmatched }" % lineNum)
else:
m = re.fullmatch(r"Count ([a-z]) while (.+) \{", line)
if m:
expression = validateExpression(m.group(2))
if expression:
loopVar = m.group(1)
pyCode.append(" "*indent + loopVar + " = 0")
pyCode.append(" "*indent + "while " + expression + ":")
indent += 1
loopVars.append(loopVar)
else:
raise SyntaxError("Line %d: invalid expression " % lineNum
+ m.group(2))
else:
m = re.fullmatch(r"Write (.+)", line)
if m:
expression = validateExpression(m.group(1))
if expression:
pyCode.append(" "*indent
+ "print(chr(%s), end='')" % expression)
else:
raise SyntaxError("Line %d: invalid expression "
% lineNum
+ m.group(1))
else:
expression = validateExpression(line)
if expression:
pyCode.append(" "*indent + "_ = " + expression)
else:
raise SyntaxError("Line %d: invalid statement "
% lineNum
+ line)
return "\n".join(pyCode)
def validateExpression(expr):
"Translates expr to Python expression or returns None if invalid."
expr = expr.strip()
if re.search(r"[^ 0-9a-z_N()*/%^+-]", expr):
# Expression contains invalid characters
return None
elif re.search(r"[a-zN_]\w+", expr):
# Expression contains multiple letters or underscores in a row
return None
else:
# Not going to check validity of all identifiers or nesting of parens--
# let the Python code throw an error if problems arise there
# Replace short operators with their Python versions
expr = expr.replace("^", "**")
expr = expr.replace("/", "//")
# Replace N with a call to get the next input character
expr = expr.replace("N", "inputStream.send(None)")
return expr
if __name__ == "__main__":
main()
```
---
## Solution
The downfall of the original *Acc!* was loop variables that continued to be accessible outside of their loops. This allowed saving copies of the accumulator, which made the solution far too easy.
Here, without this *loop*hole (sorry), we have only the accumulator to store stuff. To solve the task, though, we need to store four arbitrarily large values.1 The solution: interleave their bits and store the resulting combination number in the accumulator. For example, an accumulator value of 6437 would store the following data (using the lowest-order bit as a single-bit flag):
```
1100100100101 Binary representation of accumulator
321032103210F Key
The flag is 1 and the four numbers are
Number 0: 010 = 2
Number 1: 001 = 1
Number 2: 100 = 4
Number 3: 110 = 6
```
We can access any bit of any number by dividing the accumulator by the appropriate power of 2, mod 2. This also allows for setting or flipping individual bits.
At the macro level, the algorithm loops over the unary numbers in the input. It reads a value into number 0, then does a pass of the bubble sort algorithm to place it in proper position compared to the other three numbers. Finally, it discards the value that's left in number 0, as it is the smallest of the four now and can never be third-largest. When the loop is over, number 1 is the third-largest, so we discard the others and output it.
The hardest part (and the reason I had global loop variables in the first incarnation) is comparing two numbers to know whether to swap them. To compare two bits, we can turn a truth table into a mathematical expression; my breakthrough for *Acc!!* was finding a comparison algorithm that proceeded from low-order to high-order bits, since without global variables there's no way to loop over a number's bits from left to right. The lowest-order bit of the accumulator stores a flag that signals whether to swap the two numbers currently under consideration.
I suspect that *Acc!!* is Turing-complete, but I'm not sure I want to go to the trouble of proving it.
Here's my solution with comments:
```
# Read and process numbers until the double 0
Count y while N-48 {
# Read unary number and store it (as binary) in number 0
# The above loop header consumed the first 1, so we need to add 1 to number 0
_ + 2
# Increment number 0 for each 1 in input until next 0
Count z while N-48 {
# In this context, the flag indicates a need to carry; set it to 1
_ - _%2 + 1
# While carry flag is set, increment the next bit in line
Count i while _%2 {
# Set carry flag to 1 if i'th bit is 1, 0 if it's 0
# Set i'th bit to 1 if it was 0, 0 if it was 1
_ - _%2 + _/2^(i*4+1)%2 + (-1)^(_/2^(i*4+1)%2)*2^(i*4+1)
}
}
# Bubble number 0 upwards
Count n while n-3 {
# The flag (rightmost bit of accumulator) needs to become 1 if we want to swap
# numbers (n) and (n+1) and 0 if we don't
# Iterate over bit-groups of accumulator, RTL
Count i while _/2^(i*4+1) {
# Adjust the flag as follows:
# _/2^(i*4+n+1)%4 is the current bit of number (n+1) followed by the current
# bit of number (n), a value between 0 and 3
# - If this quantity is 1 (01), number (n) is bigger so far; set flag to 1
# - If this quantity is 2 (10), number (n+1) is bigger so far; set flag to 0
# - If this quantity is 0 (00) or 3 (11), the two bits are the same; keep
# current value of flag
_ + (_/2^(i*4+n+1)%4%3 + 1)/2*(_/2^(i*4+n+1)%4%3%2 - _%2)
}
# Now swap the two if the flag is 1
Count i while (_%2)*(_/2^(i*4+1)) {
# _/2^(i*4+n+1)%2 is the current bit of number (n)
# _/2^(i*4+n+2)%2 is the current bit of number (n+1)
_ - (_/2^(i*4+n+1)%2)*2^(i*4+n+1) - (_/2^(i*4+n+2)%2)*2^(i*4+n+2) + (_/2^(i*4+n+2)%2)*2^(i*4+n+1) + (_/2^(i*4+n+1)%2)*2^(i*4+n+2)
}
}
# Discard number 0, setting it to all zeros for the next iteration
Count i while _/2^(i*4+1) {
_ - _/2^(i*4+1)%2*2^(i*4+1)
}
}
# Once the loop is over, all input has been read and the result is in number 1
# Divide by 2 to get rid of flag bit
_ / 2
# Zero out numbers 2 and 3
Count i while _/2^(i*4) {
_ - _/2^(i*4+2)%2*2^(i*4+2)
}
Count i while _/2^(i*4) {
_ - _/2^(i*4+3)%2*2^(i*4+3)
}
# Move bits of number 1 down to their final locations
Count i while _/2^i {
_ - _/2^(i*4+1)%2*2^(i*4+1) + _/2^(i*4+1)%2*2^i
}
# _ now contains the correct answer in decimal; to output in unary:
Count z while z-_ {
Write 49
}
```
1 According to the question spec, only values up to 1 million need to be supported. I'm glad nobody took advantage of that for an easier solution--though I'm not entirely sure how you would do the comparisons.
[Answer]
# Firetype, [Cracked by Martin Büttner](https://codegolf.stackexchange.com/a/62018/21009)
A really weird mix of BF and CJam. And who knows what else! Pretty sure this'll be
an easy one, but it was fun anyway. FYI, the name is referring to [Vermillion Fire from Final Fantasy Type-0](https://www.youtube.com/watch?v=CN_aeXySgq0).
**NOTE**: Please forgive me for any ambiguities in this description. I'm not the best writer... :O
Martin cracked this really quickly! This was my original program to solve the problem:
```
_
,
^
~
+
|
|
-
%
+
_
+
=
`
~
+
|
%
_
=
\
@
-
-
!
<
>
>
>
_
+
.
<
-
`
~
~
+
|
|
-
#
%
```
## Syntax
A Firetype script is basically a list of lines. The first character of each line is
the command to run. Empty lines are basically NOPs.
## Semantics
You have an array of integers and a pointer (think BF). You can move left and
right or "push" elements onto the array.
## Pushing
When you "push" an element and you're at the end of the array, an extra element
will be appended to the end. If you're not at the end, the next element will be
overriden. Regardless, the pointer will always be incremented.
## Commands
### `_`
Push a zero onto the array.
### `+`
Increment the element at the current pointer.
### `-`
Decrement the element at the current pointer.
### `*`
Double the element at the current pointer.
### `/`
Halve the element at the current pointer.
### `%`
Take the element at the current pointer and jump forward that many lines, and move the pointer to the left. If the
value is negative, jump backwards instead.
### `=`
Take the element at the current pointer and jump to that line + 1. For instance, if
the current element is `0`, this will jump to line `1`. This also moves the pointer to the left.
### `,`
Read a character from standard input and push its ASCII value.
### `^`
Take the element at the current pointer, interpret it as the ASCII value for a
character, and convert it to an integer. For instance, if the current value is `49`
(the ASCII value of `1`), the element at the current pointer will be set to the
integer `1`.
### `.`
Write the current number to the screen.
### `!`
Take the element at the current pointer and repeat the next line that many times. Also moves the pointer to the left.
### `<`
Move the pointer left. If you're already at the beginning, an error is thrown.
### `>`
Move the pointer right. If you're already at the end, an error is thrown.
### `~`
If the current element is nonzero, replace it with `0`; otherwise, replace it with
`1`.
### `|`
Square the current element.
### `@`
Set the current element to the length of the array.
### ```
Duplicate the current element.
### `\`
Sort the elements at and before the pointer.
### `#`
Negate the current element.
## The interpreter
Also available at [Github](https://github.com/kirbyfan64/firetype).
```
#!/usr/bin/env python
# The FireType interpreter.
# Runs under Python 2 and 3.
import sys
class Array(object):
def __init__(self):
self.array = []
self.ptr = 0
def push_zero(self):
if self.ptr == len(self.array):
self.array.append(0)
else:
self.array[self.ptr] = 0
self.ptr += 1
def left(self):
self.ptr -= 1
assert self.ptr >= 0 and self.array, 'pointer underflow (at %d)' % i
def right(self):
self.ptr += 1
assert self.ptr <= len(self.array), 'pointer overflow (at %d)' % i
def sort(self):
lhs = self.array[:self.ptr-1]
rhs = self.array[self.ptr-1:]
lhs.sort()
lhs.reverse()
self.array = lhs + rhs
def __call__(self, *args):
args = list(args)
assert self.array, 'out-of-bounds (at %d)' % i
if not args:
return self.array[self.ptr-1]
self.array[self.ptr-1] = args.pop()
assert not args
def __len__(self):
return len(self.array)
def __str__(self):
return 'Array(array=%s, ptr=%s)' % (self.array, self.ptr)
def __repr__(self):
return 'Array(array=%r, ptr=%r)' % (self.array, self.ptr)
def execute(lines):
global i, array
i = 0
array = Array()
rep = 0
while i < len(lines):
line = lines[i]
if not line:
i += 1
continue
line = line[0]
if line == '_':
array.push_zero()
elif line == '+':
array(array() + 1)
elif line == '-':
array(array() - 1)
elif line == '*':
array(array() * 2)
elif line == '/':
array(int(array() / 2))
elif line == '%':
i += array()
array.left()
elif line == '=':
i = array()-1
array.left()
elif line == ',':
array.push_zero()
array(ord(sys.stdin.read(1)))
elif line == '.':
sys.stdout.write(str(array()))
elif line == '!':
rep = array()
array.left()
i += 1
elif line == '<':
array.left()
elif line == '>':
array.right()
elif line == '^':
array(int(chr(array())))
elif line == '~':
array(int(not array()))
elif line == '|':
array(array() ** 2)
elif line == '@':
array(len(array))
elif line == '`':
top = array()
array.push_zero()
array(top)
elif line == '\\':
array.sort()
elif line == '#':
array(-array())
if rep:
rep -= 1
else:
i += 1
def main(args):
try:
_, path = args
except ValueError:
sys.exit('usage: %s <file to run, - for stdin>')
if path == '-':
data = sys.stdin.read()
else:
with open(path) as f:
data = f.read()
try:
execute(data.split('\n'))
except:
print('ERROR!')
print('Array was %r' % array)
print('Re-raising error...')
raise
if __name__ == '__main__':
main(sys.argv)
```
[Answer]
## Picofuck (safe)
Picofuck is similar to [Smallfuck](https://esolangs.org/wiki/Smallfuck). It operates on a binary tape which is unbound on the right, bound on the left. It has the following commands:
* `>` move the pointer right
* `<` move the pointer left. If the pointer falls off the tape, the program terminates.
* `*` flip the bit at the pointer
* `(` if the bit at the pointer is `0`, jump to the next `)`
* `)` do nothing - parentheses in Picofuck are `if` blocks, not `while` loops.
* `.` write to stdout the bit at the pointer as an ascii `0` or `1`.
* `,` read from stdin until we encounter a `0` or `1`, and store this in the bit at the pointer.
Picofuck code wraps - once the end of the program is reached, it continues from the beginning.
In addition, Picofuck disallows nested parentheses. Parentheses appearing in a Picofuck program must alternate between `(` and `)`, starting with `(` and ending with `)`.
## Interpreter
Written in Python 2.7
usage: `python picofuck.py <source_file>`
```
import sys
def interpret(code):
# Ensure parentheses match and are not nested.
in_if_block = False
for c in code:
if c == '(':
if in_if_block:
print "NESTED IFS DETECTED!!!!!"
return
in_if_block = True
elif c == ')':
if not in_if_block:
print "Unmatched parenthesis"
return
in_if_block = False
if in_if_block:
print "Unmatched parenthesis"
return
code_ptr = 0
array = [0]
ptr = 0
while 1:
command = code[code_ptr]
if command == '<':
if ptr == 0:
break
ptr -= 1
elif command == '>':
ptr += 1
if ptr == len(array):
array.append(0)
elif command == '*':
array[ptr] = 1-array[ptr]
elif command == '(':
if array[ptr] == 0:
while code[code_ptr] != ')':
code_ptr = (code_ptr + 1) % len(code)
elif command == ',':
while True:
c = sys.stdin.read(1)
if c in ['0','1']:
array[ptr] = int(c)
break
elif command == '.':
sys.stdout.write(str(array[ptr]))
code_ptr = (code_ptr+1)%len(code)
if __name__ == "__main__":
with open(sys.argv[1]) as source_file:
code = source_file.read()
interpret(code)
```
# Solution
The following python 2.7 program outputs my solution which can be found [here](https://www.dropbox.com/s/9xs6sedwhvukgz1/third.pf?dl=0)
I may edit this post later with a more thorough explanation of how this works, but it turns out that Picofuck is Turing-complete.
```
states = {
"SETUP":(
"*>",
"GET_NUMBER",
"GET_NUMBER"
),
"GET_NUMBER":(
",",
"CHANGE_A",
"PREPARE_PRINT_C"
),
"GET_DIGIT":(
",",
"CHANGE_A",
"GOT_DIGIT"
),
"GOT_DIGIT":(
">>>>",
"GO_BACK",
"GO_BACK"
),
"CHANGE_A":(
">",
"CHANGE_B",
"SET_A"
),
"SET_A":(
"*>>>>",
"GET_DIGIT",
"GET_DIGIT"
),
"CHANGE_B":(
">",
"CHANGE_C",
"SET_B"
),
"SET_B":(
"*>>>",
"GET_DIGIT",
"GET_DIGIT"
),
"CHANGE_C":(
">",
"CONTINUE_GET_NUMBER",
"SET_C"
),
"SET_C":(
"*>>",
"GET_DIGIT",
"GET_DIGIT"
),
"CONTINUE_GET_NUMBER":(
">>",
"GET_DIGIT",
"GET_DIGIT"
),
"GO_BACK":(
"<<<<<",
"FINISH_GO_BACK",
"GO_BACK"
),
"FINISH_GO_BACK":(
">",
"GET_NUMBER",
"GET_NUMBER"
),
"PREPARE_PRINT_C":(
">>>",
"PRINT_C",
"PRINT_C"
),
"PRINT_C":(
".>>>>>",
"PRINT_C",
"TERMINATE"
),
"TERMINATE":(
"<",
"TERMINATE",
"TERMINATE"
),
}
def states_to_nanofuck(states,start_state):
state_list = list(states)
state_list.remove(start_state)
state_list.insert(0,start_state)
states_by_index = []
for i,state in enumerate(state_list):
commands, next1, next0 = states[state]
states_by_index.append((commands,state_list.index(next1),state_list.index(next0)))
# setup first state
fragments = ['*(*>>>>>*<<<<<)>>>>>']
# reset states that don't match
for index in range(len(states_by_index)):
for bool in range(2):
# at state_0_0
state_dist = index*3 + bool
# move state to curstate
fragments.append('>'*state_dist)
fragments.append('(*')
fragments.append( '<'*state_dist)
fragments.append( '<<*>>')
fragments.append( '>'*state_dist)
fragments.append(')')
fragments.append('<'*state_dist)
# go to arr
fragments.append('<<<')
if bool == 0:
#flip arr
fragments.append('*')
# compute match = arr & curstate
fragments.append('(>)(>*<)<(<)>')
if bool == 0:
#flip arr
fragments.append('*')
# reset curstate
fragments.append('>(*)')
# move match to matchstate, go back to state_0_0
matchstate_dist = index*3 + 2
fragments.append('>(*>')
fragments.append( '>'*matchstate_dist)
fragments.append( '*')
fragments.append( '<'*matchstate_dist)
fragments.append('<)>')
#fragments.append('|')
# do the commands of the matching state
for index,state in enumerate(states_by_index):
for bool in range(2):
# at state_0_0
matchstate_dist = index*3 + 2
# move matchstate to curstate
fragments.append('>'*matchstate_dist)
fragments.append('(*')
fragments.append( '<'*matchstate_dist)
fragments.append( '<<*>>')
fragments.append( '>'*matchstate_dist)
fragments.append(')')
fragments.append('<'*matchstate_dist)
# if curstate, reset curstate
fragments.append('<<(*')
# go to arr
fragments.append('<')
# do commands
commands,next1,next0 = state
for c in commands:
if c in '<>':
fragments.append(c*(3*len(states_by_index)+5))
else:
fragments.append(c)
# go to state_0_0
fragments.append('>>>')
# set next states
for dist in [next0*3, next1*3+1]:
fragments.append('>'*dist)
fragments.append('*')
fragments.append('<'*dist)
# go to curstate
fragments.append('<<')
# end if
fragments.append(')')
# go to state_0_0
fragments.append('>>')
# go back to setup and set it
fragments.append('<<<<<*')
code = ''.join(fragments)
return code
print states_to_nanofuck(states, "SETUP")
```
[Answer]
# *PQRS* – Safe! / Solution Provided
**Basics**
All implied instructions have four memory address operands:
```
P₀ Q₀ R₀ S₀
P₁ Q₁ R₁ S₁
...
Pᵥ₋₁ Qᵥ₋₁ Rᵥ₋₁ Sᵥ₋₁
```
Where `v` is the size of memory in quartets.
`Pᵢ`, `Qᵢ`, `Rᵢ`, `Sᵢ` are signed integers in your machine's native size (e.g. 16, 32 or 64 bits) which we will refer to as words.
For each quartet `i`, the implied operation, with `[]` denoting indirection, is:
```
if (([Pᵢ] ← [Qᵢ] − [Rᵢ]) ≤ 0) go to Sᵢ else go to Pᵢ₊₁
```
Note that [Subleq](http://esolangs.org/wiki/subleq "Subleq") is a subset of *PQRS*.
Subleq has been proven complete, so *PQRS* should be complete as well!
**Program Structure**
*PQRS* defines an initial header as follows:
```
H₀ H₁ H₂ H₃ H₄ H₅ H₆ H₇
```
`H₀ H₁ H₂ H₃` is always the first instruction `P₀ Q₀ R₀ S₀`. `H₀` to `H₃` need to be defined at load time.
*PQRS* has rudimentary I/O, but sufficient for the challenge.
`H₄ H₅`: at program start, it reads in a maximum of `H₅` ASCII characters from standard input and saves as words at index `H₄` onwards. `H₄` and `H₅` need to be defined at load time. After reading, `H₅` will be set to the number of characters read (and words saved).
`H₆ H₇`: at program termination, starting at index `H₆`, it prints all the bytes comprising the `H₇` words to standard output as ASCII characters. `H₆` and `H₇` need to be defined before the program ends. Null bytes `'\0'` in the output will be skipped over.
**Termination**
Termination is achieved by setting `Sᵢ` out of bounds `i < 0` or `i ≥ v`.
**Tricks**
Quartets `Pᵢ Qᵢ Rᵢ Sᵢ` need not be aligned or sequential, branching is permitted at sub-quartet intervals.
*PQRS* has indirection so, unlike Subleq, there is enough flexibility to implement subroutines.
Code can be self-modifying!
**Interpreter**
The interpreter is written in C:
```
#include <stdlib.h>
#include <stdio.h>
// The "architecture"
enum {P, Q, R, S, START_OF_INPUT, LENGTH_OF_INPUT, START_OF_OUTPUT, LENGTH_OF_OUTPUT};
const int NEXT = S + 1;
// Recommend optimized!
#define OPTIMIZED
#ifdef PER_SPECS
// This may not work on all OSes and architectures - just too much memory needed!
const int K = 1002000200;
#else // OPTIMIZED
// This provides enough space to run the test cases with challenge-optimized.pqrs
const int K = 5200;
#endif
int main(int argc, char *argv[])
{
int i, *M;
char *p;
FILE *program;
// Allocate enough memory
M = calloc(K, sizeof(int));
// Load the program
for (i = 0, program = fopen(argv[1], "r"); i < K && !feof(program); i++)
if (!fscanf(program, "%d", M + i))
break;
fclose(program);
// Read in the input
for (i = 0; i < M[LENGTH_OF_INPUT] && !feof(stdin); i++)
{
int c = fgetc(stdin);
if (c != EOF)
M[M[START_OF_INPUT] + i] = c;
else
break;
}
M[LENGTH_OF_INPUT] = i;
// Execute until terminated
for (i = 0; i >= 0 && i < K; )
i = (M[M[P + i]] = M[M[Q + i]] - M[M[R + i]]) <= 0? M[S + i]: i + NEXT;
// Write the output
for (i = 0, p = (char *)(M + M[START_OF_OUTPUT]); i < M[LENGTH_OF_OUTPUT] * sizeof(int); i++)
// Ignore '\0'
if (p[i])
fputc(p[i], stdout);
// Done
free(M);
return 0;
}
```
To use, save the above as pqrs.c then compile:
```
gcc -o pqrs pqrs.c
```
**Sample program**
Echos input up to 40 characters, preceded by 'PQRS-'.
```
8 8 8 -1 14 40 9 45 0 80 81 82 83 45
```
To run, save the above as `echo.pqrs`, then:
```
$ ./prqs echo.pqrs
greetings[enter]
[ctrl-D]
PQRS-greetings
```
Running the test cases:
```
$ ./pqrs challenge-optimized.pqrs < test-1.txt
1
$ ./pqrs challenge-optimized.pqrs < test-2.txt
11111111111111111
$ ./pqrs challenge-optimized.pqrs < test-3.txt
[lots of ones!]
$ ./pqrs challenge-optimized.pqrs < test-3.txt | wc
0 1 773
```
All the test cases run extremely quickly, e.g. < 500 ms.
**The challenge**
*PQRS* can be deemed stable, so the challenge begins 2015-10-31 13:00 and ends 2015-11-08 13:00, times in UTC.
Good luck!
**Solution**
The language is quite similar to the one used in ["Baby"](http://history-computer.com/ModernComputer/Electronic/SSEM.html "Baby") – the world's first stored-program electronic digital machine. On that page is a program to find the highest factor of an integer in less than 32 words of (CRT!) memory!
I found writing the solution to conform to the specs was not compatible with the OS and machine I was using (a Linux Ubuntu derivative on slightly older hardware). It was just requesting more memory than available, and core dumping. On OSes with advanced virtual memory management or machines with at least 8 GB memory, you can probably run the solution per specs. I have provided both solutions.
It is very difficult to code in *PQRS* directly, akin to writing machine language, maybe even microcode. Instead it is easier to write in a kind of assembly language then "compile" it. Below is annotated assembly language for the solution optimized to run the test cases:
```
; ANNOTATED PQRS ASSEMBLER CODE
; MINIMAL SIZED BUFFERS TO RUN THE TEST CASES
;OFFSET LABEL P-OP Q-OP R-OP S-OP
0 TEMP ZERO ZERO L1
; INPUT AND OUTPUT LOCATIONS AND SIZES
4 INPUT 4000
6 L0: OUTPUT 1000
; GET CURRENT INPUT
8 L1: TEMP INPUT ASCII_ZERO L2
12 SUM SUM INC IGNORE
16 L1+1 L1+1 INC IGNORE
20 TEMP ZERO ZERO L1
; CHECK IF END OF NUMBERS
24 L2: NUMBERS SUM ZERO L3
; ADVANCE TO NEXT NUMBER
28 L2 L2 INC IGNORE
; ADVANCE COUNT
32 COUNT COUNT INC IGNORE
36 L1+1 L1+1 INC IGNORE
; CLEAR SUM AND GO BACK
40 SUM ZERO ZERO L1
; SORT NUMBERS
44 L3: P NUMBERS ZERO LA
48 L4: Q NUMBERS+1 ZERO L9
; COMPARE
52 TEMP Q P L8
; SWAP IF OUT OF ORDER
56 L5+1 L3+1 ZERO IGNORE
60 L6 L3+1 ZERO IGNORE
64 L6+1 L4+1 ZERO IGNORE
68 L7 L4+1 ZERO IGNORE
72 L5: TEMP P ZERO IGNORE
76 L6: P Q ZERO IGNORE
80 L7: Q TEMP ZERO IGNORE
; INCREMENT INNER INDEX
84 L8: L4+1 L4+1 INC IGNORE
88 TEMP ZERO ZERO L3
; INCREMENT OUTER INDEX AND RESET INNER INDEX
92 L9: L3+1 L3+1 INC IGNORE
96 L4+1 L3+1 INC IGNORE
100 TEMP ZERO ZERO L3
; OUTPUT THIRD LARGEST NUMBER
104 L0+1 NUMBERS+2 ZERO IGNORE
108 LA: TEMP NUMBERS+2 ZERO EXIT
112 LB: OUTPUT ASCII_ONE ZERO IGNORE
116 LB LB INC IGNORE
120 NUMBERS+2 NUMBERS+2 DEC EXIT
124 TEMP ZERO ZERO LA
; SAFETY LOOP – JUST IN CASE IGNORE DOESN'T WORK AS PLANNED!
128 IGNORE: TEMP ZERO ZERO IGNORE
; CONSTANTS
132 ZERO: 0
133 INC: -1
134 DEC: 1
135 ASCII_ZERO: 48
136 ASCII_ONE: 49
; VARIABLES
137 TEMP: [1]
138 SUM: [1]
139 COUNT: [1]
140 P: [1]
141 Q: [1]
; WORKING SPACE
142 NUMBERS: [10]
; I/O SPACE
152 INPUT: [4000]
4152 OUTPUT: [1000]
5152
```
What it does is parse the input, converting unary to binary, then a bubble sort on the numbers with the values in decreasing order, then finally outputs the third largest value by converting binary back to unary.
Note that `INC` (increment) is negative and `DEC` (decrement) is positive! Where it's using `L#` or `L#+1` as `P-` or `Q-OP`s, what's going on is that it is updating pointers: incrementing, decrementing, swapping, etc. The assembler was hand compiled to *PQRS* by substituting the labels with the offsets. Below is the *PQRS* optimized solution:
```
137 132 132 8
152 4000
4152 1000
137 152 135 24
138 138 133 128
9 9 133 128
137 132 132 8
142 138 132 44
24 24 133 128
139 139 133 128
9 9 133 128
138 132 132 8
140 142 132 108
141 143 132 92
137 141 140 84
73 45 132 128
76 45 132 128
77 49 132 128
80 49 132 128
137 140 132 128
140 141 132 128
141 137 132 128
49 49 133 128
137 132 132 44
45 45 133 128
49 45 133 128
137 132 132 44
7 144 132 128
137 144 132 -1
4152 136 132 128
112 112 133 128
144 144 134 -1
137 132 132 108
137 132 132 128
0
-1
1
48
49
```
The code above can be saved as `challenge-optimized.pqrs` to run the test cases.
For completeness, here are the per specs source:
```
; ANNOTATED PQRS ASSEMBLER CODE
; FULL SIZED BUFFERS TO RUN ACCORDING TO SPECS
;OFFSET LABEL P-OP Q-OP R-OP S-OP
0 TEMP ZERO ZERO L1
; INPUT AND OUTPUT LOCATIONS AND SIZES
4 INPUT 10^9
6 L0: OUTPUT 10^6
; GET CURRENT INPUT
8 L1: TEMP INPUT ASCII_ZERO L2
12 SUM SUM INC IGNORE
16 L1+1 L1+1 INC IGNORE
20 TEMP ZERO ZERO L1
; CHECK IF END OF NUMBERS
24 L2: NUMBERS SUM ZERO L3
; ADVANCE TO NEXT NUMBER
28 L2 L2 INC IGNORE
; ADVANCE COUNT
32 COUNT COUNT INC IGNORE
36 L1+1 L1+1 INC IGNORE
; CLEAR SUM AND GO BACK
40 SUM ZERO ZERO L1
; SORT NUMBERS
44 L3: P NUMBERS ZERO LA
48 L4: Q NUMBERS+1 ZERO L9
; COMPARE
52 TEMP Q P L8
; SWAP IF OUT OF ORDER
56 L5+1 L3+1 ZERO IGNORE
60 L6 L3+1 ZERO IGNORE
64 L6+1 L4+1 ZERO IGNORE
68 L7 L4+1 ZERO IGNORE
72 L5: TEMP P ZERO IGNORE
76 L6: P Q ZERO IGNORE
80 L7: Q TEMP ZERO IGNORE
; INCREMENT INNER INDEX
84 L8: L4+1 L4+1 INC IGNORE
88 TEMP ZERO ZERO L3
; INCREMENT OUTER INDEX AND RESET INNER INDEX
92 L9: L3+1 L3+1 INC IGNORE
96 L4+1 L3+1 INC IGNORE
100 TEMP ZERO ZERO L3
; OUTPUT THIRD LARGEST NUMBER
104 L0+1 NUMBERS+2 ZERO IGNORE
108 LA: TEMP NUMBERS+2 ZERO EXIT
112 LB: OUTPUT ASCII_ONE ZERO IGNORE
116 LB LB INC IGNORE
120 NUMBERS+2 NUMBERS+2 DEC EXIT
124 TEMP ZERO ZERO LA
; SAFETY LOOP – JUST IN CASE IGNORE DOESN'T WORK AS PLANNED!
128 IGNORE: TEMP ZERO ZERO IGNORE
; CONSTANTS
132 ZERO: 0
133 INC: -1
134 DEC: 1
135 ASCII_ZERO: 48
136 ASCII_ONE: 49
; VARIABLES
137 TEMP: [1]
138 SUM: [1]
139 COUNT: [1]
140 P: [1]
141 Q: [1]
; WORKING SPACE
142 NUMBERS: [10^6]
; I/O SPACE
1000142 INPUT: [10^9]
1001000142 OUTPUT: [10^6]
1002000142
```
And solution:
```
137 132 132 8
1000142 1000000000
1001000142 1000000
137 1000142 135 24
138 138 133 128
9 9 133 128
137 132 132 8
142 138 132 44
24 24 133 128
139 139 133 128
9 9 133 128
138 132 132 8
140 142 132 108
141 143 132 92
137 141 140 84
73 45 132 128
76 45 132 128
77 49 132 128
80 49 132 128
137 140 132 128
140 141 132 128
141 137 132 128
49 49 133 128
137 132 132 44
45 45 133 128
49 45 133 128
137 132 132 44
7 144 132 128
137 144 132 -1
1001000142 136 132 128
112 112 133 128
144 144 134 -1
137 132 132 108
137 132 132 128
0
-1
1
48
49
```
To run the above, you will need to comment out `#define OPTIMIZED` and add `#define PER_SPECS` in `pqrs.c` and recompile.
This was a great challenge – really enjoyed the mental workout! Took me back to my old 6502 assembler days...
If I were to implement *PQRS* as a “real” programming language, I would probably add additional modes for direct and doubly indirect access in addition to indirect access, as well as position relative and position absolute, both with indirect access options for the branching!
[Answer]
# Compass Soup ([cracked by cardboard\_box](https://codegolf.stackexchange.com/a/63343/32671))
*Interpreter: C++*
Compass Soup is kind of like a Turing machine with an infinite 2-dimensional tape. The main catch is that the instruction memory and data memory are in the same space, and the output of the program is the entire contents of that space.
[![enter image description here](https://i.stack.imgur.com/ZvgjE.png)](https://i.stack.imgur.com/ZvgjE.png)
**How it works**
A program is a 2-dimensional block of text. The program space starts with the entire source code placed with the first character at (0,0). The rest of the program space is infinite and is initialized with null characters (ASCII 0).
There are two pointers that can move around the program space:
* The execution pointer has a location and a direction (North, South, East, or West). Each tick, the instruction under the execution pointer is executed, then the execution pointer moves in its current direction. The execution pointer starts moving east (positive x), at the location of the `!` character or at (0,0) if that doesn't exist.
* The data pointer has only a location. It is moved with the instructions `x`, `X`, `y`, and `Y`. It starts at the location of the `@` character or at (0,0) if that doesn't exist.
**Input**
The contents of stdin are printed into the program space starting at the location of the `>` character, or at (0,0) if that doesn't exist.
**Output**
The program terminates when the execution pointer runs irretrievably out of bounds. The output is the entire contents of the program space at that time. It is sent to stdout and 'result.txt'.
**Instructions**
* `n` - redirects the execution pointer North (negative y)
* `e` - redirects the execution pointer East (positive x)
* `s` - redirects the execution pointer South (positive y)
* `w` - redirects the execution pointer West (negative x)
* `y` - moves the data pointer North (negative y)
* `X` - moves the data pointer East (positive x)
* `Y` - moves the data pointer South (positive y)
* `x` - moves the data pointer West (negative x)
* `p` - writes the next character encountered by the execution pointer at the data pointer. That character isn't executed as an instruction.
* `j` - checks the next character encountered by the execution pointer against the character under the data pointer. That character isn't executed as an instruction. If they are the same, the execution pointer jumps over the next character.
* `c` - writes the null character at the data pointer.
* `*` - breakpoint - just causes the interpreter to break.
All other characters are ignored by the execution pointer.
**Interpreter**
The interpreter takes the source file as an argument and input on stdin. It has a steppable debugger, which you can invoke with a breakpoint instruction in the code (`*`). When broken, the execution pointer is shown as ASCII 178 (darker shaded block) and the data pointer is shown as ASCII 177 (lighter shaded block).
```
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
// Compass Soup programming language interpreter
// created by Brian MacIntosh (BMacZero)
// for https://codegolf.stackexchange.com/questions/61804/create-a-programming-language-that-only-appears-to-be-unusable
//
// 31 October 2015
struct Point
{
int x, y;
Point(int ix, int iy) { x = ix; y = iy; };
bool operator==(const Point &other) const
{
return other.x == x && other.y == y;
}
bool operator!=(const Point &other) const
{
return other.x != x || other.y != y;
}
};
struct Bounds
{
int xMin, xMax, yMin, yMax;
Bounds(int xmin, int ymin, int xmax, int ymax)
{
xMin = xmin; yMin = ymin; xMax = xmax; yMax = ymax;
}
bool contains(Point pt)
{
return pt.x >= xMin && pt.x <= xMax && pt.y >= yMin && pt.y <= yMax;
}
int getWidth() { return xMax - xMin + 1; }
int getHeight() { return yMax - yMin + 1; }
bool operator==(const Bounds &other) const
{
return other.xMin == xMin && other.xMax == xMax && other.yMin == yMin && other.yMax == yMax;
}
bool operator!=(const Bounds &other) const
{
return other.xMin != xMin || other.xMax != xMax || other.yMin != yMin || other.yMax != yMax;
}
};
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }
Bounds hull(Point a, Bounds b)
{
return Bounds(min(a.x, b.xMin), min(a.y, b.yMin), max(a.x, b.xMax), max(a.y, b.yMax));
}
Bounds hull(Bounds a, Bounds b)
{
return Bounds(min(a.xMin, b.xMin), min(a.yMin, b.yMin), max(a.xMax, b.xMax), max(a.yMax, b.yMax));
}
Bounds programBounds(0,0,0,0);
char** programSpace;
Point execPtr(0,0);
Point execPtrDir(1,0);
Point dataPtr(0,0);
Point stdInPos(0,0);
bool breakpointHit = false;
char breakOn = 0;
/// reads the character from the specified position
char read(Point pt)
{
if (programBounds.contains(pt))
return programSpace[pt.x - programBounds.xMin][pt.y - programBounds.yMin];
else
return 0;
}
/// read the character at the data pointer
char readData()
{
return read(dataPtr);
}
/// read the character at the execution pointer
char readProgram()
{
return read(execPtr);
}
/// gets the bounds of the actual content of the program space
Bounds getTightBounds(bool debug)
{
Bounds tight(0,0,0,0);
for (int x = programBounds.xMin; x <= programBounds.xMax; x++)
{
for (int y = programBounds.yMin; y <= programBounds.yMax; y++)
{
if (read(Point(x, y)) != 0)
{
tight = hull(Point(x, y), tight);
}
}
}
if (debug)
{
tight = hull(dataPtr, tight);
tight = hull(execPtr, tight);
}
return tight;
}
/// ensure that the program space encompasses the specified rectangle
void fitProgramSpace(Bounds bounds)
{
Bounds newBounds = hull(bounds, programBounds);
if (newBounds == programBounds) return;
// allocate new space
char** newSpace = new char*[newBounds.getWidth()];
// copy content
for (int x = 0; x < newBounds.getWidth(); x++)
{
newSpace[x] = new char[newBounds.getHeight()];
for (int y = 0; y < newBounds.getHeight(); y++)
{
Point newWorldPos(x + newBounds.xMin, y + newBounds.yMin);
newSpace[x][y] = read(newWorldPos);
}
}
// destroy old space
for (int x = 0; x < programBounds.getWidth(); x++)
{
delete[] programSpace[x];
}
delete[] programSpace;
programSpace = newSpace;
programBounds = newBounds;
}
/// outputs the current program space to a file
void outputToStream(std::ostream &stream, bool debug)
{
Bounds tight = getTightBounds(debug);
for (int y = tight.yMin; y <= tight.yMax; y++)
{
for (int x = tight.xMin; x <= tight.xMax; x++)
{
char at = read(Point(x, y));
if (debug && x == execPtr.x && y == execPtr.y)
stream << (char)178;
else if (debug && x == dataPtr.x && y == dataPtr.y)
stream << (char)177;
else if (at == 0)
stream << ' ';
else
stream << at;
}
stream << std::endl;
}
}
/// writes a character at the specified position
void write(Point pt, char ch)
{
fitProgramSpace(hull(pt, programBounds));
programSpace[pt.x - programBounds.xMin][pt.y - programBounds.yMin] = ch;
}
/// writes a character at the data pointer
void write(char ch)
{
write(dataPtr, ch);
}
/// writes a line of text horizontally, starting at the specified position
void writeLine(Point loc, std::string str, bool isSource)
{
fitProgramSpace(Bounds(loc.x, loc.y, loc.x + str.size(), loc.y));
for (unsigned int x = 0; x < str.size(); x++)
{
programSpace[x + loc.x][loc.y] = str[x];
// record locations of things
if (isSource)
{
switch (str[x])
{
case '>':
stdInPos = Point(loc.x + x, loc.y);
break;
case '!':
execPtr = Point(loc.x + x, loc.y);
break;
case '@':
dataPtr = Point(loc.x + x, loc.y);
break;
}
}
}
}
void advanceExecPtr()
{
execPtr.x += execPtrDir.x;
execPtr.y += execPtrDir.y;
}
void breakpoint()
{
breakpointHit = true;
outputToStream(std::cout, true);
std::cout << "[Return]: step | [Space+Return]: continue | [<char>+Return]: continue to <char>" << std::endl;
while (true)
{
std::string input;
std::getline(std::cin, input);
if (input.size() == 0)
{
break;
}
else if (input.size() == 1)
{
if (input[0] == ' ')
{
breakpointHit = false;
break;
}
else
{
breakOn = input[0];
breakpointHit = false;
break;
}
}
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("Usage: CompassSoup <source-file>");
return 1;
}
// open source file
std::ifstream sourceIn(argv[1]);
if (!sourceIn.is_open())
{
printf("Error reading source file.");
return 1;
}
programSpace = new char*[1];
programSpace[0] = new char[1];
programSpace[0][0] = 0;
// read starting configuration
std::string line;
int currentLine = 0;
while (std::getline(sourceIn, line))
{
writeLine(Point(0, currentLine), line, true);
currentLine++;
}
sourceIn.close();
// take stdin
std::string input;
std::cout << ">";
std::cin >> input;
std::cin.ignore();
writeLine(stdInPos, input, false);
// execute
while (programBounds.contains(execPtr))
{
if (execPtrDir.x == 0 && execPtrDir.y == 0)
{
printf("Implementation error: execPtr is stuck.");
break;
}
advanceExecPtr();
char command = readProgram();
// breakpoint control code
if (breakpointHit || (breakOn != 0 && command == breakOn))
{
breakOn = 0;
breakpoint();
}
switch (command)
{
case 'n':
execPtrDir = Point(0,-1);
break;
case 'e':
execPtrDir = Point(1,0);
break;
case 's':
execPtrDir = Point(0,1);
break;
case 'w':
execPtrDir = Point(-1,0);
break;
case 'x':
dataPtr.x--;
break;
case 'X':
dataPtr.x++;
break;
case 'y':
dataPtr.y--;
break;
case 'Y':
dataPtr.y++;
break;
case 'p':
advanceExecPtr();
write(readProgram());
break;
case 'j':
advanceExecPtr();
if (readData() == readProgram())
{
advanceExecPtr();
}
break;
case 'c':
write(0);
break;
case '*':
breakpoint();
break;
}
}
std::ofstream outputFile("result.txt");
outputToStream(outputFile, false);
outputToStream(std::cout, false);
outputFile.close();
}
```
**Examples**
Hello World
```
Hello, World!
```
Cat
```
>
```
Parity: accepts a string of characters terminated by a zero ('0'). Outputs `yes` on the first line of the output if the number of 1s in the input is odd, otherwise outputs `|`.
```
|>
!--eXj1s-c-eXj0s-c-exj|s-pyXpeXps
c | c | | |
cn0j-w---n1j-w n---w
```
**Tips**
You should use a good text editor and make judicious use of the functionality of the 'Insert' key, and use 'Alt-Drag' to add or delete text on multiple rows at once.
**Solution**
Here is my solution. It's not as nice as cardboard\_box's because I had to make the source code delete itself. I was also hoping I could find a way to delete all of the code and leave only the answer, but I couldn't.
My approach was to split the different sequences of `1`s onto different lines, then sort them by having the `1`s all "fall" up until they hit another `1`, and finally erase everything except the third line after the input.
* The big block to the bottom-right of `#A#` reads `1`s and copies them to the last line of the split until a `0` is read.
* `#B#` checks for a second `0` and goes north to `#D#` there is one. Otherwise, `#C#` starts a new split line by putting `|` after the last one, and goes back to `#A#`.
* The block at and above `#F#` is the gravity code. It walks to the last `1` of the first row and moves it up until it hits `1` or `-`. If it can't do that, it marks the row as finished by putting `+` before it.
* `#G#` is erasing all the unneeded splits, and `#H#` is erasing stdin and all the code between the parentheses.
Code:
```
s-----------------------w
s-c-w s-c-w s---w e+-
eXj)nc-eXj)nc-exj(ncyj(nn
(n-----------------------------------------w ))
( #H# s---w | ))
( exj+ncyxn ))
( | ))
( s---w s-c-+w ))
( exj+ncy-eXj1nn ))
( | ))
( s---w s-c-+w s+pxw ))
( eyj-n-YY-eXj1nn | sn1jX--w e----s ))
( | Y x e+---s e---s ns1jyw ))
( ej+n------s j | nn+jYw-n+jxw-Yw | ))
( Y ec----s e---s| | 1 ))
( c ns1jX-wYcYYY-n-jyww | p ))
( ns+jxw #G# e--s Y ))
( e---n | s------w| ))
( | | ej-nn ))
( s--w e----s exc----eyj1n---n ))
(#A# p e+---s s---w |#F#| ))
(e----se---s 1 || | exj|n----p+YeXj1ns ))
(ns-jXwn-jyw--w-nn1jXw c #D# n----w ))
( | | | | ))
( | n---------+---+-------------|pw s---w s---w ))
( | | | exp)XYs | eyj-nYeXj0ns)
( | s---ws---+w n-----+-----+---+------------+----------w))
( | | || || e--yp)n e---+--s | )
( | e-c-exj|neYj|nn | #C# | | p ))
( | | | s---w s---+w s---w s---+w ))
( | | #B# e+s | | | || | | | || ))
(!ep-Yj0n-c----------Xj0nne----exj|n-eYj|nn exj|n-eYj|nn ))
(-@
|>
```
[Answer]
# Zinc, [Cracked! by @Zgarb](https://codegolf.stackexchange.com/a/62300/21009)
Also available at [GitHub](https://github.com/kirbyfan64/zinc).
You need Dart 1.12 and Pub. Just run `pub get` to download the only
dependency, a parsing library.
Here's to hoping to this one lasts longer than 30 minutes! :O
## The language
Zinc is oriented around redefining operators. You can redefine all the operators
in the language easily!
The structure of a typical Zinc program looks like:
```
let
<operator overrides>
in <expression>
```
There are only two data types: integers and sets. There is no such thing as a set
literal, and empty sets are disallowed.
## Expressions
The following are valid expressions in Zinc:
### Literals
Zinc supports all the normal integer literals, like `1` and `-2`.
### Variables
Zinc has variables (like most languages). To reference them, just use the name.
Again like most languages!
However, there is a special variable called `S` that behaves kind of like Pyth's
`Q`. When you first use it, it will read in a line from standard input and
interpret it as a set of numbers. For instance, the input line `1234231` would
turn into the set `{1, 2, 3, 4, 3, 2, 1}`.
**IMPORTANT NOTE!!!** In some cases, a literal at the end of an operator override
is parsed incorrectly, so you have to surround it with parentheses.
### Binary operations
The following binary operations are supported:
* Addition via `+`: `1+1`.
* Subtraction via `-`: `1-1`.
* Multiplication via `*`: `2*2`.
* Division via `/`: `4/2`.
* Equality with `=`: `3=3`.
Additionally, the following unary operation is also supported:
* Length with `#`: `#x`.
Precedence is always right-associative. You can use parentheses to override this.
Only equality and length work on sets. When you try to get the length of an
integer, you will get the number of digits in its string representation.
### Set comprehensions
In order to manipulate sets, Zinc has set comprehensions. They look like this:
```
{<variable>:<set><clause>}
```
A clause is either a when clause or a sort clause.
A *when clause* looks like `^<expression>`. The expression following the caret must
result in an integer. Using the when clause will take only the elements in the set
for which `expression` is non-zero. Within the expression, the variable `_` will
be set to the current index in the set. It is roughly equivalent to this Python:
```
[<variable> for _, <variable> in enumerate(<set>) when <expression> != 0]
```
A *sort clause*, which looks like `$<expression>`, sorts the set descending by the
value of `<expression>`. It is equal to this Python:
```
sorted(<set>, key=lambda <variable>: <expression>)[::-1]
```
Here are some comprehension examples:
* Take only the elements of set `s` that equal 5:
```
{x:s^x=5}
```
* Sort the set `s` by the value if its elements squared:
```
{x:s$x*x}
```
## Overrides
Operator overrides allow you to redefine operators. They look like this:
```
<operator>=<operator>
```
or:
```
<variable><operator><variable>=<expression>
```
In the first case, you can define an operator to equal another operator. For
instance, I can define `+` to actually subtract via:
```
+=-
```
When you do this, you can redefine an operator to be a *magic operator*. There
are two magic operators:
* `join` takes a set and an integer and joins the contents of the set. For
instance, joining `{1, 2, 3}` with `4` will result in the integer `14243`.
* `cut` also takes a set and an integer and will partition the set at every
occurence of the integer. Using `cut` on `{1, 3, 9, 4, 3, 2}` and `3` will
create `{{1}, {9, 4}, {2}}`...BUT any single-element sets are flattened, so the
result will actually be `{1, {9, 4}, 2}`.
Here's an example that redefines the `+` operator to mean `join`:
```
+=join
```
For the latter case, you can redefine an operator to the given expression. As an
example, this defines the plus operation to add the values and then add 1:
```
x+y=1+:x+:y
```
But what's `+:`? You can append the colon `:` to an operator to always use the
builtin version. This example uses the builtin `+` via `+:` to add the numbers
together, then it adds a 1 (remember, everything is right-associative).
Overriding the length operator looks kind of like:
```
#x=<expression>
```
Note that almost all the builtin operations (except equality) will use this
length operator to determine the length of the set. If you defined it to be:
```
#x=1
```
every part of Zinc that works on sets except `=` would only operate on the first
element of the set it was given.
## Multiple overrides
You can override multiple operators by separating them with commas:
```
let
+=-,
*=/
in 1+2*3
```
### Printing
You cannot directly print anything in Zinc. The result of the expression following `in` will be printed. The values of a set will be concatenated with to separator. For instance, take this:
```
let
...
in expr
```
If `expr` is the set `{1, 3, {2, 4}}`, `1324` will be printed to the screen once the program finishes.
## Putting it all together
Here's a simple Zinc program that appears to add `2+2` but causes the result to be
5:
```
let
x+y=1+:x+:y
in 1+2
```
## The interpreter
This goes in `bin/zinc.dart`:
```
import 'package:parsers/parsers.dart';
import 'dart:io';
// An error.
class Error implements Exception {
String cause;
Error(this.cause);
String toString() => 'error in Zinc script: $cause';
}
// AST.
class Node {
Obj interpret(ZincInterpreter interp) => null;
}
// Identifier.
class Id extends Node {
final String id;
Id(this.id);
String toString() => 'Id($id)';
Obj interpret(ZincInterpreter interp) => interp.getv(id);
}
// Integer literal.
class IntLiteral extends Node {
final int value;
IntLiteral(this.value);
String toString() => 'IntLiteral($value)';
Obj interpret(ZincInterpreter interp) => new IntObj(value);
}
// Any kind of operator.
class Anyop extends Node {
void set(ZincInterpreter interp, OpFuncType func) {}
}
// Operator.
class Op extends Anyop {
final String op;
final bool orig;
Op(this.op, [this.orig = false]);
String toString() => 'Op($op, $orig)';
OpFuncType get(ZincInterpreter interp) =>
this.orig ? interp.op0[op] : interp.op1[op];
void set(ZincInterpreter interp, OpFuncType func) { interp.op1[op] = func; }
}
// Unary operator (len).
class Lenop extends Anyop {
final bool orig;
Lenop([this.orig = false]);
String toString() => 'Lenop($orig)';
OpFuncType get(ZincInterpreter interp) =>
this.orig ? interp.op0['#'] : interp.op1['#'];
void set(ZincInterpreter interp, OpFuncType func) { interp.op1['#'] = func; }
}
// Magic operator.
class Magicop extends Anyop {
final String op;
Magicop(this.op);
String toString() => 'Magicop($op)';
Obj interpret_with(ZincInterpreter interp, Obj x, Obj y) {
if (op == 'cut') {
if (y is! IntObj) { throw new Error('cannot cut int with non-int'); }
if (x is IntObj) {
return new SetObj(x.value.toString().split(y.value.toString()).map(
int.parse));
} else {
assert(x is SetObj);
List<List<Obj>> res = [[]];
for (Obj obj in x.vals(interp)) {
if (obj == y) { res.add([]); }
else { res.last.add(obj); }
}
return new SetObj(new List.from(res.map((l) =>
l.length == 1 ? l[0] : new SetObj(l))));
}
} else if (op == 'join') {
if (x is! SetObj) { throw new Error('can only join set'); }
if (y is! IntObj) { throw new Error('can only join set with int'); }
String res = '';
for (Obj obj in x.vals(interp)) {
if (obj is! IntObj) { throw new Error('joining set must contain ints'); }
res += obj.value.toString();
}
return new IntObj(int.parse(res));
}
}
}
// Unary operator (len) expression.
class Len extends Node {
final Lenop op;
final Node value;
Len(this.op, this.value);
String toString() => 'Len($op, $value)';
Obj interpret(ZincInterpreter interp) =>
op.get(interp)(interp, value.interpret(interp), null);
}
// Binary operator expression.
class Binop extends Node {
final Node lhs, rhs;
final Op op;
Binop(this.lhs, this.op, this.rhs);
String toString() => 'Binop($lhs, $op, $rhs)';
Obj interpret(ZincInterpreter interp) =>
op.get(interp)(interp, lhs.interpret(interp), rhs.interpret(interp));
}
// Clause.
enum ClauseKind { Where, Sort }
class Clause extends Node {
final ClauseKind kind;
final Node expr;
Clause(this.kind, this.expr);
String toString() => 'Clause($kind, $expr)';
Obj interpret_with(ZincInterpreter interp, SetObj set, Id id) {
List<Obj> res = [];
List<Obj> values = set.vals(interp);
switch (kind) {
case ClauseKind.Where:
for (int i=0; i<values.length; i++) {
Obj obj = values[i];
interp.push_scope();
interp.setv(id.id, obj);
interp.setv('_', new IntObj(i));
Obj x = expr.interpret(interp);
interp.pop_scope();
if (x is IntObj) {
if (x.value != 0) { res.add(obj); }
} else { throw new Error('where clause condition must be an integer'); }
}
break;
case ClauseKind.Sort:
res = values;
res.sort((x, y) {
interp.push_scope();
interp.setv(id.id, x);
Obj x_by = expr.interpret(interp);
interp.setv(id.id, y);
Obj y_by = expr.interpret(interp);
interp.pop_scope();
if (x_by is IntObj && y_by is IntObj) {
return x_by.value.compareTo(y_by.value);
} else { throw new Error('sort clause result must be an integer'); }
});
break;
}
return new SetObj(new List.from(res.reversed));
}
}
// Set comprehension.
class SetComp extends Node {
final Id id;
final Node set;
final Clause clause;
SetComp(this.id, this.set, this.clause);
String toString() => 'SetComp($id, $set, $clause)';
Obj interpret(ZincInterpreter interp) {
Obj setobj = set.interpret(interp);
if (setobj is SetObj) {
return clause.interpret_with(interp, setobj, id);
} else { throw new Error('set comprehension rhs must be set type'); }
}
}
// Operator rewrite.
class OpRewrite extends Node {
final Anyop op;
final Node value;
final Id lid, rid; // Can be null!
OpRewrite(this.op, this.value, [this.lid, this.rid]);
String toString() => 'OpRewrite($lid, $op, $rid, $value)';
Obj interpret(ZincInterpreter interp) {
if (lid != null) {
// Not bare.
op.set(interp, (interp,x,y) {
interp.push_scope();
interp.setv(lid.id, x);
if (rid == null) { assert(y == null); }
else { interp.setv(rid.id, y); }
Obj res = value.interpret(interp);
interp.pop_scope();
return res;
});
} else {
// Bare.
if (value is Magicop) {
op.set(interp, (interp,x,y) => value.interpret_with(interp, x, y));
} else {
op.set(interp, (interp,x,y) => (value as Anyop).get(interp)(x, y));
}
}
return null;
}
}
class Program extends Node {
final List<OpRewrite> rws;
final Node expr;
Program(this.rws, this.expr);
String toString() => 'Program($rws, $expr)';
Obj interpret(ZincInterpreter interp) {
rws.forEach((n) => n.interpret(interp));
return expr.interpret(interp);
}
}
// Runtime objects.
typedef Obj OpFuncType(ZincInterpreter interp, Obj x, Obj y);
class Obj {}
class IntObj extends Obj {
final int value;
IntObj(this.value);
String toString() => 'IntObj($value)';
bool operator==(Obj rhs) => rhs is IntObj && value == rhs.value;
String dump() => value.toString();
}
class SetObj extends Obj {
final List<Obj> values;
SetObj(this.values) {
if (values.length == 0) { throw new Error('set cannot be empty'); }
}
String toString() => 'SetObj($values)';
bool operator==(Obj rhs) => rhs is SetObj && values == rhs.values;
String dump() => values.map((x) => x.dump()).reduce((x,y) => x+y);
List<Obj> vals(ZincInterpreter interp) {
Obj lenobj = interp.op1['#'](interp, this, null);
int len;
if (lenobj is! IntObj) { throw new Error('# operator must return an int'); }
len = lenobj.value;
if (len < 0) { throw new Error('result of # operator must be positive'); }
return new List<Obj>.from(values.getRange(0, len));
}
}
// Parser.
class ZincParser extends LanguageParsers {
ZincParser(): super(reservedNames: ['let', 'in', 'join', 'cut']);
get start => prog().between(spaces, eof);
get comma => char(',') < spaces;
get lp => symbol('(');
get rp => symbol(')');
get lb => symbol('{');
get rb => symbol('}');
get colon => symbol(':');
get plus => symbol('+');
get minus => symbol('-');
get star => symbol('*');
get slash => symbol('/');
get eq => symbol('=');
get len => symbol('#');
get in_ => char(':');
get where => char('^');
get sort => char('\$');
prog() => reserved['let'] + oprw().sepBy(comma) + reserved['in'] + expr() ^
(_1,o,_2,x) => new Program(o,x);
oprw() => oprw1() | oprw2() | oprw3();
oprw1() => (basicop() | lenop()) + eq + (magicop() | op()) ^
(o,_,r) => new OpRewrite(o,r);
oprw2() => (id() + op() + id()).list + eq + expr() ^
(l,_,x) => new OpRewrite(l[1], x, l[0], l[2]);
oprw3() => lenop() + id() + eq + expr() ^ (o,a,_,x) => new OpRewrite(o, x, a);
magicop() => (reserved['join'] | reserved['cut']) ^ (s) => new Magicop(s);
basicop() => (plus | minus | star | slash | eq) ^ (op) => new Op(op);
op() => (basicop() + colon ^ (op,_) => new Op(op.op, true)) | basicop();
lenop() => (len + colon ^ (_1,_2) => new Lenop(true)) |
len ^ (_) => new Lenop();
expr() => setcomp() | unop() | binop() | prim();
setcomp() => lb + id() + in_ + rec(expr) + clause() + rb ^
(_1,i,_2,x,c,_3) => new SetComp(i,x,c);
clausekind() => (where ^ (_) => ClauseKind.Where) |
(sort ^ (_) => ClauseKind.Sort);
clause() => clausekind() + rec(expr) ^ (k,x) => new Clause(k,x);
unop() => lenop() + rec(expr) ^ (o,x) => new Len(o,x);
binop() => prim() + op() + rec(expr) ^ (l,o,r) => new Binop(l,o,r);
prim() => id() | intlit() | parens(rec(expr));
id() => identifier ^ (i) => new Id(i);
intlit() => intLiteral ^ (i) => new IntLiteral(i);
}
// Interpreter.
class ZincInterpreter {
Map<String, OpFuncType> op0, op1;
List<Map<String, Obj>> scopes;
ZincInterpreter() {
var beInt = (v) {
if (v is IntObj) { return v.value; }
else { throw new Error('argument to binary operator must be integer'); }
};
op0 = {
'+': (_,x,y) => new IntObj(beInt(x)+beInt(y)),
'-': (_,x,y) => new IntObj(beInt(x)-beInt(y)),
'*': (_,x,y) => new IntObj(beInt(x)*beInt(y)),
'/': (_,x,y) => new IntObj(beInt(x)/beInt(y)),
'=': (_,x,y) => new IntObj(x == y ? 1 : 0),
'#': (i,x,_2) =>
new IntObj(x is IntObj ? x.value.toString().length : x.values.length)
};
op1 = new Map<String, OpFuncType>.from(op0);
scopes = [{}];
}
void push_scope() { scopes.add({}); }
void pop_scope() { scopes.removeLast(); }
void setv(String name, Obj value) { scopes[scopes.length-1][name] = value; }
Obj getv(String name) {
for (var scope in scopes.reversed) {
if (scope[name] != null) { return scope[name]; }
}
if (name == 'S') {
var input = stdin.readLineSync() ?? '';
var list = new List.from(input.codeUnits.map((c) =>
new IntObj(int.parse(new String.fromCharCodes([c])))));
setv('S', new SetObj(list));
return getv('S');
} else throw new Error('undefined variable $name');
}
}
void main(List<String> args) {
if (args.length != 1) {
print('usage: ${Platform.script.toFilePath()} <file to run>');
return;
}
var file = new File(args[0]);
if (!file.existsSync()) {
print('cannot open ${args[0]}');
return;
}
Program root = new ZincParser().start.parse(file.readAsStringSync());
ZincInterpreter interp = new ZincInterpreter();
var res = root.interpret(interp);
print(res.dump());
}
```
And this goes in `pubspec.yaml`:
```
name: zinc
dependencies:
parsers: any
```
## Intended solution
```
let
#x=((x=S)*(-2))+#:x,
/=cut
in {y:{x:S/0$#:x}^_=2}
```
[Answer]
# *Acc!*, [Cracc'd](https://codegolf.stackexchange.com/a/62446/16766) by ppperry
This language has one looping structure, basic integer math, character I/O, and an accumulator (thus the name). *Just one* accumulator. Thus, the name.
### Statements
Commands are parsed line by line. There are three types of command:
1. `Count <var> while <cond>`
Counts `<var>` up from 0 as long as `<cond>` is nonzero, equivalent to C-style `for(<var>=0; <cond>; <var>++)`. The loop counter can be any single lowercase letter. The condition can be any expression, not necessarily involving the loop variable. The loop halts when the condition's value becomes 0.
Loops require K&R-style curly braces (in particular, [the Stroustrup variant](https://en.wikipedia.org/wiki/Indent_style#Variant:_Stroustrup)):
```
Count i while i-5 {
...
}
```
2. `Write <charcode>`
Outputs a single character with the given ASCII/Unicode value to stdout. The charcode can be any expression.
3. Expression
Any expression standing by itself is evaluated and assigned back to the accumulator (which is accessible as `_`). Thus, e.g., `3` is a statement that sets the accumulator to 3; `_ + 1` increments the accumulator; and `_ * N` reads a character and multiplies the accumulator by its charcode.
**Note:** the accumulator is the only variable that can be directly assigned to; loop variables and `N` can be used in calculations but not modified.
The accumulator is initially 0.
### Expressions
An expression can include integer literals, loop variables (`a-z`), `_` for the accumulator, and the special value `N`, which reads a character and evaluates to its charcode each time it is used. **Note:** this means you only get one shot to read each character; the next time you use `N`, you'll be reading the next one.
Operators are:
* `+`, addition
* `-`, subtraction; unary negation
* `*`, multiplication
* `/`, integer division
* `%`, modulo
* `^`, exponentiation
Parentheses can be used to enforce precedence of operations. Any other character in an expression is a syntax error.
### Whitespace and comments
Leading and trailing whitespace and empty lines are ignored. Whitespace in loop headers must be exactly as shown, with a single space between the loop header and opening curly brace as well. Whitespace inside expressions is optional.
`#` begins a single-line comment.
### Input/Output
*Acc!* expects a single line of characters as input. Each input character can be retrieved in sequence and its charcode processed using `N`. Trying to read past the last character of the line causes an error. A character can be output by passing its charcode to the `Write` statement.
### Interpreter
The interpreter (written in Python 3) translates *Acc!* code into Python and `exec`s it.
```
import re, sys
def main():
if len(sys.argv) != 2:
print("Please supply a filename on the command line.", file=sys.stderr)
return
codeFile = sys.argv[1]
with open(codeFile) as f:
code = f.readlines()
code = translate(code)
exec(code, {"inputStream": (ord(char) for char in input())})
def translate(accCode):
indent = 0
loopVars = []
pyCode = ["_ = 0"]
for lineNum, line in enumerate(accCode):
if "#" in line:
# Strip comments
line = line[:line.index("#")]
line = line.strip()
if not line:
continue
lineNum += 1
if line == "}":
if indent:
loopVar = loopVars.pop()
if loopVar is not None:
pyCode.append(" "*indent + loopVar + " += 1")
indent -= 1
else:
raise SyntaxError("Line %d: unmatched }" % lineNum)
else:
m = re.fullmatch(r"Count ([a-z]) while (.+) \{", line)
if m:
expression = validateExpression(m.group(2))
if expression:
loopVar = m.group(1)
pyCode.append(" "*indent + loopVar + " = 0")
pyCode.append(" "*indent + "while " + expression + ":")
indent += 1
loopVars.append(loopVar)
else:
raise SyntaxError("Line %d: invalid expression " % lineNum
+ m.group(2))
else:
m = re.fullmatch(r"Write (.+)", line)
if m:
expression = validateExpression(m.group(1))
if expression:
pyCode.append(" "*indent
+ "print(chr(%s), end='')" % expression)
else:
raise SyntaxError("Line %d: invalid expression "
% lineNum
+ m.group(1))
else:
expression = validateExpression(line)
if expression:
pyCode.append(" "*indent + "_ = " + expression)
else:
raise SyntaxError("Line %d: invalid statement "
% lineNum
+ line)
return "\n".join(pyCode)
def validateExpression(expr):
"Translates expr to Python expression or returns None if invalid."
expr = expr.strip()
if re.search(r"[^ 0-9a-z_N()*/%^+-]", expr):
# Expression contains invalid characters
return None
elif re.search(r"[a-zN_]\w+", expr):
# Expression contains multiple letters or underscores in a row
return None
else:
# Not going to check validity of all identifiers or nesting of parens--
# let the Python code throw an error if problems arise there
# Replace short operators with their Python versions
expr = expr.replace("^", "**")
expr = expr.replace("/", "//")
# Replace N with a call to get the next input character
expr = expr.replace("N", "inputStream.send(None)")
return expr
if __name__ == "__main__":
main()
```
[Answer]
# GoToTape (Safe)
(Formerly know as Simp-plex.)
This language is simple. The main flow control is goto, the most natural and useful form of control.
## Language specification
Data is stored on a tape and in an accumulator. It works entirely with unsigned integrates.
Each character is command. The following are all of the commands:
* Letters: `a`-`z` are goto statements, going to `A`-`Z`, respectively.
* `:`: set the accumulator to the ASCII value to char from input.
* `~`: output the char for the ASCII value in the accumulator.
* `&`: subtract one from the the accumulator if it is 1 or more, otherwise add one.
* `|`: add one to the accumulator.
* `<`: set the data pointer to 0.
* `+`: increment the data cell at the data pointer; move the pointer +1.
* `-`: subtract one from the data cell at the data pointer if it is positive; move the pointer +1.
* `[...]`: run code n times where n is the number on the tape at the data pointer (cannot be nested).
* `/`: skip next instruction if the accumulator is 0.
## Interpreter(C++)
```
#include <iostream>
#include <memory.h>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int serch(char* str,char ch){
for(int i = 0;str[i];i++){
if(str[i]==ch)
return i;
}
return -1;
}
void runCode(char* code){
int i = 0;
char c;
unsigned int* tape;
tape = new unsigned int[1000003];
memset(tape,0,1000003*sizeof(int));
unsigned int p=0;
unsigned int a=0;
unsigned int n;
unsigned int s;
while(c=code[i]){
if('A'<=c && c<='Z');
if('a'<=c && c<='z')i=serch(code, c+'A'-'a');
if(':'==c)a=cin.get();
if('+'==c)tape[p++]++;
if('-'==c)tape[p++] += tape[p]?-1:0;
if('|'==c)a++;
if('&'==c)a=a?a-1:1;
if('<'==c)p=0;
if('['==c){if(tape[p]){n=tape[p];s=i;}else i+=serch(code+i,']');};
if(']'==c)i=--n?i:s;
if('~'==c)cout<<(char)a;
if('/'==c)i+=a?0:1;
if('$'==c)p=a;
i++;
}
delete[](tape);
}
int main(int argc, char* argv[]) {
if(argc == 2){
ifstream sorceFile (argv[1]);
string code(static_cast<stringstream const&>(stringstream() << sorceFile.rdbuf()).str());
runCode((char*)code.c_str());
}else
cout << "Code file must be included as a command-line argument \n";
return 0;
}
```
Have fun!
## Solution
`A:+&&&&&&&&&&/gbG&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/a<aB<[|]C[&]-[|]/c<[|]D[&]-[|]/d<[|]+E[&]|||||||||||||||||||||||||||||||||||||||||||||||||~X&/x-[|]/e`
[Answer]
## Slindow (safe)
Slindow is a language inspired by [this](https://codegolf.stackexchange.com/questions/171884/overlapping-polyglots) cops and robbers challenge. However, unlike the linked challenge (based on 3 consecutive items), this only involves two consequtive items, which simplifies the programming.
## Transpilation process
Slindow processes in digraphs (aka 2 consequtive characters). Due to a bug that I'm too lazy to fix (anyway it's part of the challenge! :D ), this groups the instructions like this:
```
Grouping process:
QWERTYU
QW # Instruction #1
WE # Instruction #2
ER # Instruction #3
RT # Instruction #4
TY # Instruction #5
YU # Instruction #6
```
Therefore the complete executed digraph chain is:
```
[QW,WE,ER,RT,TY,YU]
```
### The digraph mapping to Slindow/Base
Any undefined digraph throws an error and will be rejected by Slindow. Note that multiple digraphs can produce a single transpilation result. (The possible digraphs are separated by the space, since none of them contain the space.)
```
Mapping Digraphs
| : U? UD !C
) : eU p@ D!
0 : DW p6 9z
$ : ?w wD Dm
' : m@ m! m?
* : @` `? @?
; : Wp Dq eV
I : ^C $v #W
[ : ve v? 9C
{ : Cv CW vp
1 : oV km C?
_ : 64 4o Vq q9 z, ,k
```
## Slindow/Base
To simplify the language, Slindow automatically outputs the top of the stack at the end of the execution.
In the compilation-target Slindow the instructions are as follows:
* `I`: Push a single input onto the stack
* `{...;`: Pop the stack and perform each loop. Implicit operand pushed onto stack at every iteration.
* `[.A|.B;`: Pop an item off the stack. If the integer representation of that is true, execute `.A`. Else, execute `.B`.
* `)`: Increment the top of the stack.
* `|`: Else statement accompanied with the if expression above.
* `$`: Sort all items in the whole stack.
* `0`: Append a 0 onto the stack.
* `;`: Ending marker for all current-executing block-based structures.
* `1`: Append a 1 onto the stack.
* `_`: Pop the top of the stack off.
* `'`: Convert the top of the stack to its string representation.
* `*`: Python multiplication. Can also be used to repeat strings.
## Interpreter
```
# Your code goes here
slindow_code = ""
# Your input goes here
input = "101011100"
code = ""
for x,i in enumerate(slindow_code):
try:
t = i + slindow_code[x+1]
except: # Index out of bounds
continue
if t in ['wD', 'Dm', '?w']:
code += "$"
elif t in ['Dq', 'Wp', 'eV']:
code += ";"
elif t in ['Cv', 'CW', 'vp']:
code += "{"
elif t in ['@?', '`?', '@`']:
code += "*"
elif t in ['4o', 'Vq', ',k', 'q9', 'z,', '64']:
code += "_"
elif t in ['D!', 'eU', 'p@']:
code += ")"
elif t in ['UD', '!C', 'U?']:
code += "|"
elif t in ['9z', 'p6', 'DW']:
code += "0"
elif t in ['v?', '9C', 've']:
code += "["
elif t in ['C?', 'km', 'oV']:
code += "1"
elif t in ['$v', '^C', '#W']:
code += "I"
elif t in ['m@', 'm?', 'm!']:
code += "'"
else:
raise SyntaxError # Refuse to interpret
# Uncomment this if you want to check
# if your Slindoc/Base code is right.
# print(code)
# Slindow / Base interpreter
stack = [0]
out = ""
indent = ""
for i in code:
if i == "I":out += indent + "stack.append(input)\n"
if i == ")":out += indent + "stack.append(stack.pop()+1)\n"
if i == "$":out += indent + "stack.sort()\n"
if i in "01":out += indent + "stack.append("+i+")\n"
if i == "_":out += indent + "stack.pop()\n"
if i == "'":out += indent + 'stack.append(str(stack.pop()))\n'
if i == "*":out += indent + "stack.append(stack.pop()*stack.pop())\n"
if i == ";":indent = ""
if i == "{":
out += indent + "for i in stack.pop():\n"
out += indent + "\tstack.append(i)\n"
indent += "\t"
if i == "[":
out += indent + "if int(stack.pop()):\n"
indent += "\t"
if i == "|":
indent = indent[:-1]
out += indent + "else:\n"
indent = indent + "\t"
# print(out)
exec(out)
print(stack.pop())
```
[Try it online!](https://tio.run/##lZRvb9owEMZf40/hmkqBhrVEq5BIVYEGe9G3qyiaKG2zYEpEY6eOw7/2u7PzpaXGrKompFPi/J7n7mwf2VrPpPi@3Vbpb1koGssJp4@S53TGFSf5UyImcnmPy5eU3fUWfNBZ9odZ61zePLc3jXnafWDkTZ2IrNCWvHwHXdCEXxA0m4yQdy9GplLRVSMBGeWiSLmKNK/ZKeshqWi1hlgxNgn1qf15tPKDManwVcwzHdIqvRITvqIScsop/SMLMclBGkuhE1FwUkmmVJtsI2/Z9xrU66cmdpbeOEQOCvOhsmMGpk8fcP/ZYMPMRH7jwBcO3FsYrDc0cZE58IsDdzsGe8DYfXDgEwc@lwa7wWIacxOf2yZuGia2zh35vdvFEdY/MDHrOnDdgQe4P0c9EwcdB3514PYGPVu4pUMHbjrwAptto/OCO/DI3UyE53hM0t35wIGPcefv0LnqlnHlwGnXYCn6p0cO7CGcc7OooiTn9HotdLT6qRRc2Sr9xacFLGoJXpqrTHFNYAYGIpZpyoWmepbkFJKtZUGXkVmQNJ7xeA5UuazoNd7k@OxHBFaYGjQqeZzpU6AyBdY1HAJjXcJLekYR36XliuQ6iucwHaPmmBBZzhuD0ZuYQvAZBw3HzPiFOAcJvcRdCY0Cen7jfcrQ7zTKMi4mNZzg@q1glqj@lah8yWRWq/uBIz7@VJxLpWsWDeWyZvBVLuYnPnNy3H8qwpr2Ye8Q9pxulN1RHfSepT/5j904sX32y7hgoX1kHx9emLmFByl2R2pZhmh5yN7q/TMtU1fegUtD2ClH/05pvsOdtHsIv3B6RaddY@XDKPxm/rYPE@DI7Tnud8HIbjBAC3PBVzwuH8tVu7Tt9i8 "Python 3 – Try It Online")
## Solution
```
^CveU?wDWp64oVq9z,km@`
```
Decoded from digraphs:
```
I{[)|$$0;0__1__0__1'*
```
## Explanation
Golfed and explained, it looks like this:
```
I Push the input.
{ Foreach input:
[ If int(current) == 1:
) Current += 1
| Else:
$ Sort(stack)
0 stack.append(0)
; End all current looping structures.
___ Discard the trailing 0, the largest, and the second largest.
1' Push stringified 1.
* Repeat the string TOS times.
```
[Answer]
This was a bad idea since almost all esoteric languages look unreadable (look at Jelly).
But here goes:
# [Pylongolf2](https://github.com/lvivtotoro/pylongolf2/) beta6
## Pushing to the Stack
Pushing to the stack acts differently that in other languages.
The code `78` pushes `7` and `8` into the stack, however in Pylongolf it pushes `78`.
In Pylongolf2 this is toggleable with `Ü`.
## Commands
```
) Print the stack.
Ü Toggle the method Pylongolf2 uses for pushing to stack.
a The useless command, removes and adds the selected item in the same place.
c Ask for input.
n Convert string to a number.
" Toggle string mode for pushing text to the stack.
s Convert a number to a string. ╨ Encode the selected item (it must be a string).
_ Duplicate the selected item next to itself.
b Swap places between the selected item and the one before.
d Set the selected item to the last one.
m Move the selected item to the end of the stack.
@ Select an item. (Number required after this command as an argument).
w Wait a specified amount of time (the time is taken from the stack).
= Compare the selected item to the one before. (WARNING. THIS DELETES THE 2 ITEMS AND PLACES A true OR A false) (V2 beta)
~ Print the stack nicely. (V2 beta)
² Square a number. (V3 beta)
| Split a string to an array by the character after |. (V4 beta)
♀ Pop the array. (the contents are left in the stack) (V4 beta)
> Begin a while statement. (V5 beta)
< Loop back to the beginning of the while statement. (V5 beta)
! Break out of the while statements. (V5 beta)
? An if statement, does nothing if the selected item is a `true` boolean. (V6 beta)
¿ If an if statement is `false`, the interpreter skips everything to this character. (V6 beta)
```
## String Concatenation and Removing a Regex Pattern from a String
The + symbol concatenates strings.
You are able to use the - symbol to remove characters following a regex pattern from a string:
```
c╨2"[^a-zA-Z]"-~
```
This code takes input and removes all non-alphabetical characters by removing all patterns matching `[^a-zA-Z]`.
The selected item must be the regex and the one before must be the string to edit.
## If Statements
To do if statements, put a `=` to compare the selected item and the one after.
This places either a `true` or a `false` in it's place.
The command `?` checks this boolean.
If it's `true` then it does nothing and the interpreter goes on.
If it's `false` then the interpreter skips to the closest `¿` character.
Taken from the Github page.
# Interpreter for Pylongolf2 (Java):
```
package org.midnightas.pylongolf2;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Pylongolf {
public static final void main(String[] args) throws Exception {
String content = new String(Files.readAllBytes(Paths.get(new File(args[0]).toURI()))) + " ";
boolean fullreadMode = true;
List<Object> stack = new ArrayList<Object>();
List<Integer> whileStatements = new ArrayList<Integer>();
HashMap<String, Object> vars = new HashMap<String, Object>();
int ifStatements = 0;
Scanner scanner = new Scanner(new UnclosableDecorator(System.in));
int selectedIndex = 0;
for (int cl = 0; cl < content.length(); cl++) {
char c = content.charAt(cl);
if (isNumber(c)) {
if (!fullreadMode) {
stack.add(Double.parseDouble(c + ""));
} else {
String number = "";
for (int cl0 = cl; cl0 < content.length(); cl0++) {
if (isNumber(content.charAt(cl0))) {
number += content.charAt(cl0);
} else {
cl = cl0 - 1;
stack.add(Double.parseDouble(number));
break;
}
}
}
} else if (c == ')') {
System.out.println(Arrays.toString(stack.toArray()));
} else if (c == 'Ü') {
fullreadMode = !fullreadMode;
} else if (c == '+') {
if (stack.get(selectedIndex) instanceof Object[]) {
Object[] obj = (Object[]) stack.remove(selectedIndex);
Double dbl = new Double(0d);
for (Object o : obj) {
dbl += (Double) o;
}
stack.add(selectedIndex, dbl);
} else {
Object obj0 = stack.remove(selectedIndex);
Object obj1 = stack.remove(selectedIndex);
if (obj0 instanceof Number && obj1 instanceof Number)
stack.add(((Number) obj0).doubleValue() + ((Number) obj1).doubleValue());
else if (obj0 instanceof String) {
stack.add(obj0.toString() + obj1.toString());
}
}
} else if (c == '-') {
Object obj0 = stack.remove(selectedIndex);
Object obj1 = stack.remove(selectedIndex);
if (obj0 instanceof Number && obj1 instanceof Number)
stack.add(((Number) obj0).doubleValue() - ((Number) obj1).doubleValue());
else if (obj0 instanceof String && obj1 instanceof String) {
stack.add(obj0.toString().replaceAll(obj1.toString(), ""));
}
} else if (c == '*') {
Object obj0 = stack.remove(selectedIndex);
Object obj1 = stack.remove(selectedIndex);
if (obj0 instanceof Number && obj1 instanceof Number)
stack.add(((Number) obj0).doubleValue() * ((Number) obj1).doubleValue());
} else if (c == '/') {
Object obj0 = stack.remove(selectedIndex);
Object obj1 = stack.remove(selectedIndex);
if (obj0 instanceof Number && obj1 instanceof Number)
stack.add(((Number) obj0).doubleValue() / ((Number) obj1).doubleValue());
} else if (c == 'a') {
stack.add(selectedIndex, stack.remove(selectedIndex));
} else if (c == 'c') {
stack.add(scanner.nextLine());
} else if (c == 'n') {
if (stack.get(selectedIndex) instanceof String) {
stack.add(selectedIndex, Double.parseDouble(stack.remove(selectedIndex).toString()));
} else if (stack.get(selectedIndex) instanceof Object[]) {
Object[] oldArray = (Object[]) stack.remove(selectedIndex);
Object[] newArray = new Object[oldArray.length];
for (int i = 0; i < oldArray.length; i++) {
newArray[i] = Double.parseDouble(oldArray[i].toString());
}
stack.add(selectedIndex, newArray);
}
} else if (c == '"') {
String string = "\"";
for (int cl0 = cl + 1; cl0 < content.length(); cl0++) {
string = string + content.charAt(cl0);
if (content.charAt(cl0) == '"') {
stack.add(string.substring(1, string.length() - 1));
cl = cl0;
break;
}
}
} else if (c == 's') {
Object obj = stack.remove(selectedIndex);
if (obj instanceof Double) {
Double dbl = (Double) obj;
if (dbl.doubleValue() == Math.floor(dbl)) {
stack.add(selectedIndex, "" + dbl.intValue() + "");
} else {
stack.add(selectedIndex, "" + dbl + "");
}
}
} else if (c == '╨') {
cl++;
char editmode = content.charAt(cl);
if (editmode == '0') {
stack.add(selectedIndex, rot13(stack.remove(selectedIndex).toString()));
} else if (editmode == '1') {
stack.add(selectedIndex,
new StringBuilder(stack.remove(selectedIndex).toString()).reverse().toString());
} else if (editmode == '2') {
stack.add(selectedIndex, stack.remove(selectedIndex).toString().toLowerCase());
} else if (editmode == '3') {
stack.add(selectedIndex, stack.remove(selectedIndex).toString().toUpperCase());
}
} else if (c == '_') {
stack.add(selectedIndex, stack.get(selectedIndex));
} else if (c == 'b') {
stack.add(selectedIndex + 1, stack.remove(selectedIndex));
} else if (c == 'd') {
selectedIndex = stack.size() == 0 ? 0 : stack.size() - 1;
} else if (c == 'm') {
stack.add(stack.remove(selectedIndex));
} else if (c == '@') {
String number = "";
for (int cl0 = cl + 1; cl0 < content.length(); cl0++) {
if (isNumber(content.charAt(cl0)))
number += content.charAt(cl0);
else {
cl = cl0 - 1;
selectedIndex = Integer.parseInt(number);
break;
}
}
} else if (c == 'w') {
String number = "";
for (int cl0 = cl + 1; cl0 < content.length(); cl0++) {
if (isNumber(content.charAt(cl0)))
number += content.charAt(cl0);
else {
cl = cl0 - 1;
Thread.sleep(Long.parseLong(number));
break;
}
}
} else if (c == '=') {
Object obj0 = stack.remove(selectedIndex);
Object obj1 = stack.remove(selectedIndex);
stack.add(new Boolean(obj0.equals(obj1)));
} else if (c == '~') {
for (Object o : stack)
System.out.print(o);
System.out.println();
} else if (c == '²') {
if (stack.get(selectedIndex) instanceof Double) {
Double dbl = (Double) stack.remove(selectedIndex);
stack.add(selectedIndex, dbl * dbl);
} else if (stack.get(selectedIndex) instanceof Object[]) {
Object[] obj = (Object[]) stack.remove(selectedIndex);
Object[] newArray = new Object[obj.length];
for (int i = 0; i < obj.length; i++) {
newArray[i] = Math.pow((Double) obj[i], 2);
}
stack.add((Object[]) newArray);
}
} else if (c == '|') {
String string = (String) stack.remove(selectedIndex);
cl++;
char splitChar = content.charAt(cl);
stack.add((Object[]) string.split(splitChar + ""));
} else if (c == '♀') {
for (Object obj : (Object[]) stack.remove(selectedIndex)) {
stack.add(selectedIndex, obj);
}
} else if (c == '>') {
whileStatements.add(new Integer(cl));
} else if (c == '<') {
cl = whileStatements.get(whileStatements.size() - 1);
} else if (c == '!') {
whileStatements.remove(whileStatements.size() - 1);
} else if (c == '?') {
if (stack.get(selectedIndex) instanceof Boolean) {
Boolean bool = (Boolean) stack.remove(selectedIndex);
if (bool == false) {
ifStatements++;
for (int cl0 = cl; cl0 < content.length(); cl0++) {
if (content.charAt(cl0) == '¿') {
ifStatements--;
cl = cl0;
}
}
}
}
} else if (c == 't') {
break;
} else if (c == '(') {
stack.remove(selectedIndex);
} else if (c == ':') {
cl++;
char charToVar = content.charAt(cl);
vars.put(charToVar + "", stack.remove(selectedIndex));
} else if (c >= 'A' && c <= 'Z') {
stack.add(vars.get(c + ""));
} else if (c == 'r') {
stack.add(selectedIndex,
(double) new Random().nextInt(((Double) stack.remove(selectedIndex)).intValue() + 1));
}
}
scanner.close();
}
public static String rot13(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'm')
c += 13;
else if (c >= 'A' && c <= 'M')
c += 13;
else if (c >= 'n' && c <= 'z')
c -= 13;
else if (c >= 'N' && c <= 'Z')
c -= 13;
sb.append(c);
}
return sb.toString();
}
public static boolean isNumber(char c) {
return c >= '0' && c <= '9';
}
}
```
] |
[Question]
[
Write a program that takes a single line string that you can assume will only contain the characters `/\_‾`. (That's forward and backward slash, underline and [overline](https://en.wikipedia.org/wiki/Overline). You can use `~` in place of overline if you need since overline is not convenient ASCII.)
For example, one possible input is:
```
__/‾‾\/\_/‾
```
Your program needs to output a truthy or falsy value depending on whether the left edge of the string is "connected", so to speak, to the right edge of the string via the lines of the characters. So, if the kerning was a bit less, there would be a solid black (albeit kinky) line all the way from the left edge to the right, like an unbroken piece of string or twine.
The output for the above example would be true because the edges are connected:
[![example path](https://i.stack.imgur.com/17nyk.png)](https://i.stack.imgur.com/17nyk.png)
To be clear on the connections:
* `/` connects on its bottom left and top right
* `\` connects on its top left and bottom right
* `_` connects on its bottom left and bottom right
* `‾` (or `~`) connects on its top left and top right
Also:
* It doesn't matter whether the edges of the string started on the top or the bottom, it only matters that they connect horizontally through the whole length of the string.
* You can assume the input string is non-empty, and of course just one line.
Here are some more examples followed by 1 (truthy) if they are connected or 0 (falsy) if not:
```
__/‾‾\/\_/‾
1
_
1
\
1
/
1
‾
1
___
1
\/
1
/\/
1
/\/\
1
‾‾‾
1
\\
0
‾‾
1
_‾
0
‾_
0
\_____/
1
\/\\/\\___
0
\/\__/‾‾\
1
______/\_____
1
‾‾‾‾‾‾\\_____
0
‾‾‾‾‾‾\______
1
_____/‾‾‾‾‾
1
\___/‾‾‾\___/‾‾‾
1
\_/_\_
0
\_/\_
1
/\/\/\/\/\/\/\/\/\/\/\/
1
____________________
1
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
1
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾/
0
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\
1
/\‾/\‾___/\_\/__\/\‾‾
0
```
The shortest code is the winner.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
*-1 byte thanks to @EriktheOutgolfer*
Expect `~` instead of `‾`. Returns \$0\$ or \$1\$.
```
O*Ɲ:⁽8ƇḂẠ
```
[Try it online!](https://tio.run/##y0rNyan8/99f69hcq0eNey2OtT/c0fRw14L////Hx@vX1cXoxwApAA "Jelly – Try It Online"), [Truthy test suite](https://tio.run/##y0rNyan8/99f69hcq0eNey2OtT/c0fRw14L/D3dvOdz@qGnN///x8fp1dTH6MUCKK54rhkufC0jHA1n6XPoQHMNVV1cHxFwx8SCgzwVSDdbFFQ8RgUiAlAEBhBMPkdMHC4F16kPl9CECQE1gw7FAqLGoAGo6BsAlXhcDAA), [Falsy test suite](https://tio.run/##y0rNyan8/99f69hcq0eNey2OtT/c0fRw14L/D3dvOdz@qGnN//8xMVzxdVx18Vwx@jEgFB8fz1UHBmA2kBcTrx8fAxPEBPpc@jF1QARUqh8TH6MfD8QxdXUA)
Using this formula (but otherwise similar to the 11-byte version below):
$$n=\left\lfloor\frac{x^y}{15145}\right\rfloor$$
The transition is valid if \$n\$ is odd, or invalid if \$n\$ is even.
### Commented
```
O*Ɲ:⁽8ƇḂẠ - main link, taking a string e.g. "\_/"
O - get ASCII codes --> [92, 95, 47]
*Ɲ - exponentiation on all pairs --> [92**95, 95**47]
:⁽8Ƈ - integer division by 15145 --> [23964828…8421, 59257069…0485]
Ḃ - least significant bit (i.e. parity) --> [1, 1]
Ạ - all values equal to 1? --> 1
```
---
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14 12~~ 11 bytes
Supports (and expects) the `‾` character in the input string. Returns \$0\$ or \$1\$.
```
O*Ɲ%276%7ỊẠ
```
[Try it online!](https://tio.run/##y0rNyan8/99f69hcVSNzM1Xzh7u7Hu5a8P////h4/UcN@4AoRj8GzAQA "Jelly – Try It Online"), [Truthy test suite](https://tio.run/##y0rNyan8/99f69hcVSNzM1Xzh7u7Hu5a8P/h7i2H2x81rfn/Pz5e/1HDPiCK0Y8BM7niuWK49LnArHggW59LH4JjuCAKQTJQKiYeBPS5QHrh5nDFQ0QhkghNcASRiIeo00eTBJupj6JWH1kSaCzYMVgg1GJUgMV@MhB1TAH5BwA), [Falsy test suite](https://tio.run/##y0rNyan8/99f69hcVSNzM1Xzh7u7Hu5a8P/h7i2H2x81rfn/PyaGK/5Rwz4uII7nitGPAaH4@HgQHw2BxYEyMfH68THYFJCH9Ln0Y0AUiAAarx8TH6MfD8QxEGkA)
### How?
Given two consecutive characters of ASCII codes \$x\$ and \$y\$, we want a function that checks whether they form a valid transition.
We need a non-commutative operation, because the result may change when the characters are reversed. For instance, `_/` is valid but `/_` is not.
Using exponentiation, a possible formula1 is:
$$n=(x^y \bmod 276)\bmod 7$$
The transition is valid if \$n\le1\$, or invalid if \$n>1\$.
```
chars | x | y | (x**y)%276 | %7 | valid
-------+------+------+------------+----+-------
__ | 95 | 95 | 71 | 1 | yes
_/ | 95 | 47 | 119 | 0 | yes
_‾ | 95 | 8254 | 265 | 6 | no
_\ | 95 | 92 | 265 | 6 | no
/_ | 47 | 95 | 47 | 5 | no
// | 47 | 47 | 47 | 5 | no
/‾ | 47 | 8254 | 1 | 1 | yes
/\ | 47 | 92 | 1 | 1 | yes
‾_ | 8254 | 95 | 136 | 3 | no
‾/ | 8254 | 47 | 88 | 4 | no
‾‾ | 8254 | 8254 | 196 | 0 | yes
‾\ | 8254 | 92 | 196 | 0 | yes
\_ | 92 | 95 | 92 | 1 | yes
\/ | 92 | 47 | 92 | 1 | yes
\‾ | 92 | 8254 | 184 | 2 | no
\\ | 92 | 92 | 184 | 2 | no
```
*1. Found with a brute-force search in Node.js (using BigInts)*
### Commented
```
O*Ɲ%276%7ỊẠ - main link, taking a string e.g. "\_/"
O - get ASCII codes --> [92, 95, 47]
*Ɲ - exponentiation on all pairs --> [92**95, 95**47]
%276 - modulo 276 --> [92, 119]
%7 - modulo 7 --> [1, 0]
Ị - ≤1? --> [1, 1]
Ạ - all values equal to 1? --> 1
```
[Answer]
# [Ruby -n](https://www.ruby-lang.org/), 30 bytes
```
p !/[_\\][\\‾]|[\/‾][_\/]/
```
[Try it online!](https://tio.run/##KypNqvz/v0BBUT86PiYmNjom5lHDvtia6Bh9EA0U04/V//8/Ph7EBaIY/RgwkysmhgvIBqH4@HgQE6GEC0IjI7Cq@Ph/@QUlmfl5xf918wA "Ruby – Try It Online")
Reduces all of the string-breaking sequences to two cases using Regex character classes.
[Answer]
# JavaScript (ES6), 45 bytes
The naive way.
```
s=>!/\/\/|\\\\|_~|~_|~\/|_\\|\/_|\\~/.test(s)
```
[Try it online!](https://tio.run/##rVNRasMwDP3PKbz8NIY1OkF6kbmIkDndRmhK7A0GwfRkO8wukklZ6tje6GDUEY5lP0nPkvxSv9WmGZ5PdnvsH/XUVpOpdneg6BsVjRHd6HB0pCJpCpC2HZRWG1sYOfFfVMKIaiea/mj6TpddfyjawpSDPnV1owv4PH/A4V5s3EZKmWUhLn@ww6t9et/nMpt95oiMJ1FEQs3KeuZXSvkl@FUExRC8YiBVAk/fcUMviUp8eEDomfc84zA8AxeDnxG8LAiMLSFBxQwgtoZfYRw7ueg1SZjH4wr/f8htvV3ynrRVW3cm6Cru5fWKCQmM67lMf9UtrS3nHMOk3@p6Ub@yPs9ceHqL/B4BceZ8Se/0BQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://docs.python.org/3/), 46 bytes
```
f=lambda s:s==''or s[:2]in"__/~~\/\_"*f(s[1:])
```
[Try it online!](https://tio.run/##dU/RCoMwDHzPV4gv2r0EtzfBLzESHJtYcCrqGAPJr7vUytjYTBPa3iXHpX9OddeelqXKmvJ2vpTBmI5ZFkXdEIx5eixsGzKjCCFxeKjiMU/SwiyP2jbXIEn7wbZTXMW27e9TbIxZ3t0owECAoDfrCwF9EYiIFhC7QHDd6xSwRzzh2jT8hz2HK7RO4sahB3RoFf9zNtnv2NR/Yg9Xd6QGlXe7kMsPj5tjtcG0Ky1ufdF0rmfimZBZhURe "Python 3 – Try It Online")
Confirms that each adjacent pair of characters connects by checking that they appear consecutively in `__/~~\/\_`. This string can be viewed as a [De\_Bruijn\_sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) on the \$2^3=8\$ triples of high/low positions.
I tried other less humdrum methods to check character pairs, but they were all longer that hardcoding all legal pairs like this .
[Answer]
# [R](https://www.r-project.org/), 89 87 81 78 bytes
-2 bytes thanks to @Giuseppe
-6 bytes thanks to @Nick Kennedy
-3 bytes replacing `1:length(y)` with `seq(a=y)`, where `a` is short for `along.with`
```
y=utf8ToInt(scan(,''));all(!diff(cumprod(c(1,y>93)*2-1)[seq(a=y)]*(y%%2*2-1)))
```
uses `\ / _ ~`. This is probably not as short as a regex based solution, but I fancied doing something a bit different to everyone else.
```
utf8ToInt('\\/_~')
# [1] 92 47 95 126
```
The characters less than 93 switch the state from up to down (or vice versa), and as such behave as `-1` while the others do nothing and behave as `1`, cumprod tracks the state with respect to the start. The even numbers are in an upstate (represented with `-1`), the odd numbers are in a down state (`1`). If the string is unbroken the tracked state multiplied with the up/down position, should not change, it will always be the starting condition (`-1`,or `1`)
[Try it online](https://tio.run/##PcpRC4IwFAXg9/5Fgniv6ER7KWq9995bC5HZBcG20gkOcX99UWJw4Bw@TueJ06CkabSCEadeVuqU/oUxhtM4e8sHQ/urvigD3wskUYR4rNoWtnVDBHJ4vjpdg4Q8sefDDuMizfHWP95QcYv3GGwYFj9E9POGIBAiwKXXVbpVsiXOOSHKMgvQfwA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 93 bytes
```
w,o,r;k(char*_){for(r=0;w=*_,o=*++_;)r|=w-126&&w>47?w-95&&w-92?0:o>47&&o-95:o-92&&o<126;_=r;}
```
[Try it online!](https://tio.run/##hVLRToMwFH3nK7BmpN1KyojTbNgRHzQx8cnMtybNxjZdFsG0Gh629dexBZSWJXpDL4dzbi/3FLLwNcuqqsQFFskeZm9LMeTosC0EFDRKSjrkuKDD0YgnSBxpGY7j6yAo51c3aRlOJxqG0ziNZoVmgqDQ1EynWMNbXZlwKpJTdbnebHf5xl9AiVfo8CF2@ecWgkEYT6Qfzv3B2k@pyXAgEcsBlngPJcIXq/pO6SoFD3ePTy/P92AG5FeWbaQEKDl53vtyl0N08BYQcE6UYowwpgHA3hh5Nd1BxjpMOmgXc6fcKiJnT3Y3pZS9r5aiH8lqryyed1iPbII47zZt6tQMFVlCa9WZ2@xv@zhzKVPZCZEr8N6Gpk8t2sO05C9wNMJ1csyQhnAO66@rb8SNvp2z@LdAkb7z83B@DsaUWcbtUXvRi3Bez6raT3iqvgE "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ ~~14~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÇümŽb‘÷ÈP
```
Port of [*@Arnauld*'s Jelly answer](https://codegolf.stackexchange.com/a/181718/52210), so make sure to upvote him as well!
Input with `‾`.
[Try it online](https://tio.run/##yy9OTMpM/f//cPvhPblH9yY9aphxePvhjoD//@Pj9R817AOiGP0YMBMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8Pth/fkHt2b9KhhxuHthzsC/uv8j4/Xf9SwD4hi9GPATK54rhgufS4wKx7I1ufSh@AYLohCkEwMjMMVDyKAGKgyHgT0gTpiQAiiOQZhPlc8RAFEHcIwOIrBKQOShOiGGKKPKQ@2Xh9dhz6yvH58DMiVQAeAvYMFQp2ICrC7h1REHVOASJ9qJgGjOQZkIIgAhVVNTHxNjH58fAxYBIgA).
---
### Original 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:
```
„_~SD2×s:Çü-т+•6_üê{↕ƵΔвåO_
```
Input with `~` instead of `‾`.
It sounded shorter in my head.. ~~Will try to golf it down from here.~~
[Try it online](https://tio.run/##yy9OTMpM/f//UcO8@LpgF6PD04utDrcf3qN7sUn7UcMis/jDew6vqj686FHDAiD32NZzUy5sOrw0IP7///h4/bq6GP0YIAUA) or [verify all test cases](https://tio.run/##dVCxCsIwEN3vK4qryoGDg0sXdwfXg0PBwcmhIBTLURx0F8FNpODiKLh1CziK/kJ@JF6aLkX7cuGSey/3jqyS2Xy5cNk6jTuR3R2iTpw6m59ZpuOBOSUjszdl/7Pt2rwYsinNbWMKm1/0@ny8ju@7uU7Y9RwzihCSJmAgQNDMekLAsAlEBMgnYAFRjj1QNeQjyCl0Ag5k0PinCmregiQosSpVLbHmMBSQyVtpp2qKP6v2aqI2@UFbXbCV0d8g0fAzZcQZIbP6inwB).
**Explanation:**"
```
„_~S # Push the characters ["_","~"]
D2× # Duplicate it, and increase each to size 2: ["__","~~"]
s: # Swap and replace all "__" with "_" and all "~~" with "~"
# in the (implicit) input-string
Ç # Convert the remaining characters to unicode values
ü- # Calculate the difference between each pair
т+ # Add 100 to each
•6_üê{↕ # Push compressed integer 1781179816800959
ƵΔ # Push compressed integer 180
в # Convert the larger integer to Base-180 as list:
# [52,66,69,100,103,131,179]
å # Check for each if it's in the difference-list
# (1 if present; 0 if not)
O # Sum the truthy values
_ # Check if this sum is exactly 0 (1 if 0; 0 otherwise)
# (and output this result implicitly)
```
[See this 05AB1E tip of mine (sections *How to comrpess large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•6_üê{↕` is `1781179816800959`, `ƵΔ` is `180` and `•6_üê{↕ƵΔв` is `[52,66,69,100,103,131,179]`.
**Additional explanation:**
There are 16 (\$2^4\$) possible pairs of characters we have to verify. If we convert each character to its unicode value, and calculate the differences, we would get [these differences](https://tio.run/##ASoA1f9vc2FiaWX//yIvXF9@IlNEw6NKROKCrMOHw4bigJrDuM6jzrh9dnks//8). Because compressed integer lists in 05AB1E has to have positive integers only, I [add 100 to each](https://tio.run/##ATMAzP9vc2FiaWX//yIvXF9@IlNEw6NKROKCrMOHw4bigJrDuM6jzrh9dnnOtU5p0YIrfX0s//8). The invalid pairs and their corresponding values are then: `["/_", 52]`; `["\~", 66]`, `["_~", 69]`, `["//", 100]`, `["\\", 100]`, `["_\", 103]`, `["~_", 131]`, `["~/", 179]`, which is why I have the compressed integer list in my code containing these values.
Since `__` and `~~` will just like `//` and `\\` result in `0` (or `100` after I add 100), I first remove any adjacent duplicates of `~` and `_` in the input-string, before calculating and verifying the pair-differences.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~79~~ ~~70~~ 63 bytes
*Saved 16 bytes thanks to Arnauld and Jo King, thanks!*
```
p=lambda s:len(s)<2or((ord(s[-2])%13>5)^ord(s[-1])%2)&p(s[:-1])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8A2JzE3KSVRodgqJzVPo1jTxii/SEMjvyhFozha1yhWU9XQ2M5UMw4qYAgUMNJUKwCyrUCc/wVFmXklGgUaSvHx@o8a9gFRTIx@TAyYo6SpyYUkDwT6UDXICFWVPpD7HwA "Python 3 – Try It Online")
# [Python 3](https://docs.python.org/3/), ~~67~~ 60 bytes with ~ instead of ‾
```
p=lambda s:len(s)<2or(~(ord(s[-2])//7^ord(s[-1]))&p(s[:-1]))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8A2JzE3KSVRodgqJzVPo1jTxii/SKNOI78oRaM4WtcoVlNf3zwOyjOM1dRUKwCyrMDM/wVFmXklGgUaSvHx@nV1MTH6MTHx@o8a9ilpanIhyQGBPlC@Dij8HwA "Python 3 – Try It Online")
[Answer]
# [Chip](https://github.com/Phlarx/chip) `-z`, 17 bytes
```
FZ!C~aS
A}^]--^~t
```
[Try it online!](https://tio.run/##S87ILPj/3y1K0bkuMZjLsTYuVlc3rq7k///4eP26uhj9GCD1X7fqv24ZAA "Chip – Try It Online") (TIO includes `-v` to make it easier to understand the output.)
Expects the `_/~\` set. Returns either `\x00` (falsy) or `\x01` (truthy).
The strategy for my answer uses the following information:
```
Symbol Binary
_ 0101 1111
/ 0010 1111
~ 0111 1110
\ 0101 1100
^ ^ ^
HGFE DCBA
```
`A`: This bit position happens to be `1` when the left side of the symbol is low, and `0` when it is high
`F`: This bit position happens to be `0` when the right side of the symbol is low, and `1` when it is high
`C`: This bit position happens to always be `1`
Using this information, I simply need to check that the `F` of each character matches the `not A` of the next. An `xor` gate is a convenient way to accomplish this.
The following code does this, but gives output for each pairing (plus an extra `1` at the start) (7 bytes):
```
FZ!
A}a
```
We want to halt at the first failure, and also print whether we have halted within the string, or at the null terminator (we also add `-z` to give us a null terminator). We can use `not C` to signify where we stopped, and that gives us this program (13 bytes):
```
FZ!C~a
A}^]~t
```
But we still have "leading zeroes" (e.g. `\_/\` gives `00 00 00 00 01`), so this is transformed to the answer given at the top.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O*Ɲ%⁽wḃ%5ỊẠ
```
A monadic Link accepting a list of characters, uses the `~` in place of `‾` option.
**[Try it online!](https://tio.run/##y0rNyan8/99f69hc1UeNe8sf7mhWNX24u@vhrgX///@Pj9evq4vRjwFSAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##fU87CgJBDO1zj21sUnkOLxB41TayvQhLQC0WvIPgASwtxMVK8B6zFxmTySCInzcTMvNe8kiWbdetc17MHodm2txW6bJr5mncp@sxp/F8H6btKWeAVYXFEoGEmCzDXkwcIaSqFiRwMHl16SIEE4KXGeKD0LhQpZOrxkFYUzH/cqrtO6r7B37xNp3YgKb7LuK3rAWGvEaVv9bq66tdn7oX9MKAGak@AQ "Jelly – Try It Online") (...where I've reordered to place the 8 falsey ones at the end)
This formula was found by fiddling around by hand :p (as were those below)
For this one I too all 16 pairs of character's ordinals treated as an exponentiation and looked for a large modulo that will fit into three bytes followed by a one-byte modulo (1,2,3,4,5,6,7,8,9,10,16,256) that partitioned the 16 such that all of the acceptable results were either 1 or 0 ("insignificant") since I know `Ị` is shorter than `<5`, in my previous solution, which was looking for all acceptable results being less than all unacceptable ones.
```
O*Ɲ%⁽wḃ%5ỊẠ - Link: list of characters
O - ordinals
Ɲ - for each pair of neighbours:
* - exponentiate
⁽wḃ - 30982
% - modulo (vectorises)
5 - five
% - modulo (vectorises)
Ị - insignificant? (abs(x) <=1) (vectorises)
Ạ - all truthy?
```
The possible neighbouring characters and their internal evaluations:
```
(Ɲ) (O) (*%⁽wḃ) (%5) (Ị)
pair a,b=ordinals c=exp(a,b)%30982 d=c%5 abs(d)<=1
__ 95, 95 28471 1 1
_/ 95, 47 29591 1 1
/~ 47, 126 19335 0 1
/\ 47, 92 9755 0 1
~~ 126, 126 28000 0 1
~\ 126, 92 26740 0 1
\_ 92, 95 9220 0 1
\/ 92, 47 13280 0 1
~_ 126, 95 3024 4 0
~/ 126, 47 12698 3 0
\~ 92, 126 27084 4 0
\\ 92, 92 17088 3 0
_~ 95, 126 28169 4 0
_\ 95, 92 4993 3 0
/_ 47, 95 22767 2 0
// 47, 47 7857 2 0
```
---
Previous @ 12:
```
O*Ɲ%⁽?K%⁴<8Ạ
```
[Try it online!](https://tio.run/##y0rNyan8/99f69hc1UeNe@29geQWG4uHuxb8//8/Pl6/ri5GPwZIAQA "Jelly – Try It Online")
---
Previous @ 13:
```
O%7ḅ6$Ɲ%⁵%8ỊẠ
```
[Try it online!](https://tio.run/##y0rNyan8/99f1fzhjlYzlWNzVR81blW1eLi76@GuBf///4@P16@ri9GPAVIA "Jelly – Try It Online")
[Answer]
# Python 3, 126 bytes
```
lambda s,d={'‾':'\‾','_':'/_','/':'\‾','\\':'/_'}:len(s)<2or all([s[i+1] in d[s[i]]for i in range(len(s)-1)if s[i]in d])
```
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
This variant uses `~` instead of overlines. It takes all eight valid pairs and checks whether the string only contains those:
```
f(a:b:x)=[a,b]`elem`words"__ _/ /~ ~~ ~\\ \\_ \\/ /\\"&&f(b:x)
f _=1>0
```
[Try it online!](https://tio.run/##dU5BboNADLz7FSNURaC0dXtFIh@pK2fTgoIKpAqpwslfp16WS9Rm1pZ3Z8b2HsP4VXfdPDd5KA/lVFRv4fHwvq@7ut9fT@fPMVOFMthgHiIQUU9nRLLNpsljFzXQ6nX3MvehHVChHS71OXxc8ICfoWuHesQz@vCNXCY87TBhu0VWIot1PJ6uyBtMReGuxT2rspmweCElISav6jcmTilkZiSxkBqZaxrB7pEYyS5pEmkSkye2OuT2lSzJyQu1jORV40SwSlzlk5Zf/HPWXbdYl/zBPd74riK/ "Haskell – Try It Online")
Ungolfed:
```
validate :: String -> Bool
validate xs = all valid $ zip xs (tail xs)
where
valid (a,b) = [a,b] `elem` starts
starts = words "__ _/ /~ ~~ ~\\ \\_ \\/ /\\"
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes
```
{!/< \\\ \~ ~/ // _~ ~_ _\ /_>/}
```
[Try it online!](https://tio.run/##rVDLCsJAEDu7XxEvbgvV0YsXbb8kMFSxIPii9VLU4pf5Mf5I3W1BsPYkzoYhO4HMkNMm383rfYlRhhj1ZShLkAQrVAIRqCMKJUQTudXZMUew2x42RYhxAqYRuIqtjbh2HRczKNISWZBOznl6KAL7vD9snNjKhmEEiziBjYDVwtxqJ3VAqi8zNaZH1FacGdMQ6ehe4Mf889fqomz8HWPjJex97zWd8vPv237A34wcpD@x38A2FW/rm8/wSr1SVNlM/PHTFw "Perl 6 – Try It Online")
A regex solution that simply checks that the string contains no invalid sequences.
### Explanation:
```
{ } # Anonymous code block
/< >/ # Find the longest sequence from
\\\ # \\
\~ # \‾
~/ # ‾/
// # //
_~ # _‾
~_ # ‾_
_\ # _\
/_ # /_
! # And logically negate the match
```
[Answer]
# perl 5, ~~26~~ 25 bytes
using `;` as delimiter the end delimiter can be removed
```
$_=!m;[/~][_/]|[\\_][~\\]
```
[TIO](https://tio.run/##K0gtyjH9/18l3lYx1zpavy42Ol4/tiY6JiY@NrouJib2//86MAAKgAAXlBcP4YFJfbAQVwyUCaOBAvrxMfEgCkjqx2CFEBPQABfUFgyAS7xOH6dMDNDmRw37wATIYTUx8TUx@vHxMWARIPqXX1CSmZ9X/F@3IAcA)
[26 bytes](https://tio.run/##K0gtyjH9/18l3lYxVydavy42Ol4/tiY6JiY@FkjUxer8/18HBkAREOCC8uIhPDCpDxbiioEyYTRQQD8@Jh5EAUn9GKwQYgIa4ILaggFwidfp45SJAdr8qGEfmAA5rCYmviZGPz4@BiwCRP/yC0oy8/OK/@sW5AAA)
[Answer]
# [R](https://www.r-project.org/), 43 chars, 47 bytes
It's the same regex the other answers use, but adapted for R.
```
!grepl('[/‾][/_]|[\\\\_][\\\\‾]',scan(,''))
```
[Try it online!](https://tio.run/##K/r/XzG9KLUgR0M9Wv9Rw77YaP342JroGCCIjwVTIEF1neLkxDwNHXV1Tc3/MfH6MSCl/wE "R – Try It Online")
And obligatory [xkcd](https://www.xkcd.com/1638/).
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 100 98 bytes
```
: x = swap '~ = + ;
: f 1 tuck ?do over i + >r i 1- c@ r> c@ dup 92 x swap dup 47 x <> + loop 0> ;
```
[Try it online!](https://tio.run/##bU9dT4QwEHz3V0x48cFw9dDEeGj1hzRpLhyo0aRN4fx46V/H3UI/SK4QZjuzM7sMxk3v9dvAMM8H/OIZ48/R4tpTdYMWBwzYYzp3n3g5GZjv3uGDFMmwr9G9wkn@ns4Wjw0lBD/f7h/o9iSp@csYi1uJdlYUaNGwPP3ZHs3dElljtMeuH7GrgFqiCmN3Dp1De7X1EJXFoI8VtBbeK6EIKtjArKhWFCsmXaeOKImyij7vo0NlKmbEwqcszUekZMVvOUotm@YluH1x5YF01CVOl9xiDUIxXKx9oqSFVnlBkWr@ywvPZrftIWn@Bw "Forth (gforth) – Try It Online")
### Explanation
Go through the string and determine whether each character starts on the same position (top or bottom) as the one before ends. Subtract 1 from a counter if they don't match. At the end, if the counter has changed, then the string is not a string.
End position is high if char is `/` (47) or `~` (126). Otherwise it's low
Start Position is high if char is `\` (92) or `~` (126). Otherwise it's low
### Code Explanation
```
\ x is basically just extracting some common logic out into a function to save a few bytes
\ it checks if the first number is equal to the second number
\ or the third number is equal to 126
: x \ start a new word definition
= swap \ check if the first two numbers are equal then swap with the third
'~ = \ checks if the third number is equal to 126
+ \ adds results together (cheaper version of or)
; \ end the word definition
: f \ start a new word definition
1 tuck \ set up parameters for a loop (and create a bool/counter)
?do \ start counted loop from 1 to string-length -1,
\ ?do will skip if loop start and end are the same
over i + \ copy the string address and add the loop index to get the char address
>r i \ place char address on return stack and place a copy back on the stack
1- c@ \ subtract 1 to get previous char address and grab ascii from memory
r> c@ \ move char address back from return stack, then grab from memory
dup 92 x \ get the "output" position of the prev character
swap dup 47 x \ get the input position of the current character
<> + \ check if they aren't equal and add the result to the counter
\ the counter won't change if they're equal
loop \ end the loop
0> \ check if counter is less than 1 (any of the "links" was not valid)
; \ end word definition
```
[Answer]
# Haskell, 42 bytes
```
g=tail>>=zip
h=all(`elem`g"__/~~\\/\\_").g
```
this solution uses `~`, and the function to call is h (i.e., `h string` gives the answer)
The solution uses a function g that given a list, returns all tuples of adjacent values on the list.
Then we use g to generate the list of allowed neighbors (in `g"__/~~\\/\\_"`) and also the list of all neighboring pairs in the input list. Then we check that each neighboring pair is an allowed pair.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~41~~ 36 bytes
```
f(char*_){_=!_[1]||*_/32+*++_&f(_);}
```
[Try it online!](https://tio.run/##fVHLboMwELz7KyhSIhsTbZsoJ0p/JEaryJUbH0Iimhthf536RUjVipUZL7OzD9t686X1OBquT8euQNFj/YKHt@Z@LxB2W1lIiWvDUVTDeD7aloueBWl204em7lmOCERKgVLOyUtHeFDKI3iIJCY6UPC0RyURxfj0G5ICUspEb5CqeGGAubD3wyipn1enrNSBfPQfCh9MzAr0oylMGphZQAeTn9x4mKU1D/bb5ln@2EKIYCmYHkAp8l@6CzcDYpjFVR4qxsyl47a9ZbZ@rez7zoGUgl07xxmer7b772zzka0@VZuX7sFtUxoediEqNow/ "C (gcc) – Try It Online")
-5 eliminated `&1` starting off from an idea from [Peter Cordes](https://codegolf.stackexchange.com/questions/181708/would-this-string-work-as-string/181842?noredirect=1#comment437944_181842); changed operators (precedence) to remove parentheses
---
Uses `~`. Checks the first and sixth bits of the first two characters' binary representations:
```
_ 1011111
\ 1011100
/ 101111
~ 1111110
^ ^
```
and traverses the string recursively.
`(*_ / 32) & 1` is true only for chars that end high, while `*_ & 1` is true only for chars that start low. `(x&1) ^ (y&1) == (x+y)&1`. XOR is add-without-carry, and carry doesn't disturb the lowest bit. The `1` comes from the `f(_)` return value, if the rest of the string was stringy.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~80~~ 78 bytes
I don't realy do many python code golfs but I thought I could give it a try
* -2 bytes: realised not(any()) is the same as all(not()) and could move the not into the r-string
```
def f(x):*l,=map(r'_/\~'.find,x);return 1-any((i^j//2)%2for i,j in zip(l,l[1:]))
```
[Try it online!](https://tio.run/##dVDBbsMgDD3XX8FlAiY0a90tU/5it3mzKjVRqWiKUKJlU8WvdybkUm19GD14ftgW8Xs8nIeX63Xf9ao3s20eg2tPu2iSpsyon3o/7N1sX1M3TmlQuxCM8Z9HxK192PbnpLw7Kj@oHx9NcOH9ufmw9vp18KFTb2nqGthE1YojTqOxsPG9knurdDd7EXRTWVzJD6OJTulGO5klShlmzJmQhICBAEGY5YSAdRPknIEKAWfIkuMCFA@VqHaqlYBrsnrKUwHd3qqlOnGRlpK45rAKyFRaSaVlin/W2usWa5M/uKdnvJuR36AsUWa6EF8ImaVvzr8 "Python 3 – Try It Online")
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 71 bytes
I wanted to try out the new `:=` expression assignment
```
lambda x:all((i^j//2)%2for i,j in zip(l:=[*map(r'\~_/'.find,x)],l[1:]))
```
[Try it online!](https://tio.run/##dVBNa8MwDD1Pv8KXEXuEiXWXEci/2K3qREYb6uKmxqSsG0V/PZPjXMrWZxlZek8fOH6P@9Pw@hbT1Lc0he74ue3MpelCsNZ/HBBX7nHVn5Lx9cH4wfz4aEPTrp@OXbSpImGsnns/bOuL29Rh/dJsnJu@9j7szHs67xp4iKbVyngerdMg@WG0sTZVU9Wmt1HVzChCSOqAgQBBPesLAcslEBGg7IAFRDnOQNVQtiKn0gm4kEWTSxV0GxVJUeKcmlviwmFJIFMepZ3mLf45y6xbLEP@4F5e8C6jv0Gilne6El8JmXWuyC8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# Bash, 30 bytes
```
grep -E '//|\\\\|_~|~_|~/|_\\|/_|\\~'
```
Input is STDIN. Exit code is 1 if valid, 0 if invalid.
[Answer]
# Excel, 150 bytes
```
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"_\",),"_‾",),"‾_",),"‾/",),"/_",),"//",),"\‾",),"\\",)=A1
```
Removes any invalid pairs, then return `true` if this results in the original string.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes
```
C`[_\\][\\~]|[~/][_/]
^0
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zkhOj4mJjY6JqYutia6Tj82Ol4/livO4P//@Hj9uroY/RggBQA "Retina – Try It Online")
Uses `~` rather than `‾`, because that made it easier to type.
* -2 bytes by removing some unnecessary backslashes (thanks to @Neil)
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 58 bytes
```
INPUT '/_' | '_\' | '\\' | '//' | '~/' | '\~' @OUTPUT
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9PTLyA0REFdP15doUZBPT4GTMVAKH19MFUHoWLq1BUc/ENDgOq5XP1c/v@Pj9evq4vRjwFSAA "SNOBOL4 (CSNOBOL4) – Try It Online")
Outputs nothing for truthy and a positive integer (indicating the position of the first break in the string) for falsy.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 18 bytes
```
⌊⭆θ∨¬κ⁼№_/ι№\_§θ⊖κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3My8ztzRXI7gEyE33TSzQKNRR8C/S8Msv0cjW1FFwLSxNzCnWcM4vBSpWitdX0lHIBApD@TEx8UABxxLPvJTUCpBOl9TkotTc1LyS1BSgdiiw/v8/Pl7/UcM@IIrRjwEz/@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
⭆ Map over characters and convert to string
κ Current index
¬ Logical Not (i.e. is zero)
∨ Logical Or
ι Current character
№ Count (i.e. contained in)
_/ Literal _/ (i.e. begins at bottom)
⁼ Equals
θ Input string
§ Indexed by
κ Current index
⊖ Decremented (i.e. previous character)
№ Count (i.e. contained in)
\_ Literal \_ (i.e. ended at bottom)
⌊ Minimum (i.e. if all true)
Implicitly print
```
[Answer]
# Regex, 34 bytes
I couldn't find rules on using Regex as a language. Please let me know if I need to adjust this.
```
^(‾+|(‾*\\)?(_*\/‾*\\)*_*(\/‾*)?)$
```
Try it here: <https://regex101.com/r/s9kyPm/1/tests>
[Answer]
# x86 machine code, 13 bytes.
(Or 11 bytes without handling single-character strings that are trivially stringy.)
Uses the bit-position check from [@attinat's C answer](https://codegolf.stackexchange.com/questions/181708/would-this-string-work-as-string/181842#181842)
Same machine code works in 16, 32, and 64-bit modes. The source is NASM for 64-bit mode.
```
nasm -felf64 -l/dev/stdout listing
17 addr global string_connected
18 code string_connected:
19 bytes ;;; input: char *RSI, transitions to check=RCX
20 ;;; output: AL=non-zero => connected. AL=zero disconnected
21 .loop: ; do {
22 00000000 AC lodsb ; al = *p++
23 00000001 E309 jrcxz .early_exit ; transitions=0 special case. Checking before the loop would require extra code to set AL.
24 00000003 C0E805 shr al, 5
25 00000006 3206 xor al, [rsi] ; compare with next char
26 00000008 2401 and al, 1
27 0000000A E0F4 loopne .loop ; }while(--rcx && al&1);
28 .early_exit:
29 0000000C C3 ret
```
Callable from C as **`unsigned char string_connected(int dummy_rdi, const char *s, int dummy_rdx, size_t transitions);`** with the x86-64 System V calling convention. Not `bool` because the transitions=0 case returns an ASCII code, not 1.
`RCX = len = strlen(s) - 1`. i.e. the number of character-boundaries = transitions to check in the explicit-length string.
For `transitions > 0`, returns 0 (mismatch) or 1 (connected) and leaves ZF set accordingly. For `transitions == 0`, returns the single byte of the string (which is non-zero and thus also truthy). **If not for that special case, we could drop the early-exit JRCXZ.** It's inside the loop only because AL is non-zero there.
---
The bit-position logic is based on the observation that bit 0 of the ASCII code tells you the starting height, and bit 5 tells you the ending height.
```
;;; _ 1011111
;;; \ 1011100
;;; / 101111
;;; ~ 1111110
;;; ^ ^
; end condition (c>>5) & 1 => 0 = low
; start cond: c&1 => 0 = high
; (prev>>5)&1 == curr&1 means we have a discontinuity
; ((prev>>5) ^ curr) & 1 == 0 means we have a discontinuity
```
Test harness (modified from attinat's TIO link, beware the C sequence-point UB in that C reference function). [Try it online!](https://tio.run/##fVLtTsIwFP3NnuI6A9mgWNH4RwQfxGJDugJNWDFrl/hFXx1v123UaGi6fpxz77l32xHTrRCn0@laabGvCwlPxlZKb292yyTGCnXwUFJro7ZaFiB26wpCLBcHraWwssiUtlDUZfnBq0IRQMLYEDp@IxCz7wSM@pTcwl7qfJ4kntxk54wxz78qaetKwxV/ma2@v8d8uXwYzV7HkwkfzUajTcbz@TFklmuls/wrGUQCbXkrXlYLZAYp59Q5xihjeEhJA4WNsbDTsHUk7@mWoL9OXZZzros7Q61Eu7teiftBe12f0ixxMX9rWu378Dltbl/T@Yh/QR5hIbchohZoF0djnHJczrf@El720owb/T3izv6Mi6Sjl@n@pzHm/NN@I@yG86Yr1D@iswabQ9U4Uy1u5@rpHpfJJAdvCY9aiSZZoPfQKGqFVgzw2pS8kqbee/KP0W8JNOEE8IQsmrjNhynMGpHY/KUy5dqKHUqFcotY/xnSFB4h7aJSn/6GFe0mS4d3DwamSxgWOJlldmiYTklb3auRSItAJ@J7OCbH5PQD "C (gcc) – Try It Online"). This function is correct for all 30 cases. (Including the single-character cases where the return value doesn't match: both are truthy with different non-zero values in that case.)
[Answer]
# Excel, 79 bytes
Cell `A1` as input
```
=1---SUMPRODUCT(--ISNUMBER(FIND({"//","/_","\~","\\","~/","~_","_\","_~"},A1)))
```
[Answer]
# [naz](https://github.com/sporeball/naz), 142 bytes
```
2a2x1v4a8m1s2x2v2m2s2x3v3a2x4v3d4m2a2x5v1x1f1r3x2v2e3x3v3e3x4v3e2f0x1x2f1r3x1v4e3x3v3e3x5v2e0m1o0x1x3f1r3x1v4e3x2v2e3x4v3e0m1o0x1x4f0m1a1o0x1f
```
Another answer with a lot of conditionals - so many, in fact, that halfway through writing the explanation for a 206-byte solution, I realized an optimization I could make to achieve this one.
Works for any input string terminated with the control character STX (U+0002). `~` is expected instead of `‾`.
**Explanation** (with `0x` commands removed)
```
2a2x1v # Set variable 1 equal to 2
4a8m1s2x2v # Set variable 2 equal to 47 ("/")
2m2s2x3v # Set variable 3 equal to 92 ("\")
3a2x4v # Set variable 4 equal to 95 ("_")
3d4m2a2x5v # Set variable 5 equal to 126 ("~")
1x1f # Function 1
1r # Read a byte of input
3x2v2e # Jump to function 2 if it equals variable 2
3x3v3e3x4v3e # Jump to function 3 if it equals variable 3 or variable 4
2f # Otherwise, jump to function 2
1x2f # Function 2
1r # Read a byte of input
3x1v4e # Jump to function 4 if it equals variable 1
3x3v3e # Jump to function 3 if it equals variable 3
3x5v2e # Jump back to the start of the function if it equals variable 5
0m1o # Otherwise, output 0
1x3f # Function 3
1r # Read a byte of input
3x1v4e # Jump to function 4 if it equals variable 1
3x2v2e # Jump to function 2 if it equals variable 2
3x4v3e # Jump back to the start of the function if it equals variable 4
0m1o # Otherwise, output 0
1x4f0m1a1o # Function 4
# Output 1
1f # Call function 1
```
[Answer]
# [Dart](https://www.dartlang.org/), 94 bytes
```
f(s)=>!(r'//,\\,~/,_\,~_,_~,/_,\~'.split(',').map((t)=>s.contains(t)).fold(false,(p,e)=>p|e));
```
[Try it online!](https://tio.run/##tVPvaoMwEP/uU6RQSKTBdJ@l@7an8MoRrK5ltkp0Y7C27Mn2MHsRd4ldaVJHobB4RO93v/sbs9Km6/tStPHicSIMV0oCyKOSSDtKPEqFEo48aZtq0wkueZxsdSNERw5tkte7Tm92LalxUtbVSpS6agspGlkQodkXcZz2b9qwXLdFyxYsixjLDEdU359fJKDAfXLZmddiKa2Z46VmOHDJLqzKVxHRA4ivAkBZJADAR4ZqgkIoFNFcSz7PJ6FDQhoGEKBdQSFUhxXXg8@muZxnFKQbAg3x/ujiLPBLG@nC4@FIuCFRwAwa8Bi@FjIVwvVQFOD12Yw8YzPw161R3CH/EJJE3TyN@wTCQdpcdrOnsgfcg0IEh1z/sSffaJlG0ZbutIg/yLDZdax@oXs7T0/aVr@T6q5zUhW7525tLYNe1uZJ52shcudMDqUoRZ7NlzGbkFP2QB@NoTADmDpSQVVQktnMqgcC6TWQ@JRyKzalnJzwQ/8D "Dart – Try It Online")
[Answer]
# APL+WIN, 58 bytes
m←2 2⊤'\_/\~'⍳s←,⎕⋄(1+⍴s)=+/((↑m[0;]),m[1;])=m[0;],¯1↑m[1;]
Prompts for input of string, index origin 0 and uses ~ for upper character
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tfy6QaaRg9KhriXq8fkyd@qPezcVAIR2gskfdLRqG2o96txRr2mrra2g8apuYG21gHaupkxttCKRswTydQ@sNwTJAof9AI/@ncanrqwMA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Write a program or function that, when given a string, filters out as many distinct bytes as it can and returns the cleaned string. However, since your program hates them, none of these bytes can be present in your own code.
Your score will be the number of distinct bytes your program filters out from the input, with the higher the better. This is a max score of 255 (since your program has to be a minimum of one byte). The tiebreaker is the length of your code, with lower being better.
For example, if your program filters out the bytes `0123456789`, it receives a score of 10, but your program itself cannot contain these bytes.
### Rules
* Bytes mean octets.
* You also have the option to take input as a list of integers, with values ranging from 0 to 255. These correspond to the equivalent bytes.
+ Your output should be in the same form as your input
* No reading your source code
* Your code must be non-empty
* Yes, I know there's going to be a Lenguage/Unary answer. But at least golf it please? `;)`
Edit Rule:
* You may choose to ignore a byte, for example if it is indistinguishable from the terminating byte for a string or for EOF. However, this means you can't use it in your submission, nor does it count for your score. If you choose to do so, your max score will be 254, but you don't have to handle that byte being in your input.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-P`, score: 255 (2 bytes)
```
ff
```
---
`f => filter, second f => everything but 'f'`
[Try it online!](https://tio.run/##FcvdCoIwGIfxW/lnH0trWdknEXQJHXQmBIve6UKdbG9CV78UnqMHfh/VcghahxA9SuPROls4VUObisl5UEfux6Yp8PoyKuL@QmgB1bzBg@hTYPIMtgPvCN5is812@8PxdF4jTeTiKvOLSFfL0W08mT5nyTyOIO9/)
---
# [Japt](https://github.com/ETHproductions/japt), score: 255 (2 bytes)
*From @Shaggy*
```
oo
```
`o => remove everything but, second o => 'o'`
[Try it online!](https://tio.run/##FcvbCoJAFEbhV/mzw5hlmnYkgh6iu0CYaGsT6paZndDTTwrrasH30Z14z@x9cH8bh85yZXWD0tRC1oF6sj8xbYXnV1CTDBeKFXT7goxiSEPICYRH3hMcY5vlu/3heDqnSKJ4dY0fF5Vs1pPbdDYvFlG4DP4 "Japt – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), score 249, 1732 bytes
```
c="%c%%c%%%%c%%%%%%%%c"
ex=c==c
ee=c==""
exec"e=%x%%x"%ex%ex
exec"e%%%%%%%%=%x%%x%%%%x"%ee%ex%ee
exec"ee=%x%%x"%e%ee
exec"ee%%%%=%x%%x"%ex%e
exec"e=%x%%x"%ee%e
exec"ec=ex%cex"%e
exec"xe=ec%cec"%e
exec"xx=xe%cxe"%e
exec"xc=xx%cxx"%e
exec"ce=xc%cxc"%e
exec"cc=ce%cce"%e
exec"eee=xx%cec"%e
exec"cee=ce%cec"%e
exec"exe=ce%cex%%cxe"%e%e
exec"xxe=ce%cxx"%e
exec"cxe=ce%cex%%cxx"%e%e
exec"ece=ce%cec%%cxe%%%%cxx"%e%e%e
exec"xce=ce%cex%%cxe%%%%cxx%%%%%%%%cxc"%e%e%e%e
exec"cce=cc%cex%%cce"%e%e
exec"eex=cc%cex%%cec%%%%cce"%e%e%e
exec"xex=cc%cex%%cxe%%%%cce"%e%e%e
exec"cex=cc%cec%%cxe%%%%cce"%e%e%e
exec"exx=cc%cxx%%cce"%e%e
exec"xxx=cc%cex%%cxx%%%%cce"%e%e%e
exec"cxx=cc%cec%%cxx%%%%cce"%e%e%e
exec"ecx=cc%cxe%%cxx%%%%cce"%e%e%e
exec"xcx=cc%cec%%cxe%%%%cxx%%%%%%%%cce"%e%e%e%e
exec"ccx=cc%cex%%cec%%%%cxe%%%%%%%%cxx%%%%%%%%%%%%%%%%cce"%e%e%e%e%e
exec"eec=cc%cxc%%cce"%e%e
exec"xec=cc%cec%%cxc%%%%cce"%e%e%e
exec"cec=cc%cex%%cec%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"exc=cc%cxe%%cxc%%%%cce"%e%e%e
exec"xxc=cc%cex%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"cxc=cc%cec%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e
exec"ecc=cc%cxx%%cxc%%%%cce"%e%e%e
exec"""x=""
"""
exec"x%c=c%%xex%%ecc%%xex%%eex"%e
exec"x%c=c%%cee%%cee%%ece%%cxx"%e
exec"x%c=c%%ccx%%xxx%%xcx%%xxe"%e
exec"x%c=c%%eex%%exx%%xec%%xxe"%e
exec"x%c=c%%xex%%cxc%%cce%%ecx"%e
exec"x%c=c%%xxe%%eex%%cxe%%cxe"%e
exec"x%c=c%%cex%%ccx%%xec%%ce"%e
exec"x%c=c%%eex%%ce%%xxx%%xcx"%e
exec"x%c=c%%ce%%eex%%ecc%%ece"%e
exec"x%c=c%%cec%%eec%%ecx%%xxx"%e
exec"x%c=c%%exc%%xxe%%cxe%%cxe"%e
cx="""eec
xec
xxx
xcx
exc
cee
cee
ece
cxx
ccx
xxx
xcx
xxe
xex
ce
cex
ccx
xec
ce
xex
ce
xxx
xcx
ce
xxx
xcx
eec
xxc
exc
xxe
cxe
xxx
cex
ce
xex
ce
xxx
xcx
cee
cee
cee
eee
xex
ecc
xex
eex
cee
xce
exe
cee
cee
cee
cxe"""
exec"exec%cx"%ce
```
[Try it online!](https://tio.run/##fVXZbhQxEHyfz7Dkl0QIiXd/DBQFOSAHBFLh55duH2PP2htpZ9bqrq6uLq@9T28vN48Pn04npBAR/VNfeRE2KiElbKR/Bw8QgSkqRoVI2afGWlXJ@coBzBhWTC8cYr2oEJ734B5CsjzowRIRE2ER9IiSGCH2CJKsSr0KTLIq9SogwarQq2havWyghpvAQ8heJWRSS8@uo2TGtgewBjDRmDNN9r4C@hSHThWy71SeZcTD8ah4jMroe9oyLDteAd3WAVKbnUHQILgIoQpEkwRp5NeSXyP/EkJUfl6ECLPKwbUd3V2bvRG7y3vpiqIbjKIL09w1U@Rg7StmBbismMJgwno3hWk336OEMJv2ngSg7/NaQgjyyyO0C8QOVjKgXJKVt9V4sgsCfj3kl52ReDhODQG/Jry3yornCGbujPCRFgixSQdyq6mL3AfuDmLmqCetdcFahtM3sTND0@qOEIsWmSYny9BTDzWto0y4@f6z3OSPtFl3q8NmzubHmhlKm@nf80ZjeIs5pKboJS3agMMy9zBe5/Z6qORQK84L2RWwpG328s2St3vPJzxgfaz9r8jddi/B0yl8/oKv/Pb95vbu/sfPh8en51@/X/78fdXbv3T94epjDP8B "Python 2 – Try It Online")
Removes everything but `exc%="` and newlines. The code generation is [xsot's](https://codegolf.stackexchange.com/a/110722/3852). I doubt it's optimized, so there are lots of bytes to save here!
[Answer]
## Haskell, score ~~249~~ 250, ~~1088~~ 335 bytes
```
(!:)((=:):(!=))=(((!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(:):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(:):(!):(!):(!):(!):(!):(!):(:):(:):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(!):(:):(!):(!):(:):(=!))!!(=:))(=:)((!:)(!=))
(!:)(=:)=(=:)
(=:)!(!=)=(!=)
(=!)=(!):(=!)
```
Defines a function `!:` that takes a list of integers and filters out all except `10,33,40,41,58,61`, the ASCII-codes of `\n ! ( ) : =`.
[Try it online!](https://tio.run/##7VHBCsIwDL33KxLYITk4RNilLF6GXyEeBk4drt1Y6/fPpjdPDtnRQh6Pl5cGXh5teHbDsCyElonEsiUUZiEiVL6i7ErfL2W/9OzGO5QLMiNqFqxAORoNxWSWJFEwCqgNUTA6J/mTRBbX9h4ErqOB9ALUO3DtBLd5dCf/clAXR7h3sRl97HwM2TXNvY9QJLcI6C741LN03pfloaou/4tte7E3 "Haskell – Try It Online")
How it works: First let's rename the functions and parameters to sane names:
```
f (x:xs) = (listOfFunctions !! x) x (f xs) -- (!:)
f x = x
listOfFunctions = d:d:d:d:d:d:d:d:d:k:d:d ... : infiniteDs -- inlined
infiniteDs = d : infiniteDs -- (=!)
k = (:) -- inlined
d x xs = xs -- (!)
```
The main idea is to have a list of two different functions (`listOfFunctions`), one to keep an element (`k`) and one to drop it (`d`). The list is indexed by the current element from the input list (`x`) and the function it picks determines whether to keep or drop the element. At index 0 we have `d`, because we want to drop 0s, the first `k` is at index 10, because we want to keep 10s (newlines). Both `k` and `d` take two parameters: `x` and the result of a recursive call with the rest of the list (`xs`). `k` prepends `x` to the recursice call and `d` just returns the recursive call.
The literal list of functions ends at index 61 (char `=`, the last `k` in the list) and is followed by an infinite number of `d`. This not only saves many explicit `d`, but also prevents us from having to end a finite list with `[]` which would require additional chars.
Edit: thanks to @Ørjan Johansen for +1 score and -753 bytes.
[Answer]
# JavaScript (ES6), score: 242 (142 bytes)
A rather naive approach using an array of bytes for I/O.
```
t=>t.filter(t=>'f'>'fffffffffffffffffffffffffffffffffffffffeeeffffeffffffffffffffeeffffffffffffffffffffffffffffefefffffffeeffeffefffffefe'[t])
```
[Try it online!](https://tio.run/##jZDxSsMwEMb/31McY5AENVMQBKGFOd@iLSxLL21HTUtyjI4xX72m3SoyZXgQcvn4fV@S26m98tpVLT3YJsfeRD1FMUlT1YSOh54ZFtb/ChHH7Vq96fnGBw4nd5BZQpnoCT1BBB6iGHRjfVOjrJuCbxZH7jDIYHgipfSZ/FAt1yMndancOnxoRVyEkjXagsoTbA@E3IvX1CaLY7DLXVNZzu6ZOGWp3YjZbLiPz9PH1MLqbf2utjr/TLsXk3bGzAUsl2AbKitbXEjGhYziJMMwMkeBmCqQuEd3GGHgVCI8PcPwMKXDbD1QqQiUwyEQzgPHXFxip/OPwL9isdPYErCcnX0G7oCxa88vX/8F "JavaScript (Node.js) – Try It Online")
### How?
The 14 characters that are not filtered are `'().=>[]efilrt`. They are marked with an `e` in the lookup string. For characters above `t` (ASCII code 116) which are not defined in this string, `'f'>undefined` is *false*.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), score: 253, tiebreaker: 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function
```
∩∘'∩∘'''
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHykcdM9ShlLr6/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NPS8/P6lYnSsNpA/GzAMaAESoHHX1YnUA "APL (Dyalog Unicode) – Try It Online")
`∩` intersection of the argument
`∘` and
`'∩∘'''` the three characters in the code (`∩∘'`)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), score ~~232~~ ~~235~~ ~~239~~ ~~241~~ 242, ~~260~~ ~~407~~ ~~352~~ ~~249~~ ~~243~~ 249 bytes
```
fn(int*f,int*i,int*n,int**t){if(f==i)if(*t=n){}if((f==i)==('+'=='*')){if((*f==',')+(*f=='\'')+(*f=='(')+(*f==')')+(*f=='*')+(*f=='+')+(*f=='=')+(*f=='\\')+(*f=='f')+(*f=='i')+(*f=='n')+(*f=='t')+(*f=='{')+(*f=='}'))if(*n++=*f){}if(fn(++f,i,n,t)){}}}
```
[Try it online!](https://tio.run/##5VLbTsMwDH1ev8IMQXMrKq9s2RdMvCCeGEKjazZLI53aVKBV/fbhpCPrvoEX5@jYPj62UmTbojidjGVonTDKRwzRhigc79AwozVyeoXTlnc9oYHSmqUy1ToVKQ@FTBCfqpTLAa3SCFlEPCIRkYxIX5pXEZqIMCIbkYuoi6gnR96xlVILM5imNaWkJZVVjvz2fX@6RVvs200J88ZtsHrYLZIxVaPdei6hY8DXGi3j0CWTYreuofhszVv@85jn77Nk0jR4LD8cIGFffEkqEKXdEP29w30JzGxL1zDfrSBUKPCzLYcbDc@vy2UYMTFVDQxBQz4bRuH7DFBKTjmAgaDsX8p3WBZEKUgMj4J7Gs190nsIYmNp4jIqI11YhEGYZYN@EQeM9A9tNE6Oq9Z55T65soowH7YazF6M@sOMHZ5Xv3J5oHs7w6Yr@1JUdfkEd8d2er4SZMD8Dplv4VTd/99v@ws "C (gcc) – Try It Online")
A function taking [a pointer to the beginning and end of an int array](https://codegolf.meta.stackexchange.com/a/14972/) (where end is the first character not included), a pointer to a buffer and a pointer to another int pointer. It writes the result into the buffer and the end pointer of the result into the last pointer.
[Answer]
# Regex, Score: 255, 2 bytes
```
\\
```
Matches the character `\`.
[Try it online!](https://tio.run/##DcxpX4IwHADg934KWodb4bpP0iyzsrRDSDvIWuOvLHHQNgw7Pjvx/vk9XFe4FnmqhRxZ7kwbmFAPMkO7MEojpppZokBrEUvtlIaxAsZDPGXKGltCWi1ZOBZ4cVMGmFA3iYTBZV@WCSn1lTDQFhKwNqrYaSOWnBlcxJDRDjM8BI3Hdh3lvp@jIkoixgEjXyIbIVJ0EAE3mFdrnPZYlAIhxMmtOTS/sLhUxmR5xa7Q1bX1jc2t7Z3dvf0D57BaO6ofnzROm2fnF63Lq3bn@ub2rut6973@w@PTs/8yeH1j7zyA4SgUH@NoIuPkU2mTTr@y2ffP798/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), score 254 (4 bytes)
```
f⁾f⁾
```
[Try it online!](https://tio.run/##y0rNyan8/z/tUeM@IEr7//9/YlJySiqQvxfET01JTkoEAA "Jelly – Try It Online")
`⁾xy` is shorthand for `“xy”` (a two-character string).
We `f`ilter the input string down to just the characters occurring in `“f⁾”`.
[Answer]
# [POSIX shell](https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/V3_chap02.html), score 249, 18 bytes
```
tr -cd \\\\\ cdrt-
```
[Try it online!](https://tio.run/##S0kszvj/v6RIQTc5RSEGBBSSU4pKdP//V1RSVlFVU9fQ1NLW0dXTNzA0MjYxNTO3sLSytrG1s3dwdHJ2cXVz9/D08vbx9fMPCAwKDgkNC4@IjIqOiY2LT0hMSk5JTUvPyMzKzsnNyy8oLCouKS0rr6isqq6prePKycxLVTDiKgEA "Dash – Try It Online")
Simple [`tr` command](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/tr.html) that deletes all characters but `-\cdrt` and space. Four backslashes are needed because both the shell and the `tr` command use backslash escapes. The fifth backslash escapes the following space character.
If `tr -cd` was considered a programming language, one could write a single byte progam with score 255.
[Answer]
# [Ruby](https://www.ruby-lang.org/) -p, score 248 (8 unique bytes / 483 bytes)
```
eval""<<11+11+11+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1+1<<11+11+11+11+1+1<<111+1+1+1+1+1<<111+1+1+1<<11+11+11<<11+11+11+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1<<111+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1<<11+11+11+11+1+1+1+1+1<<11+11+11+1<<11+11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+11+11+1+1+1+1+1<<11+11+11+1+1+1+1+1+1<<11+11+11+11<<11+11+11+1+1+1+1+1+1<<11+11+11+1+1+1+1+1+1
```
[Try it online!](https://tio.run/##KypNqvz/P7UsMUdJycbG0FAbikAQmY@GkCGaMogAmjyGUnS7SLARjyJs1pPgE2JMJ@B3TGHsPsVtHTYZHOoJK0HA///DHH1cgfGcqqSkpKysDAojbe1/@QUlmfl5xf91CwA "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), Score ~~244~~ ~~245~~ 246, ~~13390~~ 1575 bytes
Takes a list of integers
```
exec'%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c'%(111+1,111+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1,111+1+1+1+1+1,11+11+11+11+11+11+11+11+1+1+1,111+1+1+1+1+1+1+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1,11+11+11+11+11+11+11+11+11+11+1,111+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,111+1+1+1+1+1+1+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1,111+1,111+1+1+1+1+1+1,111+1+1+1+1+1,11+11+11+1+1+1+1+1+1+1,11+11+11+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,111+1+1+1+1+1+1+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1,11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,111+1,11+11+11+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+11+11+1,111+1+1+1,11+11+11+11+11+11+11+11+11+1,11+11+11+1+1+1+1+1+1+1+1+1+1+1,11+11+11+1,11+11+11+11+11+11+11+11+11+1+1,111+1+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+1,11+11+11+1+1+1+1+1+1,11+11+11+1+1+1+1,11+11+11+1+1+1+1+1+1+1+1+1+1,11+11+11+1+1+1+1+1+1+1,11+11+11+1+1+1+1+1+1+1+1,11+11+11+11+1+1+1+1+1,11+11+11+1+1+1+1+1+1+1+1+1+1+1,11+11+11+1,11+11+11+1+1+1+1+1+1+1+1,11+11+11+11+11+11+11+11+1+1+1+1+1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P7UiNVldNZl@UF1Vw9DQUNtQB0xqQ1jaOBECEqkMRQNR2jHVouvBLYPPQG18CNP7hDxABUeRH5D0txGL/3FGqDZhYeq5dQTEF3F5BmuEEYgSIvMCLmXE@JqwN/HHE2lhjF9Qh8jQJSMBE2UFrlAh1eea//8XJealp2oYmZppAgA "Python 2 – Try It Online")
This evaluates to the following line of code:
```
print[x for x in input()if x in map(ord,"exc'%+()1,")]
```
---
# [Python 2](https://docs.python.org/2/) Score 248, \$ \sim 2^{52}\$ bytes
This answer is obviously a theoretical one.
The structure is
```
exec'<2**51 times %>c<2**50 times %>c ... %%c%c'%<112 times -~>0%<114 times -~>0% ... %<41 times -~>0%<93 times -~>0
```
In theory this would execute the same as:
```
print[x for x in input()if x in map(ord,"exc'%-~0")]
```
---
# [Python 3](https://docs.python.org/3/), Score ~~240~~ 241, 54 bytes
+1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
```
lambda a:[i for i in a if i in b""" ":[]abdfilmnor"""]
```
[Try it online!](https://tio.run/##LYyxDsIgFEX3fsWVpIEmdtHo0ERndweH2gEKVBIKzZOlX49YfdPNveedZU2vGI7Z4oJn9nJWWkJ2vYONBAcXIOHsLynGGFjXD1Jp6/wcIpVmyFSerSAZJiMOp3PTVAu5kAS/j5FMx/coLVp4EwSVtfq602bkN@N9xCOS17sCKp7MO21hjNpM0VveVcBfWBPaK2riqCFSodaCCytSUy5/AA "Python 3 – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), score 247, ~~234~~ ~~213~~ 208 bytes
*-5 bytes thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen)*
```
== =t
t['\'':t]=['\'': ==t]
t['\\':t]=['\\': ==t]
t[':':t]=[':': ==t]
t['[':t]=['[': ==t]
t[']':t]=[']': ==t]
t['t':t]=['t': ==t]
t['=':t]=['=': ==t]
t[' ':t]=[' ': ==t]
t['
':t]=['
': ==t]
t[tt:t]= ==t
t t=t
```
[Try it online!](https://tio.run/##Tc@xDoIwFIXhvU9xt8KAMSY6kNxNBxM3RujQQEUiLUaOJr68FbDGbuf/tlP3Rjtvh@bRG7K6c56ZGAKlrKTMofg7iBlq0eqnVaR5wDyyMlgZmQqmIkMwRMbBODIKRpGJYOJvwExzCRAYvrO34Q4q0BzcUxTQUzBttjvKqDeuxYWS6XQCfTULT9/WcrVSaerf9bnX7eiz48nvX07brh4/ "Clean – Try It Online")
Uses a pattern-matching recursive function to remove characters. Doesnt even need `StdEnv`.
[Answer]
# Lenguage (with `stty +brkint -ignbrk`), score 255, 3890951 bytes
The program consists of 3890951 NUL bytes (making this one of the shortest Lenguage programs ever; 3890951 bytes is easily small enough to fit on my disk, so I actually ran this in a Lenguage interpreter). The OP wanted the Lenguage/Unary solution to be golfed, so here we go. (Note that Unary would be much longer because it requires the use of `0` rather than allowing the use of NUL.)
Note that Lenguage does not, despite what its documentation implies, act like brainfuck does; I/O works entirely differently (something that I noticed when testing this program). In particular, Lenguage refuses to take input from anything other than a terminal, so the bytes that are being filtered out are the raw bytes sent over the terminal connection (note also that as it's filtering out the raw bytes, you won't see the keys you type at all). In practice, this means that the program will absorb any sort of input sent to it except for the NUL byte (typically typed as Ctrl-@), which will be echoed literally (at which point, the vast majority of terminals will ignore it, as the NUL byte is the terminal equivalent of a NOP instruction). In order to verify that the program works, it's simplest to modify the Lenguage interpreter to output in decimal, leading to the echo being actually visible.
What happens at EOF? Well, if the terminal is sending a series of bytes, there's no way to send EOF; all 256 possible bytes are interpreted literally, and there's nothing else you can insert into the terminal stream. However, if you happen to be using an old-fashioned serial terminal, you can press the "break" button on your terminal to purposely send misencoded data, allowing for a 257th possible code; this "break" is the only plausible equivalent of an EOF, as it's sent out-of-band and indicates something other than valid data. If your terminal configuration has the "interrupt-on-break" flag set (and the Lenguage interpreter does not, as far as I can tell, alter that setting), sending the break signal will cause the Lenguage interpreter to crash, which conveniently acts as a way to implement the desired EOF behaviour. I'm not sure whether this is a default setting (because nobody actually uses serial terminals nowadays, it basically never comes up), so I mentioned it in the header as part of the specification of the language interpreter being used.
## Explanation
```
1110110101111100000111
001 Initialise tape element 0 to -1
110 111 While tape element 0 is nonzero:
110 111 While tape element 0 is nonzero:
101 Read a byte from the terminal into tape element 0
100 Output tape element 0
000 Add 1 to tape element 0
```
The inner loop will only exit when NUL is typed at the terminal; after this, we immediately echo the character typed (i.e. the NUL). Adding 1 at this point will ensure that tape element 0 is nonzero again, so the outer loop cannot exit at all (until a break input crashes the interpreter), and we'll fall back into the inner loop.
It's golfiest to use subtraction to enter the outer loop, but addition to continue looping around it; addition has a shorter encoding, but cannot appear at the start of the program (as the encoding would look like leading zeroes and thus be ignored).
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, score 251, 13 bytes
```
y/ycd\\\///cd
```
[Try it online!](https://tio.run/##K0gtyjH9/79SvzI5JSYmRl9fPznl/39FJWUVVTV1DU0tbR1dPX0DQyNjE1MzcwtLK2sbWzt7B0cnZxdXN3cPTy9vH18//4DAoOCQ0LDwiMio6JjYuPiExKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrqmto6rpzMvFQFo3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~252~~ 253 (~~4~~ 3 distinct [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) used; 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) in total)
```
„ÃJ„„JJÃ
```
[Try it online.](https://tio.run/##DczBDcIwEETRVkZ7RhTiMw0syYRYCjayVwnckNwHzbiTNGJW@nrHn6veI8c4v7/eguuF0NsYtzVWeApjNVhGJREXHMSkCYXPvBPcWT62xvQA3xNfhiUX6LZBfCUXSG@uphkS5PoH)
**Explanation:**
```
„ÃJ # Push the String "ÃJ"
„„J # Push the string "„J"
J # Join them together: "ÃJ„J"
à # Only keep these three characters from the (implicit) input
# (and output the result implicitly)
```
Note that the order of `ÃJ` and `„J` in the 2-char strings are important, because `„` is also used for [dictionary words](https://codegolf.stackexchange.com/a/166851/52210), where every two characters is a dictionary word (except for a select few characters like letters, digits, `-`, and such). So `„JÃ` would be 'a word' `J`, as well as a dictionary word `Ã` + the next character (in this case `„`), [which apparently is the word `"causing"`](https://tio.run/##yy9OTMpM/f//UcM8r8PNQPL/fwA).
[Answer]
# Perl 5, score 251 (5 distinct bytes, 8058 bytes total)
```
s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s>><><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s>><><<s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>>^s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<^>^>^^s>^><>^s<^>^>^^s>^>s>^s>^>e>^s>^>^>^s<^>^>^^s>^><>^s>^><>^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s^^^<<s^^^<<s>>><<s>>>^s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>>^s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>>^s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s^^^<<s>><<><<s>>>^s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>>^s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<^>^>^^s>^><>^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s>><<><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s^^^<<s>><<><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>>^s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s>><<><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>>^s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s^^^<<s>><><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<s<>e<><s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^<<s^^^^s^^^<<s>>><<s>>><<s>>><<s>>><<s>>>^s>>><<s>>><<s>>><<s>>><<s>>><e^s<^>e>ee<e^<see><>>>>^<^^<se^e^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^e^^^^^^^e^^>^^^^s^s^ss>^<^^^^s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^s^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>^<^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>>eeee^s<><<eee<e^<see><>>>^<^<^>^^^^s^s^s>^<^^^^^^^^^^^>^<^^^>>eeee
```
[Try it online!](https://tio.run/##7ZnJUsMwDIafhQOcGDhxAY14E82wiLVAqcv68kFJKMQ0hTYx1e@AO2PX2aRMvl9SnLFORntFEYiJrFMbg4jQEr1EG5irSzBHvXzdsGinSiBhZVX7S0HVLlceQlLORMWh6efI9f3aL1Q@1Tfv2Brm3x3ybxCOsCGkJU1dgG6H@HugXcmFQNSVxfVa7EXXLFAuA5d4swVAliNX67T3wZRZ5TIIiT3laBq4GrQehOeOnZ3SN4nHCX3VHE5A@A4iyeeQ9CGLgF8I2z/UDd0EklExPEA5ZayynMSXUpPSmqiIOokNS2aYysESg7MLiyq1BGsnvRZP4LNGBlkBOOoj@ZO4kpojf4jlUi41EXrhA@dUktUgosxfruHwhuHYz3qyMP3/WefPh@D8P@vICgvvLT0KxGjgosDqZrwJpcZ0mEvUeEqxi/WsPrsojl51Mn15uLwb34fTs/OLq@vRzdPzyePxrb1cbh/sbxzu7G5uvQE "Perl 5 – Try It Online")
Uses the [`<>^es` Turing-complete subset of Perl](https://codegolf.stackexchange.com/a/124046/6484). The above code was obtained by running `print<>=~y<<>^es><>cdr` through [my converter](https://tio.run/##dVNNT@MwED2i5sofmA1eNeGjpkgrrTaOlSOXHvdEcNQGQytKGmLaUkH717tv4lRlV9qMFNsvb8Z@z5PaNvMf@/3ZtxoTuqrnQSBCSqlv@kkQvGzoe7l4sA7I6zpSpEgjDMIiHCIha2hE2tGElKETUlifYm3oHHNHt2Qxz3NS2tCKNFbxofR03HDpKOj1VZ9STX2njVa6fwlEd4gywEwLmSPJeJI9ItYj7og4j1x/4ShltW3R4ReeMaZDk@OmEIJ3h6@@4KrFjbLW4hwKyc4PFmymsz63nNC6Gdf0EfSgNcpaHy8pK/lr73HRUNTYlW2cJVHcXd9TuiM5kE8xZ3CKKGGNaNM@RLElZDzMLIW/q@dqsa6I3fuF3DABP2NyhJQBrg42vVOELemChnRFc1s9vU1RKyZJN3F82IoT/QZ3omgP4KSRouSVJD7i9WAgzkrmORndKX0f@7cUN2LoKccTgraFtOzQMS9QHypR6JBlMwhGY9@WTUWhU1p5EJ5ZCxFbb1q1fOk8ExMUWVb1uHymcPITVVqjkvZj1mCsl26K2SVrNrh4iFfKT99JXLGr6@lsbttS0DxkzUFvvijHcxRD@TBr2D8nc8PhpNbayYPXPnkjlZRo@43UGC/o5u8E1WbMHjtemv6X@A@zq8gn6lzZ7Y4t4Q2RubuQecXnzorOU7gj2l@nbYvPz7RttOg1ciq/PdcnMXyAi5EoePYanVjDfZuskiRHT7tbezoZjXSMRtzSYUPfD0FnSmH4frjD@S9w1rJKbnL@GdlgDt/0h8evdHeb@33dzKo3pdPdBroNrlnp8qH5Aw).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), Score ~~248~~ 249 (50 bytes)
There *had* to be a better way... and there is!
```
@(a)a('l'=='a'==all('l'=='a'==(a==('@al()''=')')))
```
[Try it online!](https://tio.run/##TYexDYAwDATHeX/jDSxllSckNJZoItY3KSgo7k5396Vn1Ax3r2aiDIkIaEuZvzNt0JRGIECQrGnQ0c8xry9gvQ "Octave – Try It Online")
Filters out everything but `@al()'=`.
The `all` function is superior over `any`, because it only uses two distinct bytes. Note that `any(...)` is equal to `not(all(not(...)))`. So, we start with the program
```
@(a)a(~all(a~=('@al~()''=')'))
```
Instead of `~` (`not`) we can also write `0==`. Of course, that would mean we have to filter out `0` as well. Instead, note that the following expression is also false (zero)
```
'l'=='a'
```
---
If MATLAB compatibility is not an issue, I can go to 47 bytes
```
@(a)a((l='l'=='a')==all(l==(a==('@al()''=')')))
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), score 249, 16 bytes
```
{∈"{∈\\\"&}ˢ"&}ˢ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v/Vjzo6lEBETEyMklrt6UVg4v9/pcTilDQ1tZKi1PKS8tSikiIlAA "Brachylog – Try It Online")
Not entirely sure how this works with the rules, what with Brachylog having [its own special code page](https://github.com/JCumin/Brachylog/wiki/Code-page) and all, but I can still explain how it works:
```
{ Start of inline predicate.
∈" Input is a member of the string literal containing:
{∈ the opening bracket, the member-of character,
\\\" backslash, quote,
&} ampersand, the closing bracket,
ˢ" and the superscript s.
&} Unify the input to the inline predicate with the output from the inline predicate.
ˢ Output everything from the input that made it through the inline predicate.
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score: 253 (3 distinct bytes used, 97 bytes in total)
```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S N
S _Duplicate_input][S S S T S S T N
_Push_9][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_PRINT][S N
S _Duplicate_input][S S S T S T S N
_Push_10][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_PRINT][S N
S _Duplicate_input][S S S T S S S S S N
_Push_32][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_PRINT][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][T N
S S _Print_character][N
S N
N
_Jump_to_Label_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[**Try it online**](https://tio.run/##7ZLBCoMwDIbP@hQ@gttOO8@LQ6qoN5FQXYYF56S22@M7oxY2NoYMdpPQHvKn/xea3CuhsGt5iX2fMTtxEofZcJDIFULAC6whCMMoz0gZtUh3FbiUoHLwdFuLkqqHXGoxO7WGbIz8BEnq@Qx4B2XFJS8VSqqgGHQlBd7wg41oWq0Mj8zoNtw9OUwpSHShyDbPJujYnX8GF4760oK6zv1Hsc/SJSA6BrRx/0kyYWi77e80YjF7KHlVp6lNE32f6fyWPpZkiKRo1POcvrmum7JuyrJNeQA) (with raw spaces, tabs and new-lines only). A nice bonus is that I can use this code to transform the highlighted code above to the raw Whitespace program (which I did in this TIO as example), for which I usually use Notepad++. :)
**Explanation:**
Pretty straight forward. Here the pseudo-code:
```
Loop indefinitely:
Character c = STDIN as character
if(c == SPACE or c == TAB or c == NEWLINE):
Print c as character
Go to the next iteration of the loop
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), Score 245, 111 bytes
```
h=>h.Where(W=>W=='|'||W=='='||W=='>'||W=='h'||W=='e'||W=='r'||W=='W'||W=='\\'||W=='\''||W=='('||W==')'||W=='.')
```
[Try it online!](https://tio.run/##ZcjHUsMwFIXhPU9BlwyJ6dWWKCGBQGihiGKKolxHgkQB2aaaZzcwc1lxNt8/RyVllZiillkV1qs264GTrS6ESkvHS/8eHrNCM659ocEBFYwLxkhO8vxXhnJUo4A6VKBR9BcEg6Ie6hOvCAaEMynQJHXGdvxK3yqZ0pg2QbYbxgL1fhYUg0PDI6Nj44R6E5Olsj81PTM7N7@wuLS8shqEjK@tb2xWtqq17Z367l5j/@Dw6Lh5cnp2Li4ur66jm9u7e9lSbYg72jw8dnu2//TskjR7eX17//jMv74B "C# (Visual C# Interactive Compiler) – Try It Online")
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), Score 243, 33 bytes
```
n=>n.Intersect("Iter\\\"c=>n().")
```
Naive solution using `Intersect`
[Try it online!](https://tio.run/##ZchbXwFBGIDx@z6FljQrlqKTPeQQtYgiFIvGmGUcXszMlkqffe19z9Xz@xORIIL5ZQ@IYZfAW1GOx0tqkBnmVvyfWK7pg2mBZoOkXFAikWIH5ziOQgJHqqaovn7U5UxSJCRnMNWKayBYIhc1KZ7UGFCkBul@6FgJR06ip0iNncUTWjJ1fpHOXF5d39xmdcO07nL5QvG@VH54tCvV2lO98fzSbL22O923917fGQxHH3hMJtSdzth8sVzBerPlQnqfX7vvn9/93wE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes, score: 250
```
[^]n\\\n[^]
```
[Try it online!](https://tio.run/##K0otycxL/P8/Oi42LyYmJg9Ic6HyAA "Retina 0.8.2 – Try It Online") Filters out all characters except for newline, `[`, `\`, `]`, `^` and `n`. Although the characters `[\]^` are consecutive, using a range would actually cost a byte and also reduce my score.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 249 score, 20 bytes
```
f"[ fq\"[\\\\\\]]" q
```
[Try it online!](https://tio.run/##y0osKPn/P00pWiGtMEYpOgYMYmOVFAr//1cyNDa1MDSwNDUCAQUFC8OSwvzCwkyFtLS01PSM8piY1PT86NjoWCUA "Japt – Try It Online")
[Answer]
# Ruby `-paF[^$_=F*']`, score 250, 8 bytes
```
$_=$F*''
```
I'm not sure at all this is legal under the current site rules for command-line flags, since the "flag" here is sort of passing in code that includes forbidden bytes. The `F` flag defines an input separator regex consisting of all characters not in the code proper. The code proper sets the output to the concatenation of all input records.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Dv`, Score 254, 4 bytes
```
‛↔‛↔
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=Dv&code=%E2%80%9B%E2%86%94%E2%80%9B%E2%86%94&inputs=%27Helloworld%E2%80%9B%E2%86%942345678%E2%80%9B%E2%86%94%27&header=&footer=)
```
‛↔‛ # Two-char-string '↔‛'
↔ # Remove characters not in said string
```
This *is* valid because of the `v` flag, which takes input as Vyxal encoding.
[Answer]
# PHP, score 234, ~~58~~ 62 bytes
```
<?=preg_replace("_[^\"$(),;<=?[\]^\_\\\\aceglnpr]_","",$argn);
```
Run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/d1b00ccf72df48adaaeb948453b4457395110eea).
[Answer]
# [MATL](https://github.com/lmendo/MATL), Score 252
```
t't''m)'m)
```
[Try it online!](https://tio.run/##y00syfn/v0S9RF09VxOI/v9XT0xKTkksyVVTV1cHAA "MATL – Try It Online")
Explanation (for input `input`)
```
t % Duplicate input.
% Stack: {'input', 'input'}
't''m)~' % Push the string t'm)~
% Stack: {'input', 'input', 't'm)~'}
m % 'ismember' to filter
% Stack: {'input', [0 0 0 0 1]}
) % Index into input.
% Stack: {'t'}
% Implicit display.
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), Score: 248, 162 bytes
```
,[>---[----------->--<]>-[>->->->-->------->-->-------[<<]>-]>--->-->->--->------------->->-----------[<]<<[->>>->->->->->->->-<<<<<<<<<<]>>>[>]>[[>]<[->-<]>.>],]
```
[Try it online!](https://tio.run/##VU5dDoJgDHv3KjBPsPQiyx74EUQQlB9BL4/7ogNtl2Vdl2Zpn1RtMWX1usYCIhLaYZoVZPsPQ7nho3A4Ufj2O/yl/GphZRYCPNTJG9RMgUKshdPwxBEaq/0YkSjjkKRZfirKc3Wpm2vb3e79ME6PeXm@3g "brainfuck – Try It Online")
Usually I don't answer my own questions, but people seem to have read my profle page, especially where it says `If someone comments on a question "I wish there was a brainfuck solution", I feel obliged to provide one.`
The bytes filtered out are `-<>[],.` and ignores the NUL byte, since it is indistinguishable from EOF. This is a bit longer than usual, since I'm deliberately avoiding using `+` to get a slightly better score. Even so, I might be able to golf the number generation part to save a few bytes.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), score 249, 16 bytes
```
sf/"f/\"Tzs\\"Tz
```
Filters out every character except `f`, `s`, `T`, `z`, `"`, `/`, and `\`
[Try it online!](https://tio.run/##K6gsyfj/vzhNXylNP0YppKo4BkT@/5@YlJySmpaekZmVnZObl19QWFRcUlpWXlFZpaRuaGRsYmpmbmFpoBtvq61vH1MTHVtda22lY6NnBwA "Pyth – Try It Online")
[Answer]
## K, score 246, 23 bytes
`{x@&~x in"\"~ in@&{x}"}`
{..} is a lambda with arg x
read as 'returns x at where not x in string'
String contains \"~ in@&{x} (the ten bytes used in the program)
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), score 239, 133 bytes
```
+xed -i -case ixixi x+x+x xexex xdxdx x-x-x xixix xcxcx xaxax xsxsx xbxbx xyxyx xtxtx x"x"x x\[x\[x x\]x\]x x\\x\\x "x x x" x[byte]xx
```
[Try it online!](https://tio.run/##HcrnVsMwDAXg3/AUl5bRYswotOy9955JAMdxITQEqENRWK8eZM53jyVZss1WUQgyEWQMqZU1iImBBAMZBooYSDK4Jb@agRQDWQYKGShnoIyBSgzkey5cAxeuvgvcik9AXphnJiAqRBKnJjEphDVZR7Xx32uVaEg31uoNWa7wZ7XA/VhtfKLemJyaHpXzvz1L5d6@2/7BSvVOdL19mHaWv8cvr17gH1@un5xdn28fHn39fHcrGzUfHp9ayezA8unaxubWzu7eTOmTdCdMn4eGR26uVi9WDvbnFhb/AA "sfk – Try It Online")
Performs replacements on the input (written as `[delim][from][delim][to][delim]`) changing all characters used in the program to themselves, which removes the character positions from consideration for input to the final replacement `x[byte]xx` which maps all bytes to the empty string.
] |
[Question]
[
The Tabula Recta (sometimes called a 'Vigenere Table'), was created by Johannes Trithemius, and has been used in several ciphers, including all variants of Bellaso's Vigenere cipher and the Trithemius cipher. It looks like this:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
```
I frequently need this, but can't find it anywhere on the internet to copy and paste from. Because the square table is so long, and takes frigging *ages* to type, your code must be as short as possible.
### Rules/Requirements
* Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
* If it is possible, provide a link to a site where your program can be tested.
* Your program must not write anything to `STDERR`.
* [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Your program can output in any case, but it must be printed (not an array or similar).
### Scoring
Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.
Eventually, the answer with the least bytes will win.
## Submissions
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 86986; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Vim, ~~25~~ 23 bytes
```
:h<_↵jjYZZP25@='Ypx$p'↵
```
Where `↵` is the Return key.
```
:h<_↵ Open the help section v_b_<_example.
jjY Copy the "abcdefghijklmnopqrstuvwxyz" line.
ZZP Close this buffer and paste in ours.
25@=' '↵ Run these commands 25 times:
Yp Duplicate line and move to column 1 of new line.
x Cut the first character.
$p Move to the end and paste.
```
[![GIF of solution](https://i.stack.imgur.com/RuYkf.gif)](https://i.stack.imgur.com/RuYkf.gif)
**EDIT**: lowercase is okay, so I can save two keys.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes
Thanks to **Downgoat** for saving 1 byte. Code:
```
ADv=À
```
Explanation:
```
A # Push the lowercase alphabet.
D # Duplicate it.
v # For each in the alphabet...
= # Print without popping and with a newline.
À # Rotate 1 to the left.
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=QUR2PcOA&input=).
[Answer]
# Python 2, ~~59~~ ~~57~~ 53 bytes
```
a=range(65,91)*27
a[::-27]=[10]*26
print bytearray(a)
```
*Thanks to @xsot for -4 bytes!*
[Answer]
## [///](http://esolangs.org/wiki////), 220 bytes
```
/|/\/\///n/WXY|m/JKL|l/PQRS|k/CDEF|j/ZaNfV|i/MbAeI|h/TUcO|g/GHdB|f/OlTU|e/BkGH|d/ImMbA|c/VnZaN|b/NfVnZ|a/AeImM/ab
ed
kg
DEFgC
EFgCD
FgCDE
gk
HdBkG
de
mi
KLiJ
LiJK
im
ba
fc
lh
QRShP
RShPQ
ShPQR
hl
UcOlT
cf
nj
XYjW
YjWX
jn
```
[Try it online!](http://slashes.tryitonline.net/#code=L3wvXC9cLy8vbi9XWFl8bS9KS0x8bC9QUVJTfGsvQ0RFRnxqL1phTmZWfGkvTWJBZUl8aC9UVWNPfGcvR0hkQnxmL09sVFV8ZS9Ca0dIfGQvSW1NYkF8Yy9WblphTnxiL05mVm5afGEvQWVJbU0vYWIKZWQKa2cKREVGZ0MKRUZnQ0QKRmdDREUKZ2sKSGRCa0cKZGUKbWkKS0xpSgpMaUpLCmltCmJhCmZjCmxoClFSU2hQClJTaFBRClNoUFFSCmhsClVjT2xUCmNmCm5qClhZalcKWWpXWApqbg&input=)
This was surprisingly non-trivial and I have no clue whether it's optimal.
~~The only way to golf a problem like this in /// is by extracting common substrings.~~ ([Turns out I was wrong.](https://codegolf.stackexchange.com/a/87384/8478)) However, due to the nature of the output it's not at all clear which substrings should best be extracted since you can't actually extract the entire alphabet due to the linebreaks. So you'll need to extract some substrings of the wrapped alphabet, but then there are trade-offs in terms of how long you make the substrings and which ones you choose.
So here's what I did. [This is a CJam script](http://cjam.tryitonline.net/#code=MjYsMj5xZmV3On4kZWB7fl8sKEAoKjUtW1xdfSUkVyVTZipOKg&input=QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoKQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWkEKQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaQUIKREVGR0hJSktMTU5PUFFSU1RVVldYWVpBQkMKRUZHSElKS0xNTk9QUVJTVFVWV1hZWkFCQ0QKRkdISUpLTE1OT1BRUlNUVVZXWFlaQUJDREUKR0hJSktMTU5PUFFSU1RVVldYWVpBQkNERUYKSElKS0xNTk9QUVJTVFVWV1hZWkFCQ0RFRkcKSUpLTE1OT1BRUlNUVVZXWFlaQUJDREVGR0gKSktMTU5PUFFSU1RVVldYWVpBQkNERUZHSEkKS0xNTk9QUVJTVFVWV1hZWkFCQ0RFRkdISUoKTE1OT1BRUlNUVVZXWFlaQUJDREVGR0hJSksKTU5PUFFSU1RVVldYWVpBQkNERUZHSElKS0wKTk9QUVJTVFVWV1hZWkFCQ0RFRkdISUpLTE0KT1BRUlNUVVZXWFlaQUJDREVGR0hJSktMTU4KUFFSU1RVVldYWVpBQkNERUZHSElKS0xNTk8KUVJTVFVWV1hZWkFCQ0RFRkdISUpLTE1OT1AKUlNUVVZXWFlaQUJDREVGR0hJSktMTU5PUFEKU1RVVldYWVpBQkNERUZHSElKS0xNTk9QUVIKVFVWV1hZWkFCQ0RFRkdISUpLTE1OT1BRUlMKVVZXWFlaQUJDREVGR0hJSktMTU5PUFFSU1QKVldYWVpBQkNERUZHSElKS0xNTk9QUVJTVFUKV1hZWkFCQ0RFRkdISUpLTE1OT1BRUlNUVVYKWFlaQUJDREVGR0hJSktMTU5PUFFSU1RVVlcKWVpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1gKWkFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFk) which finds all substrings up to length 25 in the given string and for each of them computes how many bytes its extracting would save. Basically if there are `N` copies of a length-`M` substring, you'd save `(N-1)*(M-1) - 5` substrings, these substrings don't contain slashes. Also, technically, when you've already extract 8 substrings or so, the constant offset at the end reduces to `-4`, but the script doesn't consider that.
Anyway, here's what I did with the script:
* Run the script against the current code (which is initially just the output).
* Out of the substrings that yield the largest improvement, pick the shortest one. If there are several, pick the lexicographically smallest (from what I can tell, for the given input this reduces overlaps between substrings).
* Replace all occurrences of the chosen substring in the code with an unused lower case letter.
* Prepend `/x/ABC/` to the code where `x` is the chosen letter and `ABC` is the substring.
* Repeat until there are no substrings left that would save anything.
At the end, we save a few more bytes by replacing the resulting `//` with `|` and prepending `/|/\/\//` (this is why extracting substrings only costs 4 instead of 5 bytes after the 8th substring or so).
Like I said, I have no clue whether this is optimal and I find the rather irregular-looking result quite interesting. It might be possible to get to a shorter solution by chosing non-optimal (but more) substrings somewhere down the line. I wonder what the complexity class of this problem is...
[Answer]
# C, 47 bytes
```
i;f(){for(i=702;i--;)putchar(i%27?90-i%26:10);}
```
[Try it on Ideone](http://ideone.com/uTof3S)
A single loop, printing the alphabet every 26 characters but with every 27th character replaced by a newline.
[Answer]
# J, 15 bytes
```
u:65+26|+/~i.26
```
[Online interpreter](http://tryj.tk/).
```
u:65+26|+/~i.26
i.26 creates vector [0 1 2 ... 25]
+/~ builds an addition table with itself
26| modulo 26 to every element
65+ add 65 to every element
u: convert every element from codepoint to character
```
[Answer]
## [///](http://esolangs.org/wiki////), 128 bytes
```
/:/fABCDEFGHIJKLMNOPQRSTUVWXYZ
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\: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:
```
[Try it online!](http://slashes.tryitonline.net/#code=LzovZkFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaCmZiZmJBZnhmCnhiQV94Zl94CnhmYmJiQWZiYi8veC9iZmYvL2YvXC8vL2IvXFw6QjpDOkQ6RTpGOkc6SDpJOko6SzpMOk06TjpPOlA6UTpSOlM6VDpVOlY6VzpYOlk6Wjo&input=)
Inspired by [Jakube's amazing answer](https://codegolf.stackexchange.com/a/87245/8478) to the L-phabet challenge, I thought I'd try my hand as well at actual *programming* in /// as opposed to just using it for compression. This was pretty tricky and I needed four attempts, but in the end it came out much shorter than my [compression-based solution](https://codegolf.stackexchange.com/a/87056/8478).
### Explanation
A quick primer on ///: basically the interpreter just reads the code character by character and does the following:
* If it's neither a `\` nor a `/`, print it.
* If it's a `\`, print the next character.
* If it's a `/`, parse a `/x/y/` instruction (with the same escaping rules) and repeatedly substitute all `x` in the remaining code with `y`.
Taking some more inspiration from Jakube, for simplicity I'll just explain a 4x4 version of this:
```
/:/fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\:B:C:D:
```
We start by replacing those `:` with the stuff between the second and third `/`. This will end up being the code the rotates the subsequent rows. We get this:
```
/x/bff//f/\///b/\\fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbBfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbCfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbDfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb
```
The `f`, `b` and `x` are just shorthands for common strings, which we'll expand now. The `f` is for slashes, the `b` is for backslashes and the `x` is for `\//` which happens to come up quite a lot. The reason I'm using aliases for the single-character substrings `/` and `\` is that they'd have to be escaped in the first substitution instruction, so I'm actually saving quite a lot of bytes by not needing all those backslashes. Here's what we get after `x`, `f` and `b` have been filled in:
```
ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\B/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\C/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\D/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\
```
Very readable.
So the first line is just printed verbatim. Then we get to the funky part that rotates all further rows. It actually consists of four different instructions. One thing to notice is that I've escaped all occurrences of `A` within these instructions. The reason for this is that it allows me to distinguish `A`s within the instructions from `A`s in the remaining rows, which need to be processed differently.
```
/\/\A/\//
```
This matches `/A` and replaces it with `/`, removing the `A`. Note that this substring only appears at the front of each `ABCD`, so this drops the first character of all subsequent lines:
```
/
\//\A_\//
```
This matches a linefeed followed by a slash and replaces it with `A_/`. So this inserts an `A` at the end of each line, completing the rotation and also turns the linefeed into an underscore.
```
/_\//
\//
```
This matches `_/` and replaces it with a linefeed followed by a slash. The reason I need to make this detour via the underscore is the fact that /// applies each instruction repeatedly until the string no longer matches. That means you can never use an instruction of the form `/x/axb/` where `x`, `a` and `b` are arbitrary strings, because after the substitution `x` will always still match. In particular, this means we can't just insert something in front of a linefeed. We need to replace the linefeed in the process and the undo this replacement.
```
/\\\A/\\B/
```
This matches `\A` and replaces it with `\B`, so that the instructions after the remaining rows process the next character. After all four instructions have been processed the remaining string looks like this:
```
BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\C/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\D/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\
```
So now the first rotated row gets printed, and then the next set of instructions rotates the remaining rows by another cell and so on. After the last rotation, we have a few more instructions that we can ignore and then we end with the incomplete instruction:
```
/\\\B/\\
```
Incomplete instructions at the end are simply ignored and the program terminates.
[Answer]
# Emacs, 47 bytes
```
abcdefghijklmnopqrstuvwxyz^M
^P
<F3>
^K ^K ^Y ^Y
^P
^<space> ^F ^W ^E ^Y ^A
<F4>
^U 2 4 F4
```
Where `^P` means "Control P", etc. That's 47 bytes, since the F3 and F4 keys require two ASCII bytes.
After entering the starting input, it defines a keyboard macro to duplicate the line and move the first character to the end. It then runs the macro a further 24 times.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes
```
25..0|%{-join('Z'..'A')[$_..($_-25)]}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38hUT8@gRrVaNys/M09DPUpdT0/dUV0zWiVeT09DJV7XyFQztvb/fwA "PowerShell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØAṙJṢj⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=w5hB4bmZSuG5omrigbc&input=)
### How it works
```
ØAṙJṢj⁷ Main link. No arguments.
ØA Set argument and return value to "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
J Yield the indices of the argument, i.e., [1, ..., 26].
ṙ Rotate the alphabet 1, ..., 26 units to the left.
This generates all rotations, but not in the correct order.
Ṣ Sort the rotated alphabets.
j⁷ Join, separating by linefeeds.
```
[Answer]
## JavaScript (ES6), 56 bytes
```
_=>"ABCDEFGHIJKLMNOPQRSTUVWXYZ".replace(/./g,"$&$'$`\n")
```
Yes, that's right, half my code is the alphabet string literal. Best I could do without the literal is 81 bytes:
```
_=>[...Array(26)].map((_,i,a)=>a.map(_=>(i++%26+10).toString(36)).join``).join`
`
```
If you want a program rather than a function, then remove the `_=>` and wrap in `console.log()` for a cost of 10 bytes.
[Answer]
# C, ~~88~~ 64 bytes
Call `f()` without arguments.
```
f(i,j){for(i=j=0;i<26;putchar(j==26?j=0,i++,10:65+(i+j++)%26));}
```
[Try it on ideone](http://ideone.com/hWifIZ).
[Answer]
# [Piet](http://www.dangermouse.net/esoteric/piet.html), 247 bytes/190 codels
[![Tabula Recta in Piet](https://i.stack.imgur.com/PNk35.png)](https://i.stack.imgur.com/PNk35.png)
[Try it Online!](https://tio.run/#%23fZRLbxQxEITv/IoSSChC0LI9tsfmgJIoUTYIhRASRBCHeF6wJxKF/79U27t5XLBmLO/I/rqqu7236/nvZmPaeI@UEQz8DN/DTDAFtuhszO6Z4DN8gvcIDpDzsxPZjtPV0cWLCrJEPRxx8cnxAJNg3OOXEhEZKxMl8loexi9pKEdUtE8IHfoO3qmM4CutPtOA2cIvmA1QlHB/eHpZUZ@3qO6pKkbsjRoJWYHbjwPs87WqktvV9f1OV0N5RVVVuSCPsOmRzC@aIg9vVaFLsAEhNFRL1NHB5Z5cNVQgarRIVnM7dugqpC2WCf2CHNDNmDqkEcVrBirK1Ec@PKqKRAWWzCnKOSSn686qQZY1e3QOQ4exGh9H1YkfIi9F7P25OJGVnDZUT9TA2o1afTfpKa7ToHbGSc/SPg36ukG7wlLVW3nHd4@CDj7xbahElKUpr0oC0ztjyJiobVZJMWDK2hi0xrJGA6sosV9rrma@hzdbg1mbIcJXL4zLsyxfTEgGKcIZxAVd1kTZWPM/Ass@Kde/RfAnU9TPhipETdyQkCN6qwWaipJTj5g1b4k2I/KC4hQYtUW/y92V7Mu61XHdUANRLLp2MnuScYuqSiRnvSNERadRqJb8YDUcDa6/fbwWuZBB5v0vdw01agU97FiDOj3OnxqdCezh2BVxm0y6awtol19cyo28ivS3a4aJKCbcFd2Z68ySFZ7yGJntUEtZ9Kb7oFeSEWHfHCiBY09OjneoWSvoMXEb79eidrqgbbA4JTDzz26oqX2lkCHoXG/jtq8WohhO/2E8yrytOJ3@bxyfHWkPbDb/AA)
So, this took far longer than I had anticipated, and I have a few ideas on some other more efficient (more stack-friendly) approaches, but I finally got the dang thing working (and [fixed an interpreter bug](https://github.com/cincodenada/bertnase_npiet/commits/bugfix/pointer) and [added IDE features](https://github.com/cincodenada/PietCreator/commits/master) along the way), so here it is. Hardly the most byte-efficient language, but a hell of a lot of fun. Here's a larger view, and a trace showing the path taken. History up on my [GitHub](https://github.com/cincodenada/piet_projects).
[![Tabula Recta in Piet, large version](https://i.stack.imgur.com/BLKPF.png)](https://i.stack.imgur.com/BLKPF.png)
[![Tabula Recta run trace](https://i.stack.imgur.com/mEcOt.png)](https://i.stack.imgur.com/mEcOt.png)
As a stack-based language, it's far too convoluted to explain briefly, but here's a basic overview of what the various sections/loops do. All variable and function names are just for explanation, as there are no variables or functions in Piet.
* Initialization (upper-left): starts `line_counter` at 27, loads '@' as `cur_letter`, sets `letter_count` to 27
* Main loop (starting at dark purple, center top)
+ Decrements `letter_counter`
+ Branches to `reset_line` if zero (light cyan 2-block)
+ Rolls `cur_letter` to the top of the stack
+ Branches to `check_done` if `cur_letter > 'X'` (teal/red block, right side)
+ Increments `cur_letter` and outputs it (lower-right corner)
+ Branches to `reset_letter` if `cur_letter > 'Y'` (light green block, left)
+ Rolls `letter\_counter\_ back to top of stack, back to top of loop
* `reset_line` branch (big pink square):
+ Outputs newline character
+ Resets `letter_count` to 27
+ Continues back to top of main loop
* `check_done` branch (right half inside)
+ Rolls `line_counter` to top
+ Branches to end if zero
+ Decrements `line_counter` and rolls back to bottom of stack
+ Resumes where it left off, printing letter
* `reset_line` branch (left side, green block):
+ Resets `cur_letter` to '@'
+ Resumes where it left off, rolling/returning to top of loop
[Answer]
# Mathematica ~~68~~ 61 bytes
```
Column[""<>RotateLeft["A"~CharacterRange~"Z",#]&/@0~Range~25]
```
Thanks to...
@MartinEnder (7 bytes)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
*With thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis), who [suggested](https://codegolf.stackexchange.com/questions/75841/parity-of-a-permutation/75853#comment184427_75853) that MATL should incorporate modular indexing, and to [@Suever](https://codegolf.stackexchange.com/users/51939/suever), who had the [idea](https://codegolf.stackexchange.com/questions/82981/leyland-numbers/82995#comment202388_82995) of automatic pairwise operations.*
```
1Y2t&+Q)
```
[**Try it online!**](http://matl.tryitonline.net/#code=MVkydCYrUSk&input=)
```
1Y2 % Predefined literal: string 'AB...Z'
t % Push another copy of it
&+ % 2D array with all pairwise additions of ASCII code points from that string.
% Gives the 26×26 array [130 131... 155; 131 132... 146; ...; 155 156... 180]
Q % Add 1 to each element. First entry is now 131, etc
) % Index into string 'AB...Z'. Since it has length 26 and MATL uses modular
% indexing, 131 is the first entry (character 'A'), etc. Implicitly display
```
[Answer]
# Python 2, ~~75~~ ~~65~~ ~~61~~ 58 bytes
```
a='%c'*26%tuple(range(65,91))
for x in a:print a;a=a[1:]+x
```
Gets the alphabet with `map(chr,range(65,91))`, then manually applies the string shift operation.
*Thanks to @LeakyNun and @TheBikingViking for -4 bytes!*
*Thanks to @xnor for -3 bytes!*
[Answer]
# R, ~~47~~ ~~42~~ 41 bytes
```
write(rep(LETTERS,27)[-27*1:26],1,26,,'')
```
[Try it online!](https://tio.run/##K/r/v7wosyRVoyi1QMPHNSTENShYx8hcM1rXyFzL0MrILFbHUMfITEdHXV3z////AA "R – Try It Online")
Generates 27 alphabetes, removes 27-th letters and prints in 26 columns.
*Improvement inspired by* [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)'s [solution](https://codegolf.stackexchange.com/a/154518/65510).
[Answer]
# Javascript, ~~113~~ ~~96~~ ~~91~~ 76 bytes
A super-short version for running in the console:
```
l="ZABCDEFGHIJKLMNOPQRSTUVWXY";for(C=26;C--;console.log(l=l.slice(1)+l[0]));
```
# Javascript/HTML, ~~140~~ ~~123~~ ~~118~~ 105 bytes
A prettier version, with an HTML output that makes it easier for OP to copy and paste:
```
<script>l="ABCDEFGHIJKLMNOPQRSTUVWXYZ";for(C=26;C--;document.write(l+"<br>"),l=l.slice(1)+l[0]);</script>
```
**(EDIT: I should've just used the string A-Z instead of generating it)**
**(EDIT 2: Thanks to @Neil and @DanTheMan for their input (see comments))**
[Answer]
# Retina, ~~36~~ 31 bytes
**5 bytes thanks to Martin Ender.**
```
Z
{2`
$`
}T01`L`_L
\`.
$&$'$`¶
```
Leading linefeed is significant.
[Try it online!](http://retina.tryitonline.net/#code=CloKezJgCiRgCn1UMDFgTGBfTApcYC4KJCYkJyRgwrY&input=)
[Credits](https://codegolf.stackexchange.com/a/85123/48934).
[Answer]
# [Sesos](https://github.com/DennisMitchell/sesos), ~~27~~ 25 bytes
```
0000000: 685902 ae7b33 764992 c45d9b 397360 8fef1f 7bca72 hY..{3vI..].9s`...{.r
0000015: 3adc33 07
```
[Try it online!](http://sesos.tryitonline.net/#code=YWRkIDI2CmptcAogICAgam1wCiAgICAgICAgcndkIDEsIGFkZCAxLCByd2QgMSwgYWRkIDEsIGZ3ZCAyLCBzdWIgMQogICAgam56CiAgICByd2QgMiwgYWRkIDY0CiAgICBqbXAKICAgICAgICBmd2QgMiwgYWRkIDEsIHJ3ZCAyLCBzdWIgMQogICAgam56CiAgICBmd2QgMSwgc3ViIDEKam56CmZ3ZCAxCmptcAogICAgam1wCiAgICAgICAgcHV0LCBmd2QgMQogICAgam56CiAgICByd2QgMjcKICAgIGptcAogICAgICAgIHB1dCwgZndkIDEKICAgIGpuegogICAgYWRkIDEwLCBwdXQsIGdldCwgZndkIDEKICAgIGptcAogICAgICAgIHJ3ZCAxLCBhZGQgMSwgZndkIDEsIHN1YiAxCiAgICBqbnoKICAgIGZ3ZCAxCjsgam56IChpbXBsaWNpdCk&input=) Check *Debug* to see the generated SBIN code.†
### Sesos assembly
The binary file above has been generated by assembling the following SASM code.
```
add 26
jmp
jmp
rwd 1, add 1, rwd 1, add 1, fwd 2, sub 1
jnz
rwd 2, add 64
jmp
fwd 2, add 1, rwd 2, sub 1
jnz
fwd 1, sub 1
jnz
fwd 1
jmp
jmp
put, fwd 1
jnz
rwd 27
jmp
put, fwd 1
jnz
add 10, put, get, fwd 1
jmp
rwd 1, add 1, fwd 1, sub 1
jnz
fwd 1
; jnz (implicit)
```
### How it works
We start by initializing the tape to `ABCDEFGHIJKLMNOPQRSTUVWXYZ`. This is as follows.
Write **26** to a cell, leaving the tape in the following state.
```
v
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 0
```
As long as the cell under the data head is non-zero, we do the following.
Copy the number to the two cells to the left and add **64** to the leftmost copy.
```
v
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 90 26 0 0
```
Move the leftmost copy to the original location, then subtract **1** from the rightmost copy.
```
v
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 90 0
```
The process stops after **26** iterations, since the rightmost copy is **0** by then. We move a cell to the right, so the final state of the tape after the initialization is the following.
```
v
0 0 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
Now we're ready to generate the output, by repeating the following process until the cell under the data head is zero.
First, we print the character under the data head and move to the right, repeating this step until a cell with value **0** is found. After printing `ABCDEFGHIJKLMNOPQRSTUVWXYZ`, the tape looks as follows.
```
v
0 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
Now we move the data head **27** units to the left (back to the leading **0**) and repeat the print-move combination until a cell with value **0** is found. This prints nothing and leaves the tape as follows.
```
v
0 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
Now, we write **10** to the current cell, print the corresponding character (linefeed) and zero the cell with a call to `get` on empty input, leaving the tape unchanged.
Afterwards, we move the content of the cell to the right to the current cell, then move the data head to units to the right.
```
v
65 0 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
The next iteration is slightly different. The first printing step prints `BCDEFGHIJKLMNOPQRSTUVWXYZ`, leaving the tape as follows.
```
v
65 0 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
Now we move the data head **27** units to the left.
```
v
65 0 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
The subsequent printing loop prints `A` and leaves the tape as follows.
```
v
65 0 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
Once again, we print a linefeed, move the content of the cell to the right to the current cell, then move the data head to units to the right.
```
v
65 66 0 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0
```
After **24** more iterations, the final step of moving the data head to the right leaves the tape in the following state.
```
v
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0 0
```
The cell under the data head is now **0** and the program terminates.
---
† TIO uses a newer version of Sesos, which is backwards-compatible for SASM, but generates shorter SBIN code.
[Answer]
# Haskell, ~~56~~ ~~53~~ 52 Bytes
```
mapM(\x->putStrLn$init$[x..'Z']++['A'..x])['A'..'Z']
```
same length: (using a suggestion by @AndersKaseorg)
```
a=['A'..'Z']
mapM putStrLn[take 26$[x..'Z']++a|x<-a]
```
to do modular stuff you have to import Data.Char to get the chr function, ~~74~~ ~~59~~ 58 Bytes was the best I could get with that: (thanks to @nimi for suggesting the toEnum function)
```
a=[0..25]
mapM(\x->putStrLn[toEnum$65+(x+y)`mod`26|y<-a])a
```
This could probably be much shorter, but I don't know any Haskell golfing tricks.
*used mapM instead of mapM\_ (see @Lynn's comment)*
[Answer]
# R, 53 bytes
```
for(i in 1:26)cat(LETTERS[c(i:26,1:i-1)],"\n",sep="")
```
Here it is on an [online interpreter](http://www.r-fiddle.org/#/fiddle?id=OI53e9Np).
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~36~~, 10 bytes
```
¬AZ25ñÙx$p
```
[Try it online!](https://tio.run/##K/v//9Aaxygj08MbD8@sUCn4/x8A "V – Try It Online")
This uses the "Latin1" encoding.
Explanation:
```
¬AZ " Insert the alphabet
25ñ " 25 times...
Ù " Duplicate this line
x " Cut the first character
$p " Move to the end of the line and past the character we just cut
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~10~~ 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
(↑⍳∘⍴⌽¨⊂)⎕A
```
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20%28%u2191%u2373%u2218%u2374%u233D%A8%u2282%29%u2395A&run)
Requires `⎕IO←0` which is standard on many systems.
The generalized 7-char function is just `↑⍳∘⍴⌽¨⊂`:
`↑` make the following list of strings into a character table:
`⍳`the indices
`∘` of
`⍴` the length of the argument, i.e [1, 2, 3, ..., 26]
`⌽¨` each rotate
`⊂` the entire argument
With the argument of `⎕A` (uppercase alphabet) we get the desired result, but any argument can be fed to get the corresponding cipher:
```
f←↑⍳∘⍴⌽¨⊂
f'o+×'
o+×
+×o
×o+
```
In fact, even strings and numbers are allowed:
```
f'Alpha' 'Bravo' 'Charlie' 'Delta'
┌───────┬───────┬───────┬───────┐
│Alpha │Bravo │Charlie│Delta │
├───────┼───────┼───────┼───────┤
│Bravo │Charlie│Delta │Alpha │
├───────┼───────┼───────┼───────┤
│Charlie│Delta │Alpha │Bravo │
├───────┼───────┼───────┼───────┤
│Delta │Alpha │Bravo │Charlie│
└───────┴───────┴───────┴───────┘
f⍳8
0 1 2 3 4 5 6 7
1 2 3 4 5 6 7 0
2 3 4 5 6 7 0 1
3 4 5 6 7 0 1 2
4 5 6 7 0 1 2 3
5 6 7 0 1 2 3 4
6 7 0 1 2 3 4 5
7 0 1 2 3 4 5 6
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 222 bytes
```
(((()()()()){})<(((({}){}){}){})>)((((([[]]{}){}()){}))<>()){<>({}<>)<>{({}<(({}()))>[()])}{}<>([({})]<>{})<>(({}<>))<>({}[()])}{}<>(({}<>))<>{}{}{}<>{({}<(({}())[()]<{({}<<>({}<>)>[()])}{}{}((()()()()()){})>)>[()])}{}{}{}
```
[Try it online!](https://tio.run/##VU47CsAgDL2Ob@gNROg5xMEOhdLSoWvI2dM8pWJVNHk/sz31uJf9qqdZ8IW@IYrI3t9xEoiEnEtpQJchJhZ@i8bknbCg02GkHFCgpEJmWnGB0tPlaL5JNGBRacgcR11swPfdyHd@TN8H@5GiZrasLw "Brain-Flak – Try It Online")
I'm new to Brain-Flak, so maybe this can be golfed a lot, but at least it's a first try. It stores 27 full alphabets on the left stack, then moves the alphabets to the right and replaces every 27th letter by a newline.
My sourcecode is a bit confusing, but i will add it nevertheless.
```
(((()()()()){})
park 8 in third
<(((({}){}){}){})> push 64
)
((((([[]]{}){}()){}))<>()) push 26 twice on left and 27 on right
left stack: 64 letter, 26 letter count, 26 constant
right stack: 27 alphabet count
{ while alphabet count
<>
({}<>)<> push 26 back to right
{ while counter
(
{} park counter in third
<(({}()))> add next letter to stack
[()] decrement counter
)
}
{} pop 0 counter
<>([({})]<>{}) set Z back to A-1
<>(({}<>)) move 26 twice from right to left
<> go to right stack
({}[()]) decrement counter
}
{} pop 0
<>(({}<>)) push 26 twice on right stack
<>{}{}{} pop counter, @ and Z from left stack
<> go to right stack
{ while alphabet count
(
{} save alphabet count on third stack
<(
({}())[()] save constant on third stack and push lettercount 26 + 1 for lf
<
{ while lettercount
(
{} save lettercount on third stack
<
<>({}<>) pull letter from left to right
>
[()] decrement lettercount
)
}
{} pop 0
{} pop last letter
((()()()()()){}) push lf
>
)>
[()] decrement alphabet count
)
}
{}{}{} pop alphabet count, constant and lf
```
[Answer]
# C#, 98 bytes
I have tried to see if I can generate the letters shorter than just initializing them as a string, but it's not really possible. The letters are 26 bytes and this snippet alone
```
for(char a='A';a<'[';a++)
```
is 25 bytes. I think initializing them and then appending them with a+=a is a good solution, but with C# you are limited by the bytecount of functions like `Substring()` and `Console.WriteLine()`.
My attempt at 98 bytes:
```
var a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";a+=a;for(int i=0;i<26;i++)Console.WriteLine(a.Substring(i,26));
```
[Answer]
# Octave, 27 bytes
We're adding a row and a column vector, and Octave nicely expands the sigleton dimensions, no need for `bsxfun` (as you would need in Matlab).
```
[mod((v=0:25)+v',26)+65,'']
```
[Answer]
# q, 20 bytes
```
(til 26)rotate\:.Q.A
```
[Answer]
# Java, ~~190~~ ~~176~~ ~~172~~ 163 bytes
```
class C{public static void main(String[] a){int s=0;while(s<26){p(s,26);p(0,s++);p(-1,0);}}static void p(int s,int e){for(;s<e;s++)System.out.write(s<0?10:65+s);}}
```
[Answer]
# Bash, 66 bytes
```
A=`printf %c {A..Z}`
for i in {0..25};do echo ${A:$i}${A::$i};done
```
I create a full alphabet in `A`, then print 26 rotated versions of it by taking the characters beginning at `n` and appending those preceding position `n`.
] |
[Question]
[
## Challenge
Given two strings, work out if they both have exactly the same characters in them.
## Example
**Input**
>
> word, wrdo
>
>
>
This returns `true` because they are the same but just scrambled.
**Input**
>
> word, wwro
>
>
>
This returns `false`.
**Input**
>
> boat, toba
>
>
>
This returns `true`
## Rules
Here are the rules!
* Assume input will be at least 1 char long, and no longer than 8 chars.
* No special characters, only `a`–`z`
* All inputs can be assumed to be lowercase
## Test Cases
```
boat, boat = true
toab, boat = true
oabt, toab = true
a, aa = false
zzz, zzzzzzzz = false
zyyyzzzz, yyzzzzzy = true
sleepy, pyels = false
p,p = true
```
[Answer]
# Python, 32 bytes
```
f=lambda a,b,S=sorted:S(a)==S(b)
```
[Answer]
### Golfscript, 3 chars?
```
$$=
```
usage:
```
'boat'$'baot'$=
1
'toab'$'boat'$=
1
'oabt'$'toab'$=
1
'a'$'aa'$=
0
'zzz'$'zzzzzzzz'$=
0
'zyyyzzzz'$'yyzzzzzy'$=
1
'sleepy'$'pyels'$=
0
'p'$'p'$=
1
```
[Answer]
## J, 8
```
-:&(/:~)
```
Literaly, match (`-:`) on (`&`) sort up (`/:~`)
Sample use:
```
'boat' -:&(/:~) 'boat'
1
'toab' -:&(/:~) 'boat'
1
'oabt' -:&(/:~) 'toab'
1
'a' -:&(/:~) 'aa'
0
'zzz' -:&(/:~) 'zzzzzzzz'
0
'zyyyzzzz' -:&(/:~) 'yyzzzzzy'
1
'sleepy' -:&(/:~) 'pyels'
0
'p' -:&(/:~) 'p'
1
```
Where do the 64-bit integers come into play?
[Answer]
## Javascript, 192 157 152 147 125 bytes
Ok some of these languages are a lot more flexibile than I thought! Anyway this is the longer way I guess, but a different technique at least.
**Compressed**
Thanks to Peter and David for squeezing more chars out!
```
for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1}
```
Then do:
```
alert(b("hello")==b("elloh"));
```
**Expanded Code**
The compressed has had lots of changes, but this is the basic theory:
```
// Define dictionary of primes
a = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];
// Returns the unique ID of the word (order irrelevant)
function b(c) {
r = 1;
for (i = 0; i < c.length; i++)
r *= a[c[i].charCodeAt(0) - 97];
return r
}
alert(b("hello") == b("hlleo"));
```
[Answer]
# Golfscript, 8 bytes
This defines a function called `A`
```
{$\$=}:A
```
Test cases
```
;
'boat' 'boat' A
'toab' 'boat' A
'oabt' 'toab' A
'a' 'aa' A
'zzz' 'zzzzzzzz' A
'zyyyzzzz' 'yyzzzzzy' A
'sleepy' 'pyels' A
'p' 'p' A
```
[Answer]
# Haskell, 31 bytes
## function - 31
```
import List
f=(.sort).(==).sort
```
## program - 81 58 55
```
import List
g=sort`fmap`getLine
main=(`fmap`g).(==)=<<g
```
Usage:
```
$ runghc anagram.hs
boat
boat
True
$ runghc anagram.hs
toab
boat
True
$ runghc anagram.hs
a
aa
False
```
Kudos to [lambdabot](http://www.haskell.org/haskellwiki/Lambdabot) and its [pointfree refactoring](http://www.haskell.org/haskellwiki/Pointfree).
[Answer]
## C#, 129 chars
```
namespace System.Linq{class X{static void Main(string[]a){Console.Write(a[0].OrderBy(_=>_).SequenceEqual(a[1].OrderBy(_=>_)));}}}
```
Readable:
```
namespace System.Linq
{
class X
{
static void Main(string[] a)
{
Console.Write(a[0].OrderBy(_ => _)
.SequenceEqual(a[1].OrderBy(_ => _)));
}
}
}
```
[Answer]
# Ruby, 34 bytes
Using the IO scheme of Peter Taylors Perl solution:
```
p gets.chars.sort==gets.chars.sort
```
[Answer]
# C program, 118
```
t[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++;
for(i=27;--i&&t[i-1]==t[i+25];);puts(i?"false":"true");}
```
[Answer]
## Perl, 58 bytes
(complete program, unlike the other Perl answer which is only a function)
```
($c,$d)=map{[sort split//]}<>;print"@$c"eq"@$d"?true:false
```
## 49 as a function
```
sub f{($c,$d)=map{[sort split//]}<>;"@$c"eq"@$d"}
```
[Answer]
# Clojure - 23 chars
As an anonymous function:
```
#(apply = (map sort %))
```
Test case example:
```
(#(apply = (map sort %)) ["boat" "boat"])
=> true
```
[Answer]
**JavaScript**
Based on @zzzzBov's solution.
Comparison, 65 chars (40 without function)
```
function f(a,b){return a.split('').sort()==b.split('').sort()+""}
```
Comparator, 43 chars
```
function f(a){return a.split('').sort()+""}
```
[Answer]
# C++ (104 non-ws chars)
Based on counting sort. Note: Assumes strings of the same length, which seems to be implied (though not stated) by the question.
```
int u[123], i;
int a(char **c) {
for(; c[0][i]; ) {
u[c[0][i]]++;
u[c[1][i++]]--;
}
i=123;
while(i && !u[--i]);
return !i;
}
```
[Answer]
# APL, 2 chars
```
≡⍦
```
This is the [Multiset Match](http://wiki.nars2000.org/index.php/Multisets#Multiset_Match) function from [Nars2000](http://www.nars2000.org/), one of the leading-edge APL implementations. When applied to strings, it computes exactly the function required:
```
'elvis' ≡⍦ 'lives'
1
'alec guinness' ≡⍦ 'genuine class'
1
```
[Answer]
# [R](https://www.r-project.org/), 54 bytes
```
function(x,y,`~`=sort,`+`=utf8ToInt)identical(~+x,~+y)
```
[Try it online!](https://tio.run/##VYoxDsMgEAT7PIPKCNKniB@QPg8AOyAhIUDmLPko@Do@g5tsc7tzszX7fja7hxVcDNMhUaqq5hw3kEqoeQf7@sZPAO5@JoBbtZ@qOGQVyJud2BI1MDkOfxCAqJc/QPsyOu@gIGKhEByl4HgkImlUTVXr2@9quTNY9sYkvHw0PjPeTg "R – Try It Online")
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 112 bytes
```
;=dF;C=mB;=a 123W<96=a-a 1Id=d!E+"a"aE++"=a"a" 0";=w"+1a";C=lB;=bP:Wb;E++"=a"Ab+wAb=bGb 1Lb;=w"+~1a";Cl;=dT;CmOd
```
[Try it online!](https://tio.run/##rVlRU9tIEn62f8WgFLZky4kkuKs9C5kCFijqCGQhuTyAL8iSDKqVZZ8kwwIhfz3X3TMjjWyRu9wtD5Y1093z9Tc93T0mGNwGwfc3cRokyzDayYswnr@9G7XVkSSe1IaC4nERrQhlcXpbGyriGZcJo2mcRixJWDJPb@mjXY5@PPv0ntnV6@XHC@ZUr//Yu2Db1evR2QH7pXq9@MTsSvjo9FKRPft0qoh@Onu/d/l3PTeYjh8d9s3@i1HO7l3CsnwyuPMz1jMqBVUKsJYmRiO2Xc2dHX7GyRQmyaOvDL/v7KzI4DIkg26CTJIYKFiT2T8/PyUh/NglJ4fomwLk4pgLgL6C9d5PlpFhXKVjo90mP2BXrsbehXZ4fqR/d73wyD3wZvuu5wNtW593/vZXzx/A95PQCzcO@5qv@Yf9vubBU2OW5noPWt/2NVBKQGnyYfh54gqBvUn/YW/iTY4nzD6dkOQ3Ek1gmY/uwew8/G7AsprLkfQASuTPmIeY3HYbgC/8LI90gz23W3FasNhtt2CUnDBZb7pMAxgh5QDei9nCzBfplTP2ni3TegEbrRjMkTw8LRx49w7Nxwv2cBcXUb7wg6jdgu9JpMM4qOschsm06@I6vZ5eZ@z55WqsG8M3mkFQWvGU6SVaj3XfdA3GTcjRDRi9TmG43@cjgLMVJXmkDrxwOMFdFPzOpvOMpcvZJMpygYfpcR7Gt3EhrcLq6I5tlh7xZ4/ZFuuznkDe7xtswLpWF5ZApLHBsqhYZimTYcfVKPLcVQz3fhb7kySSKABEMn@IMj2A9SQQ9vUrk@ACeguIiC9dQ9ATN7gee7YJe@SVwyvo8CCLgAeRNFwudNxSJjgdMHhbB8zTSs6tcRjX3W6FSevyTQNl8KAExcAIpCH4DsgWfl6w4i4CY35WgLDYgJ5kFDc0MNATCVY5na@ChU/boI1uVWQQfAzdIp6nABsj1hoDtEAyki8XCyTckFElR1T61fgD2hWy0YYM5UUKcQwpESNXIOesfOyWeYMPHOEApschpkWEKYOMMip3VUfcCNVPknmgb1umbaCDOFw6QQ6myyTxs0fV0Wp/LpTt@dAtkdGCQn@ZrmjTEjYuIZJCk6d7h/sHN79tnP56/k3xWLU7iRsNO@uGN2qWj08uX7FYRBmZ9NOQ/Wvpy1c0e68usbW@BGfguFuScdJABilv15XrMi@UK7NlilvkirzeK@a5LpMlnQCI7SIOGM1OltMrZ3sscPCd7lB@KAHkCzhXxVQHUfB/M0lCTSYeqmsmGlk1AKeiNMArJl@/JrfD7K26n@g8BuMu04psGWkQhOU4xiSMT31IITihYWhpFQnoJ/ouShvR8WV/Pk9gZlJn4FVfK7d@5FDv5z1SYU7WYCaIMf1TMULQFvMk0VWoJrNMKBH/A@R0DTKW4fd7H85MLMY80OD15Mq2LAvCCVyBV/mWx0/Rl4Lhw1ViVPEWGYA3Ez8c@tzybFnTMcVhWccHfTr8sQUCRyenhz02hezotsrQFuthHg78hZlEKbUACley8@Kcwbl7jYxVRSxOWNuw4ugxNRNQjHeICxeqSoyTZd4IZouVHSCS4nGVQpCmeIzL5A9xEdzpPWBmrVEDjpj4C7BQdfe6Q4arcAEPCcVWD9Kw0SGnhHnRbNZC1nCpDFcS1NEWGdYuamqvxsZzFWbQQVFy5wtfwMJ12xlkPN3oWH9M8a@S/ACSYJVzdBsVCfSjeof2soM7hDUyjFPDjae6TvuJHUFwlyEWE@LUMPg2e5bbiBUeBvUBfL1Dvh5vHTEbCEJciRdJErmzQrlf@cPly5mDagY1VYpLmRuQwWiA@PMW80WU6srCppZp1CsAKm/GSyXEo@dY27/QuOgudN6STAF6iE5BDwcha2KDB@LQPNAbrgFLy/DSYZD1PeqF8MSCpCHoBju0FlGNFnoec9SmpaKx8uQ38CT6A/o4PO1rfm7Udp2uHRuYydYET9fCA1ZJ6rwo4r92h6JRbAjkMvOJCqSdUV@sYw0yZBEajbaNqrNcS4dS9ZK6Q30zR8X6YVhXBjqh91HXhUxqaJWonMDyEvmpMPtaCRM1S90BkVsEC@cVC3gw@M0HSeP7WaOOdTp0VxsMUHTM@9xr6rdbEtbm214OeHR4M5g8apkCf1nkcvfLmMBmT@D5traJg8ao6Je4KZ1CWsXMjRGo7CLvult1e/x@jNJwP2DSuMONY59MZ4bvE0nhMCYDT5LhGM0RHfiFfIju1O5XbBryO9oyoGs16VmIVCL8Gqz5r7iPLX0dL1fqVZvYwMJqFW/gobfGA9/@JhZmDa71SMZTjZAClCqdEqnXvYbLIAq5gwHZE0RRZV2NB85oUUsS735IzLtmYjZ/qLTZrPRPYrPmEL9i0JijeukK2jnrHhvYJcskC9TbcBwHNhxFWxV2flJ6B7JoTdbzUJTWHcoRS1JORDsjS3DtGNTV9Dziv716IGiSXIGrBOVhrETwHW8Wd1EWdXOWzqHVjpMiTtmD/wi8sXAOd9ciuo0y0FnM0ygtYh8vG3Dg5@whYnf@fQSCwhCKF2zmp0sIn8e3OIreTZBxoIKYyJdJgT8u0OJlXpQiA1VGLrlCmapXiqyYR3uvS1qvAynFdmpSFt3j/QRL6CN4nYZJFLKbCvZNaeUZv/H@TVmkcmaExgYD@W6QeEuI9hToL2XnsUPBulIfMenV8qJXz4q7TD38O@oxQNWh@OWvw7jALqv1kzRoMiUbog2La8rK7PBygbIbHhQlpVkawaHE0JqH8yGbRbNggWGWstHN7v/ryuhPcGUkXdlo8MUTvghXdl9nn6/aABmnd1lNwCklHFlnN5pwVi@lezLzqAZKeJ0q/aEvTbVhV9UUqaTU//rf6IscpJgp9d3uUJWudcOrsl6VdevTP33fkS1wdeFBuVbt0lOmQpJBi2Ovpq2kSdRAiX6/VOOQP4N7/NcxtR@teccaWpyTenOPoor@rjPcUmg55jcLT2nE@moBWr9KpeJ@YpZnYavW915yoleMuqslz2kqeVtG2Qc4pfY2Df6HhgiB4RO3IijvCGU7pPZGDniIq/ZtbJKoQeDxzyfpQRJ9cRJg9TCa@pAkwTPZiMYpTMYh/dbkBwWUqe5m0MXWFEcM9splF42VNRC6QfF7w8yPU@xpmZ/dBiYZ7fXg@72Bv2rRNRT/kaRbhKZ@23v5/vQ0Dx/aD0/h/Onf "C (gcc) – Try It Online")
Knight doesn't have arrays. It does have strings, but it only allows a subset of valid ASCII character codes. So I emulated an array by constructing strings that looks like `"=a{charcode} 0"` and evaling it.
Knight also has blocks. A block works like a niladic function, which can change its behavior depending on global variables. This code uses two blocks: `m` loops over all 26 variables `a97 - a122` initializing or testing something, and `l` handles the part of taking input and iterating over its chars to count occurrences.
```
; = d F d = False
; C = m B define and run block m:
; = a 123 a = 123
: W < 96 = a - a 1 while 96 < (a = a - 1):
I d if d:
= d ! E + "a" a d = ! eval("a" + a)
E + + "=a" a " 0" else: eval("=a" + a + " 0") (aNN = 0)
i.e. d is false on start, so initialize all of a97..a122 to 0
; = w "+1a" w = "+1a" (which is necessary to run l)
; C = l B define and run block l:
; = b P b = one line of input
: W b while b is not empty:
; E + eval(concatenation of
+ "=a" A b "=aNN"
+ w A b w+"NN") (aNN = 1 + aNN)
(w = "+~1a" changes this to aNN = -1 + aNN)
: = b G b 1 L b b = b[1:length(b)]
i.e. count occurrences of chars in the first line
; = w "+~1a" w = "+~1a"
; C l run block l i.e. count negative occurrences in the second line
; = d T d = True
; C m run block m
for each of a122..a97, check if aNN is zero
if true, keep checking; otherwise do useless thing
: O d print d
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes
```
{I{Q
```
[Try it online!](http://05ab1e.tryitonline.net/#code=e0l7UQ&input=d29yZAp3ZHJv)
This took a while because of input difficulties. Golfed down due to pop.
Explanation:
```
{I{Q Original code
{ Takes first input e.g. word and sorts -> 'dorw'
I Takes second input e.g. 'wrdo'
{ Sorts second input -> 'dorw'
Q Compare if sorted 1 = sorted 2, then print result. 'dorw' = 'dorw', so prints 1.
```
[Answer]
## PHP (command line, 87 characters)
```
function d($s){
return array_count_values(str_split($s));
}
echo d($argv[1]) == d($argv[2]);
```
[Answer]
# Javascript
A (very) slightly shorter version of @zzzzBov's solution, that uses `.join()` instead of String boxing:
```
function a(b,c){return b.split('').sort().join()==c.split('').sort().join()}
alert(a('abc','bca')); //true
```
Similarly:
```
function a(b){return b.split('').sort().join()}
alert(a('abc')==a('bca')); //true
```
[Answer]
**Clojure REPL 41 chars**
```
(= (sort (read-line)) (sort (read-line)))
```
[Answer]
# Java
(everyone's favorite language apparently!)
173 chars:
```
import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}
```
(Doesn't print newline char to save 2 chars from println)
Compile and run:
```
javac g.java
java -cp . g abcdef fedcba
true
```
Love to see a shorter one...
[Answer]
# sed, 45 chars
It's even possible in my favourite - `sed`! **Just one regular expression to solve the anagram**! Just keep removing the corresponding letters:
```
:
s/(.)(.*,.*)\1/\2/
t
/\w/{i\false
d}
i\true
```
(to be invoked with `-nE`)
# Perl, 48
```
1while s/(.)(.*,.*)\1/\2/;$_=/\w/?"false":"true"
```
To be invoked with `-p`.
# Perl function, 39
```
sub f{$,while s/(.)(.*,.*)\1/\2/;!/\w/}
```
[Answer]
# Perl, 62 bytes
This function takes the strings as arguments and returns true or false.
```
sub f{my@a;for$.(1,-1){$a[ord]+=$.for split//,pop}!grep{$_}@a}
```
Stores the ASCII values in an array and checks if it evens out. Increments for the first word and decrements for the second word.
[Answer]
## Python 3, ~~107~~ ~~97~~ ~~76~~ 64
```
s=sorted;a,b=input().split(', ')
print(str(s(a)==s(b)).lower())
```
Obviously this can be shortened if we don't take the OP's wording literally and lowercase "true" and "false"...
[Answer]
# Python, 32 bytes
```
p=sorted
f=lambda a,b:p(a)==p(b)
```
[Answer]
# Bash, 88 characters
```
diff <(grep -o .<<<$1|sort) <(grep -o .<<<$2|sort)>/dev/null && echo true || echo false
```
[Answer]
## Scala in REPL (32)
```
readLine.sorted==readLine.sorted
```
## Scala function (43)
```
def f(a:String,b:String)=a.sorted==b.sorted
```
## Scala program (61)
```
object A extends App{println(args(0).sorted==args(1).sorted)}
```
These leverage a neat feature of Scala whereby a String can also be treated as a sequence of characters (`Seq`), with all the operations on `Seq` being available.
[Answer]
# APL - 13 chars
```
{(⍺[⍋⍺])≡⍵[⍋⍵]}
```
Call like this:
```
'boat' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'baot'
1
'baot' {(⍺[⍋⍺])≡⍵[⍋⍵]} 'boat'
1
(,'a') {(⍺[⍋⍺])≡⍵[⍋⍵]} 'aa'
0
```
In the last example, `'a'` represents a single character, and the prefix `,` will convert it into a string.
[Answer]
# Java (134 bytes)
```
int[][]c=new int[2][26];
for(int i=0;i<2;i++)for(byte a:args[i].getBytes())c[i][a-97]++;
System.out.print(Arrays.equals(c[0],c[1]));`
```
This makes an array to count the number of times each letter appears, and then compares the arrays to check if they are equal.
[Answer]
## Perl, 77 75 chars
The I/O of the problem aren't well specified; this reads two lines from stdin and outputs **true** or **false** to stdout.
```
sub p{join'',sort split'',$a}$a=<>;$x=p;$a=<>;print$x eq p()?"true":"false"
```
(Thanks to Tim for 77 -> 75)
] |
[Question]
[
The challenge is actually extremely simple. Pick 5 ***distinct*** letters (you can just pick the 5 that allow you the shortest code if you like) and output them to the console. However, the twist is that they must be from the following list:
```
AAA BBBB CCCC DDDD EEEEE FFFFF GGG H H
A A B B C D D E F G H H
AAAAA BBBB C D D EEEE FFFF G GG HHHHH
A A B B C D D E F G G H H
A A BBBB CCCC DDDD EEEEE F GGG H H
IIIII J K K L M M N N OOO
I J K K L MM MM NN N O O
I J KKK L M M M N N N O O
I J J K K L M M N NN O O
IIIII JJJ K K LLLLL M M N N OOO
PPPP QQQ RRRR SSSS TTTTT U U V V W W
P P Q Q R R S T U U V V W W
PPPP Q Q RRRR SSS T U U V V W W
P Q QQ R R S T U U V V W W W
P QQQQ R R SSSS T UUU V W W
X X Y Y ZZZZZ
X X Y Y Z
X Y Z
X X Y Z
X X Y ZZZZZ
```
# Additional Rules:
* 5 of the same letter is not allowed, no repeat choices.
* Each letter must use the capital of itself as the ascii-character to draw it.
* Each letter output must be on the "same line" and have 5 spaces between each letter.
* You may choose *any* 5 letters that you want, this will allow you to reuse some code and lower your byte count. Figuring out which letters will allow you to do this most efficiently is part of the challenge.
* Trailing spaces are acceptable.
* A single trailing newline is acceptable, no more than one trailing newline though.
* This is code-golf, lowest byte-count wins.
# Examples:
A B C D E
```
AAA BBBB CCCC DDDD EEEEE
A A B B C D D E
AAAAA BBBB C D D EEEE
A A B B C D D E
A A BBBB CCCC DDDD EEEEE
```
E F L I P
```
EEEEE FFFFF L IIIII PPPP
E F L I P P
EEEE FFFF L I PPPP
E F L I P
EEEEE F LLLLL IIIII P
```
C R A Z Y
```
CCCC RRRR AAA ZZZZZ Y Y
C R R A A Z Y Y
C RRRR AAAAA Z Y
C R R A A Z Y
CCCC R R A A ZZZZZ Y
```
Don't be afraid to submit more than one answer with different letters or different strategies each time, this can be accomplished various different ways.
[Answer]
## [Charcoal](http://github.com/somebody1234/Charcoal), ~~51~~ 49 bytes (ECXKI)
```
G←⁵↓³→⁴EM⁷→G↑²↗²→⁴CM⁶→GH↘↗³XM⁶→GH↓→↗³KM⁸→PTIII‖O↓
```
Outputs
```
EEEEE CCCC X X K K IIIII
E C X X K K I
EEEE C X KKK I
E C X X K K I
EEEEE CCCC X X K K IIIII
```
[Try it online!](http://charcoal.tryitonline.net/#code=77yn4oaQ4oG14oaTwrPihpLigbRF77yt4oG34oaS77yn4oaRwrLihpfCsuKGkuKBtEPvvK3igbbihpLvvKfvvKjihpjihpfCs1jvvK3igbbihpLvvKfvvKjihpPihpLihpfCs0vvvK3igbjihpLvvLBUSUlJ4oCW77yv4oaT&input=)
Using characters that are vertically symmetrical, draws the top halves and then reflects. Most of these make use of Polygon (`G`) and PolygonHollow (`GH`) to draw a series of connected line segments with a particular character. `I` can more easily be done with MultiPrint (`P`), using `T` as the direction.
Note: PolygonHollow just draws the segments specified, without completing the polygon or filling it. Polygon will complete and fill (not what we want) **if** the polygon can be completed with a simple line in one of the eight cardinal or intercardinal directions. Otherwise, it behaves like PolygonHollow, for a savings of one byte.
The order of characters was chosen to require only horizontal moves from the endpoint of one to the start of the next. Here's how the cursor proceeds:
[![Cursor movement, drawing top halves of ECXKI](https://i.stack.imgur.com/HGbhf.png)](https://i.stack.imgur.com/HGbhf.png)
[Answer]
## PowerShell v2+, ~~138~~ ~~128~~ ~~114~~ ~~112~~ ~~106~~ 105 bytes (LICTD)
```
"L1 IIIII1 CCCC1TTTTT1DDDD
$("L11 I1 C11 T1 D D
"*3)LLLLL1IIIII1 CCCC1 T1 DDDD"-replace1,' '
```
The idea is to maximize the spaces between the letters so we can get repeated compressions.
Borrows the middle-row deduplication trick from [Florent's answer](https://codegolf.stackexchange.com/a/99918/42963). Saved 6 bytes thanks to [Ben Owen](https://codegolf.stackexchange.com/users/56849/ben-owen) by using string multiplication for the middle three rows, and an additional byte thanks to [Matt](https://codegolf.stackexchange.com/users/52023/matt).
Output is like the following at 227 bytes, for a 53.7% reduction --
```
PS C:\Tools\Scripts\golfing> .\5-favorite-letters.ps1
L IIIII CCCC TTTTT DDDD
L I C T D D
L I C T D D
L I C T D D
LLLLL IIIII CCCC T DDDD
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ 40 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
N.B. I have a [39 byte answer](https://codegolf.stackexchange.com/a/160235/53748) too.
### LICTE
```
141D+“ȷɓSɠ’“ðƁ ƥ“JrŀṘ’jḃ11“LICTE”K¤żⱮŒṙY
```
**[TryItOnline!](https://tio.run/##AVAAr/9qZWxsef//4oCcPTvigbvKi8KuxrJc4oG4ZMKwNcShJFPGsiHEl8mg4bqIdnLigJnhuIMxM3M54oCcxqzDn8K7S8Kkxbzisa7FkuG5mVn//w "Jelly – Try It Online")**
### Idea
Use a run length decode with letters that have as similar middle as possible with only one run length of each "pixel value" per row per letter.
Put a flat start like "L" to avoid different run length decode values for the rows.
Place the one different letter (could not find 5) of the three middle rows at the end so the smallest difference may be added arithmetically.
Output wanted; the run lengths; and these converted from base 11:
```
L, , I, , C, , T, , E value
-------------------------
L IIIII CCCC TTTTT EEEEE 1, 9, 5, 6, 4, 5, 5, 5, 5 399633415
L I C T E 1,11, 1, 7, 1,11, 1, 7, 1 431646160+1
L I C T EEEE 1,11, 1, 7, 1,11, 1, 7, 4 431646160+4
L I C T E 1,11, 1, 7, 1,11, 1, 7, 1 431646160+1
LLLLL IIIII CCCC T EEEEE 5, 5, 5, 6, 4, 7, 1, 7, 5 1179122455
```
The three values `399633415`, `431646160`, and `1179122455` in base `250` as Jelly code page indices are then `ðƁ ƥ`, `ȷɓSɠ`, and `JrŀṘ` which can be used to encapsulate the run-length information.
### The code
```
141D+“ȷɓSɠ’“ðƁ ƥ“JrŀṘ’jḃ11“LICTE”K¤żⱮŒṙY - Main link
141D - 141 as a decimal list: [1, 4, 1]
“ȷɓSɠ’ - 431646160
+ - add: [431646161, 431646164, 431646161]
“ðƁ ƥ“JrŀṘ’ - list [399633415,1179122455]
j - join: [399633415, 431646161, 431646164, 431646161, 1179122455]
ḃ11 - convert to bijective base 11: [[1, 9, 5, 6, 4, 5, 5, 5, 5], [1, 11, 1, 7, 1, 11, 1, 7, 1], [1, 11, 1, 7, 1, 11, 1, 7, 4], [1, 11, 1, 7, 1, 11, 1, 7, 1], [5, 5, 5, 6, 4, 7, 1, 7, 5]]
¤ - nilad followed by link(s) as a nilad:
“LICTE” - list of characters "LICTE"
K - join with spaces "L I C T E"
Ɱ - map across (the lists of numbers) applying:
ż - zip e.g. [['L',1],[' ',9],['I',5],[' ',6],['C',4],[' ',5],['T',5],[' ',5],['E',5]]
Œṙ - run-length decode e.g. "L IIIII CCCC TTTTT EEEEE"
Y - join with line feeds
```
[Answer]
# PHP, ~~107~~ ~~104~~ ~~102~~ ~~94~~ 86 bytes
Ok I'm confident I have the smallest possible source with this method now. I wrote a script to generate and then gzip every possible combination of five letters. There are two solutions that match for the shortest compressed -- LODIC and LDOIC. I'm going with the former because it's more fun to say.
Source:
```
<?=gzinflate(base64_decode('81GAA39/fwjDBQggLE8QgDCdgYDLB6EYioGqoRisHkrTSCUIEOtWAA'));
```
Output:
```
% php foo.php
L OOO DDDD IIIII CCCC
L O O D D I C
L O O D D I C
L O O D D I C
LLLLL OOO DDDD IIIII CCCC
```
[Answer]
# JavaScript, ~~110~~ 109 bytes (CLOUD)
```
` CCCC5L9 OOO6U3U5DDDD
${x=`C9L9O3O5U3U5D3D
`,x+x+x} CCCC5LLLLL6OOO7UUU6DDDD`.replace(/\d/g,c=>" ".repeat(c))
```
```
console.log(
` CCCC5L9 OOO6U3U5DDDD
${x=`C9L9O3O5U3U5D3D
`,x+x+x} CCCC5LLLLL6OOO7UUU6DDDD`.replace(/\d/g,c=>" ".repeat(c))
)
```
Output is 227 bytes:
```
CCCC L OOO U U DDDD
C L O O U U D D
C L O O U U D D
C L O O U U D D
CCCC LLLLL OOO UUU DDDD
```
[Answer]
# ES6 (Javascript), ~~194~~, 181 bytes (IGOLF/ANY)
This one is long, and is not really optimized (not yet at least), but can be modified to print any particular message, by only changing the bitmap data.
*EDIT:* Replaced inner *reduce* with *map*, use bit shift for padding
**Golfed**
```
[0x1f73a1f,0x484610,0x49c61e,0x48c610,0x1f73bf0].map(r=>[0,1,2,3,4].map(p=>('0000'+(r>>(20-p*5)<<5).toString(2)).substr(-10).replace(/(1|0)/g,b=>' IGOLF'[(p+1)*b])).join``).join`\n`
```
**Demo**
```
[0x1f73a1f,0x484610,0x49c61e,0x48c610,0x1f73bf0].map(r=>[0,1,2,3,4].map(p=>('0000'+(r>>(20-p*5)<<5).toString(2)).substr(-10).replace(/(1|0)/g,b=>' IGOLF'[(p+1)*b])).join``).join`\n`
IIIII GGG OOO L FFFFF
I G O O L F
I G GG O O L FFFF
I G G O O L F
IIIII GGG OOO LLLLL F
```
**Theory**
Take a letter:
```
IIIII
I
I
I
IIIII
```
convert it to binary matrix (bitmap)
```
11111
00100
00100
00100
11111
```
do the same for other 4 letters, scan a line, by taking "top" 5 bits off each
11111 01110 01110 10000 11111
convert to a hexadecimal string (should be using base36 or even printable ASCII here)
0x1f73a1f
apply the same algorithm to other 4 lines, to get the bitmap.
Render in the reverse order.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 44 bytes
This was a fun one.
I feel like I need to come back and try and golf it some more when I have time.
Uses [CP-1252](http://www.cp1252.com) encoding.
Inspired by *carusocomputing's* [answer](https://codegolf.stackexchange.com/a/99955/47066).
**ECOIH**
```
‘ÓÑOIHH‘SðýJ3×S•Td<UÕ‘áÓ?¢tWvkÔÚ•S)øü×J3äû»
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCYw5PDkU9JSEjigJhTw7DDvUozw5dT4oCiVGQ8VcOV4oCYw6HDkz_DgsKidFd2a8OUw5rigKJTKcO4w7zDl0ozw6TDu8K7&input=)
**Explanation**
`‘ÓÑOIHH‘` pushes the string `"ECOOIHH"`.
`SðýJ3×S` joins the string by spaces, repeats it thrice and converts it to a list.
The resulting list is `['E', ' ', 'C', ' ', 'O', ' ', 'O', ' ', 'I', ' ', 'H', ' ', 'H', 'E', ' ', 'C', ' ', 'O', ' ', 'O', ' ', 'I', ' ', 'H', ' ', 'H', 'E', ' ', 'C', ' ', 'O', ' ', 'O', ' ', 'I', ' ', 'H', ' ', 'H']`.
`•Td<UÕ‘áÓ?¢tWvkÔÚ•` pushes the number `564631055513119191317171314619131717500`.
`S)ø` zips the list and the number together.
`ü×J` does pairwise string repetition and joins them together.
The result is the string `EEEEE CCCC OOO IIIII H HE C O O I H HEEEE C O O I HHHHH`.
`3äû»`splits that into 3 pieces, adds the first and second piece in reverse order and joins by newlines.
[Answer]
# JavaScript (ES6), 96 bytes (DIOCL)
```
`${x="DDDD6IIIII6OOO7CCCC5L"}
${y=`D3D7I7O3O5C9L
`,y+y+y+x}LLLL`.replace(/\d/g,d=>" ".repeat(d))
```
The idea here is to not only make the middle three lines identical, but also make the first line nearly identical to the last. Since there are only 4 letters that perfectly fit this description `CDIO`, `L` is the next best option, as it only requires 4 added characters at the end of the string.
As with [Florent's answer](https://codegolf.stackexchange.com/a/99918/42545), this is a snippet that returns the result. Add 3 bytes if it needs to be a function.
### Test snippet
```
console.log(`${x="DDDD6IIIII6OOO7CCCC5L"}
${y=`D3D7I7O3O5C9L
`,y+y+y+x}LLLL`.replace(/\d/g,d=>" ".repeat(d)))
```
[Answer]
## Bash+coreutils with figlet, 55440 solutions, 112 106 bytes each
```
set H E L P D;for l;do figlet -f banner $l|sed "s/.//3;s/.//5;s/#/$l/g;2d;5d">$l;done;paste $@|expand -t10
```
**Output:**
```
H H EEEEE L PPPP DDDD
H H E L P P D D
HHHHH EEEE L PPPP D D
H H E L P D D
H H EEEEE LLLLL P DDDD
```
Hey, we already have a [program](http://www.figlet.org/) for ASCII art! The *banner* font almost does the job, except it outputs 7x7 letters. Hmm, let's just remove the 3rd and 5th columns, and the 2nd and 5th lines, and see what it gives...
It turns out that many letters will be output the required way, namely, B D E F H J L P T U Z.
It suffices to replace the arguments of the first *set* command with any combination of those letters to still obtain a correct result! Hence, this gives us 11\*10\*9\*8\*7=55440 solutions, each of those being 106 bytes long.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~102~~ ~~90~~ ~~89~~ 69 bytes (EOIXC)
```
•Cv¶ÉH&9;´ß{ø‰¿šq3d$µ_©Û¶«K>Ò±sÒ9ÍÊC4ÊÚúNÏŒº9¨gÚSÞ•34B2ð:2ôvy`×}J3äû»
```
[Try it online!](http://05ab1e.tryitonline.net/#code=4oCiQ3bCtsOJSCY5O8K0w597w7jigLDCv8WhcTNkJMK1X8Kpw5vCtsKrSz7DksKxc8OSOcONw4pDNMOKw5rDuk7Dj8WSwro5wqhnw5pTw57igKIzNEIyw7A6MsO0dnlgw5d9SjPDpMO7wrs&input=)
## Output (230 bytes):
```
EEEEE OOOO IIIII X X CCCC
E O O I X X C
EEEE O O I X C
E O O I X X C
EEEEE OOOO IIIII X X CCCC
```
>
> 69 / 230 = 70% Compression
>
>
>
## Explanation:
The theory was to pick vertically symmetrical letters, then encode the first 3 lines an palindromize them. Basically, I encoded as {#} of {Letter} in 2 byte pairs. I'm sure there's a better way to do this.
```
•Cv¶ÉH&9;´ß{ø‰¿šq3d$µ_©Û¶«K>Ò±sÒ9ÍÊC4ÊÚîòvÅr葾)jM•34B
<decodes to>
"E5 6O4 5I5 5X1 3X1 6C4E1 9O1 4O1 6I1 8X1 1X1 6C1 4E4 6O1 4O1 6I1 9X1 7C1 4"
2ô # Split into encoded pairs.
vy } # Loop through each letter and number pair.
`× # Add the letter X number of times.
J # Join together.
3ä # Split into 3 parts length.
û # Palindromize.
» # Print separated by newlines.
```
-20 bytes thanks to Emigna, I'll be in the chat to ask some questions soon ;).
[Answer]
# Vim, ~~116 bytes~~ 99 bytes
### ELITC
Golfed it under 100 with the help of @DrMcMoylex.
```
9i59Yo191919171
E L I T CPqqjx:%s/\d/\=repeat('"',submatch(0))
q8@q3bi Y7w.PP4rE{wl4r 22wl.2x
```
This contains unprintable characters, so I've added them in below (Vim style), so you can see them.
```
9i5^[9^AYo191919171
E L I T C^[Pqqjx:%s/\d/\=repeat('^R"',submatch(0))
q8@q3bi ^[Y7w.PP4rE{wl4r 22wl.2x
```
[TryItOnline!](http://v.tryitonline.net/#code=OWk1GzkBWW8xOTE5MTkxNzEKRSBMIEkgVCBDG1BxcWp4OiVzL1xkL1w9cmVwZWF0KCcSIicsc3VibWF0Y2goMCkpCnE4QHEzYmkgIBtZN3cuUFA0ckV7d2w0ciAyMndsLjJ4&input=)
It basically uses the same run-length decode that the jelly answer does. I used letters where I could (hopefully) repeat the top on the bottom, and the middles would all 3 be the same. Once the tops, bottoms, and middles are created I edit the characters to make them correct:
1. Add two spaces to the I (more on that below)
2. Add two spaces to the T
3. Add the bar of the E
4. Remove the top of the L
5. Remove the bottom of the T (and delete the 2 spaces)
I have to add two spaces to the I, because I didn't allow two digit numbers (so I wouldn't need a separator. This leads to a 9 space run where I need 11.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 49 bytes
```
5:lyI&(g84*t0*ytP+g73*yy!qy5XyPl5LY(90*yy!P12-&hc
```
[Try it online!](http://matl.tryitonline.net/#code=NTpseUkmKGc4NCp0MCp5dFArZzczKnl5IXF5NVh5UGw1TFkoOTAqeXkhUDEyLSZoYw&input=)
This produces the letters `TIHZN`:
```
TTTTT IIIII H H ZZZZZ N N
T I H H Z NN N
T I HHHHH Z N N N
T I H H Z N NN
T IIIII H H ZZZZZ N N
```
### Explanation
`T` is relatively easy to build from scratch. `I` can be obtained essentially as `T` plus its vertical reflection. `H` is `I` transposed. `N` is `Z` transposed and vertically reflected.
```
5: % Push [1 2 3 4 5]
lyI&( % Write [1 ;2; 3; 4 ;5] in the third column, filling with zeros.
% This gives the shape of the 'T'
g84* % Change nonzeros into 84 (ASCII for 'T'). Zeros will be displayed
% as spaces
t0* % Duplicate and multiply by zeros. This gives the separator
y % Duplicate from below: pushes the 'T' again
tP+ % Duplicate, flip vertically, add. Gives the shape of the 'I'
g73* % Change nonzeros into 73 (ASCII for 'I')
yy % Duplicate separator and 'I' array
! % Transpose. Gives the shape of the 'H'
q % Subtract 1. Transformss 73 into 72 (ASCII for 'H'), and 0 into -1,
% which will later be changed back into 0 when converting to char
y % Duplicate separator
5XyP % Size-5 identity matrix flipped vertically: gives slash of the 'Z'
l5LY( % Fill first and last rows with ones. Gives the shape of the 'Z'
90* % Multiply by 90 (ASCII for 'Z')
yy % Duplicate separator and 'Z' array
!P % Transpose and flip vertically. Gives shape of the 'N'
12- % Subtract 12 to yield ASCII code for 'N'. 0 is converted to -12
&h % Concatenate the nine arrays horizontally
c % Convert to char. Implicitly display
```
[Answer]
# JavaScript ES6, 168 bytes, CHAMP
We can stop looking guys, we have a `CHAMP` over here
```
f=_=>
` C3cHaHdA2dMaMcP3
CgHaHcAaAcMM MMcPaP
CgH4cA4cM M McP3
CgHaHcAaAcMaMcP
C3cHaHcAaAcMaMcP`.replace(/[a-z\d]/g,(a,i,c)=>+a?c[i-1].repeat(a):' '.repeat(parseInt(a,36)-7))
a.innerHTML = f()
```
```
<pre id=a>
```
[Answer]
# Brainf\*\*\* ~~512~~ 411 Bytes
**Better redo:**
This one does a better job at optimizing the tape, sacrificing setup characters for printing characters. The tape in this one looks like `'C' 'E' ' ' 'F' 'I' 'L' '\n'`, improving efficiency. I chose these because they lack internal spaces, making it so that they don't have to go back and forth between character and space more than necessary
```
++++++++[>+++++++++>+++++++++>++++>+++++++++>+++++++++>+++++++++>+<<<<<<<-]>----->--->>-->+>++++>++<<<<.<<....>>.....<.....>.....>.....<.....>>.....<<.....>>>.>.<<<<<<.>>.........<.>.........>.<...........>>.<<.......>>>.>.<<<<<<.>>.........<....>......>....<........>>.<<.......>>>.>.<<<<<<.>>.........<.>.........>.<...........>>.<<.......>>>.>.<<<<.<<....>>.....<.....>.....>.<.........>>.....<<.....>>>.....
```
If you want to read what it's doing:
```
Set the tape with 67,69,32,70,73,76,10
++++++++[>+++++++++>+++++++++>++++>+++++++++>+++++++++>+++++++++>+<<<<<<<-]>----->--->>-->+>++++>++<<<<
.<<....>>.....<.....>.....>.....<.....>>.....<<.....>>>.>.<<<<<< First Line
.>>.........<.>.........>.<...........>>.<<.......>>>.>.<<<<<< Second Line
.>>.........<....>......>....<........>>.<<.......>>>.>.<<<<<< Third Line
.>>.........<.>.........>.<...........>>.<<.......>>>.>.<<<< Fourth Line
.<<....>>.....<.....>.....>.<.........>>.....<<.....>>>..... Fifth Line
```
Output:
```
CCCC EEEEE FFFFF IIIII L
C E F I L
C EEEE FFFF I L
C E F I L
CCCC EEEEE F IIIII LLLLL
```
**Former Submission:**
```
++++++++[>++++<-]>[>++>++>++>++>++>+<<<<<<-]>+>++>+++>++++>+++++>>++++++++++<.<<<<<...>>>>>......<<<<....>>>>.......<<<....>>>.....<<....>>......<.....>>.<<<<<<.>>>>>...<<<<<.>>>>>.....<<<<.>>>>...<<<<.>>>>.....<<<.>>>.........<<.>>...<<.>>.....<.>>.<<<<<<.....>>>>>.....<<<<....>>>>......<<<.>>>.........<<.>>...<<.>>.....<....>>.<<<<<<.>>>>>...<<<<<.>>>>>.....<<<<.>>>>...<<<<.>>>>.....<<<.>>>.........<<.>>...<<.>>.....<.>>.<<<<<<.>>>>>...<<<<<.>>>>>.....<<<<....>>>>.......<<<....>>>.....<<....>>......<.....
```
I chose to go with ABCDE because it make setting up the tape for output much easier, but the time and characters I wasted in going from the letter to ' ' for all the negative space inside the A, B, and D and the placement of the endline at the end of the tape kinda killed me, I think.
I ended up with a tape that had the values `0 0 'A' 'B' 'C' 'D' 'E' ' ' \n` and then output from there
```
++++++++[>++++<-]>[>++>++>++>++>++>+<<<<<<-]>+>++>+++>++++>+++++>>++++++++++ This all sets up the tape as 0 0 A B C D E ' ' '\n'
<.<<<<<...>>>>>......<<<<....>>>>.......<<<....>>>.....<<....>>......<.....>>.<<<<<< First Line
.>>>>>...<<<<<.>>>>>.....<<<<.>>>>...<<<<.>>>>.....<<<.>>>.........<<.>>...<<.>>.....<.>>.<<<<<< Second Line
.....>>>>>.....<<<<....>>>>......<<<.>>>.........<<.>>...<<.>>.....<....>>.<<<<<< Third Line
.>>>>>...<<<<<.>>>>>.....<<<<.>>>>...<<<<.>>>>.....<<<.>>>.........<<.>>...<<.>>.....<.>>.<<<<<< Fourth Line
.>>>>>...<<<<<.>>>>>.....<<<<....>>>>.......<<<....>>>.....<<....>>......<..... Last Line
```
Output:
```
AAA BBBB CCCC DDDD EEEEE
A A B B C D D E
AAAAA BBBB C D D EEEE
A A B B C D D E
A A BBBB CCCC DDDD EEEEE
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), ~~62~~, 53 bytes
```
iC± I· D³ Dµ O³ O¸ Z3ñYp$XñS ´Cµ µIµ ´D· ³O¶ µZYHP
```
[Try it online!](http://v.tryitonline.net/#code=aUPCsSAgScK3IETCsyBEwrUgT8KzIE_CuCBaGzPDsVlwJFjDsVMgwrRDwrUgwrVJwrUgwrREwrcgwrNPwrYgwrVaG1lIUA&input=)
This outputs `C I D O Z`:
```
CCCC IIIII DDDD OOO ZZZZZ
C I D D O O Z
C I D D O O Z
C I D D O O Z
CCCC IIIII DDDD OOO ZZZZZ
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 33 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) "BCDEO"
```
┌☼&.àτ▲█╟;c♦▌ΩÅ╡≤♫¿(┌▲▲≡3*╤J s*è«
```
[Run and debug it](https://staxlang.xyz/#p=da0f262e85e71edbc73b6304ddea8fb5f30ea828da1e1ef0332ad14a20732a8aae&i=&a=1)
I picked letters that
* have vertical symmetry
* whose middle three columns are identical
These properties mean that each letter can be represented by a 3x3 grid. Here are the 9 regions, represented by digits.
```
12223
45556
78889
45556
12223
```
Consider the letter "B". It can be represented by 3 octal digits: `656`. Each digit contains three bits, which control which regions are enabled for that letter. This technique also works for "CDEO".
Unpacked, ungolfed, and commented, the program looks like this.
```
"!^*14>G2eo"! crammed integer literal [63672, 54545, 64565]
|p palindromize [63672, 54545, 64565, 54545, 63672]
m for each, run this and output...
E extract decimal digits to array [6, 3, 6, 7, 2]
`)"+0` compressed string literal "BCDEO"
\ zip arrays [[6, 66], [3, 67], [6, 68], [7, 69], [2, 79]]
{ map array using block
E explode array 6, 66
Z\ tuck a zero under, and make pair 6, [0, 66]
:B custom base convert [66, 66, 0]
3) pad to length 3 [66, 66, 0]
3O\ tuck a one under a 3 and pair [66, 66, 0], [1, 3]
:B repeat elements corresponding times [66, 66, 66, 66, 0]
A( pad right to length 10 [66, 66, 66, 66, 0, 0, 0, 0, 0, 0]
m
```
[Run this one](https://staxlang.xyz/#c=%22%21%5E*14%3EG2eo%22%21%09crammed+integer+literal++++++++++++%09[63672,+54545,+64565]%0A%7Cp+++++++++++%09palindromize+++++++++++++++++++++++%09[63672,+54545,+64565,+54545,+63672]%0Am++++++++++++%09for+each,+run+this+and+output...+++%09%0A++E++++++++++%09extract+decimal+digits+to+array++++%09[6,+3,+6,+7,+2]%0A++%60%29%22%2B0%60+++++%09compressed+string+literal++++++++++%09%22BCDEO%22%0A++%5C++++++++++%09zip+arrays+++++++++++++++++++++++++%09[[6,+66],+[3,+67],+[6,+68],+[7,+69],+[2,+79]]%0A++%7B++++++++++%09map+array+using+block++++++++++++++%09%0A++++E++++++++%09explode+array++++++++++++++++++++++%096,+66%0A++++Z%5C+++++++%09tuck+a+zero+under,+and+make+pair+++%096,+[0,+66]%0A++++%3AB+++++++%09custom+base+convert++++++++++++++++%09[66,+66,+0]%09%0A++++3%29+++++++%09pad+to+length+3++++++++++++++++++++%09[66,+66,+0]%0A++++3O%5C++++++%09tuck+a+one+under+a+3+and+pair++++++%09[66,+66,+0],+[1,+3]%0A++++%3AB+++++++%09repeat+elements+corresponding+times%09[66,+66,+66,+66,+0]%0A++++A%28+++++++%09pad+right+to+length+10+++++++++++++%09[66,+66,+66,+66,+0,+0,+0,+0,+0,+0]%0A++m%0A&i=&a=1)
[Answer]
# Python 2, 124 bytes
```
d,i,o,c,l,s,n='DIOCL \n'
T=d*4+s*6+i*5+s*6+o*3+s*7+c*4+s*5+l
M=d+s*3+d+s*7+i+s*7+o+s*3+o+s*5+c+s*9+l+n
print T+n,M,M,M,T+l*3
```
Similar to [my other answer](https://codegolf.stackexchange.com/a/99976/59363), but with better letter choices. Outputs this:
```
DDDD IIIII OOO CCCC L
D D I O O C L
D D I O O C L
D D I O O C L
DDDD IIIII OOO CCCC LLLL
```
[Answer]
# Befunge, 120 bytes (CKYTF)
**Source**
```
#&49+14489+56*1449135*44711425*:12p9138*7+:89+:56*55*v_@
-1g05$$_\#!:2#-%#16#\0#/g#20#,g#+*8#4<80\9*2p06%5p05:<^:,g2!%5:
```
**Output**
```
CCCC K K Y Y TTTTT FFFFF
C K K Y Y T F
C KKK Y T FFFF
C K K Y T F
CCCC K K Y T F
```
[Try it online!](http://befunge.tryitonline.net/#code=IyY0OSsxNDQ4OSs1NioxNDQ5MTM1KjQ0NzExNDI1KjoxMnA5MTM4KjcrOjg5Kzo1Nio1NSp2X0AKLTFnMDUkJF9cIyE6MiMtJSMxNiNcMCMvZyMyMCMsZyMrKjgjNDw4MFw5KjJwMDYlNXAwNTo8XjosZzIhJTU6&input=)
In case it matters, I should point out that my output has a leading space on each line. The rules didn't explicitly prohibit that, so I'm hoping that's OK. If not, please just consider this a non-competing entry.
**Explanation**
The letters of the word are encoded as a simple sequence of 25 integers, each integer being a binary representation of 5 pixels. Since Befunge requires you to perform a calculation to instantiate any integer greater than 9, the letters were chosen so as to minimize the number of calculations required, and ordered so potential repeating values could be duplicated rather than recalculated.
We also need to store the ASCII value of each letter, offset by 32, in an array which is indexed by the modulo 5 of a decrementing index (so it goes 0 4 3 2 1 ...). The reason for offsetting by 32 is so the value can be multiplied by a pixel bit (1 or 0) and then added to 32 to produce either a space or the character required.
This array of letter values is stored in the first 5 bytes of the code, so it's easy to access. This also then influenced the choice of letters, since those values needed to be meaningful when interpreted as a code sequence. This is the sequence `#&49+`. The `#` jumps over the `&` and the `49+` just pushes 13 onto the stack which is subsequently ignored.
[Answer]
# Ruby, ~~110~~ ~~107~~ 102 bytes (DOCIL)
```
puts a=?D*4+(t=' '*7)+?O*3+t+?C*4+(s=' '*5)+?I*5+s+?L,['D D'+s+'O O'+s+?C+' '*11+?I+t+?L]*3,a+?L*4
```
Prints
```
DDDD OOO CCCC IIIII L
D D O O C I L
D D O O C I L
D D O O C I L
DDDD OOO CCCC IIIII LLLLL
```
EDIT: Saved some chars by avoiding `join` and moving things around
[Answer]
# [Befunge-98](https://esolangs.org/wiki/Funge-98), ~~109~~ 98 bytes (FUNGE / ANY)
```
:5%!2>j#4_;\$&\#;\:0`!#@_:::'@/'@*-\'@/2%*' +,:'@/:2/-'@*-\1+:5%!2>j#4_;' 3k:4k,#;:55*%!2>j#4_;a,;
```
[Try it online!](http://befunge-98.tryitonline.net/#code=OjUlITI-aiM0XztcJCZcIztcOjBgISNAXzo6OidALydAKi1cJ0AvMiUqJyArLDonQC86Mi8tJ0AqLVwxKzo1JSEyPmojNF87JyAzazo0aywjOzo1NSolITI-aiM0XzthLDs&input=MjAyMiAxMTQxIDExMzQgOTM1IDIwMjEgMTAyIDExNDEgMTI2MiAxMDMgMTAxIDk5OCAxMTQxIDEzOTAgMTYzOSA5OTcgMTAyIDExNDEgMTY0NiAxMTI3IDEwMSAxMDIgOTQ5IDExMzQgOTM1IDIwMjEgMA)
## Input (115 characters):
```
2022 1141 1134 935 2021 102 1141 1262 103 101 998 1141 1390 1639 997 102 1141 1646 1127 101 102 949 1134 935 2021 0
```
Input is the integer version of a binary number with the format `aaaaabbbbbb` where `aaaaa` is a reversed map of the character to print (for example, the second row in the N is `NN N`, so the mask is `10011`), and `bbbbbb` is the ascii character to print, minus 32.
I also created a befunge-98 program to create my inputs:
```
4k~44p34p24p14p04p v
+1.+-**244g4%5\**88_@#`0:&::<
```
[Try it online!](http://befunge-98.tryitonline.net/#code=NGt-NDRwMzRwMjRwMTRwMDRwICAgICAgICAgIHYKKzEuKy0qKjI0NGc0JTVcKio4OF9AI2AwOiY6Ojw&input=RlVOR0UzMSAxNyAxNyAxNCAzMSAxIDE3IDE5IDEgMSAxNSAxNyAyMSAyNSAxNSAxIDE3IDI1IDE3IDEgMSAxNCAxNyAxNCAzMSAw)
## Output (255 characters):
```
FFFFF U U N N GGG EEEEE
F U U NN N G E
FFFF U U N N N G GG EEEE
F U U N NN G G E
F UUU N N GGG EEEEE
```
>
> (255 - (115 + 98)) / 255 = 16% compression
>
>
>
## Explanation:
```
:5%!2>j#4_;\$&\#;\:0`!#@_ Get input if it is available, else end program
:::'@/'@*-\'@/2%*' +, Output the current input character (or a space,
if the mask dictates so)
:'@/:2/-'@*- Throw away current mask bit
\1+ Swap loop iterator to top of stack, increment it
:5%!2>j#4_;' *3k:4k,#; If iterator % 5 == 0, print five spaces
:55*%!2>j#4_;a,; If iterator % 25 == 0, print newline character
```
This is probably pretty golfable; I've spent barely any time thinking about potential reductions.
Theoretically this can print any sequence of 5x5 ascii art.
Thanks to [James Holderness](https://codegolf.stackexchange.com/users/62101/james-holderness) for helping me get out of triple digits!
[Answer]
# C#, 290 279 267 265 Bytes
*Edit: Saved 12 bytes thanks to @milk! And 2 more thanks to @TheLethalCoder*
Golfed:
```
void F(){string g=" ",h="H H",A="A A",B=h+"|"+A;Func<string,string>j=a=>a.Replace("|",g)+"\n";Console.Write(j(" SSSS|"+h+"| AAA |RRRR |PPPP")+j("S |"+B+"|R R|P P")+j(" SSS |HHHHH|AAAAA|RRRR |PPPP")+j(" S|"+B+"|R R |P")+j("SSSS |"+B+"|R R|P"));}
```
Ungolfed:
```
public void F()
{
string g = " ", h = "H H", A = "A A", B = h + "|" + A;
Func<string, string> j = a => a.Replace("|", g) + "\n";
Console.Write(j(" SSSS|" + h + "| AAA |RRRR |PPPP") +
j("S |" + B + "|R R|P P") +
j(" SSS |HHHHH|AAAAA|RRRR |PPPP") +
j(" S|" + B + "|R R |P") +
j("SSSS |" + B + "|R R|P"));
}
```
Outputs:
```
SSSS H H AAA RRRR PPPP
S H H A A R R P P
SSS HHHHH AAAAA RRRR PPPP
S H H A A R R P
SSSS H H A A R R P
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 82 bytes (DOCIL)
Using the same letters and strategy everyone else is using (reusing the lines where possible), combined with an RLE decoder.
```
}{$_=($;="4D7 3O7 4C5 5I5 L")."
D3 D5 O3 O5 C11 I7 L"x3 ."
$;4L";s/\d+(.)/$1x$&/ge
```
[Try it online!](https://tio.run/##K0gtyjH9/7@2WiXeVkPF2lbJxMVcwdjfXMHE2VTB1NNUwUdJU0@Jy8VYwcVUwd9Ywd9UwdnQUMHTHChRYawAlFKxNvFRsi7Wj0nR1tDT1FcxrFBR009P/f//X35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) `-p`, 95 bytes (ABCDE)
Contains unprintables, so the link includes them in `\x##` notation. [Verification for 95 bytes.](https://tio.run/##dZBRT8IwFIXf@RXHOQxEV7bb3rWwKGhi/BHGGLa1QiSwwBAS9bdjmxHf6MPJTXv7nXNvOd8tTqfjsUayhVium30r2uUGD@DEzb8222Vrk5VtW7vdiWZV9A4VkurSo60Wm06RrPGDxm5XSJoL7adTej4T6FqXIMUOstaM3OoUeZZL5CWlUCQzSJIM/H7H7/f7dTOvPvGUEfc6QuYZVBFB67GDdVUOmZoK0lkDpesMpiKJ1LgxcBcdhBCpmIoXIa6FODPIM5x1BkSyhJZeyAYxpEC5dL5Smb8jCwgRFbtCFIP4Zjp4/GdIz1BMY3Dpw6iUak8jPxUTe@Each5o5FvwPHyNZkk04j6/TeJoeGaoMIulkEOloAAiluS/hwgqDGn8KrShzOcYRLPbqE88jaMjH6/ODA4M00Uog11w956duwtVmWvkfqNAh@DhJB4Niw/7Bw)
```
}{$_=unpack B125,"w...0.?.G..#....";s;.;($&?(A..E)["@-"/5%5]:$").("@+"%25?$"x5x!("@+"%5):$/);ge
```
[Try it online!](https://tio.run/##JcfdCoIwFADgV6nTDEc6f@DEbIQWRA/RJMJmRKEjiw5Er95adPFdfNbcrujc@8X2y0dnD81ltM5yjOCpqWg1Ga@Zp5pkU/rJraZj9ttEUyo1tYVnPAlqUEKFDKJwJcSG76CKIcEAa75j01qEUM0gyLFkQEjjf5EvWMLVyTj36e393HeDi@0X "Perl 5 – Try It Online")
## Explanation
The main data is stored as a binary matrix in the 16 byte string passed to `unpack`, which is called to convert to binary. Then `s///` is called to replace each character with either `$"` (space) or if `$&` is falsy (`0`) or `(A..E)["@-"/5%5]` otherwise, where `"@-"` is the start index of the current character (`@-` is a list so `$-[0]` would return the first element, but interpolating into a string is 1 byte shorter) and we divide it by `5` and then take that result modulo `5` resulting in `0-4` (as the decimal part is ignored in list indices) based on the position, this correctly gets the letters in the right place for each of the larger letters. This is then appended to with, if `"@+"%25` (like `"@-"` above, but `@+` contains the end index of the current match) is truthy, `$"x5x!("@+"%5)` (space repeated [`x`] five times, repeated once when `"@+"%5` is false) which adds the required spaces after each letter, or `$/` (newline) otherwise.
[Answer]
## Python 3, ~~234~~ ~~228~~ ~~227~~ 166 bytes (CLOUD):
```
import base64,gzip;b=b'ABzY86gn$d0{>HR1_A{T@KJyRe}8`nBNU1i6kLFS%Nec$q1YdaQ51tPO;sx(oDBkK&Q=Hwg(wC)8vxUXJX_-c000';print(gzip.decompress(base64.b85decode(b)).decode())
```
Prints:
```
CCCC L OOO U U DDDD
C L O O U U D D
C L O O U U D D
C L O O U U D D
CCCC LLLLL OOO UUU DDDD
```
[Answer]
# Python 3, 178 bytes
```
e,f,i,t,h,s='EFITH '
p=print
S=s*5
D=i+s*9+t+s*7
A=e*5+S
F=S+i*5+S
B=e+s*9+f+s*11+D+h+s*3+h
C=h+s*3+h
p(A+f*5+F+t*5+S+C)
p(B)
p(e*4+s*6+f*4+s*8+D+h*5)
p(B)
p(A+f+s*4+F,s+t+s*7+C)
```
Won't win, but does not use any compression. It makes this:
```
EEEEE FFFFF IIIII TTTTT H H
E F I T H H
EEEE FFFF I T HHHHH
E F I T H H
EEEEE F IIIII T H H
```
Any help is welcome, I probably missed something. I didn't use Python 2 because you can't do the `p=print`, and that saves 17 bytes. [Try it on repl.it.](https://repl.it/EZLa/1)
[Answer]
# Ruby, 101 bytes (TIFLE)
```
"o@h@u".bytes{|i|k=3+i%2;puts "%-10s"*5%"TIFLE".chars.map{|j|i/=2;(i/16>i%2*3?' ':'')+j+j*k*(i%2)}}
TTTTT IIIII FFFFF L EEEEE
T I F L E
T I FFFF L EEEE
T I F L E
T IIIII F LLLLL EEEEE
```
I picked letters that required a single block of letters (1,4 or 5 letters long) on each line. F,L and E are left justified, but T and I require leading spaces where a single letter (vertical part) is printed. The code for adding these spaces looks like it could be improved.
**ungolfed**
```
"o@h@u".bytes{|i| #for each byte (64 always set, 32...2 bits set for horiz bar, 1 bit=length of bar)
k=3+i%2 #decode least sig. bit for no of chars printed if a 1 is found
puts "%-10s"*5% #puts "%-10s%-10s%-10s%-10s%-10s" format string (expects array of subsitutes)
"TIFLE".chars.map{|j| #for each letter
i/=2 #halve i
(i/16>i%2*3?' ':'')+ #if i large enough and i%2 zero, add leading space (or T and I)
j+j*k*(i%2) #print the letter once, then additional letters if bar required.
}
}
```
[Answer]
# C 176 bytes
If implicit ints are allowed then it's possible to cut off another 8 bytes.
```
#define C ,//11 bytes
#define R(r)r r r r r//21 bytes
T(int l){int c=324;printf(R(R("%c")R(" "))"\n" R(R(C(++c,l>>=1)&1?c/5:32)));}//77 bytes
f(){T(67010460);T(34702434);T(66160574);T(34702434);T(67010466);}//65 bytes
```
Output: E D C B A
```
EEEEE DDDD CCCC BBBB AAA
E D D C B B A A
EEEEE D D C BBBB AAAAA
E D D C B B A A
EEEEE DDDD CCCC BBBB A A
```
How it works: The macro R just repeats a piece of code 5 times. Given how often fives appear in this problem, very useful. Now: here's what T(int) does. T takes an integer, and uses it as a bit field to determine where to print letters and where to print white space. For example, if given `T(0b11111111100111111110011100)`, it will output: `EEEEE DDDD CCCC BBBB AAA` . It progressively counts down as to what letter it prints. First it prints E, then D, then C, then B, then A. Calling f() will print the entire thing.
[Answer]
## Batch, 135 bytes (DOCILe)
```
@set b=
@set s=@echo DDDD%b% OOO%b% CCC%b% IIIII%b%L
@set t=@echo D D%b%O O%b%C%b%%b% I%b% L
%s%
%t%
%t%
%t%
%s%LLLL
```
Note: the first line ends in 5 spaces.
[Answer]
# BASH, ~~95~~, 111 bytes (EBASH)
**Golfed**
```
base64 -d<<<4ADlADhdACLpBDSMnNdRTj0Ob2qBPVT3HkdMRZzZ3kL+yIb6mhkz06EM+KOspSDy2EBoUKKL6pfwNo0akV0zAA==|xz -dqFraw
```
**Explanation**
Base64 over raw LZMA byte stream
**Demo**
```
>base64 -d<<<4ADlADhdACLpBDSMnNdRTj0Ob2qBPVT3HkdMRZzZ3kL+yIb6mhkz06EM+KOspSDy2EBoUKKL6pfwNo0akV0zAA==|xz -dqFraw
EEEEE BBBB AAA SSSS H H
E B B A A S H H
EEEE BBBB AAAAA SSS HHHHH
E B B A A S H H
EEEEE BBBB A A SSSS H H
```
**Disclaimer**
Yes, I'm well aware that this is not really portable, that's why I've paid a byte to suppress the *xz* warnings with *-q* in the first case >:)
[Answer]
# Python 2, ~~208~~ ~~194~~ 193 bytes
This is my first ever code golf ;) Fun to do
```
for i in range(0,25,5):
for c,p in {'M':18732593,'O':15255086,'N':18667121,'T':32641156,'Y':18157700}.items():
print format(p,'025b')[i:i+5].replace('0',' ',).replace('1',c)+' ',
print
```
Output:
```
Y Y M M TTTTT OOO N N
Y Y MM MM T O O NN N
Y M M M T O O N N N
Y M M T O O N NN
Y M M T OOO N N
```
Using a dictionary destroys the sort order of the letters, but that was not a requirement
[Answer]
## perl 94 bytes.
The first 4 letters (`D`, `O`, `I`, `C`) are specifically chosen to have the upper and lower lines similar, and the middle ones similar. As there is not any other similar letter, I chose the "L" to be able to apply the same algorithm and add the missing 4L.
```
for(($a="D5 6O3 6I5 6C4 5L")."
","D 3D 5O 3O 7I 7C 9L
"x3,$a."4L
"){s/(.)(\d)/$1x$2/eg;print}
```
I saved some extra bytes by replacing the `\n` in the code with a real new line.
Result:
```
DDDD OOO IIIII CCCC L
D D O O I C L
D D O O I C L
D D O O I C L
DDDD OOO IIIII CCCC LLLLL
```
] |
[Question]
[
It's been a rough few months at work and I feel like I just want to scream right to my boss' face. I am, however, not one to directly confront people I have a problem with. I also don't want to lose my job.
So here's an idea: I want to be able to insult him, without him ever finding out. And I realized the perfect way: I need some sort of software that encodes an insult inside an otherwise perfectly fine message. And seeing as how he's known to not see forests for trees, I think I know just how:
Write me a program that takes as input a string of unknown length, but containing no line breaks. This will be the raw message I want to send.
If possible, return the string formatted such that the message "DIE IN A GREASE FIRE" makes up the entire left column. With new paragraphs where spaces in between words should go. Now, as I am very angry, it is equally important that every letter is in upper case.
You may not modify the string in any other way, i.e. you may not turn all of the string into upper case characters.
If the string in question cannot be formatted in this way, you are to return the original string. Read input from standard input.
Normal rules apply: No HTTP requests, no consulting Marvin from THGTTG, etc.
Example input:
>
> Dear Boss, how are things? It has come to my attention that I received
> all the blame for the mishap last Friday. Not just the majority of it.
> Every last bit of it. Is it wrong for me to think that the rest of the
> team were at least in part responsible? After all, all six of us were
> involved from the get-go. Not that I think I should stand without
> blame. Not at all. All I'm saying is this: I do my best. I try hard. I
> improve constantly. And I am constantly taking responsibility.
> Generally speaking, I am very okay with taking full responsibility for
> my actions. But after this spring, it seems I get more than I deserve.
> Remember the Flakenhauser contract? Everything went down just about as
> smooth as one could have hoped. Or so it seemed at first. It was just
> at the very last minute that things fell apart. All of the team agreed
> that it was more akin to a freak accident than sloppy planning or
> mismanaged resources. Still, I - alone - took blame for it. Even
> though I said nothing then, my tolerance level for taking the blame
> took a serious dent then. From that point on, I have felt it necessary
> to always try twice as hard, just to escape scrutiny. And still, here
> we are again. In spite of all my accomplishments. Right where we
> always seem to end up these days. Every single project. It's becoming
> unbearable.
>
>
>
Example output:
>
> Dear Boss, how are things?
>
> It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
>
> Every last bit of it.
>
>
> Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
>
> Not that I think I should stand without blame. Not at all.
>
>
> All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.
>
>
> Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
>
> Remember the Flakenhauser contract.
>
> Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
>
> All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
>
> Still, I - alone - took blame for it.
>
> Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.
>
>
> From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again.
>
> In spite of all my accomplishments.
>
> Right where we always seem to end up these days.
>
> Every single project. It's becoming unbearable.
>
>
>
This is code golf. Shortest code wins.
[Answer]
# CJam, ~~56~~ 53 bytes
```
q_"DIEIINAAGGREASEFFIRE"{S@:A+S@+#:BA<AB>}%(!B)*\N*@?
```
[Try it online!](http://cjam.tryitonline.net/#code=cV8iRElFSUlOQUFHR1JFQVNFRkZJUkUie1NAOkErU0ArIzpCQTxBQj59JSghQikqXE4qQD8&input=RGVhciBCb3NzLCBob3cgYXJlIHRoaW5ncz8gSXQgaGFzIGNvbWUgdG8gbXkgYXR0ZW50aW9uIHRoYXQgSSByZWNlaXZlZCBhbGwgdGhlIGJsYW1lIGZvciB0aGUgbWlzaGFwIGxhc3QgRnJpZGF5LiBOb3QganVzdCB0aGUgbWFqb3JpdHkgb2YgaXQuIEV2ZXJ5IGxhc3QgYml0IG9mIGl0LiBJcyBpdCB3cm9uZyBmb3IgbWUgdG8gdGhpbmsgdGhhdCB0aGUgcmVzdCBvZiB0aGUgdGVhbSB3ZXJlIGF0IGxlYXN0IGluIHBhcnQgcmVzcG9uc2libGU_IEFmdGVyIGFsbCwgYWxsIHNpeCBvZiB1cyB3ZXJlIGludm9sdmVkIGZyb20gdGhlIGdldC1nby4gTm90IHRoYXQgSSB0aGluayBJIHNob3VsZCBzdGFuZCB3aXRob3V0IGJsYW1lLiBOb3QgYXQgYWxsLiBBbGwgSSdtIHNheWluZyBpcyB0aGlzOiBJIGRvIG15IGJlc3QuIEkgdHJ5IGhhcmQuIEkgaW1wcm92ZSBjb25zdGFudGx5LiBBbmQgSSBhbSBjb25zdGFudGx5IHRha2luZyByZXNwb25zaWJpbGl0eS4gR2VuZXJhbGx5IHNwZWFraW5nLCBJIGFtIHZlcnkgb2theSB3aXRoIHRha2luZyBmdWxsIHJlc3BvbnNpYmlsaXR5IGZvciBteSBhY3Rpb25zLiBCdXQgYWZ0ZXIgdGhpcyBzcHJpbmcsIGl0IHNlZW1zIEkgZ2V0IG1vcmUgdGhhbiBJIGRlc2VydmUuIFJlbWVtYmVyIHRoZSBGbGFrZW5oYXVzZXIgY29udHJhY3Q_IEV2ZXJ5dGhpbmcgd2VudCBkb3duIGp1c3QgYWJvdXQgYXMgc21vb3RoIGFzIG9uZSBjb3VsZCBoYXZlIGhvcGVkLiBPciBzbyBpdCBzZWVtZWQgYXQgZmlyc3QuIEl0IHdhcyBqdXN0IGF0IHRoZSB2ZXJ5IGxhc3QgbWludXRlIHRoYXQgdGhpbmdzIGZlbGwgYXBhcnQuIEFsbCBvZiB0aGUgdGVhbSBhZ3JlZWQgdGhhdCBpdCB3YXMgbW9yZSBha2luIHRvIGEgZnJlYWsgYWNjaWRlbnQgdGhhbiBzbG9wcHkgcGxhbm5pbmcgb3IgbWlzbWFuYWdlZCByZXNvdXJjZXMuIFN0aWxsLCBJIC0gYWxvbmUgLSB0b29rIGJsYW1lIGZvciBpdC4gRXZlbiB0aG91Z2ggSSBzYWlkIG5vdGhpbmcgdGhlbiwgbXkgdG9sZXJhbmNlIGxldmVsIGZvciB0YWtpbmcgdGhlIGJsYW1lIHRvb2sgYSBzZXJpb3VzIGRlbnQgdGhlbi4gRnJvbSB0aGF0IHBvaW50IG9uLCBJIGhhdmUgZmVsdCBpdCBuZWNlc3NhcnkgdG8gYWx3YXlzIHRyeSB0d2ljZSBhcyBoYXJkLCBqdXN0IHRvIGVzY2FwZSBzY3J1dGlueS4gQW5kIHN0aWxsLCBoZXJlIHdlIGFyZSBhZ2Fpbi4gSW4gc3BpdGUgb2YgYWxsIG15IGFjY29tcGxpc2htZW50cy4gUmlnaHQgd2hlcmUgd2UgYWx3YXlzIHNlZW0gdG8gZW5kIHVwIHRoZXNlIGRheXMuIEV2ZXJ5IHNpbmdsZSBwcm9qZWN0LiBJdCdzIGJlY29taW5nIHVuYmVhcmFibGUu)
### How it works
```
q_ Read all input from STDIN and push a copy.
"DIEIINAAGGREASEFFIRE" Push the characters we're searching for in form of a
string. We'll try to prepend a linefeed to all of them.
Some characters are duplicated to prepend two linefeeds.
{ For every character C in that string:
S@ Push ' ' and rotate the string on the stack on top of it.
:A Save the string (initially the input) in A.
+ Prepend the space to A.
S@+ Construct the string " C".
# Compute the index of " C" in the modified A.
:B Save the index in the variable B.
A< Push the substring of A up to the index.
AB> Push the substring of A after the index.
}%
( Shift the first element of the resulting array.
! Compute the logical NOT. This pushes 1 if and only if the
array's first element is an empty string, which is true
if and only if the input string started with a D.
B) Push the last value of B and increment. If the last match
was successful and, therefore, all matches were successful,
B != -1, so B + 1 != 0.
* Compute the product of the two topmost items on the stack.
\ Swap the resulting Booleanr with the array of substrings.
N* Join the array, separating by linefeeds.
@ Rotate the input string on top of the stack.
? Select the joined array if the Boolean is 1 and the input
string otherwise.
```
[Answer]
## Perl - 60 bytes
```
#!perl -p
$_=(join$/,$_=~('DIE\IN\A\GREASE\FIRE'=~s/./($&.*)/gr))||$_
```
Counting the shebang as one.
This solution uses the innermost string to build up the following regex:
```
(D.*)(I.*)(E.*)(\.*)(I.*)(N.*)(\.*)(A.*)(\.*)(G.*)(R.*)(E.*)(A.*)(S.*)(E.*)(\.*)(F.*)(I.*)(R.*)(E.*)
```
which is similar to the regex used in [m.buettner's solution](https://codegolf.stackexchange.com/a/32025). The generated regex is then matched against the input. In a list context, this will return an array containing each of the match groups, which are joined together by a newline (the reason for the 'match nothing' groups `(\.*)`, is to insert an additional newline). If there is no match, the original string is output instead.
---
## Perl - 73 bytes
```
#!perl -pl
$s=$_}for(map$s!~s/.*?(?=$_)//?$\='':$&,'DIEI.NA.G.REASEF.IRE$'=~/./g){
```
Counting the shebang as two.
This splits up the string at the appropriate delimiters, and collects the pieces in an array. If any of them fail to match, the [output record separator](http://perldoc.perl.org/perlvar.html#%24OUTPUT_RECORD_SEPARATOR) (which was set to a newline with the `-l` option) is unset, and so the string is output unmodified.
[Answer]
# GolfScript, 53 bytes
Looks like Dennis and I came up with pretty similar things in parallel... But here's my attempt.
Click on the links before each code block to try it online. Unfortunately, the online interpreter won't allow you to run code larger than 1024 characters, so I had to perform some... "compression" of the test input. But it does still work.
[Squished version](http://golfscript.apphb.com/?c=OyJEZWFyIEJvc3MsIGhvdyBhcmUgdGhpbmdzPyBJdCBoYXMgY29tZSB0byBteSBhdHRlbnRpb24gdGhhdCBJIHJlY2VpdmVkIGFsbCB0aGUgYmxhbWUgZm9yIHRoZSBtaXNoYXAgbGFzdCBGcmlkYXkuIE5vdCBqdXN0IHRoZSBtYWpvcml0eSBvZiBpdC4gRXZlcnkgbGFzdCBiaXQgb2YgaXQuIElzIGl0IHdyb25nIGZvciBtZSB0byB0aGluayB0aGF0IHRoZSByZXN0IG9mIHRoZSB0ZWFtIHdlcmUgYXQgbGVhc3QgaW4gcGFydCByZXNwb25zaWJsZT8gQWZ0ZXIgYWxsLCBhbGwgc2l4IG9mIHVzIHdlcmUgaW52b2x2ZWQgZnJvbSB0aGUgZ2V0LWdvLiBOb3QgdGhhdCBJIHRoaW5rIEkgc2hvdWxkIHN0YW5kIHdpdGhvdXQgYmxhbWUuIE5vdCBhdCBhbGwuIEFsbCBJJ20gc2F5aW5nIGlzIHRoaXM6IEkgZG8gbXkgYmVzdC4gSSB0cnkgaGFyZC4gSSBpbXByb3ZlIGNvbnN0YW50bHkuIEFuZCBJIGFtIGNvbnN0YW50bHkgdGFraW5nIHJlc3BvbnNpYmlsaXR5LiBHZW5lcmFsbHkgc3BlYWtpbmcsIEkgYW0gdmVyeSBva2F5IHdpdGggdGFraW5nIGZ1bGwgcmVzcG9uc2liaWxpdHkgZm9yIG15IGFjdGlvbnMuIEJ1dCBhZnRlciB0aGlzIHNwcmluZywgaXQgc2VlbXMgSSBnZXQgbW9yZSB0aGFuIEkgZGVzZXJ2ZS4gUmVtZW1iZXIgdGhlIEZsYWtlbmhhdXNlciBjb250cmFjdD8gRSB3IGQgaiBhIGEgcyBhIG8gYyBoIGguIE8gcyBpIHMgYSBmLiBJIHcgaiBhIHQgdiBsIG0gdCB0IGYgYS4gQSBvIHQgdCBhIHQgaSB3IG0gYSB0IGEgZiBhIHQgcyBwIG8gbSByLiBTLCBJIC0gYSAtIHQgYiBmIGkuIEUgdCBJIHMgbiB0LCBtIHQgbCBmIHQgdCBiIHQgYSBzIGQgdC4gRiB0IHAgbywgSSBoIGYgaSBuIHQgYSB0IHQgYSBoLCBqIHQgZSBzLiBBIHMsIGggdyBhIGEuIEkgcyBvIGEgbSBhLiBSIHcgdyBhIHMgdCBlIHUgdCBkLiBFIHMgcC4gSSdzIGIgdS4iCgouLihcOzY4PSg%2BIklFSUlOQUFHR1JFQVNFRkZJUkUiezEkLkA%2FOl48bkBePn0vXShdXjA8PQ%3D%3D)
```
..(\;68=(>"IEIINAAGGREASEFFIRE"{1$.@?:^<n@^>}/](]^0<=
```
[Unsquished, commented version](http://golfscript.apphb.com/?c=OyJEIEIsIGggYSB0PyBJIGggYyB0IG0gYSB0IEkgciBhIHQgYiBmIHQgbSBsIEYuIE4gaiB0IG0gbyBpLiBFIGwgYiBvIGkuIEkgaSB3IGYgbSB0IHQgdCB0IHIgbyB0IHQgdyBhIGwgaSBwIHI%2FIEEgYSwgYSBzIG8gdSB3IGkgZiB0IGctZy4gTiB0IEkgdCBJIHMgcyB3IGIuIE4gYSBhLiBBIEknbSBzIGkgdDogSSBkIG0gYi4gSSB0IGguIEkgaSBjLiBBIEkgYSBjIHQgci4gRyBzLCBJIGEgdiBvIHcgdCBmIHIgZiBtIGEuIEIgYSB0IHMsIGkgcyBJIGcgbSB0IEkgZC4gUiB0IEYgYz8gRSB3IGQgaiBhIGEgcyBhIG8gYyBoIGguIE8gcyBpIHMgYSBmLiBJIHcgaiBhIHQgdiBsIG0gdCB0IGYgYS4gQSBvIHQgdCBhIHQgaSB3IG0gYSB0IGEgZiBhIHQgcyBwIG8gbSByLiBTLCBJIC0gYSAtIHQgYiBmIGkuIEUgdCBJIHMgbiB0LCBtIHQgbCBmIHQgdCBiIHQgYSBzIGQgdC4gRiB0IHAgbywgSSBoIGYgaSBuIHQgYSB0IHQgYSBoLCBqIHQgZSBzLiBBIHMsIGggdyBhIGEuIEkgcyBvIGEgbSBhLiBSIHcgdyBhIHMgdCBlIHUgdCBkLiBFIHMgcC4gSSdzIGIgdS4iCgouICAgICAgICMgKFNhdmUgaW5wdXQpCi4oXDsgICAgIyBHZXQgZmlyc3QgY2hhcmFjdGVyCjY4PSg%2BICAgIyBJZiAnRCcsIHdvcmsgd2l0aCBpbnB1dDsgZWxzZSwgd29yayB3aXRoIG9uZS1jaGFyYWN0ZXIgc3RyaW5nCiJJRUlJTkFBR0dSRUFTRUZGSVJFIgp7ICAgICAgICMgRm9yIGVhY2ggY2hhcmFjdGVyCiAxJC5AICAgIyAoRHVwbGljYXRlIG1lc3NhZ2UgdHdpY2UpCiA%2FOl4gICAgIyBGaW5kIGZpcnN0IGluZGV4IG9mIGNoYXJhY3RlcgogPG4gICAgICMgRXh0cmFjdCBwYXJ0IGJlZm9yZSBpbmRleCBhbmQgYWRkIGEgbmV3bGluZQogQF4%2BICAgICMgRXh0cmFjdCBwYXJ0IGluY2x1ZGluZyBhbmQgYWZ0ZXIgaW5kZXggYXMgbmV3ICJtZXNzYWdlIgp9LyAgICAgICMgKENsb3NlIGxvb3ApCl0oXV4wPD0gIyBJZiBsYXN0IGxpbmUgd2FzIHN1Y2Nlc3NmdWxseSBtYXRjaGVkLCBzZWxlY3QgcmVzdWx0OyBlbHNlLCBzZWxlY3QgaW5wdXQ%3D)
```
. # (Save input)
.(\; # Get first character
68=(> # If 'D', work with input; else, work with one-character string
"IEIINAAGGREASEFFIRE"
{ # For each character
1$.@ # (Duplicate message twice)
?:^ # Find first index of character
<n # Extract part before index and add a newline
@^> # Extract part including and after index as new "message"
}/ # (Close loop)
](]^0<= # If last line was successfully matched, select result; else, select input
```
A point raised by Dennis: All GolfScript programs print an automatic final newline. Whether or not this should invalidate my solution as-is, I'm not sure. I believe it would cost 4 characters to suppress the final newline by adding `"":n` somewhere near the end.
[Answer]
### Ruby - 140
```
a="DIEINAGREASEFIRE";n=[4,6,7,13];i=0;o='';s=ARGV[0]
s.chars.each{|c|
if c==a[i]
i+=1;o+="\n";o+="\n"if n-[i]!=n
end
o<<c
}
puts((i<16)?s:o)
```
**No regexes in this one**. It simultaneously walks the characters in the ARGV[0] input, and a string containing characters we need to break on to make our left-column message. Was originally going to stick spaces after the letters that need to have a newline, but found that it was a bit shorter to hardcode the indexes at which to insert the line break.
Once all is said and done, it checks to see that the `i` index has incremented enough times to have gone through every letter that needed breaking. If it hasn't, we just print out the original string. If it has, we give 'em the formatted one.
`n-[i]!=n` was a neat trick to save characters when checking whether or not the current index was one that needed an extra line break (as compared to `n.include? i`). Also saved some characters by using `{}`s instead of `do/end` despite being a multiline block, and used a ternary condition on the final puts to save characters when determining which one to output.
Not the shortest, but I thought it would be neat to do without regular expressions.
[Answer]
# JavaScript 116
Javascript implementation of m-buettner's idea
```
console.log((RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z=prompt())||[,z]).slice(1).join('\n'))
```
**Test** snippet
```
z="Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. Right where we always seem to end up these days. Every single project. It's becoming unbearable.";
T1.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')
z='From that FIFA point on'
T2.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')
```
```
pre { border: 1px solid black }
```
```
T1<pre id=T1></pre>
T2 (the FIFA test)<pre id=T2></pre>
```
[Answer]
## Perl, 184 bytes
Not a spectacular score for Perl, but here is a simple regex solution
```
$_=<>;s/^(D.*) (I.*) (E.*) (I.*) (N.*) (A.*) (G.*) (R.*) (E.*) (A.*) (S.*) (E.*) (F.*) (I.*) (R.*) E/$1\n$2\n$3\n\n$4\n$5\n\n$6\n\n$7\n$8\n$9\n$10\n$11\n$12\n\n$13\n$14\n$15\nE/;print;
```
[Answer]
# Python3 (166 138)
Golfed:
```
s='';o=input()
for n in o.split():s+=[n,'\n'+n.title()][n[0]==("DIEINAGREASEFIRE"*len(o))[s.count('\n')]]+' '
print([o,s][s.count('\n')==16])
```
Ungolfed-ish:
```
format_s = ''
unformat_s = input()
for n in unformat_s.split():
format_s += [n, '\n' + n.title()][n[0] == ("DIEINAGREASEFIRE"*len(unformat_s))[format_s.count('\n')]] + ' '
print([unformat_s, format_s][format_s.count('\n') == 16])
```
Although the use of the lambda pleases me somewhat, that mass number of variables used and the somewhat messy development has the opposite effect. Regex may have been a good idea too. Hay ho, at least it works :).
Edit: replaced lambda variable with `count` builtin, and shortened split statement.
[Answer]
---
# Python3 (165)
```
def c(m,h,l=[]):
if h:s=m.rindex(h[0]);l=[m[s:]]+l;return c(m[:s],h[1:],l)
return[m]+l
i=input()
try:print('\n'.join(c(i,"ERIF ESAERG A NI EID")))
except:print(i)
```
### Ungolfed
```
def headings_remaining(headings): return len(headings) > 0
def head(s): return s[0]
def tail(s): return s[1:]
def prepend(l,e): l.insert(0, e)
def reverse(s): return s[::-1]
def chunk(message,headings,output_list=[]):
if headings_remaining(headings):
split_index = message.rindex(head(headings))
message_init = message[:split_index]
message_last = message[split_index:]
prepend(output_list, message_last)
return chunk(message_init, tail(headings), output_list)
else:
prepend(output_list, message)
return output_list
input_message=input()
try:
headings=reverse("DIE IN A GREASE FIRE")
print('\n'.join(chunk(input_message,headings)))
except ValueError: # Couldn't keep splitting chunks because didn't find heading
print(input_message)
```
### Explanation
`chunk` recursively splits off the end of the message containing the last heading and prepends it to a list.
Caveat: this won't work if there are no spaces at all between two proposed headings in your letter for some reason, but that seems unlikely in a letter to your boss.
[Answer]
**Ruby 115**
```
n,a,c,i=[4,6,7,13],gets,'',0;a.chars{|x|x=='DIEINAGREASEFIRE'[i]?(i+=1;c+="\n"if n-[i]!=n;c+="\n#{x}"):c+=x};puts c
```
**Ruby 95**
```
a,c,i=gets,"",0;a.chars{|x|x=="DIEINAGREASEFIRE"[i]?(i+=1;c+="\n#{x}"):(c+=x)};puts c
```
[Answer]
# J - ~~110~~ 103 bytes
Why doesn't J have good functions to handle strings, but only array functions? I'll revise this if I figure out something smart.
Edit: Shortened and fixed output (it had extra spaces before) and checking. I also improved the explanation.
```
f=:[:>,&.>/@('IEIINAAGGREASEFFIRE'&t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])`]@.(0=#@[))@< ::]
```
### Explanation:
>
> I'll denote function usage as `[<left argument>] <function name> <right argument>`, e.g. `f <text>`. I also won't explain every detail because the function is quite long.
>
>
> `@` applies the right function to the left function, eg. `f@g x == f(g(x))`
>
>
> `t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])']@.(0=#@[)` is a recursive function `<delimiters> t <boxed string>` that splits the string with every delimiter, in order. Fails if some delimiter is not found.
>
>
> `(((0{I.@E.)({.;LF;}.)])>@{:)` splits the string from the left side of the delimiter, adding a linefeed between them.
>
>
> `>@{:` gets the last string from a list (the one which hasn't been split yet)
>
>
> `0{I.@E.` gets the index to split at, failing if the delimiter doesn't exist.
>
>
> `{.;LF;}.` concatenates left side of the split, linefeed and right side of the split
>
>
> `}:@],` concatenates results of the earlier splits and the result of the last function (last meaning: look up)
>
>
> `']@.(0=#@[)` checks if there's any delimiters left, and calls the function described above (5 lines) if there is. Otherwise returns.
>
>
> `'IEIINAAGGREASEFFIRE'&` sets the left argument of `t` to that string
>
>
> `[:>,&.>/@` joins the results of splitting
>
>
> `::]` if something fails (I made the search for the split index the weak point), return the original string.
>
>
>
### Examples (too long?):
```
f 'Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I''m saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance lev...
Dear Boss, how are things?
It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
Every last bit of it.
Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
Not that I think I should stand without blame. Not at all.
All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.
Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
Remember the Flakenhauser contract?
Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
Still, I - alone - took blame for it.
Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.
From that point on,
I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments.
Right where we always seem to end up these days.
Every single project. It's becoming unbearable.
f 'Die in a grease fire. It''s fun. Every time.'
Die in a grease fire. It's fun. Every time.
f 'hai'
hai
```
[Answer]
# JavaScript (ES6), ~~93~~ 115 bytes
```
alert(prompt(x=[...'DIEI1NA1G1REASEF1IRE',i=0]).replace(/\b./g,a=>i<20&&a.match(x[i])?(+x[++i]?i++&&`
`:`
`)+a:a))
```
I used `replace` to step through the string, with a match for `/\b./g` so as to only find characters that either followed a space or began the string. Then I checked each character to see if it matched the current index in the array I was looking for, and added a newline before it if it did, and incremented `i`.
EDIT:
Missed the need to create newlines between words. I've done that now, which brings it up to 115.
[Answer]
**PHP, 328 bytes**
Given a file named 'G' containing the raw text to "enmessage"
```
<?php
$a=implode(file("G"));$b=str_split('DIEINAGREASEFIRE');foreach(array_unique($b) as $c){foreach(str_split($a) as $h=>$d){if($c==$d)$l[$c][]=$h;}}$e=-1;$n=$a;foreach($b as $f=>$c){foreach($l as $j=>$m){if($c==$j){foreach($m as $k=>$h){if($h>$e){$n=substr($n,0,$h)."\n".$c.substr($a,$h+1);$e=$h+2;break 2;}}}}}echo nl2br($n);
```
Explanation (~ungolfed && commented code) :
```
<?php
$string=implode(file("G")); // raw text to deal with
$msg=str_split('DIEINAGREASEFIRE'); // hidden message (make it an array)
// 2D array : [letters of the message][corresponding positions in txt]
foreach(array_unique($msg) as $letter) {
foreach (str_split($string) as $pos=>$let) {
if ($letter==$let) $l[$letter][]=$pos; //1 array per seeked letter with its positions in the string
}
}
$currentPos=-1;
$newString=$string;
foreach ($msg as $key=>$letter) { // deal with each letter of the desired message to pass
foreach($l as $cap=>$arrPos) {// search in letters list with their positions
if($letter==$cap) { // array of the current parsed letter of the message
foreach($arrPos as $kk=>$pos) { // see every position
if ($pos>$currentPos) { // ok, use the letter at that position
$newString=substr($newString,0,$pos)."\n".$letter.substr($string,$pos+1); // add line break
$currentPos=$pos+2; // take new characters into account (\n)
break 2; // parse next letter of the message
}
}
}
}
} /* (note that I could have added some other (random) line breaks management, so that
* the message is not TOO obvious... !*/
echo nl2br($newString);
```
[Answer]
# PHP, 136 bytes
```
for($f=" ".join(file(F));$c=DIEINAGREASEFIRE[$i++];){while(($p=strpos($f,$c,$p))&&$f[$p-1]>" ");$p?$f[$p-1]="\n":$i=20;}echo$i<20?$f:"";
```
if the whole insult can be put; prints the modified string with a leading space or linebreak; empty output if not.
Run with `-r`.
**breakdown**
```
for($f=" ".join(file(F)); // read input from file "F"
$c=DIEINAGREASEFIRE[$i++];) // loop through insult characters:
{
while(($p=strpos($f,$c,$p)) // find next position of $c
&&$f[$p-1]>" "); // ... preceded by a space
$p?$f[$p-1]="\n" // if found, replace the space with a newline
:$i=20; // else break the loop
}
echo$i<20?$f // if modified text has the full insult, print it
:""; // else print nothing
```
[Answer]
# [Zsh](https://www.zsh.org/) + [`sed`](https://www.gnu.org/software/sed/manual/sed.html#Top), ~~167~~ ... 158 bytes
```
cp a z;b=DIE_IN_A_GREASE_FIRE
for c (${(s::)b}){sed -i "$ s/ $c/ \n$c/" a
((##$b[j++]==95))&&sed -i '$ i\\' a}
$b()<a;`<a|cut -c -1|sed 's/^$/_/g'|rs -g0`||<z
```
[Try it Online!](https://tio.run/##VZRBc9s2EIXv/hU7iSaSJpbUHnqoY9fjTOQML8mMc6xbZUlBJCwS4GBBKXKU3@6@BeQ4vUgkuHjY/fYtHqV5urxcfr79i88@GA703oucU@P3xMFQbKyr5ZqKSA0LVb7DmqfuQByjcdF6hxiOVFAwlbE7syZuW6wZKltG9MaH9NZZabinliXSbbBrPszpk4/0MGAhBfCDDzYeyG/IxjktdyYccnxp4/NqIfijffCuTtI5H01zmxNRqWAkbdDnaLijvUEt@NgalbOOeg5Rw3rvxJatuaabTTRBcz9PBYj9pgqD5L3W7XyrxW2C75JubeKs9rmGE4GcRUHS@KFdk0R2a9rbiNeYaeRwBOOIOd3gnGLckfABlMmKKsgFFNYJcYky5qoLDg2HtT7brg9@Z9AJp/qxBcYbHFMQynxZpMhb1fxZom2Bdk4fjTMBhx9IepNCzvPWBNtv@ZASft6@GZDi/zUydfS/0ubLnN6jOE7wNHvohqSKLokxnUAeqKjzyU3stDojJuwA4850pitNNshty1vjGh7wUSuJAUdcZxskG6ITLgLN3mXTcKlc4UrpvEfOePJOySj8hgGp8b0Btc@BxD8npAaNtLEhsYWVsC3LZe@8uK6zbojm2VU6B7Qx4MFqnty9Xz3GdTAQT@E266ailaR6lOEdIAe4yq61kkRDWt/3B@pbdk5rVLhWOnZcQwzo/RAqA8xfolVvFjSDebTOGUT99pcpOw2NDqQf6kaNyHZNzmd6SNSda@eib@EBVxmMw860eUJzv1/GNmkziAXrMQSnhI2bY3jTBKDK3luseqdZJd7Ak2p3uApEOBxS3e2eD5JMHPcWpwKMuvn8NPqejFTcG5IqDNG6k6El19vo9O1Nuoy4ZosEClDrLToD@jqqyYy4mfoWV0yHREHrztYNevBzd85B@58OhP7Qaz1iCDeRPN82AgitIYzYg6mSP8aCMYS40hlciRuScV3Mz3BjPlU9CD2@K68@FMtV8Wl1s/p4t7z5slzdFnfLM8Va0WT0fSIXF9Pyx/S7oKMzS69GJAsaVQu6d/h9RXw2mbx@PSr/fnj79p@rqz//mE7fvDkFj0dk7@/HxD/ORuVkesnvvl7ysYLxZxXNfj9q2FgW/44Wq0U9PgahWf3b1@Px8vHp6T8)
The long email one-liner is stored in file `a`. Using `sed -i '$ <blah>'` always edits the *last line* of `a`. The last line `$` is incrementally reduced as we insert `\n` characters.
Cut out quite a few bytes in the early versions of this solution. Added ~50 bytes for the 'original string' requirement. Ignored the STDIN thing per meta consensus.
Could be a lot shorter ([101 bytes](https://tio.run/##VZRBb9s4EIXv@RWDIkATIHa718TbwEWdQpcWSK976EgeS4wlUuBQ9iqb/e3ZN6TddC@JTZOP8755w2ftXlerzfeHT3zxRTjS56B6Q104Ekeh1Dnf6j1ViTpWasKAtUDDTJyS@OSCxx5OVFGURtxBtsR9jzWhumfs3oWYvw1OOx6pZ030EN2W5yV9C4meJizkDfwUokszhR25tKTNQeJc9tcunVcrxT86xuDbLF3qsTL3pRCTiqL5gH1OwgMdBV7wYy8m5zyNHJNtG4NXV/dyT@tdkmi132QD6v42hUnLWecPoTdzuxiGrNtKWrSheDgRKFVUpF2Y@i1pYr@lo0v4mgqNsh2bccWS1rinej@Q8gzK5NQU9BYK24y4ho2l6YJDx3Frn90wxnAQdMKbfuqBcY1rKoLNt0VKvDfNXxZdD7RL@ipeIi6fSUfJW27K0Qw77HnOBZ@P7yaU@H@NQh39b6z5uqTPMMcZnlUP3ZhV0SUVGRTyQEVDyGlib@5EJR4A41EGGWopAXnoeS@@4wk/mpMUccV9iUGOITrhE9AcfQkN18YVqdQhBNSMT8EbGYPfMSB1YRRQ@x5Jw7kgC2iinYuZLaKEY0WuZOctdYPzU5JzqmwOaCfgwRae0r3fM8ZtFIjn7a7oZtNG0jLKyA6QA1zjtuYk09A@jONMY8/em0eD63Rgzy3EgD5MsRFg/pGcZbOiBcJjPhcQDfvfpuw0NDaQYWo7CyK7LflQ6KFQf2OdS6FHBnwjGIeD9GVCS7/fxjZrM4hFFzAEp4LFLzG8eQLgcgwOq8FbVZk38GTvHk@BKsc5@@6PPGsOcTo63Aowluab0@gHEm14FNImTsn5U6C1@O1s@o6SHyNu2aGACtRGh86Avo1qDiNeprHHEzOgUNB6dG2HHvw6XWqw/ucLoT@N5keF8BLp@bVRQOiFMGJP0uR8vFeMIcSNzuRrvJCM52J5gRfztRlB6Pmu/vNLtam@rb8@btY/Ng/V4@bOkDZ0dfnPld7eXtf/XiuauXD07pL0A102H@gvj7/viC8u66vrFd/9XPFLgzgvGlr88RKVFu3Hny8vq@fX1/8A)) if we ignore the requirement for extra line breaks
```
cp a z;b=DIEINAGREASEFIRE;for c (${(s::)b})sed -i "$ s/ $c/ \n$c/" a
$b()<a;`<a|cut -c -1|rs -g0`||<z
```
Old versions that don't fully meet the requirements:
~~[106 bytes](https://tio.run/##VZRBb9s4EIXv@RWD1mgS1HFPe9hssoGLOoUuLZAeN4tgJI8txhIpcCh7tUV/e/YNaTfdiy1Rw8eZb97wX21fbm5WX@//5LNPwpE@BtU5teFAHIVS6/xW76hK1LJSE3qsBeon4pTEJxc8YjhRRVEacXtZE3cd1oTqjhG9CTG/9U5bHqhjTXQf3ZqnBX0JiZ5HLOQAfg7RpYnChlxa0GovcSrxtUun1UrxR4cY/DZLl3wszV1JxKSiaN5gz0m4p4OgFnzsxOScp4FjsrAheHV1J3e03CSJlvs8F6DuH1MYtex1fh86K24TQ591t5KutqHUcCRQsqhI2zB2a9LEfk0Hl/CaCo0SjmAcsaAlzqnOe1KeQJmcmoJeQ2GdEdcoY2G64NByXNuz64cY9oJOeNNPHTAucUxFKPN1kRLvTPNnia4D2gV9Fi8Rh0@kg@SQedmaYYcdTznh0/bNiBT/r1Goo/@NNV8X9BHFcYZn2UM3ZlV0SUV6hTxQUR@ym9hbdaIS94DxIL30tRSD3He8E9/yiI9WSYo44q7YINsQnfAJaA6@mIZr4wpXah8CcsZT8EbG4LcMSG0YBNS@RtJwSsgMmmjjYmYLK2FbkSveeXVd7/yY5OQqmwPaCHiwmad071eP8TYKxHO4K7q5aCNpHmV4B8gBrnFrqyTT0C4Mw0RDx95bjQbXac@etxAD@jDGRoD5W3LmzYquYB6r8wqiYffLlB2HxgYyjNvWjMhuTT4UekjUz61zKXTwgG8E47CXrkxo6ffr2GZtBrHoAobgmLD4BYY3TwCqHILDavCWVeYNPLl2j6tAleOU6@4OPGk2cTo4nAow5ub5cfQDiTY8CGkTx@T80dBa6m1t@g6SLyPeskMCFagNDp0BfRvVbEbcTEOHK6ZHoqD14LYtevBzd8nB@p8PhP44WD0qhJtIT7eNAkInhBF7lib741wxhhA3OqOvcUMyrovFGW7Ml/r2U7V6qr48LZ8@P6yW31ZP99XD6sx4NnQx@36h19eX9Y/L74pWXjl6MyP9QLPmAz16/L4hPru4ePt2Vv/1/P7937e3v/92efnu3TH4fEbu8fGc@McfN/zy8h8)~~
~~[115 bytes](https://tio.run/##VZRBbxs5DIXv@RVEazQ26rjYwx42m2zgok4xlxZIj00R0GPao3hGGogae2eL/vb0UXKa7sm2LD3xfXzUf9o8XV2tPt/@w2cfhCO9D6pzasKROAqlxvmd3lCVqGGlOnRYC9SNxCmJTy547OFEFUWpxR1kQ9y2WBNat4zd2xDzr85pwz21rIluo9vwuKBPIdHjgIW8gR9DdGmksCWXFrQ6SBzL/rVLz6uV4oOOMfhdli71WJn7UohJRdF8wL4n4Y6OAi/4sxWTc556jsm29cGrW7dyQ8ttkmi1z7MBdf@awqDlrPOH0Jq5bQxd1t1JutiF4uFEoFRRkTZhaDekif2Gji7hZyo0ynZsxhULWuKe6rwj5RGUyakp6CUUNhnxGjYWpgsODceNfXddH8NB0Alv@qkFxiWuqQg2XxYp8d40f1l0LdAu6KN4ibh8JO0lb5mXoxl22POYC34@vh1Q4v81CnX0v7bm64LewxxneFY9dGNWRZdUpFPIAxV1IaeJvbkTlXgAjDvppFtLCchty3vxDQ/405ykiCtuSgxyDNEJn4Dm6EtoeG1ckUrtQkDN@Ba8kTH4DQNSE3oBtc@RNDwXZAFNtHUxs0WUcKzIley8pK5zfkjynCqbA9oKeLCFp3Tv94zxLgrE83ZXdLNpI2kZZWQHyAGudhtzkmloG/p@pL5l782jwXXasecdxIA@DLEWYP6SnGWzoguEx3xeQDTsf5uy09DYQIZh11gQ2W3Ih0IPhfq5dS6FFhnwtWAcDtKWCS39fhnbrM0gFl3AEJwKFr/A8OYJgMs@OKwGb1Vl3sCTvXs8Baocx@y7PfKoOcTp6HArwFia56fRDyRacy@kdRyS86dAa/Hb2PQdJT9GvGOHAipQ6x06A/o2qjmMeJn6Fk9Mh0JB687tGvTg1@lSg/U/Xwj9oTc/KoSXSJ9fGwWEVggj9ih1zse5YgwhbnQGv8YLyXguFmd4MZ/W1x@q1UP16WH58PFutfyyerit7lZnxrOm6eT7VC8vZ@sfs@@KVl6sHL2akL6bfl3cfJvRpH53/wfde3y@Ij6bTl@/nqy/Pr59@@36@q8/Z7M3b/IpR@cTcvd0Tvzj7yt@evoJ)~~
~~[146 bytes](https://tio.run/##VZRBb9s4EIXv/hWDbpDYqO0ihz1sNmngok6hSwukx7ZIR9LYYiyRAknZUYv@9uwb0m66J0nU8HHmmzf8EZrn6@v1p7u3PHkv7OmdC2FOjTsQe6HYGLsNt1REajhQ5TqsOepG4hjFRuMsYjhSQV4qMXupidsWa0Jly4jeOJ@@OhMa7qnlEOnOm5rHJX10kR4HLKQAfnTexJHchkxc0novfszxpYmn1SLgQQfv7DZJ53w0zV1ORKW8hLRB36NwRwdBLfjZisoZSz37qGG9s8GUrdzSahPFa@7zVEAwT6owhLzX2L1rtbiNd13S3UpcbF2u4UggZ1FQaNzQ1hQi25oOJuIzZho5HME4YkkrnFNcdBR4BGUyQRXCFRTqhLhEGUvVBYeGfa3vpuu92ws6YVU/tsC4wjEFocyXRYq8U83fJZoWaJf0Qax4HD5S6CWFzPPWBNvteEwJn7ZvBqT4f41MHf2vtPlhSe9QHCd4mj10fVJFl4JIFyAPVNS55Ca2Wp0E8XvAuJdOulKyQe5a3olteMBPrSR6HHGbbZBsiE7YCDQHm03DpXKFK0PnHHLGm7NKRuE3DEiN6wXUPnkK7pSQGjTSxvjEFlbCtiyXvfPius7YIcrJVToHtBHwYDVP7t6fHuOtF4incJN1U9FKUj3K8A6QA1xlaq0k0Qit6/uR@pat1RoVrgkdW95CDOjd4CsB5s/RqDcLWsA8WucCom73x5Qdh0YH0g3bRo3IpibrMj0kaufauehaeMBWgnHYS5snNPf7ZWyTNoOYNw5DcExY7BLDmyYAVfbOYNVZzSrxBp5Uu8VVEAL7MdXdHngMycTxYHAqwKib58fRdySh4l4oVH6Ixh4NHXK9jU7fQdJlxFs2SKAAtd6gM6Cvo5rMiJupb3HFdEgUtO7NtkEPfu/OOWj/04HQH3qtJwjhJgqn2yYAQiuEEXuUKvnjImAMIa50BlvihmRcF8sJbszn8uZ9sX4oPj6sHj7cr1ef1w93xf16ojwrmp79nIarq1n5a/YzoJWLtaFX4c30y/L224zOqjdfL@mrxfMV8WQ6/X6oaNFe8/e3l7PZ@XkjjC2XxOfnabOhi8v6ApFPN2fll8fXr7/9O53@9XRz88/fGi5V435Nrvn5@T8)~~
~~[153 bytes](https://tio.run/##VZRBb9s4EIXv/hWDbpDYqOPChz1sNmngok6hSwukx7ZIx/LYYiKRAoey4xb97dk3pNN0T5Ko4ePMN2/4Q5uny8vlp5u3PHovHOldUJ1SE/bEUSg1zm/1mqpEDSvVocNaoO5AnJL45IJHDCeqKEotbidr4rbFmtCqZURvQsxfndOGe2pZE91Et@bDjD6GRPcDFnIA34fo0oHChlya0XIn8VDiVy49r1aKB@1j8NssXfKxNB9KIiYVRfMGe0/CHe0FteBnKybnPPUck4X1watbtXJNi02SaLlPcwHqHk1h0LLX@V1orbhNDF3W3Uo634ZSw5FAyaIibcLQrkkT@zXtXcJnKjRKOIJxxIwWOKc660j5AMrk1BT0AgrrjHiFMmamCw4Nx7W9u66PYSfohDf91ALjAsdUhDJfFinxg2n@LtG1QDujD@Il4vADaS85ZFq2ZtjhgQ854eftmwEp/l@jUEf/a2u@zugdiuMMz7KHbsyq6JKKdAp5oKIuZDext@pEJe4A41Y66VZSDHLT8oP4hgf8tEpSxBHXxQbZhuiET0Cz98U0vDKucKV2ISBnvAVvZAx@w4DUhF5A7VMkDc8JmUETbVzMbGElbCtyxTsvruucH5I8u8rmgDYCHmzmKd3702O8jQLxHO6Kbi7aSJpHGd4BcoCr3doqyTS0DX1/oL5l761Gg@u0Y89biAF9GGItwPw5OfNmRecwj9V5DtHw8MeUHYfGBjIM28aMyG5NPhR6SNRPrXMptPCArwXjsJO2TGjp98vYZm0GsegChuCYsPgZhjdPAKrsg8Nq8JZV5g08uXaPq0CV4yHX3e75oNnEae9wKsCYm6fH0Q8kWnMvpHUckvNHQ2upt7Hp20u@jHjLDglUoNY7dAb0bVSzGXEz9S2umA6Jgtat2zbowe/dJQfrfz4Q@kNv9agQbiJ9vm0UEFohjNi91NkfZ4oxhLjRGfwKNyTjupiNcGM@ra7eV8u76uPd4u7D7XLxeXl3U90uR8azpvHJz7FeXExWvyY/Fa08Xzp6pW/GX2bX3yZ0Ur/5OqevHs9XxCPFhHzf13QOd33/dzw@mb@dTyanp40wds6JT0@zhqOz@foMGx6vTlZf7l@//obgvx6vrv7528KlbsKv0SU/Pf0H)~~
~~[167 bytes](https://tio.run/##VZRBb9s4EIXv@RWDbuA4QOzChz00TRq4qFPo0gLpcVOkY3lsMZZIgUPZ623727NvSKdpT5Io8nHmmzfznzZPV1eLz7fv@OSDcKT3QfWCmrAnjkKpcX6jN1QlalipDh3WAnUH4pTEJxc89nCiiqLU4nayIm5brAktW8budYj5q3PacE8ta6Lb6FZ8mNKnkOhxwELewI8hunSgsCaXprTYSTyU/UuXnlcrxYP2MfhNli7xWJjbEohJRdF8wN6TcEd7QS742YrJOU89x2Tb@uDVLVu5ofk6SbTYL3IC6v41hUHLWed3obXk1jF0WXcjabIJJYcjgRJFRdqEoV2RJvYr2ruEz1RolO3YjCumNMc91VlHygdQJqemoJdQWGXES6QxNV1waDiu7N11fQw7QSW86acWGOe4piKk@bJIibem@StF1wLtlD6Kl4jLD6S95C0X5WiGHbZ8yAE/H18PCPFPjUId9a@t@Dql90iOMzyLHroxq6JKKtIp5IGKupDdxN6yE5W4A4w76aRbSjHIbctb8Q0P@GmZpIgrbooNsg1RCZ@AZu@LaXhpXOFK7UJAzHgL3sgY/IYBqQm9gNrnSBqeAzKDJlq7mNnCSjhW5Ip3XlzXOT8keXaV9QGtBTzYzFOq97vHeBMF4nm7K7o5aSNpHmV4B8gBrnYryyTT0Db0/YH6lr23HA2u0449byAG9GGItQDzl@TMmxVNYB7LcwLRsP2ty45NYw0Zhk1jRmS3Ih8KPQTqL6xyKbTwgK8F7bCTtnRoqfdL22ZtBrHoAprgGLD4KZo3dwCy7IPDavAWVeYNPDl3j1GgyvGQ8273fNBs4rR3uBVgzM0Xx9YPJFpzL6R1HJLzR0Nrybex7ttLHka8YYcAKlDrHSoD@taq2YyYTH2LEdMhUNC6c5sGNfh1usRg9c8XQn/oLR8VwiTS52mjgNAKocUepc7@OFO0IcSNzuCXmJCMcTE9wcR8Wl5/qBYP1aeH@cPHu8X8y@LhtrpbnBjPmsan38d6eXm@/Hk@Hv9VX1@/@fv8fDTaXt/f@x8/viuqO3E0WdArfT3@Z3rz9ZxO69f3M7r3eL4ifqtom2/7miaw3Le34/Hp7N3MJBphnJ0Rj0ZHlbPZ6sw@rfXSmk63o9Hg7fj258kVPz39Dw "Zsh – Try It Online")~~
[Answer]
**Python - 190 Bytes**
```
l,r="IExINxAxGREASExFIRE","\n";k=p=raw_input();y=i=0
for c in l:
if c!="x":
h=len(p);x=p[y:h].find(c)
if x==-1:i+=1
p=p[0:x+y-1]+r+p[x+y:h];y=x+y;r="\n"
else:r=r+r
if i!=0:p=k
```
**Ungolfed**
This is my first golf attempt :) Looking to learn some great coding techniques, regardless, I just focused on using find and then some string splicing to find the appropriate characters and format the output.
Variables -
l.r = l is assigned characters we will be using as our guide to create our new formatted paragraph. r is assigned the new line character for us in spacing the new output.
k,p = The input paragraph. K is used to revert to the original as it is not reassigned during execution of the script. I check against x to know when to add a double new line for spacing purposes.
y,i = y is a "cursor" of sorts, keeps track of the last position a character was found so we find through the paragraph correctly for splicing purposes, i is sanity check, if we don't hit all of our characters we revert the paragraph (p variable) to it's original input via the k variable.
h = Input length, which we use in splicing.
x = The position of the current character represented by C, used for splicing as well.
c = Characters in l to iterate and search for.
The following code is reworded and broken out from the original code for readability to as what is happening:
```
letters,return="IExINxAxGREASExFIRE","\n"
input1=input2=raw_input()
lastpos=sanity=0
for char in letters:
if char != "x":
inputlength=len(input1)
charposition=input1[lastpos:inputlength].find(char)
if charposition==-1:
sanity+=1
input1=input1[0:position+lastpos-1]+return+input1[position+lastpos:inputlength]
lastpos=position+lastpos
return="\n"
else:return=return+return
if sanity!=0:
input1=input2
```
I would appreciate your feedback! I am looking to learn.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 6 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Your challenge: Make a Christmas tree. The size must be choosable by some input method, but doesn't have to be directly related to any part of the tree; however, larger inputs should produce a larger tree.
How can you make it? You can make the tree any way you like, other than by printing the [unicode character for the tree](http://www.fileformat.info/info/unicode/char/1f384/index.htm), such as ouputting an image, ascii art, with other aspects, etc. Whatever you do, remember that this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so be creative.
The answer with the most upvotes by the end of December wins, but I'll accept another if it gets higher
[Answer]
## Python
A fractal Christmas tree using the turtle package:
![enter image description here](https://i.stack.imgur.com/td3NW.png)
```
n = input()*1.
from turtle import *
speed("fastest")
left(90)
forward(3*n)
color("orange", "yellow")
begin_fill()
left(126)
for i in range(5):
forward(n/5)
right(144)
forward(n/5)
left(72)
end_fill()
right(126)
color("dark green")
backward(n*4.8)
def tree(d, s):
if d <= 0: return
forward(s)
tree(d-1, s*.8)
right(120)
tree(d-3, s*.5)
right(120)
tree(d-3, s*.5)
right(120)
backward(s)
tree(15, n)
backward(n/2)
import time
time.sleep(60)
```
n is the size parameter, the shown tree is for n=50. Takes a minute or two to draw.
[Answer]
### JavaScript
![enter image description here](https://i.stack.imgur.com/26fx3.png)
Show the animated tree [online](http://jsfiddle.net/62eaL/1/).
```
var size = 400;
var canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var p3d = [];
var p = [Math.random(), Math.random(), Math.random(), 0];
for (var i = 0; i < 100000; i++) {
p3d.push([p[0],p[1],p[2],p[3]]);
var t = Math.random();
if (t<0.4) {
_y = 0.4 * p[1];
_x = 0.1 * p[0];
_z = 0.6 * p[2];
var r = Math.floor(3*t/0.4)/3.0;
var rc = Math.cos(Math.PI*2.0*r);
var rs = Math.sin(Math.PI*2.0*r);
p[1] = _x+0.1*r+0.5*_y*_y;
p[0] = _y*rc+_z*rs;
p[2] = _z*rc-_y*rs;
p[3] = 0.2*t + 0.8*p[3];
} else {
p[1] = 0.2 + 0.8*p[1];
p[0] = 0.8 * p[0];
p[2] = 0.8 * p[2];
p[3] = 0.2 + 0.8*p[3];
}
}
var rot = 0.0;
function render() {
rot = rot + 0.1;
var rc = Math.cos(rot);
var rs = Math.sin(rot);
ctx.strokeStyle='#FF7F00';
ctx.lineWidth=2;
ctx.beginPath();
ctx.moveTo(size/2,size/8);
ctx.lineTo(size/2,size*15/16);
ctx.stroke();
var img = ctx.getImageData(0, 0, size, size);
for (var j = 0; j < size*size; j++) {
img.data[4*j+0] = 0.5*img.data[4*j+0];
img.data[4*j+1] = 0.5*img.data[4*j+1];
img.data[4*j+2] = 0.5*img.data[4*j+2];
img.data[4*j+3] = 255;
}
for (var i = 0; i < p3d.length; i++) {
var px = p3d[i][0];
var py = 0.5 - p3d[i][1];
var pz = p3d[i][2];
var col = Math.floor(128.0*p3d[i][3]);
var _x = rc*px + rs*pz;
var _z = rc*pz - rs*px;
var z = 3.0 * size / (_z + 4.0);
var x = size / 2 + Math.round(_x * z);
var y = size / 2 + Math.round(py * z);
if(x>=0&&y>=0&&x<size&&y<size) {
img.data[4 * (y * size + x) + 0] = col;
img.data[4 * (y * size + x) + 1] = 128+col;
img.data[4 * (y * size + x) + 2] = col;
img.data[4 * (y * size + x) + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
setInterval(render, 1000 / 30);
```
[Answer]
Yet another *Mathematica / Wolfram Language* tree based on [Vitaliy's answer](https://codegolf.stackexchange.com/a/16358/11224):
```
PD = .5;
s[t_, f_] := t^.6 - f
dt[cl_, ps_, sg_, hf_, dp_, f_, flag_] :=
Module[{sv, basePt},
{PointSize[ps],
sv = s[t, f];
Hue[cl (1 + Sin[.02 t])/2, 1, .3 + sg .3 Sin[hf sv]],
basePt = {-sg s[t, f] Sin[sv], -sg s[t, f] Cos[sv], dp + sv};
Point[basePt],
If[flag,
{Hue[cl (1 + Sin[.1 t])/2, 1, .6 + sg .4 Sin[hf sv]], PointSize[RandomReal[.01]],
Point[basePt + 1/2 RotationTransform[20 sv, {-Cos[sv], Sin[sv], 0}][{Sin[sv], Cos[sv], 0}]]},
{}]
}]
frames = ParallelTable[
Graphics3D[Table[{
dt[1, .01, -1, 1, 0, f, True], dt[.45, .01, 1, 1, 0, f, True],
dt[1, .005, -1, 4, .2, f, False], dt[.45, .005, 1, 4, .2, f, False]},
{t, 0, 200, PD}],
ViewPoint -> Left, BoxRatios -> {1, 1, 1.3},
ViewVertical -> {0, 0, -1},
ViewCenter -> {{0.5, 0.5, 0.5}, {0.5, 0.55}}, Boxed -> False,
PlotRange -> {{-20, 20}, {-20, 20}, {0, 20}}, Background -> Black],
{f, 0, 1, .01}];
Export["tree.gif", frames]
```
![Christmas tree](https://i.stack.imgur.com/OGv5a.gif)
[Answer]
## Javascript
![Output of given code sample](https://i.stack.imgur.com/if6a7.png)
This is my first code golf!
```
var a=40,b=8,c=13,o="<div style='font-family:monospace;text-align:center;color:#094'>",w=1,x=0,y="|#|<br>";for(i=1;i<a;i++){for(j=0;j<w;j++){x%c==0?o+="<span style='color:#D00'>O</span>":o+="+";x++;}i%b==0?w-=4:w+=2;o+="<br>";}document.write(o+"<span style='color:#640'>"+y+y+y+"</span></div>");
```
It comes in at 295 Characters.
The size and decoration of the tree is set by the a,b,c variables:
* a sets the amount of rows in the tree
* b sets the amount of rows between decreases in width (set low for a skinny tree, high for a fat tree). Must be greater than or equal to 3.
* c sets the amount of baubles (set zero for none, 1 for only baubles, higher numbers for less dense placement of baubles)
It looks best when a is a multiple of b, as in the example.
Paste into the console to create a tree. Looks better from far away!
[Answer]
# Javascript
Quasirealistic fully 3D procedural fir tree generator.
Featuring: extensive configuration with even more configuration options present in code; a zigzagy trunk; branching branches; growth animation; rotation of a fully grown tree.
Not featuring: jQuery, Underscore.js or any other library; hardware dependency - only canvas support is required; messy code (at least that was the intention)
**Live page:** <http://fiddle.jshell.net/honnza/NMva7/show/>
**Edit page:** <http://jsfiddle.net/honnza/NMva7/>
**screenshot:**
![fir tree](https://i.stack.imgur.com/kk42Y.png)
**HTML:**
```
<canvas id=c width=200 height=300 style="display:none"></canvas>
<div id=config></div>
```
**Javascript:**
```
var TAU = 2*Math.PI,
deg = TAU/360,
TRUNK_VIEW = {lineWidth:3, strokeStyle: "brown", zIndex: 1},
BRANCH_VIEW = {lineWidth:1, strokeStyle: "green", zIndex: 2},
TRUNK_SPACING = 1.5,
TRUNK_BIAS_STR = -0.5,
TRUNK_SLOPE = 0.25,
BRANCH_LEN = 1,
BRANCH_P = 0.01,
MIN_SLOPE = -5*deg,
MAX_SLOPE = 20*deg,
INIT_SLOPE = 10*deg,
MAX_D_SLOPE = 5*deg,
DIR_KEEP_BIAS = 10,
GROWTH_MSPF = 10, //ms per frame
GROWTH_TPF = 10, //ticks per frame
ROTATE_MSPF = 10,
ROTATE_RPF = 1*deg; //radians per frame
var configurables = [
// {key: "TRUNK_SPACING", name: "Branch spacing", widget: "number",
// description: "Distance between main branches on the trunk, in pixels"},
{key: "TRUNK_BIAS_STR", name: "Branch distribution", widget: "number",
description: "Angular distribution between nearby branches. High values tend towards one-sided trees, highly negative values tend towards planar trees. Zero means that branches grow in independent directions."},
{key: "TRUNK_SLOPE", name: "Trunk slope", widget: "number",
description: "Amount of horizontal movement of the trunk while growing"},
{key: "BRANCH_P", name: "Branch frequency", widget: "number",
description: "Branch frequency - if =1/100, a single twig will branch off approximately once per 100 px"},
{key: "MIN_SLOPE", name: "Minimum slope", widget: "number", scale: deg,
description: "Minimum slope of a branch, in degrees"},
{key: "MAX_SLOPE", name: "Maximum slope", widget: "number", scale: deg,
description: "Maximum slope of a branch, in degrees"},
{key: "INIT_SLOPE", name: "Initial slope", widget: "number", scale: deg,
description: "Angle at which branches leave the trunk"},
{key: "DIR_KEEP_BIAS", name: "Directional inertia", widget: "number",
description: "Tendency of twigs to keep their horizontal direction"},
{get: function(){return maxY}, set: setCanvasSize, name: "Tree height",
widget:"number"}
];
var config = document.getElementById("config"),
canvas = document.getElementById("c"),
maxX = canvas.width/2,
maxY = canvas.height,
canvasRatio = canvas.width / canvas.height,
c;
function setCanvasSize(height){
if(height === 'undefined') return maxY;
maxY = canvas.height = height;
canvas.width = height * canvasRatio;
maxX = canvas.width/2;
x}
var nodes = [{x:0, y:0, z:0, dir:'up', isEnd:true}], buds = [nodes[0]],
branches = [],
branch,
trunkDirBias = {x:0, z:0};
////////////////////////////////////////////////////////////////////////////////
configurables.forEach(function(el){
var widget;
switch(el.widget){
case 'number':
widget = document.createElement("input");
if(el.key){
widget.value = window[el.key] / (el.scale||1);
el.set = function(value){window[el.key]=value * (el.scale||1)};
}else{
widget.value = el.get();
}
widget.onblur = function(){
el.set(+widget.value);
};
break;
default: throw "unknown widget type";
}
var p = document.createElement("p");
p.textContent = el.name + ": ";
p.appendChild(widget);
p.title = el.description;
config.appendChild(p);
});
var button = document.createElement("input");
button.type = "button";
button.value = "grow";
button.onclick = function(){
button.value = "stop";
button.onclick = function(){clearInterval(interval)};
config.style.display="none";
canvas.style.display="";
c=canvas.getContext("2d");
c.translate(maxX, maxY);
c.scale(1, -1);
interval = setInterval(grow, GROWTH_MSPF);
}
document.body.appendChild(button);
function grow(){
for(var tick=0; tick<GROWTH_TPF; tick++){
var budId = 0 | Math.random() * buds.length,
nodeFrom = buds[budId], nodeTo, branch,
dir, slope, bias
if(nodeFrom.dir === 'up' && nodeFrom.isEnd){
nodeFrom.isEnd = false;
rndArg = Math.random()*TAU;
nodeTo = {
x:nodeFrom.x + TRUNK_SPACING * TRUNK_SLOPE * Math.sin(rndArg),
y:nodeFrom.y + TRUNK_SPACING,
z:nodeFrom.z + TRUNK_SPACING * TRUNK_SLOPE * Math.cos(rndArg),
dir:'up', isEnd:true}
if(nodeTo.y > maxY){
console.log("end");
clearInterval(interval);
rotateInit();
return;
}
nodes.push(nodeTo);
buds.push(nodeTo);
branch = {from: nodeFrom, to: nodeTo, view: TRUNK_VIEW};
branches.push(branch);
renderBranch(branch);
}else{ //bud is not a trunk top
if(!(nodeFrom.dir !== 'up' && Math.random() < BRANCH_P)){
buds.splice(buds.indexOf(nodeFrom), 1)
}
nodeFrom.isEnd = false;
if(nodeFrom.dir === 'up'){
bias = {x:trunkDirBias.x * TRUNK_BIAS_STR,
z:trunkDirBias.z * TRUNK_BIAS_STR};
slope = INIT_SLOPE;
}else{
bias = {x:nodeFrom.dir.x * DIR_KEEP_BIAS,
z:nodeFrom.dir.z * DIR_KEEP_BIAS};
slope = nodeFrom.slope;
}
var rndLen = Math.random(),
rndArg = Math.random()*TAU;
dir = {x: rndLen * Math.sin(rndArg) + bias.x,
z: rndLen * Math.cos(rndArg) + bias.z};
var uvFix = 1/Math.sqrt(dir.x*dir.x + dir.z*dir.z);
dir = {x:dir.x*uvFix, z:dir.z*uvFix};
if(nodeFrom.dir === "up") trunkDirBias = dir;
slope += MAX_D_SLOPE * (2*Math.random() - 1);
if(slope > MAX_SLOPE) slope = MAX_SLOPE;
if(slope < MIN_SLOPE) slope = MIN_SLOPE;
var length = BRANCH_LEN * Math.random();
nodeTo = {
x: nodeFrom.x + length * Math.cos(slope) * dir.x,
y: nodeFrom.y + length * Math.sin(slope),
z: nodeFrom.z + length * Math.cos(slope) * dir.z,
dir: dir, slope: slope, isEnd: true
}
//if(Math.abs(nodeTo.x)/maxX + nodeTo.y/maxY > 1) return;
nodes.push(nodeTo);
buds.push(nodeTo);
branch = {from: nodeFrom, to: nodeTo, view: BRANCH_VIEW};
branches.push(branch);
renderBranch(branch);
}// end if-is-trunk
}// end for-tick
}//end func-grow
function rotateInit(){
branches.sort(function(a,b){
return (a.view.zIndex-b.view.zIndex);
});
interval = setInterval(rotate, ROTATE_MSPF);
}
var time = 0;
var view = {x:1, z:0}
function rotate(){
time++;
view = {x: Math.cos(time * ROTATE_RPF),
z: Math.sin(time * ROTATE_RPF)};
c.fillStyle = "white"
c.fillRect(-maxX, 0, 2*maxX, maxY);
branches.forEach(renderBranch);
c.stroke();
c.beginPath();
}
var prevView = null;
function renderBranch(branch){
if(branch.view !== prevView){
c.stroke();
for(k in branch.view) c[k] = branch.view[k];
c.beginPath();
prevView = branch.view;
}
c.moveTo(view.x * branch.from.x + view.z * branch.from.z,
branch.from.y);
c.lineTo(view.x * branch.to.x + view.z * branch.to.z,
branch.to.y);
}
```
[Answer]
# C++
Let's make it in the spirit of IOCCC and have the code in the shape of a tree as well! :D
```
#include <iostream>
using namespace std;
int
main(){
int a
;
cin
>>a;int
w=a*2+5;for
(int x=
0;x<a;++x){
for(int y=2;y>=
0;--y){for(int z=0;
z<a+y-x;++z
){cout<<" ";}for(
int z=0;z<x*2-y*2+5;++z
){cout<<".";}cout
<<endl;}}for(int x=0;
x<w/5+1;++x){for(int z=0;
z<w/3+1;++z){cout<<" ";}for(
int z=0;z<w-(w/3+1)*2;z+=1){cout
<<"#";}cout
<<endl;;;}}
```
Takes an integer as input, and returns a Christmas tree with that many "stack levels". For example, an input of
```
5
```
Returns:
```
.
...
.....
...
.....
.......
.....
.......
.........
.......
.........
...........
.........
...........
.............
###
###
###
###
```
[Answer]
# Bash
Sample output:
![ASCII Xmas tree](https://i.stack.imgur.com/3ONG7.png)
The tree size (i.e. number of lines) is passed on the command line, and is limited to values of 5 or greater. The image above was produced from the command `./xmastree.sh 12`. Here's the source code:
```
#!/bin/bash
declare -a a=('.' '~' "'" 'O' "'" '~' '.' '*')
[[ $# = 0 ]] && s=9 || s=$1
[[ $s -gt 5 ]] || s=5
for (( w=1, r=7, n=1; n<=$s; n++ )) ; do
for (( i=$s-n; i>0; i-- )) ; do
echo -n " "
done
for (( i=1; i<=w; i++ )) ; do
echo -n "${a[r]}"
[[ $r -gt 5 ]] && r=0 || r=$r+1
done
w=$w+2
echo " "
done;
echo " "
```
[Answer]
Disclaimer: this is based on my LaTeX christmas tree, first posted here: <https://tex.stackexchange.com/a/87921/8463>
The following code will generate a chrismtas tree, with random decorations. You can change both the size of the tree, and the random seed to generate a different tree.
To change the seed modify the value inside `\pgfmathsetseed{\year * 6}` to any other numerical value (the default one will generate a new tree every year)
To change the size of the tree modify the `order=10` to be either larger, or smaller depending on the size of the tree you want.
Examples. `order=11`:
![enter image description here](https://i.stack.imgur.com/VQZ0M.png)
`order=8`
![enter image description here](https://i.stack.imgur.com/mQXIo.png)
```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, lindenmayersystems,shapes,decorations,decorations.shapes}
\begin{document}
\def\pointlistleft{}
\def\pointlistright{}
\pgfmathsetseed{\year * 6}
\makeatletter
\pgfdeclarelindenmayersystem{Christmas tree}{
\symbol{C}{\pgfgettransform{\t} \expandafter\g@addto@macro\expandafter\pointlistleft\expandafter{\expandafter{\t}}}
\symbol{c}{\pgfgettransform{\t} \expandafter\g@addto@macro\expandafter\pointlistright\expandafter{\expandafter{\t}}}
\rule{S -> [+++G][---g]TS}
\rule{G -> +H[-G]CL}
\rule{H -> -G[+H]CL}
\rule{g -> +h[-g]cL}
\rule{h -> -g[+h]cL}
\rule{T -> TL}
\rule{L -> [-FFF][+FFF]F}
}
\makeatother
\begin{tikzpicture}[rotate=90]
\draw [color=green!50!black,l-system={Christmas tree,step=4pt,angle=16,axiom=LLLLLLSLFFF,order=10,randomize angle percent=20}] lindenmayer system -- cycle;
\pgfmathdeclarerandomlist{pointsleft}{\pointlistleft}
\pgfmathdeclarerandomlist{pointsright}{\pointlistright}
\pgfmathdeclarerandomlist{colors}{{red}{blue}{yellow}}
\foreach \i in {0,1,...,5}
{
\pgfmathrandomitem{\c}{pointsleft}
\pgfsettransform{\c}
\pgfgettransformentries{\a}{\b}{\c}{\d}{\xx}{\yy}
\pgfmathrandomitem{\c}{pointsright}
\pgfsettransform{\c}
\pgfgettransformentries{\a}{\b}{\c}{\d}{\XX}{\YY}
\pgftransformreset
\pgfmathsetmacro\calcy{min(\yy,\YY)-max((abs(\yy-\YY))/3,25pt)}
\draw[draw=orange!50!black, fill=orange!50, decorate, decoration={shape backgrounds, shape=star, shape sep=3pt, shape size=4pt}, star points=5] (\xx,\yy) .. controls (\xx,\calcy pt) and (\XX,\calcy pt) .. (\XX,\YY);
}
\foreach \i in {0,1,...,15}
{
\pgfmathrandomitem{\c}{pointsleft}
\pgfsettransform{\c}
\pgftransformresetnontranslations
\draw[color=black] (0,0) -- (0,-4pt);
\pgfmathrandomitem{\c}{colors}
\shadedraw[ball color=\c] (0,-8pt) circle [radius=4pt];
}
\foreach \i in {0,1,...,15}
{
\pgfmathrandomitem{\c}{pointsright}
\pgfsettransform{\c}
\pgftransformresetnontranslations
\draw[color=black] (0,0) -- (0,-4pt);
\pgfmathrandomitem{\c}{colors}
\shadedraw[ball color=\c] (0,-8pt) circle [radius=4pt];
}
\end{tikzpicture}
\end{document}
```
[Answer]
# Befunge 93
This is an undecorated tree:
```
&::00p20pv
vp010 <
v p00<
>:0`!#v_" ",1-
v,"/"$<
>10g:2+v
vp01 <
>:0`!#v_" ",1-
v,"\"$<
>91+,00g1-::0`!#v_^
v *2+1g02<
>:0`!#v_"-",1-
v g02$<
>91+,v
v <
>:0`!#v_" ",1-
"||"$ <@,,
```
Sample output, input is 10:
```
/\
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
----------------------
||
```
Let's add some decorations:
```
&::00p20pv
vp010 <
v p00<
>:0`!#v_" ",1-
v,"/"$<
>10g:2+v >"O" v
vp01 < >?v
>:0`!#v_ >?>>" ">,1-
v,"\"$< >?<
>91+,00g1-::0`!#v_^ >"*" ^
v *2+1g02<
>:0`!#v_"-",1-
v g02$<
>91+,v
v <
>:0`!#v_" ",1-
"||"$ <@,,
```
Sample output:
```
/\
/O \
/ \
/ ** \
/ * \
/ ** O\
/* O* * * \
/ O O \
/ * ** O* \
/ *OO * OOO * \
----------------------
||
```
[Answer]
# HTML and CSS
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scalable christmas tree</title>
<style>
body {
background-color: skyblue;
background-size: 11px 11px, 21px 21px, 31px 31px;
background-image: radial-gradient(circle at 5px 5px,white,rgba(255,255,255,0) 1px), radial-gradient(circle at 5px 5px,white,rgba(255,255,255,0) 2px), radial-gradient(circle at 5px 5px,white 1px,skyblue 1px);
}
div {
float: left;
border-style: solid;
border-color: transparent;
border-bottom-color: green;
border-width: 20px;
border-top-width: 0;
border-bottom-width: 30px;
border-bottom-left-radius: 35%;
border-bottom-right-radius: 35%;
box-shadow: red 0 15px 5px -13px;
animation-name: light;
animation-duration: 1s;
animation-direction: alternate;
animation-iteration-count: infinite;
-webkit-animation-name: light;
-webkit-animation-duration: 1s;
-webkit-animation-direction: alternate;
-webkit-animation-iteration-count: infinite;
}
section {
float: left;
}
header {
color: yellow;
font-size: 30px;
text-align: center;
text-shadow: red 0 0 10px;
line-height: .5;
margin-top: 10px;
animation-name: star;
animation-duration: 1.5s;
animation-direction: alternate;
animation-iteration-count: infinite;
-webkit-animation-name: star;
-webkit-animation-duration: 1.5s;
-webkit-animation-direction: alternate;
-webkit-animation-iteration-count: infinite;
}
footer {
float: left;
width: 100%;
height: 20px;
background-image: linear-gradient(to right, transparent 45%, brown 45%, #600 48%, #600 52%, brown 55%, transparent 55%);
}
:target {
display: none;
}
@keyframes star {
from { text-shadow: red 0 0 3px; }
to { text-shadow: red 0 0 30px; }
}
@-webkit-keyframes star {
from { text-shadow: red 0 0 3px; }
to { text-shadow: red 0 0 30px; }
}
@keyframes light {
from { box-shadow: red 0 15px 5px -13px; }
to { box-shadow: blue 0 15px 5px -13px; }
}
@-webkit-keyframes light {
from { box-shadow: red 0 15px 5px -13px; }
to { box-shadow: blue 0 15px 5px -13px; }
}
</style>
</head>
<body>
<section>
<header>★</header>
<div id="0"><div id="1"><div id="2"><div id="3"><div id="4"><div id="5"><div id="6"><div id="7"><div id="8"><div id="9"><div id="10"><div id="11"><div id="12"><div id="13"><div id="14"><div id="15"><div id="16"><div id="17"><div id="18"><div id="19"><div id="20"><div id="21"><div id="22"><div id="23"><div id="24">
</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>
<footer></footer>
</section>
</body>
</html>
```
Sizes between 1 and 25 are supported – just add the size to the URL as fragment identifier.
Works in Chrome, Explorer and Firefox. In Opera is ugly, but the scaling part works.
Sample access:
```
http://localhost/xmas.html#5
```
![christmas tree of size 5](https://i.stack.imgur.com/dlj7F.png)
Sample access:
```
http://localhost/xmas.html#15
```
![christmas tree of size 15](https://i.stack.imgur.com/HnQNh.png)
Live view:
<http://dabblet.com/gist/8026898>
(The live view contains no vendor prefixed CSS and includes links to change the size.)
[Answer]
# Java
```
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* @author Quincunx
*/
public class ChristmasTree {
public static double scale = 1.2;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChristmasTree();
}
});
}
public ChristmasTree() {
try {
URL url = new URL("http://imgs.xkcd.com/comics/tree.png");
BufferedImage img = ImageIO.read(url);
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage result =
new BufferedImage((int)(img.getWidth() * scale),
(int) (img.getHeight() * scale),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) result.getGraphics();
g.drawRenderedImage(img, AffineTransform.getScaleInstance(scale, scale));
JImage image = new JImage(result);
image.setToolTipText("Not only is that terrible in general, but you "
+ "just KNOW Billy's going to open the root present first, "
+ "and then everyone will have to wait while the heap is "
+ "rebuilt.");
frame.add(image);
frame.pack();
frame.setVisible(true);
} catch (IOException ex) {
}
}
class JImage extends JPanel implements MouseListener {
BufferedImage img;
public JImage(){
this(null);
}
public JImage(BufferedImage image){
img = image;
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
addMouseListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, WIDTH, WIDTH, this);
}
public void setImage(BufferedImage image) {
img = image;
repaint();
}
@Override
public void mouseClicked(MouseEvent me) {
System.exit(0);
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
}
}
```
To alter the size, change `scale` to some other double value (keep it around 1 if you want to see anything).
Sample output (for 1.0 as scale, too lazy to take a screenshot, so just posted what it does):
[![enter image description here](https://i.stack.imgur.com/FcXpQ.png)](http://xkcd.com/835/ "Not only is that terrible in general, but you just KNOW Billy's going to open the root present first, and then everyone will have to wait while the heap is rebuilt.")
The program takes this image from the internet, resizes it according to `scale`, then puts it in an undecorated window where it is displayed. Clicking on the window closes the program. Also, the tool tip text is there, but the link is not.
[Answer]
# TI-89 Basic
Just because I wanted to see a Christmas Tree on my calculator. I shall type it here as it appears on my calculator.
```
:tree()
:Prgm
:
:Local size
:Prompt size
:
:Local d,x,y,str,orn
:size→x
:0→y
:{" "," "," "," "," "," "," "," ","°","∫","θ","O","©"}→orn
:size→d
:
:While d≥0
: d-1→d
: ""→str
:
: While x≥0
: str&" "→str
: x-1→x
: EndWhile
:
: str&"/"→str
: 2*y→x
:
: While x>0
: str&elementAt(orn,rand(colDim(list▶mat(orn))))→str
: x-1→x
: EndWhile
:
: str&"\"→str
: Disp str
: y+1→y
: d→x
:EndWhile
:
:""→str
:
:For x,1,2*(size+2)
: str&"-"→str
:EndFor
:Disp str
:
:""→str
:For x,1,size+1
: str&" "→str
:EndFor
:str&"||"→str
:Disp str
:
:EndPrgm
:elementAt(l,i)
:Func
:Local m
:list▶mat(l)→m
:
:Local cd
:colDim(m)→cd
:
:If i>cd or i≤0 Then
: 1/0
:Else
: If i=cd Then
: Return sum(mat▶list(subMat(m,1,i))) - sum(mat▶list(subMat(m,1,i+1)))
: Else
: Return sum(mat▶list(subMat(m,1,i))) - sum(mat▶list(subMat(m,1,i+1)))
: EndIf
:EndIf
:EndFunc
```
This works the same way as my Befunge answer, but I use different ornaments. Yes, my `elementAt` function's repeated uses slows the program down because of many conversions between lists and matrices, but as I wrote it before, I decided against editing it. Also, I learned while typing this answer that `©` makes a comment (I thought it looked like `@`, but that is another character). Never knew what it was before now.
Sample output:
```
size?
7
/\
/ O\
/∫ \
/ © ∫°\
/ θ ∫ ∫\
/° ° © ©\
/O ∫ O ° \
/ θ °© ∫ O θ\
------------------
||
```
I love those `∫`'s; they look like candy canes.
[Answer]
# Wolfram Language ( *Mathematica* )
As discussed at famed Reddit thread: [t\*sin (t) ≈ Christmas tree](http://redd.it/1tswai)
```
PD = .5; s[t_, f_] := t^.6 - f;
dt[cl_, ps_, sg_, hf_, dp_, f_] :=
{PointSize[ps], Hue[cl, 1, .6 + sg .4 Sin[hf s[t, f]]],
Point[{-sg s[t, f] Sin[s[t, f]], -sg s[t, f] Cos[s[t, f]], dp + s[t, f]}]};
frames = ParallelTable[
Graphics3D[Table[{dt[1, .01, -1, 1, 0, f], dt[.45, .01, 1, 1, 0, f],
dt[1, .005, -1, 4, .2, f], dt[.45, .005, 1, 4, .2, f]},
{t, 0, 200, PD}],
ViewPoint -> Left, BoxRatios -> {1, 1, 1.3}, ViewVertical -> {0, 0, -1},
ViewCenter -> {{0.5, 0.5, 0.5}, {0.5, 0.55}}, Boxed -> False, Lighting -> "Neutral",
PlotRange -> {{-20, 20}, {-20, 20}, {0, 20}}, Background -> Black],
{f, 0, 1, .01}];
Export["tree.gif", frames]
```
![enter image description here](https://i.stack.imgur.com/VPbxx.gif)
[Answer]
# Bash with Bc and ImageMagick
```
#!/bin/bash
size="${1:-10}"
width=$(( size*25 ))
height=$(( size*size+size*10 ))
cos=( $( bc -l <<< "for (i=0;i<3.14*2;i+=.05) c(i)*100" ) )
sin=( $( bc -l <<< "for (i=0;i<3.14*2;i+=.05) s(i)*100" ) )
cos=( "${cos[@]%.*}" )
sin=( "${sin[@]%.*}" )
cos=( "${cos[@]/%-/0}" )
sin=( "${sin[@]/%-/0}" )
snow=()
needle=()
decor=()
for ((i=2;i<size+2;i++)); do
for ((j=3;j<=31;j++)); do
(( x=width/2+i*10+cos[62-j]*i*10/100 ))
(( y=i*i+sin[j]*i*5/100 ))
for ((e=0;e<i;e++)); do
needle+=(
-draw "line $x,$y $(( x+RANDOM%i-i/2 )),$(( y+RANDOM%i-i/2 ))"
-draw "line $(( width-x )),$y $(( width-x+RANDOM%i-i/2 )),$(( y+RANDOM%i-i/2 ))"
)
done
(( RANDOM%2 )) && (( x=width-x ))
snow+=(
-draw "circle $x,$(( y-i/2 )) $(( x+i/3 )),$(( y-i/2+i/3 ))"
)
(( RANDOM%10 )) || decor+=(
-fill "rgb($(( RANDOM%5*20+50 )),$(( RANDOM%5*20+50 )),$(( RANDOM%5*20+50 )))"
-draw "circle $x,$(( y+i )) $(( x+i/2 )),$(( y+i+i/2 ))"
)
done
done
flake=()
for ((i=0;i<width*height/100;i++)); do
flake+=(
-draw "point $(( RANDOM%width )),$(( RANDOM%height ))"
)
done
convert \
-size "${width}x$height" \
xc:skyblue \
-stroke white \
-fill white \
"${snow[@]}" \
-blur 5x5 \
"${flake[@]}" \
-stroke brown \
-fill brown \
-draw "polygon $(( width/2 )),0 $(( width/2-size )),$height, $(( width/2+size )),$height" \
-stroke green \
-fill none \
"${needle[@]}" \
-stroke none \
-fill red \
"${decor[@]}" \
x:
```
Sample run:
```
bash-4.1$ ./xmas.sh 5
```
Sample output:
![christmas tree of size 5](https://i.stack.imgur.com/hYSc7.png)
Sample run:
```
bash-4.1$ ./xmas.sh 15
```
Sample output:
![christmas tree of size 15](https://i.stack.imgur.com/ZnCx1.png)
[Answer]
**C**
Sample output for depth=4, zoom=2.0
![Tree](https://i.stack.imgur.com/Iuduv.png)
This answer employs an approach quite different from other answers. It generates a tree structure by recursively branching. Each branch is represented by a set of circles. And finally the main function samples the circles and fill with characters when circles are met. Since it is done by sampling a scene (like ray-tracing), it is intrinsically scalable. The downside is speed, since it traverse the whole tree structure for every "pixel"!
The first command-line argument controls the depth of branching. And the second controls scale (2 means 200%).
```
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define PI 3.14159265359
float sx, sy;
float sdCircle(float px, float py, float r) {
float dx = px - sx, dy = py - sy;
return sqrtf(dx * dx + dy * dy) - r;
}
float opUnion(float d1, float d2) {
return d1 < d2 ? d1 : d2;
}
#define T px + scale * r * cosf(theta), py + scale * r * sin(theta)
float f(float px, float py, float theta, float scale, int n) {
float d = 0.0f;
for (float r = 0.0f; r < 0.8f; r += 0.02f)
d = opUnion(d, sdCircle(T, 0.05f * scale * (0.95f - r)));
if (n > 0)
for (int t = -1; t <= 1; t += 2) {
float tt = theta + t * 1.8f;
float ss = scale * 0.9f;
for (float r = 0.2f; r < 0.8f; r += 0.1f) {
d = opUnion(d, f(T, tt, ss * 0.5f, n - 1));
ss *= 0.8f;
}
}
return d;
}
int ribbon() {
float x = (fmodf(sy, 0.1f) / 0.1f - 0.5f) * 0.5f;
return sx >= x - 0.05f && sx <= x + 0.05f;
}
int main(int argc, char* argv[]) {
int n = argc > 1 ? atoi(argv[1]) : 3;
float zoom = argc > 2 ? atof(argv[2]) : 1.0f;
for (sy = 0.8f; sy > 0.0f; sy -= 0.02f / zoom, putchar('\n'))
for (sx = -0.35f; sx < 0.35f; sx += 0.01f / zoom) {
if (f(0, 0, PI * 0.5f, 1.0f, n) < 0.0f) {
if (sy < 0.1f)
putchar('.');
else {
if (ribbon())
putchar('=');
else
putchar("............................#j&o"[rand() % 32]);
}
}
else
putchar(' ');
}
}
```
[Answer]
# Mathematica ASCII
I really like ASCII art, so I add another very different answer - especially so it's so short in Mathematica:
```
Column[Table[Row[RandomChoice[{"+", ".", "*", "~", "^", "o"}, k]], {k, 1, 35, 2}],
Alignment -> Center]
```
![enter image description here](https://i.stack.imgur.com/HBCvn.png)
And now with a bit more sophistication a scalable dynamic ASCII tree. Watch closely - the tree is also changing - snow sticks to branches then falls ;-)
```
DynamicModule[{atoms, tree, pos, snow, p = .8, sz = 15},
atoms = {
Style["+", White],
Style["*", White],
Style["o", White],
Style[".", Green],
Style["~", Green],
Style["^", Green],
Style["^", Green]
};
pos = Flatten[Table[{m, n}, {m, 18}, {n, 2 m - 1}], 1];
tree = Table[RandomChoice[atoms, k], {k, 1, 35, 2}];
snow = Table[
RotateLeft[ArrayPad[{RandomChoice[atoms[[1 ;; 2]]]}, {0, sz}, " "],
RandomInteger[sz]], {sz + 1}];
Dynamic[Refresh[
Overlay[{
tree[[Sequence @@ RandomChoice[pos]]] = RandomChoice[atoms];
Column[Row /@ tree, Alignment -> Center, Background -> Black],
Grid[
snow =
RotateRight[
RotateLeft[#,
RandomChoice[{(1 - p)/2, p, (1 - p)/2} -> {-1, 0, 1}]] & /@
snow
, {1, 0}]]
}, Alignment -> Center]
, UpdateInterval -> 0, TrackedSymbols -> {}]
]
]
```
![enter image description here](https://i.stack.imgur.com/ArhPo.gif)
[Answer]
I made this for [a challenge on /r/dailyprogrammer](http://www.reddit.com/r/dailyprogrammer/comments/1t0r09/121613_challenge_145_easy_tree_generation/), (not sure if reusing code is against the spirit/rules of this) but:
Brainfuck. Takes as input a number (length of bottom row of leaves) and two characters. One space between each.
Example input: 13 = +
Example output:
```
+
+++
+++++
+++++++
+++++++++
+++++++++++
+++++++++++++
===
```
Code:
```
>
,--
-----
-------
---------
---------[+
+++++++++++++
+++++++++++++++
+++<[>>++++++++++
<<-]>--------------
---------------------
-------------[<+>-]>[<<
+>>-]<,------------------
--------------],>,,>>++++[<
++++++++>-]++++++++++>+<<<<<-
[>>>>>>+>+<<<<<<<--]>>>>>>>[<<<
<<<<++>>>>>>>-]<<<<<<<[>>>>>>[<<<
.>>>>+<-]>[<+>-]<<[<<<.>>>>>+<<-]>>
[<<+>>-]<<<.>>><-<++<<<<<--]>>...>>>-
--[>+<<<<..>>>--]<.>>[<<<.>>>>+<-]<<<<<
...>>>.
```
[Answer]
## Processing
The original fractal Christmas tree. Mouse Y position determines size, use up and down arrow keys to change the number of generations.
```
int size = 500;
int depth = 10;
void setup() {
frameRate(30);
size(size, size, P2D);
}
void draw() {
background(255);
tree(size/2.0, size, 0.0, radians(0), radians(108), (size - mouseY)/3, depth);
tree(size/2.0, size, 0.0, radians(108), radians(0), (size - mouseY)/3, depth);
}
void keyPressed() {
if(keyCode == UP) depth++;
if(keyCode == DOWN) depth--;
depth = max(depth, 1);
}
void tree(float posX, float posY, float angle, float forkRight, float forkLeft, float length, int generation) {
if (generation > 0) {
float nextX = posX + length * sin(angle);
float nextY = posY - length * cos(angle);
line(posX, posY, nextX, nextY);
tree(nextX, nextY, angle + forkRight, forkRight, forkLeft, length*0.6, generation - 1);
tree(nextX, nextY, angle - forkLeft, forkRight, forkLeft, length*0.6, generation - 1);
}
}
```
![What a lovely Christmas tree, don't you think, ma?](https://i.stack.imgur.com/zXM91.png)
```
Or, if you prefer a fuller tree:
int size = 500;
int depth = 10;
void setup() {
frameRate(30);
size(size, size, P2D);
}
void draw() {
background(255);
tree(size/2.0 - 5, size, 0.0, 0.0, (size - mouseY)/3, depth);
}
void keyPressed() {
if(keyCode == UP) depth++;
if(keyCode == DOWN) depth--;
depth = max(depth, 1);
}
void tree(float posX, float posY, float angle, float fork, float length, int generation) {
if (generation > 0) {
float nextX = posX + length * sin(angle);
float nextY = posY - length * cos(angle);
line(posX, posY, nextX, nextY);
tree(nextX, nextY, angle + fork + radians(108), fork, length*0.6, generation - 1);
tree(nextX, nextY, angle - fork, fork, length*0.6, generation - 1);
tree(nextX, nextY, angle + fork - radians(108), fork, length*0.6, generation - 1);
}
}
```
![I'm super bummed that somebody beat me to posting a fractal tree even though I was was ahead of them in the idea and in actually starting work on it :/](https://i.stack.imgur.com/bQ58p.png)
[Answer]
# Ruby
```
((1..20).to_a+[6]*4).map{|i|puts ('*'*i*2).center(80)}
```
![Happy New Year](https://i.stack.imgur.com/5RbU7.png)
You can customize output by changing `*`.
For a green tree: `((1..20).to_a+[6]*4).map{|i|puts "\e[32m"+('*'*i*2).center(80)}`
**Approach 2** (Xmas tree that doesn't look like an arrow)
```
((1..6).to_a+(3..9).to_a+(6..12).to_a+[3]*4).map{|i|puts "\e[32m"+('*'*i*4).center(80)}
```
![Happy New Year](https://i.stack.imgur.com/iZUMt.png)
**Approach 3**
```
((1..20).to_a+[6]*4).map{|i|puts' '*(20-i)+'*'*(2*i-1)}
```
[Answer]
# [Turtle Graphics](https://blockly-demo.appspot.com/static/apps/turtle/index.html#)
![enter image description here](https://i.stack.imgur.com/Z0QPP.png)
Based on properties of the [Euler spiral](http://en.wikipedia.org/wiki/Euler_spiral).
Code:
![enter image description here](https://i.stack.imgur.com/CXdP5.png)
The scale is determined by the step size (`move forward by: 6`). An interactive version is available [here](https://blockly-demo.appspot.com/static/apps/turtle/index.html#rjtwyt).
P.S. Inspired by [this](https://codegolf.stackexchange.com/q/18157/13509) question.
[Answer]
## Processing
I made this tree generator using an L-System and a Turtle.
![A Tree](https://i.stack.imgur.com/20ddP.png)
code:
```
//My code, made from scratch:
final int THE_ITERATIONS = 7;
final float SCALE = 1;
final int ANGLE = 130;
final int SIZE = 4;
final int ITERATIONS = THE_ITERATIONS - 1;
int lineLength;
String lSystem;
ArrayList<Turtle> turtles;
int turtleIndex;
int lSystemIndex;
void setup()
{
size(320, 420);
background(255);
translate(width / 2, height - 70);
lineLength = ITERATIONS * 2 + 2;
lSystem = "[-F][+F]F";
turtles = new ArrayList<Turtle>(ITERATIONS + 1);
lSystemIndex = 0;
calculateLSystem();
println(lSystem);
turtles.add(new Turtle(0, 0));
doTurtles();
save("Tree.png");
}
void doTurtles()
{
while(lSystemIndex < lSystem.length())
{
print("\"" + lSystem.charAt(lSystemIndex) + "\": ");
if(lSystem.charAt(lSystemIndex) == 'F')
{
turtleForward();
}
else if(lSystem.charAt(lSystemIndex) == '[')
{
lineLength -= 2;
addTurtle();
println(turtles.size());
}
else if(lSystem.charAt(lSystemIndex) == ']')
{
lineLength += 2;
removeTurtle();
println(turtles.size());
}
else if(lSystem.charAt(lSystemIndex) == '+')
{
turtleRight();
}
else if(lSystem.charAt(lSystemIndex) == '-')
{
turtleLeft();
}
lSystemIndex++;
}
}
void addTurtle()
{
turtles.add(new Turtle(turtles.get(turtles.size() - 1)));
}
void removeTurtle()
{
turtles.remove(turtles.size() - 1);
}
void turtleLeft()
{
turtles.get(turtles.size() - 1).left(ANGLE + random(-5, 5));
}
void turtleRight()
{
turtles.get(turtles.size() - 1).right(ANGLE + random(-5, 5));
}
void turtleForward()
{
print(turtles.get(turtles.size() - 1) + ": ");
strokeWeight(min(lineLength / SIZE, 1));
stroke(5 + random(16), 90 + random(16), 15 + random(16));
if(turtles.size() == 1)
{
strokeWeight(lineLength / 2);
stroke(100, 75, 25);
}
turtles.get(turtles.size() - 1).right(random(-3, 3));
turtles.get(turtles.size() - 1).forward(lineLength);
}
void calculateLSystem()
{
for(int i = 0; i < ITERATIONS; i++)
{
lSystem = lSystem.replaceAll("F", "F[-F][+F][F]");
}
lSystem = "FF" + lSystem;
}
void draw()
{
}
//——————————————————————————————————————————————————————
// Turtle code, heavily based on code by Jamie Matthews
// http://j4mie.org/blog/simple-turtle-for-processing/
//——————————————————————————————————————————————————————
class Turtle {
float x, y; // Current position of the turtle
float angle = -90; // Current heading of the turtle
boolean penDown = true; // Is pen down?
int lineLength;
// Set up initial position
Turtle (float xin, float yin) {
x = xin;
y = yin;
//lineLength = lineLengthin;
}
Turtle (Turtle turtle) {
x = turtle.x;
y = turtle.y;
angle = turtle.angle;
//lineLength = turtle.lineLength - 1;
}
// Move forward by the specified distance
void forward (float distance) {
distance = distance * SIZE * random(0.9, 1.1);
// Calculate the new position
float xtarget = x+cos(radians(angle)) * distance;
float ytarget = y+sin(radians(angle)) * distance;
// If the pen is down, draw a line to the new position
if (penDown) line(x, y, xtarget, ytarget);
println(x + ", " + y + ", " + xtarget + ", " + ytarget);
// Update position
x = xtarget;
y = ytarget;
}
// Turn left by given angle
void left (float turnangle) {
angle -= turnangle;
println(angle);
}
// Turn right by given angle
void right (float turnangle) {
angle += turnangle;
println(angle);
}
}
```
[Answer]
# JavaScript (run on any page in console)
I was golfing this but then decided not to, so as you can see there are TONS of magic numbers :P
```
// size
s = 300
document.write('<canvas id=c width=' + s + ' height=' + s + '>')
c = document.getElementById('c').getContext('2d')
c.fillStyle = '#0D0'
for (var i = s / 3; i <= s / 3 * 2; i += s / 6) {
c.moveTo(s / 2, s / 10)
c.lineTo(s / 3, i)
c.lineTo(s / 3 * 2, i)
c.fill()
}
c.fillStyle = '#DA0'
c.fillRect(s / 2 - s / 20, s / 3 * 2, s / 10, s / 6)
```
Result for s = 300:
![screenshot](https://i.stack.imgur.com/ho8Sd.png)
s = 600:
![screenshot](https://i.stack.imgur.com/6dNEd.png)
[Answer]
## Game Maker Language
**spr\_tree**
![spr_tree](https://i.stack.imgur.com/xpwbq.png)
**The tree's Create Event**
```
image_speed=0
size=get_integer("How big do you want me to be?#Integer between 1 and 10, please!",10)
image_index=size-1
```
**Room, 402 by 599**
The tree is placed at `(0,0)`
**Bonus!** You can resize the Christmas tree after the initial input with the keys 0-9.
[Answer]
# AppleScript + SE Answer
Actually picked this up by accident while editing an answer in this question. Go figure.
Use this by running the code, typing in your number that you want, swiping over to the SE post and clicking in the text field. This exploits the fact that quotes stack.
```
tell application "System Events"
set layers to (display dialog "" default answer "")'s text returned as number
delay 5
repeat layers times
keystroke ">"
end repeat
end tell
```
Output (input 50):
>
>
> >
> >
> > >
> > >
> > > >
> > > >
> > > > >
> > > > >
> > > > > >
> > > > > >
> > > > > > >
> > > > > > >
> > > > > > > >
> > > > > > > >
> > > > > > > > >
> > > > > > > > >
> > > > > > > > > >
> > > > > > > > > >
> > > > > > > > > > >
> > > > > > > > > > >
> > > > > > > > > > > >
> > > > > > > > > > > >
> > > > > > > > > > > > >
> > > > > > > > > > > > >
> > > > > > > > > > > > > >
> > > > > > > > > > > > > >
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > > >
> > > > > > > > > > > > > >
> > > > > > > > > > > > > >
> > > > > > > > > > > > > >
> > > > > > > > > > > > >
> > > > > > > > > > > > >
> > > > > > > > > > > > >
> > > > > > > > > > > >
> > > > > > > > > > > >
> > > > > > > > > > > >
> > > > > > > > > > >
> > > > > > > > > > >
> > > > > > > > > > >
> > > > > > > > > >
> > > > > > > > > >
> > > > > > > > > >
> > > > > > > > >
> > > > > > > > >
> > > > > > > > >
> > > > > > > >
> > > > > > > >
> > > > > > > >
> > > > > > >
> > > > > > >
> > > > > > >
> > > > > >
> > > > > >
> > > > > >
> > > > >
> > > > >
> > > > >
> > > >
> > > >
> > > >
> > >
> > >
> > >
> >
> >
> >
>
>
>
[Answer]
## Decorated FORTRAN tree
```
character(len=36) :: f='/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\'
character(len=18) :: g = ' '
character(len=14) :: p = ".x$.+oO+oO.#,~"
character(len=10) :: q
n = iargc()
if (n /= 1) then
k = len(g)
else
call getarg(1,q)
read(q,*) k
end if
l = modulo(k,len(g))+1
do i=1,l
j = mod(i,len(p)-1)+1
print *,g(1:l-i),p(j:j),f(1:2*i),p(j+1:J+1)
end do
print *,g(1:l-1),f(1:4)
end
```
The tree has a limited range of sizes, but it believe it accurately reflects the life of most Christmas trees.
From infant tree:
```
$./tree
x/\$
/\/\
```
To adolescent tree:
```
$./tree 6
x/\$
$/\/\.
./\/\/\+
+/\/\/\/\o
o/\/\/\/\/\O
O/\/\/\/\/\/\+
+/\/\/\/\/\/\/\o
/\/\
```
To adult:
```
$./tree 17
x/\$
$/\/\.
./\/\/\+
+/\/\/\/\o
o/\/\/\/\/\O
O/\/\/\/\/\/\+
+/\/\/\/\/\/\/\o
o/\/\/\/\/\/\/\/\O
O/\/\/\/\/\/\/\/\/\.
./\/\/\/\/\/\/\/\/\/\#
#/\/\/\/\/\/\/\/\/\/\/\,
,/\/\/\/\/\/\/\/\/\/\/\/\~
./\/\/\/\/\/\/\/\/\/\/\/\/\x
x/\/\/\/\/\/\/\/\/\/\/\/\/\/\$
$/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\.
./\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\+
+/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\o
o/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\O
/\/\
```
[Answer]
# Java
```
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
public class ChristmasTree {
static class Point{
Point(int a,int b){x=a;y=b;}
int x,y;
double distance(Point o){
int dx=x-o.x;
int dy=y-o.y;
return Math.sqrt(dx*dx+dy*dy);
}
}
static int siz;
static BufferedImage b;
static Random r=new Random();
public static void main(String[]args) throws IOException{
if(args.length==0){
siz=(new Scanner(System.in)).nextInt();
}else{
siz=Integer.parseInt(args[0]);
}
b=new BufferedImage(20*siz,30*siz,BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D)b.getGraphics();
g.setColor(new Color(140,70,20));
int h=b.getHeight();h*=0.4;
for(int i=(int)(0.4*b.getWidth());i<(int)(0.6*b.getWidth());i++){
if(r.nextDouble()<0.3){
g.drawLine(i,b.getHeight(),i+r.nextInt(2)-1,h);
}
}
for(int i=h;i<b.getHeight();i++){
if(r.nextDouble()<0.3){
g.drawLine((int)(0.4*b.getWidth()),i,(int)(0.6*b.getWidth()),i);
}
}
for(int i=0;i<siz;i++){
g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
g.drawLine(b.getWidth()/2-(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9)+r.nextInt(5)-2,b.getWidth()/2+(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9)+r.nextInt(5)-2);
g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
g.drawLine(b.getWidth()/2-(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9),b.getWidth()/2,(int)(b.getHeight()*(0.1+(.06*i)/siz)));
g.setColor(new Color(r.nextInt(4),150+r.nextInt(15),20+r.nextInt(7)));
g.drawLine(b.getWidth()/2+(int)(b.getWidth()*0.42*i/siz),(int)(b.getHeight()*0.9),b.getWidth()/2,(int)(b.getHeight()*(0.1+(.06*i)/siz)));
}
g.setColor(new Color(150,120,40));
g.fillOval((b.getWidth()-siz-2)/2,b.getHeight()/10,siz+2,siz+2);
g.setColor(new Color(250,240,80));
g.fillOval((b.getWidth()-siz)/2,b.getHeight()/10,siz,siz);
List<Color>c=Arrays.asList(new Color(0,255,0),new Color(255,0,0),new Color(130,0,100),new Color(0,0,200),new Color(110,0,200),new Color(200,205,210),new Color(0,240,255),new Color(255,100,0));
List<Point>pts=new ArrayList<>();
pts.add(new Point((b.getWidth()-siz)/2,b.getHeight()/10));
loop:for(int i=0;i<8+siz/4;i++){
int y=r.nextInt((8*b.getHeight())/11);
int x=1+(int)(b.getWidth()*0.35*y/((8*b.getHeight())/11));
x=r.nextInt(2*x)-x+b.getWidth()/2;
y+=b.getHeight()/8;
g.setColor(c.get(r.nextInt(c.size())));
x-=siz/2;
Point p=new Point(x,y);
for(Point q:pts){
if(q.distance(p)<1+2*siz)continue loop;
}
pts.add(p);
g.fillOval(x,y,siz,siz);
}
ImageIO.write(b,"png",new File("tree.png"));
}
}
```
**Sample results:**
Size=3:
![enter image description here](https://i.stack.imgur.com/KsKEy.png)
Size=4:
![enter image description here](https://i.stack.imgur.com/U3oYc.png)
Size=5:
![enter image description here](https://i.stack.imgur.com/ONZvl.png)
Size=12:
![enter image description here](https://i.stack.imgur.com/nairL.png)
Size=20:
![enter image description here](https://i.stack.imgur.com/wbe3W.png)
[Answer]
**Rebol**
With a dialect to display the symbols. To change the tree size, just change the parameter of `make-tree`.
```
make-tree: func [int /local tr] [
tr: copy []
length: (int * 2) + 3
repeat i int [
repeat j 3 [
ast: to-integer ((i * 2) - 1 + (j * 2) - 2)
sp: to-integer (length - ast) / 2
append/dup tr space sp
append/dup tr "*" ast
append tr lf
]
]
append/dup tr space (length - 1) / 2
append tr "|"
append tr lf
tr
]
print make-tree 3
```
![a tree with 3 layers ](https://i.stack.imgur.com/rZyXF.png)
![a tree with 5 layers](https://i.stack.imgur.com/qqLvO.png)
[Answer]
**Python**
```
import sys
w = sys.stdout.write
def t(n,s):
for i in range(n):
for a in range(n-i):
w(" ")
w("[")
for l in range(i<<1):
if i==n-1:
w("_")
else:
w("~")
w("]")
print("")
for o in range(s):
for i in range(n):
w(" ")
print("[]")
t(10, 2)
```
![enter image description here](https://i.stack.imgur.com/qFk6W.png)
[Answer]
## Ti-Basic 84
Asks for a size:
```
:
Input
S:Lbl 1
S-1→S
:
"||
"+""→
Str1:"
"→Str2
:Disp Str2+
" **":Disp
Str2+" "+"*"+
Str1+"*":Disp "
"+Str1+"*-"+"||-*
":Disp Str1+"*--||-
-*":Disp " *---||--
-*":Disp " *----||----
*":Disp Str1+" "+Str2+"
":If S>0:Goto 2:Goto 1:Lbl
2
```
Output (size 1):
```
**
*||*
*-||-*
*--||--*
*---||---*
*----||----*
||
```
] |
[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.
Your task: To write a program that should obviously terminate, but it never (to the extent of a computer crash) does. Make it look like it should perform a simple task: adding numbers, printing something,... But it just gets caught in an infinite loop.
Try to make your program very clear and simple, while it actually will get stuck in an unforeseen loop. Voters: judge the answers on how "underhanded" they are!
This is a popularity contest: Be creative!
[Answer]
## Javascript
```
var x=prompt('Enter a value under 100');
while (x != 100) {
x=x+1;
}
console.log('End!');
```
>
> prompt() returns a string and the loop appends the character '1', it will never be equal to 100.
>
>
>
[Answer]
## C
Just a basic example program that illustrates the three different kinds of while-loops in C.
```
int main() {
int x = 0;
// Multi-statement while loops are of the form "while (condition) do { ... }" and
// are used to execute multiple statements per loop; this is the most common form
while (x < 10) do {
x++;
}
// x is now 10
// Null-statement while loops are of the form "while (condition) ;" and are used
// when the expression's side effect (here, decrementing x) is all that is needed
while (x-- > 0)
; // null statement
// x is now -1
// Single-statement while loops are of the form "while (condition) statement;"
// and are used as a shorthand form when only a single statement is needed
while (x > -10)
x--;
// x is now -10
return 0;
}
```
>
> While loops don't have a "do" before the opening curly brace. This actually creates a do-while loop inside of the (x < 10) loop that's terminated by the following "null statement" while loop. Since x is incremented inside of the loop and then decremented in the do-while loop's condition, the inner loop never terminates, and so neither does the outer loop. The "single-statement" loop at the end is never reached.
>
>
>
> If you're still confused, look [here](http://pastebin.com/hTPdRceu) (externally hosted because codegolf.SE doesn't like code blocks in spoilers).
>
>
>
[Answer]
# JavaScript
```
var a = true;
(function() {
while(!a){}
alert("infinite");
var a = true;
})();
```
>
> Variable hoisting: JavaScript will actually grab my second definition of `var a = true;`, declare it at the top of the function as `var a;`, and modify my assignment to `a = true;` meaning `a` will be undefined at the time it enters the while loop.
>
>
>
[Answer]
# C#
```
class Program
{
// Expected output:
// 20l
// 402
// 804
// l608
// 32l6
// game over man
static void Main()
{
var x = 20l;
while (x != 6432)
{
Console.WriteLine(x);
x *= 2;
}
Console.WriteLine("game over man");
}
}
```
>
> The number literal in the first line of the function is not a '201', but a '20' with a lowercase 'L' (**long** datatype) suffix. The number will overflow pretty quickly without ever hitting 6432, but the program will keep going unless overflow checking was switched on in the build options.
>
> Sensibly, Visual Studio 2013 (and probably other versions too) gives you a warning for this code, recommending that you use 'L' instead of 'l'.
>
>
>
[Answer]
## C
How about precision ?
```
int main(void)
{
double x = 0;
while(x != 10) x += 0.1;
return 0;
}
```
>
> Imagine you have to store a range of integer numbers <0;3> in computer memory. There are only 4 integer numbers in this range (0,1,2,3). It's enough to use 2 bits to store that in memory.
> Now imagine you have to store a range of floating point numbers <0;3>. The problem is there is an infinite number of floating point numbers in this range. How to store infinite number of numbers ? It is impossible. We can only store finite number of numbers. This is why some numbers like 0.1 are actually different. In case of 0.1 it is 0.100000000000000006.
> It is highly recommended to not use == or != in conditions as far as you use floating point numbers.
>
>
>
[Answer]
# HTML / JavaScript
Imagine you have an input box in your page:
```
<input onfocus="if (this.value === '') alert('Input is empty!');">
```
And now you want to type something in it... Try in Chrome: <http://jsfiddle.net/jZp4X/>.
>
> Standard browser dialog box called with `alert` function is modal, so when it's displayed it takes the focus out of the text box, but when it is dismissed the text box receives the focus back.
>
>
>
[Answer]
# C++
```
#include <iostream>
#include <cstddef>
int main() {
size_t sum = 0;
for (size_t i = 10; i >= 0; --i) {
sum += i;
}
std::cout << sum << std::endl;
return 0;
}
```
>
> The condition `i >=0` is always true because size\_t is unsigned.
>
>
>
[Answer]
**bash**
*(There was a request for no loops or recursion)*
```
#!/bin/bash
# Demo arrays
foo=("Can I have an array?")
echo $foo
echo ${foo[0]}
foo[2] = `yes`
echo $foo
echo ${foo[2]}
```
>
> Instead of assigning the string 'yes' to foo[2], this calls the system command `yes`, which fills up foo[2] with a never ending amount of "yes\n".
>
>
>
[Answer]
# C
Letter "x" was lost in a file. A program was written to find it:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE* fp = fopen("desert_file", "r");
char letter;
char missing_letter = argv[1][0];
int found = 0;
printf("Searching file for missing letter %c...\n", missing_letter);
while( (letter = fgetc(fp)) != EOF ) {
if (letter == missing_letter) found = 1;
}
printf("Whole file searched.\n");
fclose(fp);
if (found) {
printf("Hurray, letter lost in the file is finally found!\n");
} else {
printf("Haven't found missing letter...\n");
}
}
```
It was compiled and to ran and it finally shout:
```
Hurray, letter lost in the file is finally found!
```
For many years letters have been rescued this way until the new guy came and optimized the code. He was familiar with datatypes and knew that it's better to use unsigned than signed for non-negative values as it has wider range and gives some protection against overflows. So he **changed int into unsigned int**. He also knew ascii well enough to know that they always have non-negative value. So he also **changed char into unsigned char**. He compiled the code and went home proud of the good job he did. The program looked like this:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE* fp = fopen("desert_file", "r");
unsigned char letter;
unsigned char missing_letter = argv[1][0];
unsigned int found = 0;
printf("Searching file for missing letter %c...\n", missing_letter);
while( (letter = fgetc(fp)) != EOF ) {
if (letter == missing_letter) found = 1;
}
printf("Whole file searched.\n");
fclose(fp);
if (found) {
printf("Hurray, letter lost in the file is finally found!\n");
} else {
printf("Haven't found missing letter...\n");
}
}
```
He came back to a havoc on the next day. Letter "a" was missing and even though it was supposed to be in the "desert\_file" containing "abc" the program was searching for it forever printing out only:
```
Searching file for missing letter a...
```
They sacked the guy and rolled back to previous version remembering that one should never optimize datatypes in working code.
But what is the lesson they should have learnt here?
>
> First of all, if you take a look at the ascii table you'll notice that there is no EOF. That's because EOF is not a character but a special value returned from fgetc(), which can either return character extended to int or -1 denoting end of file.
>
>
> As long as we are using signed char everything works well - char equal to 50 is extended by fgetc() into int equal to 50 as well. Then we transform it back to char and still have 50. Same happens for -1 or any other output coming from fgetc().
>
>
> But look what happens when we use unsigned char. We start with a char in fgetc() extend it to int and then want to have an unsigned char. The only problem is that we can't preserve -1 in unsigned char. Program is storing it as 255 which no longer equal to EOF.
>
>
>
>
> **Caveat**
>
>
> If you take a look at section 3.1.2.5 Types in [copy of ANSI C documentation](http://flash-gordon.me.uk/ansi.c.txt) you'll find out that whether char is signed or not depends solely on implementation. So the guy probably shouldn't be sacked as he found a very tricky bug lurking in the code.
> It could come out when changing the compiler or moving to different architecture. I wonder who would be fired if the bug came out in such a case ;)
>
>
>
PS. Program was built around the bug mentioned in PC Assembly Language by Paul A. Carter
[Answer]
# Regex
With appropriate input, the following regex can cause most backtracking regex engine to go into backtracking hell:
```
^\w+(\s*\w+)*$
```
Simple input such as `"Programming Puzzles and Code Golf Stack Exchange - Mozilla Firefox"` or `"AVerySimpleInputWhichContainsAnInsignificantSentence."` (both strings quoted for clarity) is enough to keep most backtracking regex engines running for a long time.
>
> Since `(\s*\w+)*` allows for the expansion `\w+\w+\w+`...`\w+`, which means the regex engine will basically try out all possible ways to split up a string of *word characters*. This is the source of the backtracking hell.
>
> It can easily be fixed by changing `\s*` to `\s+`, then `(\s+\w+)*` can only be expanded to `\s+\w+\s+\w+`...`\s+\w+`.
>
>
>
[Answer]
# **JavaScript**
```
function thiswillLoop(){
var mynumber = 40;
while(mynumber == 40){
mynumber = 050;
}
return "test";
}
thiswillLoop();
```
>
> 050 is an octal constant in Javascript, and it happens to have the decimal value of 40.
>
>
>
[Answer]
# Haskell
```
head $ reverse $ (repeat '!') ++ "olleH"
```
Well, think of it! It would be the same as `head $ "Hello" ++ (repeat '!')`, i.e should just return `'H'`.
>
> In haskell lists are recursive structures, with first element being the topmost. To append to a list, you have to unroll all those elements, place your appendix, and put the lifted elements back. That wouldn't work on an infinite list. Similarly, reversing an infinite list won't magically give you your `"Hello"` back. It will just hang forever.
>
>
>
[Answer]
# Java under Windows
```
public class DoesntStop
{
public static void main(String[]a) throws InterruptedException, IOException
{
ProcessBuilder p = new ProcessBuilder("cmd.exe","/c","dir");
p.directory(new File("C:\\windows\\winsxs"));
Process P = p.start();
P.waitFor();
}
}
```
>
> Program relies on a jammed standard output stream from the commandline to get stuck. The WinSXS directory under windows has multiple thousands of files with long names so it is almost guaranteed to clog stdout, and the `waitFor` can't return so the program is deadlocked
>
>
>
[Answer]
# To compare apples and oranges... in C
I'm impressed that there is no piece of code here using a `goto`... (You know: *Goto is evil!*)
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
char *oranges = "2";
long int apples;
next_harvest:
apples = random() % 3;
printf("%ld apples comp. %s oranges ...\n", apples, oranges);
if( apples != (long int)oranges )
{
sleep(1);
goto next_harvest;
}
return 0;
}
```
The sleep is just for being able to read it. Press ^C if you don't have an endless amount of time to wait for something that never happens ;-)
[Answer]
# C, with certain optimizing compilers
This program increments an integer variable until it overflows.
```
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t x = 0;
while(x + 1 > x)
x++;
printf("Got overflow!\n");
return 0;
}
```
>
> Signed integer overflow is undefined behaviour. Usually in practice it wraps, when optimizations are turned off. With optimizations on, compilers can and do decide that `x + 1 > x` is always true.
>
>
>
[Answer]
# C++
```
int main()
{
int x = 1;
//why doesn't this code terminate??/
x = 0;
while(x) {} //no-op/
return 0;
}
```
The weird commenting style is the trick. Hint: trigraphs.
[Answer]
## Java
I particular love this side effect of the autoboxing optimization:
```
class BoxingFun {
public static void main( String[] args) {
Integer max;
Integer i;
max = 100;
for( i = 1; i != max; i++ ) {
System.out.println("Not endless");
}
max = 200;
for( i = 1; i != max; i++ ) {
System.out.println("Endless");
}
}
}
```
>
> Because of autoboxing, `Integer` objects behave almost like plain `int`s here, with one exception: The `i != max` in the `for` loops compares the *references* (identity) of the `Integer` objects, not their value (equality). For values up to 100 this surprisingly "works" nevertheless because of an optimization in the JVM: Java preallocates `Integer` objects for the "most common values" and reuses them when autoboxing. So for values up to 100 we have identity <==> equality.
>
>
>
[Answer]
# Ruby/C
```
#include <stdio.h>
#ifdef llama
def int(*args)
end
def main(arg)
yield
end
void = nil
#endif
#define do {
#define end }
int main(void) {
int x = 10;
while(x-=1) do
printf("%i\n",x);
end
return 0;
}
```
This [works correctly in C](https://ideone.com/ahoDdm), counting down from 9 to 1 in STDOUT. When run in Ruby, it does not terminate, because
>
> 0 is not a false value in Ruby.
>
>
>
[Answer]
# JavaScript
```
// This multiplies the elements in the inner lists and sums the results.
function sum_of_products(var items)
{
var total = 0;
for(var i = 0; i < items.length; i++) {
var subitems = items[i];
var subtotal = 1;
for(var i = 0; i < subitems.length; i++) {
subtotal *= subitems[i];
}
total += subtotal;
}
return total;
}
// Should return 1*2 + 3*4*5 + 6*7*8*9 + 10*11 = 3196
sum_of_products([[1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11]]);
```
>
> Both loops use the same loop variable, so depending on the input, the inner loop can keep the outer loop from ever finishing.
>
>
>
[Answer]
## C
This should print a code table for all ASCII characters, from 0 to 255. A `char` is large enough to iterate over them.
```
#include <stdio.h>
int main(){
char i;
for(i = 0; i < 256; i++){
printf("%3d 0x%2x: %c\n", i, i, i);
}
return 0;
}
```
>
> All chars are less than 256. 255++ gives 0 due to overflow, so the condition `i < 256` always hold. Some compilers warn about it, some don't.
>
>
>
[Answer]
# Python
```
a = True
m = 0
while a:
m = m + 1
print(m)
if m == 10:
exit
```
>
> it should be `exit()` and not `exit`. As I understand it, `exit()` is the command to exit the python interpreter. In this case the call is to the representation of the function and not to the function see: [exit-discussion](https://stackoverflow.com/questions/9730409/exiting-from-python-command-line). Alternatively `break` would be a better choice.
>
>
>
[Answer]
# C++
How about the classical C++-programmer's trap?
```
int main()
{
bool keepGoing = false;
do {
std::cout << "Hello, world!\n";
} while( keepGoing = true );
return 0;
}
```
[Answer]
# Java:
```
public class LoopBugThing{
public static void main(String[] args)
{
int i = 0;
while(i < 10)
{
//do stuff here
i = i++;
}
System.out.println("Done!");
}
}
```
>
> The "i = i++" is a pretty common beginner mistake and can be surprisingly hard to find
>
>
>
[Answer]
## C++
A bit of random ?
```
class Randomizer
{
private:
int max;
public:
Randomizer(int m)
{
max = m;
srand(time(NULL));
}
int rand()
{
return (rand() % max);
}
};
int main()
{
Randomizer r(42);
for (int i = 0; i < 100; i++)
{
i += r.rand();
}
return (0);
}
```
>
> Doesn't call the function `rand` but instead call recursively the `Randomizer::rand` function.
>
>
>
[Answer]
# Haskell
Some code to time the computation of a given value of the Ackermann
function. For very low values it usually terminates. On my machine
very low values means something like 3 5 or smaller with compiled
code and `-O`. In ghci low values means something like 3 3.
The `'` symbol seems to mess up syntax highlighting, not sure why.
In some places they are needed so can't remove all of them.
Edit- changed language.
```
{-# LANGUAGE NamedFieldPuns #-}
import Control.Concurrent.STM
import Control.Concurrent
import Data.Time.Clock.POSIX
data D = D { time :: !POSIXTime
, m :: !Integer
, n :: !Integer
, res :: !(Maybe Integer)
} deriving Show
startvalue = D 0 3 8 Nothing
-- increment time in D. I belive lensen make code like
-- this prettier, but opted out.
inctime t t' (d@D{time}) = d {time = time + t' - t }
-- Counting time
countTime :: TVar D -> POSIXTime -> IO ()
countTime var t = do
t' <- getPOSIXTime
atomically $ modifyTVar' var (inctime t t')
countTime var t'
-- Ackermann function
ack m n
| m == 0 = n + 1
| n == 0 = ack (m - 1) 1
| otherwise = ack (m - 1) (ack m (n - 1))
-- Ackerman function lifted to the D data type and strict
ack' (d@D{m, n}) = let a = ack m n
in seq a (d { res = Just a })
-- fork a counting time thread, run the computation
-- and finally print the result.
main = do
d <- atomically (newTVar startvalue)
forkIO (getPOSIXTime >>= countTime d)
atomically $ modifyTVar' d ack'
(atomically $ readTVar d) >>= print
```
>
> This causes a livelock. The counting thread repeatedly causes
> the Ackermann computation to roll back since they touch the
> same TVar.
>
>
>
[Answer]
# Java -- No loops or recursion
I just started learning regular expressions and wrote my first program to test if my string matches a regular expression.
Unfortunately, the program does not produce any result. It holds up the terminal. Please help in finding the problem. I have not made any use of loops, there is no recursion involved. I am completely baffled.
```
import java.util.regex.*;
public class LearnRegex {
public static void main(String[] args) {
Pattern p = Pattern.compile("(x.|x.y?)+");
String s = new String(new char[343]).replace("\0", "x");
if (p.matcher(s).matches())
System.out.println("Match successful!");
}
}
```
## What have I done wrong? Why doesn't my program end? Please help!
Ideone link [here](https://ideone.com/xvAICY).
>
> This is a stupid example of [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html). The complexity is O(2n/2). While the program might not run indefinitely, it'd probably outlive both living and non-living *objects* around and *not-so-around*.
>
>
>
[Answer]
# C
You should only need one of the two loops, but which one you need depends on your compiler.
```
main()
{
int i, a[10];
i = 0;
while (i <= 10) {
i++;
a[i] = 10 - i;
printf("i = %d\n", i);
}
/* Now do it in reverse */
i = 10;
while (i >= 0) {
i--;
a[i] = 10 - i;
printf("i = %d\n", i);
}
}
```
>
> A simple bounds overrun that resets *i* to a non-terminating value. Compilers can differ on whether they allocate *i* above or below *a* on the stack, so I've included overruns in both directions.
>
>
>
[Answer]
# C / C++
C++ just allows the easy inline variable declarations used here, but it's just as easy to make this mistake in plain old C...
```
#include <stdio.h>
int main(void)
{
int numbers[] = {2, 4, 8};
/* Cube each item in the numbers array */
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; i++) {
numbers[j] *= numbers[j];
}
}
/* Print them out */
for(int i = 0; i < 3; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
```
>
> In the inner loop, 'j' is compared but never incremented. (The 'i++' should actually be 'j++'). This is not so much a sneaky trick but more of an actual error I've made in the past ;) Something to watch out for.
>
>
>
[Answer]
## C#
The following is a simple class performing an arithmetic operation (summation) on a large input array using a background thread. A sample program is included.
However, even though it is quite straightforward, it never terminates. Note that there is no sleight of hand (character lookalikes, hidden/missing semicolons, trigraphs ;-), etc.)
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void Main()
{
var summer = new BackgroundSummer(Enumerable.Range(1, 1234567));
Console.WriteLine(summer.WaitAndGetResult());
}
}
public class BackgroundSummer
{
private IEnumerable<int> numbers;
private long sum;
private bool finished;
public BackgroundSummer(IEnumerable<int> numbers)
{
this.numbers = numbers;
new Thread(ComputingThread).Start();
}
public long WaitAndGetResult()
{
while (!finished) { /* wait until result available */ }
return sum;
}
private void ComputingThread()
{
foreach(var num in numbers)
{
sum += num;
}
finished = true;
}
}
```
>
> This is an example of a real-world nasty bug which might appear in your code as well. Per the .NET memory model and C# specification, a loop such as the one in `WaitAndGetResult` might never terminate unless you specify the variable as volatile, because it is modified by another thread. See [this StackOverflow question](https://stackoverflow.com/q/458173/304138) for details.
> The bug is dependent on the .NET implementation, so it might or might not affect you. But usually, running a release build on an x64 processor seems to display the problem. (I tried it with *“csc.exe /o+ /debug- infinite.cs”*.)
>
>
>
[Answer]
Javascript
```
var а = 0;
a = 1;
while(а<10){
a++;
}
```
>
> The variables used in 1st and 3rd line are different from the ones used in 2nd and 3rd line.
>
> One uses [a](http://www.fileformat.info/info/unicode/char/61/index.htm) (U+0061) while the other uses [а](http://www.fileformat.info/info/unicode/char/430/index.htm) (U+0430)
>
>
>
] |
[Question]
[
Write a program that outputs the lyrics to 99 Bottles of Beer, **in as few bytes as possible**.
Lyrics:
```
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.
96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.
95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.
....
3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
```
Rules:
* Your program must log to STDOUT or an acceptable alternative, or be returned from a function (with or without a trailing newline).
* Your program must be a full, runnable program or function.
* Languages specifically written to submit a 0-byte answer to this challenge are allowed, just not particularly interesting.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* **This is different from the output by HQ9+ or 99. Any answers written in these languages will be deleted.**
As this is a catalog challenge, this is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.
### Catalogue
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64198; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 36670; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
## C#, ~~285~~ ~~298~~ 289 Bytes
(My first attempt at Code golfing ...)
```
class d{static void Main(){for(int b=99;b>0;)System.Console.Write("{0}{6}{1}{2}, {0}{6}{1} of beer. {3}, {4}{6}{5}{2}.{7}",b,b==1?"":"s"," of beer on the wall",b==1?"Go to the store and buy some more":"Take one down and pass it around",b==1?99:b-1,b==2?"":"s"," bottle",b--<2?"":"\n\n");}}
```
A little bit ungolfed:
```
class d{
static void Main(){
for(int b = 99; b > 0;){
System.Console.Write("{0}{6}{1}{2}, {0}{6}{1} of beer.\n{3}, {4}{6}{5}{2}.{7}", b, b==1 ? "" : "s", " of beer on the wall", b == 1 ? "Go to the store and buy some more" : "Take one down and pass it around", b == 1 ? 99 : b-1, b== 2 ? "" : "s", " bottle", b--<2 ? "" : "\n\n");
}
}
}
```
[Answer]
# [Motorola MC14500B Machine Code](https://en.wikipedia.org/wiki/Motorola_MC14500B), 46612 bytes
For length reasons, I can not post the program here. However, it can be found [here in hexadecimal](https://dl.dropboxusercontent.com/s/c41qf1weyf6idda/mc14500b-hex-99bottles), and [here in binary](https://dl.dropboxusercontent.com/s/h57z170sjkduq0y/mc14500b-binary-99bottles) (padded with `0`s).
---
This is the shortest possible program in Motorola MC14500B machine code. It consists of only `1000` and `1001` (`8` and `9`, respectively); one opcode for each bit of output.
It uses 93,224 half-byte opcodes, and outputs the song lyrics one bit at a time. This is the only possible output method.
For those interested, the output goes to pin #3 (of 16), the I/O pin.
---
### Explanation
```
8 Store the register's value
9 Store the logical complement of the register's value
```
The register starts at `0`.
---
### Code Trivia
* The [hexadecimal](https://dl.dropboxusercontent.com/s/c41qf1weyf6idda/mc14500b-hex-99bottles) is 93,224 `8`s and `9`s long.
* The [binary](https://dl.dropboxusercontent.com/s/h57z170sjkduq0y/mc14500b-binary-99bottles) is 745,792 `1`s and `0`s long.
* I used the Python 2 code below to generate the code. Input `0` for binary and `1` for hexadecimal.
```
a,b=["8","9"]if input()else["00001000","00001001"]
f="""99 Bottles of Beer lyrics"""
print''.join(b if int(i)else a for i in''.join((8-len(bin(i)[2:]))*'0'+bin(i)[2:]for i in bytearray(f)))
```
[Answer]
# Vitsy, 0 Bytes
Seriously ain't got nothin' on me. (@Mego I'm so sorry. ;))
[Try it online!](http://vitsy.tryitonline.net) (Just hit "Run")
[Answer]
# [Seriously](https://github.com/Mego/Seriously), 1 byte
```
N
```
If the stack is empty (which it is at the start), `N` pushes the lyrics. Then they're implicitly printed at EOF.
Thanks to @Mego for fixing the Seriously interpreter.
[Answer]
## JavaScript ES6, ~~230~~ ~~218~~ ~~198~~ ~~196~~ ~~192~~ ~~188~~ 185 bytes
```
for(x=99,z=(a=' on the wall')=>`${x||99} bottle${1-x?'s':''} of beer`+a;x;)alert(z()+', '+z`.
`+(--x?'Take one down and pass it around, ':'Go to the store and buy some more, ')+z()+'.')
```
Just just trimming off a few bytes while still keeping it looking clean and understandable.
3 most recent revisions:
```
for(x=99,z=a=>`${x||99} bottle${1-x?'s':''} of beer${a||' on the wall'}`;x;)alert(z()+', '+z(`.
`)+(--x?'Take one down and pass it around, ':'Go to the store and buy some more, ')+z()+'.')
for(x=99,z=a=>(x||99)+' bottle'+(1-x?'s':'')+' of beer',w=' on the wall';x;)alert(z()+w+', '+z()+(--x?`.
Take one down and pass it around, `:`.
Go to the store and buy some more, `)+z()+w+'.')
for(x=99,o=' bottle',q=b=o+'s',e=' of beer',w=e+" on the wall";x;)alert(x+b+w+', '+x+b+e+(--x?`.
Take one down and pass it around, `+x:`.
Go to the store and buy some more, 99`)+(b=1-x?q:o)+w+'.')
```
[Answer]
# JavaScript ES6, ~~328~~ ~~318~~ ~~307~~ 305 bytes
Is an anonymous function. Add `f=` at the beginning to make function and `f()` to execute.
```
x=>eval('s=o=>v=(o?o:" no more")+" bottle"+(1==o?"":"s");for(o="",i=99;i>0;)o+=`${s(i)}@ on the wall, ${v}@.\nTake one down, pass it around, ${s(--i)}@ on the wall.\n`;o+`No more bottles@ on the wall, no more bottles@.\nGo to the store and buy some more, 99 bottles@ on the wall.`'.replace(/@/g," of beer"))
```
[Answer]
# C, ~~197~~ 196 bytes
```
main(i){for(i=299;i--/3;printf("%d bottle%s of beer%s%s",i/3?:99,"s"+5/i%2,i%3?" on the wall":i^3?".\nTake one down and pass it around":".\nGo to the store and buy some more",~i%3?", ":".\n\n"));}
```
I think I have reached the limit of this approach.
[Answer]
## Java ~~304~~ ~~301~~ ~~300~~ 295 Bytes
First time posting an answer. I heard we could use enum but could not find how.
```
interface A{static void main(String[]a){String b=" of beer",c=" on the wall",n=".\n",s;for(int i=100;i-->1;s=" bottle"+(i>1?"s":""),System.out.println(i+s+b+c+", "+i+s+b+n+(i<2?"Go to the store and buy some more, 99":"Take one down and pass it around, "+(i-1))+" bottle"+(i!=2?"s":"")+b+c+n));}}
```
## Ungolfed
```
interface A {
static void main(String[] a) {
String b = " of beer", c = " on the wall", n = ".\n", s;
for (int i = 100; i-- > 1; s = " bottle" + (i > 1 ? "s" : ""), System.out.println(i + s + b + c + ", " + i + s + b + n + (i < 2 ? "Go to the store and buy some more, 99" : "Take one down and pass it around, " + (i - 1)) + " bottle" + (i != 2 ? "s" : "") + b + c + n));
}
}
```
---
Thanks to `quartata`, `J Atkin` and `Benjamin Urquhart`
[Answer]
# [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 667 bytes
```
Ap<Fun<Ap<Fun<Cat<Cat<Cat<Cat<Ap<A<1,1>,A<1>>,A<2,1>>,St<44,32>>,Ap<A<1,1>,A<1>>>,If<A<1>,Cat<Cat<Cat<Cat<St<46,10,84,97,107,101,32,111,110,101,32,100,111,119,110,32,97,110,100,32,112,97,115,115,32,105,116,32,97,114,111,117,110,100,44,32>,Ap<A<1,1>,Sub<A<1>,T>>>,A<2,1>>,St<46,10,10>>,Ap<A<0>,Sub<A<1>,T>>>,Cat<Cat<Cat<St<46,10,71,111,32,116,111,32,116,104,101,32,115,116,111,114,101,32,97,110,100,32,98,117,121,32,115,111,109,101,32,109,111,114,101,44,32>,Ap<A<1,1>,I<98>>>,A<2,1>>,St<46>>>>>,I<98>>>,Fun<Cat<Cat<Cat<Add<A<1>,T>,St<32,98,111,116,116,108,101>>,If<A<1>,St<'s'>,St<>>>,St<32,111,102,32,98,101,101,114>>>,St<32,111,110,32,116,104,101,32,119,97,108,108>>
```
Sort of expanded:
```
Ap<
Fun<
Ap<
Fun<
Cat<
Cat<Cat<Cat< Ap<A<1,1>,A<1>> , A<2,1> >, St<44,32> >, Ap<A<1,1>,A<1>> >,
If<A<1>,
Cat<Cat<Cat<Cat< St<46,10,84,97,107,101,32,111,110,101,32,100,111,119,110,32,97,110,100,32,112,97,115,115,32,105,116,32,97,114,111,117,110,100,44,32> , Ap<A<1,1>,Sub<A<1>,T>> >, A<2,1> >, St<46,10,10> >, Ap<A<0>,Sub<A<1>,T>> >,
Cat<Cat<Cat< St<46,10,71,111,32,116,111,32,116,104,101,32,115,116,111,114,101,32,97,110,100,32,98,117,121,32,115,111,109,101,32,109,111,114,101,44,32> , Ap<A<1,1>,I<98>> >, A<2,1> >, St<46> >
>
>
>,
I<98>
>
>,
Fun< Cat<Cat<Cat< Add<A<1>,T> , St<32,98,111,116,116,108,101> >, If<A<1>,St<'s'>,St<>> >, St<32,111,102,32,98,101,101,114> > >,
St<32,111,110,32,116,104,101,32,119,97,108,108>
>
```
[Answer]
# [///](http://esolangs.org/wiki////), 341 bytes
```
/-/\/\///+/ bottle-)/\/&\/<\/
-(/\/\/?\/ ->/+s of beer-^/> on the wall-!/^,-$/>.
-@/$Take one down and pass it around,-#/^.
-*/?1@?0#<0!?0@-%/99!?9@?8#<8!?8@?7#<7!?7@?6#<6!?6@?5#<5!?5@?4#<4!?4@?3#<3!?3@?2#<2!?2@?1#<1!-&/?9#
%*-</
9(9/%*/</
8(8)7(7)6(6)5(5)4(4)3(3)2(2)1(1)0(0-
0/
- 0/ /#/1+s/1+/
% 01$Go to the store and buy some more, 099^.
```
It would need 99 years to write a proper explanation of this code.
I would probably just include the result of every stage...
Basically, this compresses the lyrics repeatedly (as is every answer in [///](http://esolangs.org/wiki////)).
[Try it online!](http://slashes.tryitonline.net/#code=Ly0vXC9cLy8vKy8gYm90dGxlLSkvXC8mXC88XC8KLSgvXC9cLz9cLyAtPi8rcyBvZiBiZWVyLV4vPiBvbiB0aGUgd2FsbC0hL14sLSQvPi4KLUAvJFRha2Ugb25lIGRvd24gYW5kIHBhc3MgaXQgYXJvdW5kLC0jL14uCi0qLz8xQD8wIzwwIT8wQC0lLzk5IT85QD84Izw4IT84QD83Izw3IT83QD82Izw2IT82QD81Izw1IT81QD80Izw0IT80QD8zIzwzIT8zQD8yIzwyIT8yQD8xIzwxIS0mLz85IwolKi08Lwo5KDkvJSovPC8KOCg4KTcoNyk2KDYpNSg1KTQoNCkzKDMpMigyKTEoMSkwKDAtCjAvCi0gMC8gLyMvMStzLzErLwolIDAxJEdvIHRvIHRoZSBzdG9yZSBhbmQgYnV5IHNvbWUgbW9yZSwgMDk5Xi4&input=)
### Each step of decompression
Since replacements followed by replacements will have the string `//`, it will appear often.
It appears often enough that I decided to compress `//` into `-`.
When this is decompressed, the result is as follows:
```
/+/ bottle//)/\/&\/<\/
//(/\/\/?\/ //>/+s of beer//^/> on the wall//!/^,//$/>.
//@/$Take one down and pass it around,//#/^.
//*/?1@?0#<0!?0@//%/99!?9@?8#<8!?8@?7#<7!?7@?6#<6!?6@?5#<5!?5@?4#<4!?4@?3#<3!?3@?2#<2!?2@?1#<1!//&/?9#
%*//</
9(9/%*/</
8(8)7(7)6(6)5(5)4(4)3(3)2(2)1(1)0(0//
0/
// 0/ /#/1+s/1+/
% 01$Go to the store and buy some more, 099^.
```
The string `bottle` only appeared three times, but I compressed it to `+` anyways:
```
/)/\/&\/<\/
//(/\/\/?\/ //>/ bottles of beer//^/> on the wall//!/^,//$/>.
//@/$Take one down and pass it around,//#/^.
//*/?1@?0#<0!?0@//%/99!?9@?8#<8!?8@?7#<7!?7@?6#<6!?6@?5#<5!?5@?4#<4!?4@?3#<3!?3@?2#<2!?2@?1#<1!//&/?9#
%*//</
9(9/%*/</
8(8)7(7)6(6)5(5)4(4)3(3)2(2)1(1)0(0//
0/
// 0/ /#/1 bottles/1 bottle/
% 01$Go to the store and buy some more, 099^.
```
Then, `)` corresponds to `/&/</` followed by a newline, and `(` corresponds to `//?/` , which are patterns that will be often used later:
```
/>/ bottles of beer//^/> on the wall//!/^,//$/>.
//@/$Take one down and pass it around,//#/^.
//*/?1@?0#<0!?0@//%/99!?9@?8#<8!?8@?7#<7!?7@?6#<6!?6@?5#<5!?5@?4#<4!?4@?3#<3!?3@?2#<2!?2@?1#<1!//&/?9#
%*//</
9//?/ 9/%*/</
8//?/ 8/&/</
7//?/ 7/&/</
6//?/ 6/&/</
5//?/ 5/&/</
4//?/ 4/&/</
3//?/ 3/&/</
2//?/ 2/&/</
1//?/ 1/&/</
0//?/ 0//
0/
// 0/ /#/1 bottles/1 bottle/
% 01$Go to the store and buy some more, 099^.
```
Now, we would decompress some useful strings:
* `>` decompresses to `bottles of beer`
* `^` decompresses to `bottles of beer on the wall`
* `!` decompresses to `^,`, where `^` is the one above.
* `$` decompresses to `>.\n`, where `>` is the first rule and `\n` is a newline.
* `@` decompresses to `$` followed by `Take one down and pass it around,`, where `$` is the rule above.
The decompressed code now becomes:
```
/*/?1 bottles of beer.
Take one down and pass it around,?0 bottles of beer on the wall.
<0 bottles of beer on the wall,?0 bottles of beer.
Take one down and pass it around,//%/99 bottles of beer on the wall,?9 bottles of beer.
Take one down and pass it around,?8 bottles of beer on the wall.
<8 bottles of beer on the wall,?8 bottles of beer.
Take one down and pass it around,?7 bottles of beer on the wall.
<7 bottles of beer on the wall,?7 bottles of beer.
Take one down and pass it around,?6 bottles of beer on the wall.
<6 bottles of beer on the wall,?6 bottles of beer.
Take one down and pass it around,?5 bottles of beer on the wall.
<5 bottles of beer on the wall,?5 bottles of beer.
Take one down and pass it around,?4 bottles of beer on the wall.
<4 bottles of beer on the wall,?4 bottles of beer.
Take one down and pass it around,?3 bottles of beer on the wall.
<3 bottles of beer on the wall,?3 bottles of beer.
Take one down and pass it around,?2 bottles of beer on the wall.
<2 bottles of beer on the wall,?2 bottles of beer.
Take one down and pass it around,?1 bottles of beer on the wall.
<1 bottles of beer on the wall,//&/?9 bottles of beer on the wall.
%*//</
9//?/ 9/%*/</
8//?/ 8/&/</
7//?/ 7/&/</
6//?/ 6/&/</
5//?/ 5/&/</
4//?/ 4/&/</
3//?/ 3/&/</
2//?/ 2/&/</
1//?/ 1/&/</
0//?/ 0//
0/
// 0/ / bottles of beer on the wall.
/1 bottles/1 bottle/
% 01 bottles of beer.
Go to the store and buy some more, 099 bottles of beer on the wall.
```
[Answer]
## Haskell, ~~228~~ 223 bytes
```
o=" of beer on the wall"
a n=shows n" bottle"++['s'|n>1]
b 1="Go to the store and buy some more, "++a 99
b n="Take one down and pass it around, "++a(n-1)
f=[99,98..1]>>= \n->[a n,o,", ",a n," of beer.\n",b n,o,".\n\n"]>>=id
```
Function `f` returns a string with the lyrics.
[Answer]
# Brainfuck, 743 bytes
```
++++++++++>>--->++++>------>-->>++>+>>+>->++[[>+++++++[>++>+>+<<<-]<-]+<+++]>>>>>--
>>-->>++>->+++[<]>[-<<+[<->-----]<---[<[<]>[->]<]+<[>-]>[-<++++++++++<->>>]-[<->---
--]<+++[<[<]>[+>]<]<->>>[>[[>]<<<<.<<<<---.>>>-.<<<++++.<.>>>.-.<<.<.>-.>>+.<+++.>-
.<<<.>---.>>.<<+++.<.>>>++.<<---.>----..<<.>>>>--.+++<<+.<<.>.>--.>-.<+++.->-.+<<++
+.<<.>.<<<<-<]>[[>]<<<-.<<<.<<<.>>.>.<<< . > > .<++++.---.<.>>-.+.>.<--.<.<.>----.>
>-.<<+++.<.>--.>+++.++++.<<.>>------.>+.--.<<+++.<.>>>.++.<-.++<.-<<.>.<<<<-<<<++++
+++++.>>>]<+>]<++[<<[<]>[.>]>>>>>>.>--.>>.<..->>.<<<+++.<<<<-[>>>>>.[<]]<[>]>+>>>.>
>>.<<+.<.>----.+++..->-.++[<<]<-[>>>>>.>>>.-.+<<<.>>.<++++.---.<.>>+++.---<----.+++
>>>..[<<]]<<[>]>-[>>>>++.--<.<<<+[>>>.<<<<]>[>]<-<]>>[>>.>.<<<<]>[<<++>]<[>]<-]>+>]
```
[Try it online!](https://tio.run/##bVJbagRBCDxQoycQLyJ@JIFACOQjsOefVJXu4yPN7oyPKi3tef99@/r5vH18X9d5nEwzS1mmg1fCT2QQglWVi62Jn4iwxu8Egp08JC1R1So6yyJg2BQGwaxiEtkBdqUJ9VQDcGbbC0m1RDokCVAJTQ0V4XwA55RAh0U86Dp9mkwixsRgPIfhgg@a7ynEtk7qjOVUFUcBJlWDNCj0sxWYkxLqHGnTSd1ysuoofexAFwWYkhfbeeZYXfRpnnuXvSNE3exVv9Og2HB7kRPP3RKFdfKPjc5KPef2djKwHHPlLnJq1ACAb1xY87tIddRWVjXRsxHW7gdr7uH8O/3acS9ArJON9bHR1BBIizw1XYPKMQaXDWO3yyBVp1Ti44TQvq4/ "brainfuck – Try It Online")
The above uses wrapping cells in a few places to save instructions. I've also made a non-wrapping version in [755 instructions](https://github.com/primo-ppcg/bfal/blob/master/samples/bottles.bf).
---
**Uncompressed**
The following is a polyglot in [Brainfuck Annotation Language](https://github.com/primo-ppcg/bfal).
```
; byte sequence
; \n _ _ _ _ c \n comma space d t o l T G
++++++++++>>
--->++++>------>-->>++>+>>+>->++
[[>+++++++[>++>+>+<<<-]<-]+<+++]
>>>>>-->>-->>++>->+++[<]
c = 0
n = 100
>
while(n)
[
n = n minus 1
-<<
N = str(n)
; first time \n _ becomes 9 9
+[<->-----]<---[<[<]>[->]<]
+<[>-]>[-<++++++++++<->>>]
-[<->-----]<+++[<[<]>[+>]<]
<->>>
if(c)
[
>
if(n)
[
'Take one down and'
[>]<<<<.<<<<---.>>>-.<<<++++.<.>>>.-.<<.<.>-.>>+.<+++.>-.<<<.>---.>>.<<+++.
' pass it around' comma space
<.>>>++.<<---.>----..<<.>>>>--.+++<<+.<<.>.>--.>-.<+++.->-.+<<+++.<<.>.<<<<-<
]>
else
[
'Go to the store and'
[>]<<<-.<<<.<<<.>>.>.<<<.>>.<++++.---.<.>>-.+.>.<--.<.<.>----.>>-.<<+++.
' buy some more' comma space
<.>--.>+++.++++.<<.>>------.>+.--.<<+++.<.>>>.++.<-.++<.-<<.>.<<<<-
N = '9'
N
<<<+++++++++.>>>
]
<+>
]
c = c plus 2
<++
while(c)
[
N
<<[<]>[.>]>>>
' bottle'
>>>.>--.>>.<..->>.<<<+++.<<<<
if(n minus 1) 's'
-[>>>>>.[<]]<[>]>+
' of beer'
>>>.>>>.<<+.<.>----.+++..->-.++
[<<]<-
if(c minus 1)
[
' on the wall'
>>>>>.>>>.-.+<<<.>>.<++++.---.<.>>+++.---<----.+++>>>..[<<]
]
<<[>]>-
if(c minus 2)
[
period newline
>>>>++.--<.<<<+
if(c minus 1) newline
[>>>.<<<<]>[>]<-<
]>>
else
[
comma space
>>.>.<<<<
]
if(not n) c = c minus 2
>[<<++>]
c = c minus 1
<[>]<-
]
c = 1
>+>
]
```
[Answer]
# Vim, 139 bytes
*Saved 6 bytes due to [xsot](https://codegolf.stackexchange.com/posts/comments/179296?noredirect=1)*.
```
i, 99 bottles of beer on the wall.<ESC>YIGo to t<SO> store and buy some more<ESC>qa
3P2xgJX$12.+<CAN>YITake one down a<SO> pass it around<ESC>o<ESC>q98@adk?s
xn.n.ZZ
```
This is my first attempt at golfing Vim commands, although apparently it's [quite popular](http://www.vimgolf.com/). I've included the final `ZZ` in the byte count (write to file and exit) as it seems to be the accepted norm.
Side note: [mission accomplished](http://golf.shinh.org/p.rb?99+shinichiroes+of+hamaji#ranking).
---
**Explanation**
```
Command Effect
-------------------------------------------------------------------------------------------
i, 99 bottles of beer on the wall.<ESC> insert text at cursor
Y copy this line into buffer
IGo to t<SO> store and buy some more<ESC> insert text at beginning of line
auto-complete "the" (<Ctrl-N>, searches forward)
qa begin recording macro into "a"
<LF> move down one line (if present)
3P paste 3 times before cursor
2x delete 2 characters at cursor
gJ join this line with next (without space between)
X delete character before cursor
$ move to last non-whitespace character of line
12. repeat the last edit command (X) 12 times
+ move to column 0 of next line
<CAN> numeric decrement (<Ctrl-X>)
Y copy this line into buffer
ITake one down a<SO> pass it around<ESC> insert text at beginning of line
auto-complete "and" (<Ctrl-N>, searches forward)
o<ESC> insert text on new line
q stop recording macro
98@a repeat macro "a" 98 times
dk delete upwards (this line and the one above it)
?s<LF> move to previous /s/
x delete character at cursor
n.n. repeat last match and delete 2 times
ZZ write to file and exit
```
[Answer]
## Python 2, 195
```
i=198
while i:s=`i/2or 99`+' bottle%s of beer'%'s'[1<i<4:];print['%s, '+s+'.','Take one down and pass it around, %s.\n',"Go to the store and buy some more, %s."][i%2+1/i]%(s+' on the wall');i-=1
```
Took the `i/2` idea from [Sp3000's answer](https://codegolf.stackexchange.com/a/64227/20260).
[Answer]
## JavaScript ES6, 237 217 208 203 195 193 189 186 bytes
It is getting pretty hard to golf this...
**Edit 1:** Somebody totally outgolfed me, looks like I have to try harder if I want to have the best Javascript answer.
**Edit 2:** I honestly can't believe that I managed to golf it that much!
```
for(i=99,Y=" on the wall",o=k=>k+(i||99)+` bottle${i==1?'':'s'} of beer`;i;)alert(o``+Y+o`, `+o(--i?`.
Take one down and pass it around, `:`.
Go to the store and buy some more, `)+Y+`.`)
```
Did I mess up somewhere?
I also apologize for using `alert`, if you want to test my code, replace it with `console.log`.
Currently, there is one other notable Javascript answer: ["99 Bottles of Beer"](https://codegolf.stackexchange.com/questions/64198/99-bottles-of-beer/64235#64235). Check it out! :D
[Answer]
# JavaScript ES6, ~~210~~ ~~209~~ ~~205~~ ~~199~~ ~~198~~ 196 bytes
```
s=""
for(i=299;--i>1;s+=`${i/3|0||99} bottle${5/i^1?"s":""} of beer`+(i%3?" on the wall":i^3?`.
Take one down and pass it around`:`.
Go to the store and buy some more`)+(~i%3?", ":`.
`));alert(s)
```
This is a crude translation of my C submission. I don't actually know javascript so there is definitely room for improvement.
Edit: Neat, I discovered backticks
[Answer]
# Brainfuck, 4028 bytes
This is quite hideous.
Lots of duplication, and very inefficient, so it won't win any prizes. However, I started it, and was determined to finish it.
I may try and improve this, but probably wont, because frankly, my brain is fucked.
## Golfed
```
>>+++[-<+++<+++>>]>>++++++[-<++++++++++<++++++++++>>]<---<--->>>+++++[-<++++++>]
<++>>++++++++++[-<++++++++++>]<-->>++++++++++[-<+++++++++++>]<+>>++++++++++[-<++
++++++++>]<+>>++++++++++[-<++++++++++>]<++>>++++++++++[-<+++++++++++>]<++++++>>+
+++++++++[-<++++++++++>]<++++>>++++++++++[-<+++++++++++>]<-->>++++++++++[-<+++++
++++++>]<++++>>++++++++++[-<+++++++++++>]<+++++>>++++++++++[-<+++++++++++>]>++++
++++++[-<+++++++++++>]<+++++++++>>++++++++++[-<++++++++++>]<--->>+++++[-<++++++>
]<++>>++++[-<++++++++++++>]<---->>++++[-<++++++++++++>]<-->++++++++++>>+++++++++
+[-<+++++++++++>]<--->>++++++++++[-<++++++++++>]>++++++++++[-<+++++++++++>]<++>>
++++++++++[-<++++++++++>]<+++++>>++++++++++[-<+++++++++++>]<+++++++<<<<<<<<<<<<<
<<<<<<<<<<<<[>[->.>.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.<
<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>.<.<<<<<<
<<<<<<<<<.>.->.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.>>>>>>>.
>.<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<.<<<.>>.>>>>>>>>.<<<<<<<.<<<.>>>>>>>>>
>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<.>>>.<.<<.>>>>>>>>.<<<<<.>>>>>>.<<<<<<<.<<
<..>>>>.>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>.<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<
<<<<<<.>>>>>>>>.<<<<.<.<<<<<<<<<<<<<<<.>.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.
>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<
<<<..>>>>>>>>.>..<<<<<<<<<<<<<<<<<<<]<->+++++++++>.>.>.>.>.>>>..>>.<<<<.>>>>>>.<
<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>
>>>>>>>.>.<<<<<..>>>>>>>.<.<<<<<<<<<<<<<<<.->.+++++++++>.>.>.>>>..>>.<<<<.>>>>>>
.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.>>>>>>>.>.<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<
<<<<.<<<.>>.>>>>>>>>.<<<<<<<.<<<.>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<
.>>>.<.<<.>>>>>>>>.<<<<<.>>>>>>.<<<<<<<.<<<..>>>>.>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>
>>.<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>.<<<<.<.<<<<<<<<<<<<<<<
.>.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>>>>>>
>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>>.>..<<<<<<<<<<<<<<<<<<<<]
>--[->>.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>
>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>.<.<<<<<<<<<<<<<<.->.
>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.>>>>>>>.>.<<<<<<<<<<<.>
>>>>>>.>>>>>.<<<<<<<<<<<<<<.<<<.>>.>>>>>>>>.<<<<<<<.<<<.>>>>>>>>>>>>>>>>>>.<<<<<
<<<<<<<<<<<.>>>>>>>>>.<.>>>.<.<<.>>>>>>>>.<<<<<.>>>>>>.<<<<<<<.<<<..>>>>.>>>>>>>
.<<<<<<<<<<<<<<<.>>>>>>>>.<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>
.<<<<.<.<<<<<<<<<<<<<<.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>
>.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>>.>..<
<<<<<<<<<<<<<<<<<<]>>.>.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>
.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>.<.<<<<
<<<<<<<<<<.->.>.>.>>>..>>.<<<<.>>>>>>.<<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.>>>>>>>.>
.<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<.<<<.>>.>>>>>>>>.<<<<<<<.<<<.>>>>>>>>>>
>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<.>>>.<.<<.>>>>>>>>.<<<<<.>>>>>>.<<<<<<<.<<<
..>>>>.>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>.<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<
<<<<<.>>>>>>>>.<<<<.<.<<<<<<<<<<<<<<.>.>.>.>>>..>>.<<<<.<<<.>>.>>.<<<<.>.>>..>>>
>>.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>>.>..
<<<<<<<<<<<<<<<<<.>.>.>.>>>..>>.<<<<.<<<.>>.>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>>>>
>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>>>>>>>>.>.<<<<<..>>>>>>>.<.<<<<<<<<<<<<<<.++++++
++>.>.>.>>>..>>.<<<<.<<<.>>.>>.<<<<.>.>>..>>>>>.>>>>>>>.>.>---->>+++++++++>++++<
<<.<<<<<<<<<<<<<<<.<<.>>>>>.<<<.<<.>>>>>.>.<<<.<<<.>>>>>>>>>.<<<<.<<<.>>>>>>.<<<
<<.<<<.>>>>>>>>>>>>.<<.>>>>>>>>.<<<<<.<<<<<<<<<<<<.>>>>>>>>>>>>>>>>>>>>.<<.<<<<<
<.<<<<.<<<<<<<.>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<<.>>>>>>>>>>.>>>>>>>.<<<<<<<<<
<<<<<<<<<.>>>>>>.<<<<<.>>>>>>>>>>>.<.<<<<<<<<<<<<<<..>.>.>.>>>..>>.<<<<.>>>>>>.<
<<<<<<<<.>>.>>.<<<<.>.>>..>>>>>.<<<<<<<<.>>.>>>>>>>>.>>>.<<<<<<<<.>.<<<.<<<.>>>>
>>>>>>>.>.<<<<<..>>>>>>>>.>.
```
## Ungolfed
```
# SETUP COUNTERS
>>+++[-<+++<+++>>]
>>++++++[-<++++++++++<++++++++++>>]<---<--->>
# SETUP CONSTANTS
>+++++[-<++++++>]<++>
>++++++++++[-<++++++++++>]<--> # B
>++++++++++[-<+++++++++++>]<+> # O
>++++++++++[-<++++++++++>]<+> # E
>++++++++++[-<++++++++++>]<++> # F
>++++++++++[-<+++++++++++>]<++++++> # T
>++++++++++[-<++++++++++>]<++++> # H
>++++++++++[-<+++++++++++>]<--> # L
>++++++++++[-<+++++++++++>]<++++> # R
>++++++++++[-<+++++++++++>]<+++++> # S
>++++++++++[-<+++++++++++>] # N
>++++++++++[-<+++++++++++>]<+++++++++># W
>++++++++++[-<++++++++++>]<---> # A
>+++++[-<++++++>]<++> # SPACE
>++++[-<++++++++++++>]<----> # Comma
>++++[-<++++++++++++>]<--> # Stop
++++++++++> # Newline
>++++++++++[-<+++++++++++>]<---> # K
>++++++++++[-<++++++++++>] # D
>++++++++++[-<+++++++++++>]<++> # P
>++++++++++[-<++++++++++>]<+++++> # I
>++++++++++[-<+++++++++++>]<+++++++ # U
# BACK TO START
<<<<<<<<<<<<<<<<<<<<<<<<<
[>
[
-> # Dec x0 counter
.> # Print 0x char
.> # Print x0 char
.>
.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>. # Comma
<.
<<<<<<<<<<<<<<<.>.- # Counter with decrement
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
>>>>>>>. # Stop
>. # Newline
<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<. # Take
<<<.
>>.>>>>>>>>.<<<<<<<. # One
<<<.
>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<. # Down
>>>.
<.<<.>>>>>>>>. # And
<<<<<.
>>>>>>.<<<<<<<.<<<.. # Pass
>>>>.
>>>>>>>.<<<<<<<<<<<<<<<. # It
>>>>>>>>.
<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>. # Around
<<<<. # Comma
<.
<<<<<<<<<<<<<<<.>. # 0x and x0
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>>. # Stop
>.. # Newline x2
<<<<<<<<<<<<<<<<<<< # Reset loop
]
<-
>+++++++++
>.>.
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>. # Comma
<.
<<<<<<<<<<<<<<<.- # 0x with decrement
>.+++++++++ # x0 with increment
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
>>>>>>>. # Stop
>. # Newline
<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<. # Take
<<<.
>>.>>>>>>>>.<<<<<<<. # One
<<<.
>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<. # Down
>>>.
<.<<.>>>>>>>>. # And
<<<<<.
>>>>>>.<<<<<<<.<<<.. # Pass
>>>>.
>>>>>>>.<<<<<<<<<<<<<<<. # It
>>>>>>>>.
<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>. # Around
<<<<. # Comma
<.
<<<<<<<<<<<<<<<.>. # Counter
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>>. # Stop
>.. # Newline x2
<<<<<<<<<<<<<<<<<<<< # Reset outer loop
]
>-- # Decrement counter to only count from 7
# Last 8 loop
[
-> # Dec counter
>. # Print x0 char
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>. # Comma
<.
<<<<<<<<<<<<<<.- # x with decrement
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
>>>>>>>. # Stop
>. # Newline
<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<. # Take
<<<.
>>.>>>>>>>>.<<<<<<<. # One
<<<.
>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<. # Down
>>>.
<.<<.>>>>>>>>. # And
<<<<<.
>>>>>>.<<<<<<<.<<<.. # Pass
>>>>.
>>>>>>>.<<<<<<<<<<<<<<<. # It
>>>>>>>>.
<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>. # Around
<<<<. # Comma
<.
<<<<<<<<<<<<<<. # Count
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>>. # Stop
>.. # Newline x2
<<<<<<<<<<<<<<<<<<< # Reset loop
]
# Last but 1 exception
>>. # Counter
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>. # Comma
<.
<<<<<<<<<<<<<<.- # x with decrement
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
>>>>>>>. # Stop
>. # Newline
<<<<<<<<<<<.>>>>>>>.>>>>>.<<<<<<<<<<<<<<. # Take
<<<.
>>.>>>>>>>>.<<<<<<<. # One
<<<.
>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<.>>>>>>>>>.<. # Down
>>>.
<.<<.>>>>>>>>. # And
<<<<<.
>>>>>>.<<<<<<<.<<<.. # Pass
>>>>.
>>>>>>>.<<<<<<<<<<<<<<<. # It
>>>>>>>>.
<.<<<<.<<<<<<.>>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>. # Around
<<<<. # Comma
<.
<<<<<<<<<<<<<<. # Count
>.
>.>.>>>..>>.<<<<. # Bottle
<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>>. # Stop
>.. # Newline x2
# Last 1 exception
<<<<<<<<<<<<<<<<<. # Counter
>.
>.>.>>>..>>.<<<<. # Bottle
<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>. # Comma
<.
<<<<<<<<<<<<<<.++++++++ # x with reset to 99
>.
>.>.>>>..>>.<<<<. # Bottle
<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
>>>>>>>. # Stop
>. # Newline
>---- # Change K to G
>>+++++++++ # Change P to Y
>++++ # Change I to M
<<<.<<<<<<<<<<<<<<<. # Go
<<.
>>>>>.<<<. # To
<<.
>>>>>.>.<<<. # The
<<<.
>>>>>>>>>.<<<<.<<<.>>>>>>.<<<<<. # Store
<<<.
>>>>>>>>>>>>.<<.>>>>>>>>. # And
<<<<<.
<<<<<<<<<<<<.>>>>>>>>>>>>>>>>>>>>.<<. # Buy
<<<<<<.
<<<<.<<<<<<<.>>>>>>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<<. # Some
>>>>>>>>>>.
>>>>>>>.<<<<<<<<<<<<<<<<<<.>>>>>>.<<<<<. # More
>>>>>>>>>>>.
<.
<<<<<<<<<<<<<<.. # 99
>.
>.>.>>>..>>.<<<<.>>>>>>. # Bottles
<<<<<<<<<.
>>.>>. # Of
<<<<.
>.>>..>>>>>. # Beer
<<<<<<<<.
>>.>>>>>>>>. # On
>>>.
<<<<<<<<.>.<<<. # The
<<<.
>>>>>>>>>>>.>.<<<<<.. # Wall
>>>>>>>>. # Stop
>. # Newline x2
```
## Output:
~~Try it yourself here!~~
OK, so it seems the URL is too long to include here, so you will need to copy/paste to try it yourself.
I tested it using [this interpreter](https://copy.sh/brainfuck).
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), ~~1195~~ ~~1190~~ 932 bytes
```
"{"9"
^ }
""
<
713.101.801..:611.111.89.23}!:({.23.44.001.011.711.111.411.79.23.611.501.23..:511.79.211.23.001.011.79.23.011.911.111.001.23.101.(.:111.23.101.701.79.48\.411..:101.89.23.201.111.23.511.101.801..:611.111.89.23}!:{.23.44..:801.79.911.23.101.401.611.23.(.:111.23.411..:101.89.23.201.111.23.511.101.801..:611.111.89.23}!:{
_
3`<
_ (
""""
"
{(32.111.102.32.98.101:..114.32.111:.(.32.116.104.101.32.119.97.108:..46.\\49.32.98.111.116:..108.101.32.111.102.32.98.101:..114.32.111:.(.32.116.104.101.32.119.97.108:..44.32.49.32.98.111.116:..108.101.32.111.102.32.98.101:..114.46.\71.111.32.116.111.32.116.104.101.32.115:.).111.114.101.32.97.110.100.32.98.117.121.32.115.111.109.101.32.109.111.114.101.44.32.9!9!32.98.111.116:..108.101.115.32.111.102.32.98.101:..114.32.111:.(.32.116.104.101.32.119.97.108:..46.@
)
}
<
87\\.64..:801.79.911.23.101.401.611.23.(.:111.23.411..:101.89.23.201.111.23.511
_
3`<
_ (
v"""
```
This is a bit excessive...
While Labyrinth isn't particularly good at printing strings (because you need to push all the character codes), I think it should be possible to do better than this by using more but shorter long lines and getting even crazier with the grid rotation.
As I think any golfing improvements will substantially change the structure of this code, I'll wait with an explanation until I'm out of ideas how to golf it further.
[Answer]
# Julia, ~~227~~ ~~215~~ 213 bytes
```
w=" on the wall"
b=" bottles"
o=" of beer"
k=b*o
for n=99:-1:1
println("$n$k$w, $n$k.
$(n>1?"Take one down and pass it around":"Go to the store and buy some more"), $(n>1?"$(n-1)$(k=b*"\b"^(n<3)*o)":"99$b"o)$w.
")end
```
This uses string interpolation (`"$variable"`) and ternaries to construct the output and print it to STDOUT.
Saved 14 bytes thanks to Glen O!
[Answer]
# Windows Batch, 376 bytes
Very very long and ugly:
```
@echo off
setlocal enabledelayedexpansion
set B=bottles
set C=on the wall
set D=of beer
for /l %%* in (99,-1,1) do (
set A=%%*
if !A! EQU 1 set B=bottle
echo !A! !B! !D! !C!, !A! !B! !D!.
set /a A=!A!-1
if !A! EQU 1 set B=bottle
if !A! EQU 0 (
echo Go to the store and buy some more, 99 bottles !D! !C!.
) else (
echo Take one down and pass it around, !A! !B! !D! !C!.
echo.
))
```
[Answer]
# GolfScript, 143 bytes
```
[99.{[', '\.' bottle''s of beer'@(:i!>' on the wall''.
'n].1>~;5$4<\'Take one down and pass it around'i}**'Go to the store and buy some more'](
```
~~May still be room for improvement.~~ Getting close to the final revision, I think.
[Answer]
# Python, 254 bytes
```
b,o,s,t="bottles of beer","on the wall","bottle of beer",".\nTake one down and pass it around,"
i=99;exec'print i,b,o+",",i,b+t,i-1,b,o+".\\n";i-=1;'*97
print"2",b,o+", 2",b+t+" 1",s,o+".\n\n1",s,o+", 1",s+".\nGo to the store, buy some more, 99",b,o+"."
```
Pretty straightforward, assign some of the most common phrases, print each bit from 99 to 3, then print the last lines by adding together the variables and some strings.
[Answer]
## Python 2, 204 bytes
```
n=198
while n:s="bottle%s of beer"%"s"[:n^2>1];print n%2*"GToa kteo otnhee dsotwonr ea nadn dp absusy isto maer omuonrde,, "[n>1::2]+`n/2or 99`,s,"on the wall"+[", %d %s."%(n/2,s),".\n"[:n]][n%2];n-=1
```
The spec is quite underspecified in terms of whitespace, so here I'm assuming that the last line needs to have a single trailing newline. If the spec clarifies otherwise I'll update this answer.
I'm pretty happy with this, but looking at anarchy golf I feel like this can be golfed still, possibly with a different approach.
[Answer]
# JavaScript ES6, 214 bytes
>
> *Edit:* Deleted all previous code, view edits if you want to see the older code.
>
>
>
Limited popups:
```
p='.';o=" of beer";e=o+" on the wall";i=99;u=m=>i+" bottle"+(i==1?'':'s');while(i>0){alert(u()+e+", "+u()+o+p+(--i>0?"Take one down and pass it around, "+u()+e:"Go to the store and buy some more, 99 bottles"+e)+p)}
```
Expanded:
```
p='.';
o=" of beer";
e=o+" on the wall";
i=99;
u=m=>i+" bottle"+(i==1?'':'s');
while(i>0){
alert(u()+e+", "+u()+o+p+(--i>0?"Take one down and pass it around, "+u()+e:"Go to the store and buy some more, 99 bottles"+e)+p)
}
```
@commenters: Thanks for the idea of arrow functions, saved 15 bytes
For infinite beer just use this code here, 212 bytes
```
p='.';o=" of beer";e=o+" on the wall";i=99;u=m=>i+" bottle"+(i==1?'':'s');while(i>0){alert(u()+e+", "+u()+o+p+(--i>0?"Take one down and pass it around, "+u()+e:"Go to the store and buy some more, "+u(i=99)+e)+p)}
```
[Answer]
# CJam, ~~149~~ ~~148~~ ~~146~~ ~~144~~ ~~138~~ ~~137~~ 134 bytes
```
00000000: 39 39 7b 5b 22 2c 2e 22 22 01 bd 8f 2d b4 49 b5 f5 99{[",.""...-.I..
00000011: 9d bd 21 e8 f2 72 27 df 4d 4f 22 7b 32 36 39 62 32 ..!..r'.MO"{269b2
00000022: 35 62 27 61 66 2b 27 6a 53 65 72 28 65 75 5c 2b 2a 5b'af+'jSer(eu\+*
00000033: 7d 3a 44 7e 4e 4e 32 24 32 3e 29 34 24 4a 3c 5c 4e }:D~NN2$2>)4$J<\N
00000044: 5d 73 27 78 2f 39 39 40 2d 73 2a 7d 2f 27 73 2d 5d ]s'x/99@-s*}/'s-]
00000055: 22 07 9c 4b a2 4e 15 d7 df d5 82 88 c9 d9 a7 ad 37 "..K.N..........7
00000066: 16 7e 76 22 44 33 35 2f 28 5d 22 41 90 1d b1 f3 69 .~v"D35/(]"A....i
00000077: ba 3d 05 45 81 50 af 07 e4 1b 38 f7 19 22 44 .=.E.P....8.."D
```
The above hexdump can be reversed with `xxd -r`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=99%7B%5B%22%2C.%22%22%01%C2%BD%C2%8F-%C2%B4I%C2%B5%C3%B5%C2%9D%C2%BD!%C3%A8%C3%B2r'%C3%9FMO%22%7B269b25b'af%2B'jSer(eu%5C%2B*%7D%3AD~NN2%242%3E)4%24J%3C%5CN%5Ds'x%2F99%40-s*%7D%2F's-%5D%22%07%C2%9CK%C2%A2N%15%C3%97%C3%9F%C3%95%C2%82%C2%88%C3%89%C3%99%C2%A7%C2%AD7%16~v%22D35%2F(%5D%22A%C2%90%1D%C2%B1%C3%B3i%C2%BA%3D%05E%C2%81P%C2%AF%07%C3%A4%1B8%C3%B7%19%22D).
At the cost of 9 extra bytes, for a total of **143 bytes**, we can avoid unprintable characters:
```
99{[", X bottles of beer on the wall."NN2$2>)4$J<\N]s'X/99@-s*}/'s-]"Take one down and pass it around"*35/("Go to the store and buy some more"\
```
### How it works
```
99{ e# For each I in [0 ... 98]:
[ e#
",." e# Push that string.
"…" e# Push a string.
{ e# Define a decoder function:
269b e# Convert the string from base 269 to integer.
25b e# Convert from integer to base 25.
'af+ e# Add 'a' to each base-25 digit.
'jSer e# Replace j's with spaces.
( e# Shift the first character from the resulting string.
eu e# Convert it to uppercase.
\+ e# Prepend it to the remaining string.
* e# Join the string/array on the stack, using the
e# generated string as delimiter.
}:D~ e# Name the function D and execute it.
e# This pushes ", x bottles of beer on the wall.".
NN e# Push two linefeeds.
2$ e# Push a copy of the generated string.
2>) e# Discard the first two characters and pop the dot.
4$ e# Push another copy of the generated string.
J< e# Discard all but the first 19 characters.
e# This pushes ", x bottles of beer on the wall".
\N e# Swap the string with the dot and push a linefeed.
]s e# Collect in an array and cast to string.
'x/ e# Split at occurrences of 'x'.
99@- e# Rotate I on top of 99 and compute their difference.
s* e# Cast to string and and join.
e# This replaces x's with 99-I.
}/ e#
's- e# Remove all occurrences of 's' for the last generated string.
] e# Wrap the entire stack in an array.
"…"D e# Join the array with separator "Take one down and pass it around".
35/( e# Split into chunks of length 35 and shift out the first.
e# This shifts out ", 99 bottles of beer on the wall.\n\n".
] e# Wrap the modified array and shifted out chunk in an array.
"…"D e# Join the array with separator "Go to the store and buy some more".
```
[Answer]
## C, ~~303~~ ~~299~~ 297 bytes
```
#define B"%d bottle%s of beer"
#define O" on the wall"
#define P printf(
#define V(n,m,S)q(n);P O);P", ");q(n);P S);q(m);P".\n");
*s[]={"","s"};q(n){P B,n,s[n>1]);}main(){for(int i=99;--i;){V(i+1,i,".\nTake one down and pass it around, ")P"\n");}V(1,99,".\nGo to the store and buy some more, ");}
```
Compile with `gcc -std=c99 -w`.
[Answer]
# Mathematica, ~~238~~ ~~226~~ ~~222~~ 224 bytes
Saved several bytes thanks to Martin Büttner.
```
a={ToString@#," bottle",If[#<2,"","s"]," of beer"}&;b=a@#<>" on the wall"&;Echo[{b@n,", ",a@n,".
"}<>If[n<2,"Go to the store and buy some more, "<>b@99<>".","Take one down and pass it around, "<>b[n-1]<>".
"]]~Do~{n,99,1,-1}
```
[Answer]
## PHP, 172 bytes
```
<?for(;100>$a=1+$a." bottle$o[21] of beer";$o="
Take one down and pass it around, $b.
".$g="$b, $a.$o")$b="$a on the wall";echo"$g
Go to the store and buy some more, $b.";
```
The most significant trick is `$o[21]`. On the first iteration, `$o` will be undefined, resulting in an empty string. On each iteration after, it refers to the first `s` of `pass`.
[Answer]
## C, 230 bytes
My first codegolfing and learning C!
```
#define B "%d bottle%s of beer"
main(i,a){for(i=99;i;i--)a=i<2,printf(B" on the wall, "B".\n%s, "B" on the wall.\n\n",i,"s"+a,i,"s"+a,a?"Go to the store and buy some more":"Take one down and pass it around",a?99:i-1,"s"+(i==2));}
```
Compiled with `gcc -std=c99 -w beer.c`
Readable (sort of):
```
#define B "%d bottle%s of beer"
main(i,a){
for (i = 99; i; i--) {
a=i<2;
printf(B" on the wall, "B".\n%s, "B" on the wall.\n\n",
i, "s"+a, i, "s"+a,
a? "Go to the store and buy some more":"Take one down and pass it around",
a? 99 : i-1, "s"+(i==2));
}
}
```
My first entry (**293 bytes**):
```
#define BOT "bottle%s of beer"
main(){
char *e[]={"Go to the store an buy some more","Take one down and pass it around"};char *z[]={"","s"};
for(int i=99;i>0;i--){int j=i>1?i-1:99;char* s=z[i>1];
printf("%d "BOT" on the wall, %d "BOT". %s, %d "BOT" on the wall.\n",i,s,i,s,e[i>1],j,z[j>1]);}}
```
Haha, I love all these nasty tricks i applied that i never though could even exist in C!
[Answer]
# [Beam](http://esolangs.org/wiki/Beam), ~~1141~~ 1109 bytes
I still have a lot of room to golf this further with all the empty spaces, but it is getting really hard to follow and breaks quite easily :)
It's very similar to the one that I posted for this [question](https://codegolf.stackexchange.com/a/62123/31347), except it goes to the store before the beer reaches 1 and the cells used for the parameters have been shifted. I've also change the layout considerably. I'll try and do an explanation once I try out a couple more layouts.
```
P'P''''>`++++++)++'''P>`+++++++++++++)'''''''''''P+++++++++++++`P```>`++\ v@@++++++++++L(`<@+p'''''''''PL<
v``P''(++++++`<P'''''''''(++++++++`<L```P'+++++P'+++P'++++++P'++++P''''(/> p++@---@``p@'''''p+++@`> `)''' 'p-@''p\
>''p:'p@'p@'\>n' >`>`)'''p@''''p@\>n'''p@''''p@-@````p@'''''p@`>`)'''''/v `P+p``@p'''(`<@-p''''''''P'+up(`<`@@/
^/``@@p'@p''/ >'''\ /-p'@p'@p``@p``/`>-'P''''''''p+@>`)''p`n`L++++++++++@S 'p@````p@````p@'''''p@`p@````p@'''''p@```p++@---@``p@'''''p-@+@`p@+++@``p-@``p@'p-@'''p-@```p++@`p@'p@''''p+@++++@`````p@'''''p-@`p@--@``p-@``p@''''p--@p@+++@``p-@''''p-@>`)'''p@'p+:`p@'p@'''p@'p@@``p@`p-@'''p-@`>`)'''p@''''p@``p@``p@'p@'p-@@'''p--@`>`)'''p@''''p@-@````p@'''''p@`>`)'''''p++@---@``p@'''''p+++@`>`)''''p-@''p@@'''p+@H
^\p@`p-@```p`//'''/ \@@'''p--@`>`)'p/``````@pS@++++++++++L`<vP+p`P-p`P-p`@ p'''(`<@-p''''@--p``@-p`@+p'@p`@--p''''@-p'@p`````@p'''@+++p''@p```\
^ \'p-@/v \ p-@''p-@`p-@``p@''''p@ -@``p-@``p@'p ++@'''p@'p+++@`p-@````p@'p-@'''p-@```p++@`p@''''p+@```p-@''''p-@@``/
^ < < <
```
Try it in the stack snippet [here](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/57190#57190)
] |
[Question]
[
Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of \$N\$ characters, where \$1 \le N < \text{program length}\$.
For example, the three character Python 2 program
```
`8`
```
is a pristine program ([thanks, Sp](https://chat.stackexchange.com/transcript/message/25274283#25274283)) because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
```
8`
``
`8
```
and also all the programs resulting from removing substrings of length 2 cause errors:
```
`
`
```
If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.
Your task in this challenge is to write the shortest pristine program possible that takes no input but outputs any one of the following five words:
```
world
earth
globe
planet
sphere
```
Which word you choose is entirely up to you. The sole word plus an optional trailing newline should be printed to stdout (or your language's closest alternative). The shortest program in bytes wins.
**Notes:**
* A standalone program is required, not a function.
* The words are case sensitive; outputting `World` or `EARTH` is not allowed.
* Compiler warnings do not count as errors.
* The erroring subprograms can take input or give output or do anything else as long as they always eventually error.
Here's a stack snippet that will list what programs need to error given a potentially pristine program:
```
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>function go() { var s = $('#i').val(), e = []; for (var i = 1; i < s.length; i++) { for (var j = 0; j <= s.length - i; j++) { e.push(s.substring(0, j) + s.substring(j + i)); } } $('#o').val(e.join('\n---\n')); }</script>Program:<br><textarea id='i' rows='16' cols='80'>`8`</textarea><br><button onclick='go()' type='button'>Go</button><br><br>Programs that should error: (--- separated)<br><textarea id='o' rows='16' cols='80'></textarea><br>
```
[Answer]
# [Rail](https://esolangs.org/wiki/Rail), 24 bytes
```
$'main' #
-[world]o/
```
I *think* this works. And it's both short and readable (as far as Rail goes).
* If the removed substring includes any part of `$'main'` we get `Internal Error: Crash: No 'main' function found`.
* If the removed substring includes the `#`, there is no way for the program to exit cleanly, so it will always terminate with `Crash: No valid move`. I believe that it's not possible to delete a substring such that the track forms a valid (infinite) loop.
* If the removed substring is in front of the `#`, it will be disconnected from the end of the track, so the train will crash (with the same error as above).
* If the removed substring is after the `#`, it will also disconnect the `#` from the end of the track (and potentially even the beginning of the track from the entry point `$`). So again the same error.
As for the actual program: every Rail program needs to have a `$'main'` (or a longer variant, but we're golfing here) as an entry point into the function and the train starts on the `$` going South-East. Everything on that first line can be part of the track though, so removing the `'main'` the track is:
```
$ #
-[world]o/
```
The `-` and `/` are simply pieces of rail which we need to let the train take those 45° turns.
`[world]` pushes the string `world` and `o` prints it. `#` marks the end of the track - the only way to safely terminate a Rail program.
Interestingly, this solution is *only* possible because Rail allows the tracks to go through the `main` line - if that wasn't possible `#` would be after the first newline and the code could always be shortened to
```
$'main'
#
```
which is a valid program that doesn't do anything. (Non-space characters between `'` and `#` wouldn't affect that.)
Also quite interesting: if I had just *golfed* the task printing `world` it wouldn't have been much shorter or simpler:
```
$'main'
-[world]o#
```
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton) (~~186~~ 136 bytes in UTF-16)
```
╔══════════════╗
║19342823075080╟
║88037380718711║
╚══════════════╝
```
This program prints “world”.
Most substrings you remove from this will stop it from being a complete box, which the parser will complain about. The only possible removals that leave a complete box are:
```
╔══════════════╗
|║19342823075080╟ (remove this whole line)
|║88037380718711║
╚══════════════╝
╔══════════════╗
║|19342823075080╟ ← substring starts at | here
║|88037380718711║ ← substring ends at | here
╚══════════════╝
... ↕ or anything in between these that removes a whole line’s worth ↕ ...
╔══════════════╗
║19342823075080|╟ ← substring starts at | here
║88037380718711|║ ← substring ends at | here
╚══════════════╝
╔══════════════╗
|║19342823075080╟
║88037380718711║ (both lines entirely)
|╚══════════════╝
╔══════════════╗
║19342823075080╟
|║88037380718711║ (remove this whole line)
|╚══════════════╝
```
Most of these remove the dangling end at the top right of the box, which is the output connector. Without this loose end, the box is just a comment:
```
╔══════════════╗
║88037380718711║
╚══════════════╝
```
This is no longer a valid program because the parser expects a program with exactly one output:
>
> Error: Source files do not contain a program (program must have an output).
>
>
>
The only possibility that leaves an output connector is the last one of the above, which leaves this:
```
╔══════════════╗
║19342823075080╟
╚══════════════╝
```
However, this number does not encode a valid Unicode string in Funciton’s esoteric UTF-21. Try to run this, you get:
>
> Unhandled Exception: System.ArgumentOutOfRangeException: A valid UTF32 value is between 0x000000 and 0x10ffff, inclusive, and should not include surrogate codepoint values (0x00d800 ~ 0x00dfff).
>
>
>
Therefore, this program is pristine.
[Answer]
## Visual C++ - 96 95 bytes
```
#include<iostream>
#define I(a,b)a<<b
int main()I({std::cout,I('w',I('o',I('r',I('l','d';)))))}
```
**Properties:**
1. You can't remove any part of `int main()` without a compile error.
2. You can't remove the modify the macros expansion AT ALL, removing `a` at all means `main()` never gets `{`, removing `b` at all means our line doesn't end in a `;`, removing `<` means `std::cout<'w'` causes an error, and removing `<<` causes `std::cout'w'`, `'w''o'`, etc.
3. You can't remove parameters from the macro definition or invocation, the only valid names for the definition would be `I(a)`,`I(b)` which never match and `I` which expands to before `(`; on the other hand using `I(,` causes `<<<<`, and `,)` drops the semi-colon (barring any other errors).
4. You can't remove part of all of `std::cout` without running into a leading `<<`, and therefore cannot remove any of `#include<iostream>` in the beginning without a compile error.
5. You can't remove any part of a single character, `''` has an empty character error and `'w,`, etc... try to making everything into one character.
6. You can't remove the left/right side of a macro without leaving too many `)` or `(` on the other side, e.g. you cannot do things like `I('w',I('r'`.
Compiles online using [Visual C++](http://webcompiler.cloudapp.net/).
Once again this not an exhaustive proof. If you think you can get it too work without section be sure to let me know.
*Previous versions used a considerably different approach and was proved to not be pristine so I've removed those scores.*
---
**Verification:**
The following program has confirmed this version is pristine using the `cl` compiler from Visual C++ 2010. Wished I had bothered to write this sooner:
```
#include <fstream>
#include <iostream>
char *S = "#include<iostream>\n#define I(a,b)a<<b\nint main()I({std::cout,I('w',I('o',I('r',I('l','d';)))))}";
//uncomment to print source code before compile
// #define prints
int main(){
for(int i=0; i<95; i++)
for(int j=i; j<95; j++){
std::fstream fs;
fs.open ("tmptst.cpp",std::fstream::out);
for(int k=0; k<95; k++)
if(k<i || k>j){
fs << S[k];
#ifdef prints
std::cout<<S[k];
#endif
}
fs.close();
#ifdef prints
std::cout<<'\n';
#endif
//Compile and surpress/pipe all output
//if it doesn't compile we get a nonzero errorlevel (i.e.true) from system.
if(!system("cl -nologo tmptst.cpp >x"))
return 0;
}
std::cout<<"PRISTINE!";
}
```
[Answer]
# Python 3, ~~79~~ 33
```
if 5-open(1,'w').write('world'):a
```
`open(1,'w')` opens standard output, then we print the string. `write` returns the number of characters written. This is used to harden against substring removal: Removing part of the string causes something other than 5 to be returned, and 5 minus that value then evaluates to true. But that causes the `if`-body to be executed and `a` is undefined.
This is based on Anders Kaseorg's clever pristine quine [here](https://codegolf.stackexchange.com/a/132990/36695).
As only a single statement needs to be verified this is much shorter than the old solution, but also less general.
### Old solution:
```
try:
q="print('world');r=None"
if exec('e=q')==eval(q[17:]):exec(e)
finally:r
```
To verify that it really is a pristine program:
```
w=r'''try:
q="print('world');r=None"
if exec('e=q')==eval(q[17:]):exec(e)
finally:r'''
exec(w)
for j in range(1,len(w)):
for i in range(len(w)+1-j):
e=w[:i]+w[i+j:]
try:exec(e,{});print('WORKED',e)
except:pass
```
Some key points:
* Every executed statement could be deleted. Verifying that `q` has been executed requires a statement outside of `q`. The `try` solves that nicely, by requiring at least two statements, neither of which can be deleted fully.
* Verifying that `q` has executed happens by evaluating `r` at the end.
* Verifying that `q` was not modified is achieved by `eval(q[17:])`, which has to evaluate to `None` for `q` to be executed.
* The `if` condition is a bit tricky to get right. To ensure that it was evaluated it has the nice side effect of setting `e`, which is needed to set `r`. (This is the reason I used Python 3, `expr` as a function does wonders for expression-level side effects.)
[Answer]
# Haskell, 61
```
x=uncurry(:)
main=putStr$x('w',x('o',x('r',x('l',x('d',[])))))
```
Any type of error is OK? In that case:
# Haskell, 39
```
main=putStr$take 5$(++)"world"undefined
```
[Answer]
# JavaScript, ~~74~~ ~~73~~ 35 bytes
```
if((alert(a="world")?x:a)[4]!="d")x
```
It turns out the answer was much simpler than I thought...
## Explanation
```
if(
(
alert(a="world") // throws a is not defined if '="world"' is removed
?x // throws x is not defined if 'alert' or '(a="world")' is removed
:a // throws a is not defined if 'a="world"' or 'a=' is removed
)
[4]!="d" // if "world" is altered fifth character will not be "d"
// if 'd' is removed it will compare "world"[4] ("d") with ""
// if '[4]' is removed it will compare "world" with "d"
// if '(alert(a="world")?x:a)' is removed it will compare [4] with "d"
// if '?x:a' is removed [4] on alert result (undefined[4]) will error
// if '[4]!="d"' is removed the if will evaluate "world" (true)
// if '!', '!="d"' or '(alert...[4]!=' is removed the if will
// evaluate "d" (true)
)x // throws x is not defined if reached
// any other combination of removing substrings results in a syntax error
```
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), ~~143~~ ~~142~~ 136 bytes
Score is in UTF-8 as usual, as UTF-16 would be two bytes larger (due to the BOM).
```
╔══════════╗
║1934282307║╔╗
║5080880373╟╚╝
║80718711 ║
╚══════════╝
```
So, I've been contemplating a Funciton answer for a while and I figured it would be impossible, because you could always remove a full line and the code would still form a valid block. Then I talked to Timwi about it, and [he figured out](https://codegolf.stackexchange.com/revisions/63537/1) that you can just put the entire number in a single line, such that removing it would break the program for lack of an output connector.
But literals on a single line are notoriously expensive, both because of the larger character count *and* because of the larger number of non-ASCII characters. And his mention of an "empty comment" block got me thinking...
So I came up with this more efficient solution which uses an additional empty comment block which breaks when you try removing anything which would leave the literal block in tact:
* We can't possibly remove the third line, because then we'd remove the output connector.
* If we remove the second line, the comment block loses its top edge and breaks.
That leaves two options (thanks to [Steve](https://codegolf.stackexchange.com/users/46698/steve) for pointing that out):
* Remove the fourth line. That leaves both boxes in tact. However, when the resulting integer `19342823075080880373` is decoded, the corresponding string would contain the code point `0x18D53B` which is not a valid Unicode character, `System.Char.ConvertFromUtf32` crashes with an `ArgumentOutOfRangeException`.
* Remove a full line starting after the top-right corner. Again, both boxes are left in tact, but the resulting integer `508088037380718711` would contain two invalid code points `0x1B0635` and `0x140077`, leading to the same exception.
Note that even without the empty comment block, removing the second line would lead to an invalid code point. But the comment block prevents that we're taking a line from *inside* the second line, to get an integer like `193428037380718711` for instance, which would not cause an error.
[Answer]
# Java 8, 301 bytes
Because every question needs a Java answer.
```
class C{static{System.out.print(((((w='w')))));System.out.print((((o='o'))));System.out.print(((r='r')));System.out.print((l='l'));System.out.print(d='d');e=(char)((f=1)/((g=8)-C.class.getDeclaredFields()[h=0].getModifiers()));}public static void main(String[]a){}static final char w,o,r,l,d,e,f,g,h;}
```
## Expanded
```
class C {
static {
System.out.print(((((w = 'w')))));
System.out.print((((o = 'o'))));
System.out.print(((r = 'r')));
System.out.print((l = 'l'));
System.out.print(d = 'd');
e = (char) ((f = 1) / ((g = 8) - C.class.getDeclaredFields()[h = 0].getModifiers()));
}
public static void main(String[] a) { }
static final char w, o, r, l, d, e, f, g, h;
}
```
## Explanation
* `public static main(String[]a){}` is required.
* If the field declarations are removed (or made non-static), the first static block can't find them.
* If the static block is removed (or made non-static), the fields aren't initialized.
### The hardest part:
* If the `final` keyword is removed, the second line evaluates to `1/(8-8)`, causing a `/ by zero` exception.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 17 bytes
```
e"ooooo7-c0pBhtra
```
[Try it online!](https://tio.run/##S8sszvj/P1UpHwTMdZMNCpwySooS//8HAA "><> – Try It Online")
Prints "earth".
The only way a `><>` program exits without an error is executing the `;` character, which is a problem as you can just remove all the characters before that, so that `;` is the first character executed. You can get around that by using the `p` command to modify the program to include `;` during execution instead. Removing any section of the code causes the `;` to never be produced causing errors via the invalid instructions `B`, `h` and `t`, stack underflow, and infinite loops making it eventually run out of memory. I only had to make sure that all the infinite loops kept filling up the stack.
All variants were tested using this python snippet:
```
code = 'e"ooooo7-c0pBhtra'
count = {"invalid":0, "underflow":0, "memory":0}
for l in range(1, len(code)):
for x in range(0, len(code)-l+1):
print(code[:x] + code[x+l:], "\t\t", end='')
try:
interp = Interpreter(code[:x]+code[x+l:])
for _ in range(0,1000):
interp.move()
print(len(interp._stack), "< ", end='')
interp2 = Interpreter(code[:x]+code[x+l:])
for _ in range(0,2000):
interp2.move()
print(len(interp2._stack))
count["memory"] += 1
except Exception as e:
print(e)
if str(e) == "pop from empty list": count["underflow"] += 1
else: count["invalid"] += 1
print(count)
#don't judge me
```
added to (a slightly modified version of) the official [fish.py](https://gist.github.com/anonymous/6392418) interpreter by the creator of ><>. Out of 152 possible sub-programs, 92 errored from invalid instructions, 18 from stack underflow, and 42 from running out of memory.
Funny facts, the first version of this `e"ooooo6-c0pAhtra` had a couple of freak sub-programs that managed to use the put command to place a `[` which would clear the stack, in place of the invalid instruction `A`. Also, "earth" is the only one of the phrases that will work with this method, because the first letter, `e` is a valid instruction in `><>`. Otherwise the `"` command has to be placed at the front of the program, and a valid subprogram could be just `"` by itself.
[Answer]
# Ruby, 36
```
eval(*[(s="planet")[$>.write(s)^6]])
```
We assign `s="planet"`, then write that string to STDOUT. This returns the number of characters written. We xor that with 6, so that if anything other than 6 characters were written, we'll get a nonzero integer. Then we slice into `s` with that index. Only the 0th character of `s`, "p", is a valid code string (a no-op). We pass that to `eval`, using the `(*[argument])` syntax which is equivalent to just `(argument)` except that it's not valid outside of a method call.
Pristineness verified programmatically on Ruby 1.9.3 and 2.2
[Answer]
# C#, ~~128~~ ~~118~~ 101 bytes
Thought of abusing the contiguous substring rule.
**The Code**
```
class h{static void Main()=>System.Console.Write(new char[1
#if!i
*5]{'w','o','r','l','d'
#endif
});}
```
**Why It Works**
1. `class h` and `static void Main()` are required.
2. Removing any of the chars in `'w','o','r','l','d'` causes an error because the char array is initialized with length `1*5`.
3. You can't remove the contents inside Main() without violating the contiguous character rule as parts are separated by preprocs. (See below)
**Before Golfing and Separation**
```
class h
{
static void Main() =>
System.Console.Write(new char[1 * 5]{'w','o','r','l','d'});
}
```
**Verified With**
<https://ideone.com/wEdB54>
EDIT:
* Saved some bytes by using `#if !x` instead of `#if x #else`.
* Used `=>` func syntax. `#if!x` instead of `#if !x`. Credits to @JohnBot.
* Due to `=>` func syntax, extra preproc condition can be removed.
[Answer]
## MATLAB, 37 36 33 bytes
```
feval(@disp,reshape('world',1,5))
```
Since I am not sure if we are allowed to also output *ans=*, I had to find some work-around to output in a proper way. Using *fprintf* by itself did not work, because no matter what I tried it simply refused to error. Using *disp* by itself was not an option, as it would only take 1 argument and that argument itself obviously would also execute without errors.
If it's no problem to also include *ans=* in the output, then MATLAB can be done with **20 bytes**:
```
reshape('world',1,5)
```
[Answer]
# Ruby, 34
```
eval(*[($>.write("world")-1).chr])
```
This has a few components:
`eval(*[` *expr* `])` is borrowed from [histocrat's answer](https://codegolf.stackexchange.com/a/63498/31388), and is pristine as well as verifying the return value of *expr* is a valid ruby program that doesn't error. `method(*arr)` is a ruby syntax that calls `method` with the values of `arr` as the arguments. The reason this is needed here is because it is *only* valid as parameters for a method, so that if `eval` is removed, `(*[expr])` is a syntax error. If *expr* is removed, `eval` complains about not having enough arguments
`$>.write("world")-1` cannot be mangled except for inside the string and the subtraction. `$>.write("world")` writes "world" to STDOUT and returns the number of characters written, then subtracts 1. Therefor if the program is un-mangled the value will be exactly **4**. If it is mangled (either the `-1` is removed or the string shortened) then it will return one of **-1,0,1,2,3, or 5**. Any other mangling results in a syntax error.
Calling `chr` on a number returns the character represented by that number. So, when called on the result of the above example, it errors on -1, and returns a single-character string otherwise.
I'm not actually sure why this is, but it seems that ruby interprets `\x04` as a whitespace character, which means the expression is valid (empty ruby programs do nothing). However, any of the other characters (`\x00` - `\x03` and `\x05`) result in `Invalid char '\x01' in expression`. I found this by simply iterating over possible math I could do to the number returned. Previously I had used
```
$>.write("planet
")*16
```
where "planet" plus a newline was 7 chars, times 16 to get 112 for `p`, the only single-letter function in ruby defined by default. When given no arguments, it is effectively a no-op
---
Honorable mention: `$><<"%c"*5%%w(w o r l d)` is very close but not pristine. Removing `"%c"*5%` results in no errors. Mini-explanation:
`$>` is stdout, and `<<` is a function being called on it. `"%c"*5` generates the format string `"%c%c%c%c%c"`, which then then trys to be formatted (`%`) by an array: `%w(w o r l d)` which is a shorter version of `['w','o','r','l','d']`. If there are too few or too many elements in the array such that it does not match the format string, an error is thown. The achilles heel is that `"%c"*5`, and `%w(w o r l d)` can both exist independantly, and `$><<` only needs an argument of either. So there are a few different ways of mangling this program into non-erroring cousins.
---
Validated using this:
```
s = 'eval(*[($>.write("world")-1).chr])'
puts s.size
(1...s.length).each do |len| #how much to remove
(0...len).each do |i| #where to remove from
to_test = s.dup
to_test.slice!(i,len)
begin #Feels so backwards; I want it to error and I'm sad when it works.
eval(to_test)
puts to_test
puts "WORKED :("
exit
rescue SyntaxError
#Have to have a separate rescue since syntax errors
#are not in the same category as most other errors
#in ruby, and so are not caught by default with
#a plain rescue
rescue
#this is good
end
end
end
```
[Answer]
# [Python 3](https://docs.python.org/3/), 43 bytes
```
for[]in{5:[]}[open(1,"w").write("world")]:a
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/KDo2M6/a1Co6tjY6vyA1T8NQR6lcSVOvvCizJFVDqTy/KCdFSTPWKvH/fwA "Python 3 – Try It Online")
### How it works
To protect against substring deletions, we use `open(1,"w").write` instead of `print`. In Python 3, `write` returns the number of written characters, which we will verify is `5` to ensure that no part of the string was deleted. We do this by looking up the return value in the dictionary `{5:[]}`, and looping over the result with `for[]in…:a`, which will fail if we didn’t get an empty iterable or if the `for` statement is deleted.
[Answer]
# Perl 5.10+, ~~71~~ 63 bytes
```
(${open 0;@{\(read(0,$a,63)!=63?die:@_)};say"world"});{$a//die}
```
Prints `world` with a trailing newline. Run like this:
```
perl -M5.010 file
```
This relies on the byte count of the source code, so `file` must contain the above code and nothing else (no shebang, no trailing newline). Perl 5.10+ is required for `say` and the defined-or operator `//`.
---
It's incredibly difficult to make a pristine program with Perl, because:
* Any bareword identifier (e.g. `foo`, `a`, `_`) is a valid statement with `no strict 'subs';` (the default). This means the program can neither begin nor end with a letter, number, or underscore.
* As [tchrist explains](https://stackoverflow.com/a/4800711/176646), "Identifiers specified via symbolic dereferencing have **absolutely no restriction whatsoever** on their names." This means the program cannot begin with any of the sigils `$`, `@`, `%`, or `*`, since removing all but the first and last character would always leave a valid variable name.
* Many built-in functions (including most functions capable of producing output) work on `$_` by default, so calls will often work even if you remove the argument (e.g. `say"world"` vs. `say`).
## How it works
This solution was inspired by [Naouak's Node.js answer](https://codegolf.stackexchange.com/a/63525/31388), which checks its own length to make sure characters haven't been removed.
The program has two sections, one inside parentheses and the other inside a block:
```
(...);{...}
```
The first section reads the source file and dies if it is less than 63 characters long. The second section checks that the `read` executed successfully. If either section is removed (with or without the enclosing parentheses or curly braces), the other section will throw an exception.
Removing the middle or the left or right side of the program will unbalance the parentheses and/or curly braces, causing a syntax error.
If the first `die` is altered (to `d`, `e`, `di`, `de`, or `ie`, which are all valid identifiers), the length check becomes:
```
@{\(read(0,$a,63)!=63?di:@_)};
```
which evaluates to:
```
@{\'di'};
```
This takes a reference to a string and tries to dereference it as an array, producing an error:
```
Not an ARRAY reference
```
If any other statement is altered, the length check will fail and the program will die.
---
Verified pristine with the following program:
```
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use File::Temp;
use List::MoreUtils qw(uniq);
sub delete_substr {
my ($str, $offset, $len) = @_;
my $tmp = $str;
substr($tmp, $offset, $len) = '';
return $tmp;
}
sub generate_subprograms {
my ($source) = @_;
my $tot_len = length $source;
my @subprograms;
foreach my $len (1 .. $tot_len - 1) {
foreach my $offset (0 .. $tot_len - $len) {
push @subprograms, delete_substr($source, $offset, $len);
}
}
return uniq @subprograms;
}
chomp(my $source = <DATA>);
my $temp = File::Temp->new;
foreach my $subprogram ( generate_subprograms($source) ) {
print $temp $subprogram;
my $ret = system(qq{/usr/bin/perl -M5.010 $temp > /dev/null 2>&1});
say($subprogram), last if $ret == 0;
truncate $temp, 0;
seek $temp, 0, 0;
}
__DATA__
(${open 0;@{\(read(0,$a,63)!=63?die:@_)};say"world"});{$a//die}
```
[Answer]
# Ruby + coreutils, ~~33~~ ~~27~~ 26 bytes
```
`base#{$>.write"world
"}4`
```
[Try it online!](https://tio.run/##KypNqvz/PyEpsThVuVrFTq@8KLMkVak8vygnhUup1iTh/38A "Ruby – Try It Online")
Backticks in ruby execute the command inside them and return whatever the program put into STDOUT as a string. The `#{expr}` syntax allows embedding of expressions in strings and backticks. This program could be rewritten (non-pristinely) as:
```
system("base" + (STDOUT.write("world\n")).to_s + "4")
```
`IO#write` returns the number of bytes written, so if the string is shortened then it won't be the right number. `#{}` embedding automatically makes the number into a string. If some piece is removed, and it doesn't result in a syntax error, the wrong command will be run. If part of `"world"` is removed than one of `base04` through `base54` will try to run.
The newline, whether in or out of the string, is required. Otherwise the first 5 characters(``base`) can be removed, making the whole line a comment. Also there must be one or more characters between the first backtick and `#`, otherwise the `{` can get removed to make the whole thing a *shell* comment.
---
```
exec(*[(s="ec%co earth")%s[10]])
```
`exec` Replaces the current ruby process with the command specified. See [my other answer](https://codegolf.stackexchange.com/a/63625/46718) for an explanation of the `meth(*[])` syntax and the neccesity of it.
`(s="ec%co earth")` assigns the string "ec%co earth" to the variable `s`. Assignments return what was assigned, so the string is also returned.
`"format string %d" % 5` is syntactic sugar for `sprintf("format string %d",5)`, however spaces around the `%` are not neccesary.
`s[10]` gets the character in the string at index 10. When un-mangled, this character is "h", the last letter in the string. However, removing any characters in the string means the string is shorter, so there is no character at index 10, so `s[10]` returns `nil`, and `"%c" % nil` causes an error.
if `%s[10]` is removed, then ruby tries to run the command `ec%co earth` which doesn't work.
Changing `10` to `1` or `0` also results in an unknown command (either `eceo` or `ecco`). Removing it entirely is technically not a syntax error since it calls the method `#[]` on the string, but then it complains about not enough arguments.
---
A note on solving this in general: You must have some wrapper that verifies the code inside in an abstract sense while being pristine itself. For example, a program with division at the end (`blablabla/somevar`) will never work because a division can always be removed(`blablabla`). These are some such wrappers I've used so far:
* `eval(*[` code `])` used by histocrat and in my first answer. Validates that the output is a valid ruby program
* `exec(*[` code `])` used above, validates that the response is a valid command
* ``#{` code `}``
The backtick syntax also runs a command (and therefor validates that it's a valid one), however STDOUT is captured as a string instead of being output as the parent process' (Ruby's) STDOUT. ~~Due to this I was not able to use it for this answer,~~ EDIT: I made it work. Limitations outlined above.
Edit: Thanks to @histocrat for pointing out some flaws
[Answer]
# Javascript(Node.js), ~~93~~ 95 bytes
```
if(l=arguments.callee.toString().length,l!=158)throw l;console.log("world");if(g=l!=158)throw g
```
Check it's own size twice so if any chars is missing an error is thrown.
The length is 156 because Node.js prepends `function (exports, require, module, __filename, __dirname) {` to the code on runtime.
Thanks Martin Büttner for pointing out an error. Fixed now.
[Answer]
# [C (gcc)](https://gcc.gnu.org/) (Linux,`-Werror=undef`), 66 bytes
```
main(a){a
=
1
/
(puts("world")/
6);
#if(7^__LINE__)
#else
}
#endif
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1GzOpHLlsuQS59Lo6C0pFhDqTy/KCdFSVOfy0zTmks5M03DPC4@3sfTzzU@XpNLOTWnOJWrFkjnpWSm/f//LzktJzG9@L9ueGpRUX6RbWleSmoaAA "C (gcc) – Try It Online")
Great challenge! This was deceptively hard, but I'm pretty sure I have a valid program now!
Uses a preprocessor command so that no newlines can be removed, since the closing bracket to `main` is included only if `__LINE__==6`. It also keeps you from just clearing out `main` entirely, since that leaves `#endif` floating (so it is important that `#endif` is outside of `main`).
I used `#else` because I've become fairly convinced there's no version of `__LINE__==6` that can't have a substring removed and still be true, since both `6` and `__LINE__` by themselves are truthy. It also uses `-Werror=undef` so that something like `#ifdef(LINE__)` doesn't evaluate to false, but is an error.
With gcc (on Linux, at least), `puts` returns the number of characters printed (including the trailing newline), so removing any part of the string makes `puts("...")/6` return `0`, so that `1/0` causes a floating point exception. Note that this exception isn't caused unless `1/0` is assigned to something, so the `a=` is required.
No other part of any line can be removed without creating an error, usually a syntax error or a linking error.
As a bonus, this gives an 86 byte solution for C++ pretty trivially, just add `#include <cstdio>` and declare `a` as an `int`. [Try it online! (C++)](https://tio.run/##Sy4o0E1PTv7/XzkzLzmnNCVVwSa5uCQlM9@OKzcxM09Dszozr0QhkcuWy1CfS6OgtKRYQ6k8vygnRUlTn8tM05pLOTNNwzwuPt7H0881Pl6TSzk1pziVqxZI56Vkpv3/DwA)
[Answer]
## PowerShell, (97 bytes + 5 for program name) = 102 Bytes
```
"$(try{if(($a=(gc .\c.ps1).Length)-eq97){"world";a}}catch{if($a-ne97){a}$error.clear();exit}a)";a
```
Checks itself before it wrecks itself ... twice.
Expects to be saved as `c.ps1` and executed from the local directory as such:
`PS C:\Tools\Scripts\Golfing\> .\c.ps1`.
The alias `gc` is short for `Get-Content` and is similar-ish to a `cat` reading a file (in this case, our execution path `.\c.ps1`). We get the `.Length` of the file, set it to `$a`, and check whether it's not equal to 97 with `-eq97`. If it is equal (i.e., the program has not been modified), we print with `"world"`, and execute invalid command `a`. This forces the `catch` to take effect, which allows us to check ourselves again. This time, if our code is not equal to 97, we throw an invalid command so our program has errored and printed error text to the output. We then `clear()` the error and `exit` normally.
It's obvious that if either `if` statement is tampered with, the other will have an error. If any portion of `"world";` is tampered with, the first `if` will cause an error. Since it has to be contiguous, we can't remove both `if` statements. Strings in the middle will result in mismatched parentheses, or will result in the second `{a}` getting executed. The `try`/`catch` is to catch the error from the first `if` statement so we can properly clear it. The outer `"$( )"` prevent strings from either end getting snipped. The final `;a` is to prevent portions of the middle getting snipped that would result in valid programs (e.g., `"it}a)";a`, which will print `it}a)` and then error).
There are several special circumstances:
* If the `gc`, `gc<space>` or `gc .\` are removed, the program will eventually error out with some flavor of an out of memory error (due to repeated self-execution calls) and likely crash the shell (and maybe the computer). Not tested.
* If the `<space>.\c.ps1` or `.\c.ps1` are removed, the program will stop and prompt for user input. No matter what the user enters, the program will still error since the size counts will be wrong.
* If a substring starting at the `$` and ending before the last `"` is snipped, the program will output whatever remains and then error because `a` is not valid.
Verified with the following:
```
$x='"$(try{if(($a=(gc .\c.ps1).Length)-eq97){"world";a}}catch{if($a-ne97){a}$error.clear();exit}a)";a'
$yy='"$(try{if(($a=( .\c.ps1).Length)-eq97){"world";a}}catch{if($a-ne97){a}$error.clear();exit}a)";a'
$yyy='"$(try{if(($a=(.\c.ps1).Length)-eq97){"world";a}}catch{if($a-ne97){a}$error.clear();exit}a)";a'
$yyyy='"$(try{if(($a=(c.ps1).Length)-eq97){"world";a}}catch{if($a-ne97){a}$error.clear();exit}a)";a'
for($i=1;$i-lt$x.Length;$i++){
for($j=0;$j-lt($x.Length-$i);$j++){
$y=($x[0..$j]+$x[($i+$j+1)..$x.Length])-join''
$y>.\c.ps1
$error.clear()
if(!($y-in($yy,$yyy,$yyyy))){try{.\c.ps1}catch{};if(!($error)){exit}}
$q++;
write-host -n "."
if(!($q%150)){""}
}
}
"No success."
```
(Thanks to Martin for his extensive assistance!)
[Answer]
# PHP, 73 bytes
```
<?=call_user_func(($p='ns')|(($f="u{$p}erialize"))?$f:'','s:5:"world"');
```
### Explination
I assume the default php.ini configuration. So short\_tags is disabled. This means you can't remove the `=` from the opening tag.
This is basically `<?=unserialize('s:5:"world"');`.
If you remove any part of the serialized string you'll get an error.
You can simply remove `unserialize` and the script will just output the serialized string. To overcome this I use `call_user_func`. Removing one of the params will result in an error.
```
'<?=call_user_func('unserialize','s:5:"world"');
```
However you can remove `un`, to call the `serialize` function. So we take out 'ns`. Removing any characters would no result in an incorrect function name.
```
<?=call_user_func(($p='ns')&&($f="u{$p}erialize")?$f:'','s:5:"world"');
```
We'll use an inline if to using variable assignment with the output tag.
Instead of using `&&` we use '|' to prevent removing a single `&` or removing the `$f` assignment
You could remove `='ns')&&($f="u{$p}erialize"` and end up with `($p)?$f:''`. Therefor I add extra parenthesis around `$f="u{$p}erialize"`.
### Note
*Technically you can remove the opening tags without producing an error. This is than however no longer a PHP script but just a plain text file.*
[Answer]
# [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), 17 bytes
This program contains bytes with the high bit set (that aren't valid UTF-8 and thus can't be posted on TIO), so here's an `xxd` reversible hexdump:
```
00000000: 7072 696e 7427 776f 726c 6427 23cd 4290 print'world'#.B.
00000010: bf .
```
## Explanation
This is just `print'world'` with a checksum appended. I've verified by brute force that none of the possible deletions give a program with a valid checksum, so you get an error after any possible deletion.
Fairly boring, but ties the current leader, so I felt it was worth posting.
[Answer]
## Matlab(77)
```
bsxfun(@(c,b)arrayfun(@(x)getfield(c,{x}),conv(b,ismember(4,b))),'world',1:5)
```
## [try it](http://rextester.com/KJVXPB33733)
**Note:**
Following @Optimiser's advice of designing a CPR or something, I was faced to unforeseen substring which didnt lead to any compilation error when removed, example: removing `arrayfun(@(x)a(x),prod(b,ismember(4,1:5))),` from this previous edit `feval(@(a)arrayfun(@(x)a(x),prod(b,ismember(4,1:5))),'world')` doesnt generate any bug! also, for recent same edition, there were `bsxfun(@(a,b)arrayfun(@(x)(x),prod(b,ismember(4,b))),'world',1:5)` and `bsxfun(@(a,b)a,'world',1:5)`,if you asked about how was I when finding them out in my output console, I cried like a baby, so here is the program:
```
b=0;string='bsxfun(@(c,b)arrayfun(@(x)getfield(c,{x}),conv(b,ismember(4,b))),''world'',1:5)'
for u=1:numel(string),for j=u:numel(string)-2,try a=eval([string(1:u) string(j+2:end)]);catch(b); a=0;end; if a~=0, ['here is it : ' string(1:u) string(j+2:end)],end;end;end
```
[An example of a nonpristine program](http://ideone.com/1QrmNk)
**edit:**
>
> Thanks to everyone beside @Martin for pointing my previous code's (not-errors) out .
>
>
>
[Answer]
# SmileBASIC, 63 bytes
```
REPEAT
A=1/(PRGSIZE(0,1)==63)?"world
UNTIL 1/(PRGSIZE(0,1)==63)
```
] |
[Question]
[
Super simple challenge today, or is it?
I feel like we've heard a fair bit about double speak recently, well let's define it in a codable way...
Double speak is when each and every character in a string of text is immediately repeated. For example:
```
"DDoouubbllee ssppeeaakk!!"
```
---
# The Rules
* Write code which accepts one argument, a string.
* It will modify this string, duplicating every character.
* Then it will return the double speak version of the string.
* It's code golf, try to achieve this in the smallest number of bytes.
* Please include a link to an online interpreter for your code.
* Input strings will only contain characters in the printable ASCII range. Reference: <http://www.asciitable.com/mobile/>
---
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
var QUESTION_ID=188988;
var OVERRIDE_USER=53748;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, [Other information] N bytes
```
where `N` is the size of your submission. Other information may include flags set and if you've improved your score (usually a struck out number like `<s>M</s>`). `N` should be the right-most number in this heading, and everything before the first `,` is the name of the language you've used. The language name and the word `bytes` may be links.
For example:
```
# [><>](http://esolangs.org/wiki/Fish), <s>162</s> 121 [bytes](https://esolangs.org/wiki/Fish#Instructions)
```
[Answer]
# [Malbolge](https://www.lscheffer.com/malbolge.shtml), 20775 and 2334 bytes
Probably I didn't beat anyone with it, but it was incredibly fun to make.
```
bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTRnQOkNLhgfIdcFaZ_^A\[Z<XW:U8SRQPOHML/JIHG*ED=%%:?>=~;:{876w43210/(-,+*)('h%$d"ca}|_z\rqYYnsVTpoRPledLLafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(DCB%@?"=<;|98765.3210p.-n+$)i'h%${"!~}|{zyxwvuXVlkpSQmlOjLbafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(D'%A@?"=<}:98y6543,1r/.o,+*)j'&%eez!~a|^tsx[YutWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U86R53O20LKJ-HG*ED'BA@?>7~;:{y7x5.3210q.-n+*)jh&%$#"c~}`{z]rwvutWrkpohmPkjihafI^cba`_^A\[>YXW:UTS5QP3NM0KJ-HGF?D'BA:?>=~;:z8765v32s0/.-nl$#(ig%fd"ca}|_]yrqvYWsVTpSQmPNjMKgJHdGEa`_B]\?ZY<WVUTMR5PO20LK.IHA))>CB%#?87}}49zx6wu3tr0qo-nl*ki'hf$ec!~}`{^yxwvotsrUponQlkMihKIe^]EEZ_B@\?=Y<:V97S64P31M0.J-+GFE(C&A@?8=<;:{876w43s10qo-&%kk"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNiLgf_dcba`C^]\?ZY;WV97SLK33HM0.J-+G*(D'%A$">!};|z8yw543t1r/(-,+*)(i&%fd"!~}|_t]xwvutslqTonmPNdchKIeHFbaD_AWV[><X;9U86R53ON1L.DCH+)EDC&;@#>=<;|98x6wu32s0p(',mk)(i&f|{"ca}`^z][wZXtWUqTRnmPNjcbJJ_dcbEDYB@@?ZSX;VUTS6QPO11F..CHGF)(C<A$?>=<}:98xx/uu,10/po,+$kiih%$#z!b}|{z]xwvXXmUUjonmPOjihafIdcbaD_^]??T<<QVUT76QPONG0..-HGFED=B%@?>=~|438yw5vt21r/o'&+lj(ig%fd"ca}`^z][wZXtWUqpoRQlkjihafIdcbaDBXW\?=YX;9UNMR53O20//DIH+)E>=B%#?"~<}{9zx6wu3tr0/pn,%$jj!&%$ed!~}|{zs\ZZYtsrqponglOjiLgfHdGEaDB^]@[=SRW:8T75Q42N1/K.,HG*E'=<A$"!!6;:{8x0/4us1rp.-,ml)('&%$#z!b}|{zy[qvutsUkTinmlejchKIIH]bE`_^A\[=Y<:VU86RKJO20LK.,HA@E(&BA$">76;|z8yw5vt2sq/pn,mkjj!&%$edy~a|{z][qpuXVUUjonQOkdchKIHH]baD_AWV[><;;PUT7R4JIN1/K.,H+)E(&B%#?"~<}{zz1654ut1*qoon+*#(i&%$e"!~``uzy\ZvonsVTSShmlOjLbafIGFF[`_B@\UTY<:99NSR53OHGL/-I,*F)'C&$@#!=~|:{y765vu21*/pnnm*)(!h%$#d!~}__tyx[vXnmrUSoRPlkNiKa`eHFbECBBW\[>Y;QPU86R53O20L/-I,*F)'&&;@?>!~;:92ywwv3210).o,+*k('g%fd"ca}`^z][wZXtsVqSihmPNjiLgI_^cFD`_B]?UTY<:VUT76QPONGL/--,GFEDC<%@?>!<;:98yw5.-2sq/.o,l$#(ig%fd"!b`|uty\ZYYnsrUpRhglOMiLJfIGcFD`CA]@>==RWVU87RQPONG0..-HGFEDC<A$?>!<;:zz1ww.321rq.-,+*)"'hffe"!~}|{zyrwZutsVqpoQQfkjMhJ`_dGEaDBAAV[Z=;WPOT75Q4211FKJ-+G@?D'%A$">!};|z8yw5vt210qp-,+*)('&}$e"!~}|^tyxwvXnWlqpohmfkNLLK`IdcbE`_^]\?=YRQV97S64P31ML/J,BAF)'CB%@"87<}{9zx6wu3tr0qo-nlkk"'&%fezcaa`{ty\wvuXsrTpSQmPNjiLJf_^cFD`_B@\UTY<:V97S64P31M0.J-+GFE('B;@#!!~;:3z765v321qq(-,m*j"!&ge#db~}`{]srwZXtWUTTinmPkMcbgJHdGEaDB^A?[><X;988MRQP32MLE.,,+FED=B%@?>!}549zxww.32sq/(',mk)(i&f|{"ca}`^z][wZXtWUqTRnQOkNLhgfIHcbaZ_B@@?ZYXWP9TSR5PON00EJI,*F?>C&$##8=<}:z216wu32s0p(',mk)jh&ge#db~a_{^\x[YuXVUUjonmPOjihg`IdcFa`BAAV[Z=;WPOT75Q42N1/K.,HGF)(CBA@?8=~;:9z76v43tr0)(-nl*)j'g}|#db~a_^^sxwZXtmlqTRnQOkNLhKIeHFbEC_^]@?ZYXWVUN7554ONMLKJIBG*EDC&$:9!!6;:9zy6543210/(o,+*)(h~%$#"bxav{tyxwpuXVVUjoRmlkNihJfIGcFD`CA]@>ZY<:VONS64PO2M/EDI,*F)'C&$@#!=~|:98yx/4u21r/.-mm$)(i&f|{"ca}`^z][wZXtWUqTRnQOkjMhJ`_dGEaDB^A?>>SXWV98SL5332MLEJ-HGF)DC%A@#>~65:{y76w4t,+0qo-,m*j"!&ge#"c~`vuz][wZXtWUqTRnQOkNLhgfIHcb[`C^]\[>YXW99N66KPON10KJIB+))(CBA@9>!<;:9z765uu,10q.n&%*ki'&g$dzy~a_{^\x[YuXVrUSoRPlOMiLJfIGFF[`_^A@[ZYXQV9TSRQ4ON0L/-,,AFE(C%;:?"~<;|z8105vtss*/.o,l$#(ig%fd"ca}`^z][wZXtWUTTinmlONihgfe^GEED_^]\[ZSX;VUT7RQP22GLK.I+A@E(&%%:?>!};438yw5vtss*/.om+$#(ig%$ec!xw|_]y\ZvYWsVTpSQmPNMMbgfeHGba`_^]V[>YX;VUTSR53OHGL/-,,AFE(C%;:?"~<;|9y105vt2sq/pn,mk)jh&ge#db~a_{zy\[vutsrqpiRmlkjiKafedcE[DY^]\UZSX;VUT7RQ322GLK.I+A@E(&BA$">76;|z8yw5vt2sq/pn,mk)jh&geddy~}|_^s\ZZYtmrUponQlkMihKIe^]bEC_^A\>TSX;988MRQ4O1GFK.,HG*E'=<A$">!};|z8yw5vt2sqpp',+*kj'~%f#"!b}|^z][wvYWslkpSQPPejiLJf_^cFD`_B]?UTY<:VU8S5KJO20L/-I,*F)'CB%#?87<;:{z76/vtts0/.',m*)(i&%$ddy~}`{]srwZXtWUqpSnPfejMKgJHGG\a`C^@VUZ=;W:8T75Q42N1/K.,++@EDC&%@?>7<}{{z7654-t10/p-,l*ki'&g$dzy~a_{^\x[YuXVrUSoRPlOMiLJII^cbaDC^]\[T=;;:UTSRQJO2MLK.IHGFE(&B;:?"~<}{98y6v.-2sq/pn,mk)jh&ge#db~a_{^\xwvYXsrqpohmPNNMhgfedc\E`_^A\[=YX;9UNMR53O20L/-I,*F)'C&$@#!=~|:{yxx/432sr/.-,+*#jhhg$#"!~}|uz]xwvYtsUqpSnPfejMKgJHdcFaCYX]@>Z=;WV9T6LKP31M0.J-+GF)D&<;@?>!~;:98765.3trrq.-,+*)('~g$#"c~}|{z][wpotWUqTRnQOkNLhgJeG]\aDB^]@[=SRW:8T75Q42N1/..CHGF)(CBA@?>=<5|98765u-210/o'n%*)(!&}$eccbw|_zyx[vuWsVTSShmlOMibafIGFF[`_B]?UTY<:V97S6433HML/-IBAF)'C&$@#!=~|:{y765vu,1r/.-nl$#(igff{"!b}_uty\ZYYnsrUSohglOMiLJfIGcFD`CA]@>Z=;W:877LQPO21LE.,,+FE>C&A@?"=<|{{276wu3,+0qonn%*)j'g}|#db~a_{^\x[YuXVrUSoRPlOMihgJIdc\aD_^]@[Z<XW:U7MLQ42N1/K.,H+)E(&B%#?"~<}{9zxww.321rq.-,%ljji&%$#z!b}|{^yxwYYnsrUSohglOMiLJfeHcE[Z_B@\?=Y<:V97S64P31M0.J-+**?DCB%$?>=<5:{876w432rr).-n+k#"'hf$#d!awv{^\xwZXtmlqTRnQOkNLhKIeHFbEC_B@\?=YXW:9TSRQPI200/JIHGFE>C&A@#!76||3876wv3210/.',m*)j'&%eez!~a_{tsx[YXXmrqTRngfkNLhgJeG]\aDB^A?[><;;PUTS65PONMLKJC,**)DCBA@?>=6;|987x54t21r/o'&+lj(ig%fd"ca``uzy\wYonsVTpSQmPNjMKgfIGc\[`_^A@[ZYXWVUTMR5PONML.DIHGF(>'<A@9>=6;|98y654tt+0/p-m%$)('hg|eccb}v{^yxwZutVrqToQgfkNLhgJeG]\aDBAAV[Z=X:POT7544INM0.JCBG*(D'%A$">!};|z8yw543ts0).o,+*)j'&%eezbbw|{z]\wvoXVVUponglOjihgJedcEEZ_^A?[TSX;9UT7R4JIN1/K.,H+)E(&B%#?"~<}{9zx6wutt+0/.on+*)"'h%$#"c~}|^^sxwZuWmlqTRnQOkjMhJ`_dGEaDB^A?[><X;9U86R53ON1L.DCHGF)(CBA@9"~~}:9876/4u210/p-,l*kihh}$#db~wv{^\[[putWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U8655JONM0/JIHGF?D'BA@?"=<;{{2xx/432sr/.-,+*)(!h%$#"!aw|{zy[qZotsrkpinQOONchKfedcFa`B^A?[Z=X:POT7544INM0K-CBG*(D'%A$">!};|z8yw5vtss*/.-nm$)j'&%$e"!a}`^]]rwvYWslkpSQmPNjMKgJHdGEaDB^A?[ZY<;VO8665POHM0KJ-HGFED'%A:9>!}||387x5u-,1rp.-n+k#"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNMhg`eHFFE`_^]V[>YXW:UTS55JON1L.DCH+)E(&BA$?!76;|z8yw54u2r*).om+lj('h%e{z!b`|{z]\wvutmrUponQOediLJII^cbEC_XW\?=Y<:V97S64P31M0.J-+G*(D'%$$9>=<}|98765.ussr/.-,+*#(i&%$e"!~``u]]rwvuXWrqponmfkNihKfeGcFD`CA]@>==RWV9T6LKP31M0.J-+G*(D'%A$">=<}|9876543,s0/p-,lkk"'&ge#zy~a_{^\x[YutWUqjinQONNchgfIHcba`_^]\UZ=XWVUT6LQPON0F/DIHG@E>C&A@#>=<||387x5u-,1rp.om+lj(ig%fd"ca}`^zy\wYonsVTpSQmPNMMbgfeHG\ECCB]V[>YXW:UT6R53O20//DIH+)E>=B%#?>!<|438yw5vt21rp.'&+lj(ig%fd"ca}`^zyx[ZunsVqpoRmlNjiLJf_^cFD`CA]@>Z=;WV9T6LKP31ML/J,BAF)'CB%@"87<}{zz1654ut10)pnnm*)(!&g$#"cawv{^\xwZuWmlqTRnQONNchgJeG]\aDB^]@[=SRW:8T75Q42N1/K.,H+)((=BA@#"=<;49z765v321qq(-,mk)"!&ge#"c~`vuz][wZXWWlqpSQmfejMKgfIGc\[`CA]@>Z=;W:8T75Q42NML/.IHGF?(&&%@?>=<5:{876w432rr).-n+k#"'hf$ec!~a|^tsx[YuXVUUjonQlNdchKIeHFbEC_B@\?=Y<:99NSRQ43NMLKJCH+))(CBA@?>7~;:9z76v43t1q)(-nl*ki'hf$ec!b`|_]y\ZvYWsVTSShmlkNMhgfedc\ECCB]\[ZYXWPU8SRQ4ONMLK.,HA@E(&BA$?!76;|z8yw5vt2sq/pn,mk)jh&ge#db~}|_^yxwvutslqTRRQlkjihgfe^Gba`C^]?[Z=;WPOT75Q42N1/K.,H+)E(&B%#?"~<}{zz1654ut10/.-,+*#j'&%$#cy~}|{]s\qvunsrkpSQQPejMhgfIdcEa`C^@VUZ=;WV9T6LKP31ML/J,BAF)'C&$@#!=~|:{y7xv4usrr).-,ml#(iggf#zc~}|_zy[wZXtsVTpihmPNjMKgfIdF\[`CA]\?Z<RQV97S64P31M0.--BGFE('B;$""!<;49z765v32r0qonn%*)jh&}|#dbaav{z]xZpotWUqTRnQONNchgJHd]\aDB^A?[><X;9U86RQP32MLEJ-++*EDC<%@?>!<;{9zx6wu3tr0qonn%*)j'g}|#db~}`{]srwZXtsVqSihmPNMMbgfIGc\[CCX]\[>=XWVO8665PONMFK.IHG*ED&B%#?>!<|438yw54u2r*).omll#('hf${z!b`|{^y[qpuXVrUSoRPlOMLLafedGFa`_^W\?ZYX;VU7SR5P2HGL/-I,*F)'C&$@#!=~|:{y7xv4usrr).-,ml)('&%|eccb}|{zyxqvYtsrUSihmPNjMKgfIdF\[`CA]@>Z=;WV9T6LKP31M0.J-+G*(''<A@?"!<;:98705v321rp(',mk)jh&%fd"yx}`^z][wZXtsVTpihmPNjMKgJHdGEaDBAAV[ZY<;VUTSRQPI200/JIHGFEDC<A$?>=~|438yw54u2r*).om+lj(igff{"!b`|uty\ZvYWsVTpSQmPNjMKgfeHGba`_^]\[TY<WVUTS5KPONM/E.CHGF?D=B%@?>!<;{9zx6wu32s0p(',mk)(i&f|{"ca``uzy\wYonsVTpSQPPejiLJf_^cFD`CA]@>Z=;W:8TSR54I200/JCH+FED'BA#?"~<}{98y6v.-2sq/pn,mk)(ig%|{"ca}`^z][wZXtsVqSihmPNMMbgfeHGb[`C^]\?ZY;WV97SLKP31M0.J-+G*(D'%A$">!};|z8ywvv-210qp-,%ljji&%${"c~}|_zy[wvYtVlkpSQmlOjLbafIGcbE`BXW\?=Y<:99NSR5P2HGL/-I,*F)'C&$##8=<;|{876/4u210q.-,ll#('hf${z!b`|{^\xqpuXVrUSonQlNdchKIedGEaZY^A?[><X;9U86R53O20//DIHG*)DCBA:#!!~;:98705v321r/.-mm$)(i&f|{"ca}`^zy\wYonsVTpoRmOediLJII^cbE`BXW\?=YX;V8NMR53O20L/-I,*F)'&&;@?>!~;:98705v321r/.n,mk)jh&ge#"ca}vuz][wZXtsVTpihmPNjMKgJHdGEa`C^@VUZ=;::OTSR54ONMLKJC,**)DCBA@?>7<}:98y65u3tr0qonn%*)j'g}|#db~a_{z]xZpotWUqTRnQOkNLhgJHd]\a`_BA\[ZYXWVOT7RQP3NM/KJ-H*@?D'%A$">!};|z8yw5vt2sq/pn,mkjj!&%$ed!~}|{zyxqZutsrqSinmlkMcLafed]b[`CAA@UZ=XWV9TS544INM0.JCBG*(DC&$@98=~|:{yxx/43tr0)(-nl*ki'hf$ec!b`|{^y[qputsVUjoRmlkNihJII^cbE`BXW\?=<<QVU8S5KJO20LK.I+A@E(&BA$?!76;|z87x5u-,1rp.om+ljii~%$#dc~w`^^]xwpuXsrqTonmOOdihKIe^]bEC_B@\[><XQPU86R5322GLK.,HA@E(&B%#?"~<}{9zx6wutt+0/.on+*#(i&%$e"!a}`^z][wZXtWUqTRnQOkNLhKIedcFE`_^W@>>=XWVUNS6QPO2ML.JI,G)?>&&;@?>!~;:9816w43tr*).omll#('h%e{z!b`|{^y[qpuXVrUSoRPlOMiLJfIGcFD`CA]\[>=XWVUTM6QP3NML..CHG*(D=<A$"!!6;:{y70/4us1rp.om+lj('&gf#"!~}|uz]xwZutVrqToQgfkNLhKIeHFbEC_B@\?=YX;V8NMR53O20L/-IHG*)DCBA@?>7~||{87654321*/p-,+l)('gg|#"ca}vuz][wZXWWlqpSnPfejMKgJHGG\a`C^@VUZ=;WV9T6LKP31MLK.-HGFEDCBA:?"=<;:9y16543s+r).',+*#(i&%$e"!~}|_]yrqvYWsVTSShmlOMibafIGFF[`_B@\UTY<:V97S64P31M0.J-+G*(''<A@?"!6}:9z76vuu,10qo-&%*ki'hf$ec!b`__tyx[vXnmrqpSRmfkNihgJedFbaD_AWV[><XW:U7MLQ4211FKJ-H*@?D'%A$">!};|z8yw5vt2sq/.-nm*)"iggf#"!x}`{z][qpuXVUUjonQlNdchKIedGbDZY^A?[><X;9U86R53O20L/-I,*FED'&A@?8=~;:{876vv-21rp.'&+ljii~%$ec!xw|_]yx[vXnmrUSoRPlOMLLafedGFa`_^W@>>=XWVUTMR5PO2ML.JI,G)?>C&$@#!=~|:{y7xv4us1rp.om+ljii~%$#dc~}|{zsx[YYXsrqpongPkjiLgfeGG\a`C^@VUZ=;W:8T75Q4211FKJ-H*@?D'%A$"!!6;:9zy654321*qoon+*)('&%|#d!~}`{zyxwZXtmlqTRnQONNchgJHd]\aDBAAV[Z=;WPOT75QP31MFEJ-+G*(D'%A$">!};|z876wv3210/.-&+l)(i&%eddy~}`^zsrwZXtWUqTRnQONNchgJeG]\a`_BA\[ZYXWVUN7RQPON0FKJIH*@)>CBA:?8=~||{27x543t10/oo&+*k(h~}$ec!~a|^tsx[YuXVUUjonQlNdchKIedGbDZY^A?[><X;9U86R53O20LKJ-,AF)DC&$:9>!}||387x5u-,1rp.-n+k#"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNMhaJedGba`BBW\[><XQPU8655JON1/KDCH+)E(&B%#?"~<;:{z76/4u21r/.n,+l)i!~%fd"ca}`^z][wZXtWUqpSnPfejMKgJHdGEa`_BA\[ZS<::9TSRQJO2MLK.IH*F)'C&$@#!=~|:{y7xv43t1q)(-nl*ki'hf$#d!awv{^\x[YutsVUponmfkNihgJedFbaD_AWV[><;;PUT75QJIN1/..CHG*(D=<A$">=~|:327xv4us1rp.om+lj(ig%$#dc~}|{zs\wvYtsUTTinmPNjcbgJHdGEaDB^A?>>SXW:U7MLQPO21LKJIHG@E(CBA$"87}}4987xw43210/.'nllk('&%$#"!x}`{z][qpuXVUUjonQlNdchKIedGbDZY^A?[><X;9U86R53O20L/-I,*FED'&A@?>=<;:38y65432r*/.-,l$k"'&%|#z!b}|_zyxZZotsVTpihmPNMMbgfIGc\[`CA]\?Z<RQV97S64P3100EJIH+*?(&&%@9>!<;|98x65v3s+*/pn,mk)jh&ge#db~a_{^\x[YuXVUUjonmPOjchKIIHcb[D_^]@[Z<XW:8TMLQ42N1/KJ-H*@?D'%A@#>~65:{y7xv4us1rp.om+ljii~%$#dc~}v_]]\wvunsVqpSnmONNchgJHd]\aDB^]@[=SRW:8T75Q42N1/KJ-H*@?D'%A$">=~|:327xvuu,10/po,+*#(iggf#"!~}v{^yx[YonVVkponQPkjihg`eHFFE`_^]\[T=XWV9TS5Q42N1/K.,H+)ED'%A:9>!};|z87x5u-,1rp.om+lj(ig%$e"bxw|_]\\qvutWVqponmleNihKfeGcFDCCX]\?Z<RQV97S64PO20LEDI,*F)'C&$@#!=~|:{yxx/432sr/.-,+*)"'h%$#d!~`|{^y[qpuXVrqToQgfkNLhgJeG]\aDB^A?[><X;9U86R53O20//DIHG*)DCBA@?>=6}:9876v.3210p(o&+*#('~%fddcx}`{z]xwYutWrTjinQOkjMhJ`_dGEa`C^@VUZ=;W:8T75Q42N1/K.,H+)((=BA@#"7<}:9z765uu,10qo-&%*kihh}$#db~wv{^\xwZuWmlqTRnQOkNLKK`edcFE`YB@@?ZYRW:UTS6QP2NM0K-CBG*(DC&A#98=~|{{276wu3,+0qo-nl*ki'hf$ec!b`|_]yxwZYtslqTonQlkjLLafeHcE[Z_^]@?ZYXQ:887RQPOHM0KJI,GF(D'%A$">!};|z8yw54u2r*).om+lj(ig%fdccx}|_z\rqvYWVVkponQPkjihafIdcFDZY^A?>>SXW:U7MLQ42NM0K-CBG*(D'%A$">!};|z8yw5vt2sq/.-nm*)('&}f#"c~}|^^sxwZXtmlqTRQQfkjMKg`_dGEaDB^A?[><XWV98SRQPONGL/--,GFEDCBA:#>=<}:9y7xv4us1rp.om+*k(h~}$ec!b`|_]y\ZvuXVrkjonmPOjihgfed]Fa`C^]\>>SXW:U7MLQPO21LKJIHGFE>C&A@?>=}5:987w/v-210).',m*)(ig}|#db~a_{z][wpotWUqTRQQfkjMKg`_dGEaDB^A?[><X;9U86RQP32G0..-HAF)DC&A@"!!6;:{8x0/4us1rp.-n+k#"'hf$ec!b`|_]y\ZvuXsUkjoRPlOMLLafedGFaZ_B]\?ZYX::OTS64PIHM0.--BGF)'C<;@#!=<}:z216wu3tr0qonn%*)(ih%${dbba|{zsx[vutWrqSonQOkdchKIHH]baD_AWV[><X;988MRQ4O1GFK.,H+)E(&B%#?"~<}{zz1654ut10/(-n+*k('&ff{"!b}_utyxwZYtsrqjSQQPkjihg`eHcbaD_^@??TYX;V8NMR53ON1L.DCH+)E(&BA$?!76;|z87x5u-,1rp.om+lj(ig%$e"bxw|{z]\wvutslqTonmlOjihJJ_GG\a`_BA\[ZYXWVUN7RQPON0FKJIH*@)>CBA:?8=~||{27x5432s0/onn%*)jh&}|#db~}`{]srwZXtWUqTRnQOkNLhKIeHFbEC_B@??TYXW:9NS6QPON1LK-IH+F(>=B%#?"~<;|z8105vt2sq/pn,mk)jh&ge#db~}|_^yr[vutsVqpoQQfNNchgfIHcbaZCAA@[ZYXQV9TSRQ42HGL/-I,*))>CB%@"87<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\[[putsVUponmfkNihgfIdcEaDBAAV[Z=;WPOT75Q42N1/K.,H+)E(&B%#?>=~}:9876/vtts0/.-,+$)j'&ge{z!b`__tyx[vXnmrUSonQlNdchKIeHFbEC_B@\?=Y<:V97S64PON10KJIHGF?D'BA$?>=}}498yw5.-2sqpp',+lj(!~%fd"!b}_uty\ZvYWsVTSShmlkNMhgfedcb[D_^A\[Z<<Q99NSRQ43NMLKJIHG@E(CBA@?!7<;:9y1x/43,10).o,+l)('gg|ddy~}|_^s\ZZYtmrUponQlkjihKIe^]bEC_^A?[TSX;9U86RQ42NGFK.,H+)E(&B%#?"~<}{9zxww.321rq.',mkkj'&}fddc~}|uz]xwvYWmlTTinmlONihg`eHFFE`_^]V?ZYX;VU7S64PO2M/EDI,*F)'&&;@?"=}549zx6wu3tr0qo-nl*kihh}$#"cb}|{zs\wvYtsrTTinmPkMcbgfeHGba`_^W\?ZYX;VU766KPO2M/EDI,*))>CB%#?87<}{9zxww.32sq/(',mk)jh&ge#db~a_{^\xwvYXsrqpongPNNMhgfedcb[`C^]@>TSX;988MRQ4O1GFK.,HG*E'=<A$">!};|z8yw5vt2sq/pn,mk)('hg$#"!~}|uz]xwZutsUUjonQOkdchKIHH]baDB^WV[><XW:U7MLQ42N1/K.,++@EDC&%@?>=<;:92y65432r*/.-,l$k"'&%|#z!b``_ty\wvuXsrqSShmlOMibafIGcbEC_XW\?=YX;V8NMR53O20L/-I,*F)'C&$@#!=~|:98yx/4ussr/(o,+l)('g%$ed!xa__^yxqvYtsrUSihPPejihKJed]bE`_^A\[=Y<:V97SR5P2HGL/-IH+F(>=B%#?>!};438yw5vt2sq/pn,mkjj!&%$ed!~}v_zy\wvuWWlqpSnPfejihKJedcb[`C^]\?=SRW:8T7544INM0.JCBG*(DC&$@98=~|:{y76w4t,+0qo-nl*ki'hfeez!~}`_zyxwvoXVVUponmlkdiLgfeHcbD`_B@\UTY<:VU8S5KJO20L/-I,*F)'C&$@#!=~|:{y765vu210/.-&+l)(i&%$#"ca}vu]]rwvuXWrqponmleNLLKfedcba`_X]@[ZY<WV877LQP3N0FEJ-+G*(D'%A@#>~65:{y7xv43tr0)(-nl*ki'hf$ec!b`|{z]\wvutsrqpinQlkjihJ`edcbDZCX]\[TYRW:UT7RQP22GLK.I+A@EDC&%:#!!~;49z765v32r0/pn,%$)jh&ge#"ca}vuz][wZXtsVqSihmPNjMKgJHdGEDDY^]\?>YRW:UT75KJO20//DIH+F(>=B%#?>!<|438yw5vt2sq/pn,mk)jh&ge#db~}|_^yxqZutWrqpRRglkNLha`eHFEEZ_^A?[TSX;9U86R53O20LKJ-,GFE>C&A@?"=<;{{276wu3,+0qo-,mk)"!&ge#"c~`vuz][wZXtWUqTRnQOkNLhKIeHFba`CB]\[ZS<::9TSRQPIN1LKJ-+A@((=BA@#"=<;:981xvvu210/.-,%*k('&g$#cbbw|{^y[qpuXVrUSoRPlOMiLJfeHcE[Z_B@\[>Y;QPU86RQ4O1GFK.,HGF)(CBA@?>=6;|98y654tt+0/p-m%$)jh&ge#db~a_{^\x[YuXVrqToQgfkNLhKIeHFEEZ_^]@?ZYXWVUTSL5PONML.DIHGF(>'<;@?>=6;|zzy05v321rp(',mk)jh&%fd"yx}`^]]rwvYWslkpSQmPNMMbgfIdF\[`CA]@>Z=;W:8T75QPO21FK.IH+)?>C&$##8=<}:z216wu32s0p(',mk)jh&ge#db~a_{^\x[YuXVrqpSRmfOjiLgfeGG\a`CA]VUZ=;::OTS64PIHM0.J-+G*(D'%A@?"!<;49z765v321qq(-,mk)"!&ge#"ca}vuz][wvYtVlkpSQPPejiLgI_^cFD`CA]@>Z=;W:8T75Q42NML/.IHG@)''&A@?>7<}:98y65u32s0p(',mk)jh&ge#"c~`vuz][wvYWslkpSQmPNjMKgJHdGEDDY^]\?>YXWVOT7RQ4ONM//DIH+F(>=B%#?"~<}{9zx6wu3tr0qo-,m*j"!&ge#db~a_^^sxwvYXsrqpohQOONihgfed]bE`_^A\[=Y<:V97S64P31ML/J,BAF)'C&$@?"=}549zx6wu3tr0/p-m%$)jh&geddy~}|_^yxwvutmrUSSRmlkjihg`IdcbE`_A]@>ZY<:VONS64P31M0.JI,G)?>C&$@#!=~|:{y765vu210/.-,%ljji&%$#"!~}v{^yxwZXnmrUSRRglkNLha`eHFbEC_^A\>TSX;988MRQ42NGFK.,H+)E(&B%#?"~<;:{z76543210).o,+*)(h~%$#"bxav{zyrwpuXsrUponPPeMMbgfeHG\ECCB]V[>YXW:8NMR53O20//DIH+F(>=B%#?"~<}{98y6v.-2sq/.o,l$#(ig%$#dc~w|_zyx[vutsrUSohglOMLLafeHFb[Z_B@\?=YX;9UNMR5322GLK.,HA@E(&B%#?"~<}{9zx6wu321rq.-&m*)jh&%$#"cb}|{ty\wvuXVlkSShmlkNMhgfe^GEED_^]\[TY<WV9TSRQP31MFEJ-+**?DC&A#98=~|:9z7w/.3tr0qo-nl*ki'hf$ec!b`|_]yxwZYtsrqpinQOONihgfed]Fa`CAW\[ZY<;VUTSRQJ3110KJIHGFE>C&A@#!76||3876wv3210/.-&+l)('h%$#ccx}|_]yrqvYWsVTpoRmOediLJII^cbE`BXW\?=Y<:99NSR53OHGL/-I,*F)'C&$@#!~~5:98yx543210/.'n+*)('g}$#"!aw`uzyxqvotWrqTonPOOdihKIe^]bEC_B@\?=Y<:V97S64P31M0.J-+GFE('<A$?>=~;:9yy054u2r*).om+ljii~%$ec!xw|_]\\qvuXVrkjoRPOOdihKfH^]bEC_^A\>TSX;9U86R53O20//DIHG*)D=&$$#>=6;|98y65u32s0p(',mk)jh&ge#db~a_{^\x[YuXVrUSRRglkjMLgf_dGbaD_^]??TYX;9UNMR5322GLK.,HA@E(&BA$?!76;|z8yw5vtss*/.-nm*)(!hffe"!~}v{^yxwZutsUUjonQOkdchKIedGEaZY^A?[Z=X:POT75Q42N1/K.,H+)E(&B%#?"~<;:{z7654-2s0/pn,+*)(ih%$#"!xa__^yxwvutmrUponQOedLLafedGFa`_^]\UZ=XWV9TS5Q42NM0.JCBG*(DC&A#98=~|{{276w4t,+0qo-nl*ki'hf$ec!b`|_]yxwZYtsrqpongPkjMhgfHH]baD_AWV[ZY<;VUTSRQPOHM0KJIHG)?DCBA#9"7<;49816w432s0/.nn%*)j'g}|#db~a_{z][wpotWUTTinmPNjcbgJHdGEaDB^A?[><X;988MRQP32G0..-HAF)DC&$:9>!}||387x5u-,1rp.-n+k#"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNMhafIdcFa`_AAV[Z=;WPOT7544INM0.JCBG*(DC&A#98=~|:{y7xvuu,10/po,+$kiih%$#z!b}|{^yxwYYnsrUSohglOMihKIe^]bEC_^A\>TSX;9U86R53O20L/-I,*F)'C&$@?>!~;:927x54us10/.-nm*)('~geed!~}|{ty\wvuXVlkSShmlkNMhgfed]bE`_B]\>ZY<W9ONS64PO2M/EDI,*F)'C&$@#!=~|:{y7xv4us10/po,+*)('~geed!~}|{zyrwZutWUkponmPOjihgfed]bE`_B@VU==RWVU87RQPONMLKD-HGFED&<A@?>~6}498705.3trrq(-n+*)j'&feez!~a|^tsx[YuXVUUjonQlNdchKIedGbDZY^A?[Z=X:POT75Q42N1/K.,HGF)(=B%@?"=<;{{276wu3,+0qonn%*)jh&}|#db~}`{]srwZXtWUqTRnmPkMcbgfeHGb[DBBA\[TY<WVU86LKP31ML/-IBAF)'CB%#?87<}{zz165vt2+*/pn,mk)jh&ge#db~a_^^sxwvYXsrkpSnmPNdchKIHH]baD_AWV[><XW:U7MLQ42N1/K.,H+)E(&B%#?"~<}{987xw432+r/.o,+*jj!&%fd"yx}`^]]rwvYWslkpSQmPNjMKgJHdcbED_^]\UZ=XWV9TSR44INM0.JCBG*(DC&$@98=~|:9z7w/.3tr0qo-nl*ki'hf$ec!b`|_]yxwZYtsrqpiRPPOjihgfe^cFa`_B@VU==RWVU87RQPONMLE.,,+FEDCBA@?8=~;:{87w5vt2sq/pn,mk)jh&%f#cyx}`^z][wZXtWUqTRnQOkNLhKIeHFEEZ_^]@?ZYXWVUTSLQ4ONMLK-CHGFE'=&;@?>7<5:{8765v32r0/p-m%$)jh&ge#"c~`vuz][wvuXWlUSSRmfkNihKI_^FF[`_^A@[TY<WVU8SR4P31M0.J-+GF)D&<;@#!=<}:z216wu3tr0qo-nl*)(ih%${d!~a|{]\\qvuXVrkjoRPlOMiLJfIGcFD`CA]@>Z=;W:8TSR54ONMFK.IHG*ED&BA$?!76;|z8ywvv-21rp.'&+lj(ig%$e"bxw|_]y\ZvYWsVTpSQmlkNMhgfe^GEED_^]\[TY<WV9TS5QP3N0FEJ-+G*(D'%A$">!};|z8yw5vt2sqpp',+*kj'&%$#z!b}|_zyxZZotsVTpihmPNMMbgfIGc\[`CA]\?Z<RQV97S64P3100EJIH+*EDCBA@9"=<}:98xx/43t1q)(-,+lk('&%$#"y~a|{z][qpuXVUUjonQOkdchKIeHFbEC_B@\?=Y<:V97S64P3100EJIH+*EDCBA@?>7~;:987w/4321q)p',+$)(!&g$#"!b}|^z][wvYWslkpSQmPNjMKgJHdGEaDB^A?>>SXWV98SRQJ3110KJIHAF)DCBA$?>=<;|z8105vt2sqpp',+lj(!~%fdccx}|_z\rqvYWsVTpSQmPNjMKgJHdGEDDY^]\?>YXWVOT7RQPO2ML.JI,G)?>C&$@#!=<}{9216wu3tr0qo-nl*ki'hf$ec!~}`_zyxwvoXsrqpSnmlNNcKK`edcFE`_^]\[ZS<::9TSRQPONMFK.IHGF)'=<A$">!}||387x5u-,1rpoo&+*k(h~}$ec!b`|_]y\ZvYWsVTpSQPPejihKJedcba`_^W\?ZYXWV8NSRQP2H1FKJIBG@E(CBA@#>=};|zyy054us1*).om+lj(ig%fd"ca}`^z][wvuXWlUpoRmlkjiLJf_^FF[`_^A@[TY<WVU8SRQPO20LEDI,*F)'CB%@"87<}{9zx6wu3tr0qo-nl*ki'hf$#"cb}|u^\\[vutmrUpoRmlkMihKJedc\aD_^]@>TS;;PUTS65PONMF/--,GFEDC<A$?>=~;:z8yw5vt21r/o'&+lj('h%e{z!b`|{^\xqpuXVrUSoRPlOMiLJII^cbaDC^]\[ZSX;VU8SRQ33HML/J,BAFED'&A@?>=<5|zzy6543210).o,+*k('g%fd"!b}_uty\ZvuXsUkjoRPlOMiLJfeHcE[Z_B@\?=Y<:V97S6433HMLK.-HGFEDCB;@#>=~|438ywvv-21r/o'&+lj('h%e{z!b`|_]y\ZvYWsVTpSQmPNjMKgfeHGba`_^]\[T=XWVUT6LQPON0F/DIHG@E>C&A@#>=<||387xv4-,1rpoo&+*ki'~}$ec!b`|_]y\ZvutWVkpSnmlOjiKJJ_dcFD`YX]@>Z=;WV97SLKP31M0.J-+G*(D'%A$">!}||3876wv3,sqqp-,%*k('h%$#c!~a`{zsx[vutWUkjRRglkjMLgfe^GEED_^]\UZ=XWV9TS544INM0K-CBG*(D'%A$">=~;{327xv4us10qo-&%*ki'hf$ec!b`|_]yxwZYtsrqjoRmlOjihJJ_dcFaCYX]@>Z=;W:8T75Q42N1/K.,HG*E'=<A$">!};|zyy0543ts0/.-,%ljji&%$#"!x}`{zy\wvXtWUqTRnmPkMcbgJHdcFaCYX]@>ZY<W9ONS64P31M0.JI,*F?>CBA$#>=<;:927x54us+*/pnmm$)(i&f|{"ca}|_z\rqvYWsVTpSQmPNjMKgJHdGEaDB^]\?>YXWVUTSL5PO2MLK--BGF)'C<;@#!~~5:9zx6/.3tr0qo-nl*ki'&%fe"!~}|{zyrwZutsrqSinmlkMcLaf_dcb[`C^]@[Z<X;9U86RQ42NGFK.,++@ED'B$:9>!};|z8yw5vt21r/o'&+lj(igff{"!~a`u^yx[YonVVkponQPkjcLJJIdcb[`C^]@[ZY;;PUT75QJINML/.IHG@E(&&%@?>=<5:{87xv.-ss*/.-nm*)('&}$e"!b}|{]]rwvYWslkpSQmPNjiLgI_^cFD`_B]?UTY<:VU86RKJO20LK.I+A@EDC&%@?>=<;4{yyx543210/(-n+*)j'&f$ec!~a|^tsx[YuXVrqToQgfkNLhgJeG]\aDB^A?[><X;988MRQP32MLKJIHG@E(CB%#?>=<;|3z765432+0q.-,m*)i'hf$ecbbw|{^\xqpuXVrqTRngfkNLhgJeG]\aDB^A?[><X;988MRQ42NGFKJI,AF)DCBA$?>=}}4zz1654ut+rppo,%*k('&%f#"baav{z][wpotWUqpSnPfejMKgJHdGEaDB^A?[><X;9U86R5322GLKJ-,G@E(CBA@#>=};:{8x0/4us1rp.-nl*#"'hf$ec!b`|_]y\ZvYWsVTponQPkjcLgfedGba`BBW??TYXW:9TSRQJ3110KJIHG@E(CBA@#!76;|z8ywvv-21r/o'&+ljii~%$e"bxw|_]y\ZvYWsVTpSQmPNjMKJJ_dcbED_^]\[TY<WVUT7RQ3O20//DIH+)E>=B%#?"~<}{9zx6wu3tr0qo-,+lk('&%$#zc~}`^zyxwvYnWrqponmfkNihgJedcEEZ_^A\>TSX;9UT7R4JIN1/KJ-H*@?D'%A@#>~65:{y76w4t,+0qonn%*)j'g}|ddy~}|_ty\wvutWrqpRRgOOdihgJI^GEED_X]@[ZYX;VU766KPO20LEDI,*FE(C%;:?"~<}{9zx6wu3tr0qo-nl*ki'hfeez!~}`_zsx[vutsVqpRnmPkMcbgJHdGEa`CA]VUZ=;W:8T75Q42N1/K.,H+)EDC&%@?8!<;:9z765uu,rr).-,ml)('&}fddc~}|{zsx[vutsVTjinQOkNLKK`edGbDZY^A?>>SXW:U7MLQ42N1/K.,H+)E(&B%#?"~}}4987xw43210).o,+*)j'&f$ecbbw|{^\xqpuXVrUSoRPlOMiLJfIGcFD`_^A@[ZYXWVO8SR53ONMLK.C,GFEDCB;@#>=<}:9y7xv43t1q)(-nlkk"'&ge#zy~a_{^\xwZXtmlqTRnQOkNLhKIeHFbEC_^]@UZ=XWVU8SRQ33H00EJIH+*?(&&%@9>!<;:9z76vuu,10qo-&%*ki'&g$dzy~a_{^\x[YuXVrUSoRPlOMiLJfIGFF[`_^A@[TY<WVUT7RQ3ON1L.DCH+)E(&BA$">76;|z8yw5vt2sq/pn,mk)jh&%$ed!~w`{zyx[vutVVkSShmlkNMhgfe^GEED_^]\[TY<WVUT75KJO20L/-,,AFE(C%;:?"~}}498y6v.-2sq/pn,mk)jh&ge#db~a_^^sxwvYXsrqpohmPkjihKfeGcFDCCX]\?=YRQV97S64P31M0.J-+G*(D'%A@?"!<;:9870w43tr0/.-,m$k('&%$#z!b}|{^yxZYYnsrUSohglOMLLafeHcE[Z_B@\?=Y<:V97S64P31M0.J-+GF)D&<;@#!~~5:98y05v3210q.-,ll#ii~%$#dcxa__^yrwZutsrUpoQPPejiLJf_^cFD`_B]?UTY<:V97S64P31M0.J-+G*(D'%A$"!!6;:9zy6/4u210/p-,l*)j'g}|#db~a_{z][wpotWUqTRnQOkNLhKIeHFbEC_^]@?ZYR;VU86RQPON1F/JIHGFE>C&$@#>7<;:9z16w4321r/.n,+l)i!~%fd"ca``uzy\wYonsVTpSQmPNjMKgJHdGEaDBAAV[ZY<;P977LQ4221FK.IHGFE(CBA##8~~5:98yx/4u210qo-,+*)j!h%$#"!~w|_zyx[YonsVTpSQmPNMMbgfIdF\[`CA]@>Z=;W:8TS6Q3IHMLK.C,GFEDCB%^#K=[}GziUUfSt,ON)ooK%kH5XgCBdSRQ=v_^9'[%Y#FlUTR.-P>j<htIHH]o4`l1A?>Zwv*:8TSq5]3!kk/DgHTwd'b%;^L\[Z|49i1Tv4u2rr)(nKl76jE~%BdSbQ`Ouz\[8ZuWs3UC0Rm->jvKt`HG#EE`B1@/z==vutOT&Ro]O[MYKJVyf*c(b%%ML]=Z;X3i1xTRRt+*pp-,%[jYhD%CAARa}+_MLr&Y$5V3DToAmPej*;a`e$]#[Z_B{@[-fwv)UT&qKPmllj/hhBx)(>C&_M^]7Z}Xz8yTf.@Qba/;^,lkk"!WC1BS@-`_uMyK7I5XVV200{mfNj*uK&HHpb[D}B@zy=,+QV9Tr6p]"Nk0|{VBeSRcPa$_9Kn};{zEhgT4u,>*);'nJIkiEW210SRQ=<*;(K&I$tslk}BA@?eMv;(JI$F""mB^|i>>=vW)9'7%$#2NlYX-,HA@)''%%_?8[~;{zzVCT.d,s*N_n,mk6"FDCCTA?>P+{z(xq655s22}S/gfkjLL:fIH#EE!YAjVzgYX:)(s65p]m[MY/hCB+)RcPa$#""=<|43ixwS4Q2P*`p'KJHZ(!WVBec!-P=*ML9J6$GF3q10A-O>=c;(J%HGF!~_^0?.-w+QcUs`p4JmH1//{gyxeRQ
```
[Try it online!](https://tio.run/##pXxpVwLLzvX3918wj04MCqIyKMgsAuKAAoKKMqiAoqL41@@TpKq6q5tuz7n3/exatcp0amdnZ4fx7aj7Murf/@c/3YozmYgf7O/FdqORne1wKBjY2txYX/P7vB63y@mw162W3@VP7Obr82P@/jYbndWqp@tfn74nTz56f5fphjrt1s01/LV66nHX4Y83Y8vxZiGf@/rMzI9uHe1E3Lq/F2anr68FfF75dBud/v72NZ3g6dPJ4OV5XBkOnh77D/d3veujo8tk8vrg4DIWa0Qi28VwMBA43tg48vuPPZ4DpzNps1l2fsO73187n/P3d7/27jbrV3f5871gdx83JrWXx/HJCZx@@3Cf7aVvO3h68@qyer57tlMrFirBcqlYWMv5jzPpI6fDgZHZjv1Ev3Y2N0LvGJmXtWff0GO19Pt4989lB0@/ml/i3Wsv1fFoOCg@FvDu6dsjjMzB1f7FeQNO3z6tnJQ3i4UjdvphKmmDyCxjoWDkC@M@25rC6U6Hd4h3v7fdYWRaixu8@/msMXl9ea6M8O79HNy9e9tJtejuMbg7xD1UyQXg7nm/P5lJu52p2G7c@ru3/F4strbD8@AM4v767B8PPYNHZx9O7/7etr9b13D6ywXc/bX6PH4YDkqFfqd9fHx9ewSnx5sHexex6FlkuxoOnpRL8FUP/T68O@aMxbL98xOEr/oRWnub4ld1irjfi69KcT8fDeHuY7h777Hfub87hru3L86v4xD308ZJfad6WslB3DfyuWxSnH5g2Yt9RyNfH5Azsxnd3TcauC2/Dw/f1t7tsgORaX5cXbydn03q1efTk2G5CDmTu@tlbq/aFJm9C4hMBDKycpJlpx9700f7DscufNXf2O433Z3y3c1z5tFhv8PTf9qL6@nk8vJ51qi/vlQro/u7YvH2IXfc66Y7qYvzeLx@ubfbiMJXDVWCW6XN9fya79jrhq/qoHyHnKF8x9Nf1yFn7J4nPP2bIsMz8qIBkamdYmSK3X9zusuRpNOX8JooZ/yQM@svePcB5sz9wvJ7@9N6m302L98xMoMnjMyg9JjvtO@O0wZfNQAZmV@jyLhSGPcdjAy8Jnb3Cd7dizmDr6n3i/l@M6WvOoWv@sjeKty9hRlJcT@4vKCMDJ/ia9qk0zNxPJ3HfYGRmQcDM3yrzyO7zf3UdzzwuN8gElyeY9whMpUyZmQ@i3fvtFM3mDN78JrqpWq4Qndfh5wBJIC42@KRneUyFF18bn@8B9@mmxN4qyPvEOL@YL/vWfDuLYz7C7zVM8jI09Gw9PRYyN23btLpq3YqcR3fN4g7vCbKyAhiJM@Z2Rae7nQMh1Z@ereDd7@@Uu8@Gpafiv2H9h1G5rBFd4@d4@nFQjCY1XxVu/XAsoz9LDDfQ8E3@Ko8I5@cGBnMmfbbDUfgSR0xsnzXw7tnM13AmeR5Q/tWt4rrR4dZnwdfUyxhO2AZSZGBuL@6XYgEcPrDj9Frwrj3uvk83j19dJlKJOJXtYsYxJ1QbGsrs75@CF/V4z7cS9qxemBGfn5uMAR@hYy0D5@eIN9tCwshMN794mJ8dkb4zhA4h5FBjIR839s7hdN3CCOPN9fXMWfgraYIgX9/ECM/wvO3AGKky4lIoOSMfHd4q/BVpdNTiDP7lxiZconlO1SPHEbmYB9zhjBSzRnEGYd9MLAgit2xtzq7vroifIec6SMCw1fN8td0k2ju16B6ROo74dNQoLy1UVj342ty7UNkrICRmDOfWD0A3wEJ/OMRr008Ml9Nqnxnw/oTYOT9AL9qLnsDSECviTISv2ohz/Ldn00mEN8xZ3a2ec5AZGYThu/i7l@ABBD35uQVcIbiDkhAOZOF05WcicUqEPdqKJ/jd4fIwOkiMlQ9Qu9vW97JywsggQ0zkvC903lfYL6/IEbWao8qimUyzQ6@pjNEsWi0XMO4Z4@LG1BXvRmP69BpT9gs8FURZwAJoK4ivj@PId8tmDMY93YbqkdzfvE8np7VEIHhNRVuO5jv6cNU6hxxJnZaUVFMnO6EfIfqATgTDXx9fMwRxTyEkVBXV3IG6mrt6RHzHb5qrt3qZY4QZ@J0dzUj4fQ1VrX3HKw27fLahHGH01UUQySAynd9hdUDcKb6CDlTeirmEd/h9MPkTeJgf78KKBbByifnO3tNeDrE/eMDEXg6YXwGcebhXlSP6cfV@xtxgtPTBw2@J5ON5tV@7LxywjIS3moBcSYR1@MMvqbNyatgS0tetVtUtS@ez0cTxPcHqKvFQgdfU5qYHrwmqNoKRkJd9aeS@FXhrVojO5rXRAiMGAkodr/o3d52viEyWPlmU4HvGBkRd54zBgjsSgGKWfCrBhesemxNJoCRY@/AauF8BvD9ZjZlSFDH11QZlnpdXj2kyheJlCDuQWBL6XU/8RmGM5ZlGKsHxR2@6j9gpMI4kIth9QCMhMpXiQIXCyPT20znMSPjB5DvNlsEMXIR2NIisI6LQdXmb5VhZL9DfKaz8lUFziACp6g2Yb5DZOYhjLvHjZUPOEF/@cNOb7Vmn3j38Ui9O6se6UP4quzujbPyTjgcOkEOnM@lkBPA3XejhGLRxZfoDtzEONyPv8gJup@382/MGcSZBty9SpXvUZPvV/hVT8r4VU8CpY30kR4J4DV9EsMGPrM2Htv/jLuOzxwc1ODu0UgNugP6qsQ4PEeHwJZsB7/b1B1A1X7z@zAj1ZwBPtOZv5t@1SZVbeIzgGLb2wX4qlvY2aR8Hhb3KEMCzEiqfJP1Z@TvTy5n3363@JK/KkcxgQSEka1kAvj7Bbwm7JtC2B1srDH@fuhg/B3f6tYmvFXkwBqc0UaG8n10Uqa@qXWcTlPv0eRVG3EG@iZkSz6qHsSBLaz3@FBOH/vY6chnPj/0fKZSLpW6cHqW@HvrpoGRIU6g4Lv@7tEvurtSmzT5DtWjyXq@1yfqmwDfqW9qHl3C3c/Uuwc1dzetfOz0O6h8wJZarGqP9UyP8h06ynpNIEHoZOs4o6naGoycTV5fXVg9Bq5fxwP0fF3qypofGBni75XKvQbFlOoRqYVZ1VYqH2OpyCMhZzbmb2/IgQEJGNOz090lFJu81p4rD/eMA2NXBhmZaJwhEmgZh8@XwLeKKIYIjKeHoStDLrbmH/1zRuaIvx9Rvtf3YzHqKE/h7iVi2MeajhJ7jzmrfCYd5SV1lNgdlMsl3skrfEbmYoacAHgk4Mxsyjp52@DxsS90AuKRwMW0kUGMPLy8QJzZR4Zd38ZOXqkeniPnnsIJWFf2NhV11e367bPOhtjSx@uLFgny98c318ZMT@HAKaaghFnP975GOoHr2YF8Butqr9eF17RAPoOdPGdLpSeJLYmcocqH3QFGhtVVPVuink/0TdgNQ0a2JcZRezFiHCxndnaKwDgCW6LyHVBnAx3lz/d3YAdrE2HkM95dqh4GOQORgdp0Tfw9wXvtnVJRrU1aHinqKuMzjtFg8KRyYOzKVu6O@kzTtCvzeuPYa1PvEVY6@enUg/3q0EZdGfDI2485ZaRZ5WOnw90JgSu5wOYm6QQ8MjbLjtA45kwXo7eq9trtb@q1obOZ4un9B23OEOMghl3bRk6AdfXQ7/V6jnjObJNO8BkOGXU2jGF/XBLDVrth/KrXavVQumE4ff0I7@4@cO1hbWKnY9V@e/MhEowddtQ4@j@Ykcs5xR14ZAPu/nKquztjHBe7xDhCoVwZ436YMu5XZ5xhi8h0Id/hNV2jtgScQPRNeDrgexr1mXiTEPiv3oPxSLr7OvYeyIG5CvHD@Mz7ufJV/9I4eDcs3mrU@vu7JCTgmh7HyMfHpR3znXKm2Xz9FwpKOJxHXYzlTJwpKKj@wGvSohjvbKyQkaznu0IVYviKp5@Ue0wxzJCmF9fHvbBmGHdetdeegS0NuOqGnOAG9RlRmzQKCrs7cLFY4ySyjRmZFfpMGk/fBT6zpHz/BBTzU7@qvCYzjaOEml42k0krnICpPxgZRYWgqh23KFUb4j71epBxQL7DV73/XuDpLGfeRdU@ub8TtQneKuvkTXQxuz2KKgRX3d5nSvWQ@1WKzPvFOXXy2Nk8Ydx1XZmueihxV04PBf0zljPU2UDlk@uqkjNl@Kq8O6C@6YzpwHA66cAZVCGOExxn4HRt3FlkZKanQwLBxa7Th4cpNe7bRhoHsFRZQXldX1VQoDZdvT9TRwlcTO7KlOqhRsag51N0gk2P6OSdVFcVBFbfKkXmj7rKkMDt3ofXZMPXFIpqez7U3/X8/Rz7VYgM4wQcI6XKx0@HuxOfibudxJbMqwcqhoqWKhSUkaq6KdWDaxynoSDD96zoDpiWKrqyrQnryhQ9UvuaiBMMVbaEX/Wa8L1CGjbryiT1R3pNhgwbOfCXohhWuS5G3QHTI@NGHaWJ@rMpuBgpVz1k2MBSrydzyJkp4swpcOAS09/TEks1yhmZz3zOQ@8zirt/PEI@03@wLRDfgS1xfab@yvQZ@qp3GfZVr@NXe7IKsbm@tpbiOoHdarVIOTNV@Myjk/jMLfSrwCOvJKbHMjJ7d7My9@A6ASCBzyupPxqNQ8uWVP6uaEv0VikjDw8vsKNEJOAIXC5liGHD6U7tW1UwcgSRwZzhGNn6YpqewsVwMnF/d5xBnKGpCvZNO6hCBMxUN03cSY9knIAmExOaZp3VDOJuzLC9bhcyjriV6WI7m/RWp6rGgTjz9SmrbtJXFbWJGAfWpjM9F@O6mKIDa6qH4MBcddPPDtR@FTobNjuArgzjvpEm/h4X6o/6VQ0Ucj0X0/Z8Ms5A3EPs7oAEGZqq2Ez6JkRgncahzRm8e1M/OzCoTYITzOdrXNMTDPvbqrwm@Kom8yYJxVZyhpSr2M@3wpaQv@sz8vpTyUgVI/GrXl2uzpuoNh0zDrzLND01Z4zUHzXuUJtkTtBR1P1GZKWjlHRg6XQJI/F0Rf0xyEgFxXZ3T@irrvL3HTGJM0QC1Di0OMMYNuEM9HxJhu98AgrVYwO5mNdQqdWr@2KKOLkiBaWG6s@w1CMkuMGcSSYTjHFAZ6Pj74gE0YjUayuKoVybOM5AZCRNTxN3mtkoGoesz4japOMzT0@oGN71fj86rdYNKYazKU2zTk7uJH0G6irmjFD3mfojKp9Zd6AwPROlFjOyRyz1PHFACHxWpmkW4Pt6Puc/9sQP5JzZQk7wJiOwwlJXEFjTa3N8h65sm75qkXQCiLs0EWJ@gpnK9IBHPkgah64r0/erunwXr4kYxw@9VVJqvchSfYjv/f6PJt8ZWzLTlqSqXRCTCZzeWskl8rVFbgUfVA@XhmFrprcGGoeJuq9Wj@0lY0tMS2VeCDUjpYkQ3L3K@Dt2lPIEVFEh2NzD/DVh3wQdJTEO7uPQzMpUFOseGaEYxxnAd6fQ3zHuhMCCYVO@K1qqZpqlq9oiI/lcW83I1aq9@ppoRgkslatuz32cyRehehgrhvrIaNV9PudjnIAmceRwkRUUDVvSTibwq2bSBrVJVVDWnJiRkDNMqYW3qqid@u5AwsizMpuVbcLdc3B3nPhDRiKK/XwHUEEJIkt9eXHinO/xd/k3fzf9qhAZfxJnBzj3@J@64ds8c7iwGSVHMdYNbxSUbpihGNeB@dwDHS6eJ8uv0VxbVjuZFwIjU9vbZcqVotQaMT1976HqYtivzkifMXxNbDYcPiV9RoNiyMV2gwFdRtLsQMnIa6bUskkc@glkFYJmNuytkh6JXxW6Yeyb7Fbm44C4c3fOuut5NBoKv9j/71slrxv3XAXIt@Qf2WlG@cP0SFRqr1CfEZxA5e8GvQfN@bI@L@soaSJETou/PFfaOR@b@Pe6TUlLjdQVLVV9q@o0ywwJ5u0bUlCok69BXdV2Nga9tgYjla@q@ji8vCtDfCfFsAlcrNFAR9cp8@mp6g/ODjjj0HSUirZkwAnYvMnaJYy8xo7y7Zy8buPRvarPUN8kxx2/6uoUUT874IohoJhctQ3Uzr9ZKim1TDGcM0eXG3EGOAG@1bsey8jPD1R/pnW9Ymg2s5E0DuKR6hSRVz6NHqlVO8vFQqHD@Axz55CDkdw5AUkxPHQmbcT0NOq@gQoBp19yZxHqBFSbmP7OZ8OnuxHmViDFEB2MqzqwtiuDyPQgMsxJBxgp5wy5czLsrUpIEAr8pXaqVRvdCg@yDsxrE/NCoINRo9TSbLiq83Fg78F8S9rXpFYPBd8xZ4bqTB4ZdoY5ugxRTExVDvaX5Hr92KCuzCPmfHJ3oM6bTO6uqhDMJcJqUzJh4CwyrE3AsM/g7lrGccWddBfU2cBrymWFggKvaQ@dFpJbQe1s3Ojo@r7rdm8Z4yAX4KRm4ixama@aaktu9BgivkvTLJaR08kAtSWBM8wvlkB/pMqBTVRmc5wRKjN30tFkIp8n1@t/xzjQwajVlrTTW6N5E939fDfKeg@4ewH4uy/jVtxoysTfTNOb0tSce38klfkKez7ZT6B08swfKSu15rWJ5h4aTsA0vSMzD4ryVaF68KkKn2sDAtNkos/6Jq2jy0xLFfjOnBZiqoLqD3EC4bmimTz5gZnnik9AjbRUqqvkB9471Si1CuNIQM6wzgarh5/7xXjfZOInGGj8BGKahW8VImOU7/IEFLWl4QBR7I7YEp9rA75LPg5pqqJoejr/DPWr1n3mW9K5Xql6WJmmx7nYVHJFKbqYqhiSw0WcrnpqpbsrriiziT/0HmU17oiRif/GaSF0MZd24o8ah4GDMdXS9XwrXgjqVwNmTK/TaStutImmX5XmTYba0opvCedNbpEzpM983rZRf1e1VFIMHwt51Gdkb2dUVmpVJJDdOUbqz7y9oLtLnTw7XfiW4grTM1d/JFeU4AQ011522uRQF9NbeE131FECzsg@PQOHy6q3U@757FyF0E7igOkVizQBpc0A5MCo1DK3QhAQWOooNRzYRLkS@I7OIv5W88iWoDsg/b3O2JLOFYU5w/RIaXbA/MDGiuGkplUMj8i3FD/gp7PIsEmc@lWlSZzZzAY1PYxMtdofYfUg16t2aq7pV48lH0dMy/SMZ2UGtQn4DM2blI6yksPaBHFPJqRJHOpin3PxVf1sVwXeao8m/oa6mOrjUB27EhKo/hkjt4JR36TXxSgyioOxXivqvRAxfvpi8WU@mdBPzVnPp517MP6OTI9mNj7Pf@3t5MrViazPJG9UlVlwMc2@h@WvCajISEXdZ5MJ4WU2nYAmPC7WDUsatv7uas4Y@gmUfBcaNirk2nzXues17kvVl6r4xdALwRm2HiP1bmPAGX3lk3NGVG2@@QUZWWMeQ@apxdN1vlSmRxqobiqKqb4lpRuG10R8RvNWDTyGRpyAqT/MU8v9M7KnFl3epJAjAsNXNZz4R7RbDdq4q/Mm1TnK9HfhRntTPVes58t0Fc@V4tP7S3/nji7nWN0RQsbB6ypkpMzFVF8qTeIYzgjFkBxdol/FbvhjY91gi0fuVxm@qzmDXVny/FqaIuaDW4JHmjm6WG0inYD1q9IGksm86Y@tht/fMHGCsKJckZbaXzLvD04RgRO8IL5D71FZmXuYbSC5@AQUWSqgmNxra1RmUlBYv1rlpz9kda7XVY1j32m321QE/kcU4/k@KNF@07GyxWOWMzq3gvAtkSuKbzUobjQt05OmiIorytitIF7TGnZluC3I@1VUDBkX0zqLZP1duHOEciWzJY2ComdLBhnJ9HfMd6kblubaXEHJAs7QDmjUuoP4zuZNtBNnMEXkOoGxlqrdapB1gv9Zw2Z7lICRcs@n55HirUq7t6ubX6veTgMf9uoWD@E73@LBXvt9Rm@VqT@//Xs@ATXGGVY9Urh7CzgT/WvvQNFSudqpOZ3v2Zyf0f6qqv7Q6YnGmWaLBzrKIzYrc@I0C1gqadib3G3sZnuULueDdkvTXMM2yHdkS/tiw9TAsWumQsg9X/MohRoH80JEFHeOcBsrPR/TCd4CRjqBWrWHqDLzXUSt@vMPfmCu7vv4/ip1NmZcTLi8u6x6KG@1atbZ/OvqUa2Ir9qifDf4qmJHSN2z@Y7srPB3x4OtJztcVhj2Ckvljq419KBAN0yT5x3uRhO9h8SBJS4GfdOI@AxzMALTU7ZJ@FfFbXC9/31V06MdIa7pYUZ@a6uHmYdceCEk35KM75oJqEbdN3COGnGC8ErPZ76RoXjI/7eZDfuqUauyvypmZdDJi3mT@R6lsXKlP527AFEHRk4w8eDd7cIfubpNsurYVfabJD5D@M50MY1iqNHFNPr76kb1Cn83mjzjW9XljLxRLXQCfE2ABKNyuadMJvgGktJRKjkDOCPUH01t0k5vV2qTqqD0JOXqvBFBTa8SyOJcO5cSmh7wGcwZxpZmW9rJhDpfZa/plf1yA3N0rb6mU@28yWzTUcxXiQO/t65pv4kYB55e4nfnOxNQ@eTNgIy6YSqY3mJl51n2oEieK6MtHrY9hXdn2yTUN6kT0DB2w5reQ2zHqlqqPDsw3cig01WXCO2ac58eQ4LVu6/sla349P6NU3oeknLmyaWf2bydN6g2obpfoE12QDFpR8jUSad0B/7ZhJx0GBnqDgAjO8rcAyKjcmAVxfSeK@00C77qtzI1X3W4yLWJPFd8MqHdbzLbNWcYSfke5Pq71K@yXyoBtqTjBJrtKZUtiW6Y9lcBZ2xcS2VcjDiB1qf3B87Q5JnjDNdn0K2gmTdR3wSvSVe1cW9Yu/Os8bq1FZUZp@Y6/Z10YFfKrkyeV39BgOZN8FXfV@bavWIe95uU0y8lL4RQUNJaD/nnnP1SiTqjRFcUcuAVPmO4ay7t@Ct6JNOwQ99fSkep8ki9w@XPuba686zOPWhmA9UjyFUIH3k74e48I5mmJ3DGdL9Jq3FAzki1abkMiTmfb/oKDJv/us2Dzcp92GICqne4rMzkqaNEtVPGd90EdOQ162zEV0X@zt05YhKn1QnE6To@w3OG9dpGfIbyXfxihuw2xv3Vf/rVCdTFFMaB/nfayICceZZ3VaTtKdE3qdtTRi4RpV9VO0qui7G@SajMpBP08zmGYkx/lyZCovKpm70mlU@ZHTCMxBllVbuFr6idq14Inu8ReaNadqiLWdm3cjp3WnAvhOibtH6Cld5D4yxSt9ZW833V26lu3J1EauwXkeCtHvqlyqf4CRTP1cqO0F9b@HxHiFdtA2eRkT/y3@@ayxmpm5qbb1SzedMHuQAx7oCRf2h6ytxDvw3Opreme8NaHZj9qpDG@6P91YlVhZxc3uTYpco3tg/lX1kBfNdux0oOF1PVTfRNXNNjswPhfxeeK6Yt8doETM90G9zw7pL7Ut5FNFZ/TH@5oRprMJcIfNWMur8K/P2A5toLpi2tegxNNkz1GxmVKE7iQgE@96BfREolbbaIUDv5ZsALea4GfNNRqMwrW2urU5Xa9mkwl5Vfk6NlK@w3l8eLp7Ozh9qb/6TseXkpOIbZ8EX/MHUHD2R/3m5FXU3HpS0zOqtX19cqB4O9xzdUIV5CndEWIMHVx9yLp0/CN0HLcLhx1M/WP@5cXUesVQSG/BOKPm3V56ilTj3u58JoZ3uQ/nXA6d3Tzsn74roZuXo/nwXPDjer47WDwbzw1ske29LpTmorsbHY34fXcFJ3Vl9uTpqly0K@8fXg7bm7DkepeLN/FbsIPm191qvVN5/3FXlkc3D5eOQ4TCart0tfu1ScOi/t4UbwqP6SHEPOeGO3nXv7jQ0z8jvRXHv4mHvO6s5JoTIejQYbj4@pT48bvmq71LrZuVpewFutP6wnTru3G7EW7SJazg@3UrXEWqf9Xvoq7OTCF41GYHPze/xQHnjfC85s9rXbPFqmEouvfb8PXSLT7dcba3m4@fPdSN3Xqr3Krb0dLTwvY9@L9GO/Hnr3H3g9MddzPjd8Sp/DJ8a473lj7oIzZ38DPrPEBve@NI@58zl7xmodp1o/TwcH@/NzT9S1A2kQKI8uL9ZQB/a4XA5HOx5pAgdeLBqH9fU7/8xbbiMSbFvxmdfhk1V83wv352Q7HJ4FAsvaBjCOQbG4@5DLQtwtl8lBY9G/vNj1uGfb4debMcR94/Ew5fPQ3W1W3GQPBZ8@P2qh00DF23l1FfLZK7flHP6/nmWtsu8tFaP5bftxJjjZ2kyunRzs9@DuDshpy2@7tRlfX/vwnfbOZp3XUH6c3drY@O5/fd5XT//ff/5z9PLeHd3PXu9vh/8H "Malbolge – Try It Online")
If the challenge didn't require halting at some point (eg. eof), it becomes pretty trivial, scoring **2334 bytes**:
```
bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTRnQOkNLhgfIdcFaZ_^A\[Z<XW:U8SRQPOHML/JIHG*ED=%%:?>=~;:{876w43210/(-,+*)('h%$d"ca}|_z\rqYYnsVTpoRPledLLafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(DCB%@?"=<;|98765.3210p.-n+$)i'h%${"!~}|{zyxwvuXVlkpSQmlOjLbafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(D'%A@?"=<}:98y6543,1r/.o,+*)j'&%eez!~a|^tsx[YutWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U86R53O20LKJ-HG*ED'BA@?>7~;:{y7x5.3210q.-n+*)jh&%$#"c~}`{z]rwvutWrkpohmPkjihafI^cba`_^A\[>YXW:UTS5QP3NM0KJ-HGF?D'BA:?>=~;:z8765v32s0/.-nl$#(ig%fd"ca}|_]yrqvYWsVTpSQmPNjMKgJHdGEa`_B]\?ZY<WVUTMR5PO20LK.IHA))>CB%#?87}}49zx6wu3tr0qo-nl*ki'hf$ec!~}`{^yxwvotsrUponQlkMihKIe^]EEZ_B@\?=Y<:V97S64P31M0.J-+GFE(C&A@?8=<;:{876w43s10qo-&%kk"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNiLgf_dcba`C^]\?ZY;WV97SLK33HM0.J-+G*(D'%A$">!};|z8yw543t1r/(-,+*)(i&%fd"!~}|_t]xwvutslqTonmPkjLhKIeHFbEC_^A?[TSX;9UT7R4JIN1/K.,H+)E(&B%#?"~<}{987x/4u21rp(',mk)jh&%fd"yx}`^z][wZXtWUTTinmPkMcbgJHGG\a`C^@VUZ=;::OTS6Q3IHMLK.-B+FE(CBA##8~~5:98yx5.3t10q.-,+*ki'~}eez!~}`_zyxqvYtsVqpoQQfkjMhJ`_dGEaDBAAV[Z=;WPOT7544INM0K-CBG*(D'%A$">!};|z8yw5vt210qp-,+*#j'&g$#"!~a_{ts[[putsVUponmlkdMhgJedcEEZ_^A\>TSXWV98SRQPONMFK.IHGFE'=BA@?!7~5:9816/4u21r/.-,+lj(!~ff{"!~a`uz]xwvYtsUqTRnQONNchgJHd]\aDBAAV[Z=;WPOT7544INM0.JCBG*(''<A@#!=65:{yxx/43tr0)(-nlkk"'&ge#zy~}|_ty\wvYWmlqTRnmPkMcbgJHdcFaCYX]@>==RWV97SLKP31M0.J-+G*(D'%A$">!}||3876wv-t10/p-,l*)(i~%fddcx}`{zy\wvXtWUqTRnQOkjMhJ`_dGEDDY^]@[=SRW:877LQP3N0FEJ-+**?DC&A#98=~|{{276w4t,+0qonn%*)j'g}|#db~a_^^sxwvYXmrUponQlkMiLJfIGFF[`_B@\UTY<:99NSR53OHGL/-,,AFE(&B;:?"~}}498yw5.-2sq/.-n%l)('&%$e@b>,+^^:87Z5n"!10/QP-kMv(gf%Gc543}|0{[-YXu)t87L5]Ol~jjiz++evbaa`M^!=Z|kWWD05S3?O*)o'JJH)F!~f1TAy>,<^]:xJ6YXmlD0SAQPk+vKaJ%%F5ECCX|zz=xRQ
```
[Try it online!](https://tio.run/##jZXVkvJaFITvz1sEJrgHd5cQILgHgkOCy@CvPmetDb/Mqbk416nq6nyru/dSlAdreTr@@hrwqkg4FAz4fV6P2@V02Bmb1WI2GQ16nVajVtEfFQX1fNx93cv583Q87OVquVQ0Xc76uZb1jEfJgb3fE7od@FoqajUV@NhdUilLls1czslTXKR74ZAi4He81E1Gm173t7qSqB8Pl90W1XfbxXq15KXFfDadjEfDTjzejEQ6wWDT56u53U7OwdhsKbM5bjCktNqgShVRKinX0@G9XVzn0/Fo@O5dqbgMHvfb9eV9WduW17NloQDq4mScHibEPqq3W81S3Vt1lbksz@RzXNaYMaSSibiKppGM03f3XFwWs/2IZNbGlV7SKqjpFL2fH31Ub52a6L28Li1lacHNsug9IcaRTLAVaNRroO4s8oW8hcvGX@qxaEQJZB4@O@O@IPe9dQfqKlonofexcoRkhGsXvdf3te1mveJl9D7NgPeB2I8KxLsPvAN3O5@xgXfWYIgkExpV1OcNKZ7@x@16tTodJ2YP3Dcrw1LSLmaqKagPnmLvJnRAfd0A75vSajmRFrnstN9LpTpiHNRD7aC/4fNU3c6Sgynkc3DVmEGP3jEzFOW83xm46qfdeNjhVVW/uI9/XZVwr8sSeF@C9@Fs2h@PUuC916h3QsC9WCtUXKUinwHuZjaTjvxSD1J@383jvnxCZvZ74l0vLzTUczK5KYbiow9k2p@txqFe3VZKq2JBynOQmcxomBRbPULG3wAybkgkX0i/1FO6RDxA01646tPnvRHvJO@ad2Zm9McI1e@9a2e3bTZX@1plsy7x8njEceIkkxoOEv1oox4KVZp@b80DV7XzjDVnMbFGfUqngavSJO@QGZJ3VN@YIDMf2jmq3wiZdyIbNSBTLiIZbvB/1NV0hKg/oE0kMwbIjGmN3heYmfGVeop34bA/t5tHJLOYI5lFbsb2e6NU4oer2iCRrJGQUUeRuwvJQJte3rfoXYeZwTYNn5j37o5cdQdXnb26Ct4FTCThHmw2SCIdRWyThagnQ6j@5n5FMifGtseuruQPpWY@pSdv7l1cgmYduQMZPo@JZNPovd@LdjEzfmhTJVdy8MS7CTIDSwDclSG36/Gwe65n5@eROewsW@iqrJOA@@RjPKTQu4Dc19DVKiSyKEu5@SybGQvdRKLVi4Y7ocAP3KFNJJFu3Mh3ZvZWVFfRkqR4qw/66L3T@uNdlvJzbjrpjZBMTCDefXVU57IMk/521Q9FkHr47lfMu505wFXfiZyrkAxmpnfovhd4W3ltJIfe08lBItbDq1bKeFVok53N5K3mrMmQ1mtxCYAMWQJI5Jms2G6jUb@XANUv57/bVKnMUT03HAB3XALwHq5VWwGf11uowIoxGWhT1mSM6pEMrJjS/Xzivl8wMweSGfAO3J8PkshHvwd53@JG4ooVi5NviYxEam1Qr/OwBA67PYOZMcaiP5A5HTCRG1RXQt7JAuOKHfbt9gbI1KpkZ6RRbjZlcYETZAmCQAa4v5Ygn0tiZuCq6gDmnbweHrfV@SJDXo/fOwPq/SNZYPD@3pl8HlYMEtnt/OzdxBLvarU/ElZSASe@TWfgjonUaiCRmBlc4OuFXPXSAfX6Ukb139xxxWLNRjccDARK78z8dwkImfcCn4zA3QxkZMzME646Gr7eJlD/ayN/c4d3VeiG24EyvHxul4vDrlqSCVDX6UK4wEqPO/C83242zPvBoIe8r1Y07sz0cX@9HoKwRzKN5Z82cSysWDLZ7mObqrhiHk@@jDuTTnFm47e3Cbv62nfbfotLQMvv1yM8CBr0ggDGWo6VgoI/K/JGKXfSTCd0aggFedwtt7ax2ThqD24X5@gW5OdiMb/q9ePTQBT7OYEKtO5SvR63OMpMqKDTrtUsm9Ym4arWSuQSNPiFrvfMOsG7HLeUI0Ve0p@yIkvTSUciFmvcr9fAuVT85@srvj4O5PF@MxYl6l8 "Malbolge – Try It Online")
## Explanation
I've been asked to explain how the program works. I'll pick on the second one as it's way easier to explain it than the first one, but the way both of these work is really similar.
Let's start things off with decrypting the code. As someone down in the comments did it before I started working on the explanation, so I really advise you to check it out.
It doesn't make reading the program any easier one would say, but before we jump straight into the code, let's review basics of Malbolge.
The virtual machine is based on trits (**tri**nary digit**s**). Each machine word is ten trits wide, making it range from 0 to 2222222222t (= 59048d). Each memory position holds a machine word; the addresses are one machine word wide too. Both data and code share the same memory space.
There are three registers, each of which holds one machine word, initially 0: the code register C which is a pointer to the instruction that is about to be executed, the data register D used for data manipulation and the accumulator A also used by several instructions to manipulate data.
If the instruction to execute is not in the range 33-126, execution stops (the reference interpreter hangs in this case due to a bug). Otherwise, in order to determine the actual instruction to execute, the value pointed to by the C register is added to the C register itself and the result divided by 94, taking the remainder.
Here is a table of all possible instructions.
| `(C+[C])%94` | Description | Pseudocode | Op |
| --- | --- | --- | --- |
| 4 | Set code pointer to the value pointed to by the current data pointer. | `C = [D]` | i |
| 5 | Output the character in `A`, modulo 256, to standard output. | `PRINT(A%256)` | < |
| 23 | Input a character from standard input and store it in `A`. | `A = INPUT` | / |
| 39 | Tritwise rotate right. | `A = [D] = ROTATE_RIGHT([D])` | \* |
| 40 | Set data pointer to the value pointed to by the current data pointer. | `D = [D]` | j |
| 62 | Tritwise "crazy" opertaion (see table below). | `A = [D] = CRAZY_OP(A, [D])` | p |
| 68 | No operation. | `NOP` | o |
| 81 | Stop execution of the current program. | `STOP` | v |
An image of the table can be found [here](https://i.stack.imgur.com/2edPi.png)
Now as the code is more understandable and it's actually possible to tell what is happening there, we can jump to the general idea of what is happening there.
Without any jumps, programming Malbolge is pretty much trivial. When the jumps are used though, there is decrypting task needed to be done before executing this code again. Everytime an instruction is executed, it's getting straight after encrypted, so it doesn't behave this way it did before.
To illustrate the workaround, let's look at normalized Malbolge cat program:
```
jpoo*pjoooop*ojoopoo*ojoooooppjoivvv
o/i<iviv
i<vvvvvvvvvvvvv
oji
```
So as you can see, on the second line we have `/` and `<` instructions dealing with I/O stuff. Utilizing the fact that `C` register is the instruction pointer, we can modify it using `i` instruction effectively creating a branch. Before the branch happens though, we need to decrypt instructions that just a few cycles away read and wrote output to and from TTY, combined with a jump. As there is no real way to store constants effectively, we need to embed many non-related instructions and use their value to compute other constants needed (utilizing the fact that Malbolge doesn't separate program and data)
*Note: Parts of this answer were taken from Esolang wiki Malbolge page licensed under CC0 - [link](https://esolangs.org/wiki/Esolang:Copyrights).*
*Possibly, you might want to check my [other answer featuring Seed](https://codegolf.stackexchange.com/a/189091/61379)*
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 6 bytes
```
,[..,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1pPTyf2/3@X/NKknFSF4oLUxGxFAA "brainfuck – Try It Online")
For once, a really competitive answer in brainfuck. :-) It just reads from the standard input (`,`), then loops while the character read is not zero (`[`), writing the character read twice (`..`) and finally reading a new character (`,`) before going back to the start of the loop (`]`).
Alternative 6-byte answer:
```
+[,..]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1pHTy/2/3@X/NKknFSF4oLUxGxFAA "brainfuck – Try It Online")
[Answer]
# [Seed](https://github.com/TryItOnline/seed), ~~6013~~ ~~3942~~ ~~3884~~ ~~3865~~ 3848 bytes
```
6 2686150228553910251590139707025615036563204497823963635717768129239771871066022173506550480510882628259267028226290577985584582829987099606110915656117177113555095646841841520224800333754793732176561479800611856258812006670385981709167679328497862503284773114717364645850756926464567857029605682209030697372493435852024478962025612141035167904456425050991742516020282696732660004824569723936406080643638019715421991278634074220365586727498681650073989748857985341022350116695714407041551609933358182688736747622670056818175549484918971558384479903673900409406866275258032866680967195428439907751537922194839977711106739550525066186108781580088916582559490041917035011328862266125578018990106393872489460844458091217404944194309597162769266585917996079831048944050703695352212652362891425728346891039020051565145149143668695374506752075410956647268061596926723805877631732070244839345640289062870487268706837056753112890753688530410829624567367052492603150395779619674714389456447573342335882718419424356991739625084740814435581409670174841935167450868967735568432921607395284483532735870628809137816139721467391760314297120583388009684979379888771619327969950939260709632318979448755571394507744993723267176377451465261335636767345281382139780890626858048062851714445255458413414708836044457819560626602471881203745677166851290194466534044374122781840150694963232713079984019097616802988558052961445185981197848860688635007868494303883280609553158126926303057368716954797175868772233997584782178460308584468311133667562020523260687787209651365697360075036255149184531675013585317549831215044187699501112214237282761452176427542227751840469500783022037518267131004723958694850409020207947539046371030202918430731468837057173037358435898981729128093138565524861044307737736772778645659866179416374742499528142506977571896833797572787168504674372995624869224644028121889021513694674680344413147327217671463636201883832593707987630471763158950694907193475270346642656464131212900528377257996057522592531063490286796434946290829640562975054259249630102041301990094261151488784971084438450904697283402436878185751193256803412549504172175692725366543545573099651580644132336272302990268431569623087644930350666119986012078396755208814027614451748455718916151950218835893255721018309717807161101069849247670957963270760531996609510342178009605381013854568528344071028665101709824510991652144229895556116304356971449229862349660751509158124118556805449346752918775201366378708970673708268140336609704879631200464020207189960217784283188350457711700181561855735903701439931161728546207607766764248018356183768557244013532032616392458312600465372655052565572757979232509950076857757257164261786986456779565081319671440867797151240096925123970490604003172676471092543424462070540303172987644037832692737644573481399927217285232015082118420498058022229538934735831710860610342762500071914715742707928060606416262583307855509796730058097681208691054336064995992598081644175617375019325706441005506100489323794725547244923204524790583484243672718647866979116309868261348266944902049457094368284266044502218232850494065571536043568039093446786891928597439310947971461490128765873399872574753055564655381318395939745692438909430171644009177696549501234738931977436030245682360974103741227416811200635596942701451202333113537361407624672328798572271366897755165037017879673502748767425083758652376018772700583221474572236166246539494675416322678094399996691972837962509574037110004298629947088012862552029152119412750923308070223808629424081676003170951500587426197322368913565250353332410276730344732325753114510178069340400741671217608323179698501977213623893949006870978691284571486316780769512681865771113879654002525802085758553029765815927252866913455193686303619992165147682671351400793392238437682055370542229871989802092530537034276944154276536658348210
```
[Try it online!](https://tio.run/##JddbjiTHDQXQrdg7iHcw/rURG@ovG5AAwesfnZseQd1dVZmR5H2R9dfPz@@/fp1/7DlanVPv1dhn9NnbaX3eeccdr86qc318@601Ruu73@ajffdct40xzmij39n3dO313jnz9Zp1@nxtLSeO3ftat15/fW/X37H3u25ziDtHtbuGS@au/PTYWv2c9tZxYX9vjff6avt5xJi3ebHvrfN6U3eqnyd1731HO97x51DAdqLqa03F33Wez@fazZHunG/1V2@WDrfm3mzXo7Tfa6ntzN73835rtertPZsH9Td6b@2Coj9F3LPa6m6bGqs279oFo1ajxmxt3ddmFXTarX76eq46cEuXuyvhnte2fzdYvHcdW54OChc3j3xLKSrwFkjrzjnUHsYw0BW@y7MV4gon6nfO9e58R59nraO@5ij97d1xvL7eJsYRtzQ7Fl6dO@9ee81RofDVavljva1ulTT4FaD6PtUg5qBxthaPY1LXVf1M67rdzX8a7ePB8g59gqHGOgdqczVNQGM9lQ487eOYwtd3jCo2AXizNxLt1cAbeJDgTT2SAznRQS@8eNzpsG/D4x1CDPM8J7nZw@v4yOdo1zRKaRVjxz2bYukMaYt8eu83BfdLtQPTRwsnHZI0jWlYVw3@UcN0FNCGPiO0p8mob5DcHtvHBw9ayMmvE0YeTBGQZrpqFbnuFje4vnqdrSrvQ5507uuHILlsEQvKNrR1ALMW2@Yw/yMl1Wms7T6H2tuLbx@1qDKKUetF7SWxrYBwT1N5iwIKdm/yx@0nj@JfHJWiyOJE7IvhX269Kg6sOohNlLkAoBMtv6hqzfjJb1BFEZSnLM@lO4b3qgXQ8ZgRn9Nvekd7RKAh8HrdkhHr9OGZikIivR/uuxdf/E7q3L2@cJISdD1xC8@59Z9I@UBVKyYo//ao0dMoys@a/SiWwNWsLfwzyuZYZdxzd9Vnxy1/5qNxfb4rKs4XQjH9Csvdfe7h7HikJYLYV4UvUkCtcLzu76tGoisBpEPCJS82cU99mfB5an/kYE6UQHpeOTA4hmlb9LVFV5KHM1cVrh2Pi4E6vm1DQOC5hyunBDUEyRERGVpuLO0Hhim7V24nwhercIOOKopCHuetz@eJZjlpHPSoD/sgUGVrCs2nTpNP0q6S8a4BI6sOo@SR6gMlpIkw5wdT@DCVaAluAAf1jeSoCYt0Khednr6S/Zt3hAY42FMtwbOHNODfZML1jiJQGowUBUWMI21keqEWryuRYhLBewnoyiggNslZBEWsVM8UEkRg0/JNOsw4rTQWC9NSpp5g2sGYBZJsgn0mcKJGnA8tG5PEPsQF2RplpkAKRWIb8@QaIIPlipRK2rrVsEIxBDngo6dLq0rk@W00GIaZVsrXgLs6@b//p/e66QENRIvN/iUBg8BUBx2zN7OPmdehSBVl6IVzPQkyrBAo3hDqRboLf0l7tX@qGxz@BWwPW@mE4ZXfLgeysAnUExZ81D45t5PJE4RckyGBthtmX1RN7Ls@UQu57dIc@kjWNRBrscGKtOWSlxVGwRJN8HVIootDHDE8Z95YEnEn3ToL2WZ0Dof1EICgzvrixJnh12JcYSrwTPJDRjuxkXy9VcffGd5ZKawmy5RxRka97Hev8XBMyn7BJ61jeQrLXLvZMLBsWdghBRnr5pSsRawBT8@EUMvEBHolFQdeWjYrz3hMwxmWokVAI7OcjLMcSPn27Tt9xmIcaEtJSkaCkmXEu3YVY1QWVKQjrrOa5f5ot92ZzYKPvZX1y0YzpasnoSLTL9HCHRkgIysY2FrARJWY9nqMD2mj4O3oZRqUOirzXNBDKzWNiqq4dieZKcgW1/XD8C38jewFWUZCZ2XoX4KTRcSdSHl5rkGZrapFUyu@3jOx1QI7SWQP0sHLk/heUngGjdlURhYiAynSE8U0DdXKRtC/@ZqZM@r7eRM/L9hQkRVTPhuP4@OY5kMBuj5ZYDZ1apsN3X2T9eH0htwsdkbHTj47l0yokQgiHpwRcyFDBMsthHFPpgiFZ8@akjYwJ5mUCwWCEjpe3yzj2TZiALveyoqeXdf6k73CHOV/25yYpcovIE42SVSc7IQurW8DEEAj8sl@RGvM7cmhB0fGR3K3JY8yMBgo1wULSYm9mQ05CBJStnInV/aEA2a4ZEzpLjuZg4UPf5GViMOUiHCklM6aYGV580NAbEaO2bHc54uDTgKZgOj5UuAoTHN4drLkvanhEZ4YAastKx12s@G8li35W/EFAz8ynw4coq5847DfjO@B60tDu0m6TWokzhOGSY64R5fp7Ebn@VoysgeksqwtNwHe8zUjMzCyTC/29HzxEVJOzIJrpmea6Et5PW5MLfFFnvgyfwTTieezW9rUvq8cqh3xY@xGwa7Jjp/sE3Ii4mUcZwIBSM0py7WqkFtsYNokCPOFIrM1Xwek0/uSqmWfx40RS3LZvQ1nQxrBwhmHNqYX6OSY5rOXJ20z/sStt2ULj7yvMUG3wlkGX5J0Bq3oDFQCDP5u0WDWgfvF5PyaPNlpv9W2Z4P93JW@PaEiWXCoUaOocbqh1Kh9rVzaM1myzrWMA39@ku6Mh3HLo0XBP2zPbHPsl4Xuy@rsjLYYw0K9sd/KFh6MhRHvZ28L4F8SZEXO9qYWG3X/9eu3P/737//@/PXnz7/@88@/AQ "Seed – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
Full program.
```
ż
```
[Try it online!](https://tio.run/##y0rNyan8///onv///7vklyblpCoUF6QmZgMA "Jelly – Try It Online")
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~139~~ ~~129~~ ~~109~~ 106 bytes
*-3 bytes thanks to Jo King*
```
N.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Ajax and Page]Ajax:Open mind.Speak thy.Speak thy.Let usAct I.
```
[Try it online!](https://tio.run/##Ky7I@f/fT88xK7FCRy8gMT1VR88xuUTB00ovODk1LxXEiHatSC3NK4mNds0rSS1SAClVSMxLUQCpjgXxrPwLUvMUcjPzUvSCC1ITsxVKMiqRWD6pJQqlxWBT9f7/d8kvTcpJVSgGSSsCAA "Shakespeare Programming Language – Try It Online")
Spews warnings and terminates with an error. Deal with it.
[Answer]
# [Haskell](https://www.haskell.org/), ~~15~~ ~~14~~ 13 bytes
```
(>>=(<$"dd"))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81Ww87OVsNGRSklRUlT839uYmaegq1CQWlJcEmRT56CikKagpJLfmlSTqpCcUFqYrai0n8A "Haskell – Try It Online")
or legibly:
```
\xs -> concatMap (\x -> map (const x) ['d','d']) xs
```
Explanation: Lists are a `Monad` in Haskell, and using the bind operator `>>=` is a `concatMap`, executing a function that takes an element and returns a list on each element of the list and then concatenating the resulting lists into one big list.
Now we just have to build a function that, given a value, returns a list of that value twice, which is accomplished by `(<$"dd")`, which can be read as "Take the list `['d','d']` and replace every element with the argument of this function. The `"dd"` could be any expression that results in a list of exactly two elements, but this is the shortest I could come up with.
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~229 218~~ 213 bytes
```
^
/l\
/oop\
^-----^
-^ ^-
/[\ /]\
^---^---^
-^ / \ -^
^-/out\ / \
-^-----/set\
-^ ^-----^
-^ - /+\
/ \ ^---^
/arg\ /1\ -
^-----^ ---
-^ -
-^
/ \
/arg\
-----^
/1\
---
```
[Try it online!](https://tio.run/##PU1LCgIxDN3nFHEtIXgHb2EtVC0qztAynVl4@voSywTaJO@X@l3S/H5Iu7/ynHtnVCR8OgU0LaWiR7ECLtF4IdZLYL0GMsYfgVIODAlALdsabCf5e7XlNez@kear2Ek9@jXzDwFoTcvTAD1ZLA0bRhHyIIDsQtxxMe3J7vIOoPd@LtttytxqTp/DDw "Pyramid Scheme – Try It Online")
This can definitely be shorter. Input is taken via command line arguments. This equates to basically:
```
str = input()
n = 0
while str[n]:
print(str[n]*2)
n += 1
```
With a few caveats, like the printing actually being handled in both the loop condition and the loop body.
Alternative 215 byter:
```
^
/l\
/oop\
^-----^
/[\ -^
^---^ / \
-^ ^-^ /set\
^- -^-^-----^
-^ / \- /+\
^-/out\ ^---^
-^----- /1\ -
-^ ---
-^
/ \
/arg\
^-----^
-^ -
-^
/ \
/arg\
-----^
/1\
---
```
[Try it online!](https://tio.run/##TY7RCsIwDEXf8xXxWULwH/wLQ6FqmeJGx7o9@PU1t@vAQNvbe9Kbzt8lTu@nlMcrTalWRgXCrqPh1JxniCAoR3ozYJewAlrYyEXwpSWt5sCxHC9gs0nLPANq3lZkhI5bn8OLm0LcMjFB/II5@wTWuAxGf6nc26nxHR@/5JZHPafWes3bfUxc5hQ/px8 "Pyramid Scheme – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ø˜ or øS (both 05AB1E versions)
ζ˜ or ζS (new 05AB1E version only)
€D or €Â (new 05AB1E version only)
.ι (new 05AB1E version only)
ºS (new 05AB1E version only)
·S or xS (legacy 05AB1E version only)
+S (legacy 05AB1E version only)
```
Ok, I give up. I'm unable to find a 1-byter to solve this. Loads of 2-byters, though..
[Try `ø˜` online](https://tio.run/##yy9OTMpM/f//8I7Tc/7/j1ZyUdJRygfiUiBOAuIcIE4FYgUgLgbiAig/EYizgVhRKRYA) or [Try `øS` online](https://tio.run/##yy9OTMpM/f//8I7g//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA).
[Try `ζ˜` online](https://tio.run/##yy9OTMpM/f//3LbTc/7/j1ZyUdJRygfiUiBOAuIcIE4FYgUgLgbiAig/EYizgVhRKRYA) or [Try `ζS` online](https://tio.run/##yy9OTMpM/f//3Lbg//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA).
[Try `€D` online](https://tio.run/##yy9OTMpM/f//UdMal///o5VclHSU8oG4FIiTgDgHiFOBWAGIi4G4AMpPBOJsIFZUigUA) or
[Try `€Â` online](https://tio.run/##yy9OTMpM/f//UdOaw03//0cruSjpKOUDcSkQJwFxDhCnArECEBcDcQGUnwjE2UCsqBQLAA).
[Try `.ι` online.](https://tio.run/##yy9OTMpM/f9f79zO//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA)
[Try `ºS` online.](https://tio.run/##yy9OTMpM/f//0K7g//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA)
[Try `·S` online](https://tio.run/##MzBNTDJM/f//0Pbg//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA) or [Try `xS` online](https://tio.run/##MzBNTDJM/f@/Ivj//2glFyUdpXwgLgXiJCDOAeJUIFYA4mIgLoDyE4E4G4gVlWIB).
[Try `+S` online.](https://tio.run/##MzBNTDJM/f9fO/j//2glFyUdpXwgLgXiJCDOAeJUIFYA4mIgLoDyE4E4G4gVlWIB)
I/O as a list of characters.
**Explanation:**
```
ø # Zip/transpose the (implicit) input-list with itself
# i.e. ["a","b","c"] → [["a","a"],["b","b"],["c","c"]]
˜ # Deep flatten it
# OR
S # Convert it to a flattened list of characters
# (which will be output implicitly as result)
```
The only program which works the same in both versions of 05AB1E. :)
```
ζ # Zip/transpose the (implicit) input-list with the (implicit) input-list
# i.e. ["a","b","c"] → [["a","a"],["b","b"],["c","c"]]
˜ # Deep flatten it
# OR
S # Convert it to a flattened list of characters
# (which will be output implicitly as result)
```
This version basically works the same as the one above for the new version. In the old version you would need an explicit pair `‚` first, and then you could zip/transpose that. Just `ζ` on a 1D list will be a no-op in the legacy version of 05AB1E.
```
€ # For each character in the (implicit) input-list,
# keeping all values on the stack into the resulting list:
D # Duplicate it
# OR
 # Bifurcate it (short for duplicate & reverse copy)
# (which will be output implicitly as result)
```
In the new version of 05AB1E, it keeps all values on the stack into the resulting list when doing a map. Whereas with the legacy version of 05AB1E it would only keep the top value. Which is why these only work in the new version.
```
.ι # Interleave the (implicit) input-list with the (implicit) input-list
# (which will be output implicitly as result)
```
This builtin wasn't there yet in the legacy version of 05AB1E.
```
º # Mirror each value in the (implicit) input-list
# i.e. ["a","b","c"] → ["aa","bb","cc"]
S # Convert it to a flattened list of characters
# (which will be output implicitly as result)
```
In the legacy version of 05AB1E, the horizontal mirror builtin would be `∞` instead of `º`. However, `∞S` doesn't work in the legacy version, because it would implicitly convert the list to a newline-delimited string before mirroring it completely ([Try it here](https://tio.run/##MzBNTDJM/f//Uce8//@jlVyUdJTygbgUiJOAOAeIU4FYAYiLgbgAyk8E4mwgVlSKBQA)), after which the `S` would also include these newlines.
```
· # Double each character
# OR
x # Double each character (without popping)
# i.e. ["a","b","c"] → ["aa","bb","cc"]
S # Convert it to a flattened list of characters
# (which will be output implicitly as result)
```
Double is short for `2*`. In the new version of 05AB1E, build in Elixir, this only works on numeric values. The legacy version of 05AB1E was built in Python however, so `2*` works similar and repeats the character.
```
+ # Append all characters in the (implicit) input-list at the same indices
# with the characters of the (implicit) input-list
# i.e. ["a","b","c"] → ["aa","bb","cc"]
S # Convert it to a flattened list of characters
# (which will be output implicitly as result)
```
Again, because the legacy version of 05AB1E was built in Python, `"a"+"a"` results in `"aa"`, whereas the `+` cannot be used to append strings in the new version. (PS: There is an append for strings which works in both version, which is `«`, but when giving two list arguments it will concatenate them together instead of merging each string at the same indices like the program above ([Try it here](https://tio.run/##yy9OTMpM/f//0Or//6OVXJR0lPKBuBSIk4A4B4hTgVgBiIuBuADKTwTibCBWVIoFAA)).)
[Answer]
## Python, ~~34~~ 25 bytes
```
lambda i:sum(zip(i,i),())
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSHTqrg0V6Mqs0AjUydTU0dDU/P/fwA)
Another one that returns a string instead of a list of characters:
```
for i in input():print(i,end=i)
```
```
for i in input(): asking for the input, and doing a
for loop for every char in the string.
print(i,end=i) print the character, and then close
the line with the same character.
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITMPiApKSzQ0rQqKMvNKNDJ1UvNSbDM1///3SM3JyVcEAA)
[Answer]
# x86-16 machine code, IBM PC DOS, ~~16~~ ~~10~~ 8 bytes
**Assembled byte `xxd` dump**
```
00000000: b401 cd21 cd29 ebf8 ...!....
```
**Unassembled listing:**
```
B4 01 MOV AH, 01H ; DOS read char from STDIN (AH=01)
CD 21 INT 21H ; read char into AL (echoes input)
CD 29 INT 29H ; write char in AL to console again
EB F8 JMP -8 ; continue looping until break
```
Standalone PC DOS executable. Input from `STDIN`, output to console.
Interactive console input:
[![enter image description here](https://i.stack.imgur.com/qX2mT.png)](https://i.stack.imgur.com/qX2mT.png)
Input by pipe:
[![enter image description here](https://i.stack.imgur.com/CpIIQ.png)](https://i.stack.imgur.com/CpIIQ.png)
### Original **16 byte** answer:
**Assembled byte `xxd` dump**
```
00000000: d1ee ad8a c849 acb4 0ecd 10cd 10e2 f7c3 .....I..........
```
**Unassembled listing:**
```
D1 EE SHR SI, 1 ; point SI to DOS PSP (080H)
AD LODSW ; load input length into AL
48 DEC AX ; remove leading space from length counter
8A C8 MOV CL, AL ; move length to loop counter
C_LOOP:
AC LODSB ; load next char into AL
B4 0E MOV AH, 0EH ; PC BIOS tty output function
CD 10 INT 10H ; write char to console
CD 10 INT 10H ; write char to console again
E2 F7 LOOP C_LOOP ; continue looping through chars
C3 RET ; exit to DOS
```
Standalone PC DOS executable. Input via command line, output to console.
[![enter image description here](https://i.stack.imgur.com/ikYgn.png)](https://i.stack.imgur.com/ikYgn.png)
[Answer]
## Jelly, 1 byte
```
ż
```
[Try it online!](https://tio.run/##y0rNyan8///onv///7vklyblpCoUF6QmZgMA)
Pardon my inexperience, I'm just getting started with Jelly. What I believe is happening is that we've defined a dyadic chain, which treats a single argument as both the left and right arguments. In this case, the chain consists of "zip; interleave x and y", interleaving the input string with itself.
Someone already posted a 1-byte Jelly solution, so I hope it's not bad manners to post mine.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḥ
```
A full program printing the result.
**[Try it online!](https://tio.run/##y0rNyan8///hjiX///9X9yhNSspJVUiCUCX5mTkKiXkpCiVF@aVAAXUA "Jelly – Try It Online")**
### How?
Uses a ~~bug~~ feature...
Jelly's "double" atom, `Ḥ` is implemented with Python's `*` and it vectorises, while Jelly's lists of characters (its only "strings") are implemented as lists of Python strings which are usually just one character long - that is until we realise that in Python `'blah'*2='blahblah'`...
```
Ḥ - Main link: list of characters (as parsed from an argument as a Python string)
- e.g. ['A','b','b','a']
Ḥ - double (vectorises) ['AA','bb','bb','aa']
- implicit, smashing print AAbbbbaa
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~10~~ 8 bytes
```
s/./&&/g
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1hfT19NTT/9/3@X/NKknNTigtTEbAA "sed – Try It Online")
Thanks to @manatwork for -2 bytes.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 22 bytes
Takes input as an array of characters.
```
s=>s.flatMap(c=>[c,c])
```
[Try it online!](https://tio.run/##BcExDoAgDADAr@gEJNofwOTqC4xDrWBQQolVv1/vTvxQ6M7tGSvvUZNX8UEgFXxmbJZ8WGig1SlxFS4RCh822QUAzMTvVmInLeLVm9XByblaY5zTHw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 26 bytes
Takes input as a string.
```
s=>s.replace(/./gs,c=>c+c)
```
[Try it online!](https://tio.run/##BcHBDYAgDADAWXwBUWECeDmGn1oLURtKrLo@3p3wgeJ9tGeuslPPsWtM6m9qDEg2@FB0wphwRNdRqgqTZyk2W7PIuzGtVRvBNRjn@g8 "JavaScript (Node.js) – Try It Online")
Alternate version suggested by @PabloLozano:
```
s=>s.replace(/./gs,'$&$&')
```
[Try it online!](https://tio.run/##BcHBDYAgDADAWUyIQKIwAb4cw0/FQlRCCVXXr3cXfMCxn@2ZKx0oKQiHhV3HViCi8c5nnrQa1aitRKpMBV2hbJLRK717wa1yQ7gHba38 "JavaScript (Node.js) – Try It Online")
Doing it the recursive way is also just as long:
```
f=([c,...s])=>c?c+c+f(s):s
```
[Try it online!](https://tio.run/##BcFRDkAwDADQq/Cly9gBJOPHLcTHVCdY1kVx/XrvDF8QvI/ydJk3Uo0eZmydc7IYP@CIFm0EMb0ochZO5BLvEKGZ@F0TVVIoXHVjjP4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~29~~ ~~23~~ 21 bytes
-6 bytes thanks to Andrei Odegov
-2 bytes thanks to mazzy
```
-join($args|%{$_+$_})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V83Kz8zT0MlsSi9uEa1WiVeWyW@VvN/LReXSrGtkkt@aVJOanFBamK2EpeaSpqCQzGXujpYygNoQr5CeX5RTgpM6j8A "PowerShell – Try It Online")
Takes input via splatting, essentially making it an array of chars
[Answer]
# [Haskell](https://www.haskell.org/), 8 bytes
```
(<*"x2")
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8NGS6nCSEnzf25iZp6CrUJBUWZeiYKKQpqCkkt@aVJOqkJxQWpitqLS/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
Any two-character string works in place of `"x2"`.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 2 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function.
```
2⌿
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsZ/o0c9@/9rcj3qmwrkpimou@SXJuWkKhQXpCZmK6r/BwA "APL (dzaima/APL) – Try It Online")
`⌿` is "replicate" :-)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 40 bytes
```
f(s,t)char*s,*t;{while(*t++=*t++=*s++);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9No1inRDM5I7FIq1hHq8S6ujwjMydVQ6tEW9sWQhRra2ta1/7PzCtRyE3MzNPQVKjm4gRpUCiJNjWItebiTNNQcskvTcpJVSguSE3MVgIaCBQtKAJqAUqpFivpKIBEav8DAA "C (gcc) – Try It Online")
Assumes `t` is a buffer which is large enough to store the output.
Probably not standard-conforming, but it works on TIO.
[Answer]
# [Rust](https://www.rust-lang.org/), ~~83~~ ~~46~~ 45 bytes
```
|x:&str|for c in x.chars(){print!("{}{0}",c)}
```
[Try it online!](https://tio.run/##DcpBCoAgEADAr2weQqGic1GnPmKiJJXKrkJgvt26DoOJYjUObmkdF/3KRb50BLPU95laivgaj6DAOngGdUikfwS0Ljac5ZLHwjolSp0NZ5tP@6WBgpZnw378AA "Rust – Try It Online")
I don't like this, but [it's not cheating](https://codegolf.meta.stackexchange.com/a/2457/43394).
* -1 byte thanks to [Maya](https://codegolf.stackexchange.com/users/55934/maya).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
jᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@vh1gn//yu55Jcm5aQqBBekJmYr/Y8CAA "Brachylog – Try It Online")
### Explanation
```
ᵐ Map on each char
j Juxtapose the char to itself
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes
```
.i
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/z/3@lxKRkJQA "Pyth – Try It Online")
`.i`nterleaves two copies of the input together. The input is implicit, so a 'full' version of this program would be `.iQQ`, where `Q` is the program's input.
[Answer]
# Perl 5 (`-0777p` `-Mre=/s`), 10 bytes
```
s/./$&$&/g
```
[TIO](https://tio.run/##K0gtyjH9/79YX09fRU1FTT/9/3@X/NKknFSF4oLUxGwuo7wUhZzMvNR/@QUlmfl5xf91DczNzQv@6/oWpdrqFwMA)
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 6 bytes
```
#@~:,,
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9Xdqiz0tH5/98lvzQpJ1WhuCA1MVsRAA "Befunge-98 (PyFunge) – Try It Online")
[Answer]
# Java 8, 27 bytes
```
s->s.replaceAll(".","$0$0")
```
[Try it online.](https://tio.run/##jY9PDwExEMXvPsWYSHSDxpmQSFwccHAUh6qSUt1mZ1Yi4rOvonHxJy6TzvT33pvZq5Pq7DeHSjtFBFNl/aUGYD2bYqu0gdm9BVhwYf0OtEgPyvpxfq3FQqzYapiBhwFU1BmSLExwUTxyTqDENja6jS5mVf@Oh3LtIp5Up9xu4BhTk/FyBSp7RrIhFjjOI2@AglGHOr6lPvQP8rVYWvhMbI4yL1mG@MHOC5z4UHIPni4fkSY2W9SK9TuC85L/sfFSC8p@e6VzrtUN)
**Old 31 bytes answer before the rules got changed:**
```
s->s.replaceAll("(?s).","$0$0")
```
NOTE: The suggestion of *@EmbodimentOfIgnorance* (`\n|.` instead of `(?s).` has been reverted, since it fails if the input contains `\r`. Thanks for reporting to *@OlivierGrégoire*.
[Try it online.](https://tio.run/##jU87TwMxDN77K0xUqYlKT52pAFViYaAMjIQh5EJJL/WdbF8rhPrbj/S4svAQixPb38Pfxu3cbFNWnU@OGe5cxPcRQEQJ9OJ8gNWxBXgQirgGr4cPm0WeH0a5sDiJHlaAcAkdz664oNCkTF6mpJW@ZlOoczWej@fKdIsjpWmfU6YMzF0dS9hm50H88Qmc@bSVwKLVTZ3xAbgJrjpTvfNpZdHiMnFtcV9TxfmJ8moRwz5FDGzJYWnJO6Lo1sESBWkJ89yS@hahP6TX/Uo5pH9jCduibqVo8kISanWLTSsXcDrnB8hETaY8zfV3iLpv5T8yWHjN5m@tIc6h@wA)
**Explanation:**
```
s-> // Method with String as both parameter and return-type
s.replaceAll("(?s).","$0$0") // Regex-replace all matches with the replacement
// And return the changed String as result
```
*Regex explanation:*
```
(?s). // Match:
(?s) // Enable DOTALL mode so newlines and carriage returns
// are treated as literal
. // A single character
$0$0 // Replacement:
$0 // All character(s) found in the match
$0 // And again all character(s) found in the match
```
[Answer]
# [Haskell](https://www.haskell.org/), 15 bytes
Here `(:)<*>pure` takes an argument and returns a list containing this argument twice. Then `>>=` maps this function over every entry of a the input list (which is a string in our case) and flattens the result (a list of lists) back to a list.
```
(>>=(:)<*>pure)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8POzlbDStNGy66gtChV839uYmaegq1CQVFmXomCikKagpJLfmlSTqpCcUFqYrai0v9/yWk5ienF/3UjnAMCAA "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~6~~ 3 bytes
-3 bytes thanks to Richard Donovan
```
2#]
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9IOfa/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCukt@aVJOqkJxQWpitqI6138A "J – Try It Online")
# [K (oK)](https://github.com/JohnEarnest/ok), ~~8~~ 4 bytes
-4 bytes thanks to ngn!
```
{2}#
```
[Try it online!](https://tio.run/##y9bNz/7/P82q2qhW@X@agpJHak5OvkJ5flFOiqLSfwA "K (oK) – Try It Online")
[Answer]
# [dotcomma](https://github.com/Radvylf/dotcomma), ~~15~~ 14 bytes
```
[[],][.[[,],]] code
[[],] push 0 to the queue
[. ] while next block is non-zero
[[,],] pop from the queue and push it twice
```
[Answer]
# [makina](https://github.com/GingerIndustries/makina), 96 bytes
```
v L>C
v>n0; >n0;
>wv ^
>Ov ^
^i>?g
^IvOC
^ nv
;1<>ppuv
^<<<OOO<
^ >vv
;0nCUv>n1;
T<<
;1nC
```
It's hard to explain makina code, but basically this goes through each letter of the input and prints it twice.
[Answer]
# JavaScript, 39 bytes
```
alert([...prompt()].map(a=>a+a).join``)
```
May not be the shortest but at least original.
## EDIT
Removed 2 bytes thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)
[Answer]
# [MarioLANG](https://github.com/tomsmeding/MarioLANG), 23 20 17 bytes
```
>,
"+
.[
.<
!-
#=
```
[Try it online!](https://tio.run/##y00syszPScxL///fTodLSZtLL5pLz4ZLUZdL2fb/f5f80qScVIXigtTEbEUA "MarioLANG – Try It Online")
Unlike brainfuck, MarioLANG returns -1 on EOF, so we must increment the value read before comparing it to zero, and then decrement before printing it. This is probably the shortest answer possible in MarioLANG.
] |
[Question]
[
Your job is to animate this [circle illusion](http://www.youtube.com/watch?v=pNe6fsaCVtI). It looks like the points rotating inside of the circle, but they are actually just moving in straight lines.
![enter image description here](https://i.stack.imgur.com/rsGXn.gif)
# Criterias
* The result has to be animated. The way you do the animation is irrelevant, it can generate a `.gif`, it can draw to a window, some device screen or whatever.
* This is a popularity contest, so you might want to add some additional features to your program to get more upvotes, for example varying the number of points.
* The winner is the most upvoted **valid** answer 7 days after the last valid submission.
* **The answers that will actually implement points moving on straight lines and not another way around are more welcomed**
[Answer]
# Python 3.4
Using the turtle module. The turtles are different colours and they always face in the same direction, so they can be easily seen to be moving along straight lines by just focusing on one of them. Despite this the circle illusion is still strong.
![11 turtles](https://i.stack.imgur.com/HQ1P6.gif "11 turtles")
The illusion still seems quite strong even with just 3 or 4 turtles:
![3 turtles](https://i.stack.imgur.com/h19Uc.gif "3 turtles")![4 turtles](https://i.stack.imgur.com/aVgnC.gif "4 turtles")
The framerate is reduced considerably for all of these GIF examples, but it doesn't seem to detract from the illusion. Running the code locally gives a smoother animation.
```
import turtle
import time
from math import sin, pi
from random import random
def circle_dance(population=11, resolution=480, loops=1, flip=0, lines=0):
population = int(population)
resolution = int(resolution)
radius = 250
screen = turtle.Screen()
screen.tracer(0)
if lines:
arrange_lines(population, radius)
turtles = [turtle.Turtle() for i in range(population)]
for i in range(population):
dancer = turtles[i]
make_dancer(dancer, i, population)
animate(turtles, resolution, screen, loops, flip, radius)
def arrange_lines(population, radius):
artist = turtle.Turtle()
for n in range(population):
artist.penup()
artist.setposition(0, 0)
artist.setheading(n / population * 180)
artist.forward(-radius)
artist.pendown()
artist.forward(radius * 2)
artist.hideturtle()
def make_dancer(dancer, i, population):
dancer.setheading(i / population * 180)
dancer.color(random_turtle_colour())
dancer.penup()
dancer.shape('turtle')
dancer.turtlesize(2)
def random_turtle_colour():
return random() * 0.9, 0.5 + random() * 0.5, random() * 0.7
def animate(turtles, resolution, screen, loops, flip, radius):
delay = 4 / resolution # 4 seconds per repetition
while True:
for step in range(resolution):
timer = time.perf_counter()
phase = step / resolution * 2 * pi
draw_dancers(turtles, phase, screen, loops, flip, radius)
elapsed = time.perf_counter() - timer
adjusted_delay = max(0, delay - elapsed)
time.sleep(adjusted_delay)
def draw_dancers(turtles, phase, screen, loops, flip, radius):
population = len(turtles)
for i in range(population):
individual_phase = (phase + i / population * loops * pi) % (2*pi)
dancer = turtles[i]
if flip:
if pi / 2 < individual_phase <= 3 * pi / 2:
dancer.settiltangle(180)
else:
dancer.settiltangle(0)
distance = radius * sin(individual_phase)
dancer.setposition(0, 0)
dancer.forward(distance)
screen.update()
if __name__ == '__main__':
import sys
circle_dance(*(float(n) for n in sys.argv[1:]))
```
### For contrast here are some that really do rotate:
![23 loop turtles](https://i.stack.imgur.com/xBDT7.gif "23 turtles")![23 trefoil turtles](https://i.stack.imgur.com/Iqqak.gif "23 turtles")
### ...or do they?
The code can be run with 5 optional arguments: population, resolution, loops, flip and lines.
* `population` is the number of turtles
* `resolution` is the time resolution (number of animation frames per repetition)
* `loops` determines how many times the turtles loop back on themselves. The default of 1 gives a standard circle, other odd numbers give that number of loops in the string of turtles, while even numbers give a string of turtles disconnected at the ends, but still with the illusion of curved motion.
* `flip` if non-zero causes the turtles to flip direction for their return trip (as suggested by [aslum](https://codegolf.stackexchange.com/users/17277/aslum "aslum's profile") so that they are never moving backwards). As default they keep a fixed direction to avoid the visual distraction at the endpoints.
* `lines` if non-zero displays the lines on which the turtles move, for consistency with the example image in the question.
Examples with `flip` set, with and without `lines`. I've left my main example above without flip as I prefer not to have the sporadic jump, but the edge of the circle does look smoother with all the turtles aligned, so the option is there for people to choose whichever style they prefer when running the code.
![11 turtles with flip and lines](https://i.stack.imgur.com/rz9CI.gif "with flip and lines")![11 turtles with flip](https://i.stack.imgur.com/t3gBn.gif "with flip")
It might not be immediately obvious how the images above were all produced from this same code. In particular the image further up which has a slow outer loop and a fast inner loop (the one that looks like a cardioid that someone accidentally dropped). I've hidden the explanation of this one below in case anyone wants to delay finding out while experimenting/thinking.
>
> The animation with an inner and outer loop of different sizes was created by setting the number of loops to 15 and leaving the number of turtles at 23 (too low to represent 15 loops). Using a large number of turtles would result in 15 clearly defined loops. Using too few turtles results in aliasing (for the same reason as in image processing and rendering). Trying to represent too high a frequency results in a lower frequency being displayed, with distortion.
>
>
>
Trying out different numbers I found some of these distortions more interesting than the more symmetrical originals, so I wanted to include one here...
[Answer]
# C
Result:
![enter image description here](https://i.stack.imgur.com/PagHz.gif)
```
#include <stdio.h>
#include <Windows.h>
#include <Math.h>
int round (double r) { return (r > 0.0) ? (r + 0.5) : (r - 0.5); }
void print (int x, int y, char c) {
COORD p = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), p);
printf("%c", c);
}
int main ()
{
float pi = 3.14159265358979323846;
float circle = pi * 2;
int len = 12;
int hlen = len / 2;
int cx = 13;
int cy = 8;
float w = 11.0;
float h = 8.0;
float step = 0.0;
while (1)
{
system("cls"); // xD
for (int i = 0; i < len; i++)
{
float a = (i / (float)len) * circle;
int x = cx + round(cos(a) * w);
int y = cy + round(sin(a) * h);
print(x, y, 'O');
if (i < hlen) continue;
step -= 0.05;
float range = cos(a + step);
x = cx + round(cos(a) * (w - 1) * range);
y = cy + round(sin(a) * (h - 1) * range);
print(x, y, 'O');
}
Sleep(100);
}
return 0;
}
```
[Answer]
# SVG (no Javascript)
[JSFiddle link here](http://jsfiddle.net/xh3Tj/)
```
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 380 380" width="380" height="380" version="1.0">
<g transform="translate(190 190)">
<circle cx="0" cy="0" r="190" fill="#000"/>
<line x1="0" y1="-190" x2="0" y2="190" stroke="#fff" stroke-width="1.5"/>
<line x1="72.71" y1="175.54" x2="-72.71" y2="-175.54" stroke="#fff" stroke-width="1.5"/>
<line x1="134.35" y1="134.35" x2="-134.35" y2="-134.35" stroke="#fff" stroke-width="1.5"/>
<line x1="175.54" y1="72.71" x2="-175.54" y2="-72.71" stroke="#fff" stroke-width="1.5"/>
<line x1="190" y1="0" x2="-190" y2="0" stroke="#fff" stroke-width="1.5"/>
<line x1="175.54" y1="-72.71" x2="-175.54" y2="72.71" stroke="#fff" stroke-width="1.5"/>
<line x1="134.35" y1="-134.35" x2="-134.35" y2="134.35" stroke="#fff" stroke-width="1.5"/>
<line x1="72.71" y1="-175.54" x2="-72.71" y2="175.54" stroke="#fff" stroke-width="1.5"/>
<g transform="rotate(0)">
<animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0" to="360" begin="0" dur="8s" repeatCount="indefinite"/>
<g transform="translate(0 90)">
<g transform="rotate(0)">
<animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0" to="-360" begin="0" dur="4s" repeatCount="indefinite"/>
<circle cx="0" cy="90" r="10" fill="#fff"/>
<circle cx="63.64" cy="63.64" r="10" fill="#fff"/>
<circle cx="90" cy="0" r="10" fill="#fff"/>
<circle cx="63.64" cy="-63.64" r="10" fill="#fff"/>
<circle cx="0" cy="-90" r="10" fill="#fff"/>
<circle cx="-63.64" cy="-63.64" r="10" fill="#fff"/>
<circle cx="-90" cy="0" r="10" fill="#fff"/>
<circle cx="-63.64" cy="63.64" r="10" fill="#fff"/>
</g>
</g>
</g>
</g>
</svg>
```
[Answer]
<http://jsfiddle.net/z6vhD/13/>
`intervaltime` changes the FPS (FPS = 1000/intervaltime).
`balls` changes the # balls.
`maxstep` adjusts the # steps in a cycle, the larger the 'smoother' it is. 64 should be large enough where it appears smooth.
Modeled as a circle moving, instead of moving the balls along the lines, but the visual effect (should be?) the same. Some of the code is pretty verbose, but this isn't code golf, so...
```
var intervalTime = 40;
var balls = 8;
var maxstep = 64;
var canvas = $('#c').get(0); // 100% necessary jquery
var ctx = canvas.getContext('2d');
var step = 0;
animateWorld = function() {
createBase();
step = step % maxstep;
var centerX = canvas.width/2 + 115 * Math.cos(step * 2 / maxstep * Math.PI);
var centerY = canvas.height/2 + 115 * Math.sin(step * 2 / maxstep * Math.PI);
for (var i=0; i<balls; i++) {
drawCircle(ctx, (centerX + 115 * Math.cos((i * 2 / balls - step * 2 / maxstep) * Math.PI)), (centerY + 115 * Math.sin((i * 2 / balls - step * 2 / maxstep) * Math.PI)), 10, '#FFFFFF');
}
step++;
}
function createBase() {
drawCircle(ctx, canvas.width/2, canvas.height/2, 240, '#000000');
for(var i=0; i<balls*2; i++) {
drawLine(ctx, canvas.width/2, canvas.height/2, canvas.width/2 + 240 * Math.cos(i / balls * Math.PI), canvas.height/2 + 240 * Math.sin(i / balls * Math.PI), '#FFFFFF');
}
}
function drawLine(context, x1, y1, x2, y2, c) {
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.lineWidth = 3;
context.strokeStyle = c;
context.stroke();
}
function drawCircle(context, x, y, r, c) {
context.beginPath();
context.arc(x, y, r, 0, 2*Math.PI);
context.fillStyle = c;
context.fill();
}
function drawRect(context, x, y, w, h, c) {
context.fillStyle = c;
context.fillRect(x, y, w, h);
}
$(document).ready(function() {
intervalID = window.setInterval(animateWorld, intervalTime);
});
```
[Answer]
### CSS animations
A solution using only css animations (see animation [on JSFiddle](http://jsfiddle.net/nBCxz/6/) - note that I added the browser specific prefixes in the fiddle so that it can work in most recent versions).
```
<body>
<div id="w1"></div>
<div id="w2"></div>
<div id="w3"></div>
<div id="w4"></div>
<div id="w5"></div>
<div id="w6"></div>
<div id="w7"></div>
<div id="w8"></div>
</body>
div {
position: absolute;
width: 20px;
height: 20px;
border-radius: 20px;
background: red;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
#w1 { animation-name: s1; animation-delay: 0.0s }
#w2 { animation-name: s2; animation-delay: 0.5s }
#w3 { animation-name: s3; animation-delay: 1.0s }
#w4 { animation-name: s4; animation-delay: 1.5s }
#w5 { animation-name: s5; animation-delay: 2.0s }
#w6 { animation-name: s6; animation-delay: 2.5s }
#w7 { animation-name: s7; animation-delay: 3.0s }
#w8 { animation-name: s8; animation-delay: 3.5s }
@keyframes s1 { from {top: 100px; left: 0px;} to {top: 100px; left: 200px;} }
@keyframes s2 { from {top: 62px; left: 8px;} to {top: 138px; left: 192px;} }
@keyframes s3 { from {top: 29px; left: 29px;} to {top: 171px; left: 171px;} }
@keyframes s4 { from {top: 8px; left: 62px;} to {top: 192px; left: 138px;} }
@keyframes s5 { from {top: 0px; left: 100px;} to {top: 200px; left: 100px;} }
@keyframes s6 { from {top: 8px; left: 138px;} to {top: 192px; left: 62px;} }
@keyframes s7 { from {top: 29px; left: 171px;} to {top: 171px; left: 29px;} }
@keyframes s8 { from {top: 62px; left: 192px;} to {top: 138px; left: 8px;} }
```
[Answer]
## Mathematica
Here is a pretty straight-forward submission.
```
animateCircle[n_] := Animate[Graphics[
Flatten@{
Disk[],
White,
Map[
(
phase = #*2 \[Pi]/n;
line = {Cos[phase], Sin[phase]};
{Line[{-line, line}],
Disk[Sin[t + phase]*line, 0.05]}
) &,
Range[n]
]
},
PlotRange -> {{-1.1, 1.1}, {-1.1, 1.1}}
],
{t, 0, 2 \[Pi]}
]
```
If you call `animateCircle[32]` you'll get a neat animation with 32 lines and circles.
![enter image description here](https://i.stack.imgur.com/jJnop.gif)
It's completely smooth in Mathematica, but I had to limit the number of frames for the GIF a bit.
Now what happens if you put two discs on each line? (That is, add `Disk[-Sin[t + phase]*line, 0.05]` to the list within the `Map`.)
![enter image description here](https://i.stack.imgur.com/Ak5oN.gif)
You can also put them 90° out of phase (use `Cos` instead of `-Sin`):
![enter image description here](https://i.stack.imgur.com/aKiHv.gif)
[Answer]
# Excel (no VBA)
[![Excel](https://i.stack.imgur.com/3vvJK.gif)](https://i.stack.imgur.com/3vvJK.gif)
```
=2*PI()*(NOW()*24*60*60/A2-FLOOR(NOW()*24*60*60/A2,1))
=ROUND(7*SIN(A1),0)
=ROUND(5*SIN(A1+1*PI()/4),0)
=ROUND(7*SIN(A1+2*PI()/4),0)
=ROUND(5*SIN(A1+3*PI()/4),0)
```
A2 (period) determines the time (seconds) for a full 'revolution'.
Each cell within the lines is a basic conditional relating to the value of the corresponding line. For example, K2 is:
```
=1*(A5=7)
```
And the center cell (K9) is:
```
=1*OR(A5=0,A6=0,A7=0,A8=0)
```
Forced the animation by holding 'delete' on a random cell to constantly trigger a refresh.
I know this is an old topic, but recent activity brought it to the top and it seemed appealing for some reason. Long time pcg listener, first time caller. Be gentle.
[Answer]
## VBScript + VBA + Excel Pie Chart
This will make your processor cry a little but it looks pretty and I believe it works according to spec. I used @Fabricio's answer as a guide to implement the circle movement algorithm.
EDIT: Made some adjustments to improve render speed.
![Screenshot of Pie chart](https://i.stack.imgur.com/f975V.png)
The code:
```
'Open Excel
Set objX = CreateObject("Excel.Application")
objX.Visible = True
objX.Workbooks.Add
'Populate values
objX.Cells(1, 1).Value = "Lbl"
objX.Cells(1, 2).Value = "Amt"
For fillX = 2 to 17
objX.Cells(fillX, 1).Value = "V"+Cstr(fillX-1)
objX.Cells(fillX, 2).Value = "1"
Next
'Create pie
objX.Range("A2:B17").Select
objX.ActiveSheet.Shapes.AddChart.Select
With objX.ActiveChart
.ChartType = 5 'pieChart
.SetSourceData objX.Range("$A$2:$B$17")
.SeriesCollection(1).Select
End with
'Format pie
With objX.Selection.Format
.Fill.ForeColor.RGB = 0 'black
.Fill.Solid
.Line.Weight = 2
.Line.Visible = 1
.Line.ForeColor.RGB = 16777215 'white
End With
'animation variables
pi = 3.14159265358979323846
circle = pi * 2 : l = 16.0
hlen = l / 2 : cx = 152.0
cy = 99.0 : w = 90.0
h = 90.0 : s = 0.0
Dim posArry(7,1)
'Animate
While 1
For i = 0 to hlen-1
a = (i / l) * circle
range = cos(a + s)
x = cx + cos(a) * w * range
y = cy + sin(a) * h * range
If whileInx = 1 Then
createOval x, y
ElseIf whileInx = 2 Then
objX.ActiveChart.Legend.Select
ElseIf whileInx > 2 Then
ovalName = "Oval "+ Cstr(i+1)
dx = x - posArry(i,0)
dy = y - posArry(i,1)
moveOval ovalName, dx, dy
End if
posArry(i,0) = x
posArry(i,1) = y
Next
s=s-0.05
wscript.Sleep 1000/60 '60fps
whileInx = 1 + whileInx
Wend
'create circles
sub createOval(posX, posY)
objX.ActiveChart.Shapes.AddShape(9, posX, posY, 10, 10).Select '9=oval
objX.Selection.ShapeRange.Line.Visible = 0
with objX.Selection.ShapeRange.Fill
.Visible = 1
.ForeColor.RGB = 16777215 'white
.solid
end with
end sub
'move circles
sub moveOval(ovalName, dx, dy)
with objX.ActiveChart.Shapes(ovalName)
.IncrementLeft dx
.IncrementTop dy
end with
end sub
```
[Answer]
Just for fun with PSTricks.
![enter image description here](https://i.stack.imgur.com/ulLwI.gif)
```
\documentclass[preview,border=12pt,multi]{standalone}
\usepackage{pstricks}
\psset{unit=.3}
% static point
% #1 : half of the number of points
% #2 : ith point
\def\x[#1,#2]{(3*cos(Pi/#1*#2))}
\def\y[#1,#2]{(3*sin(Pi/#1*#2))}
% oscillated point
% #1 : half of the number of points
% #2 : ith point
% #3 : time parameter
\def\X[#1,#2]#3{(\x[#1,#2]*cos(#3+Pi/#1*#2))}
\def\Y[#1,#2]#3{(\y[#1,#2]*cos(#3+Pi/#1*#2))}
% single frame
% #1 : half of the number of points
% #2 : time parameter
\def\Frame#1#2{%
\begin{pspicture}(-3,-3)(3,3)
\pstVerb{/I2P {AlgParser cvx exec} bind def}%
\pscircle*{\dimexpr3\psunit+2pt\relax}
\foreach \i in {1,...,#1}{\psline[linecolor=yellow](!\x[#1,\i] I2P \y[#1,\i] I2P)(!\x[#1,\i] I2P neg \y[#1,\i] I2P neg)}
\foreach \i in {1,...,#1}{\pscircle*[linecolor=white](!\X[#1,\i]{#2} I2P \Y[#1,\i]{#2} I2P){2pt}}
\end{pspicture}}
\begin{document}
\foreach \t in {0,...,24}
{
\preview
\Frame{1}{2*Pi*\t/25} \quad \Frame{2}{2*Pi*\t/25} \quad \Frame{3}{2*Pi*\t/25} \quad \Frame{5}{2*Pi*\t/25} \quad \Frame{10}{2*Pi*\t/25}
\endpreview
}
\end{document}
```
[Answer]
**Fortran**
Each frame is created as an individual gif file using the Fortran gif module at: <http://fortranwiki.org/fortran/show/writegif>
Then I cheat a little by using ImageMagick to merge the individual gifs into one animated gif.
![Fortran](https://i.stack.imgur.com/F01x8.gif)
UPDATE: Set new = .true. to get the following:
![enter image description here](https://i.stack.imgur.com/zx5XK.gif)
```
program circle_illusion
use, intrinsic :: iso_fortran_env, only: wp=>real64
use gif_util !gif writing module from http://fortranwiki.org/fortran/show/writegif
implicit none
logical,parameter :: new = .false.
integer,parameter :: n = 500 !550 !size of image (square)
real(wp),parameter :: rcircle = n/2 !250 !radius of the big circle
integer,parameter :: time_sep = 5 !deg
real(wp),parameter :: deg2rad = acos(-1.0_wp)/180.0_wp
integer,dimension(0:n,0:n):: pixel ! pixel values
integer,dimension(3,0:3) :: colormap ! RGB 0:255 for colors 0:ncol
real(wp),dimension(2) :: xy
integer,dimension(2) :: ixy
real(wp) :: r,t
integer :: i,j,k,row,col,m,n_cases,ang_sep
character(len=10) :: istr
integer,parameter :: black = 0
integer,parameter :: white = 1
integer,parameter :: red = 2
integer,parameter :: gray = 3
colormap(:,0) = [0,0,0] !black
colormap(:,1) = [255,255,255] !white
colormap(:,2) = [255,0,0] !red
colormap(:,3) = [200,200,200] !gray
if (new) then
ang_sep = 5
n_cases = 3
else
ang_sep = 20
n_cases = 0
end if
do k=0,355,time_sep
!clear entire image:
pixel = white
if (new) call draw_circle(n/2,n/2,black,n/2)
!draw polar grid:
do j=0,180-ang_sep,ang_sep
do i=-n/2, n/2
call spherical_to_cartesian(dble(i),dble(j)*deg2rad,xy)
call convert(xy,row,col)
if (new) then
pixel(row,col) = gray
else
pixel(row,col) = black
end if
end do
end do
!draw dots:
do m=0,n_cases
do j=0,360-ang_sep,ang_sep
r = sin(m*90.0_wp*deg2rad + (k + j)*deg2rad)*rcircle
t = dble(j)*deg2rad
call spherical_to_cartesian(r,t,xy)
call convert(xy,row,col)
if (new) then
!call draw_circle(row,col,black,10) !v2
!call draw_circle(row,col,m,5) !v2
call draw_circle(row,col,white,10) !v3
else
call draw_square(row,col,red) !v1
end if
end do
end do
!write the gif file for this frame:
write(istr,'(I5.3)') k
call writegif('gifs/test'//trim(adjustl(istr))//'.gif',pixel,colormap)
end do
!use imagemagick to make animated gif from all the frames:
! from: http://thanosk.net/content/create-animated-gif-linux
if (new) then
call system('convert -delay 5 gifs/test*.gif -loop 0 animated.gif')
else
call system('convert -delay 10 gifs/test*.gif -loop 0 animated.gif')
end if
!delete individual files:
call system('rm gifs/test*.gif')
contains
subroutine draw_square(r,c,icolor)
implicit none
integer,intent(in) :: r,c !row,col of center
integer,intent(in) :: icolor
integer,parameter :: d = 10 !square size
pixel(max(0,r-d):min(n,r+d),max(0,c-d):min(n,c+d)) = icolor
end subroutine draw_square
subroutine draw_circle(r,c,icolor,d)
implicit none
integer,intent(in) :: r,c !row,col of center
integer,intent(in) :: icolor
integer,intent(in) :: d !diameter
integer :: i,j
do i=max(0,r-d),min(n,r+d)
do j=max(0,c-d),min(n,c+d)
if (sqrt(dble(i-r)**2 + dble(j-c)**2)<=d) &
pixel(i,j) = icolor
end do
end do
end subroutine draw_circle
subroutine convert(xy,row,col)
implicit none
real(wp),dimension(2),intent(in) :: xy !coordinates
integer,intent(out) :: row,col
row = int(-xy(2) + n/2.0_wp)
col = int( xy(1) + n/2.0_wp)
end subroutine convert
subroutine spherical_to_cartesian(r,theta,xy)
implicit none
real(wp),intent(in) :: r,theta
real(wp),dimension(2),intent(out) :: xy
xy(1) = r * cos(theta)
xy(2) = r * sin(theta)
end subroutine spherical_to_cartesian
end program circle_illusion
```
[Answer]
Mandatory **C64** version.
Copy&paste in your favorite emulator:
![C64 version](https://i.stack.imgur.com/xfNbC.gif)
```
1 print chr$(147)
2 poke 53281,0
3 for p=0 to 7
5 x=int(11+(cos(p*0.78)*10)):y=int(12+(sin(p*0.78)*10))
6 poke 1024+x+(y*40),15
9 next p
10 for sp=2040 to 2047:poke sp,13:next sp
20 for i=0 to 62:read a:poke 832+i,a:next i
30 for i=0 to 7:poke 53287+i,i+1:next i
40 rem activate sprites
50 poke 53269,255
60 an=0.0
70 rem maincycle
75 teta=0.0:k=an
80 for i=0 to 7
90 px=cos(k)*64
92 s=i:x=px*cos(teta): y=px*sin(teta): x=x+100: y=y+137: gosub 210
94 teta=teta+0.392699
95 k=k+0.392699
96 next i
130 an=an+0.1
140 goto 70
150 end
200 rem setspritepos
210 poke 53248+s*2,int(x): poke 53249+s*2,int(y)
220 return
5000 data 0,254,0
5010 data 3,199,128
5020 data 7,0,64
5030 data 12,126,96
5040 data 25,255,48
5050 data 59,7,152
5060 data 52,1,200
5070 data 116,0,204
5080 data 120,0,100
5090 data 120,0,100
5100 data 120,0,100
5110 data 120,0,36
5120 data 104,0,36
5130 data 100,0,108
5140 data 54,0,72
5150 data 51,0,152
5160 data 25,131,16
5170 data 12,124,96
5180 data 4,0,64
5190 data 3,1,128
5200 data 0,254,0
```
[Answer]
A compact javascript version, changing the default settings to something different
<http://jsfiddle.net/yZ3DP/1/>
HTML:
```
<canvas id="c" width="400" height="400" />
```
JavaScript:
```
var v= document.getElementById('c');
var c= v.getContext('2d');
var w= v.width, w2= w/2;
var num= 28, M2= Math.PI*2, da= M2/num;
draw();
var bw= 10;
var time= 0;
function draw()
{
v.width= w;
c.beginPath();
c.fillStyle= 'black';
circle(w2,w2,w2);
c.lineWidth= 1.5;
c.strokeStyle= c.fillStyle= 'white';
var a= 0;
for (var i=0; i< num*2; i++){
c.moveTo(w2,w2);
c.lineTo(w2+Math.cos(a)*w2, w2+Math.sin(a)*w2);
a+= da/2;
}
c.stroke();
a= 0;
for (var i=0; i< num; i++){
circle(w2+Math.cos(a)*Math.sin(time+i*Math.PI/num)*(w2-bw),
w2+Math.sin(a)*Math.sin(time+i*Math.PI/num)*(w2-bw), bw);
a+= da/2;
}
time+=0.03;
requestAnimationFrame(draw);
}
function circle(x,y,r)
{
c.beginPath();
c.arc(x, y, r, 0, M2);
c.fill();
}
```
[Answer]
My take with **Elm**. I am a total beginner who will happily accept PRs to improve this solution ([GitHub](https://github.com/netzwerg/elm-playground/blob/master/Circle.elm)):
[![enter image description here](https://i.stack.imgur.com/O6y5F.gif)](https://i.stack.imgur.com/O6y5F.gif)
Note that this submission is really moving points on straight lines:
```
import Color exposing (..)
import Graphics.Collage exposing (..)
import Graphics.Element exposing (..)
import Time exposing (..)
import Window
import List exposing (..)
import AnimationFrame -- "jwmerrill/elm-animation-frame"
import Debug
-- CONFIG
size = 600
circleSize = 240
dotCount = 12
dotSize = 10
velocity = 0.01
-- MODEL
type alias Dot =
{ x : Float
, angle : Float
}
type alias State = List Dot
createDots : State
createDots = map createDot [ 0 .. dotCount - 1 ]
createDot : Int -> Dot
createDot index =
let angle = toFloat index * pi / dotCount
in { x = 0
, angle = angle
}
-- UPDATE
update : Time -> State -> State
update time dots = map (moveDot time) dots |> Debug.watch "Dots"
moveDot : Time -> Dot -> Dot
moveDot time dot =
let t = velocity * time / pi
newX = (-circleSize + dotSize) * cos(t + dot.angle)
in { dot | x <- newX }
-- VIEW
view : State -> Element
view dots =
let background = filled black (circle circleSize)
dotLinePairs = map viewDotWithLine dots
in collage size size (background :: dotLinePairs)
viewDotWithLine : Dot -> Form
viewDotWithLine dot =
let dotView = viewDot dot
lineView = createLineView
in group [dotView , lineView] |> rotate dot.angle
viewDot : Dot -> Form
viewDot d = alpha 0.8 (filled lightOrange (circle dotSize)) |> move (d.x, 0)
createLineView : Form
createLineView = traced (solid white) (path [ (-size / 2.0, 0) , (size / 2.0, 0) ])
-- SIGNALS
main = Signal.map view (animate createDots)
animate : State -> Signal State
animate dots = Signal.foldp update dots time
time = Signal.foldp (+) 0 AnimationFrame.frame
```
[Answer]
Second Life LSL
![animation](https://i.gyazo.com/aec7ea1fbcc464d55f56be06a5e003a5.gif)
start of turtle alpha image (right click below to save image)
![turtle.png](https://i.stack.imgur.com/WpaV5.png)
end of turtle alpha image (right click above to save image)
building the object:
make a root prim cylinder size <1, 1, 0.01> slice 0.49, 0.51, color <0, 0, 0>
make the description of this cylinder "8,1,1,1" without the quotes (very important)
make a cylinder, name it "cyl", color <0.25, 0.25, 0.25> alpha 0.5
duplicate the cyl 48 times
make a box, name it "sphere", color <1, 1, 1> transparency 100 except for the top transparency 0
put your turtle texture on face 0 of the box, turtle should face +x
duplicate the box 48 times
select all the boxes and the cylinders, make sure to select the root cylinder last, link (control L)
put these 2 scripts in the root:
```
//script named "dialog"
default
{
state_entry()
{
}
link_message(integer link, integer num, string msg, key id)
{
list msgs = llCSV2List(msg);
key agent = (key)llList2String(msgs, 0);
string prompt = llList2String(msgs, 1);
integer chan = (integer)llList2String(msgs, 2);
msgs = llDeleteSubList(msgs, 0, 2);
llDialog(agent, prompt, msgs, chan);
}
}
//script named "radial animation"
float interval = 0.1;
float originalsize = 1.0;
float rate = 5;
integer maxpoints = 48;
integer points = 23; //1 to 48
integer multiplier = 15;
integer lines;
string url = "https://codegolf.stackexchange.com/questions/34887/make-a-circle-illusion-animation/34891";
list cylinders;
list spheres;
float angle;
integer running;
integer chan;
integer lh;
desc(integer on)
{
if(on)
{
string desc =
(string)points + "," +
(string)multiplier + "," +
(string)running + "," +
(string)lines
;
llSetLinkPrimitiveParamsFast(1, [PRIM_DESC, desc]);
}
else
{
list params = llCSV2List(llList2String(llGetLinkPrimitiveParams(1, [PRIM_DESC]), 0));
points = (integer)llList2String(params, 0);
multiplier = (integer)llList2String(params, 1);
running = (integer)llList2String(params, 2);
lines = (integer)llList2String(params, 3);
}
}
init()
{
llSetLinkPrimitiveParamsFast(LINK_ALL_OTHERS, [PRIM_POS_LOCAL, ZERO_VECTOR,
PRIM_COLOR, ALL_SIDES, <1, 1, 1>, 0]);
integer num = llGetNumberOfPrims();
integer i;
for(i = 2; i <= num; i++)
{
string name = llGetLinkName(i);
if(name == "cyl")
cylinders += [i];
else if(name == "sphere")
spheres += [i];
}
vector size = llGetScale();
float scale = size.x/originalsize;
float r = size.x/4;
vector cylindersize = <0.01*scale, 0.01*scale, r*4>;
float arc = 180.0/points;
for(i = 0; i < points; i++)
{
float angle = i*arc;
rotation rot = llEuler2Rot(<0, 90, 0>*DEG_TO_RAD)*llEuler2Rot(<0, 0, angle>*DEG_TO_RAD);
integer cyl = llList2Integer(cylinders, i);
integer sphere = llList2Integer(spheres, i);
llSetLinkPrimitiveParamsFast(1, [PRIM_LINK_TARGET, cyl, PRIM_POS_LOCAL, ZERO_VECTOR, PRIM_ROT_LOCAL, rot, PRIM_SIZE, cylindersize, PRIM_COLOR, ALL_SIDES, <0.25, 0.25, 0.25>, 0.5*lines,
PRIM_LINK_TARGET, sphere, PRIM_COLOR, ALL_SIDES, <0.25 + llFrand(0.75), 0.25 + llFrand(0.75), 0.25 + llFrand(0.75)>, 1
]);
}
}
run()
{
vector size = llGetScale();
float scale = size.x/originalsize;
float r = size.x/2;
vector spheresize = <0.06, 0.06, 0.02>*scale;
float arc = 180.0/points;
list params;
integer i;
for(i = 0; i < points; i++)
{
float x = r*llCos((angle + i*arc*multiplier)*DEG_TO_RAD);
vector pos = <x, 0, 0>*llEuler2Rot(<0, 0, i*arc>*DEG_TO_RAD);
rotation rot = llEuler2Rot(<0, 0, i*arc>*DEG_TO_RAD);
integer link = llList2Integer(spheres, i);
params += [PRIM_LINK_TARGET, link, PRIM_POS_LOCAL, pos,
PRIM_ROT_LOCAL, rot,
PRIM_SIZE, spheresize
//PRIM_COLOR, ALL_SIDES, <1, 1, 1>, 1
];
}
llSetLinkPrimitiveParamsFast(1, params);
}
dialog(key id)
{
string runningstring;
if(running)
runningstring = "notrunning";
else
runningstring = "running";
string linesstring;
if(lines)
linesstring = "nolines";
else
linesstring = "lines";
string prompt = "\npoints: " + (string)points + "\nmultiplier: " + (string)multiplier;
string buttons = runningstring + ",points+,points-,reset,multiplier+,multiplier-," + linesstring + ",www";
llMessageLinked(1, 0, (string)id + "," + prompt + "," + (string)chan + "," + buttons, "");
//llDialog(id, prompt, llCSV2List(buttons), chan);
}
default
{
state_entry()
{
chan = (integer)("0x" + llGetSubString((string)llGetKey(), -8, -1));
lh = llListen(chan, "", "", "");
desc(FALSE);
init();
run();
llSetTimerEvent(interval);
}
on_rez(integer param)
{
llListenRemove(lh);
chan = (integer)("0x" + llGetSubString((string)llGetKey(), -8, -1));
lh = llListen(chan, "", "", "");
}
touch_start(integer total_number)
{
key id = llDetectedKey(0);
dialog(id);
}
timer()
{
if(!running)
return;
angle += rate;
if(angle > 360)
angle -= 360;
else if(angle < 0)
angle += 360;
run();
}
listen(integer channel, string name, key id, string msg)
{
if(msg == "points+")
{
if(points < maxpoints)
{
points++;
desc(TRUE);
llResetScript();
}
}
else if(msg == "points-")
{
if(points > 0)
{
points--;
desc(TRUE);
llResetScript();
}
}
else if(msg == "multiplier+")
{
multiplier++;
desc(TRUE);
}
else if(msg == "multiplier-")
{
multiplier--;
desc(TRUE);
}
else if(msg == "running")
{
running = TRUE;
desc(TRUE);
}
else if(msg == "notrunning")
{
running = FALSE;
desc(TRUE);
}
else if(msg == "lines")
{
lines = TRUE;
desc(TRUE);
llResetScript();
}
else if(msg == "nolines")
{
lines = FALSE;
desc(TRUE);
llResetScript();
}
else if(msg == "reset")
llResetScript();
else if(msg == "www")
llRegionSayTo(id, 0, url);
dialog(id);
}
}
```
[Answer]
# PICO-8, 271 chars
```
camera(-64,-64)p=8::_::s=p.." lines"cls(7)circfill(0,0,50,0)for l=0,.5,.5/p do
u=flr(50*cos(l))v=flr(50*sin(l))line(u,-v,-u,v,5)end
?s,-#s*2,-60
for l=0,.5,.5/p do
u=flr(48*cos(l))v=flr(48*sin(l))q=cos(l-t()/4)circfill(u*q,-v*q,2,7)end
flip()p+=flr(btnp()/16+1)%3-1goto _
```
The code for this is so short, I could post it as a tweet. In fact, [I just did](https://twitter.com/WinslowJosiah/status/1196771078166732803).
[![A gif capture from PICO-8.](https://i.stack.imgur.com/h79P6.gif)](https://i.stack.imgur.com/h79P6.gif)
You can also change the number of lines with the X and Z keys. (Oddly enough, due to a side effect of how division by 0 is handled in PICO-8, 0 lines acts exactly like 1 line. Negative numbers of lines don't show up.)
Ungolfed source:
```
lines=8
while true do
cls(7)
-- draw circle
circfill(64,64,50,0)
-- draw lines
for l=0,.5,.5/lines do
u=flr(50*cos(l))
v=flr(50*sin(l))
line(64+u,64-v,64-u,64+v,5)
end
-- center string
s=lines.." lines"
print(s,64-#s*2,4)
-- draw points
for l=0,.5,.5/lines do
u=flr(48*cos(l))
v=flr(48*sin(l))
-- one full turn every 4 secs
q=cos(l-t()/4)
circfill(64+u*q,64-v*q,2,7)
end
flip()
-- -1 if only ‚ùé is pressed
-- +1 if only üÖæÔ∏è is pressed
-- 0 otherwise
lines+=flr(btnp()/16+1)%3-1
end
```
] |
[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/172480/edit).
Closed 5 years ago.
[Improve this question](/posts/172480/edit)
I'm sure most of us have heard of [zip bombs](https://en.wikipedia.org/wiki/Zip_bomb) and similar decompression bomb tricks, where a maliciously crafted input creates a massively disproportionate output. We even had [a question on here](https://codegolf.stackexchange.com/questions/69189/build-a-compiler-bomb) to do that to a compiler at one point.
Well, it occurs to me that Markdown is a compression format of sorts, replacing bulky HTML tags with "compressed" MD tokens. Therefore, might it be possible to build a compression bomb in Markdown?
# Challenge rules:
* The submission should be a piece of markdown text, between 50 and 256 characters in length. (Imposing a minimum to head off some smart-aleck posting a 3-character response or similar.)
* The submission will be processed by StackExchange's Markdown processor as implemented in this site.
* Your score will be the ratio of character count in the resulting HTML to the character count of your Markdown text.
* Highest score wins.
[Answer]
# Blockquotes, 137,469/256 = 536.99
*6,908 characters, 511 new lines, 130,050 spaces*
Markdown sure handles nested block-quotes oddly. Each `>` character gets turned into `<blockquote></blockquote>` so a solid 1 to 25 ratio. But wait! When rendering the HTML it also adds two spaces per nesting! Having this try to render causes my browser some grief, and I will keep it in the code-cage for now. Feel free to unlock it yourself!
The code input consists of 255 `>` followed by ~~`&` as the last character doesn't transform, but it does get escaped. *Thanks BWO*~~ `!` as the last character which gives the last blockquote the spoiler class with an empty p tag inside. *Thanks bta, 11 extra characters*
Input:
`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>!`
Output HTML:
```
...
<blockquote>
<blockquote class="spoiler">
<p></p>
</blockquote>
</blockquote>
...
```
Here is what it looks like in the editor view!
[![crazy nested block quotes, makes a big triangle pointing right!](https://i.stack.imgur.com/n9IRz.png)](https://i.stack.imgur.com/n9IRz.png)
Plotting the results as the number of `>` increase as suggested by LambdaBeta:
[![enter image description here](https://i.stack.imgur.com/wH3dH.png)](https://i.stack.imgur.com/wH3dH.png)
[Answer]
# MathJax, 529\$\,\$252\$\,\$640ish / 256 ≈ 2\$\,\$067\$\,\$393
A good old thousand-laughs-style code
`$$\def\a{ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£ü§£}\def\b{\a\a\a\a\a\a\a\a\a\a\a\a\a}\def\c{\b\b\b\b\b\b\b\b\b\b\b}\def\d{\c\c\c\c\c\c\c\c}\d\d\d\d\d\d\d\d$$`
multiplies the gross inefficiency of representing exotic characters in MathJax by a considerable factor.
The StackExchange MathJax configuration limitation of 10\$\,\$000 macro expansions is being honored, while the limitations of the client’s browser, which are highly likely to cause problems expanding the macros, are not. (My browser is uncooperative as well, so the figure is an estimate.)
[Answer]
# Shorthand links: 68,960 / 256 = 269.375
ASCII only: 10,114 / 256 = 39.508
```
[][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1][][1]
[1]:ftp://^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Output is a sequence of elements that each look like:
```
<a href="ftp://%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E%5E" rel="nofollow noreferrer"></a>
```
After the fixed overhead for creating the URL reference, each 5-character link expands into `42+strlen(url)` characters output. Craft the URL to have the maximum number of characters that need escaping, and this grows to `47+3*strlen(url)` characters per link. A little experimentation showed that the optimal output involved 26 links, with 114 carets per link.
**Update**:
If you interpret the "256 character" limit to include Unicode characters, you can squeeze out more chaos. Replacing the carets with the Unicode bathtub character (üõÅ, codepoint U+1F6C1) results in `47+18*strlen(url)` output characters per input character for a total of 54,574 68,960 (thanks to jimmy23013's even-shorter link notation).
Unicode input:
```
[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1],[1]
[1]:ftp://üõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅüõÅ
```
Output is a series of:
```
<a href="ftp://%EF%BF%BD%EF%BF%BD...per character...%EF%BF%BD%EF%BF%BD" rel="nofollow noreferrer">1</a>,
```
[Answer]
# 15888/50 = 317.76: Abuse of MathJaX
This is the code:
```
$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$
```
This is what it looks like:
$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$$$&$$
The resulting HTML is:
```
<p><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-618-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3081" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3082"><span id="MathJax-Span-3083" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3084"><span class="mtext" id="MathJax-Span-3085" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-618">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-619-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3086" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3087"><span id="MathJax-Span-3088" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3089"><span class="mtext" id="MathJax-Span-3090" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-619">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-620-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3091" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3092"><span id="MathJax-Span-3093" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3094"><span class="mtext" id="MathJax-Span-3095" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-620">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-621-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3096" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3097"><span id="MathJax-Span-3098" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3099"><span class="mtext" id="MathJax-Span-3100" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-621">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-622-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3101" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3102"><span id="MathJax-Span-3103" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3104"><span class="mtext" id="MathJax-Span-3105" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-622">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-623-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3106" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3107"><span id="MathJax-Span-3108" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3109"><span class="mtext" id="MathJax-Span-3110" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-623">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-624-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3111" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3112"><span id="MathJax-Span-3113" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3114"><span class="mtext" id="MathJax-Span-3115" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-624">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-625-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3116" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3117"><span id="MathJax-Span-3118" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3119"><span class="mtext" id="MathJax-Span-3120" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-625">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-626-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3121" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3122"><span id="MathJax-Span-3123" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3124"><span class="mtext" id="MathJax-Span-3125" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-626">&</script><span class="MathJax_Preview" style="display: none;"></span><div class="MathJax_Display" style="text-align: center;"><span class="MathJax" id="MathJax-Element-627-Frame" tabindex="0" style="text-align: center; position: relative;" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &amp;</mtext></merror></math>" role="presentation"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-3126" style="width: 5.447em; display: inline-block;"><span style="display: inline-block; position: relative; width: 4.503em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(1.114em, 1004.5em, 2.614em, -999.997em); top: -2.164em; left: 0em;"><span class="mrow" id="MathJax-Span-3127"><span id="MathJax-Span-3128" style="display: inline-block;"><span class="merror" id="null"><span class="mrow" id="MathJax-Span-3129"><span class="mtext" id="MathJax-Span-3130" style=""><span style="font-size: 83%;">Misplaced &</span></span></span></span></span></span><span style="display: inline-block; width: 0px; height: 2.169em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.397em; border-left: 0px solid; width: 0px; height: 1.537em;"></span></span></nobr><span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><merror><mtext>Misplaced &</mtext></merror></math></span></span></div><script type="math/tex; mode=display" id="MathJax-Element-627">&</script></p>
```
Don't forget your MathJax folks.
Caveat: The MathJaX only shows the error during editing, so you have to view it in the editor. This is still a markdown implementation on this site, so should be valid. Once posted the `Misplaced &` warnings turn into normal &'s.
[Answer]
# Syntax highlighting, ~~6376~~ 6464/256 ≈ 25.25
+0.34375 thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel?tab=profile) (using a tab instead of 4 spaces)!
This uses the shortest (unfortunately spaces seem to matter) annotation to get syntax-highlighting `lang-c`, opens a code block and fills it with `&` and `0`:
```
<!-- language: lang-c -->
&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0
```
We start with `&` because it expands to `&` and use `0` next, alternating these constantly creates new `<span>` elements with a `class` attribute. Unfortunately we can't use only `&` or `&<&<...` since they stay in the same `pun`-`<div>`
It produces:
```
<pre class="lang-c prettyprint prettyprinted" style=""><code><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span><span class="pun">&</span><span class="lit">0</span></code></pre></div>
```
And rendered by your browser it results 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&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0
```
[Answer]
# 190/50 = 3.8: Italics
As it turns out, your 3-character worry is true. `*q*` generates `<em>q</em>` giving a ratio of 10/3. Two carriage returns give `<p>...</p>\n\n` (the two carriage returns aren't necessary, but do appear to be produced) and a resulting ratio of 9/2. Total ratio, 19/5.
```
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
```
Resulting html:
```
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
<p><em>q</em></p>
```
In action:
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
*q*
[Answer]
# 222/53 = <4.2: Nasty escapes in an image inclusion.
```
> ![&](https://&)
![&](https://&)
> ![&](https://&)
```
Results in:
>
> ![&](https://&)
>
>
>
![&](https://&)
>
> ![&](https://&)
>
>
>
Resulting HTML should be approximately:
```
<blockquote>
<p><img src="https://&" alt="&" title=""></p>
</blockquote>
<p><img src="https://&" alt="&" title=""></p>
<blockquote>
<p><img src="https://&" alt="&" title=""></p>
</blockquote>
```
This abuses image inclusion and having to escape things.
It used to be much better, but apparently SE's markdown is sufficiently non-standard to ruin it.
My previous submission (which wasn't how SE rendered it) was:
# ~~428/50 = 8.56: Nasty escapes in an image inclusion.~~
`![&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&](&)`
Resulting HTML should be approximately:
```
<p><img src="&" alt="&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;"></p>
```
This abuses the fact that most markdown editors will replace the ampersands in the alt text with doubly-escaped ampersands in order for it to show up correctly. Meanwhile a single ampersand is tossed into the src section so that the parser will actually see it as an image.
[Answer]
# MathJax: 13,579 / 52 = 261.13
```
\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$
```
Just creates a bunch of empty in-line MathJax:
\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$\$
HTML Code (can inspect on the empty space above):
```
<p><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1064-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2127" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2128"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1064"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1065-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2129" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2130"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1065"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1066-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2131" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2132"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1066"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1067-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2133" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2134"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1067"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1068-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2135" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2136"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1068"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1069-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2137" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2138"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1069"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1070-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2139" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2140"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1070"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1071-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2141" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2142"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1071"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1072-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2143" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2144"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1072"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1073-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2145" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2146"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1073"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1074-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2147" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2148"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1074"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1075-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2149" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2150"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1075"></script><span class="MathJax_Preview" style="display: none;"></span><span class="MathJax" id="MathJax-Element-1076-Frame" tabindex="0" data-mathml="<math xmlns="http://www.w3.org/1998/Math/MathML" />" role="presentation" style="position: relative;"><nobr aria-hidden="true"><span class="math" id="MathJax-Span-2151" style="width: 0em; display: inline-block;"><span style="display: inline-block; position: relative; width: 0em; height: 0px; font-size: 120%;"><span style="position: absolute; clip: rect(3.785em, 1000em, 4.17em, -999.997em); top: -3.971em; left: 0em;"><span class="mrow" id="MathJax-Span-2152"></span><span style="display: inline-block; width: 0px; height: 3.978em;"></span></span></span><span style="display: inline-block; overflow: hidden; vertical-align: -0.073em; border-left: 0px solid; width: 0px; height: 0.158em;"></span></span></nobr><span class="MJX_Assistive_MathML" role="presentation"><math xmlns="http://www.w3.org/1998/Math/MathML"></math></span></span><script type="math/tex" id="MathJax-Element-1076"></script></p>
```
[Answer]
# 4830 / 256 = 18.87
```
[1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1<p>1](http://localhost:8080/welcome-to-my-fantastic-amazing-homepage-and-why-not-share-it-to-your-facebook-right-now.html)
```
An idea based on HTML autocorrect. Not quite high score though.
[Answer]
# 421 / 56 = 7.518
```
>&
&
>&
&
>&
&
>&
&
>&
&
>&
&
>&
```
Which produces the following HTML on SE:
```
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
<p>&</p>
<blockquote>
<p>&</p>
</blockquote>
```
... and the following output:
---
>
> &
>
>
>
&
>
> &
>
>
>
&
>
> &
>
>
>
&
>
> &
>
>
>
&
>
> &
>
>
>
&
>
> &
>
>
>
&
>
> &
>
>
>
[Answer]
# 11190 / 255 = ~43.88
I was inspired by [this](https://codegolf.stackexchange.com/a/172493/43446) top answer, but am too dumb to beat it and reached the max character count so, I guess I'll have to be satisfied with what I have ¯\\_(ツ)\_/¯. There's actually two spaces after the last blockquote, but the formatting does not show it.
`> - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - > - >`
**HTML:**
```
<blockquote>
<ul>
<li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
<ul><li><blockquote>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li></ul>
</blockquote></li>
</ul>
</blockquote>
```
] |
[Question]
[
Your challenge is simple: write as long of a [pristine program](https://codegolf.stackexchange.com/questions/63433/programming-a-pristine-world) as possible in the language of your choice using only unique bytes. (The full definition of a pristine program, copied from that link, is at the bottom of this question.)
That's right, no strings attached. Your code doesn't have to do anything at all, just run without erroring, meet the requirements for a pristine program (linked above), and include no duplicate bytes in the encoding you use.
For the purposes of the above explanation and linked definition of "pristine program", an error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time.
As this is [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"), ***longest***, not shortest, code wins (measured by byte count). The maximum theoretically possible score is 256, as there are 256 distinct bytes possible. In case of a tie, the first answer at the highest score wins.
---
Here's the full definition of a pristine program, copied from the above link:
>
> Let's define a *pristine program* as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where `1 <= N < program length`.
>
>
> For example, the three character Python 2 program
>
>
>
> ```
> `8`
>
> ```
>
> is a pristine program because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
>
>
>
> ```
> 8`
> ``
> `8
>
> ```
>
> and also all the programs resulting from removing substrings of length 2 cause errors:
>
>
>
> ```
> `
> `
>
> ```
>
> If, for example, ``8` had been a non-erroring program then ``8`` would not be pristine because **all** the results of substring removal must error.
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), ~~39~~ ~~45~~ ~~50~~ ~~52~~ 60 bytes
```
main=do{(\§∂∏ Ôß쬆‚µô
商
flú·öÄÊñ∞->pure fst)LT
EQ[]3
2$1}
```
Identifier `main` has to have type `IO a` for some type a. When the program is executed, the computation `main` is performed, and its result is discarded. In this case its type is `IO ((a,b)->a)`.
The result is an application of the function `(λ a b c d e f → return fst)`,
a six-argument constant function returning the function fst (which gives the first element of a 2-tuple), injected into the IO monad. The six arguments are `LT` (enum for less than), `EQ` (enum for equality), empty list `[]`, `3`, `2` and `1`.
What would be spaces are replaced with unique characters that count as spaces: a tab, a non-breaking space, a formfeed, vertical tab, OGHAM SPACE MARK, regular space, newline and carriage return. If any of these are missing, there will be a mismatch in the number of arguments. The parameter names are chosen as three or four byte UTF-8 characters, `§∂∏Ôß삵ôÂïÜflúÊñ∞`, carefully choosing characters that don't result in duplicate bytes.
Thanks to @BMO for his valuable contributions.
Hex dump:
```
00000000: 6d61 696e 3d64 6f7b 285c f0a4 b6b8 09ef main=do{(\......
00000010: a793 c2a0 e2b5 990c e595 860b df9c e19a ................
00000020: 80e6 96b0 2d3e 7075 7265 2066 7374 294c ....->pure fst)L
00000030: 540a 4551 5b5d 330d 3224 317d T.EQ[]3.2$1}
```
[Try it online!](https://tio.run/##AUcAuP9oYXNrZWxs//9tYWluPWRveyhc8KS2uAnvp5PCoOK1mQzllYYL35zhmoDmlrAtPnB1cmUgZnN0KUxUCkVRW10zCjIkMX3//w "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~253 254~~ 256 bytes
```
M‚Äú¬¢¬£¬•¬¶¬©¬¨¬Æ¬µ¬Ω¬ø‚Ǩ√Ü√á√ê√ë√ó√ò≈í√û√ü√¶√ß√∞ƒ±»∑√±√∑√∏≈ì√æ !"#%&'()*+,-./0145689:;<=>?@ABCDEFGHIJKNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|~¬∂¬∞¬π¬≤¬≥‚Å¥‚ŵ‚Å∂‚Å∑‚Å∏‚Åπ‚Å∫‚Ū‚ź‚ÅΩ‚Åæ∆Å∆á∆ë∆ì∆ò‚±Æ∆ù∆§∆¨∆≤»§…ì∆à…ó∆í…†…¶∆ô…±…≤∆• †…º Ç∆≠ 㻕·∫†·∏Ñ·∏å·∫∏·∏§·ªä·∏≤·∏∂·πÇ·πÜ·ªå·πö·π¢·π¨·ª§·πæ·∫à·ª¥·∫í»¶·∏ǃä·∏äƒñ·∏ûƒ†·∏¢ƒ∞ƒø·πÄ·πѻƷπñ·πò·π†·π™·∫Ü·∫ä·∫é≈ª·∏Ö·∏ç·∫π·∏•·ªã·∏≥·∏∑·πÉ·πá·ªç·πõ·π£·π≠·ª•·πø·∫â·ªµ·∫ì»ß·∏Ƀã·∏ãƒó·∏üƒ°·∏£≈Ä·πÅ·πֻطπó·πô·π°·π´·∫á·∫ã·∫è≈º‚ÄùL¬ª¬´‚Äô∆ä·∫°‚Äò}237$¬§¬°
```
[Try it online!](https://tio.run/##Dc3nUlpBHIfhW0nvvffee@89McWYXk0bFgsGNIkwI5BEpTuJSAAF9r8HcWb3sHMOd/HbGyF8f@Z929s6OjqbzePG81smZFKmZUb@kVmZkyU5LWeMN6t6lU/9UIMqrCL1oBpRoyqjxlTeLjgVVVAVxeshVZs1e87c@QsWLlq8ZOmy5StWrlq9bv2GTZu3bN22fcfOXbv37N23/8DBQ4ePHD1x8tTpM2fPnb9w8dLlK1evXb9x89btO3fvtd1/8PBR@@OOJ0@fPX/x8tXrN2/fve/88PHTF1mWeUmyKCcNmzKsZFjZsIph3DAyTBhmGVY1bNqwmmbapwd1SEdMIaeHdUpnddFJuSHd54Z10I25GR11C25Rpxsxt9rw6olGwElDxMC7wfshOHgKlh@8CF4GeUG9sPpBP0EJUBZWClSD6IM1BRF0MuBeu6X99hD4iN3KJOy8PQPygLqdHGgIFAHFQH8heiH8EN/qFngP@AAEgadhBcAnwSugLpAP1gDoFygJmoCVBs1AfIVVggg5Y@BddksH7DD4qB0HT9ZbHwbqcf6BwqAoKA4ah/BBBCC@16vGM3xMWnLceKK6NY8bT@TzmrUb58mUjDeb/wE "Jelly – Try It Online") or [Verify it!](https://tio.run/##rVLtV9tUGP9s/orraxqLWJyvaJk4ik7nUDdfgWFpb7fMNOmSFKlvp2EbTNjUwTkD1G28tOzoGAM2IDdhcM5NmtPyXzz5RzBJsaHqR@@H5N4nv5cnv/vkCuo5STyyn5LSOM6y7Ptu8Xe6QBdpmS7RP@gyXaEb9BHddUeWrVFrzPrFum5NWzOVSeuWddtasu5Yq/Zadctas7YsvTJl7aDHn3jy6WfYCPdstOW51udjbS@@9PKrr7W//ka84@ibnW8d60p0v/3O8XffO9nzwYcfnTr98Seffvb5F719/WcGvkwOptI4c/Ycf/4rIStKuQuyouaHvh4ufPPtdz/QTbpKCV2nD1ztoattuNqmq225mu5qxNUMVzNdbdvVHrnajqM5Y851Z8qZcddWnJtOyVl21qul2pRzpTbtTNbmakvObG2ttu6U9@Zq23sjzr29iWoZjDnQL4F@FQwd9BKY46Cvg74JZATIKJhXgfwKZAHIMpglIDtgXAHzIRiT1SXQR2wPPW7fAP2W7cks2Kv2LpAikEvVFSA3gMwAmQPyJxijYIyD8VPFBP0y6NfAIKCXwZwA/QHoW0AuAhkD8xqQ34AsArkHZhnILhg/grkBxlT1DugXbQ89YU@DftueB32x4vloQC5X7wOZBjILZB7IXTDGwJgA4@fKtlu8eYKa9K5bnHU883m3OPP9C0deeYqW6Lx36fsZWcqi81gQCojP5iRZrR8G8FBSYA4qKp/FDKPG4v6m1X9EOIbhM0jAYsQfHy4e97cKVutHrp15LCfzohpRVDnSQHEoiliUF/kLeYwGCypWWlmOwYKCG3g2McwrKkrncwKfSqqHYIwoiQlZlmQFxVGMSUl5UfV2bQyTkWSkqEmvUV5EclI8i0PLaJvXC/KWD8JiOoQEjGhbSwitlzpi3AHFX3WbqO8TltJ4QJX5bBanvQb8Y297QO33/i84ekbt/Q2CKhdCQX/JWMkLfvNh1JHDqi29/VyDgIdTOKc2C@SSihICgvwOfw6Tamo8YAYpN5n5scTZPrFPPNbTlUBdPYlT6GTPadTdefyEX2W5/1GBYQ7u2au2BDS2PkqNnjti9Z85wHUOSkMY/R23b4vSElY8vIqwTwhH6DBLEJo5AbQ@R43r@Ef6Qer1tFEiePGS2KTanfdkA7lMkheU/3QOMf9qc3//Lw)
Turns out golfing languages can bowl...
* +1 byte by working in `‘`. ~~Now only `«»` are not used~~
* +2 bytes with with `«»`. Now have the optimal score!
## How?
The crucial feature of Jelly that makes this possible is that the opening and closing characters for string literals are not the same like in nearly all other languages.
The program structure is as follows:
`M <239 character long string> L»«’Ɗạ‘}237$¤¡`
`M` finds the indices of its argument that point to maximal elements. All that matters is that with no argument to this program Jelly assigns `0` to the chain and Jelly errors when `M` is applied to `0`.
To prevent `M` from acting on `0` in the full program, we use the `¡` quick, which applies `M` a number of times determined by the result of the link immediately preceding it. In this case that link is `<239 character long string> L»«’Ɗạ‘}237$¤`.
`L` takes the length of this string (239), and `»«’Ɗ` decrements this to 238. The `»«` part doesn't do anything but `Ɗ` (last three links as a monad) makes it so that if they are deleted an error will occur. Then `ạ` takes the absolute difference between the result of `»«’Ɗ` and the monad `‘}237$` applied to the string. `‘` increments and is a monad, but the `}` turns this into a dyad and applies it to it's right argument, `237`, yielding `238`. Thus `ạ` yields `0` in the full program.
`¤` links back to the string literal forming a nilad. The result of this is `0`, so `M` is not applied at all, preventing any error.
**Possible subprograms:**
* If any part of the string is removed, `<string>..¤` will be nonzero and `M` gets applied to `0`, causing an error.
* If any part of `L»«’Ɗạ‘}237$` is removed either `M` will get applied to `0` or there will be operations between the string and a number, resulting in a `TypeError`.
* If any of `¤¡` is removed, `M` gets applied to `0`.
* If the string closing character `”` and both of `’‘` get removed and `“` doesn't, everything after `M` turns into a string so `M` will act on `0`.
+ If the string closing character `”` and `’` get removed and `“` doesn't, everything between `”` and `‘` turns into a list of integers.
* If `M` alone is removed there is a an `EOFError` because `¬°` expects a link before the preceding nilad.
* If `M“` and any number of characters after it is removed, there will be an `EOFError` because the `¤` looks for a nilad preceding it but doesn't find one. `238` doesn't count because it is part of a monad.
This pretty much covers everything.
I previously hadn't used `«»‘` because the latter two cannot be included in the string because they match the `“` character to form things other than strings. `«` can't be in a `“”` string either but I don't know why.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~ 20 21 33 39 45 ~~ 50 bytes
Now very much a collaborative effort!
+2 thanks to Aidan F. Pierce (replace `sorted({0})` with `map(long,{0})`)
+8 thanks to dylnan (use of `\` and newline to replace space; suggestions to move from `0` to a mathematical expression; replacing `-1` with `-True`; use of hexadecimal)
+11 thanks to Angs (`4*23+~91` -> `~4836+9*1075/2` then later `~197836254+0xbCABdDF` -> `~875+0xDEAdFBCbc%1439/2*6`)
---
```
if\
map(long,{~875+0xDEAdFBCbc%1439/2*6})[-True]:q
```
**[Try it online!](https://tio.run/##K6gsycjPM/r/PzMthis3sUAjJz8vXae6zsLcVNugwsXVMcXNyTkpWdXQxNhS30jLrFYzWjekqDQ11qrw/38A "Python 2 – Try It Online")** Or see the [confirmation suite](https://tio.run/##dZJfT8IwFMXf@ymuD6SbGwj@t8lIEGZi4pv6BDyM7YJNoMW2U4jRr45tBwxjSJbs9t5fT3pOu1ybNynON5tcFphQPh2NRmKRLYO5FLP46@f25ipqrwZpr3i470/yRufy4u7s/PT6Oxw2X1SJY/ZOCeFTmKMInEYISeIXGk3VCBmBpeLC1EwMtBT8vUSYrA1qSnCucY/Rh4zPGQgpmocU4Iprc0KJK0wQErLFVSkEFzNw0vDJzRvocqKNHc40KFzIDyxarRbd8fbAVjtVSioNCbRJLkvbT6BDplKBNpkywAWoTMww2B866jgnjkBR1HOPR5245qpWt@2dgxN2/SHz7TFE1dKKsLGbq7XDrCnMAxMSV@W4NJD6H5cCMuvdM1sDjYLRhj90DPajzS6NAd3OKsaj4EhYkD6/9vtpOkgHwALq6DqNyIUAUAXiF3Vo28LCgI6uKGYV9/utOKPWIA0DOtx3u@3xP5XdnS0yG6TLw18QqcLwUfgsybEsdi@l9/i09fH3CR14DOlm8ws "Python 2 – Try It Online")
`0xDEAdFBCbc` is hexadecimal and evaluates to `59775106236`.
`~` is bit-wise complement so `~875` evaluates to `-876`.
`%` is the modulo operator so `0xDEAdFBCbc%1439` evaluates to `293`.
`/` is integer division so `0xDEAdFBCbc%1439/2` evaluates to `146`.
`*` is multiplication so `xDEAdFBCbc%1439/2*6` evaluates to `876`.
`+` is addition so `~875+xDEAdFBCbc%1439/2*6` evaluates to `0`.
...no stripped version also evaluates to `0`.
`{0}` is a `set` containing a single element, `0`.
Calling `sorted` with a `set` as the argument yields a list, which may be indexed into with `[...]`.
Without `sorted` the code `({0})` would just yield the `set` and this cannot be indexed into in the same fashion, `if({0})[-True]:q` would raise a `TypeError`.
Indexing in Python is 0-based and allows negative indexing from the back and `True` is equivalent to `1`, hence `sorted({0})[-True]` finds the element `0`, while `sorted({0})[True]` will raise an `IndexError`, as will `sorted({})[-True]` and `sorted({0})[]` is invalid syntax.
The `0` that is found is falsey so the body of the `if`, `q`, is never executed, however if it were it would raise a `NameError` since `q` has not been defined.
Since a non-empty list is truthy we cannot trim down to `if[-1]:q` either.
See the [confirmation suite](https://tio.run/##dZJfT8IwFMXf@ymuD6SbGwj@t8lIEGZi4pv6BDyM7YJNoMW2U4jRr45tBwxjSJbs9t5fT3pOu1ybNynON5tcFphQPh2NRmKRLYO5FLP46@f25ipqrwZpr3i470/yRufy4u7s/PT6Oxw2X1SJY/ZOCeFTmKMInEYISeIXGk3VCBmBpeLC1EwMtBT8vUSYrA1qSnCucY/Rh4zPGQgpmocU4Iprc0KJK0wQErLFVSkEFzNw0vDJzRvocqKNHc40KFzIDyxarRbd8fbAVjtVSioNCbRJLkvbT6BDplKBNpkywAWoTMww2B866jgnjkBR1HOPR5245qpWt@2dgxN2/SHz7TFE1dKKsLGbq7XDrCnMAxMSV@W4NJD6H5cCMuvdM1sDjYLRhj90DPajzS6NAd3OKsaj4EhYkD6/9vtpOkgHwALq6DqNyIUAUAXiF3Vo28LCgI6uKGYV9/utOKPWIA0DOtx3u@3xP5XdnS0yG6TLw18QqcLwUfgsybEsdi@l9/i09fH3CR14DOlm8ws "Python 2 – Try It Online") to see: confirmation the bytes being unique; all the errors; and the success of the code itself.
[Answer]
# [C (tcc)](http://savannah.nongnu.org/projects/tinycc), x86\_64, ~~29~~ ~~31~~ ~~33~~ ~~39~~ 40 bytes
```
main[]={(23*8),-~0xABEDFCfebdc%95674+1};
```
Returns **0**. *Thanks to @feersum for suggesting uppercase hex digits.*
[Try it online!](https://tio.run/##S9YtSU7@/z83MTMvOta2WsPIWMtCU0e3zqDC0cnVxc05LTUpJVnV0tTM3ETbsNb6/38A "C (tcc) – Try It Online")
### How it works
The assignment writes two ints (**184** and **49664**) to the memory location of *main*. With 32-bit ints and little-endian byte order, the exact bytes are `b8 00 00 00 00 c2 00 00`.
Since tcc doesn't declare the defined array as *.data* (most compilers would), so jumping to main executes the machine code it points to.
* `b8 00 00 00 00` (`mov eax, imm32`) stores the int **0** in the eax register.
* `c2 00 00` (`ret imm16`) pops **0** extra bytes from the stack and returns. (The value in the eax register is the function return value).
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 122 bytes
```
e"~l=?!z6-d0p}xwutsrqonmkjihgfcba`_]\[>ZYXWVUTSRQPONMLKJIHGFEDCB@<:98754321/,+*)('&%$#
.
|{Ay
```
[Try it online!](https://tio.run/##S8sszvj/P1WpLsfWXrHKTDfFoKC@tqK8tKS4qDA/Lzc7KzMjPS05KTEhPjYm2i4qMiI8LDQkOCgwwN/P18fby9PD3c3VxdnJwcbK0sLc1MTYyFBfR1tLU0NdTVVFWUFeTlZPRlpKUkJcTFREWEhQgJ@Ph5uTg52NlYWZibGm2rHy/38A "><> – Try It Online")
Does nothing. Based on the same format as my [Programming a Pristine World](https://codegolf.stackexchange.com/a/153233/76162) answer.
First, we check that the length of the code is 122 and error if it isn't. `><>` programs can't end without the use of the `;` command, but if this command is in the program, we can just remove everything before it to make the program end immediately. To combat this, we use the `p` command to place a `;` in the code during runtime. To do this, we subtract 6 from `A` and place it after the `p`.
I'll probably add most of the other values above 127 once I figure out the right two byte values. The missing 5 values are `v^;` and the two newlines.
Of the 7502 sub-programs, 7417 of them errored from invalid instructions, 72 from memory underflow, and 13 from running out of memory.
[Answer]
# JavaScript, 42 bytes
```
if([0XacdCADE*Proxy.length]!=362517948)Áî∞
```
* Removing `i`, `f`, or `if` will cause `SyntaxError: missing ; before statement`;
* Removing `Áî∞` will cause `SyntaxError: expected expression, got end of script`;
* Removing 1 or 2 bytes from `Áî∞` will cause `Invalid or unexpected token`;
* Modify the boolean expression will cause either Syntax Error or Reference Error on `Áî∞`
```
00000000: 6966 285b 3058 6163 6443 4144 452a 5072 if([0XacdCADE*Pr
00000010: 6f78 792e 6c65 6e67 7468 5d21 3d33 3632 oxy.length]!=362
00000020: 3531 3739 3438 29e7 94b0 517948)...
```
```
(function () {
let valid = code => { try { eval(code); return true; } catch (e) { return false; } };
let test = P => {
for (let i = 0; i < P.length; i++) for (j = i + 1; j <= P.length; j++) {
let Q = P.slice(0,i) + P.slice(j);
if (Q && valid(Q)) {
console.log(Q);
return false;
}
}
return true;
};
let unique = P => !/(.).*\1/.test(P);
let P = 'if([0XacdCADE*Proxy.length]!=362517948)Áî∞';
console.log(unescape(encodeURIComponent(P)).length);
console.log(valid(P));
console.log(unique(P));
console.log(test(P));
}());
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 2 bytes
```
<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/38bu/38A "Brain-Flak – Try It Online")
Alternatively, `[]`, `{}` or `()`. Removing either bracket causes the other bracket to become unmatched.
Proof that this is the optimal solution:
A Brain-Flak program is made out of nilads (a pair of brackets on their own) or monads (a pair of brackets containing 1 or more nilads). A monad cannot be in a pristine program, as you can simply remove one or more of the nilads. Similarly, you cannot have more than one nilad in the program, since you can remove one of them without breaking the program.
As such, this might be the least optimal language for pristine or unique programming.
[Answer]
# Ada, 110 bytes (latin1)
Probably the best answer you'll get out of any language in use in industry?
Hexdump:
```
0000000: 7061 636b 4167 4520 6266 686a 6c6d 6f71 packAgE bfhjlmoq
0000010: 7274 7576 7778 797a e0e1 e2e3 e4e5 e6e7 rtuvwxyz........
0000020: e8e9 eaeb eced eeef f0f1 f2f3 f4f5 f6f8 ................
0000030: f9fa fbfc fdfe 0d69 730b 656e 6409 4246 .......is.end.BF
0000040: 484a 4c4d 4f51 5254 5556 5758 595a c0c1 HJLMOQRTUVWXYZ..
0000050: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1 ................
0000060: d2d3 d4d5 d6d8 d9da dbdc ddde 3b0a ............;.
```
Compile by saving to any file ending in `.ads` and running `gcc -c <filename>`. Produces an executable that does nothing. (Can't provide TIO link since TIO puts code in a `.adb` file and `gcc` by default tries to find a matching spec for them)
Basically declares a package with a name abusing capital/lowercase latin1 letters. Needs a different whitespace character for each of the spaces, so it uses space, CR, LF, and TAB.
How it looks in vim version:
```
packAgE bfhjlmoqrtuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ^Mis^Kend^IBFHJLMOQRTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ;
```
### How it works
In Ada even spec's can be compiled. Spec's are like c's header files, but are more full-featured and can compile some basic code. In order to be valid any specification must have the format: `package <NAME> is ... end <NAME>;` with `<NAME>` matching. The nice thing about Ada is that it is completely case insensitive. Thus as long as your name has uppercase and lowercase variants, you'll be good to go!
The hard part was getting a compilable unit. Normally Ada programs have a 'main' procedure or function lying outside of any package that will become the final executable. Unfortunately procedures require the `begin` keyword, which leads to too many `e`s (only 2 cases known) while functions require the `return` keyword, which leads to too many `n`s. Thus I had to just compile a package.
[Answer]
# C, 8 bytes
```
main(){}
```
Does nothing.
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O69v9/AA)
[Answer]
# JavaScript, 22 bytes
```
with(0xF?JSON:[])parse
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f@/PLMkQ8Ogws3eK9jfzyo6VrMgsagYKA4A "JavaScript (Node.js) – Try It Online")
### Possible errors
When altered, it will throw one of the following errors1:
```
[some_identifier] is not defined
expected expression, got ')'
expected expression, got ':'
expected expression, got '?'
expected expression, got ']'
expected expression, got end of script
identifier starts immediately after numeric literal
missing ( before with-statement object
missing ) after with-statement object
missing : in conditional expression
missing ] after element list
missing exponent
missing hexadecimal digits after '0x'
missing octal digits after '0o'
unexpected token: ')'
unexpected token: ']'
unexpected token: identifier
```
1. The exact number of distinct errors depends on the engine. This list was generated with SpiderMonkey (Firefox).
[Answer]
# [Python 3](https://docs.python.org/3/) + [Flask-Env](https://pypi.org/project/Flask-Env/), ~~7~~ ~~13~~ ~~14~~ 17 bytes
```
import\
flask_env
```
No TIO because it doesn't have `flask-env`.
Found the longest module name that has no intersection with `import` and doesn't have any numbers at the end of the name. `_sha256` is longer but `256` on it's own doesn't error. I did find one library, `b3j0f.sync` that is one byte longer but I could not get it to import properly.
* +1 byte by replacing a space after `import` with `\<newline>`. Taking out either or both causes an error.
There still may be longer options than `flask_env`, I didn't really do an exhaustive search but I did look through ~70,000 modules. Open to suggestions.
[Answer]
# [R](https://www.r-project.org/), 14 bytes
```
(Sys.readlink)
```
[Try it online!](https://tio.run/##K/r/XyO4slivKDUxJSczL1vz/38A "R – Try It Online")
This might be the longest possible in R. Calling any function is doomed to failure, because you would be able to remove everything but the function name, which would just result in printing the function's source code. This is the longest named object in the default R setup with no duplicate characters and no object name left over when removing contiguous characters.
*This first try didn't work, but I learned a lot by trying!*
~~`dontCheck({family;NROW})`~~
[Answer]
# Perl 5, 3 bytes
```
y=>
```
`=>` is the "fat comma," which quotes the bareword on the left. So this is equivalent to
```
"y",
```
which does nothing.
Without the fat comma, `y` is the transliteration operator, which is invalid without three of the same character repeated later.
The fat comma alone is also invalid, as is `=` and `>` alone.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 2 bytes
```
[]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v8/Ovb/fwA "brainfuck – Try It Online")
Inspired by Jo King's [Brain-Flak answer](https://codegolf.stackexchange.com/a/162524/75553). This is optimal because the only error in brainfuck is unmatched brackets. (Again thanks to Jo King for this info.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 28 bytes
```
(?2*0xA)[%r<\d{1}>].unpack$/
```
[Try it online!](https://tio.run/##KypNqvz/X8PeSMugwlEzWrXIJial2rDWLlavNK8gMTlbRf//fwA "Ruby – Try It Online")
[Verify it!](https://tio.run/##rY67boMwFIZn/BQnSStDopiLOlW9qFK7dujQhTAYcxKsUhsdTJQqyrNTIGSqlKnbuf7fR23@03WLWdg2FObahGj2QP0wEXdM2QLhEbj/nCyjw0uQ3tLDpjjGp6dMtKaW6usm5IzpLVB/NlynoS8CsdzEYQauRMM8mVtyPv/AGqXDAlQpSSqHdA8cVkBplAUMTcFYjjvdP@BeVv6QFTDCRrUIbweFtdP2kgb83dK3rEYiIJElwc8ZW0ugQRuIhBi2okKzc@U6hsIyT10s@63QWY8fO72KhVjHGfMmhckh6KszcL44qhO8WmwMdxNxzry/foPEVZHkukjy7yJ16xrgn7LSxQiZ8a77BQ "Verify it!")
[Answer]
# [Standard ML](http://www.mlton.org/), 22 bytes
```
val 1089=op-(765,~324)
```
[Try it online!](https://tio.run/##K87N0c3NKcnP@/@/LDFHwdDAwtI2v0BXw9zMVKfO2MhE8/9/AA "Standard ML (MLton) – Try It Online") `op-(a,b)` is the de-sugared form of `a-b`. `~` denotes the unary minus, so we are actually computing `765+324`. This expression is pattern-matched on the constant `1089`. This match succeeds if the program has not been tampered with and does - well, nothing.
If the match does not succeed because some digits were removed one gets an `unhandled exception: Bind`. Removing `op-` results in a type error because a tuple is matched on an `int`. All other removals should result in an syntax error.
[Answer]
# [Tcl](http://tcl.tk/), 6 bytes
```
puts a
```
[Try it online!](https://tio.run/##K0nO@f@/oLSkWCHx/38A "Tcl – Try It Online")
---
# [Tcl](http://tcl.tk/), 3 bytes
```
pwd
```
[Try it online!](https://tio.run/##K0nO@f@/oDzl/38A "Tcl – Try It Online")
---
# [Tcl](http://tcl.tk/), 2 bytes
```
cd
```
[Try it online!](https://tio.run/##K0nO@f8/OeX/fwA "Tcl – Try It Online")
[Answer]
# Batch, 7 bytes
```
set/px=
```
A nice start
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 2 bytes
I wouldn't be surprised if this is optimal...
```
()
```
[**Try it online!**](https://tio.run/##K0otycxLNPz/X0Pz/38A "Retina – Try It Online")
The regex contains an empty group. Removing either paren will cause a parse error due to unmatched parentheses.
Other solutions are: `\(`, `\)`, `\[`, `\]`, `\*`, `\+`, `\?`, `a]`
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), 76 bytes
```
cba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwd
```
[Try it online!](https://tio.run/##y03MScrPSU/9/z85KTEhPi42JjoqMiI8LDQkOCgwwN/P18fby9PD3c3VxdnJ0cHeztbG2srSwtzM1MTYyNBAX09XR1tLU0NdTVVFWUmxrramuqqyojzl/38A "Malbolge – Try It Online")
Malbolge is a great language for this challenge due to the way it translates normalized Malbolge into your familiar keyspam-esque Malbolge.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
Closed 7 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
[# 4, 8, 15, 16, 23, 42](http://lostpedia.wikia.com/wiki/The_Numbers)
Write a program that outputs this sequence of numbers infinitely. However, The Numbers must not appear in your source code anywhere.
The following is not a valid Java program to output The Numbers because The Numbers appear in its source code:
```
class TheNumbers {
public static void main(String[] args) {
for(int n = 0;;) System.out.println(
n == 4 ? n = 8 :
n == 8 ? n = 15 :
n == 15 ? n = 16 :
n == 16 ? n = 23 :
n == 23 ? n = 42 : (n = 4)
);
}
}
```
The definition of *"The Numbers must not appear in your source code"* is as follows:
* You must not use the numeral 4.
* You must not use the numeral 8.
* You must not use the numeral 1 followed by the numeral 5.
* You must not use the numeral 1 followed by the numeral 6.
* You must not use the numeral 2 followed by the numeral 3.
If your language ignores certain characters that can be placed between the numerals, it's not a valid substitution. So for example if your language interprets the literal `1_5` as `15`, this would count as the numeral 1 followed by the numeral 5.
Alternative bases are included in the restriction, so for example:
* Binary 100 can't be used as a substitute for 4.
* Octal 10 can't be used as a substitute for 8.
* Hexadecimal F can't be used as a substitute for 15.
Therefore, the following is a valid (but not very inspired) Java program to output The Numbers because The Numbers do not appear in its source code:
```
class TheNumbers {
public static void main(String[] args) {
for(int n = '*';;) {
System.out.println(n -= '&');
System.out.println(n *= 2);
System.out.println(n += 7);
System.out.println(++n);
System.out.println(n += 7);
System.out.println(n += 19);
}
}
}
```
Note that in that program, `'*'` and `'&'` are substituted for the integers 42 and 38, because otherwise the numerals 4 and 8 would appear in its source code.
The definition of *"outputs the sequence infinitely"* is open to interpretation. So, for example, a program that outputs glyphs getting smaller until they are "infinitely" small would be valid.
Kudos if you are able to generate the sequence in some way that's not basically hard-coding each number.
* Deriving it to a formula. My impression is there is not one but maybe there is or it can be faked.
* [Fixing a pseudo-random generator](https://stackoverflow.com/questions/15182496/why-does-this-code-print-hello-world) to return the sequence.
This is a popularity contest, so be creative. The answer with the most up votes on March 26th is the winner.
[Answer]
# Java
I decided to add another entry since this is completely different from my first one (which was more like an example).
This program calculates the average of an array entered by the user...
```
import java.util.Scanner;
public class Numbers {
public static double getSum(int[] nums) {
double sum = 0;
if(nums.length > 0) {
for(int i = 0; i <= nums.length; i++) {
sum += nums[i];
}
}
return sum;
}
public static double getAverage(int[] nums) { return getSum(nums) / nums.length; }
public static long roundAverage(int[] nums) { return Math.round(getAverage(nums)); }
private static void beginLoop(int[] nums) {
if(nums == null) {
return;
}
long avg = roundAverage(nums);
System.out.println("enter nums for average");
System.out.println("example:");
System.out.print("array is " + nums[0]);
for(int i = 1; i <= nums.length; i++) {
System.out.print(", " + nums[i]);
}
System.out.println();
System.out.println("avg is " + avg);
}
private static int[] example = { 1, 2, 7, 9, };
public static void main(String[] args) {
boolean done = false;
while(!done) {
try {
int[] nums = example;
beginLoop(nums);
nums = getInput();
if(nums == null) {
done = true;
} else {
System.out.println("avg is " + getAverage(nums));
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
static int[] getInput() {
Scanner in = new Scanner(System.in);
System.out.print("enter length of array to average or 0 to exit: ");
int length = in.nextInt();
if(length == 0) {
return null;
} else {
int[] nums = new int[length];
for(int i = 0; i <= nums.length; i++) {
System.out.print("enter number for index " + i + ": ");
nums[i] = in.nextInt();
}
return nums;
}
}
}
```
...or does it?
```
java.lang.ArrayIndexOutOfBoundsException: 4
at Numbers.getSum(Numbers.java:8)
at Numbers.getAverage(Numbers.java:15)
at Numbers.roundAverage(Numbers.java:16)
at Numbers.beginLoop(Numbers.java:23)
at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
at Numbers.getSum(Numbers.java:8)
at Numbers.getAverage(Numbers.java:15)
at Numbers.roundAverage(Numbers.java:16)
at Numbers.beginLoop(Numbers.java:23)
at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
at Numbers.getSum(Numbers.java:8)
...
```
[Answer]
## Python
```
#!/usr/bin/python
lizt = ["SPOI",
"LERS: Lo",
"st begins with ",
"a plane crash on",
"a desert island and end",
"s with its viewers stuck in limbo forever."
]
while True:
for item in lizt:
print len(item)
```
**Edit:** As per nneonneo's suggestion, script now includes no digits.
[Answer]
# Perl
There is nothing hidden in the source code. Nope. If the code doesn't work, type `use re "eval";` before it (required in Perl 5.18).
```
''=~('('.'?'.('{').(
'`'|'%').('['^'-').(
"\`"| '!').('`'|',')
.'"'. '\\' .'@'.('`'
|'.') .'=' .'('.('^'
^('`' |"\*")).
','.("\:"& '=').','.
('^'^('`'| ('/'))).(
'^'^("\`"| '+')).','
.('^'^('`'|('/'))).(
'^'^('`'|'(')).','.(
'^'^('`'|',')).('^'^
("\`"| '-')).','
.('^' ^('`' |'*')).(
'^'^( "\`"| (','))).
(')'). ';'.('['^
','). ('`'| ('(')).(
"\`"| ')'). ('`'|','
).('`' |'%').'('
.'\\'.'$'.'|'."\=".(
'^'^('`'|'/'))."\)".
'\\'.'{'.'\\'."\$".(
"\["^ '/') .((
'=') ).+( '^'^('`'|
'.' ) ).(( (';'))).(
"\`"| '&'). ('`'
|'/') .('['^')') .((
'(')) .''. '\\'. '@'
.+( '`' |'.'
).')'.'\\'.'{'.('['^
'(').('`'|',').('`'|
'%').('`'|'%').('['^
'+'). '\\'. '$'.
'_'. '-'. '\\'. '$'
.+( ( '[') ^'/').';'
.'\\' .'$' .''.
('['^ '/') .'='. (((
'\\') )).+ "\$". '_'
.(( ';' )).+
'\\'.'$'.'_'.'='.'='
.('^'^('`'|'*')).'|'
.'|'.('['^'+').('['^
')' ).( '`'|
(( ')')) ) .('`' |((
'.'))).( '['^'/' ).+
((( ((( '\\'
)) )))).'"'.('{' ^((
(( '[')))) ).''. (((
(( (( '\\'
))))))).'"'.';'.('['
^'+').('['^')').('`'
|')').('`'|'.').('['
^+ '/').''. '\\'
.+ '}'. +( "\["^ '+'
). ('[' ^"\)").( '`'
|+ (( ')')
)).('`' |+ '.').('['
^'/').( (( '{'))^'['
).'\\'. (( '"'
)).('!'^'+').('\\').
'"'.'\\'.'}'.(('!')^
'+').'"'.'}'.')');$:
='.'#madebyxfix#'.'=
^'~';$~='@'|"\(";#;#
```
Explanation in spoiler.
>
> This is a simple Perl program which makes use of multiple bitwise operations, and evaluates the regular expression using **=~** operator. The regex begins with **(?{** and ends with **})**. In Perl, this runs code while evaluating regular expression - this lets me use **eval** without actually using it. Normally, however, **re "eval"** is required, for security reasons, when evaluating regular expressions from strings (some older programs actually took regular expressions from the user) - but it turns out that before Perl 5.18 there was a bug causing constant folded expressions to work even without this pragma - if you are using Perl 5.18, type **use re "eval";** before the code to make it work. Other than that, there is not much else to this code.
>
>
>
[Answer]
## Brainfuck
I'm so bad at ASCII art !
```
++ ++++++++ +[>+>++ ++>++++
+< <<-]>++> >- --<
<< +[ >> >.<.>++ ++.
<. >- -- ----.++ ++.
<.>--- -.+++++. <. >--
-/-./+ .<.>+.-/ -.++<<. </]
```
Test it here : <http://ideone.com/kh3DYI>
[Answer]
## Unix C
There are lots of places to find numeric constants.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <fcntl.h>
#include <pwd.h>
#include <netdb.h>
int main(void)
{
int thenumbers[] = {
S_IRGRP|S_IXGRP|S_IWOTH,
ntohs(getservbyname("telnet", "tcp")->s_port),
exp(M_E)-cos(M_PI),
SIGTERM,
CHAR_BIT,
strlen(getpwuid(EXIT_SUCCESS)->pw_name)
}, i=sizeof(thenumbers)/sizeof(*thenumbers);
while(i--)
printf("%d\n", thenumbers[i]);
return main();
}
```
[Answer]
## C#
>
> Formula "stolen" from <https://oeis.org/A130826> :
> a(n) is the smallest number such that twice the number of divisors of (a(n)-n)/3 gives the n-th term in the first differences of the sequence produced by the Flavius-Josephus sieve.
>
>
>
```
using System;
using System.Collections.Generic;
using System.Linq;
public static class LostNumberCalculator
{
public static int GetNumber(int i)
{
int a = GetPairwiseDifferences(GetFlaviusJosephusSieveUpTo(100)).ElementAt(i);
int b = FindSmallestNumberWithNDivisors(a / 2);
return b * 3 + i + 1;
}
public static IEnumerable<int> GetFlaviusJosephusSieveUpTo(int max)
{
List<int> numbers = Enumerable.Range(1, max).ToList();
for (int d = 2; d < max; d++)
{
List<int> newNumbers = new List<int>();
for (int i = 0; i < numbers.Count; i++)
{
bool deleteNumber = (i + 1) % d == 0;
if (!deleteNumber)
{
newNumbers.Add(numbers[i]);
}
}
numbers = newNumbers;
}
return numbers;
}
public static IEnumerable<int> GetPairwiseDifferences(IEnumerable<int> numbers)
{
var list = numbers.ToList();
for (int i = 0; i < list.Count - 1; i++)
{
yield return list[i + 1] - list[i];
}
}
public static int FindSmallestNumberWithNDivisors(int n)
{
for (int i = 1; i <= int.MaxValue; i++)
{
if (CountDivisors(i) == n)
{
return i;
}
}
throw new ArgumentException("n is too large");
}
public static int CountDivisors(int number)
{
int divisors = 0;
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
{
divisors++;
}
}
return divisors;
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
for (int i = 0; i < 6; i++)
{
int n = LostNumberCalculator.GetNumber(i);
Console.WriteLine(n);
}
}
}
}
```
[Answer]
# C#
Using the fact that any sequence of N elements can be generated by an N-1 polynomial and entering the numbers involved a lot of beeps and boops. For reference, the polynomial I derived is
```
( -9(X^5) +125(X^4) -585(X^3) +1075(X^2) -446(X) +160 ) / 40
```
I assigned the factors to the variables named for the numbers, for simplicity ;)
First version:
```
int BEEP,
// Magic numbers, do not touch.
four = -9,
eight = 125,
fifteen = -117*5,
sixteen = 1075,
twenty_three = (-1-1337) /3,
forty_two = 320/2;
for(BEEP=0;;BEEP=++BEEP%6)
{
Console.WriteLine( 0.025* (
four *BEEP*BEEP*BEEP*BEEP*BEEP+
eight *BEEP*BEEP*BEEP*BEEP+
fifteen *BEEP*BEEP*BEEP+
sixteen *BEEP*BEEP+
twenty_three *BEEP+
forty_two ));
}
```
I liked the implication of rising tension as the number of BEEPs decreases after each number.
Then I figured I could calculate the factors using beep and boops, too:
```
int BEEEP=0, BEEP=++BEEEP ,BOOP=++BEEP,BLEEP=++BOOP+BEEP,
four = BOOP*-BOOP,
eight = BLEEP*BLEEP*BLEEP,
fifteen = BOOP*-(BOOP+(BEEP*BLEEP))*BLEEP*BOOP,
sixteen = BLEEP*BLEEP*(BOOP+(BLEEP*BEEP*BEEP*BEEP)),
twenty_three = BEEP*-((BLEEP*BOOP*BLEEP*BOOP)-BEEP),
forty_two = BEEP*BEEP*BEEP*BEEP*BEEP*BLEEP;
```
Went a little overboard after that...
```
int BEEEP=default(int), BEEP=++BEEEP ,BOOP=++BEEP,BLEEP=++BOOP+BEEP;
for(--BEEEP;;BEEEP=++BEEEP%(BEEP*BOOP))
{
Console.WriteLine(
BOOP*( (BOOP*-BOOP)*BEEEP *BEEEP*BEEEP*BEEEP *BEEEP+(BLEEP*BLEEP*
BLEEP) *BEEEP* BEEEP* BEEEP* BEEEP+
(BOOP* -(BOOP+ (BEEP* BLEEP) )*BLEEP
*BOOP) *BEEEP* BEEEP* BEEEP+(BLEEP*BLEEP *(BOOP+
(BLEEP* BEEP* BEEP* BEEP))) *BEEEP*
BEEEP+ (BEEP*-( (BLEEP *BOOP* BLEEP
*BOOP) -BEEP)) *BEEEP+ (BEEP* BEEP*
BEEP*BEEP*BEEP*BLEEP))/ (BEEP*((BEEP*BEEP*BEEP *BEEP*BEEP*BEEP)-( BEEP+BEEP))));
}
```
Using the default operator in C# for value types allows initialization of BEEEP to zero. This way no numeric literals are used in the code. The basic algorithm is the same. but the factors are calculated inline.
[Answer]
## D
Not allowed to use the numbers 4, 8, 15, 16, 23, or 42 in my code? No problem, then I won't use numbers at all!
```
import std.stdio;
void main()
{
while( true )
{
( ',' - '(' ).writeln;
( '/' - '\'' ).writeln;
( '/' - ' ' ).writeln;
( '_' - 'O' ).writeln;
( '^' - 'G' ).writeln;
( '~' - 'T' ).writeln;
}
}
```
[Answer]
# Javascript + HTML
Anti-golf!
```
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre>
/*hereIsTheDataPart~ Es="5030000307000022
E2000000100000010000 E5370000507000022200
E0010100001110000005 E0337001010000102220
E0100010010111005033 E7001010000102220010
E1010010111~33079900 E1000111102221000001
E1110111~03037910100 E0111102220010100001
E0111".replace(/~/g, E5);Zfillfillfillfil
Eqw=21;fq=2;fz=fq*2; Efl=fz*2;fm=fl*2;fw=
Efm+2; M=Math;functi Eon r(n,i,z){return
Efunction(){l=i||''; E;for(m=0;m!=n;m++)l
E+=String.fromCharCo Ede(97+M.floor(M.ran
Edom()*26));return l E+(z||'')}};kb=r(fm,
E'/*','*'+'/');kc=r( Efw,'//');kd=r(20);Z
Eke=r(fw,'/*');kf=r( E20);kg=r(fw,'','*'+
E'/');kh=kf;ki=new Z EArray(21).join(' ')
E;x=[];for(n=35*ix;n E!=s.length;++n){x.Z
Epush(parseInt(s[n]) E)};oo=function(){oZ
E+=z==1?kb():z==9?kc E():z==3?(ee.shift()
E||kd()):z==5?(y==0? Eke():(ee.shift()||Z
Ekf())):z==7?(y==(yl E-1)?kg():(ee.shift(
E)||kh())):z==0?ki:Z Epl.shift();}Ze=mc^2
EZthis=does*nothing; EZnor*does+this-haha
EZawkw0rd+space+fi11 EZrunn1ng/out+of=stf
EZfjsddfkuhkarekhkhk 777777777777777777*/
0;ix=typeof ix=="number"?(ix+1)%6:1;s=text();ee=[];pl=[];//2
0;q=function(n,m){return s.substr(n,m)};evl="";xl=20;yl=12//
0;while(s.length){c=s[0];m=1;if(c=='\n'){s=q(1);continue;}//
0;if(c=='E'){ev=q(0,xl);i=ev.indexOf('Z');ee.push(ev);//sd//
0;evl+=i==-1?ev.substr(1):ev.substr(1, i-1);}if(c=='0'){//sd
0;pl.push(q(0,xl*3),'','');m=3};s=q(xl*m);}eval(evl);o="";//
0;for(r=0;r!=5;++r){for(y=0;y!=yl;++y){for(n=0;n!=7;++n){//s
0;z=x[n+r*7];oo()}o+="\n"}}setTimeout(function(){text(o);//z
0;(function(){var space=' ____ ',garbage='asfdasr#@%$sdfgk';
0;var filler=space+garbage+space+garbage+space+garbage;//s//
0;})("test",1199119919191,new Date(),"xyz",30/11/1)//asdfsaf
0;eval(text());},1000);//askfdjlkasjhr,kajberksbhfsdmhbkjygk
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
/*1111111111111111*/
</pre>
<script>
window.onload = function () {
setTimeout(function() {
text = function (txt) {
pre = document.getElementsByTagName('pre')[0];
if(!txt) {
return pre.innerText;
}
pre.innerText = txt;
}
eval(text());
}, 1000);
}
</script>
</body>
</html>
```
The `<pre>` element displays a number in the sequence. It also contains all the code necessary to get to the next number in the sequence. So the `<pre>` is eval'd, which results in the text of the `<pre>` being updated to resemble the next number in the sequence. This process repeats endlessly.
[Here it is in action!](http://codepen.io/anon/pen/wEBxs)
[Answer]
# C
Get your squinting goggles on :-)
```
main( i){char*s ="*)2;,5p 7ii*dpi*t1p+"
"={pi 7,i)?1!'p)(a! (ii(**+)(o(,( '(p-7rr)=pp="
"/((' (^r9e n%){1 !ii): a;pin 7,p+"
"{*sp ;'*p* op=p) in,** i+)s"
"pf/= (t=2/ *,'i% f+)0f7i=*%a (rpn"
"p(p; )ri=} niipp +}(ipi%*ti( !{pi"
"+)sa tp;}* s;}+% *n;== cw-}"
"9{ii i*(ai a5n(a +fs;i *1'7", *p=s-
1;while(p=('T'^i)?++p:s){ for(i=1;55!=* p;p++
)i+=(' '!=* p);printf ("%d ",i/ 2);}}
```
[Answer]
# Mathematica
We can answer the question by focusing on the repeating partial
denominators of the [periodic continued fraction](http://en.wikipedia.org/wiki/Periodic_continued_fraction) shown below. They are what we need.
![repeat cf](https://i.stack.imgur.com/7jzRs.png)
After all, they comprise the non-terminating sequence we are trying to produce :
4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 42 ...
---
In Mathematica one obtains the [quadratic irrational](http://en.wikipedia.org/wiki/Quadratic_irrational) corresponding to the periodic continued fraction by
```
FromContinuedFraction[{0, {4, 8, 15, 16, 23, 42}}]
```
![quad irr 1](https://i.stack.imgur.com/QgPBF.png)
where the 0 refers to the implicit integer part.
We can check by inverting the operation:
![enter image description here](https://i.stack.imgur.com/fYMw5.png)
>
> {0, {4, 8, 15, 16, 23, 42}}
>
>
>
---
The 4' s and 8' s violate one of the rules of the challenge. The substring `15` is an additional violation. We can reformat the quadratic irrational to satisfy the
rules.
![c](https://i.stack.imgur.com/A73VQ.png)
>
> {0, {4, 8, 15, 16, 23, 42}}
>
>
>
---
Now we grab the sequence of interest:
```
Last[c]
```
>
> {4, 8, 15, 16, 23, 42}
>
>
>
And print the list forever …
```
While[True, Print@Row[ContinuedFraction[(-3220235/5+Sqrt[(10611930613350/25)])/(61630/2)],"\t"]]
```
![table](https://i.stack.imgur.com/Ramlx.png)
[Answer]
## Haskell, 1 LoC
```
import Data.Char; main = putStr $ unwords $ map (show . (+)(-ord 'D') . ord) $ cycle "HLST[n"
```
I've decided to go for a readable one-liner just to show how awesome Haskell is. Also, I've decided to avoid *all* digits, just in case.
Thanks to built-in lazy evaluation, Haskell can manipulate (map, split, join, filter...) infinitely long lists just fine. It even has multiple built-ins to create them. Since a string is just a list of characters, infinitely long strings are no mystery to Haskell either.
[Answer]
# C / C++
Using only the characters `L`, `O`, `S` and `T` repeatedly in that order:
```
int main(){for(;;)printf("%d %d %d %d %d %d\n",
'L'- 'O'*'S' &'T','L' &'O'+'S'*
'T', 'L'^ 'O' |'S'* 'T'&
'L', 'O'* 'S' &'T'/ 'L'+
'O', 'S'^ 'T' &'L', 'O'*
'S'&'T' +'L'+ 'O'^'S'+ 'T') ;}
```
[Answer]
## Java
I can't find a pattern in that sequence. If there's no recognizable pattern, we might as well just throw a bunch of small primes together, cram them into Java's built-in RNG, and call it a day. I don't see how that could possibly go wrong, but then again, I'm an optimist :)
```
import java.util.Random;
public class LostNumbers {
public static void main(String[] args) {
long nut=2*((2*5*7)+1)*((2*2*3*((2*2*2*2*11)+3))+5)*
((3*5*((2*3*3)+1)*((2*2*2*2*2*3)+1))+2L);
int burner=2*2*2*5;
while(true){
Random dice = new Random(nut);
for(int i=0;i<6;i++)
System.out.print((dice.nextInt(burner)+3) + " "); // cross your fingers!
System.out.println();
}
}
}
```
[Answer]
# Bash one-liner
```
yes `curl -s "https://oeis.org/search?q=id:A$((130726+100))&fmt=text" |
grep %S | cut -d " " -f 3 | cut -d "," -f 1-6`
```
Line break added for readability. It (ab)uses the fact that these are the first six numbers of [OEIS Sequence A130826](https://oeis.org/A130826).
[Answer]
## C using no numbers at all and no character values
```
s(int x) { return x+x; }
p(int x) { return printf("%d ",x); }
main()
{
for(;;){
int a = s(p(s((s==s)+(p==p))));
int b = a+s(a+p(a+a));
putchar(b-s(p(b*a-b-s(p(s(s(p(b-(s==s))+p(b)))-(p==p))))));
}
}
```
[Answer]
I like the idea of using the sequence
```
a[n+5] = a[n] + a[n+2] + a[n+4]
```
as in [this answer](https://codegolf.stackexchange.com/a/23922/13708). Found it through the [OEIS Search](https://oeis.org/search?q=4,8,15,16,23,42) as [sequence A122115](https://oeis.org/A122115).
If we go through the sequence in reverse we will find a suitable initialization quintuple that doesn’t contain 4, 8, 15, 16 or 23.
## Python3:
```
l = [3053, 937, -1396, -1757, -73]
while l[-1] != 66:
l.append(l[-5] + l[-3] + l[-1])
while True:
print(l[-6:-1])
```
[Answer]
# JavaScript
No numbers at all is a good move. But rather than print the sequence once per pass through the loop, only print once number per pass.
```
t = "....A...B......CD......E..................FEDCBA";
b = k = --t.length;
do {
console.log(p = t.indexOf(t[k]));
} while (k-=!!(p-k)||(k-b));
```
The lower part of the string codes the numbers to print and the upper part of the string codes the next character to find. Where the two parts meet (a single `F`) codes resetting the cycle.
[Answer]
# Python
```
b=a=True;b<<=a;c=b<<a;d=c<<a;e=d<<a;f=e<<a
while a: print c,d,e-a,e,e+d-a,f+d+b
```
Bitwise operators and some simple math.
[Answer]
# Ruby
Generates the Numbers by embedding the equally mystical sequence *0, ∞, 9, 0, 36, 6, 6, 63*;
No good can come from this.
```
(0..1/0.0).each{|i|puts"kw9ygp0".to_i(36)>>i%6*6&63}
```
[Answer]
# C (54 50 chars)
I'm posting a golf answer because golfing at least makes it fun.
```
main(a){while(printf("%d\n","gAELMT"[a++%6]-61));}
```
[Answer]
## Haskell
```
main = mapM_ (print . round . go) [0..]
where
go n = 22 - 19.2*cos t + 6*cos (2*t) - 5.3*cos (3*t) + 0.5*cos (5*t)
where t = fromInteger (n `mod` 6) / 6 * pi
```
<http://ideone.com/erQfcd>
Edit: What I used to generate the coefficients: <https://gist.github.com/ion1/9578025>
Edit: I really liked [agrif’s program](https://codegolf.stackexchange.com/a/24291/1621) and ended up writing a Haskell equivalent while figuring it out. I picked a different base for the magic number.
```
import Data.Fixed
main = mapM_ print (go (369971733/5272566705 :: Rational))
where go n = d : go m where (d,m) = divMod' (59*n) 1
```
<http://ideone.com/kzL6AK>
Edit: I also liked his second program and ended up writing [a Haskell implementation of quadratic irrationals](https://github.com/ion1/quadratic-irrational) ;-). Using the library and agrif’s magic number, this program will print the sequence.
```
import qualified Data.Foldable as F
import Numeric.QuadraticIrrational
main = F.mapM_ print xs
where (_, xs) = qiToContinuedFraction n
n = qi (-16101175) 1 265298265333750 770375
```
This is how one could look for the magic number with the help of the library:
```
> continuedFractionToQI (0, Cyc [] 4 [8,15,16,23,42])
qi (-644047) 1 424477224534 30815
```
The printed value stands for the number `(−644047 + 1 √424477224534)/30815`. All you need to do is to find factors that get rid of disallowed digit sequences in the numbers while not changing the value of the expression.
[Answer]
# C#
```
var magicSeed = -1803706451;
var lottery = new Random(magicSeed);
var hurleysNumbers = new List<int>();
for (int i = 0; i < 6; i++) hurleysNumbers.Add(lottery.Next(43));
while (true) Console.WriteLine(String.Join(",", hurleysNumbers));
```
I found the seed after listening to some radio station in a flight over the pacific.
[Answer]
# Python
```
import math
def periodic(x):
three_cycle = abs(math.sin(math.pi * \
(x/float(3) + (math.cos(float(2)/float(3)*x*math.pi)-1)/9)))
two_cycle = abs(math.sin(math.pi * x / float(2)))
six_cycle = three_cycle + 2*two_cycle
return round(six_cycle, 2) # Correct for tiny floating point errors
def polynomial(x):
numerator = (312+100)*(x**5) - 3000*x*(x**3) + (7775+100)*(x**3) - \
(7955+1000)*(x**2) + (3997+1)*x + 120
denominator = float(30)
return float(numerator)/denominator
def print_lost_number(x):
lost_number = polynomial(periodic(float(x)))
print(int(lost_number)) # Get rid of ugly .0's at the end
i=0
while (1):
print_lost_number(i)
i += 1
```
While a lot of people used patterns taken from OEIS, I decided to create my own set of functions to represent the numbers.
The first function I created was periodic(). It is a function that repeats every six input numbers using the cyclical properties of the trig functions. It goes like this:
```
periodic(0) = 0
periodic(1) = 5/2
periodic(2) = 1
periodic(3) = 2
periodic(4) = 1/2
periodic(5) = 3
periodic(6) = 0
...
```
Then, I create polynomial(). That uses the following polynomial:
```
412x^5-3000x^4+7875x^3-8955x^2+3998x+120
----------------------------------------
30
```
(In my code, some of the coefficients are represented as sums because they contain the lost numbers as one of their digits.)
This polynomial converts the output of periodic() to its proper lost number, like this:
```
polynomial(0) = 4
polynomial(5/2) = 8
polynomial(1) = 15
polynomial(2) = 16
polynomial(1/2) = 23
polynomial(3) = 42
```
By constantly increasing i and passing it through both functions, I get the lost numbers repeating infinitely.
(Note: I use float() a lot in the code. This is so Python does floating-point division instead of i.e. saying 2/3=0.)
[Answer]
## Emacs Lisp 73 chars
The best way to loop forever? A cyclic list!
```
(let((a'(?\^D?\^H?\^O?\^P?\^W?*)))(setcdr(last a)a)(while(print(pop a))))
```
But wait, there's more!
?\^D is the nice way to insert the char for EOT, however if I was just submitting a file I wouldn't need the literal "\^D" I could just insert a '?' followed by an actual EOT character, thus taking the real number of needed chars down to: 63
*Edit*
I've been working on "gel" which is not a real language yet, but is basically series of emacs lisp macros for code golf. In "gel" this would be the solution:
```
(m a(~o ?\^D?\^H?\^O?\^P?\^W?*)(@(<^(^ a))(...)))
```
and without the waiting:
```
(m a(~o ?\^D?\^H?\^O?\^P?\^W?*)(@(<^(^ a))))
```
44 chars with nice character entry. Would be 34 if not for it being a web submission.
[Answer]
# Julia
By researching a while i found a mathematical way to express the sequence by other sequences without using any of the numbers (or tricky ways to use them):
```
L(n)=n==0?2:n==1?1:L(n-1)+L(n-2) #Lucas numbers.
O(n)=int(n*(n+1)*(n+2)/6)
S(n)=n in [O(i) for i=1:50]?0:1 #A014306
T(n)=begin k=ifloor(n/2);sum([L(i)*S(n+1-i) for i=1:k]) end #A025097
lost(n)=n>5?lost(n-1)+lost(n-3)+lost(n-5):(n+3)>5?T(n+3):-T(n+3) #A122115
[lost(i-2) for i=5:10]
```
Output:
```
6-element Array{Int64,1}:
4
8
15
16
23
42
```
[Answer]
## C++
A nice clean language like C++ can permit you to lay out your source in a neat and highly readable way, and has the advantage of being easy to copy out by hand with minimum ambiguity.
Here the solution is reached using only the number 1.
```
#include <iostream>
typedef long int lI;
auto &VV = std::cout;
std::string vv = " ";
int main() {
for(lI UU; UU --> UU;) {
lI l1=1l+1l;lI
ll=1l << l1;VV
<< ll << vv;lI
Il=ll*l1;VV <<
Il << vv;VV <<
ll*ll-1l << vv;
lI II=ll*ll;VV
<< II << vv;VV
<<(II += Il-1l)
<< vv;VV << l1
* (II-l1)<< vv;
}
}
```
Test: <http://ideone.com/fuOdem>
[Answer]
## Scheme (Guile)
```
(let l ((x 179531901/2199535975))
(let* ((b (* x 51)) (f (floor b)))
(format #t "~a " f)
(l (- b f))))
```
<http://ideone.com/QBzuBC>
Arguably this breaks the "don't encode the numbers in other bases" rule, but I think it's obscure enough that it doesn't count. As evidence of this obscurity, those two magic numbers in base 51 are:
```
26:27:21:9:18 / 6:19:6:19:6:19
```
*Edit*: Same trick, different representation. I actually like this one more, since it does not depend on an arbitrarily-chosen base. However, it requires a scheme implementation with infinite-accuracy support for quadratic irrationals, which (AFAIK) doesn't exist. You could implement it in something like Mathematica, though.
```
(let l ((x (/ (+ -16101175 (sqrt 265298265333750)) 770375)))
(let* ((b (/ 1 x)) (f (floor b)))
(format #t "~a " f)
(l (- b f))))
```
[Answer]
## PHP
I thought it was time someone submited a php answer, not the best but a fun one anyway
```
while(true)
{
$lost = array(
"Aaah",
"Aaaaaaah",
"Aaaaaaaaaaaaaah",
"Aaaaaaaaaaaaaaah",
"Aaaaaaaaaaaaaaaaaaaaaah",
"Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah");
foreach ($lost as $a)
{
echo strlen($a).'
';
}
}
```
the Ahs are the screams of the passengers as the plane crashes
[Answer]
# Perl
```
#!/usr/bin/perl
use Math::Trig;
$alt = 2600;
$m = 10 x 2;
$ip = 1 - pi/100;
@candidates = (
"Locke",
"Hugo",
"Sawyer",
"Sayid Jarrah",
"Jack Sh.",
"Jin-Soo Kwon"
);
@lost = map {map{ $a+=ord; $a-=($a>$alt)?($r=$m,$m=-$ip*$m,$r):$z; }/./g; $a/100 }@candidates;
for(;;) {
printf "%d\n",$_ for @lost;
}
```
] |
[Question]
[
Create the shortest program or function that finds the [factorial](http://en.wikipedia.org/wiki/Factorial) of a non-negative integer.
The factorial, represented with `!` is defined as such
$$n!:=\begin{cases}1 & n=0\\n\cdot(n-1)!&n>0\end{cases}$$
In plain English the factorial of 0 is 1 and the factorial of n, where n is larger than 0 is n times the factorial of one less than n.
Your code should perform input and output using a standard methods.
**Requirements:**
* Does not use any built-in libraries that can calculate the factorial (this includes any form of `eval`)
* Can calculate factorials for numbers up to 125
* Can calculate the factorial for the number 0 (equal to 1)
* Completes in under a minute for numbers up to 125
The shortest submission wins, in the case of a tie the answer with the most votes at the time wins.
[Answer]
## Golfscript -- 12 chars
```
{,1\{)*}/}:f
```
---
### Getting started with Golfscript -- Factorial in step by step
Here's something for the people who are trying to learn golfscript. The prerequisite is a basic understanding of golfscript, and the ability to read golfscript documentation.
So we want to try out our new tool [golfscript](http://www.golfscript.com/golfscript/index.html). It's always good to start with something simple, so we're beginning with factorial. Here's an initial attempt, based on a simple imperative pseudocode:
```
# pseudocode: f(n){c=1;while(n>1){c*=n;n--};return c}
{:n;1:c;{n 1>}{n c*:c;n 1-:n;}while c}:f
```
Whitespace is very rarely used in golfscript. The easiest trick to get rid of whitespace is to use different variable names. Every token can be used as a variable (see the [syntax](http://www.golfscript.com/golfscript/syntax.html) page). Useful tokens to use as variables are special characters like `|`, `&`, `?` -- generally anything not used elsewhere in the code. These are always parsed as single character tokens. In contrast, variables like `n` will require a space to push a number to the stack after. Numbers are essentially preinitialized variables.
As always, there are going to be statements which we can change, without affecting the end result. In golfscript, everything evaluates to true except `0`, `[]`, `""`, and `{}` (see [this](http://www.golfscript.com/golfscript/builtin.html#!)). Here, we can change the loop exit condition to simply `{n}` (we loop an additional time, and terminate when n=0).
As with golfing any language, it helps to know the available functions. Luckily the list is very short for golfscript. We can change `1-` to `(` to save another character. At present the code looks like this: (we could be using `1` instead of `|` here if we wanted, which would drop the initialization.)
>
> `{:n;1:|;{n}{n|*:|;n(:n;}while|}:f`
>
>
>
It is important to use the stack well to get the shortest solutions (practice practice practice). Generally, if values are only used in a small segment of code, it may not be necessary to store them into variables. By removing the running product variable and simply using the stack, we can save quite a lot of characters.
>
> `{:n;1{n}{n*n(:n;}while}:f`
>
>
>
Here's something else to think about. We're removing the variable `n` from the stack at the end of the loop body, but then pushing it immediately after. In fact, before the loop begins we also remove it from the stack. We should instead leave it on the stack, and we can keep the loop condition blank.
>
> `{1\:n{}{n*n(:n}while}:f`
>
>
>
Maybe we can even eliminate the variable completely. To do this, we will need to keep the variable on the stack at all times. This means that we need two copies of the variable on the stack at the end of the condition check so we don't lose it after the check. Which means that we'll have a redundant `0` on the stack after the loop ends, but that is easy to fix.
This leads us to our optimal `while` loop solution!
>
> `{1\{.}{.@*\(}while;}:f`
>
>
>
Now we still want to make this shorter. The obvious target should be the word `while`. Looking at the documentation, there are two viable alternatives -- [unfold](http://www.golfscript.com/golfscript/builtin.html#/) and [do](http://www.golfscript.com/golfscript/builtin.html#do). When you have a choice of different routes to take, try and weigh the benefits of both. Unfold is 'pretty much a while loop', so as an estimate we'll cut down the 5 character `while` by 4 into `/`. As for `do`, we cut `while` by 3 characters, and get to merge the two blocks, which might save another character or two.
There's actually a big drawback to using a `do` loop. Since the condition check is done after the body is executed once, the value of `0` will be wrong, so we may need an if statement. I'll tell you now that unfold is shorter (some solutions with `do` are provided at the end). Go ahead and try it, the code we already have requires minimal changes.
>
> `{1\{}{.@*\(}/;}:f`
>
>
>
Great! Our solution is now super-short and we're done here, right? Nope. This is 17 characters, and J has 12 characters. Never admit defeat!
---
### Now you're thinking with... recursion
Using recursion means we *must* use a branching structure. Unfortunate, but as factorial can be expressed so succinctly recursively, this seems like a viable alternative to iteration.
```
# pseudocode: f(n){return n==0?n*f(n-1):1}
{:n{n.(f*}1if}:f # taking advantage of the tokeniser
```
Well that was easy -- had we tried recursion earlier we may not have even looked at using a `while` loop! Still, we're only at 16 characters.
---
### Arrays
Arrays are generally created in two ways -- using the `[` and `]` characters, or with the `,` function. If executed with an integer at the top of the stack, `,` returns an array of that length with arr[i]=i.
For iterating over arrays, we have three options:
1. `{block}/`: push, block, push, block, ...
2. `{block}%`: [ push, block, push, block, ... ] (this has some nuances, e.g. intermediate values are removed from the stack before each push)
3. `{block}*`: push, push, block, push, block, ...
The golfscript documentation has an example of using `{+}*` to sum the contents of an array. This suggests we can use `{*}*` to get the product of an array.
```
{,{*}*}:f
```
Unfortunately, it isn't quite that simple. All the elements are off by one (`[0 1 2]` instead of `[1 2 3]`). We can use `{)}%` to rectify this issue.
```
{,{)}%{*}*}:f
```
Well not quite. This doesn't handle zero correctly. We can calculate (n+1)!/(n+1) to rectify this, although this costs far too much.
```
{).,{)}%{*}*\/}:f
```
We can also try to handle n=0 in the same bucket as n=1. This is actual extremely short to do, try and work out the shortest you can.
>
> Not so good is sorting, at 7 characters: `[1\]$1=`.
> Note that this sorting technique does has useful purposes, such as imposing boundaries on a number (e.g. `[0\100]$1=)
>
> Here's the winner, with only 3 characters: .!+
>
>
>
If we want to have the increment and multiplication in the same block, we should iterate over every element in the array. Since we aren't building an array, this means we should be using `{)*}/`, which brings us to the shortest golfscript implementation of factorial! At 12 characters long, this is tied with J!
>
> `{,1\{)*}/}:f`
>
>
>
---
### Bonus solutions
Starting with a straightforward `if` solution for a `do` loop:
```
{.{1\{.@*\(.}do;}{)}if}:f
```
We can squeeze a couple extra out of this. A little complicated, so you'll have to convince yourself these ones work. Make sure you understand all of these.
```
{1\.!!{{.@*\(.}do}*+}:f
{.!{1\{.@*\(.}do}or+}:f
{.{1\{.@*\(.}do}1if+}:f
```
A better alternative is to calculate (n+1)!/(n+1), which eliminates the need for an `if` structure.
>
> `{).1\{.@*\(.}do;\/}:f`
>
>
>
But the shortest `do` solution here takes a few characters to map 0 to 1, and everything else to itself -- so we don't need any branching. This sort of optimization is extremely easy to miss.
>
> `{.!+1\{.@*\(.}do;}:f`
>
>
>
For anyone interested, a few alternative recursive solutions with the same length as above are provided here:
```
{.!{.)f*0}or+}:f
{.{.)f*0}1if+}:f
{.{.(f*}{)}if}:f
```
---
\*note: I haven't actually tested many of the pieces of code in this post, so feel free to inform if there are errors.
[Answer]
# Python - 27
Just simply:
```
f=lambda x:0**x or x*f(x-1)
```
[Answer]
## Haskell, 17
```
f n=product[1..n]
```
[Answer]
## APL (4)
```
×/∘⍳
```
Works as an anonymous function:
```
×/∘⍳ 5
120
```
If you want to give it a name, 6 characters:
```
f←×/∘⍳
```
[Answer]
# [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 1827 1698 chars
I felt like learning a new language today, and this is what I landed on... (Why do I do this to myself?) This entry won't be winning any prizes, but it beats all 0 other answers so far using the same language!
```
Take Northern Line to Bank
Take Central Line to Holborn
Take Piccadilly Line to Heathrow Terminals 1, 2, 3
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Parsons Green
Take District Line to Bank
Take District Line to Parsons Green
Take District Line to Acton Town
Take District Line to Hammersmith
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Hammersmith
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Acton Town
Take District Line to Acton Town
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Parsons Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Temple
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Aldgate
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Bank
Take District Line to Upney
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Embankment
Take Circle Line to Embankment
Take Northern Line to Angel
Take Northern Line to Moorgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Moorgate
Take Circle Line to Moorgate
Take Northern Line to Mornington Crescent
```
[Try it online!](https://tio.run/##xVXLbgIxDLz3K3zqiUp9fAHQqhwAcVg@IASXjUjsleMK8fU0aoEthX1AUXseZzz2TJLAQo4WynRnBaNF0s0mM0uEMYvmKARDRwjK0DO0vPmE@qlKjN8jA/azxPMFTpy1Zu68X5c4Gs2FV5ChBEfGR3jowGMHniqPdG2SBBmvtqzPLqo4q@0LJkYiU4RXQayqKUe66HijhoEJASUGp/l2c06sx5LAzxdGsRkboQoX7J2a0pB@bvwbk8ItDI261KmmuK7VkczGSU841uN3mh/sq4Wt1@I535pvaT53GdMihTjqbt0XRWfMqunewSCNBa9VxrSrqhwlw1B4/O/k/WFMm5ypue/TgnB9Ie3vhdV1r7T3JcwSFNJj3Ao@etC7tEBfgY2Y5ZohOOT7ofQQPKFl90dBf/9H3X8A)
Anyone who's journeyed around London will understand that instantly of course, so I'm sure I don't need to give a full explanation.
Most of the work at the start is in handling the 0 case. After initialising the product at 1, I can use that to calculate max(input, 1) to get the new input, taking advantage of the fact that 0! = 1! Then the main loop can begin.
(EDIT: A whole bunch of trips have been saved by stripping the 1 from "Heathrow Terminals 1, 2, 3" instead of generating it by dividing 7 (Sisters) by itself. I also use a cheaper method to generate the -1 in the next step.)
Decrementing is expensive in Mornington Crescent (although less expensive than the Tube itself). To make things more efficient I generate a -1 by taking the NOT of a parsed 0 and store that in Hammersmith for much of the loop.
---
I put some significant work into this, but since this is my first attempt at golfing in Mornington Crescent (in fact my first attempt in *any* language), I expect I missed a few optimisations here and there. If you're interested in programming in this language yourself (and why wouldn't you be?), [Esoteric IDE](https://github.com/Timwi/EsotericIDE/) - with its debug mode and watch window - is a must!
[Answer]
# [J](http://jsoftware.com/), 12 bytes
A standard definition in J:
```
f=:*/@:>:@i.
```
[Try it online!](https://tio.run/##y/r/P83WSkvfwcrOyiFT739qcka@QpqCocF/AA "J – Try It Online")
Less than 1sec for 125!
Eg:
```
f 0
1
f 5
120
f 125x
1882677176888926099743767702491600857595403
6487149242588759823150835315633161359886688
2932889495923133646405445930057740630161919
3413805978188834575585470555243263755650071
31770880000000000000000000000000000000
```
[Answer]
## Golfscript - 13 chars **(SYM)**
defines the function `!`
```
{),()\{*}/}:! # happy robot version \{*}/
```
alternate 13 char version
```
{),()+{*}*}:!
```
whole program version is **10 chars**
```
~),()+{*}*
```
testcases take less than 1/10 second:
**input:**
```
0!
```
**output**
```
1
```
**input**
```
125!
```
**output**
```
188267717688892609974376770249160085759540364871492425887598231508353156331613598866882932889495923133646405445930057740630161919341380597818883457558547055524326375565007131770880000000000000000000000000000000
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
:p
```
Explained:
```
: % generate list 1,2,3,...,i, where i is an implicit input
p % calculate the product of of all the list entries (works on an empty list too)
```
[Try it online!](https://tio.run/##y00syfn/36rg/3@T/wA "MATL – Try It Online")
[Answer]
## Perl 6: 13 chars
```
$f={[*]1..$_}
```
`[*]` is same as Haskell `product`, and `1..$_` is a count-up from 1 to `$_`, the argument.
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
f=lambda x:x/~x+1or x*f(x-1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRocKqQr@uQtswv0ihQitNo0LXUPN/QVFmXolGmoahgabmfwA "Python 2 – Try It Online")
(based off Alexandru's solution)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 85 bytes
```
BigInteger f(int n){return n<2?BigInteger.ONE:new BigInteger(""+n).multiply(f(n-1));}
```
[Try it online!](https://tio.run/##RY7BCsIwDIbve4qwU4sY1KMKguDBg3rwCarW2dlmo80mY@zZayfC/luSj/9LqVo1Lx/vaFxdeYYyzegUv3BviiOxLrTfZNndqhDgpAxBn0FKYMXmDnGi4CkMMZDsvebGE9B2tZvOeDkf1qQ/MK1Ens9Iomssm9p24ilovpRyM8TRUDc3mwx/UVuZB7jkF1f2hgpEBOWLIP//jLl2gbXDqmGsE8OWUuVykRp/yJAN8Qs "Java (JDK) – Try It Online")
[Answer]
# Matlab, 15
```
f=@(x)prod(1:x)
```
Test Cases
```
>> f(0)
ans =
1
>> f(4)
ans =
24
>> tic,f(125),toc
ans =
1.8827e+209
Elapsed time is 0.000380 seconds.
```
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 26 bytes
There's no inbuilt product function in F#, but you can make one with a [fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))
```
let f n=Seq.fold(*)1{1..n}
```
[Try it online!](https://tio.run/##SyvWTc4vSv3/Pye1RCFNIc82OLVQLy0/J0VDS9Ow2lBPL6/2f0FRZl5JWp6CkmqKkoJGmoahgabmfwA "F# (.NET Core) – Try It Online")
[Answer]
## JavaScript, 25
```
function f(n)!n||n*f(n-1)
```
## CoffeeScript, 19
```
f=(n)->!n||n*f(n-1)
```
Returns `true` in the case of n=0, but JavaScript will type-coerce that to 1 anyway.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
f=->n{n>1?n*f[n-1]:1}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/O0D5PKy06T9cw1sqw9n9BaUmxQlq0oUHsfwA "Ruby – Try It Online")
## Test
```
irb(main):009:0> f=->n{n>1?n*f[n-1]:1}
=> #<Proc:0x25a6d48@(irb):9 (lambda)>
irb(main):010:0> f[125]
=> 18826771768889260997437677024916008575954036487149242588759823150835315633161
35988668829328894959231336464054459300577406301619193413805978188834575585470555
24326375565007131770880000000000000000000000000000000
```
[Answer]
# PostScript, 26 chars
```
/f{1 exch -1 1{mul}for}def
```
Example:
```
GS> 0 f =
1
GS> 1 f =
1
GS> 8 f =
40320
```
The function itself takes only 21 characters; the rest is to bind it to a variable. To save a byte, one can also bind it to a digit, like so:
```
GS> 0{1 exch -1 1{mul}for}def
GS> 8 0 load exec =
40320
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~7~~ 6 bytes
By making a range and multiplying it
-1 byte tanks to ovs having the idea to use the max() function
```
;1⌉⟦₁×
```
## Explanation
```
;1 -- If n<1, use n=1 instead (zero case)
⟦₁ -- Construct the range [1,n]
× -- return the product of said range
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39rwUU/no/nLHjU1Hp7@/7/p/ygA "Brachylog – Try It Online")
---
# [Brachylog](https://github.com/JCumin/Brachylog), ~~10~~ 9 bytes
recursion
```
≤1|-₁↰;?×
```
## Explanation
```
--f(n):
≤1 -- if n ≤ 1: return 1
| -- else:
-₁↰ -- f(n-1)
;?× -- *n
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnEsMa3UdNjY/aNljbH57@/7@hwf8oAA "Brachylog – Try It Online")
[Answer]
# Ruby - ~~30~~ 29 characters
```
def f(n)(1..n).inject 1,:*end
```
Test
```
f(0) -> 1
f(5) -> 120
```
[Answer]
# Javascript, ES6 17
```
f=n=>n?n*f(n-1):1
```
ES6:
* Arrow function
[Answer]
# C#, 20 or 39 characters depending on your point of view
As a traditional instance method (39 characters; [tested here](http://rextester.com/XER29007)):
```
double f(int x){return 2>x?1:x*f(x-1);}
```
As a lambda expression (20 characters, but see disclaimer; [tested here](http://rextester.com/HEAQRN39064)):
```
f=x=>2>x?1:x*f(x-1);
```
We have to use `double` because [125! == 1.88 \* 10209](http://www.wolframalpha.com/input/?i=125!), which is much higher than [`ulong.MaxValue`](https://msdn.microsoft.com/en-us/library/system.uint64.maxvalue(v=vs.110).aspx).
### Disclaimer about the lambda version's character count:
If you recursion in a C# lambda, you obviously have to store the lambda in a named variable so that it can call itself. But unlike (e.g.) JavaScript, a self-referencing lambda must have been declared **and initialized** on a previous line. You can't call the function in the same statement in which you declare and/or initialize the variable.
In other words, [this doesn't work](http://rextester.com/DEV6527):
```
Func<int,double> f=x=>2>x?1:x*f(x-1); //Error: Use of unassigned local variable 'f'
```
But [this does](http://rextester.com/JFV25693):
```
Func<int,double> f=null;
f=x=>2>x?1:x*f(x-1);
```
There's no good reason for this restriction, since `f` can't ever be unassigned at the time it runs. The necessity of the `Func<int,double> f=null;` line is a quirk of C#. Whether that makes it fair to ignore it in the character count is up to the reader.
# CoffeeScript, 21 19 characters for real
```
f=(x)->+!x||x*f x-1
```
**Tested here:** <http://jsfiddle.net/0xjdm971/>
[Answer]
# [Aheui (esotope)](https://github.com/aheui/pyaheui), ~~93~~ ~~90~~ 87 bytes
```
박밴내색뱅뿌뮹
숙쌕빼서빼처소
타뿌싼때산쑥희
매차뽀요@어몽
```
[Try it online!](https://tio.run/##AWMAnP9haGV1af//67CV67C064K07IOJ67GF67@M6665CuyImeyMleu5vOyEnOu5vOyymOyGjArtg4Drv4zsi7zrlYzsgrDskaXtnawK66ek7LCo672A7JqU77yg7Ja066q9//8xMjU "Aheui (esotope) – Try It Online")
Nice, small, and fast code. Slightly golfed after writing explanation. I'll not change it, because it is just same code.
# Explaination
Aheui is befunge-like language and (almost) every character of Aheui is operator. Part of character looks like `ㅏ, ㅐ, ㅓ, ㅜ, ㅛ, ㅗ, ㅢ` determines direction where next operator execute. `ㅏ` is left-to-right, `ㅓ` is right-to-left, `ㅗ` is down-to-up, `ㅜ` is up-to-down, `ㅛ` is down-to-up, with skipping one character in two characters. `ㅐ` is 'nothing' : keep same speed and direction.
```
박밴내
```
`ㅂ` commend is store given number in current stack, `ㄴ` commend is divide upmost two number in current stack. Both `박` and `백` store 2, so `박밴내` store 1 in current stack(default `아` or `nothing` stack)
```
색뱅
```
`ㅅ` commend change current stack. `색` change stack to `악` (or `ㄱ`) stack. `ㅂ` commend with `ㅇ` (like `뱅` or `방`) get a number from STDIN. So `색뱅` get a number and store it in stack `악(ㄱ)`.
```
뿌
처
```
`ㅃ` commend duplicate upmost value in current stack, and `ㅊ` commend pop value from current stack and see if it is 0. If it is, it go to opposite direction from `ㅓ` indicate : in here right-to-left. If it is not, it go to direction where `ㅓ` indicate. So `뿌(\n)처` see if input is 0 or not, and go right if zero, and go left if not.
```
망희
소
```
If input is zero, here is evaluated. (from `소` commend) First, change current stack to `nothing`(`아`). `ㅁ` commend is pop, and if used with `ㅇ` it print value as number. `희` halts program. So it print 1 and halt.
```
숙쌕빼서빼
타뿌싼때산쌕꾸
매차뽀요애애어
```
[![enter image description here](https://i.stack.imgur.com/PA8hr.png)](https://i.stack.imgur.com/PA8hr.png)
Look at this image for help. Here is main loop.
`ㅌ` is subtraction, and `ㄸ` is multiply. `ㅆ` move value from current stack to selected one.
Put it shortly, it get number from `nothing` stack(or get 1), subtract to find if it is zero, and if not zero multiply and restart loop.
And if zero, go to rightmost place of code with popping one number.
```
몽
```
Print number, then pointer go to `희` : halt.
In one image :
[![AheuiChem image translated](https://i.stack.imgur.com/8nfNl.png)](https://i.stack.imgur.com/8nfNl.png)
SEL is select, MOV is move, DUP is duplicate. This image is produced by [AheuiChem](http://yoo2001818.github.io/AheuiChem/), Aheui development tool in Korean. Translated with paint tool of windows.
[Answer]
# [8088](https://en.wikipedia.org/wiki/Intel_8088) / [8087](https://en.wikipedia.org/wiki/Intel_8087) machine code, 13 bytes
```
D9 E8 FLD1 ; start with 1
E3 08 JCXZ DONE ; if N = 0, return 1
FACT_LOOP:
51 PUSH CX ; push current N onto stack
8B F4 MOV SI, SP ; SI to top of stack for N
DE 0C FIMUL WORD PTR[SI] ; ST = ST * N
59 POP CX ; remove N from stack
E2 F8 LOOP FACT_LOOP ; decrement N, loop until N = 0
DONE:
C3 RET ; return to caller
```
Input **\$n\$** is in `CX`, output **\${n!}\$** is in `ST(0)`.
Test output displayed using Borland Turbo Debugger 3:
**n = 1:**
[![enter image description here](https://i.stack.imgur.com/M46YW.png)](https://i.stack.imgur.com/M46YW.png)
**n = 15:**
[![enter image description here](https://i.stack.imgur.com/3pLeB.png)](https://i.stack.imgur.com/3pLeB.png)
**n = 50:**
[![enter image description here](https://i.stack.imgur.com/TsvIA.png)](https://i.stack.imgur.com/TsvIA.png)
**n = 125:**
[![enter image description here](https://i.stack.imgur.com/LVXDC.png)](https://i.stack.imgur.com/LVXDC.png)
**Notes:**
* Calculates \${125!}\$ in an imperceptible amount of time (difficult to accurately profile in DOS)
* Language is not newer than the challenge
[Answer]
# C (39 chars)
```
double f(int n){return n<2?1:n*f(n-1);}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
RP
```
[Try it online!](https://tio.run/##y0rNyan8/z8o4P///6YA "Jelly – Try It Online")
Alternatively, a builtin answer is one byte:
```
!
```
[Try it online!](https://tio.run/##y0rNyan8/1/x////pgA "Jelly – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes
```
x=input();forstep(y=x-1,1,-1,x=x*y);print(x);
```
[Try it online!](https://tio.run/##K0gsytRNL/j/v8I2M6@gtERD0zotv6i4JLVAo9K2QtdQx1AHSFTYVmhValoXFGXmlWhUaFr//w8A "Pari/GP – Try It Online")
[Answer]
# D: 45 Characters
```
T f(T)(T n){return n < 2 ? 1 : n * f(n - 1);}
```
More legibly:
```
T f(T)(T n)
{
return n < 2 ? 1 : n * f(n - 1);
}
```
A cooler (though longer version) is the templatized one which does it all at compile time (**64 characters**):
```
template F(int n){static if(n<2)enum F=1;else enum F=n*F!(n-1);}
```
More legibly:
```
template F(int n)
{
static if(n < 2)
enum F = 1;
else
enum F = n * F!(n - 1);
}
```
Eponymous templates are pretty verbose though, so you can't really use them in code golf very well. D's already verbose enough in terms of character count to be rather poor for code golf (though it actually does *really* well at reducing overall program size for larger programs). It's my favorite language though, so I figure that I might as well try and see how well I can get it to do at code golf, even if the likes of GolfScript are bound to cream it.
[Answer]
## PowerShell – 36
Naïve:
```
filter f{if($_){$_*(--$_|f}else{1}}
```
Test:
```
> 0,5,125|f
1
120
1,88267717688893E+209
```
[Answer]
## Scala, 39 characters
```
def f(x:BigInt)=(BigInt(1)to x).product
```
Most of the characters are ensuring that `BigInt`s are used so the requirement for values up to 125 is met.
[Answer]
## PowerShell, 42 bytes
(saved 2 chars using *filter* instead of *function*)
```
filter f($x){if(!$x){1}else{$x*(f($x-1))}}
```
Output:
```
PS C:\> f 0
1
PS C:\> f 5
120
PS C:\> f 1
1
PS C:\> f 125
1.88267717688893E+209
```
[Answer]
# Racket (scheme) 40 35 29 bytes
Computes 0! to be 1, and computes 125! in 0 seconds according to timer. Regular recursive approach
```
(define(f n)(if(= n 0)1(* n(f(- n 1)))))
```
New version to beat common lisp: multiplies all elements of a list (same as that Haskell solution)
```
(λ(n)(apply *(build-list n add1)))
```
Newer version to beat the other scheme solution and math the other racket solution by using foldl instead of apply and using range instead of buildlist
```
(λ(n)(foldl * n(range 1 n)))
```
] |
[Question]
[
[![Dilbert is awesome](https://i.stack.imgur.com/eOwqR.gif)
source: Dilbert, September 8, 1992](http://dilbert.com/strips/comic/1992-09-08/)
I'm hoping to add a new twist on the classic "Hello World!" program.
Code a program that outputs `Hello World!` without:
* String/Character literals
* Numbers (any base)
* Pre-built functions that return "Hello World!"
* RegEx literals
With the exceptions of "O"† and 0.
†"O" is capitalized, "o" is not acceptable.
[Answer]
## C, 327 chars
```
#define O(O)-~O
#define OO(o)O(O(o))
#define Oo(o)OO(OO(o))
#define oO(o)Oo(Oo(o))
#define oo(o)oO(oO(o))
#define O0 putchar
main() {
O0(OO(oO(!O0(~O(Oo(OO(-O0(~O(Oo(-O0(O(OO(O0(oo(oO(O0(O(oo(oO(OO(Oo(oo(oO(
O0(oo(oo(!O0(O(OO(O0(O0(O(OO(Oo(O0(O(Oo(oo(oO(O0(oo(oo(oO(oo(oo(0))))))))
))))))))))))))))))))))))))))))))))))));
}
```
Strangely, it does't lose its beauty after preprocessing:
```
main() {
putchar(-~-~-~-~-~-~-~-~-~-~!putchar(~-~-~-~-~-~-~-~-putchar(~-~-~-~-~-~-
putchar(-~-~-~putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~putchar(
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~putchar(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
-~-~-~-~-~-~-~-~-~-~-~-~-~!putchar(-~-~-~putchar(putchar(-~-~-~-~-~-~-~putchar
(-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~putchar(-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0))))))))))));
}
```
[Answer]
## Windows PowerShell, *way too much*
Yes, indeed, back in the day we had to write a »Hello world« using (almost exclusively) zeroes ...
```
&{-join[char[]]($args|% Length)} `
O00000000000000000000000000000000000000000000000000000000000000000000000 `
O0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O0000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 `
O00000000000000000000000000000000
```
On a more serious note:
## Windows PowerShell, 25
```
Write-Host Hello World!
```
No string literal. The `Hello World!` in there just happens to be *parsed* as a string since PowerShell is in argument parsing mode there.
[Answer]
## BrainFuck, 102 ~~111~~ characters
```
++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>>---.+++++++..+++.>.<<-.>.+++.------.--------.>+.
```
Meets all of the rules.
Credit goes to [Daniel Cristofani](http://www.hevanet.com/cristofd/brainfuck/short.b).
[Answer]
# C, 182 bytes
```
#define decode(c,o,d,e,g,O,l,f) e##c##d##o
#define HelloWorld decode(a,n,i,m,a,t,e,d)
#define Puzzles(flog) #flog
#define CodeGolf Puzzles(Hello World!)
HelloWorld(){puts(CodeGolf);}
```
[Answer]
## C program - 45
(cheating)
Lexically, this doesn't use any string literals or regex literals. It takes advantage of the [stringification](http://gcc.gnu.org/onlinedocs/cpp/Stringification.html) feature of the C preprocessor. `s(x)` is a macro that turns its argument into a string.
```
#define s(x)#x
main(){puts(s(Hello World!));}
```
[Answer]
# [Unary](http://esolangs.org/wiki/Unary), ~~10197~~ 1137672766964589547169964037018563746793726105983919528073581559828 bytes
I'm surprised that no one's done this yet...
It's too long to post here, but it's **1137672766964589547169964037018563746793726105983919528073581559828** zeroes.
Or, more easily read: ***~1067*** zeroes.
[Thanks to @dzaima for saving 10197 bytes](https://chat.stackexchange.com/transcript/message/46201745#46201745)
[Answer]
## Haskell - 143 characters
```
o%y=o.o.o$y;o&y=(o%)%y;o!y=o$o$(o%)&y
r=succ;w=pred;a=r%y;e=r$w&l;l=r!'O';o=r e;u=(w&)&a;y=r%l
main=putStrLn[w!o,o,l,l,y,w u,w$r&'O',y,a,l,e,u]
```
oy, that was woolly!
No numbers, no numeric operations, variables renamed for amusement.
Some exposition might be nice:
* `o%y`, `o&y`, and `o!y` each applies the function `o` to `y` multiple times: 3, 9, and 29 times respectively. 29?!?! Yes, 29!
* `r` and `w` are next and previous character, which when applied using the above higher- order functions can be made to get all the characters needed from `'O'`.
The sequence of jumps needed is:
```
'O' +29 -> 'l'
'O' +9 -1 -> 'W'
'l' -9 +1 -> 'd'
'l' +3 -> 'o'
'd' +1 -> 'e'
'o' +3 -> 'r'
'e' -29 -> 'H'
'r' -81 -> '!'
'!' -1 -> ' '
```
---
* Edit: (134 -> 144) Forgot to output an exclamation point, sigh....
* Edit: (144 -> 143) Removed a unnecessary `$`, renamed `#` to `!` for Hugs.
[Answer]
## Mathematica 12 chars
Only symbols, no strings.
```
Hello World!
```
The ! is a factorial operator, but as the symbols Hello and World are undefined, returns the input unchanged.
If we modify the program a bit:
```
Hello=2;
World=3;
Hello World!
```
Then it prints `12` (2 \* 3!)
[Answer]
## i386 assembly (Linux, gcc syntax), ~~440~~ ~~442~~ 435
Today's my assembly day, and after that I'll have had enough for a while. ~~I allowed myself number 128, see below program for discussion of why.~~ Nothing extraordinary: I'm just encoding "Hello World!" as assembly opcodes where that made sense without numeric constants, and filled in the rest with arithmetic.
```
#define M mov
M $0,%ecx;inc %cx;M %ecx,%ebx;inc %cx;M %ecx,%eax;add %ax,%ax
M %ecx,%edx;shl %cl,%dx;M (e),%ch;add %dl,%ch;dec %ch;M %ch,(l)
M %ch,(j);M %ch,(z);M $0,%ch;shl %cl,%edx;M %dl,(s);inc %dl
M %dl,(b);M (o),%dl;M %dl,(u);add %al,%dl;dec %dl;M %dl,(r)
M $m,%ecx;M $n,%edx;int $c;M %ebx,%eax;M $0,%ebx;int $c
.data
m:dec %eax;e:gs;l:es;j:es;o:outsl (%esi),(%dx)
s:es;push %edi;u:es;r:es;z:es;fs;b:es;n=.-m
t=(n+n)/n;c=t<<(t*t+t)
```
(assemble with `gcc -nostartfiles hello.S -o hello`, possibly `-m32` depending on your arch)
~~Why the tolerance for 128? I need syscalls to actually show anything; Linux syscalls are on INT 80h (128 decimal); the only operand format for INT is immediate, so it's not possible to have anything else than a constant (to the code) there. I *could* (after I get sober) attempt to express it as a function of other symbolic constants in the code, likely *n*, but that's getting *very* boring for not much gain. I read the constraint on numbers as a way to prevent ASCII coding, and that's definitely not what I'm doing here, so I feel innocent enough to submit this. (FWIW, I also tried self-modifying code, but that segfaulted)~~ There's now no 128 left either. The code's pure!
* **Edit1** reformatted to save lines; removed a numeric 1 (nobody
noticed?!)
* **Edit2** compressed `mov` with CPP macros; eliminated the remaining 128.
[Answer]
# Javascript - 305
A bit long but I like the method used.
```
O=0;O++;O=O.toString();alert([O+0+0+O+0+0+0,0+O+O+0+0+O+0+O,O+O+0+O+O+0+0,O+O+0+O+O+0+0,O+O+0+O+O+O+O,O+0+0+0+0+0,O+0+O+0+O+O+O,O+O+0+O+O+O+O, O+O+O+0+0+O+0,O+O+0+O+O+0+0,O+O+0+0+O+0+0,O+0+0+0+0+O].map(function(e){O=0;O++;O++;return String.fromCharCode(parseInt(e,O))}).reduce(function (a,b){return a+b}))
```
[Answer]
# C# (131 chars)
~~141 chars~~ ~~142 chars~~
```
enum X{Hello,World,A,B=A<<A<<A}class Y{static void Main(){var c=(char)X.B;System.Console.Write(X.Hello.ToString()+c+++X.World+c);}}
```
Readable:
```
// Define some constants (B = 32)
enum X { Hello, World, A, B = A << A << A }
class Y
{
static void Main()
{
// Generate the space (character #32)
var c = (char) X.B;
// Remember that “!” is character #33
System.Console.Write(X.Hello.ToString() + c++ + X.World + c);
}
}
```
[Answer]
# JavaScript, 88
```
t=!0<<-~-~-~-~!0
r=[]
for(i in{Hello:"O",World:0})r+=i+String.fromCharCode(t++)
alert(r)
```
99
### Many thanks to @Timwi for the suggestions
removed ternary operator:
```
o={Hello:"O",World:0}
t=!0<<-~-~-~-~!0
c=String.fromCharCode
r=c(0)
for(i in o)r+=i+c(t++)
alert(r)
```
103
aliased `String.fromCharCode`
```
o={Hello:"O",World:0}
t=!0<<-~-~-~-~!0
c=String.fromCharCode
for(i in o)o[i]?r=i+c(t):alert(r+i+c(++t))
```
117
Switched if-else to ternary operator
```
o={Hello:"O",World:0},t=!0<<-~-~-~-~!0
for(i in o)o[i]?r=i+String.fromCharCode(t):alert(r+i+String.fromCharCode(++t))
```
125
I'm keeping the `"O"` just to have an "O" in the program.
```
o={Hello:"O",World:0},t=!0<<-~-~-~-~!0
for(i in o)if(o[i])r=i+String.fromCharCode(t)
else alert(r+i+String.fromCharCode(++t))
```
133
```
o={Hello:"O",World:0},t=!0<<(!0+!0<<!0)+!0
for(i in o)if(o[i])r=i+String.fromCharCode(t)
else r+=i+String.fromCharCode(t+!0)
alert(r)
```
[Answer]
# Brainfuck, 111 bytes
```
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++
.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.
------.--------.>+.>.
```
## Algorithm explained
```
Increment cell 0 to 10 (it will be loop counter)
Repeat 10 times ; will stop at cell 0
Increment cell 1 to 7
Increment cell 2 to 10
Increment cell 3 to 3
Increment cell 4 to 1
Increment cell 1 by 2 and output it ; Thus, output ASCII 72 'H'
etc. for all symbols in 'Hello World!'
```
## Longer version without loop, 389 bytes:
```
+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.+++++++++++++++++
++++++++++++.+++++++..+++.-------------------
---------------------------------------------
---------------.+++++++++++++++++++++++++++++
++++++++++++++++++++++++++.++++++++++++++++++
++++++.+++.------.--------.------------------
---------------------------------------------
----.-----------------------.
```
[Answer]
## GolfScript, 63 chars
```
[0))):O.)?O.*-.O.?+)).O.*+((..O+.O(.O+?.O-O*@.O+O.+$.O.*-).O/]+
```
What, no GolfScript entry yet?
This one uses a single numeric literal `0` and a variable named `O` (which is used to store the number `3`). Everything else is arithmetic and stack manipulation. The string `Hello World!` is built up from its ASCII codes, character by character.
### Here's how it works:
```
[ # insert start-of-array marker
0))):O # increment 0 thrice to get 3, and save it in the variable O
.)?O.*- # calculate 3^(3+1) - 3*3 = 81 - 9 = 72 = "H"
.O.?+)) # calculate 72 + 3^3 + 1 + 1 = 72 + 27 + 2 = 101 = "e"
.O.*+(( # calculate 101 + 3*3 - 1 - 1 = 101 + 9 - 2 = 108 = "l"
. # ...and duplicate it for another "l"
.O+ # calculate 108 + 3 = 111 = "o"
. # ...and duplicate it for later use
O(.O+? # calculate (3-1)^(3-1+3) = 2^5 = 32 = " "
.O-O* # calculate (32 - 3) * 3 = 29 * 3 = 87 = "W"
@ # pull the second 111 = "o" to the top of the stack
.O+ # calculate 111 + 3 = 114 = "r"
O.+$ # copy the (3+3 = 6)th last element on the stack, 108 = "l", to top
.O.*-) # calculate 108 - (3*3) + 1 = 108 - 9 + 1 = 100 = "d"
.O/ # calculate int(100 / 3) = 33 = "!"
] # collect everything after the [ into an array
+ # stringify the array by appending it to the input string
```
[Answer]
## Python (126 130)
```
O=ord("O")
N=O/O
T=N+N
R=N+T
E=T**R
E<<T
print'O'[0].join(chr(c+O)for c in[N-E,E*R-T,_-R,_-R,_,N-_-E-E,E,_,_+R,_-R,E*R-R,T-_-E-E])
```
[Answer]
### QR with halfblocks ~~(169)~~ 121 characters
With QR-Code by using UTF-8 Half-blocks characters:
```
▗▄▄▄▗▄▖▗▄▄▄
▐▗▄▐▝█▙▐▗▄▐
▐▐█▐▝▄ ▐▐█▐
▐▄▄▟▗▗▗▐▄▄▟
▗▗▖▄▞▝ ▗ ▖▄
▟▜ Code ▀▟
▙▀ Golf ▘▚
▗▄▄▄▐▗▘▟▙▝▝
▐▗▄▐▝▀▛▘▘█▖
‚ñê‚ñê‚ñà‚ñê‚ñê‚ññ‚ñê‚ñù‚ññ‚ñú‚ñò
▐▄▄▟▗ ▌█▛▗▝ 3
```
Unfortunely, this won't render nicely there. There is a little snippet with appropriate style sheet, but.. No! The language presented here is **not** HTML! Language presented here is [QR Code](https://en.wikipedia.org/wiki/QR_code)! (HTML and CSS is used here only to work around presentation bug!)
```
body {
font-family: monospace;
line-height:97%;
}
```
```
▗▄▄▄▗▄▖▗▄▄▄  <br>
▐▗▄▐▝█▙▐▗▄▐  <br>
▐▐█▐▝▄ ▐▐█▐  <br>
▐▄▄▟▗▗▗▐▄▄▟  <br>
▗▗▖▄▞▝ ▗ ▖▄  <br>
 ▟▜ Code ▀▟  <br>
 ▙▀ Golf ▘▚  <br>
▗▄▄▄▐▗▘▟▙▝▝  <br>
▐▗▄▐▝▀▛▘▘█▖  <br>
▐▐█▐▐▖▐▝▖▜▘  <br>
▐▄▄▟▗ ▌█▛▗▝  <br>
             <br>
```
### QR with halfblocks (169)
```
▛▀▀▌▚▝▐▀▌▛▀▀▌
‚ñå‚ñà‚ñå‚ñå‚ññ‚ñû‚ñö‚ñö‚ñò‚ñå‚ñà‚ñå‚ñå
▌▀▘▌ ▚▛▞ ▌▀▘▌
▀▀▀▘▚▌▙▘▌▀▀▀▘
▄▙▛▚▜▀▄▀█▖▝▄▌
▖▄▄▘▖▄▄▄▟▗ ▀▘
‚ñúCode‚ÄÉ‚ÄÉgolf!‚ñå
▚▟▘▘▝▙▛▚▐▀▖▜▘
▘▘ ▀▛▗▚▗▛▀▌▄ 
▛▀▀▌▟▌▜▖▌▘█▐▘
‚ñå‚ñà‚ñå‚ñå‚ñò‚ñà‚ñå‚ñü‚ñà‚ñú‚ñô‚ñê‚ÄÉ
▌▀▘▌▚▌▌█▗▝▌▚▘
▀▀▀▘ ▝▘▘▀▀▀▀▘
```
Idealy, this could look like:
![QR:Hello World!](https://i.stack.imgur.com/INyyi.png)
[Answer]
# J, 250
```
oo=:#a.
o0=:<.o.^0
o0o=:%:%:%:oo
ooo=:p:^:(-*oo)
o=:<.(^^^0)*(^^0)*(^^0)
o00=:o,~(,[)o0(**(**[))o0o
oo0=:*/p:(!0),>:p:!0
echo u:(o0(**(**]))o0o),(ooo ooo ooo(o.o.^^^0)*oo),o00,(+:%:oo),(oo0-~!p:>:>:0),o,(<.-:o.o.^o.^0),(>:p:(]^])#o00),(*:#0,#:oo),oo0
```
I had entirely too much fun with this one, and I learned a little bit more J to boot. Also, `ooo ooo ooo` may be the stupidest code I've ever written.
[Answer]
# [ForWhile](https://esolangs.org/wiki/ForWhile) 22 bytes
`!dlroW olleH{}+~(~~@#)`
uses ForWhiles ability to read its own source code
[online Interpreter](https://bsoelch.github.io/OneChar.js/?lang=forwhile&src=IWRscm9XIG9sbGVIe30rfih-fkAjKQ==)
# Explanation
`!` invert empty stack, will push one
`dlroW olleH` no-ops (all letters and white spaces are interpreted as comments)
`{}` empty procedure, push current instruction pointer (`-14`)
`+~` add one and flip bits (`12` length of the string)
`(~~@#)` print the first 12 characters of the program (stored at address `-1` to `-12`)
[Answer]
## Lua 144 97 86 chars
A different approach, based on the fact that table keys are also strings, and the fact that #Hello == #World == 32 == string.byte'\n'
```
e=#"O"t=e+e for k,v in pairs{Hello=0,World=e}do T=t^#k io.write(k,string.char(T+v))end
```
**145 char solution**
* no strings except "O" or 0
* no Regexes
* no pre-built functions
Did delta encoding of the bytes, then some primenumbers etc etc :)
Golfed version:
```
e=#"O"d=e+e t=d+e v=d+t z=v+t T=t^d*d^t n=0 for l,m in pairs{T,T/t-z,z,0,d,-T-z,z*z+t*d,T/d,d,-d*t,-t^d,-T+v}do n=n+m io.write(string.char(n))end
```
Commented:
```
-- without numbers, strings, regex
-- except "O" and 0
e=#"0"
t=e+e --2
d=t+e -- 3
v=d+t -- 5
z=v+t -- 7
n=0
T=t^d*d^t -- 72 = 2^3+3^2
for l,m in pairs{T, --72
T/t-z, -- 29 = 72/2-7
z, --7
0, -- 0
d, -- 3
-T-z, -- -79 = -72 - 7
z*z+t*d, -- 55 = 7*7 + 2*3
T/d, -- 24 = 72/3
d, -- 3
-d*t, -- -6
-t^d, -- -8
-T+v -- -67 = -72+5
} do
n=n+q[k]
io.write(string.char(n))
end
```
**Edit:** Changed multiple O strings, and found some more optimalisations.
[Answer]
## Scala (357 423 361 characters)
Not the shortest answer, unfortunately, but hoping to get bonus marks for the most use of `'O'` and `'0'`
```
def h(){type t=scala.Char;def OO(c:t)={(c-('O'/'O')).toChar};def O(c:t)={OO(OO(OO(c)))};def O00(c:t)={(c+('O'/'O')).toChar};def O0(c:t)={O00(O00(O00(c)))};val l=O('O');val z=O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(0)))))))))));print(OO(O(O('O'))).toString+(OO(O(O(O('O')))).toString+l+l+'O'+OO(z)+O0(O0(O0(OO('O'))))+'O'+O0('O')+l+OO(OO(O(O(O('O')))))+z).toLowerCase)}
```
Previously:
```
def h(){type t=scala.Char;print(OO(O(O('O'))).toString+(OO(O(O(O('O')))).toString+O('O')+O('O')+'O'+OO(O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(0))))))))))))+O0(O0(O0(OO('O'))))+'O'+O0('O')+O('O')+OO(OO(O(O(O('O')))))+O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(O0(0)))))))))))).toLowerCase);def OO[Char](c:t)={(c-('O'/'O')).toChar};def O[Char](c:t)={OO(OO(OO(c)))};def O00[Char](c:t)={(c+('O'/'O')).toChar};def O0[Char](c:t)={O00(O00(O00(c)))}}
```
Old (illegal) version:
```
def h(){type t=scala.Char;print(""+OO(O(O('O')))+(""+OO(O(O(O('O'))))+O('O')+O('O')+'O'+OO(O(O(O(O(O('0'))))))+O0(O0(O0(OO('O'))))+'O'+O0('O')+O('O')+OO(OO(O(O(O('O')))))+O(O(O(O(O('0')))))).toLowerCase);def O0[Char](c:t)={O00(O00(O00(c)))};def O[Char](c:t)={OO(OO(OO(c)))};def OO[Char](c:t)={(c-('O'/'O')).toChar};def O00[Char](c:t)={(c+('O'/'O')).toChar}}
```
[Answer]
**C (or C++)** (body segment: 49)
(cheating)
when compiling, compile to a binary called `Hello\ World\!`, the code is:
```
#include <stdio.h>
#include <string.h>
int main(int i,char**a)
{
int j=i+i,k=j<<j;puts(strrchr(*a,'O'-(k<<j))+i);
}
```
The `strrchr` segment is required to remove the full path in the event the program name passed in contains the full path, also *no arguments must be passed in*..
Typical compile line could be: `gcc -o Hello\ World\! foo.c`
[Answer]
# Java 389 characters
spotted a unnecessary declaration
```
class A{static int a=0,b=a++,f=a,e=a++;static char p(String s){return(char)Byte.parseByte(s,a);}public static void main(String[]z){long x=e,y=b;String c=((Long)x).toString(),d=((Long)y).toString();char l=p(c+c+d+c+c+d+d),m=p(c+c+d+d+c+d+c),o=(char)(l+a+f),_=p(c+d+d+d+d+d),$=_++;System.out.print(new char[]{p(c+d+d+c+d+d+d),m,l,l,o,$,p(c+d+c+d+c+c+c),o,(char)(o+a+f),l,(char)(m-f),_});}}
```
History is in edit history
now the original ungolfed version readable:
```
// H e l l o W o r l d !
//72,101,108,108,111,32,87,111,114,108,100 33
import static java.lang.Integer.*;
class A
{
public static void main(String[] args)
{
Integer a=0,b=a++,e=a++; // making a 0 a 1 and a 2 which is required later;
String c=e.toString(),d=b.toString(),z=c.substring(0,0); //
String H = ((char)parseInt(d+c+d+d+c+d+d+d,a))+z+ // make binary values and then to char
(char)parseInt(d+c+c+d+d+c+d+c,a)+
(char)parseInt(d+c+c+d+c+c+d+d,a)+
(char)parseInt(d+c+c+d+c+c+d+d,a)+
(char)parseInt(d+c+c+d+c+c+c+c,a)+
(char)parseInt(d+d+c+d+d+d+d+d,a)+
(char)parseInt(d+c+d+c+d+c+c+c,a)+
(char)parseInt(d+c+c+d+c+c+c+c,a)+
(char)parseInt(d+c+c+c+d+d+c+d,a)+
(char)parseInt(d+c+c+d+c+c+d+d,a)+
(char)parseInt(d+c+c+d+d+c+d+d,a)+
(char)parseInt(d+d+c+d+d+d+d+c,a)
;
System.out.println(H); //obvious
}
```
[Answer]
# C++, 141, ~~146~~
First time trying one of these, can probably be improved quite a bit yet:
```
char o='O'/'O',T=o+o,X=T+o,f=T+X,t=f+f,F=t*f,h=F+F,l=h+t-T,O=l+X;
char c[]={F+t+t+T,h+o,l,l,O,o<<f,h-t-X,O,l+f+o,l,h,0};
cout<<c;
```
EDIT:
Stole the divide trick from another post, can't believe I didn't think of that :(
[Answer]
## Haskell - 146
```
a:b:c:f:g:s:j:z=iterate(\x->x+x)$succ 0
y=[f+j,d+a,c+s+h,l,a+b+l,s,f-s+o,o,a+b+o,l,l-f,a+s]
[h,e,l,_,o,_,w,_,r,_,d,x]=y
main=putStrLn$map toEnum y
```
I figured pattern matching would give Haskell a huge leg up, in particular because you can initialize powers of two like so:
```
one:two:four:eight:sixteen:thirty_two:sixty_four:the_rest = iterate (*2) 1
```
However, as seen in [MtnViewMark's Haskell answer](https://codegolf.stackexchange.com/questions/1536/hello-world-0-0/1555#1555) (which deserves many many upvotes, by the way) and other answers, better compression can be achieved by using more than just `+` and `-`.
[Answer]
## Clojure - 46 chars
```
(map print(butlast(rest(str'(Hello World!)))))
```
Note that `Hello` and `World!` are symbols, not literals of any kind.
[Answer]
**C++**
```
/*
Hello World!
*/
#define CodeGolf(r) #r
#include<iostream>
using namespace std;
int main()
{
char str[*"O"];
freopen(__FILE__,CodeGolf(r),stdin);
gets(str);gets(str);puts(str);
}
```
[Answer]
## PHP – 49 chars
```
<?=Hello.chr(($a=-~-~-~0).~-$a).World.chr($a.$a);
```
**Changelog**:
* (73 -> 86) Forgot to output an exclamation point... *sigh*
* (86 -> 57) Uses a single variable with incrementing
* (57 -> 51) Changed to use bitwise operators on 0
* (51 -> 49) More bitwise operators
[Answer]
# Python, 106
```
o=-~-~-~0
L=o+o
d,W=-~L,o**o
_=o*W
print str().join(chr(L+W+_-i)for i in[d*L,L+d,L,L,o,-~_,W,o,0,L,d+d,_])
```
[Answer]
# Perl, 186 bytes
```
@A=(0,0,0,0);@B=(@A,@A);@C=(@B,@B);@D=(@C,@C);@E=(@D,@D);@d=(@E,@D,@A);$l=[@d,@B];$o=[@$l,0,0,0];print(chr@$_)for[@E,@B],[@d,0],$l,$l,$o,\@D,[@E,@C,@A,0,0,0],$o,[@$o,0,0,0],$l,\@d,[@D,0]
```
Each chararcter is printed via its ordinal number, which is the length of an array. The construction of the arrays are optimized via the binary representation of the character numbers.
## Ungolfed:
```
@A = (0, 0, 0, 0); # A = 2^2
@B = (@A, @A); # B = 2^3
@C = (@B, @B); # C = 2^4
@D = (@C, @C); # D = 2^5
@E = (@D, @D); # E = 2^6
# d = 100 = 0x64 = 1100100b
@d = (@E, @D, @A); # d = 2^6 + 2^5 + 2^2
# l = 108 = 0x6C = 1101100b
$l = [@d, @B]; # l = d + 2^3
# o = 111 = 0x6F = 1101111b
$o = [@$l, 0, 0, 0]; # o = l + 3
print (chr @$_) for
[@E, @B], # "H" H = 72 = 0x48 = 1001000b = 2^6 + 2^3
[@d, 0], # "e" e = 101 = 0x65 = 1100101b = d + 1
$l, $l, $o, # "llo"
\@D, # " " ' ' = 32 = 0x20 = 0100000b = 2^5
[@E, @C, @A, 0, 0, 0], # "W" W = 87 = 0x57 = 1010111b = 2^6 + 2^4 + 2^2 + 3
$o, # "o"
[@$o, 0, 0, 0], # "r" r = 114 = 0x72 = 1110010b = o + 3
$l, \@d, # "ld"
[@D,0] # "!" ! = 33 = 0x21 = 0100001b = 2^5 + 1
```
[Answer]
## [Perl 6](http://perl6.org), 199 bytes
```
my \O=+[0];my \t=O+O;my \T=t+O;my \f=(t+t,O);my \F=t+T;my \S=T+T;my \L=(S,F);
say [~] ((S,T),(|L,t,0),(my \l=(|L,T,t)),l,(my \o=(|l,O,0)),F,(S,|f,t,0),o,(|L,|f),l,(|L,t),(F,0),)
.map({chr [+] t X**@_})
```
(newlines are added to reduce width, but are unnecessary so are not counted)
---
`Hello World!` is encoded as a list of lists of the powers of 2 of each letter.
There is exactly one place where I have a literal `0` that is used for anything other than a `0`. It is used to create a one-element list, which is immediately turned into the number `1` with the numeric prefix operator (`+[0]`).
```
my \O=+[0]; # one # (List.elems)
my \t=O+O; # two
my \T=t+O; # Three
my \f=(t+t,O); # (four, one) # <W r>
my \F=t+T; # five
my \S=T+T; # six
my \L=(S,F); # lowercase letter # (6,5)
say [~] (
(S,T), # H
(|L,t,0), # e
(my \l=(|L,T,t)), # l
l, # l reuse <l>
(my \o=(|l,O,0)), # o reuse <l>, add 0,1
F, # ␠
(S,|f,t,0), # W
o, # o reuse <o>
(|L,|f), # r
l, # l reuse <l>
(|L,t), # d
(F,0), # !
).map({chr [+] t X**@_})
```
] |
[Question]
[
To "function nest" a string, you must:
* Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was `Hello`, then the first step would be:
```
H(ello)
```
* Then, repeat this same step for every substring. So we get:
```
H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
```
Your task is to write a program or function that "function nests" a string. For example, if the input string was `Hello world!`, then you should output:
```
H(e(l(l(o( (w(o(r(l(d(!)))))))))))
```
The input will only ever contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters), and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.
For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.
```
Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
Input:
foobar
Output:
f(o(o(b(a(r)))))
Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))
Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))
Input:
a
Output:
a
Input:
42
Output:
4(2)
```
As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!
[Answer]
# Python, ~~41~~ ~~39~~ 34 bytes
```
lambda e:"(".join(e)+")"*~-len(e)
```
[Ideone it](http://ideone.com/6zHzp5)
Pretty self explanatory.
It puts a parenthesis between every other character then adds one less than the length parentheses to the end.
[Answer]
## MS-DOS .com file, 30 bytes
```
0000 fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010 b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3
```
The string is passed to the executable using the command line. (One space character between the .COM file name and the string).
The result is written to standard output.
The disassembly is here:
```
fc cld ; Make sure DF is not set (lodsb!)
be 82 00 mov si,0x82 ; First character of command line args
b4 02 mov ah,0x2 ; AH=2 means output for INT 21h
ac lodsb ; Load first character
88 c2 mov dl,al ; Move AL to DL (DL is written to output)
recursiveFunction:
cd 21 int 0x21 ; Output
ac lodsb ; Get the next character
3c 0d cmp al,0xd ; If it is "CR" (end of command line) ...
74 0d je doReturn ; ... return from the recursive function
b2 28 mov dl,0x28 ; Output "(" next...
50 push ax ; ... but save character read first
cd 21 int 0x21 ; (Actual output)
5a pop dx ; Restore character (but in DL, not in AL)
e8 f0 ff call recursiveFunction ; Recursively enter the function
doReturn:
b2 29 mov dl,0x29 ; Output ")"
cd 21 int 0x21
c3 ret ; Actually return
```
Note: You can exit a DOS .COM file (unlike files with EXE headers) using a "RET" instruction.
[Answer]
## JavaScript (ES6), ~~40~~ ~~34~~ 33 bytes
*Saved 6 bytes, thanks to ETHproductions*
A recursive function.
```
f=([c,...s])=>s+s?c+`(${f(s)})`:c
```
[Try it online!](https://tio.run/##dY/dCoJAEIXve4olujhLqWX2C9Yb9AIRtG3uYogbO9JN9Ow2goJIzTAwF@c7Z@ahXoq0z59VULp7VtcmxVnPwjCki0wPNKWjnl4xeRuQ/MjrXtfaleSKLCychcH4lFEllKDK56UdSymiSJyQgVBBQPE0m0eOElb2ajQwMs7dlG8c2mIjA8d9Yxv/k1nEy2S13mx385ZjZoEYSyRYYY0Ntthh/jdT88@BdYXpYpnXnHjnBwJY3gqYf7Dq3drBaihK4oGKRQliWX8B "JavaScript (Node.js) – Try It Online")
[Answer]
# Brainfuck, ~~42~~ 40 bytes
```
>+[-->+[<]>-]>+>>,.,[<+<.>>.,]<<+>[-<.>]
```
[Try it online!](http://brainfuck.tryitonline.net/#code=PitbLS0-K1s8XT4tXT4rPj4sLixbPCs8Lj4-LixdPDwrPlstPC4-XQoK&input=dGVzdA)
Ungolfed:
```
>+[-->+[<]>-]>+ # count to 40 (ASCII for open paren)
>> # move to the input holder
,. # input the first byte and output it
, # input the next byte
[ # while it's not zero
<+ # move to the input counter and increment it
<. # move to the open paren and output it
>>. # move to the input holder and output it
, # input the next byte
]
<<+ # move to the open paren and increment it to a close
> # move to the input counter
[ # while it's not zero
- # decrement it
<. # move to the close paren and output it
> # move to the input counter
]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
S'(ý¹g<')×J
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Uycow73CuWc8JynDl0o&input=TmVzdCBhIHN0cmluZw)
**Explanation:**
```
S'(ý join input by "("
¹g< push length of input - 1, call it n
')× push a string with char ")" n times
J concatenate
```
[Answer]
# Brainfuck, 44 bytes
```
>+++++[-<++++++++>],.,[<.>.>+<,]<+>>[-<<.>>]
```
Reads a byte at a time, puts an open-paren before each one except the first, puts the same number of close-parens at the end.
[Answer]
## Haskell, 30 bytes
```
f[x]=[x]
f(a:b)=a:'(':f b++")"
```
Usage example: `f "Nest a string"` -> `"N(e(s(t( (a( (s(t(r(i(n(g))))))))))))"`.
Take the next char, followed by a `(`, followed by a recursive call with all but the first char, followed by a `)`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to @Dennis (use mould, `ṁ`, in place of length, `L`, and repeat, `x`)
```
j”(³”)ṁṖ
```
**[TryItOnline](http://jelly.tryitonline.net/#code=auKAnSjCs-KAnSnhuYHhuZY&input=&args=Y29kZS1nb2xm)**
### How?
```
j”(³”)ṁṖ - Main link: s e.g. "code-golf" printed output:
j - join s with
”( - literal '(' "c(o(d(e(-(g(o(l(f"
”) - literal ')'
ṁ - mould like
³ - first input, s ")))))))))"
- causes print with no newline of z: c(o(d(e(-(g(o(l(f
Ṗ - pop (z[:-1]) "))))))))" c(o(d(e(-(g(o(l(f
- implicit print c(o(d(e(-(g(o(l(f))))))))
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), ~~22~~ 17 bytes
```
\1>`.
($&
T`(p`)_
```
[Try it online!](http://retina.tryitonline.net/#code=XDE-YC4KKCQmClRgKHBgKV8&input=TmVzdCBhIHN0cmluZw)
Alternatively:
```
S_`
\`¶
(
T`(p`)_
```
### Explanation
I always forget that it's possible to print stuff along the way instead of transforming everything into the final result and outputting it in one go...
```
\1>`.
($&
```
Here `\` tells Retina to print the result of this stage without a trailing linefeed. The `1>` is a limit which means that the first match of the regex should be ignored. As for the stage itself, it simply replaces each character (`.`) except the first with `(` followed by that character. In other words, it inserts `(` in between each pair of characters. For input `abc`, this transforms it into (and prints)
```
a(b(c
```
All that's left is to print the closing parentheses:
```
T`(p`)_
```
This is done with a transliteration which replaces `(` with `)` and deletes all other printable ASCII characters from the string.
[Answer]
# J, 13 bytes
```
(,'(',,&')')/
```
J executes from right-to-left so using the insert adverb `/`, a verb can be used to reduce the letters of the input string.
## Usage
```
f =: (,'(',,&')')/
f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
f 'foobar'
f(o(o(b(a(r)))))
f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))
```
You can observe the partial outputs between each reduction.
```
|. f\. 'Hello'
o
l(o)
l(l(o))
e(l(l(o)))
H(e(l(l(o))))
```
## Explanation
```
(,'(',,&')')/ Input: string S
( )/ Insert this verb between each char and execute (right-to-left)
,&')' Append a ')' to the right char
'(', Prepend a '(' to that
, Append to the left char
```
[Answer]
## [><>](http://esolangs.org/wiki/Fish), ~~19~~ 18 bytes
```
io8i:&0(.')('o&!
o
```
[Try it online!](http://fish.tryitonline.net/#code=aW84aTomMCguJykoJ28mIQpv&input=SGVsbG8gV29ybGQh)
### Explanation
The first line is an input loop which prints everything up to the last character of the input (including all the `(`) and leaves the right amount of `)` on the stack:
```
io Read and print the first character.
8 Push an 8 (the x-coordinate of the . in the program).
i Read a character. Pushes -1 at EOF.
:& Put a copy in the register.
0( Check if negative. Gives 1 at EOF, 0 otherwise.
. Jump to (8, EOF?). As long as we're not at EOF, this is
a no-op (apart from popping the two coordinates). At EOF
it takes us to the second line.
')(' Push both characters.
o Output the '('.
& Push the input character from the register.
! Skip the 'i' at the beginning of the line, so that the next
iteration starts with 'o', printing the last character.
```
Once we hit EOF, the instruction pointer ends up on the second line and we'll simply execute `o` in a loop, printing all the `)`, until the stack is empty and the program errors out.
[Answer]
# C#, 32 bytes
```
F=s=>*s+++(0<*s?$"({F(s)})":"");
```
This lambda must be a static method, would I need to count any extra bytes for that requirement? Normally I wouldn't use a lambda for recursion in C#, but then I think it would be shorter not to use recursion.
```
/*unsafe delegate string Function(char* s);*/ // Lambda signature
/*static unsafe Function*/ F = s =>
*s++ // Take first char and increment pointer to next one
+ (0 < *s // Check if any chars left
? $"({F(s)})" // If so concat surrounding parens around recursion
: "" // Otherwise done
)
;
```
[Answer]
# Java 7,~~81~~ 79 bytes
*Saved `1` byte.Thanks to kevin.*
```
String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}
```
[Answer]
# R, 61 bytes
```
cat(gsub("(?<=.)(?=.)","(",x,F,T),rep(")",nchar(x)-1),sep="")
```
Regex finds and replaces spaces between characters with "(". Then `cat` and `rep` add ")" n-1 times at the end.
[Answer]
## PowerShell v2+, 46 bytes
```
param([char[]]$a)($a-join'(')+')'*($a.count-1)
```
Takes input string, `char`-array's it, `-join`s the array together with open parens `(`, then concatenates on the appropriate number of closed parens `)`.
[Answer]
# APL, 19 bytes
```
{∊('(',¨⍵),')'⍴⍨⍴⍵}
```
Explanation:
```
{
('(',¨⍵) ⍝ join a ( to each character in ⍵
,')'⍴⍨⍴⍵ ⍝ for each character in ⍵, add an ) to the end
∊ ⍝ flatten the list
}
```
Alternative solution, also 19 bytes:
```
{⊃{∊'('⍺⍵')'}/⍵,⊂⍬}
```
Explanation:
```
{
⍵,⊂⍬ ⍝ add an empty list behind ⍵ (as a base case)
{ }/ ⍝ reduce with this function:
'('⍺⍵')' ⍝ put braces around input
∊ ⍝ flatten the list
⊃ ⍝ take first item from resulting list
}
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 16 bytes
```
t~40+v3L)7MQ3L)h
```
[Try it online!](http://matl.tryitonline.net/#code=dH40MCt2M0wpN01RM0wpaA&input=J2Zvb2Jhcic)
### Explanation
```
t % Implicit input. Duplicate
% STACK: 'foobar', 'foobar'
~ % Negate. Transforms into an array of zeros
% STACK: 'foobar', [0 0 0 0 0 0]
40+ % Add 40, element-wise. Gives array containing 40 repeated
% STACK: 'foobar', [40 40 40 40 40 40]
v % Concatenate vertically. Gives a two-row char array, with 40 cast into '('
% STACK: ['foobar'; '((((((']
3L) % Remove last element. Converts to row vector
% STACK: 'f(o(o(b(a(r'
7M % Push array containing 40 again
% STACK: 'f(o(o(b(a(r', [40 40 40 40 40 40]
Q % Add 1, element-wise
% STACK: 'f(o(o(b(a(r', [41 41 41 41 41 41]
h % Concatenate horizontally, with 41 cast into ')'
% STACK: 'f(o(o(b(a(r)))))'
% Implicit display
```
[Answer]
## [*Acc!!*](https://codegolf.stackexchange.com/a/62493/16766), 129 bytes
Not bad for a fairly verbose Turing tarpit...
```
N
Count i while _%128-9 {
Count x while _/128%2 {
Write 40
_+128
}
Write _%128
_+128-_%128+N
}
Count j while _/256-j {
Write 41
}
```
(Yes, all that whitespace is mandatory.)
**Note:** because of the input limitations of *Acc!!*, it is impossible to read an arbitrary string of characters without some ending delimiter. Therefore, this program expects input (on stdin) as a string followed by a tab character.
### *Acc!!*?
It's a language I created that [only appears to be unusable](https://codegolf.stackexchange.com/questions/61804/create-a-programming-language-that-only-appears-to-be-unusable). The only data type is integers, the only control flow construct is the `Count x while y` loop, and the only way to store data is a single accumulator `_`. Input and output are done one character at a time, using the special value `N` and the `Write` statement. Despite these limitations, I'm quite sure that *Acc!!* is Turing-complete.
### Explanation
The basic strategy in *Acc!!* programming is to use mod `%` and integer division `/` to conceptually partition the accumulator, allowing it to store multiple values at once. In this program, we use three such sections: the lowest-order seven bits (`_%128`) store an ASCII code from input; the next bit (`_/128%2`) stores a flag value; and the remaining bits (`_/256`) count the number of close-parens we will need.
Input in *Acc!!* comes from the special value `N`, which reads a single character and evaluates to its ASCII code. Any statement that consists solely of an expression assigns the result of that expression to the accumulator. So we start by storing the first character's code in the accumulator.
`_%128` will store the most recently read character. So the first loop runs while `_%128-9` is nonzero--that is, until the current character is a tab.
Inside the loop, we want to print `(` *unless* we're on the first iteration. Since *Acc!!* has no if statement, we have to use loops for conditionals. We use the 128's bit of the accumulator, `_/128%2`, as a flag value. On the first pass, the only thing in the accumulator is an ASCII value < 128, so the flag is 0 and the loop is skipped. On every subsequent pass, we will make sure the flag is 1.
Inside the `Count x` loop (whenever the flag is 1), we write an open paren (ASCII `40`) and add 128 to the accumulator, thereby setting the flag to 0 and exiting the loop. This also happens to increment the value of `_/256`, which we will use as our tally of close-parens to be output.
Regardless of the flag's value, we write the most recent input char, which is simply `_%128`.
The next assignment (`_+128-_%128+N`) does two things. First, by adding 128, it sets the flag for the next time through the loop. Second, it zeros out the `_%128` slot, reads another character, and stores it there. Then we loop.
When the `Count i` loop exits, we have just read a tab character, and the accumulator value breaks down like this:
* `_%128`: `9` (the tab character)
* `_/128%2`: `1` (the flag)
* `_/256`: number of characters read, minus 1
(The minus 1 is because we only add 128 to the accumulator once during the first pass through the main loop.) All that we need now are the close-parens. `Count j while _/256-j` loops `_/256` times, writing a close-paren (ASCII `41`) each time. Voila!
[Answer]
# Ruby, 27 bytes
```
->s{s.chars*?(+?)*~-s.size}
```
## Explanation
```
->s{ # Declare anonymous lambda taking argument s
s.chars # Get the array of chars representing s
*?( # Join the elements back into a string using "("s as separators
+?)*~-s.size # Append (s.size - 1) ")"s to the end
```
[Answer]
# Perl, ~~24~~ 23 bytes
Includes +1 for `-p`
Give string on STDIN ***without*** newline (or add a `-l` option to the program)
```
echo -n Hello | nest.pl
```
`nest.pl`:
```
#!/usr/bin/perl -p
$\=")"x s/.(?=.)/$&(/g
```
[Answer]
# PHP, 63 Bytes
```
<?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");
```
Previous version 64 Bytes
```
<?=join("(",$s=str_split($argv[1])).str_pad("",count($s)-1,")");
```
[Answer]
## Perl, 25 bytes
*Thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for golfing out 4 bytes.*
24 bytes of code + `-F`.
```
$"="(";say"@F".")"x$#F
```
Needs `-F` and `-E` flags :
```
echo -n "I love lisp" | perl -F -E '$"="(";say"@F".")"x$#F'
```
Note that if you try this on an old version of perl, you might need to add `-a` flag.
---
Another interesting way (a little bit longer though : 28 bytes) :
Thanks to Ton Hospel once again for helping me getting this one right.
```
#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg
```
(To use it, put the code inside a file and call it with `echo -n "Hello" | perl nest.pl`)
[Answer]
# GNU sed, ~~37~~ ~~35~~ 31 bytes (30 +1 for `-r` argument)
Pure linux sed solution
```
:;s/([^(])([^()].*)$/\1(\2)/;t
```
1. Naming the subsitution `:`; then calling it recursively with `t`
2. Making 2 regex groups:
* First group is first char of two consecutive characters which are *not* parenthesis
* Second group is the second consecutive character and the rest of the string until end of line
3. Add parenthesis around the second group `\1 ( \2 )`
**Edit**: Thanks to @manatwork for helping removing 4 characters!
[Online tester](http://sed.tryitonline.net/#code=OjtzLyhbXihdKShbXigpXS4qKSQvXDEoXDIpLzt0&input=TmVzdCBhIHN0cmluZwpIZWxsbwpIZWxsbyB3b3JsZApmb29iYXIKMTIzNDU2Nzg5MApjb2RlLWdvbGYKYQo0Mgo&args=LXI)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ ~~19~~ 18 bytes
```
¤Ug<©FN¹è'(}X®')×J
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wqRVZzzCqUZOwrnDqCcofVjCricpw5dK&input=Zm9v)
**Explanation:**
```
¤Ug<©FN¹è'(}X®')×J #implicit input, call it A
¤U #push the last letter of A, save it to X
g<© #push the length of A, subtract 1, call it B and save it to register_c
F } #repeat B times
N¹è #push the Nth char of A
'( #push '('
X #push X
®')× #push ')' repeated B times
J #join together
#implicit print
```
[Answer]
# Vim, 17 bytes
`$qqha(<Esc>A)<Esc>%h@qq@q`
Goes from end to beginning, because otherwise you trip over the `)`s you've already written. Uses `ha` instead of `i` to fail when it reaches the beginning.
Usually, you wouldn't do two separate inserts like this; you'd do something like `C()<Esc>P` to save a stroke. But the positioning doesn't work as well this time.
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish), ~~19~~ 18 bytes
```
P
,+>`
_ {I
/'␁'(
```
The character `␁` is the unprintable control character with byte value `0x1`. [Try it online!](http://jellyfish.tryitonline.net/#code=UAosKz5gCl8gIHtJCi8nASco&input=SGkh)
## Explanation
This is a pretty complex Jellyfish program, since many values are used in multiple places.
* `I` is raw input, read from STDIN as a string.
* `'(` is the character literal `(`.
* The `{` (left identity) takes `'(` and `I` as inputs, and returns `'(`.
The return value is never actually used.
* ``` is thread. It modifies `{` to return the character `(` for each character of `I`, resulting in a string of `(`s with the same length as `I`.
* `>` is tail; it takes the string of `(`s as input and chops off the first character.
* `+` takes as arguments the string of `(`s and the unprintable byte, and adds the byte value (1) to each character. This gives an equal-length string of `)`s.
Using the character `␁` guarantees that the return value is a string, and not a list of integers.
* On the lower left corner, `/` takes the unprintable byte, and returns a *function* that takes two arguments, and joins the second argument with the first one once (since the byte value is 1).
* `_` takes this function, grabs the arguments of the lower `{` (which were `'(` and `I`), and calls the funtion with them. This inserts the character `(` between every pair of characters in `I`.
* `,` concatenates this string with the string of `)`s, and `P` prints the result.
[Answer]
# [Convex](http://github.com/GamrCorps/Convex), 10 bytes
```
_'(*\,(')*
```
[Try it online!](http://convex.tryitonline.net/#code=XycoKlwsKCcpKg&input=&args=SGVsbG8)
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 37 bytes
```
i:0(?\'('
$,2l~/~
/?(2:<-1$')'
>~ror:
```
**Row by row**
1. Pushes each char from input with an opening parenthesis after each
2. Removes EOF and the last opening parenthesis and pushes the stack length
3. Uses a comparison with half the stack length to push the closing parenthesis
4. Prints the content of the stack
[Try it online!](http://fish.tryitonline.net/#code=aTowKD9cJygnCiQsMmx-L34KLz8oMjo8LTEkJyknCj5-cm9yOg&input=SGVsbG8gV29ybGQh)
[Answer]
# Perl, 36 bytes (34 + 2 for `-lp`flag)
Thanks to Dada for pointing out a bug and saving one byte (in total)!
Splits the string into an array, then joins it with the `(`delimiter. We directly add the closing `)`since `length`returns the length of the string before the `join`.
```
$_=(join"(",split//).")"x(y///c-1)
```
[Try it here!](http://ideone.com/NyBniB)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 103 97 Bytes
Includes +3 for -c
```
{({}<><(((((()()){}()){}){}){})>)<>}<>({}<([][()]){({}[()()]<(({})()<>)<>>)}{}>){({}<>)<>}<>{}
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=eyh7fTw-PCgoKCgoKCkoKSl7fSgpKXt9KXt9KXt9KT4pPD59PD4oe308KFtdWygpXSl7KHt9WygpKCldPCgoe30pKCk8Pik8Pj4pfXt9Pil7KHt9PD4pPD59PD57fQ&input=Y29kZS1nb2xm&args=LWM)
---
**Explanation:**
```
#reverse the stack and put a 40 between every number
{({}<><(((((()()){}()){}){}){})>)<>}<>
{ } #repeat this until the stack is empty
({} ) #pop the top and push it after
<> #switching stacks and
<(((((()()){}()){}){}){})> #pushing a 40 (evaluated as 0)
<> #switch back to the first stack
<> #switch to the stack that everything is on now
#put as many )s on the other stack as needed
({} ) #pop the top letter and put it back
#after doing the following
#This leaves ( on the top
< > #evalute this part as 0
([][()]) #push the height of the stack minus one
{ } #repeat until the "height" is 0
({}[()()] ) #pop the "height" and push is minus two
< > #evaluate to 0
( ) #push:
({}) #the top of the stack (putting it back on)
() #plus one onto
<> #the other stack
<> #switch back to the other stack
{} #pop what was the height of the stack
#move the string of letters and (s back, reversing the order again
{ } # repeat until all elements are moved
( ) # push:
{} # the top of the stack after
<> # switching stacks
<> # switch back to the other stack
<> # switch to the stack with the final string
{} #pop the extra (
```
] |
[Question]
[
Boys and girls are excited to see *Fifty Shades of Grey* on the silver screen, we just want to code without being bothered, so here's a challenge to pick our brain.
You have to:
* Print on the screen fifty squares filled **each with a different shade of grey**
* If your language of choice **lacks image processing capabilities**, you could output an **image file**
* Squares must be visible, **at least 20 x 20 pixels**
* You cannot use random numbers **unless you make sure each shade is unique.**
* You **cannot connect to any service over any network**
* You **cannot read any files in your program.**
* You cannot use any libraries out of the standard libraries of your language of choice.
**This is code golf so shortest code wins.**
[Answer]
# Mathematica, 30 bytes
Here is another Mathematica approach:
```
ArrayPlot[#+5#2&~Array~{5,10}]
```
![enter image description here](https://i.stack.imgur.com/Vra27.png)
or
```
ArrayPlot[5#+#2&~Array~{10,5}]
```
![enter image description here](https://i.stack.imgur.com/mtElK.png)
The first one simply creates an array
```
{{6, 11, 16, 21, 26, 31, 36, 41, 46, 51},
{7, 12, 17, 22, 27, 32, 37, 42, 47, 52},
{8, 13, 18, 23, 28, 33, 38, 43, 48, 53},
{9, 14, 19, 24, 29, 34, 39, 44, 49, 54},
{10, 15, 20, 25, 30, 35, 40, 45, 50, 55}}
```
and the second one
```
{{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25},
{26, 27, 28, 29, 30},
{31, 32, 33, 34, 35},
{36, 37, 38, 39, 40},
{41, 42, 43, 44, 45},
{46, 47, 48, 49, 50},
{51, 52, 53, 54, 55}}
```
Then, `ArrayPlot` plots them as a grid and, by default, uses greyscale to visualise the values.
[Answer]
# CJam - 23 (no actual graphical output)
Since CJam can't draw on the screen (yet?), I wrote a program that outputs an image in plain [pgm](http://en.wikipedia.org/wiki/Netpbm_format) format.
Save the output to a file called 50.pgm and open with an image viewer/editor.
```
"P2"1e3K51_,1>K*$K*~]N*
```
[Try it online](http://cjam.aditsu.net/#code=%22P2%221e3K51_%2C1%3EK*%24K*~%5DN*)
The result looks like this:
![50.png](https://i.stack.imgur.com/jV4d1.png)
**Explanation:**
```
"P2" push "P2" (netpbm magic number)
1e3K push 1000 and K=20 (image size)
51 push 51 (value of white)
_, duplicate 51 and convert to an array [0 1 2 ... 50]
1> remove 0 (slice from 1)
K* repeat the array 20 times
$ sort, to get [(20 1's) (20 2's) ... (20 50's)]
K* repeat the array 20 times
~ dump the elements on the stack
] put everything from the stack in an array
N* join with newlines
```
[Answer]
# Mathematica ~~72 61 59 43 35~~ 34 bytes
**Current version** (34 bytes)
```
GrayLevel[#/50]~Style~50 &~Array~50
```
![grid2](https://i.stack.imgur.com/to2fi.png)
---
**Earlier version** (59 bytes), thanks to Martin Büttner.
```
Graphics[{GrayLevel[#/50],Cuboid@{#~Mod~9,#/9}}&/@Range@50]
```
Blue borders added to highlight position of squares.
```
Graphics[{EdgeForm[Blue], GrayLevel[#/50], Cuboid@{#~Mod~9, #/9}} & /@Range@50]
```
![blue](https://i.stack.imgur.com/LeYje.png)
Number of squares:
```
Length[%[[1]]]
```
>
> 50
>
>
>
---
**First attempt (72 bytes)**
If the squares can overlap.
As Zgarb notes, there is a remote possibility that one square would hide another.
```
Graphics@Table[{GrayLevel@k,Cuboid[{0,15}~RandomReal~2]},{k,.4,.89,.01}]
```
![enter image description here](https://i.stack.imgur.com/3h1Xp.png)
[Answer]
# Sage - ~~26~~ ~~24~~ ~~35~~ 29 characters
```
matrix(5,10,range(50)).plot()
```
It looks like this:
## 5x10 shades of grey
*Previous attempts*: First I had `Matrix([range(50)]).plot()`, then `matrix_plot([range(50)])`. These looked like this:
![50 shades of grey](https://i.stack.imgur.com/Jx2nO.png)
User @flawr pointed out that the squares produced with default settings are too small. Adding a `figsize` options fixes it, but it is 6 characters longer than the 5x10 version at the top of this answer:
```
matrix_plot([range(50)],figsize=20)
```
[Answer]
# MATLAB, 24 bytes
Second attempt, now actually conforming to the rules.
```
imshow(0:1/49:1,'I',2e3)
```
The 'I' stands for 'InitialMagnification', but apparently Matlab will autocomplete names in name/value pairs. Sure is a good golfing trick!
![enter image description here](https://i.stack.imgur.com/XBjeB.png)
[Answer]
## R, ~~47 42 39 38 37 36~~ 35 bytes
Assuming they're allowed to overlap, this works. `Symbols` requires a vector that holds the size for each square, and I'm saving space by reusing the same vector for all function parameters. The largest square is always 1 inch wide. With 50:99 as the range of integers, the smallest square will be around half an inch wide, so 36 pixels at 72 dpi.
```
symbols(x,,,x<-50:99,bg=gray(x/99))
```
Thanks to everyone for the comments and suggestions, I'm pretty new to R so this is all very educational.
![new and improved?](https://i.stack.imgur.com/vsEuP.png)
Previous versions:
```
symbols(x,sq=x<-50:99,bg=gray(x/99)) #36
x=50:99;symbols(x,sq=x,bg=gray(x/99)) #37
x<-50:99;symbols(x,sq=x,bg=gray(x/99)) #38
x<-1:50;symbols(x,sq=x/x,bg=gray(x/50)) #39
x<-1:50/50;symbols(x,sq=x/x,bg=rgb(x,x,x)) #42
x<-1:50/50;symbols(x,squares=x/x,bg=rgb(x,x,x)) #47
```
Previous image:
![50 shades of R](https://i.stack.imgur.com/S1m47.png)
[Answer]
# Java - 180
Pretty straightforward, just drawing boxes.
```
import java.awt.*;void f(){new Frame(){public void paint(Graphics g){for(int i=1;i<51;g.setColor(new Color(328965*i)),g.fillRect(i%8*20,i++/8*20,20,20))setSize(600,600);}}.show();}
```
![enter image description here](https://i.stack.imgur.com/xDGG2.png)
With line breaks:
```
import java.awt.*;
void f(){
new Frame(){
public void paint(Graphics g){
for(int i=1;
i<51;
g.setColor(new Color(328965*i)),
g.fillRect(i%8*20,i++/8*20,20,20))
setSize(600,600);
}
}.show();
}
```
[Answer]
# BBC BASIC, 57
```
FORn=51TO2STEP-1VDU19;-1,n,n,n:RECTANGLEFILL0,0,n*20NEXT
```
The squares have to be *at least* 20 pixels but there's nothing to say they have to be the same size, so I guess this qualifies.
It may be possible to shorten this by using more low-level VDU codes. But changing from this pattern to a less interesting one is unlikely to make it shorter.
![enter image description here](https://i.stack.imgur.com/IVbRk.png)
[Answer]
# ipython 2, 54 bytes
The best I could do was with an ipython program. Starting ipython with `ipython -pylab` and executing this program will show a graph with 50 shades of grey in 50 squares:
```
t=arange(50);c=t/50.;scatter(t%5,t,500,zip(c,c,c),'s')
```
Output:
![grey50](https://i.stack.imgur.com/3Mnga.png)
### Solution 2:
Here is another program (61 bytes):
```
imshow(arange(50).reshape(5,10)*.02,'Greys',None,1,'nearest')
```
that displays the following window:
![grey50b](https://i.stack.imgur.com/NpIkc.png)
[Answer]
# JavaScript (72, 70, 67 bytes)
72: original (borrowing the clever `■` usage from [Sphinxxx's answer](https://codegolf.stackexchange.com/a/45743/36910)):
```
for(i=90;i>40;)document.write('<font color=#'+i+i+i--+' size=7>■')
```
70: stealing shamelessly from [Ismael Miguel](https://codegolf.stackexchange.com/a/45767/36910) (who deserves the votes), a shorter for loop and allowing the browser to correct for a lack of # proceeding the colour code...
```
for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>■')
```
67 bytes (65 chars): swapping the entity for the unicode character:
```
for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>■')
```
[Answer]
## C++, ~~98~~ 83 characters
Okay so, you are going to need a terminal emulator that supports true colors. For mac os there are the nightly builds of iTerm2, for example. For unix I believe konsole supports it. Here's a list, just in case: <https://gist.github.com/XVilka/8346728#now-supporting-truecolor>
Compile with g++ (\e is compiler dependent).
For the squares to have enough area, you will have to change your terminal font size.
```
#include <cstdio>
int main(){for(int i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}
```
Using C libraries instead of C++ allows for shaving some characters.
![](https://i.stack.imgur.com/IC4rE.png)
## C, ~~61~~ 58 characters
This is the same program but in C, which assumes untyped function declarations to return int, and which doesn't need includes for some of the standard library functions, like in this case, printf. Suggested by @cartographer. Three characters less thanks to @user3601420
```
main(i){for(i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}
```
Compiles with a couple of warnings (for assuming main's return type to be int and for implicitly including the declaration of printf).
[Answer]
## J (~~43~~ ~~41~~ ~~40~~ ~~38~~ ~~33~~ 29 characters)
After suggestions from [randomra](https://codegolf.stackexchange.com/users/7311/randomra).
```
1!:2&4'P2 ',":(,*:,],*:#?~)50
```
This solution does not display anything as the standard library of J does not contain GUI routines. Instead, I generate an image and write it to standard output. The output is randomized, it ensured that all shades are distinct. Here is a some [sample output](http://fuz.su/~fuz/pic/50sog.pgm) and the image converted to png and rotated by 90° for easier viewing:
![50 shades of gray](https://i.stack.imgur.com/SsO6A.png)
[Answer]
# Piet- 2\*103 = 206
This is unique in that the source code and the output fulfill the challenge:
![piet](https://i.stack.imgur.com/6S1ap.png)
Most of it is decorative, so I only counted the top two rows, which stand alone just fine. Outputs a grayscale ppm like some others have done.
[Answer]
# Python 2, ~~125~~ ~~115~~ 104 bytes
```
from turtle import*
shape("square")
bk(500)
ht()
pu()
exec'color((xcor()/2e3+.5,)*3);stamp();fd(21);'*50
```
**Sample output:**
![enter image description here](https://i.stack.imgur.com/uuKd9.png)
Good old turtle. This was the only method I could think of in Python which prints images to a screen using only the standard libraries.
The square turtle shape just happens to be 21 by 21, which is very convenient. This can be seen by digging through `turtle.py`:
```
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10), (-10,-10)))
```
If you have a high res monitor or don't mind a few squares being off-screen, then this is **93 bytes:**
```
from turtle import*
shape("square")
ht()
pu()
exec'color((xcor()/2e3,)*3);stamp();fd(21);'*50
```
---
## Demo
*(This demo uses [Skulpt](http://www.skulpt.org) by adapting the snippet found [here](https://codegolf.stackexchange.com/a/40127/21487). It is only included to give an idea as to what the code does — I had to modify a few bits to get it working.)*
```
function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nt=turtle.Turtle()\nt.speed(9)\nt.shape("square")\n\nt.bk(500)\nt.ht()\nt.pu()\nfor i in range(50):t.color(64+2*i,64+2*i,64+2*i);t.stamp();t.fd(21)')}catch(a){throw Error(a.toString());}})
```
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script><script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<canvas height="100" width="1200" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>
```
[Answer]
# Excel vba, 81
In the immediate window:
```
for i=1 to 9:for j=1 to 9:k=i+j*10:cells(i,j).interior.color=rgb(k,k,k):next:next
```
on the active sheet:
![81 shades is just as much code as 50](https://i.stack.imgur.com/12JEa.png)
{81 shades is just as much code as 50}
[Answer]
# **R**, ~~37~~ 32 characters1:
```
image(t(1:50),c=gray.colors(50))
```
However, the display for this looks … meh (image rotated 90° to fit better into text; compressed, original square side length > 20px):
![boring](https://i.stack.imgur.com/d3i0D.png)
Here’s a nicer version which plots the squares in random order inside a matrix (50 characters):
```
image(matrix(sample(1:50),10),c=gray.colors(50))
```
![exciting!](https://i.stack.imgur.com/mC3pP.png)
(And yes, the three adjacent squares of seemingly identical colours are actually three different shades of grey.)
1 Yes, another R answer, ~~and not even the shortest~~ (now the shortest for R) – apologies. I was missing a *pretty* rendering in R.
[Answer]
**Matlab 35 thanks to sanchises**
```
imshow(int8(ones(20,1)*(0:.05:51)))
```
**Matlab 36**
```
imshow(uint8(ones(20,1)*(0:.05:51)))
```
Displays 50 squares filled with gray values 1 to 50 and 2 additional rectangles filled with gray value 0 and 51:
![enter image description here](https://i.stack.imgur.com/lZbmX.png)
**Matlab, 45**
```
imshow(uint8(ones(20,1)*floor(1:0.05:50.95)))
```
[Answer]
# JavaScript, 87 90 bytes
```
for(i=90;i>40;)document.write('<p style=background:#'+i+i+i--+';height:9ex;width:9ex>')
```
This outputs squares to the HTML, because it is really JavaScript's only method of graphical output. Thanks to edc65 for shaving off 3 bytes.
[Answer]
# PHP, ~~96~~ ~~88~~ 74 bytes
Thanks to Ismael Miguel for saving 22 bytes!
```
for($i=60;--$i>9;)echo"<p style=background:#$i$i$i;height:9mm;width:9mm>";
```
Writes 50 `<p>`s with 9mm as height and width (which should be bigger than 20px on the majority of screens), stacked on each other, all with a minor difference in shade.
Generated result (the image is zoomed out and 90° rotated):
![Result](https://i.stack.imgur.com/3K4oE.png)
[Answer]
# Matlab - 33 bytes
```
surf(meshgrid(1:7)),colormap gray
```
Despite the verbose commands, the result is still quite compact. It looks a bit better if you replace `surf` with `surface` but that costs 3 chars.
If you don't notice the 50th gray square that is because it is a bit bigger than the others!
[Answer]
# Javascript (~~77~~ 71 bytes):
This answer is no longer IE11 based. It works because the browser converts the bad color codes into usable ones (by adding `#` to the number).
Here is the code:
```
for(i=59;i-->9;)document.write("<hr color="+i+i+i+" size=20 width=20>")
```
Firefox still has the quirk of making circles.
(Small edit: Changed `for(i=61;i-->9;)` to `for(i=59;i-->9;)` because it was producing 52 squares)
---
**Old answer:**
This is based on [my PHP answer](https://codegolf.stackexchange.com/a/45752/14732), and uses almost the same ways to make the squares:
```
for(i=51;i--;)document.write("<hr color=rgb("+[i,i,i]+") size=20 width=20>");
```
Not the shortest answer, but it's worth adding here.
---
This solution **isn't compatible** with Chrome (produces multiple green colors) and Firefox (same result, but produces circles? o.O WTH?)
Since this is code-golf, a solution working with a specific version or a specific software is acceptable.
[Answer]
# JavaScript - 70 bytes
```
for(i=51;i-=1;)document.write('<a style=opacity:'+i/50+'>■</a>')
```
[Answer]
**Processing, 66 characters:**
```
size(1000,20);for(int i=0;i<981;i+=20){fill(i/4);rect(i,0,20,20);}
```
![gray shades in Processing](https://i.stack.imgur.com/khctc.png)
[Answer]
# PHP (~~62~~ ~~60~~ ~~63~~ ~~72~~ ~~71~~ ~~62~~ 59 bytes):
I've made the shortest I could find:
```
for($i=59;$i-->9;)echo"<hr color=$i$i$i size=20 width=20>";
```
This is **exactly** the same code as [my Javascript answer (with 71 bytes)](https://codegolf.stackexchange.com/a/45767/14732).
But **SO MUCH** shorter!
This have a quirk in Firefox: instead of squares, Firefox makes **circles**! (Go insanity!)
Othen than that, all the browsers produce the right color (even with the missing `#` on the `color` attribute).
---
**Invalid submits and changelog**:
Old answer, with 62 bytes.
```
while($i++<51)echo"<hr color=rgb($i,$i,$i) size=20 width=20>";
```
All shades are perfectly aligned.
This solution won't work for Chrome (will produce squares with multiple colors) and Firefox (which makes circles o.O Yes, **circles** with `<hr>`! Horizontal ruler is a circle on Firefox!).
You can test it on IE11 and it should be fine.
---
(simply removed from above)
I've noticed something awful: It was outputting `#111` instead of `#010101` for some colors.
This meant that some colors were repeating.
Therefore, I had to sacrifice a few bytes:
```
<?while(f>$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20 width=20>";
```
Outputs the 50 shades in perfect order, from lighter to darker.
Due to a correct point made by [@edc65](https://codegolf.stackexchange.com/users/21348/edc65), I had to add `width=20`, to produce **perfect squares**.
Reduced one more byte by replacing `f!=$c` with `f>$c`, which works perfectly.
---
Final version, without `width=20`:
```
<?while(f!=$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20>";
```
This is invalid because it is required to output squares.
This outputs the shades from lighter to darker.
---
Reduced 1 byte by switching to a `while` loop, like this:
```
<?while($c=dechex(50-$i++))echo"<hr color=#$c$c$c size=20>";
```
First solution:
```
<?for($i=50;$c=dechex($i--);)echo"<hr color=#$c$c$c size=20>";
```
This doesn't have the shades neatly ordered, but there are 50 different ones.
There is nothing stating that they must be ordered, but there is a requirement on size.
I hope I can reduce it a lot more.
You can test it on <http://writecodeonline.com/php/> (click on "Display as HTML").
[Answer]
# PostScript, 34 bytes
In ISO-Latin-1 encoding:
```
20’›‡üˆì0{’81e3’6’–10’k0ˆ (note, this is a Line Feed)
’c’§}’H
```
This is the binary equivalent to:
```
20 setlinewidth 1020 -20 0 { dup 1e3 div setgray 10 moveto 0 10 lineto stroke } for
```
(This assumes that you are using it on a device that is at least 1000 points [= 10 inches = 25.4 cm] wide.)
[Answer]
# CSS (87 chars)
Uses animation ;)
```
:after{content:'\25A0';font:9em z;animation:g 8s steps(50)}@keyframes g{to{color:#fff}}
```
The runnable version is longer since Webkit still needs the vendor prefix. :(
```
:after{content:'\25A0';font:9em z;-webkit-animation:g 8s steps(50);animation:g 8s steps(50)}@-webkit-keyframes g{to{color:#fff}}@keyframes g{to{color:#fff}}
```
If we're allowed a random, empty `<a>` element, we can get it down to just 72 characters:
```
a{padding:3em;animation:g 8s steps(50)}@keyframes g{to{background:#000}}
```
See? CSS is a legit programming language!
[Answer]
# R, 36 bytes
I can make freekvd's answer shorter trivially.
```
x=9:59/59;symbols(x,sq=x,bg=gray(x))
```
![Output](https://i.stack.imgur.com/dWDah.png)
(Sorry for not making a comment under his solution. Stackexchange does not allow me to make comments, vote etc yet).
[Answer]
# DrRacket - 83
Just for the sake of firing up DrRacket 1 year after "Introduction to Systematic Program Design".
**EDIT**:
```
(require htdp/image)(map(λ(i)(rectangle 50 50'solid(make-color i i i)))(range 50))
```
[Answer]
# C# - 173
**Using LINQPAD**
```
var b=new Bitmap(1000,20);var g=Graphics.FromImage(b);for(int i=0;i<50;i++)g.FillRectangle(new SolidBrush(Color.FromArgb(i*5,i*5,i*5)),new Rectangle(i*20,0,20,20));b.Dump();
```
**Expanded**:
```
var b = new Bitmap(1000, 20);
var g = Graphics.FromImage(b);
for (int i = 0; i < 50; i++)
g.FillRectangle(new SolidBrush(Color.FromArgb(i * 5, i * 5, i * 5)), new Rectangle(i * 20, 0, 20, 20));
b.Dump();
```
**Output**:
![output](https://i.stack.imgur.com/u2oX7.png)
[Answer]
# JavaScript, 152 bytes.
Okay, so maybe this isn't the best solution but here is mine.
```
function b(a){c=document
e=c.createElement('p')
with(e.style){background="rgb("+[a,a,a]+")"
width=height="20px"}c.body.appendChild(e)
a<245&&b(a+5)}b(0)
```
Here is the output with css float left (just so it is easier to count the squares) and without:
![with css float](https://i.stack.imgur.com/RB6YH.png)
![without css float](https://i.stack.imgur.com/DjmPK.png)
] |
[Question]
[
Write a program that takes in a string or text file whose first line has the form
```
width height
```
and each subsequent line has the form
```
x y intensity red green blue
```
where:
* `width` and `height` may be any positive integers.
* `x` and `y` may be any integers.
* `intensity` may be any non-negative integer.
* `red`, `green`, and `blue` may be any integers from 0 to 255 inclusive.
Your program must output a [truecolor](https://en.wikipedia.org/wiki/Color_depth#True_color_.2824-bit.29) image in any common lossless image file format whose dimensions are `width` by `height`. Each `x y intensity red green blue` line represents a colorful star or orb that must be drawn on the image. There may be any number of stars to draw, including 0. You may assume the string or file has a trailing newline.
The algorithm for drawing the image is as follows, though you may implement it in any way you like as long as the result is identical:
>
> For every pixel (*X*,*Y*) in the image (where *X* is 0 at the leftmost
> edge and *width-1* at the rightmost edge, and *Y* is 0 at the top edge
> and *height-1* at the bottom edge), the color channel *C* ϵ {*red*,
> *green*, *blue*} (a value pinned between 0 to 255) is given by the equation:
>
>
> ![color channel equation](https://i.stack.imgur.com/Ydexy.png)
>
>
> Where the *dist* function is either [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance):
>
>
> ![Euclidean distance equation](https://i.stack.imgur.com/okZw4.png)
>
>
> Or [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry):
>
>
> ![Manhattan distance equation](https://i.stack.imgur.com/v29z0.png)
>
>
> Choose whichever distance function you prefer, based on golfability or aesthetics.
>
>
> Each of the lines in the input besides the first is an element of the *Stars* set. So, for example, Sx represents the `x` value on one of the input lines, and SC represents either `red`, `green`, or `blue`, depending on which color channel is currently being calculated.
>
>
>
# Examples
### Example A
If the input is
```
400 150
-10 30 100 255 128 0
```
the output should be
![Example A, Euclidean](https://i.stack.imgur.com/LMlI4.png)
if you're using Euclidean distance, and
![Example A, Manhattan](https://i.stack.imgur.com/3pXJ2.png)
if you're using Manhattan distance.
### Example B
If the input is
```
200 200
100 100 10 255 255 255
20 20 40 255 0 0
180 20 40 255 255 0
180 180 40 0 255 0
20 180 40 0 0 255
```
the respective outputs for Euclidean and Manhattan distance should be
![Example B, Euclidean](https://i.stack.imgur.com/db0TF.png) and ![Example B, Manhattan](https://i.stack.imgur.com/GyxH1.png).
### Example C
If the input is
```
400 400
123 231 10 206 119 85
358 316 27 170 47 99
95 317 3 202 42 78
251 269 17 142 150 153
43 120 3 145 75 61
109 376 6 230 231 52
331 78 21 31 81 126
150 330 21 8 142 23
69 155 11 142 251 199
218 335 7 183 248 241
204 237 13 112 253 34
342 89 18 140 11 123
```
the output should be
![Example C, Euclidean](https://i.stack.imgur.com/h2YOC.png)
if you're using Euclidean distance, and
![Example C, Manhattan](https://i.stack.imgur.com/O8I74.png)
if you're using Manhattan distance.
### Example D
If the input is
```
400 400
123 231 5 206 119 85
358 316 5 170 47 99
95 317 5 202 42 78
251 269 5 142 150 153
43 120 5 145 75 61
109 376 5 230 231 52
331 78 5 31 81 126
150 330 5 8 142 23
69 155 5 142 251 199
218 335 5 183 248 241
204 237 5 112 253 34
342 89 5 140 11 123
```
the output should be
![Example D, Euclidean](https://i.stack.imgur.com/dlnsI.png)
if you're using Euclidean distance, and
![Example D, Manhattan](https://i.stack.imgur.com/MuJwa.png)
if you're using Manhattan distance.
### Example E
If the input is
```
100 1
```
then the output should be a 100 pixel wide by 1 pixel tall image that is completely black.
# Notes
* Take the input string or the name of a text file that contains it from stdin or the command line, or you may write a function that takes in a string.
* "Outputting" the image means either:
+ Saving it to a file with the name of your choice.
+ Printing the raw image file data to stdout.
+ Displaying the image, such as with [PIL](http://www.pythonware.com/products/pil/#pil117)'s [`image.show()`](http://effbot.org/imagingbook/image.htm#tag-Image.Image.show).
* I won't be checking that your images are pixel perfect (Stack Exchange lossily compresses images anyway) but I will be very suspicious if I can visually tell any difference.
* You may use graphics/image libraries.
# Winning
The shortest submission in bytes wins. In case of ties, the earliest submission wins.
*Fun Bonus:* Give the input for a truly spectacular output image.
[Answer]
# JavaScript ~~394~~ 344
```
function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}
```
**Edit:** shortened the code a lot by applying [wolfhammer](https://codegolf.stackexchange.com/users/8055/wolfhammer)'s awesome suggestions.
### Test
*Note: Wait a few seconds for the snippet below to render (takes ~4 seconds on my machine).*
```
function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}
var start = Date.now();
X("400 150\n" +
"-10 30 100 255 128 0");
X("200 200\n" +
"100 100 10 255 255 255\n" +
"20 20 40 255 0 0\n" +
"180 20 40 255 255 0\n" +
"180 180 40 0 255 0\n" +
"20 180 40 0 0 255");
X("400 400\n" +
"123 231 10 206 119 85\n" +
"358 316 27 170 47 99\n" +
"95 317 3 202 42 78\n" +
"251 269 17 142 150 153\n" +
"43 120 3 145 75 61\n" +
"109 376 6 230 231 52\n" +
"331 78 21 31 81 126\n" +
"150 330 21 8 142 23\n" +
"69 155 11 142 251 199\n" +
"218 335 7 183 248 241\n" +
"204 237 13 112 253 34\n" +
"342 89 18 140 11 123");
X("400 400\n" +
"123 231 5 206 119 85\n" +
"358 316 5 170 47 99\n" +
"95 317 5 202 42 78\n" +
"251 269 5 142 150 153\n" +
"43 120 5 145 75 61\n" +
"109 376 5 230 231 52\n" +
"331 78 5 31 81 126\n" +
"150 330 5 8 142 23\n" +
"69 155 5 142 251 199\n" +
"218 335 5 183 248 241\n" +
"204 237 5 112 253 34\n" +
"342 89 5 140 11 123");
var end = Date.now();
console.log('Done in ' + (end - start)/1000 + 's.');
```
```
canvas {
display: block;
padding: 10px;
}
```
You can also run it in [JSFiddle](http://jsfiddle.net/4q28d6bx/1/).
### Bonus: Blue Eclipse
```
function X(a){for(l=a.match(/\d+/g),h=document,v=h.body.appendChild(h.createElement("canvas")),v.width=W=l[0],v.height=H=l[1],w=v.getContext("2d"),e=w.createImageData(W,H),d=e.data,N=W*H;N--;)for(i=2,c=N*4,d[c+3]=255;i<l.length;)for(x=N%W-l[i++],y=~~(N/W)-l[i++],k=l[i++],q=0;q<3;)d[c+q++]+=k*l[i++]/-~Math.sqrt(x*x+y*y);w.putImageData(e,0,0);}
var j = 0;
var renderFrame = function () {
if(window.h && window.v){h.body.removeChild(v);} // clear prev frame
X("225 150\n" +
(70 + j) + " " + (120 - j) + " 170 135 56 0\n" +
j * 5 + " " + j * 3 + " 64 0 50 205");
if(++j < 50) { setTimeout(renderFrame, 1); } else { console.log('done!'); }
};
setTimeout(renderFrame, 10);
```
You can also run it in [JSFiddle](http://jsfiddle.net/zz6j5x6d/).
### Description
This is a straightforward JavaScript + HTML5 canvas implementation: a function that takes a string argument (without trailing spaces/newlines) and displays the output in the DOM. It uses Euclidean distance.
Here is the readable code:
```
X = function (str) {
var lines = str.split("\n");
var canvas = document.createElement('canvas');
var z = lines[0].split(u=' ');
var width = z[0], height = z[1];
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var imageData = ctx.createImageData(width, height);
for(var y = 0; y < height; y++){
for(var x=0; x < width; x++){
var coord = (y * width + x) * 4;
for(i=1; i < lines.length;i++){
var t = lines[i].split(u);
var
dx = x - t[0],
dy = y - t[1];
var distance = Math.sqrt(dx * dx + dy * dy);
for(var channel = 0; channel < 3; channel++) {
var channelIndex = coord + channel;
imageData.data[channelIndex] += t[2] * t[3 + channel] / (distance + 1);
}
}
var alphaIndex = coord + 3;
imageData.data[alphaIndex] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
};
```
[Answer]
# Java - 627 bytes
Java is indeed one of the best golfing languages :)
```
import java.awt.image.*;class M{void f(String n)throws Exception{String[]p=n.split("\n");int[]b=s(p[0]);BufferedImage o=new BufferedImage(b[0],b[1],2);for(int i=0;i<b[0];i++)for(int j=0;j<b[1];j++){int[]c=new int[3];for(int l=1;l<p.length;l++){int[]r=s(p[l]);for(int k=0;k<3;k++){c[k]+=r[2]*r[3+k]/(Math.sqrt(Math.pow(i-r[0],2)+Math.pow(j-r[1],2))+1);if(c[k]>255)c[k]=255;}}o.setRGB(i,j,new java.awt.Color(c[0],c[1],c[2]).getRGB());}javax.imageio.ImageIO.write(o,"png",new java.io.File("o.png"));}int[]s(String s){String[]a=s.split(" ");int[]r=new int[a.length];for(int i=0;i<a.length;i++)r[i]=Integer.valueOf(a[i]);return r;}}
```
Using the input below, you can create a somewhat realistic model of our solar system (the size of some planets is wrong, but the distance between them should be accurate).
I tried to give rings to saturn, but it didn't work... [Source](https://en.wikipedia.org/wiki/Solar_System_model)
```
1950 50
-15 25 25 255 255 0
39 25 1 255 0 0
55 25 3 255 140 0
68 25 4 0 191 255
92 25 2 255 0 0
269 25 10 245 222 179
475 25 7 245 245 220
942 25 6 0 250 150
1464 25 6 0 0 255
1920 25 1 255 245 238
```
![Solar system with pluto](https://i.stack.imgur.com/DWAyj.png)
[Full HD picture](https://i.stack.imgur.com/RjdkK.png), which doesn't look thaaat great... Would be happy if someone could improve it!
[Answer]
# Pyth - 46 bytes
This was fun! I finally got to use Pyth's image I/O features. Does euclidean distance because of golfiness, though manhattan is just a short change.
```
Krz7.wcmmsm/*@[[email protected]](/cdn-cgi/l/email-protection),<b2_.DdhKrR7.zU3*FKhK
```
This just loops through all the pixels with the formula's though it condenses the pixel loop into one loop and uses `divmod` since Pyth only supports 3 nested maps and the calculations take two (one for RGB and one for the stars).
Saves image as `o.png`. Pretty slow, does the first 2 tests in <2 min, but the other 2 take on the order of half an hour.
There is a bug in `.w` that no one noticed because no one uses it ;) but I put in a pull request so use my fork to test if isn't merged soon. Merged!
## Examples Outputs
### Example A
![Example A](https://i.stack.imgur.com/unlWG.png)
### Example B
![Example B](https://i.stack.imgur.com/XFFzp.png)
## Example C
![Example C](https://i.stack.imgur.com/hACIu.png)
### Example D
![Example D](https://i.stack.imgur.com/GPOnv.png)
[Answer]
# Bash, ~~147~~ 145 bytes
ImageMagick is used to manipulate images. Euclidean distance is used.
```
read w h
o=o.png
convert -size $w\x$h canvas:black $o
while read x y i r g b
do
convert $o -fx "u+$i*rgb($r,$g,$b)/(hypot(i-$x,j-$y)+1)" $o
done
```
[Answer]
## Python 3, 189 bytes
I'm nobody's idea of an expert golfer, but here goes.
* Input comes from `stdin` and goes to `stdout` in [PPM format](https://en.wikipedia.org/wiki/Netpbm_format#PPM_example).
* Run it like so: `python3 codegolf_stars_golfed.py < starfield.txt > starfield.pnm`
First, Manhattan distance:
```
import sys
(w,h),*S=[list(map(int,l.split()))for l in sys.stdin]
print('P3',w,h,255,*(min(int(sum((I*C[z%3]/(abs(X-z//3%h)+abs(Y-z//3//h)+1))for
X,Y,I,*C in S)),255)for z in range(h*w*3)))
```
And secondly, Euclidean distance:
```
import sys
(w,h),*S=[list(map(int,l.split()))for l in sys.stdin]
print('P3',w,h,255,*(min(int(sum((I*C[z%3]/(abs(X-z//3%h+(Y-z//3//h)*1j)+1))for
X,Y,I,*C in S)),255)for z in range(h*w*3)))
```
I could save four bytes by using integer division instead of `int()`, and in fact that seems to be what the original images do--you can just barely make out some striations in the dark fringes of the star glow that aren't present in strictly correct code. As it stands, though, this code follows the description, not the images.
The ungolfed version, and my original golfing before the many optimisations that others pointed out or that I stumbled upon myself, are in [this gist](https://gist.github.com/perey/c00d2c703d6692feed0d).
**EDIT:** I saved 7 bytes by moving `for x` and `for y` into a single `print` (or `o`) function, but this produces a PNM file with a very long line, which may or may not cause some problems.
**EDIT 2:** Maltysen saved me another 20 bytes. Thanks!
**EDIT again:** Now that there's only one `print`, the `o` alias is a liability, not a saving. 4 more bytes off.
**EDIT some more:** Sp3000 saved me 2 more bytes. Meanwhile, aliasing `map` to `m` wasn't saving anything, so in the interests of readability(!) I've expanded it again. It's now a nice round 28 bytes.
**EDIT the last(?):** Now with Euclidean distance support--and by abusing complex numbers, I did it in exactly the same number of bytes!
**EDIT, the Hollywood reboot:** Sp3000's next suggestion knocked off 5 bytes.
**EDIT, the stupidly named sequel:** 6 bytes trimmed off, thanks to a suggestion Maltysen made that I didn't grasp until Sp3000 repeated it... then *another* 8 bytes from `%` abuse. And talking it out in chat knocked off a phenomenal ~~21~~ 26 bytes. I'm humbled.
[Answer]
# C++, 272 bytes
```
#include<png.hpp>
#define G(a)i>>C;for(x=0;x<w*h;++x){auto&p=img[x%h][x/h];c=p.a+I*C/(abs(x/h-X)+abs(x%h-Y)+1);p.a=c>255?255:c;}
auto&i=std::cin;main(){int w,h,x,X,Y,I,c,C;i>>w>>h;png::image<png::rgb_pixel>img(w,h);while(i>>X>>Y>>I){G(red)G(green)G(blue)}img.write("a");}
```
Needs a lenient C++11 compiler (GCC 4.9.2 is only slightly displeased), and the [png++](http://www.nongnu.org/pngpp/doc/0.2.7/) library, which itself requires `libpng`. Manhattan distance used. Takes input on `stdin`, outputs to a file named "a" in the current directory in PNG format.
Example D:
![enter image description here](https://i.stack.imgur.com/5M5vN.png)
---
![enter image description here](https://i.stack.imgur.com/aptB0.png)
---
![enter image description here](https://i.stack.imgur.com/trQ0j.png)
[Answer]
# Python 2, ~~240~~ ~~232~~ 228 bytes
```
from PIL.Image import*
def f(S):
L=map(int,S.split());t=a,b=L[:2];I=new("RGB",t)
for k in range(a*b):I.load()[k/a,k%a]=tuple(sum(x[2]*x[c]/(abs(x[0]-k/a)-~abs(x[1]-k%a))for x in zip(*[iter(L[2:])]*6))for c in(3,4,5))
I.show()
```
Uses Manhattan distance. This would probably be even shorter in Python 3, but I messed up my Python packages recently and I'm having trouble reinstalling Pillow. PPM would probably be even shorter, but I like PIL.
For fun, I tried to apply the algorithm as is in the [L\*a\*b\* color space](https://en.wikipedia.org/wiki/Lab_color_space) instead, thinking it would give better colour blending (especially in example B). Unfortunately, Calvin's algorithm lets channels go over their max values, which makes the images look a little less awesome than I hoped...
![enter image description here](https://i.stack.imgur.com/ZPLNM.png)
[Answer]
# Mathematica, 146 bytes
```
Image@Table[Total[#3{##4}/255&@@@{##2}/(1+#~ManhattanDistance~{x,y}&/@({#1,#2}&@@@{##2}))],{y,0,Last@#-1},{x,0,#&@@#-1}]&@@#~ImportString~"Table"&
```
A pure function taking a string. To run it in a reasonable amount of time, replace the `1` in `1+#~ManhattanDistance...` with a `1.`; this forces numeric computation instead of symbolic.
Ungolfed:
```
Image[
Table[
Total[
(#3 * {##4} / 255 & @@@ {##2})
/ (1 + ManhattanDistance[#, {x, y}]& /@ ({#1, #2}& @@@ {##2}) )
], {y, 0, Last[#]-1}, {x, 0, First[#]-1}
] (* Header is #, data is {##2} *)
]& @@ ImportString[#, "Table"]&
```
[Answer]
# Python 2, ~~287~~ 251 bytes
A golfed version of the original code I used to generate the images. Could probably be golfed a bit more (by a better golfer than me). It's a function that takes in the full input string. Image processing done with [PIL](http://www.pythonware.com/products/pil/)'s [Image Module](http://effbot.org/imagingbook/image.htm). Uses Manhattan distance.
```
from PIL import Image
def S(I,r=range):
I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
for z in r(w*h):
P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1.+abs(I[i]-z%w)+abs(I[i+1]-z/w))for i in r(2,len(I),6)))for j in r(3))
M.show()
```
Using Euclidean distance is 5 bytes longer (256 bytes):
```
from PIL import Image
def O(I,r=range):
I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
for z in r(w*h):
P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1+((I[i]-z%w)**2+(I[i+1]-z/w)**2)**.5)for i in r(2,len(I),6)))for j in r(3))
M.show()
```
Here's a complete test suite that runs examples A through E from the question, for both distance metrics:
```
from PIL import Image
def S(I,r=range):
I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
for z in r(w*h):
P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1.+abs(I[i]-z%w)+abs(I[i+1]-z/w))for i in r(2,len(I),6)))for j in r(3))
M.show()
def O(I,r=range):
I=map(int,I.split());w,h=I[:2];M=Image.new('RGB',(w,h));P=M.load()
for z in r(w*h):
P[z%w,z/w]=tuple(int(sum(I[i+2]*I[i+j+3]/(1+((I[i]-z%w)**2+(I[i+1]-z/w)**2)**.5)for i in r(2,len(I),6)))for j in r(3))
M.show()
A = """400 150
-10 30 100 255 128 0"""
B = """200 200
100 100 10 255 255 255
20 20 40 255 0 0
180 20 40 255 255 0
180 180 40 0 255 0
20 180 40 0 0 255"""
C = """400 400
123 231 10 206 119 85
358 316 27 170 47 99
95 317 3 202 42 78
251 269 17 142 150 153
43 120 3 145 75 61
109 376 6 230 231 52
331 78 21 31 81 126
150 330 21 8 142 23
69 155 11 142 251 199
218 335 7 183 248 241
204 237 13 112 253 34
342 89 18 140 11 123"""
D = """400 400
123 231 5 206 119 85
358 316 5 170 47 99
95 317 5 202 42 78
251 269 5 142 150 153
43 120 5 145 75 61
109 376 5 230 231 52
331 78 5 31 81 126
150 330 5 8 142 23
69 155 5 142 251 199
218 335 5 183 248 241
204 237 5 112 253 34
342 89 5 140 11 123"""
E = """100 1"""
for i in (A, B, C, D, E):
S(i) #S for Star
O(i) #O for Orb
```
They all look indistinguishable. The larger ones may take a few seconds to run.
[Answer]
# C, 247 bytes
Not going to win, but I like to golf in C. No external image library used, outputs to stdout in PPM format. Takes input on stdin. Uses Manhattan distance for golfiness.
```
j,w,h,k,*b,t[6];main(){scanf("%d %d",&w,&h);b=calloc(w*h,24);for(;~scanf("%d",t+j++%6);)for(k=0;j%6?0:k<3*w*h;k++)b[k]=fmin(b[k]+t[2]*t[3+k%3]/(abs(k/3%w-*t)+abs(k/3/w-t[1])+1),255);printf("P6\n%d %d\n255\n",w,h);for(k=0;k<3*w*h;putchar(b[k++]));}
```
Here's the Euclidean distance variant (257 bytes):
```
j,w,h,k,*b,t[6];main(){scanf("%d %d",&w,&h);b=calloc(w*h,24);for(;~scanf("%d",t+j++%6);)for(k=0;j%6?0:k<3*w*h;k++)b[k]=fmin(b[k]+t[2]*t[3+k%3]/(sqrt(pow(k/3%w-*t,2)+pow(k/3/w-t[1],2))+1),255);printf("P6\n%d %d\n255\n",w,h);for(k=0;k<3*w*h;putchar(b[k++]));}
```
[Answer]
# CJam, 86 bytes
```
q~]"P3 "\_2>:T;2<_S*" 255 "@:,~\m*{(+0a3*T6/{_2<3$.-:z~+)d\2>(f*\f/.+}/:i255fe<\;S*S}/
```
While this may look kind of lengthy for a golfing language, I believe that of the solutions posted so far, it's the shortest that does not use image output functionality. This produces a PPM file in ASCII form. The image below was converted from PPM to PNG using GIMP.
I do not recommend to run the code in the online CJam interpreter. At least not for the full size images. My browser locked up, most likely because of the memory usage. It completes the 400x400 images in the second range with the offline version.
![Example C](https://i.stack.imgur.com/WDawD.png)
Explanation:
```
q~ Read and parse input.
] Wrap it in an array.
"P3 " Output start of PPM header.
\ Swap input to top.
_2> Slice off first two values, leaving the star descriptors.
:T; Store star descriptors in variable T.
2< Get first two values in input, which is the image size.
_S* Leave a copy of the size in the output for the PPM header.
" 255 " Rest of PPM header, range of color values.
@ Pop sizes to top.
:, Expand sizes to ranges.
~ Unwrap size ranges into separate stack elements.
\ Swap ranges, since we need x-range second for Cartesian product.
m* Generate all coordinate pairs with Cartesian product.
{ Loop over pixel coordinate pairs.
(+ Swap values in coordinate pair to get x-coordinate first again.
0a3* Generate [0 0 0] array. Will be used to sum up colors from stars.
T Get list of stars.
6/ Split into sub-lists with 6 values for each star.
{ Loop over the stars.
_2< Get the first two values (position) of the star.
3$ Pull current pixel coordinates to top of stack.
.- Subtract pixel coordinates from star position.
:z Absolute value of difference.
~+ Unpack differences and add them to get Manhattan distance.
)d Add 1 and convert to double to get denominator of formula.
\ Swap star values to top.
2> Slice off first two values, leaving intensity and color.
( Pop off intensity.
f* Multiply it with color values.
\ Swap denominator to top.
f/ Perform division of color components by denominator.
.+ Add it to sum of colors.
}/ End loop over stars.
:i Convert double values for colors to integer.
255fe< Cap color components at 255.
\; Swap pixel coordinate to top and pop it.
S*S Join color components with space, and add another space.
}/ End loop over coordinate pairs.
```
[Answer]
# C# 718 bytes
I realize that c# is terrible for golfing, but here's my attempt at 718 bytes
```
namespace System{using Collections.Generic;using Drawing;using Linq;using O=Convert;class P{int j,i;List<S> s=new List<S>();Image G(string t){var l=t.Replace("\r","").Split('\n');var w=O.ToInt32(l[0].Split(' ')[0]);var h=O.ToInt32(l[0].Split(' ')[1]);for(i=1;i < l.Length;i++){var p=l[i].Split(' ');s.Add(new S{X=O.ToInt32(p[0]),Y=O.ToInt32(p[1]),I=O.ToSingle(p[2]),R=O.ToByte(p[3]),G=O.ToByte(p[4]),B=O.ToByte(p[5])});}var b=new Bitmap(w,h);for(j=0;j<h;j++)for(i=0;i<w;i++)b.SetPixel(i,j,C());return b;}Color C(){return Color.FromArgb(X(x=>x.R),X(x=>x.G),X(x=>x.B));}int X(Func<S,float>f){return(int)Math.Min(s.Sum(x=>x.I*f(x)/(Math.Sqrt((x.X-i)*(x.X-i)+(x.Y-j)*(x.Y-j))+1)),255);}class S{public float X,Y,R,G,B,I;}}}
```
If anyone has any suggestions to shorten it, feel free to let me know.
[Answer]
# Python, 259 bytes
Finally done! First code golf I've tried, decided to use Python and went with the Manhattan distance. Shoutout to Maltysen for helping me with the iterators, reduced the total size to almost half!
```
from PIL.Image import new
N,*s=[list(map(int,i.split()))for i in iter(input,'')]
q,m=new("RGB",(N[0],N[1])),[]
[m.append(tuple(sum(k[2]*k[i]//(abs(k[1]-x)+abs(k[0]-y)+1)for k in s)for i in(3,4,5)))for x in range(N[1])for y in range(N[0])]
q.show(q.putdata(m))
```
[Answer]
# CJam, 70 bytes
```
"P3"l_~\:W*255\,[q~]6Te]6/f{\[Wmd\]f{.-Z/~\)\~mh)/f*}:.+{i255e<}/}~]S*
```
Euclidean distance, ASCII PPM output. [Try it online](http://cjam.aditsu.net/#code=%22P3%22l_~%5C%3AW*255%5C%2C%5Bq~%5D6Te%5D6%2Ff%7B%5C%5BWmd%5C%5Df%7B.-Z%2F~%5C)%5C~mh)%2Ff*%7D%3A.%2B%7Bi255e%3C%7D%2F%7D~%5DS*&input=100%20150%0A-10%2030%20100%20255%20128%200)
It should be possible to squeeze a few more bytes, but I don't want to spend too much time.
] |
[Question]
[
It's that time of year when many of us get our [advent calendars](https://en.wikipedia.org/wiki/Advent_calendar)! If you are unfamiliar with an advent calendar, these are special calendars used to count down advent in anticipation of Christmas. In my experience the doors are placed randomly, and part of the fun as a child was working out where tomorrow's door was! Often these days, calendars have chocolates behind each door, but instead of buying an advent calendar this year, you should build an ASCII one!
## Task
Given input of an integer (`n`) in the range `0`-`24`, produce an ASCII advent calendar with the numbered doors up-to `n`, opened. You must use the same order as in the below example: `2`, `17`, `8`, `12`, `1`, `6`, `11`, `20`, `5`, `22`, `3`, `10`, `15`, `23`, `7`, `16`, `9`, `24`, `18`, `4`, `13`, `19`, `21`, `14`.
## Doors
The closed door must be:
```
.-----------.
| |
| |
| |
| nn |
|___________|
```
where `n` represents the number of the door (leading zeros are optional) and the opened door is:
```
.-----------.
|\ |
| | |
| | |
| | |
| |_________|
\|
```
except for door 24, which is instead:
```
.--------------------------.
| |
| |
| |
| 24 |
|__________________________|
.--------------------------.
|\ |
| | |
| | |
| | |
| |________________________|
\|
```
These doors are arranged within a frame of 37 lines of 79 characters, with two spaces between each column, and an empty line between each row.
## Opened Doors
When the doors are opened you must display one of the (tenuously Christmas related - apologies for my terrible art skills!) pictures below within the door:
```
. _ . _'_ + .^o _(")_ _n_ $ .
}\O/{ ) (^.^_ /~\ (';') (_ . _) (") |,| __/ \__
}/*\{ \./v`v' /~*~\ {\|+|/} / : \ >( o )< | | `. .'
/***\ oO8 /~*~~*\ d-b (_/ \_) ( o ) ._|_|_. /.^.\
.\^/. ____ __.==,_ .*. _ _ . . . _______ _ _
<->o<-> /_%_/| --|XX|- /.\ (O X O) .i_i_i. _j_j_j_ ( `v' )
'/v\` |_|_| | _| | |_-_| / ^ \ |-~~-~| ||__| \ /
|_|_|/ (____' (.-o-.) \/ \/ |_____| _|/$$|_ V
i |~| //'`\ |=| _{/ _{/ , * \ ==== b
.'%'. | | //....\ / \ \_/ + . + \\\|+-| .'''.
|^~~.~| Y ||()()| |(%)| /O \ . ' . \\\\\+| {*=*=*}
_'._.'_ _|_ ||_[]_| |___| @__,/\\ ~~~~~~~ \\\\\\\ '._.'
_ | _ | .W. .W. .&%$+*. \O/ .;' ..,.;.. ('v')
.'.'O | ($) | |*| |*| */'"'\& [ ]|_. .m_. |\\|//| // \\
/___\ | " o| |*| |*| $\._./% |_____) C| | \\|// |\ /|
(_____) | === | 'M' 'M' '%&*+$' ------' |__| _=|=_ Y Y
\ / .==. .-. -._.- __/\__ ... .-.
._o_O_. .--' | \| |/ .+. \_\/_/ '* ` //`);
|/\/\/| \_____/ /| |\ ( W ) /_/\_\ |_/\*_| %%
""""""" `=====' '-' `"` \/ [_____] //
```
Each image is 7 characters long and covers 4 lines so they will fit within the windows. You are free to choose any of the above images and use them in any order, but you may not repeat an image. For the 24th, you must also add a message:
```
~
~ MERRY ~
~ CHRISTMAS! ~
~~~~~
```
which fits alongside one of the above pictures, you can choose whether the text is to the right or the left of the image.
## Examples
Given input `0`, output the calendar with no doors opened:
```
.-----------------------------------------------------------------------------.
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | 2 | | 17 | | 8 | | 12 | | 1 | |
| |___________| |___________| |___________| |___________| |___________| |
| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | 6 | | 11 | | 20 | | 5 | | 22 | |
| |___________| |___________| |___________| |___________| |___________| |
| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | 3 | | 10 | | 15 | | 23 | | 7 | |
| |___________| |___________| |___________| |___________| |___________| |
| |
| .-----------. .-----------. .--------------------------. .-----------. |
| | | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
| | 16 | | 9 | | 24 | | 18 | |
| |___________| |___________| |__________________________| |___________| |
| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | | | | | | | | | | |
| | 4 | | 13 | | 19 | | 21 | | 14 | |
| |___________| |___________| |___________| |___________| |___________| |
| |
|_____________________________________________________________________________|
```
For input `5`, output something similar to:
```
.-----------------------------------------------------------------------------.
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ . _ . | | | | | | | |\ __.==,_ | |
| | | }\O/{ | | | | | | | | | --|XX|- | |
| | | }/*\{ | | | | | | | | | _| | | |
| | | /***\ | | 17 | | 8 | | 12 | | | (____' | |
| | |_________| |___________| |___________| |___________| | |_________| |
| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| | | | | | | |\ _{/ _{/ | | | |
| | | | | | | | | \_/ | | | |
| | | | | | | | | /O \ | | | |
| | 6 | | 11 | | 20 | | | @__,/\\ | | 22 | |
| |___________| |___________| |___________| | |_________| |___________| |
| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ _n_ | | | | | | | | | |
| | | (") | | | | | | | | | |
| | | >( o )< | | | | | | | | | |
| | | ( o ) | | 10 | | 15 | | 23 | | 7 | |
| | |_________| |___________| |___________| |___________| |___________| |
| \| |
| .-----------. .-----------. .--------------------------. .-----------. |
| | | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
| | 16 | | 9 | | 24 | | 18 | |
| |___________| |___________| |__________________________| |___________| |
| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ + | | | | | | | | | |
| | | /~\ | | | | | | | | | |
| | | /~*~\ | | | | | | | | | |
| | | /~*~~*\ | | 13 | | 19 | | 21 | | 14 | |
| | |_________| |___________| |___________| |___________| |___________| |
| \| |
|_____________________________________________________________________________|
```
For input `14`:
```
.-----------------------------------------------------------------------------.
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ . _ . | | | |\ . | |\ ____ | |\ __.==,_ | |
| | | }\O/{ | | | | | __/ \__ | | | /_%_/| | | | --|XX|- | |
| | | }/*\{ | | | | | `. .' | | | |_|_| | | | | _| | | |
| | | /***\ | | 17 | | | /.^.\ | | | |_|_|/ | | | (____' | |
| | |_________| |___________| | |_________| | |_________| | |_________| |
| \| \| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ _ | |\ $ | | | |\ _{/ _{/ | | | |
| | | .'.'O | | | |,| | | | | | \_/ | | | |
| | | /___\ | | | | | | | | | | /O \ | | | |
| | | (_____) | | | ._|_|_. | | 20 | | | @__,/\\ | | 22 | |
| | |_________| | |_________| |___________| | |_________| |___________| |
| \| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ _n_ | |\ _(")_ | | | | | |\ |=| | |
| | | (") | | | (_ . _) | | | | | | | / \ | |
| | | >( o )< | | | / : \ | | | | | | | |(%)| | |
| | | ( o ) | | | (_/ \_) | | 15 | | 23 | | | |___| | |
| | |_________| | |_________| |___________| |___________| | |_________| |
| \| \| \| |
| .-----------. .-----------. .--------------------------. .-----------. |
| | | |\ \ ==== | | | | | |
| | | | | \\\|--| | | | | | |
| | | | | \\\\\-| | | | | | |
| | 16 | | | \\\\\\\ | | 24 | | 18 | |
| |___________| | |_________| |__________________________| |___________| |
| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ + | |\ , * | | | | | |\ i | |
| | | /~\ | | | + . + | | | | | | | .'%'. | |
| | | /~*~\ | | | . ' . | | | | | | | |^~~.~| | |
| | | /~*~~*\ | | | ~~~~~~~ | | 19 | | 21 | | | _'._.'_ | |
| | |_________| | |_________| |___________| |___________| | |_________| |
| \| \| \| |
|_____________________________________________________________________________|
```
For input `24`:
```
.-----------------------------------------------------------------------------.
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ . _ . | |\ //''\ | |\ . | |\ ____ | |\ __.==,_ | |
| | | }\O/{ | | | //....\ | | | __/ \__ | | | /_%_/| | | | --|XX|- | |
| | | }/*\{ | | | ||()()| | | | `. .' | | | |_|_| | | | | _| | | |
| | | /***\ | | | ||_[]_| | | | /.^.\ | | | |_|_|/ | | | (____' | |
| | |_________| | |_________| | |_________| | |_________| | |_________| |
| \| \| \| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ _ | |\ $ | |\ |~| | |\ _{/ _{/ | |\ . . . | |
| | | .'.'O | | | |,| | | | | | | | | \_/ | | | .i_i_i. | |
| | | /___\ | | | | | | | | Y | | | /O \ | | | |-~~-~| | |
| | | (_____) | | | ._|_|_. | | | _|_ | | | @__,/\\ | | | |_____| | |
| | |_________| | |_________| | |_________| | |_________| | |_________| |
| \| \| \| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ _n_ | |\ _(")_ | |\ | _ | | |\ .W. .W. | |\ |=| | |
| | | (") | | | (_ . _) | | | | ($) | | | | |*| |*| | | | / \ | |
| | | >( o )< | | | / : \ | | | | " o| | | | |*| |*| | | | |(%)| | |
| | | ( o ) | | | (_/ \_) | | | | === | | | | 'M' 'M' | | | |___| | |
| | |_________| | |_________| | |_________| | |_________| | |_________| |
| \| \| \| \| \| |
| .-----------. .-----------. .-------------------------- .-----------. |
| |\ _ _ | |\ \ ==== | |\ .&%$+*. ~ | |\ \O/ | |
| | | (O X O) | | | \\\|--| | | | */'"'\& ~ MERRY ~ | | | [ ]|_. | |
| | | / ^ \ | | | \\\\\-| | | | $\._./% ~ CHRISTMAS! ~ | | | |_____) | |
| | | \/ \/ | | | \\\\\\\ | | | '%&*+$' ~~~~~ | | | ------' | |
| | |_________| | |_________| | |________________________| | |_________| |
| \| \| \| \| |
| .-----------. .-----------. .-----------. .-----------. .-----------. |
| |\ + | |\ , * | |\ | | |\ .*. | |\ i | |
| | | /~\ | | | + . + | | | .'''. | | | /.\ | | | .'%'. | |
| | | /~*~\ | | | . ' . | | | {*=*=*} | | | |_-_| | | | |^~~.~| | |
| | | /~*~~*\ | | | ~~~~~~~ | | | '._.' | | | (.-o-.) | | | _'._.'_ | |
| | |_________| | |_________| | |_________| | |_________| | |_________| |
| \| \| \| \| \| |
|_____________________________________________________________________________|
```
## Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes, in each language, wins.
* Any reasonable format can be used for I/O assuming it is consistent.
* Any amount of whitespace before and after the calendar is fine, as well as additional spaces/unprintables at the end of each line, but nothing before each line as this must fit into 80 characters.
* All [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/9365) are forbidden.
## Thanks
[James Holderness](https://codegolf.meta.stackexchange.com/users/62101/james-holderness) for contributing ASCII images!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 666 bytes
```
J⁶³¦³⁰←×⁷⁷_↑³⁶.→⁷⁷↓.↓³⁶↖J±⁷±⁴”}➙◧﹪ε⎆T⎆¿⊘W?⁸ω⁷{↙n,θ<YθTLUeK%I(+↥C…hχRνGζ)ητR✳⮌⁹πj,⊞R∕!lD)CN✳χG-=ê⊕l⟧RP↙§m∧E⁴F≧GW!↨⪪⟧⟦⟦X=G﹪ς←´:¦B^⟲⊟H⌀SM⦃}´↶E$zfI⮌εÞ⁶ι⟦⁺~W]XιθZ¦@|θ⦃‴1₂↑dA=÷PTι^V⪪Na÷⌈b#lQ+;BT⟲⌀6↑↥\⁺◨ⅉ8'Àq;?.6μ″D⎇M3§ν⁻φG>2Σ¿⟧u←@6nh¹⮌↧,‴¹f↧M⁵|Dυχ¶3⊘>γQ·UB×NO³{Lκ3¤³ν⊕φβ.¤+xl⁷MΠ⦄η+L➙⁺[Dσ◧;≔e=F⊘ξρHλκL`S"d|N℅⊗0§χ~vH⍘À§⊕g↖c@Π]R¦⎆πEx⁶⪪~;⸿j}⊗⊙↷A‹›N·?CX[´m'Jχ0`-⪫νd⪫⎆/M⍘ζG&G⟲F¿G⍘×.#ςςm≧ω²Eⅉmv`⊞ω9Þ·'ZNN→J&γQ«T~_J6◨z⪫OBg¤upε↷~⁵T«P{Zr»λ≔u⧴⁰ⅈ|≕q⊕≔χz⮌…@MυA➙⭆/TLF}¤N*N⁰⁶↖¬∕κE>α;|W"h↙⊘⁹}Σ1⁰g⮌FRü0AÀ⊗"⁸$”F⁵F⁵«J×¹⁵ι×⁷κ←×¹¹_↑⁵.¹¹↓.↓⁵»F²³«J×¹⁵I§”o⊞O↧▷⁰$ê;”¦ι×⁷I§”o⊞-Y~Fι,]”¦ι¿‹ιIθ«Mχ←↓ →\↑⁵← \»«↖UO±⁷±⁴ ←←⮌I⊕ι»»J³⁴¦¹⁷↓ H ←____↗↑ ~ ⁴¿‹²³Iθ«J²⁰¦¹⁷↘¹↓⁵↖↑\ »«J⁴⁴¦²⁰UO±²²±⁴ ← 42
```
[Try it online!](https://tio.run/##dVZ/b9s2EP3b/RQ3wY4oRSL1KzWQ1cOKbkBTNHPhpliKsuHSVEmNJlJru@mA0PrqHknJ4tHxKBD2kbynd488nq6@XC6u6svbzebVj7tvZzV5mkeQJ8GvT94s5tWKHL8ur1cRnM3vyiUZjyPwhBfY2Xff1Oqnve1Rz87N5jdflOt4bIf@qH9WCgKvaocMxml9X2pI/UpldoT@Km8uVyUZBxF0fwtLwAMKQvW@Meb7nANqFBsgVEMGnUwiwStYcz5lDwiFqmZxhGDAOfJkYiSY3FpxLM/PZaxxWMi5xZGSBCTo1/2juVC/nxXqAWnpqL9SgbAwDFEMUooPH4VdxugFxdMahfUm0RH6vGofA@sIMHQs2UikzQMz3SqnHo1BfepPkVMkHQxwTKUTQ@rPhXo0ClO8nJ3Z8YP3jsWmgIOMmyZulDgmPBH08Dp4gbZYWdb4XYiIcW5xpPGWVh1RYXUE4V4gEEGtXU@S/k1Nt/MTvVugnQDpr49kYDHIMLAYMpSm2zBVlLz6jUANwTM0euxEr1T1oP5fFElGgdYGFAoElok5tIjKZDKxVPxT33SsjVVGOAdHc5lo760UB6PhYbiVooHdprNJ8ZnCOUwDO6ibVMmyHQmZzz2VrgcG5PTP2ey9A/YBPqrN1WcHLrAevG8Wa8g5FZSNFMCLl7OTt2enz9/@YtHanQ8UFufM9Mdg@KT4o4PwcNiq0@jmxBebhrPsEE9HOjY3RZwbKXTvpLlGYA1OjkOdfQiT@r6PnRh1Uon6I9/o1ISNOwG@vQAfwol61mjHY3StyIumoTrFNEiDLqCmcQXwlc722BAa1zHtN1mYWXWl6iv@ul4AOQpg@/vwZNBd6m09SY8imAd9dYngq77ZB3sqT5r2lWeASs@Rtdui0hlpihbiouOOafd1yzLL99N7cblckeerk@pz@S/xiiRJ8qTI0jTN0yJLVM/yIvd0GAEOxHVLkqxI0yzJszQpiixP8iIt0qxz07Tm10Bel8slmXe@39W4JjQwRTFNIjjuyuJgJy7w8GBXdD3OneFeLFdcD7p1ayhvl6V9oa3Cg8H0021d3eytw/b1rdcuxfYts/K@XCxLYgI7qa4W5V1ZrcrPZBv9Wu1Cp3xeRJA@/mIAeAne7keJp1PaQx8OJnj348TTV4D1LNS/Xuss3xG745AlHQesdCdsuvcQPRINM1CZpAlYibvXFCrUTH9p7SicZXsl3tm4IjOgm01WbOL72/8A "Charcoal – Try It Online") Link is to verbose version of code. Not really golfed, but I'm not sure I want to...
```
J²⁵¦³⁰←×_³⁸↑³⁶.→³⁸‖OF²⁴«J×I§”o⊞∧№qGo⁴↨'”¦ι¹⁵×I§”o⊞Þ‹wα≕YQ”¦ι⁷≔⎇⁼²³ι²⁶⊕χη←×_η↑⁵.η↓.↓⁵↑¿‹ιIθ«Mη← ¶\↑⁵← \M⁴→…⪪✂”}⊞μ↓↙J∧W⎚2⁻⁹]jι|T◨%êⅈπ↔{Mⅈ⎇_u9⁹F⪫4AGhd⪫CNb↷a^AnQ⌀oV←×⟦c″⁵FιO↗ωsXςb⁶β|(α)ⅈ,gB№$¹ξU=◨↷…Yn´;⎆Σd$=1%▷≦″“}υ⌈ν§V?Wξ⌈‖⦃⊗↓⎚K⎚✳V✳V?↗⎆¶﹪⊙⟦≧*(▶″$Q;\⟲↶A⊗s≧»Πj⁸⎆↑´T≡⁵K⊙αηI3⊙✂“↗⌕N~e%⬤Iη◨γ·y⁸_Gλ↙%EO)⎆$YP“¦7ê⁵№¹▷⟦α)ν&℅◨⦄S“⁹aEX>➙8)↨§+φ✳⁸WR&;⎚◧⎆¬▶B³u▷J±÷δ+⁺↖M≧;↧χw➙Oθ✂⁺⁶r⟦GεCVY↖<⁻◧⁹DK‴1⌀✂$k\φ{0·M℅,ρ)S⎇⸿3oψJ5$\`↗⁰⊙0c¤?&?⌕↗Uε¦⎆~b&d⊞÷f¬;T-χUnν⁶{⊖″;f._⟦#⊗V2⍘¬T.(⁻<V⊗№êx⊕₂⦃ΣσGτ¹yΣ2⁶⧴em⁷WÀI>]≔A↘_2↓⁴⸿¦y⌕ⅉ﹪B7”×ι²⁸φ¹⁻η⁴¦⁴»«↖←←←⮌I⊕ι
```
[Try it online!](https://tio.run/##dVRtb9MwEP68/oojahcnS@y8DRCjiAmQGKIq6oY2NG@m6lwaKUtG0w3QvPz1cr50bfdhZyVn3/tzlm8yG88n1bhYLr/cXt@cVCzZDyCNvIPOt3leLtibr3q6COAkv9Y1c5SDytfeRvv9BgUv12eHOxvdKP81W5D9QWekp4WeLIZ3el6MbxhKptUcWJJ5cN/ZWaVuk3wY1wt2uDgqr/Rf5mRRFKVRlsRxnMZZEuGXpFmaYiG55wUQ73uP1T11jKIki@MkSpM4yrIkjdIszuJk7fjKotg5rOv8V8lO9Lwcz/@xT79vx0XNktQaBZC8DOConMz1tS4X@orFEQpn1u@55sy8La1tzv7m3DZnddiO8rH6UwbwRL2SkfegutM2mN3nU2BfdV2zPADC@9vzqIWt1SwAqsmaPmYFWUrpbEk2dT2FgZYrO4qVYSy6wi3LQVVcseObIl@w4yKfaASteL8fqDA0Z2cmBGUADDCF5AJwUPjBg5RDcY9c@FIiF76PGwBQpcI/MEwL8I5BBd5bBsgAz7BndSAaMhWNbzeWNeis7gXYD0tWgsyGuIX3SgVCSvIAis1d7g5BYD0opLoUxjZ9Q05Alob1PFs36kjMrbOySqV@cgoCgl9yNLb2fSRJZBC2XNP2nmpQFpjCrLYRHmZ7A1QERbYIu4TQBJTV4AKuDC5u8yusX6ieEsaKUEsMwQZo7NvucGoRBxd40xIe8xZ1z@VgLpuGN0a5XHHXQsOIBm@n61kG0oEKOaLBzIoaxoZwBkNb6iVBlVLQB0K4rm2/4EgI3DCPeQZLOr@wge0FA5zDha3dtF0OiVxCRiW5WNK938f1AFSSVTUb7Eg/6I84ycPndEm8vSQVYibGwyrkHoKmlStc3IRNEzamzWv4KSpOufExqG9WzB24gB/f7XX32rBIzYr7wpUOwtsl2eDTaPSDdF0psUzRw8OHz6Oj45PB4fELaNzerr/XddsQq64DOI9zAF9m8hrnxBSHE7JBXt7W9mFmdupkNB8eQBe13jxbfJHrV9sKnjs@ebAjjeO01u3g255TOODaPJ2H5TLJluFd8R8 "Charcoal – Try It Online") Link is to verbose version of code. This is a version that draws the presents separately for ~~577~~ ~~541~~ 530 bytes after I've stolen several ideas from @Charlie to golf a few more bytes off.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 676 639 614 607 598 590 564 561 bytes
```
P⁴⁰↓.↓³⁷M↗׳⁹_‖OF²⁴«≔⌕”%↖∧F◨℅V⊖⎚λJ↷;φε⊟ ↧”§βιε≔⎇⁼²³ι²⁶⊕χαJ×﹪ε⁵¦¹⁵×÷ε⁵¦⁷M³¦².α↓.↓⁵↖←×⁻α²_¿‹ιIθ«M±¹±⁴↘¹↓⁵↖↖\↑⁵M⁴¦¹EE⁴⁺×﹪ι⁸¦⁷×⁵⁶⁺κ×⁴÷ι⁸✂”}⊞r⌕⁸⸿‹;β/|∧±⪪I÷=EE%±÷ü5>ü⊘-▶⁹⦃vy⌈#$“o⊟ⅈ‖zMq‖s0YV↔↔|⎈⁹'⁸γ₂βxM¿yH⌕.➙↧↘⁻³]υ|tψ⧴À‹>8Φπ;V}Qλjgd↔⟲|WU(‖J⁴⁹XJx#aα➙?⁰N@⁵=πX⭆›*≡ηΦzgQ±tJ;∨≦K⪫9⁸πcω2-0CγN8|x43,BDua←A9M№»⎚‴dN|k9<·⊖R?Tρe»∧=₂₂~⁰i³e4⮌↖λ″OÞν%≧Jj◧SLÀ·Π_B₂Tσ-*¬y&XWP›J↔À≕²ψT↘b▶“ζX↙ΣψSCμ#×I?K%H6Kⅉ⁸OH…⁸Uⅈ«j×⟦χ~gP% ¦◨⦄⟲24;⦄▷Y>≕À▶;DψJψYN(N-⊞K‹▷⦃Ug∧⦃8⊕|·HO;JZ⎇*>GPM⮌Σ�“P²⁼↶w66›λ⁼±⧴ι⊟uβρ⁻C⊙Z+%oΣVLtY1O≦ O|ηf±h﹪φ⊟”¦κ⁺κ⁷M⁸±⁴¿⁼²³ι”¶<↑?≡DTh¤WSWV~≔✂r₂b…wSεGl≔TêE¶(…R↘�”»«←__↑⁵M⁻Ღ⁴←⮌I⊕ι
```
[Try it online!](https://tio.run/##TVTtThNBFH0VEqwaFFREAkFARdSgRgwK/tA0iAoiCRFBgYDZRVi2DSEYoQWtrZ9bbBXd7cd22yEks/9n3@G@wDwCnqkYTXY7na97zz33nB0aGZwYGh8c29@X7BfpedJ/kfGmAS/Pke5K9oOMuB9XEy9MWkyyn5JZ3MFRnqXIOq1skPY@REaMzPQlim/T4lI/RWO0@lZUeshw2wJDFCiaqiEjjZM8LRzhYQVXV5dJZ9zhOeGpgEWKbgTLwpYs48ell8EhvcAt7mHw4757MP@Diuew4zQI@wAtthQGY82Pk14RNnfCfI80T3iSfRMlnlV3bO5xWxVpbCLqv0uxu2S8xkRVi7qQUrKveKp8lP@AAYpSNblKUFBo9bIoq0ke0NQuJRZQ4DxFkxOKFSyUFII24ZyQuwnQg9yZDOD4bns3ooe47bs@O9PhM4pu1lMMIT2yXj2foRWz9hBpiXHwRksmaJ8FtKcYn52UzOsnYx3PHK2auHEEmUSOFhaEM32d781cQfIGSm4pvo1NkMFz94IlIJgMTErnfQ2YOlqEFWiSvZOsOC@ZLSqjww9U1JSDgwO3j1Y7nanWDy5KPdO1g6A6udUJfUi2cw4UtKsAJfphkFauo8hH4Qprdvgmtyd72sjcpoh1lTLZVqALtKEg0lh/skvkcLcFGaabTh@X7JNkX6YG0bPzrYr5xRivQDak5R/g2NyT1rPchZIkczolywf6Q2yb6XZUiuclgDzmuYdNtLOCBooKaQj@00@K3RBF0j2jFE9Llrvma9wVH8IXcEUFeVVfx7/PHL4z0AvUkOc66IhscCcwsQu67qsuaAlRvEPGlvgcmH1dgtVCAeybZCnJsiHJtpsx0lIEld3AjDSooiRZAZ3i2VEoImUFy3I3OQxHhWqgGZjCWgS1jU1gXP2NQcFeBxIje6yIxYsqf0b9gO2do3jrISOVRvNwGqK4PYzaMbbAJHMc97erTkQDoagyrFTXcblXsbizIj7LvV0UgfTKVoyM4ovmZtQLkuA3GyKAXqOpKeEEOvTRRdEtxDgWGsdNBjjfJ4HjFOKjhzU30C7hPuL2CFwQGEqRcLElylX9H3wiYA3lKzjur6HVoeJZ2KoT0kCfb43wLwN9krn9YEaZP7EwgZ7cB3sv0CdRuDyG1Vt@ppsXoT4LXUc7qoW85xV8aoy1cPg/l1YtrvyIrq2haDQIzAhvf7@x6Tc "Charcoal – Try It Online")
Here you have the [verbose version of the code](https://tio.run/##hRT9T9s49Hf@ireIKnZx7FHKxsGYhradjmm9ToWdmC5XN7QueJQEmrTb1DT/eu89O2WFnXTPepbf95ft4XUyHWbJZLXqzCaF/TS1acHaz/nRlj8evsu@pSKQwRMO7L1ETiebG3b4@a5nr66LB41ze2tytvebCHTAkdsz44kZFt25mU6SO4accTYF1mpzWGwBnOS5vUrZ7zYdseDy/nqSjG8KMx9@zb5d3dnvMB3d5rM0ECfFaToy39mlsJwLMOjnwfjcTNNk@oO9v58lk5y19lBHtF6InR22@xy1E6f8YXZ7d57V@XWy0WySMSP2udhFBM8@TYt3dm5HxktecmfpCt0TLUf4Kn1P1lSycd7s2WMe7P/0hm37aMbFpg7R6zw6Np3lLMGQ6zYC2DGwjybPmRVvk7xg95z7FtYu/zRXSWHYLhf1qe3tHiXhZiV2fxWss/uP/B70PE9AEMfBU8kT@/aTGB0cPWFbnIxGj2dgxQF1Wnjm/guncVOTbfFzJKToQJxN7NCwACRowlCDhx23y36Gu2aYJAl06sXbXkfStozjrloAB9aXfRSrKo6RzcKjEHnOKUcSPZB2KUp0oxXEsdawVM04XuBZqvlgHqJtk6wXcVzulGoJCg5RCK8ZZMBfoTUuGFBYicrNZpNCZd0DAGdaOXoUXWI8H4IzlANwqUtcEpTsS9LBra/Ij0bATR4fC8xdNh3Po3RLe6iZr6LXGSIo3dCqjKLy4qKMMLhzyrpwAV0urcYl9Ve3GFBhHEI1j@MBUBpUBW5US6kjOinoU51lVFVRheJSE9f1UdXz8JYKC0MIgckoiyRHHeWwdFmSxvZ2Sbn@5a2st0Wn6EqFA@ezPKYhLJRDgYymm2bk5nnpzmEjJMo1XCmJQJbK50SdVe6KSHdPlBrwI7QJ0absV5V04b6Qfck44@iFNbhLoes9SAgRGw1ytmge41rqUGpJ109T/tiCv/@hTlFV8EZroWKEyoOqu@JMIBBwI8BfdfxmNt/OwS8PmJ7@5ufG17@Q91jFKW7Qed/rfSGigrd/9E7PzjsnZ8@8EMUE/tUuERebr7d@1Vr/36ve@Jbaj1W9i57BXz43zP1P@PtaXle23FquVq32Kpr/Cw), quite understandable. My approach is the opposite from @Neil's. He draws all the gifts and then covers those not needed. I only draw the gifts needed.
* 5 bytes saved thanks to Neil!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~1322~~ ~~1319~~ ~~1287~~ ~~1265~~ ~~1061~~ ~~1059~~ ~~1056~~ ~~1032~~ 1030 bytes
```
n=input();k=' '
print'.'+'-'*77+'.'
for l in'
','
','\n',' ','\r':
for L in zip(*[['| ']*7]+[['.'+'-'*q+'. ']+['|'+[(['\ ']+[' | ']*6)[j]+"eJxNUkFuGzEM/Mo0qKFd2Uvdm7pAERRoD0bgpIoTRDGNoJcc2tx6saK3d0a7CEphwSVHpIYjweAwZLyV63SWT7HIpxhjwR7wPw7GGC5G+i8DXjF+zgPoMe4xmdsk3NamfQMOGBWfLk5QvR1fez5cBubPpa5reiP+a3oW7uzryINY+Mhz8QlFcUJx9gc+op9fN3X2kDevXCbchHvf7/mkyAL72NFm/jTN4ytPNauKHWafsHe37XbjeZrq/X2dMojyAJ5PC6y3vrK9OJflOrU2NdXLKvnzPPHH6W8A+RfGSTxxhz5/bf/zZu5hnocEZnw755NKM+qwGqu82hPfcHdEXmvOddcZAZbbbJr/ufezEAJ5nuOWi/oG3ov4d3q9Lli4lg7uZZmv68t7J/6IJ8qJZa6ReshC1/cy9PrfwnE16wMRrL0/BbRs3MxcLr0+5dNWFqhvKtK/eEm8opwUF9WXJH3sQHkP1DVSn1jffdgF8FP/l2W+learx9aM+nufz/W+rL+7EPnkxD+V6DU/dh5Pql/j3driJXcrS2r37ebmoUNUp0XlG66+3/y4/bn7evsBLSvb4rJf1v/+AYT9zU8=".decode('base64').decode('zip').split('Q')[i-1].split('U')[j],k*(q-4)+'%2s '%(`i`*(j>2))][i>n]+' | 'for j in 0,1,2,3]+[['| |'+'_'*e+'| ','|'+'_'*q+'| '][i>n],[' \|',k*3][i>n]+k*q]for i in map(ord,l)for(q,e)in[[11,26,9,24][i>23::2]]]):print k.join(L),'|'
print'|'+'_'*77+'|'
```
[Try it online!](https://tio.run/##PVPpb@JGHFXvblq13XZ7fLRWWo3NODHY2IZUWYlwxhhjDgcHYnV94gtf4AMr/3tqWNpP83u/mfeeRnovOh7sMCBfX4M7J4jSA4r97d0BBFxFiRMcwA2A4BrUWBZW45UVJoiPOAH48u33P34BcPDtD@@@@aM6v3oOfv7zu2r45c1fv1bH18/Jb7//BG6vkBOFryhI6URobbMBLwhQaqwCq/EiHlfa1RJWdwBu0A14Rj5D5PyWwTauAt@bXCFI3iAdlv0JMQnr8XhgkFJm7Nio05/Pw15d20YP4XLeGwohp@vkoWD26pgy6irb7Ud2vngcRQ9Pbm528jV/fGSoxWrJjh6iwnbzOZuLOTscdukhdFo92R3AciuGE7NZ7Iy9RwnqzppNpsP7lcV79CybNyyzpPX7VBMjlU5MR4QqFa7YtEyOD8ITnNhla@YPdIkr2lsdhlHbEiiZ9HpmJnc13R5lFkvsvGOHZ0lhsCPcpdA8HkRBTcejlWrtRybFypprrpOYkEljErrHDkeLXeZIZcm4PeUsf5pIpGDI/DgLSlEcjZhVqwPn1nCxLAq7pAnNIsp1SttBqPfXQc7StDCewDgfxmmLtEVLHxl9eZdNDUNfd9aapnEJkVa/6ldGQTpdOUQ4pMKsaVBxm/edpr9l0/V6lzGtA8sRzAPXirm1yszNvd1tEPqxLSZWHvQbTD6ZJ3yduNfme2pS6HxSh7QhrAaxnY0PY8Ls71phlEuD9krmRtR@NvLERu9xETRcyzK2g9ZAJHxyBX1TTYq2OoFBapXECiY8ZPti4BU9@Mj0JMKwaTH2CZcyEoeT9WRBJhRrartQEqSoLvtDhoEUcWwSWsCa2f6eX2RaM@GsRkbAztOyXUqtu/c3hqmHhokCTd2bTBNg/y@quFZoH/nOAQUzgG2c64byH5bAKZO4V0Pj6yYGwQdyj4AP6CfnUw11P5IYpmycj4ECzwk@NcA9NaCON3ASp87Rf0GqrIN/QM2Ep0bg4ALjM/xMx6sGPL@Ayoa66Hm1WDnJOSe5nRqhYWLgPlat0Bg3MSfYbBqVB4O3cbJ54pDU7S2pKAp2e64z4t24oROgPHYyvFT84nyq@At4fW1Q/wI "Python 2 – Try It Online")
-4 bytes thanks to Mr.Xcoder
-24 bytes thanks to Lynn
---
**Compressed version (thanks to Lynn and ovs):**
# [Python 2](https://docs.python.org/2/), ~~1021~~ ~~1017~~ 1013 bytes
```
exec'eJxNVG1P2zAQ/s6vuFWrHDuOQ1JGWVmRJjRpk6hQYR6gOLhCY1IK6wuwfRgmv33POWHaRdX17nxvj323mjarza+nRB7eTQWJnc1Ds3oSRqQiE2o8TvF358f6ge6pWVWlLsb6QBfgta72dVHocle/02UJcaSLXV1AGOkxxGJfv9flni4OIIDBDLnQxV492SEOeYKQ9KfZJKqqRCBRq3GdVkn1mn2L5NCmMIqod9SJFA/vy2pZp4PBgAx5/Cy9uNP8mXmuHPNcKeVoTuRXniBTMpDgRwmtSX6wCYGTnFNmvMnYblLD5xK6IMnyYrAg9jfX66gXhwL6ZxfSkL/A/j27YbtHXE824Sq8RF6akGM5J+cRn+gtxfxBh44Tc+MDPsN2w3Yfz3u7YMkIxDHXpqsfxP34oc+DZS9E6HhOc+/NdKq9zbJweRkyS7AiAfKDBPxN/KxpPD5jQ9a2Wcv+TAH1Ix/XT4vfglA/cEYPqJO+Uew/tP/XDd1V1w8K6OzTTp+zq6WQDGVgzuFh1zityKbcZxpxJkHGth1x/zcxnhECN26f1RQf8BW4F64/lhf98DROGQfvXd9fxBf3DntFNeCkvi8JPJhExPdQRP+fbKfjDh/iAkOMDwCNNTgMnXXRP7eLKZMAvrlj/J13Oa7I5iw79nc542MuAO8FcFXAR4V/XMwwULOYv+n7G3J/4bptDfD3sT/P78vEdycUnhzXnzvlg61iHTX7p/SP2p4z3K3rVbNPZ2dX0QR0WsX6lo4/n305/zr7eP6GWsvaVvXnmeI/TI953Nw3T4mYC1k1WVG/ylbwfOk7lWyzPZmKYflIYpgsmoVKlkellHXVHK3qNE4jj/OSxxkbQJd6hCnlkcbcCi/UbcrjrUUvbqPYuWtMswsCaUZ9vDu1rSXHazjePW+KZKtvJdZPxfumWyt8uBxNJmVd13ISlxbdmeW6WSUnkjP1i6xPyYsMur+PXj21'.decode('base64').decode('zip')
```
[Try it online!](https://tio.run/##Pc/HsqpIAADQz3FeUTV9CTayRFCSQBMkuCM1GUFSy8/fN6vZnt0Zv0v1Hpjf34IU2anQiRUoNGIO0QEz3NZ7@FHl1XZoXQmD3tUbd2xh5cQuLO1HJcW0ZsB93bFb9hvLIjtUEzePaH4gW8MybN8knyOhBvfKF74T6kNGyzP79tzJqW/M@@Jvd/Z8wbAs4BgGYfeYU@hccbkkPJMH6jvrCvDDPPUs8R5RQIuK3RKi6HgTcDfUnK1p8lV@DA4JOIHxbnYRG45g4JduTJMrXd2JVfKgHeh@YB5nS@pNbXrngqffRbB9mfE1cuhaiuQMpK@wWujSR/2qIisziuDtr2401FffHOXS3fvFi@AuxYo/3K1@M4c47R7ymRhQM4dv/BFLocERhGVU7Q/4IthrH0AEDcPH6aJGtwvDedPFvcOkVcyzTmXuQJULweRacZyfUaaMZovZ2Rgf7MrHZqsRWY3GacYEsdw7o@SXJ9ygWtkZBazcmIQj1ffCbb8eL9YiNuQrIhYwyIjkc@MICRNmG@WLKq0REPnchstOBNktRpNuU89iBwsCkZzTAb1fDGgfvj9SxwRDR1aC8ljvFX3Uy9dIsxcZid6qylLRBBwZGaqbZDEQ066DL9eQu0MOdBUWLrJrKw7eolz4b4VZeVjuViG1W33RkV7dCModF1E4NXAjV6AWW9uUd8my/NIcoshFfPEwXqa4fboG6DRrJ7x2rndeGLIzx5iraF/u2T0SXS4Akbnvz4cdb9TAK6wOuHRcZCyzsw8Qf9lu@Td7DtURDcfWlZCuVT/iR@AhZuQO1mA/QWqhF5NHP477E84R7N4cGNifMzg@fIGgEs5bEmzR0Bca8DXhzFo763N9LNEtHQYK@Hbpju2W78LvgV69EeNOi8dy7t@B0bVF16lRoBrsZN24pgG2R0ibOnoOK2no2izNpBo80@zTfJ7PLZ1QvIaLOe@zlDxfwiav9MeL1ORoChRSxstYNj1/IYLXPvwul/VKLL0PcprVvI6keV@EMPSeQ9sguoYEfePZXD8UihqGPv2bF9k7L/45pclcQO7053846vH05/eXZv8C "Python 2 – Try It Online")
[Answer]
# Befunge, ~~1220~~ ~~1198~~ 1186 bytes
```
<v5,,$$_\#!:,#-\#1<,".N-."+55p00&
v>1-:10p:1-!30p7>1-::0`\5`+3+8g40p::6\`\1-!+6+8g50p" |",:,,:530g
>-1-:20p:1-!30g* 35**60p10g5*+9+8g57*-:70p00g`!\6\`*40g,v
|01g07p09!`3%7+5 :p08+*27-\*4/8-1g07:,g05,g8+2`4:,g8!%5:_:2-v
>-8%7*60g7+:!v!:-1\+1,+*g05< v!\$_1#!-#:\:#,<:g05-*3\+9g06:!<
# +%68*+,:,v$_\: 80gg90g*:!^v_70g:55+/:68*+\!88+*-,55
^^<<<<0<<<<>$50>0$#<>#5g#$,#<40g,48*:,,:v>1
"|_M|"+55_^#!:$_^#!,,"|"+55$_>#!:$#g02$#<^v!:\,<
\| |.- _1860'5;,3#*:2-&9(7.)$/+4% @,,$$_1-\:^
+ _(")_ _n_ $ . ____ __.==,_ |~|
/~\ (_ . _) (") |,| __/ \__ /_%_/|--|XX|- | |
/~*~\ / : \ >( o )< | | `. .'|_|_| | _| | Y
/~*~~*\(_/ \_)( o )._|_|_. /.^.\ |_|_|/ (____' _|_
. . . _ _ i _{/ _{/ _ b \ ==== .-.
.i_i_i.( `v' ) .'%'. \_/ .'.'O .'''. \\\|+-| //`);
|-~~-~| \ / |^~~.~| /O \ /___\ {*=*=*}\\\\\+| %%
|_____| V _'._.'_@__,/\\(_____) '._.' \\\\\\\//
\O/ __/\__ ('v') \ / .==. .;' ... .&%$+*. ~
[ ]|_. \_\/_/ // \\._o_O_..--' | .m_. '* ` */'"'\& ~ MERRY ~
|_____)/_/\_\ |\ /||/\/\/|\_____/ C| | |_/\*_|$\._./% ~ CHRISTMAS! ~
------' \/ Y Y """""""`=====' |__| [_____]'%&*+$' ~~~~~
```
[Try it online!](http://befunge.tryitonline.net/#code=PHY1LCwkJF9cIyE6LCMtXCMxPCwiLk4tLiIrNTVwMDAmCnY+MS06MTBwOjEtITMwcDc+MS06OjBgXDVgKzMrOGc0MHA6OjZcYFwxLSErNis4ZzUwcCIgfCIsOiwsOjUzMGcKPi0xLToyMHA6MS0hMzBnKiAzNSoqNjBwMTBnNSorOSs4ZzU3Ki06NzBwMDBnYCFcNlxgKjQwZyx2CnwwMWcwN3AwOSFgMyU3KzUgOnAwOCsqMjctXCo0LzgtMWcwNzosZzA1LGc4KzJgNDosZzghJTU6XzoyLXYKPi04JTcqNjBnNys6IXYhOi0xXCsxLCsqZzA1PCB2IVwkXzEjIS0jOlw6Iyw8OmcwNS0qM1wrOWcwNjohPAojICslNjgqKyw6LHYkX1w6IDgwZ2c5MGcqOiFedl83MGc6NTUrLzo2OCorXCE4OCsqLSw1NQpeXjw8PDwwPDw8PD4kNTA+MCQjPD4jNWcjJCwjPDQwZyw0OCo6LCw6dj4xCiJ8X018Iis1NV9eIyE6JF9eIyEsLCJ8Iis1NSRfPiMhOiQjZzAyJCM8XnYhOlwsPAogXHwgfC4tIF8xODYwJzU7LDMjKjoyLSY5KDcuKSQvKzQlICAgQCwsJCRfMS1cOl4KICAgKyAgICBfKCIpXyAgIF9uXyAgICAgJCAgICAgIC4gICAgIF9fX18gX18uPT0sXyAgfH58CiAgL35cICAoXyAuIF8pICAoIikgICAgfCx8ICBfXy8gXF9fIC9fJV8vfC0tfFhYfC0gIHwgfAogL34qflwgIC8gOiBcID4oIG8gKTwgIHwgfCAgYC4gICAuJ3xffF98IHwgX3wgIHwgICAgWQovfip+fipcKF8vIFxfKSggIG8gICkuX3xffF8uIC8uXi5cIHxffF98LyAoX19fXycgICBffF8KIC4gLiAuICBfICAgXyAgICBpICAgX3svIF97LyAgICBfICAgICBiICAgXCAgPT09PSAgIC4tLgouaV9pX2kuKCBgdicgKSAuJyUnLiAgIFxfLyAgICAuJy4nTyAuJycnLiBcXFx8Ky18ICAvL2ApOwp8LX5+LX58IFwgICAvIHxefn4ufnwgIC9PIFwgIC9fX19cIHsqPSo9Kn1cXFxcXCt8ICUlCnxfX19fX3wgICBWICAgXycuXy4nX0BfXywvXFwoX19fX18pICcuXy4nIFxcXFxcXFwvLwogIFxPLyAgX18vXF9fICAoJ3YnKSAgXCAgIC8gICAgLj09LiAgIC47JyAgIC4uLiAgLiYlJCsqLiAgICAgICB+ClsgXXxfLiBcX1wvXy8gLy8gICBcXC5fb19PXy4uLS0nICB8ICAubV8uICAnKiAgYCAqLyciJ1wmICAgfiBNRVJSWSB+CnxfX19fXykvXy9cX1wgfFwgICAvfHwvXC9cL3xcX19fX18vIEN8ICB8IHxfL1wqX3wkXC5fLi8lIH4gQ0hSSVNUTUFTISB+Ci0tLS0tLScgIFwvICAgICBZIFkgICIiIiIiIiJgPT09PT0nICB8X198IFtfX19fX10nJSYqKyQnICAgICB+fn5+fg&input=MTQ)
Might still be possible to golf this further by compressing the pictures, but that would likely require the use of extended ASCII characters which aren't currently supported on TIO.
[Answer]
# Python 3 + numpy, ~~1164~~ ~~1159~~ ~~1123~~ ~~1103~~ ~~1097~~ ~~1065~~ ~~1061~~ ~~996~~ 994 bytes
Compress all things and use numpy to bind them together.
First build closed doors, then replace the doors that need to be opened. Finally, output everything.
*-22 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
-5 bytes thanks to [notjagan](https://codegolf.stackexchange.com/users/63641/notjagan).*
EDIT: **<1000 bytes!**
```
import lzma,base64,numpy
def g(i):
a,b,c=[numpy.array([*map(list,i.split('#'))])for i in lzma.decompress(base64.b85decode('T>t=p0RR90|NsC0{{R;Yb2=9ZB3vrGRZhN&js}K8Jmx>v0UA+%!XNuvypanfw-On6yWAqj;f`A@KhRXYG|EfWG~vnf74-|TMD9O<F~(ETm1ht`IL9PRn$&D6@Y`ipqj|2Ks2<w>M0$9alb)6kEp5V>=}iliy4by-zIAEIDqtxiie`c-6+Y_|0z6A#o^?bVc8rNg(dZq)&RMVNZfUWe9`uW87eke^e(U)p=MxBK<aHfTf^JIaEkVa{$4ct<>U}>seZ>tXR2yYjN4W~W;4T16Lv_gAVbahgLo23$DPcrdfNc#QKNxGKmP}?>l;j`Eqj*EArIMnEHDC^u(JA0-eXP$Dx!}mqnSiX}lV507wtt#)-Y{K8q<bZx*3<UiIyS__cP#9?=eN*+sh{-OgeVPlr}`jFjZnFR5NVI(DC8>d%B9EZ=gGyMp)jVbx#uVGLDHNS8Ht`@nS~?ji$ls${$28WROQ@UlY>?I1yXSuWNx7+$YlLSM2tP^f1Vl92;=q~#2jV2qwZB}$El*yJ9lpEpg5&X=pYfDIT;IHs;wMLzIOhXWsm-1n5J{Afro^Zv~Fw$_ylaND7>_!(y1hiO*la?Xms}*M82nm86zo6Lpf%>K)!16qKK7m8<A!0_88GZtXScr*7YoejPFWfmdKNN&;MKgQUoU')).decode().split(':')]
if i>23:a[23:27,45:59]=c[:,168:]
while i:i-=1;h=ord('EAKUIFOCQLGDVYMPBTWHXJNR'[i]);v,u=h//5*7-89,h%5*15+6;a[v:6+v,u-3:u]=b;a[v:4+v,u+1:u+8]=c[:,i*7:i*7+7]
for i in a:print(''.join(i))
```
[Try it online!](https://tio.run/##PVNZd6JoFHzPrzBHEsGtBWVVMCSiIooGFVxOVFSQj7AJuBCjfz1jd8/Mw70PVfdU3YeqIIkt3yv//AA38MM45Xy5en6tRwZRyXsHN0getoaZ2sEAYR5Sdya/Yed/8KIehnoCz7OuHsAOiOI8KEaBA2I4k84gyAdi@mEKpID3R7K4NTa@G4RGFMF/1YtrCv8Nbg04M@JiNigpCl36lqO30uWiVKdrjKVnr@Vj2FJmlvxsR1eJ6rhn7lga87mnx4l8OCaB7pmnQt8jEo3f21Vzxb9IljKZtr4FU2vdjp5JVgrfo16D7teaN1gYuagVr8QuPVA86LlBvExXINjb35gUYbUT1ytBtO6sEeJTCHCVY6/AAUllnRS@RF4QG/v4DICx2hSI3HT5Xfoi@LS/qK/VDRXKO3g72yPPSk@VZ@ZYM@jVQaNI49NYGPAYCdje@VWq6W1zZC46oi58qvoFqmziGje@cpEx4@KJgiVTW65oN61aGaFE97jc8epat3ZdHytDjcEm3JryJv0uyeeW5A6udc6p2ithb2cFPhR7ntBuvC0OcIcvFYzJAGqcH6/u3huCydVR8RJ5iuM0UpheJGpfW8/O2XJtDMRkuFxuBmm6zhpyNhdZl0J/Z6gDJ7yu7KY985oKLqsi3HijuO3TKy3M2F0r6QWIra7P6YPa6jba8pBqx6sXb3ir2wByIugCYZSm9N9fxs6Uq4toMhkeNPlM5qCp0x32sHiwMFHVobEqu7@lMVvF9qfZ6xUSnGzSoZ1ACHb484QNpmZDHFXFdlQ99bpfYt@aaJFbQD28c@HN0F/MjrfmCVomji43SG75CCeoBfpZR69P3Oia7VGY51LEl090A/OJk5BHlNhLEulSNf6xtKSo1iyeDDdhlpz6hj1oaqa7lWT5udqTdu9jf3yPcPHfeCL/5ZrJIB8PKWCmAIeVGX1@XxiZr@AMTn@wmzmTRwmKuV@cLOAYKcCAAotWLdYPt3BG4KWx2Oy/vXdbDXXaG7yOtPakIyuZOfhAqsf8gbV@/cKzZIGi89YTnkXxHFHV50eGyN3JQpk5fLDrP0DlN5BDmUOO@usKsiRznxx5t/6/dDoThMC7P50p2j7w7v1FfnYwijzsYKyCPPz8Aw "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~1296~~ ~~1291~~ ~~1211~~ ~~1166~~ 1164 bytes
That super-long string, though (59% of the whole thing!). There's gold in them hills; I can feel it.
Edit: If there is gold, I've only found specks so far.
Edit: -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
#define D"BQHLAFKTEVCJOWGPIX@RDMSUN"[p=r*5+c]-64
#define O D<=n
#define P printf(
#define G(x)for(x&&P" |\n|"),c=0;w=D^24?7:22,c<5;c+=1+(D==24))
#define m(c,n)memset(calloc(n+1,1),c,n)
char*x[]={"_|","\\","33 ","6 ","__",".'"," "," ."},*v,*u;U(char*q){for(;*q;q++)*q>47&*q<56?U(x[*q-48]):(*u++=*q);}t[4],r,c,s,w,p;f(n){P".%s.\n",m(45,77));for(v=u=m(r=0,732),U(".W.7W.|*| |*||*| |*|'M' 'M'_'_3 ) (^.^_1./v`v' oO833+36/~13/~*~1 /~*~~*16.^o3(';') {1|+|/}6d-b3_(\")_ (_7 _) / : 1 (_/ 1_)6_n_3 (\")6>( o )<(6o6)3$36|,|3 | |6.00_.3.34/ 14`.35 /.^.16.1^/. <->o<-> '/v1`23446/_%_/||00 ||00/ 4.==,_--|XX|- 06| (44'3.*.3 /.13|_-0 (.-o-.) _3_ (O X O) / ^ 161/ 1/6.777i_i_i.|-~~-~||4404444j_j_j_ ||_0 0/$$|_ _3_ ( `v' ) 13/3 V33i3 5%'. |^~~.~|_'._5_ 4/142~2 1_1/_/3~ MERRY ~3 /_/1_1 ~ CHRISTMAS! ~31/2~~~~~2|=|3 / 13|(%)|6|4037;'3.m_.6C|6|3|_06,3* +6. +3. '7~~~~~~~3.-.3//`); %%3 //2 b3 5''. {*=*=*} '._536_3 55O /4_1 (44_)");r<5;r++){P"|");G(s=0)P" .%s.",m(45,w+4));for(;s<4;s++)G(1)sprintf(t,"%d ",D),P" |%2s %*.*s |",O?s?"|":"\\ ":"",w,w,O?v+p*28+p/18*32+w*s:s^3?"":t);G(1)P" |%s%s|",O?" |":"__",m(95,w+2));G(1)P" %-*s",w+5,O?"\\|":"");P" |\n");}P"|%s|",m(95,77));}
```
[Try it online!](https://tio.run/##XVRtU@M2EP5cfsXWxVjyi2RZsk3jGHold9xdS0PhOOgQIjgDbTqXV4eEmSj@63QVKJ2eNFpb691Hjzb7pIr@rKqnpx9u7@4HozvoOD///v7XN@9@@fT288HH7vnh8YeLn046R6dnvzmXk3Lmp0F1FWVq69@ELnTa5eh1ewyT2WA0vyevnkPySO/HM/K4s3PsAJjeyDg0rMq4WJadfqL281aShFU7LaqgFAHplGWiKH3NH5IqHNHh3bC@m5Pq5uvXcUVGgQgFguCHreqvm5n/eHlVrhxtnNDp9dBICWgza7RGwzw0YLfAnHXoL0L/oTgjm9wpXVl@hT8tpkFA/emeynf8aTvN9s/I46U/jdTuFW0R/yEISowu1vNLdRXO8Pg6XIaT4p6M6OrYYW7NeiMnHBKVhnlOaWFhF@VDOSSzMg5zmdDwjDjsnOXnzPgGcL08vCMPcGlPS6BA@qyvBeOL64UH4@6ulIHMeCMkb/xGgLWNLzLWH0viFR6FlTCB4evsNvoiNek5VAPROWgKHFogcMNBaJrpEeLb79kegTHQNsnGGZXbMjOhkYBUMhbHmkkmFWaoayZT4KzP8DDR5wza0d4YF3h8Ia4TqVTGtau5MXEM1nBQrCxDHUXm4sJEEGcGiFKeZD6TiCSk0VEMhEXjiFHQEol24QK6lmkfRCbwWJ6xPM8HGiczUdNEjTFKxQrH39pOPErHEPPtbaOfMcBWigJWSMJnKQcSUtdjYPpNwxqjPaZTDYoLlTQJVkJwzWUDR29PTv6ABolpjk5o4OD9yYfTT0dvTr9Ht@BJY0diSiwOEpOGuNRkRsUyL/BOQ82yA9zjpeIslD4EGYNAMvDy5nlIFjHJ@TUtwHURgyfwBbl5yG3llzjXYLnJDH@XNO0CV0gDC6apQ4sZamKGHYm9hZIpDkldxtRqyHbaS58tA/XSaEXdVkWN4YdE0PpFhfPQcW@x7Ts03IjPTWpwfebXgFLp7tf7iNxCyQBaB5t5ic5FMPGT3WDCxa4vk2Dp1626L/cdpzW3JAR9RqrdeoPhgIWwKhuSHy2hhP4XBm7k1wgcpDay17OheJWXPwJ8W@PdNkCb5I1q1k9IHYY3gxGhW6ut7@5JjOWbPMxrYnOtI/3WIdS3nuT/nvXTPw "C (gcc) – Try It Online")
## Non-ASCII version
-30 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
GCC on my machine produces something that crashes immediately, making it unlikely that I will pursue this fork. (Not to mention that TiO reckons 1120 bytes for some reason (same as its reported amount of characters).).
```
#define D"BQHLAFKTEVCJOWGPIX@RDMSUN"[p=r*5+c]-64
#define P printf(
#define G(x)for(x&&P" |\n|"),c=0;w=D^24?7:22,c<5;c-=~(D==24))
#define m(c,n)memset(calloc(n+1,1),c,n)
char*v,*u;U(char*q){for(;*q;q++)*q<48|*q>55?*u++=*q:U(L"籟\\\x203333‶彟✮†⸠"+*q-48);}t[4],r,c,s,w,p;f(n){P".%s.\n",m(45,77));for(v=u=m(r=0,732),U(".W.7W.|*| |*||*| |*|'M' 'M'_'_3 ) (^.^_1./v`v' oO833+36/~13/~*~1 /~*~~*16.^o3(';') {1|+|/}6d-b3_(\")_ (_7 _) / : 1 (_/ 1_)6_n_3 (\")6>( o )<(6o6)3$36|,|3 | |6.00_.3.34/ 14`.35 /.^.16.1^/. <->o<-> '/v1`23446/_%_/||00 ||00/ 4.==,_--|XX|- 06| (44'3.*.3 /.13|_-0 (.-o-.) _3_ (O X O) / ^ 161/ 1/6.777i_i_i.|-~~-~||4404444j_j_j_ ||_0 0/$$|_ _3_ ( `v' ) 13/3 V33i3 5%'. |^~~.~|_'._5_ 4/142~2 1_1/_/3~ MERRY ~3 /_/1_1 ~ CHRISTMAS! ~31/2~~~~~2|=|3 / 13|(%)|6|4037;'3.m_.6C|6|3|_06,3* +6. +3. '7~~~~~~~3.-.3//`); %%3 //2 b3 5''. {*=*=*} '._536_3 55O /4_1 (44_)");r<5;r++){P"|");G(s=0)P" .%s.",m(45,w+4));for(;s<4;s++)G(1)sprintf(t,"%d ",D),P" |%2s %*.*s |",D>n?"":L"|⁜"+!s,w,w,D>n?s^3?"":t:v+p*28+p/18*32+w*s);G(1)P" |%s%s|",D>n?"__":" |",m(95,w+2));G(1)P" %-*s",w+5,D>n?"":"\\|");P" |\n");}P"|%s|",m(95,77));}
```
[Ideone link](https://ideone.com/uNnLdU)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~2798~~ ~~1976~~ ~~1963~~ ... ~~1862~~ ~~1742~~ ~~1703~~ ~~1651~~ ~~1634~~ 1632 bytes
-2 Bytes thanks to ceilingcat
I've replaced a few icons to avoid unnecessary ESC '\' characters.
```
(*L)()=printf;
#define E else L
#define W" |"
#define V W" | %.7s "
#define S(x)else if(i<x)L
#define D(x)for(i=0,++j;i++<x;)
#define R L("%s.%1$s.%1$s",I);L(q^7?".%s.%1$s":"%2$s----.%1$s",I,I+3);L(". |\n|");D(30)d(n)
char*P="_______ + _(\")_ _n_ $ . ____ __.==,_ .*. _ _ . . . _ _ |~| //'`\\ |=| , * j .&%$+* | _ | ('v') .==..W. .W. ... .-. _j_j_j_ /~\\ (_ . _) (\") |,| __/ \\__ /_%_/|--|XX|- /.\\ (O X O).i_i_i.( `v' ) | | //....\\ / \\ + . + .'''. */'\"'\\&| ($) |// \\\\.--' ||*| |*| '* ` //`); ||__| /~*~\\ / : \\ >( o )< | | `. .'|_|_| | _| | |_-_| / ^ \\ |-~~-~| \\ / Y ||()()| |(%)| . ' .{*=*=*}$\\._./%| \" o||\\ /|\\_____/|*| |*||_/\\*_| %% _|/$$|_/~*~~*\\(_/ \\_)( o )._|_|_. /.^.\\ |_|_|/ (____' (.-o-.) \\/ \\/ |_____| V _|_ ||_[]_| |___| ~~~~~~~ '._.' '%&*+$'| === | Y Y `=====''M' 'M'[_____]// CRIMBGLUFWDKPXHQJYASENTVO",*I=" .-----------",*T="_________";q,i,j,k,l,g;d(o){l=(i-1)%5+j*5;k=7*l+168+168*(i>10)-(g=7*(l>17));if(q=P[672+l]-65)if(q>o)if(q^24)if(i<16)L(W"%9c"W,32);S(21)(W"%10d |",q);S(26)(W"_%s_|",T);E("%15c",32);S(16)(W"%26c|",32);S(21)(W"%25d |",q);S(26)(W"%s%1$s%s|",T,T+1);E("%30c",32);else if(q^24)if(i<6)L(W"\\%9.7s |",P+7*l-g);S(16)(V"|",P+k);S(21)(V"|",P+7*l+504-g);S(26)(W" |%s|",T);E(" \\|%10c",32);S(6)(W"\\%9.7s %7c%9c",P+7*l,'~','|');S(11)(V"%s"W,P+k," ~ MERRY ~ ");S(16)(V"%s |",P+k,"~ CHRISTMAS! ~");S(21)(V"%9.7s "W,P+7*l+504,P+608);S(26)(W" |%s%1$s%s|",T,T+3);E(" \\|%25c",32);i%5||L(W"\n|");}f(n){L(".");D(77)L("-");L(".\n|",j=-1);R;R;R;R;R;D(77)L("_");L("|");}
```
[Try it online!](https://tio.run/##XVRrVxs3EP1c/4qpYiFpH1qvie0kyzonDbRxaxdqKI/DgpxjY7LGtQMmHM5B7F@nM1o/SkdIRqOZe69GWg3D6@Hw5U0@G05/jK5gZ3E/yuf6W/tFel0lVfr9Lp/dj5PKm9HVOJ9dwR5cTRdX0F07ThiAZevpMTkscN1awMZ7KB@Vy8vHMt95VJv0XVwZz@9kntYC358kue/vPCZqvd6HrmR8oXlcLQcWdFTSlbeXrY9MLxfYB8br1UWItooJOv42xTGN8rKZZSrZlds1NZIzVRl@@3rnHaTMlAYAPnYwMmOKZmZGI0DVjaDd6CKN0Wka4Kr2yGvKrl1bzcAWFscoEoMso2lK0wC7RzgTQtziVd/DOlG8BSkehHJMaar1CYJhB61LYh1qMBPXELUgTGmQz2AKKaYYGxCWiSDLUGVkuIlsGNrTUxtijnY5@3AK@0rnBpuWMHgQoIjdklYkc1GE4Mqh3SCE0OBFImMiy7ZQaVWBjSJkzNB0GApEsB6CYBe4v4Hb@UAl6DaGoAuvKIE/EHRbwhzUzpJ3QDvUwhpsOKd4@jOhy4RLyrBhUYRYUVdLYoYz2rCVeD0xSXJl3RkJ0E9eiu25isqMjjj6MwZza8tUS7VBi5Z6rYmyzEMmzt352qhaRR/qLbwsk2UxlQQUDEqTRKOxlpdUJ6c4wnNAEyB1OA@1wvjIdet4SNZxeXUsHbM15xe0TbdUlAYClQoQfMvzq8JCmqZUgTPa4yAlE6KH6z1x7jAvXO0BPvc7vV9@6/7968nuHwenX/76/ezT4d6fR8f7LPA6KaNLszH0Ha0vuzEsuQ3yYBLcBNPgOhnJuXqapjIPY8Ub/sRrJDdpy5v6cfMddU/m7bimQnmNXjltxy2lEvyMb9OD82ar7k8vwmZDkaM9dz@X9bfKfeZxU3XlCePvh@wk2K6r5FDWY0WeuDbCNyO4da4muQxfGPQcqWQPP/e4MWTLjNgt83pzaNlrkHrj/yB8QR8/XxBQcOTHJdh2bQm2eoA2CkuBWcbf03OFaQc@7jy8XhEfM@e7WbEu51SdRu1tGVdSgy1pHaX7Oizucr0LF7Pi4a0h1aQECkQhAmGFo3QUfIHlQtIAcQro7fX7Z/gLbCOKL7ViSAGfv/Q7h0e9T4c/Q8E2QksqNAe2VIz/NWvvXqt@VbLt/@qvr04h5w1rXaXcO/o8xjf0iZ5W96i2WlhFFrLytaWQYJLiZUr667YKMmWQA3n552s@k8PgQbnX2HtIKk@Vn8YSzyb5/uN@IRlGVWBpY4nuyvPLvw "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 966 bytes
```
->n{a=%w{8. 99|/ 99|1 8' .;.. |//| |// |=_ 9.W. 9|*| 9|*| 9'M' _99| $)9| "9o| ==9| ~| 9| Y9 |__ .9. i_i. ~8~| ___| $ ,| 9| _|_. ^/. o<8> v1` 9 _9. O/{ *1{ **1 n_ ") o9)< o99) v') 9911 99/| 9Y *. .1 8_| o8.) _.8 +. W9) "` 993 _O_. /1/| """" + ~1 *~1 ~451 . 91__ 99.' ^.1 =| 91 %)| __| ")_ .9_) :91 91_) 99_ X9O) ^91 91/ 99_ v'9) 99/ V ^o ;') +|/} 8b b ''. *=*} _.' i9 %'. ~2~| _.'_}
b=(0..34).map{?|+" "*77+?|}
96.times{|i|z="EAKUIFOCQLGDVYMPBTWHXJNR"[j=i/4].ord-65;y=z/5*7
t=j<n
b[l=1+y+k=i%4][x=z%5*15+3]=b[l][x+12+m=i/92*15]=?|
b[y+(k+4)%7][x,13+m]=["|%*d |"%[9+m,j+1],(t ?"| |":?|).ljust(12+m,?_)+?|,(t ?" \\|":"").ljust(13+m),?.+?-*(11+m)+?.][k]
w=i>91?["~%14s"%".-. ","~ MERRY ~ //`);","~ CHRISTMAS! ~ %% ","~~~~~ %-6s "%"// "][k].rjust(24):(a[i][1,3].reverse.tr("1/;o)8~`></1{)O3451')/bo}~2"[j,5],"/1, (~8'<>1/}(o1*~/`(1d.{^~"[j,5])+a[i]).center(9)
t&&b[l][x+1,11+m]="\\ | | |"[k*2,2]+w.tr('1345298','\\\\/~*. -')}
puts ?.+?-*77+?.,b,?|+?_*77+?|}
```
[Try it online!](https://tio.run/##PVJrU9s6EP2eX7HV1LVlOavKScAiUTy0t/f2RdPSB2UcR5CSzhga3EkCXIjiv05Xoe16tGOdPTo62tnF1fT2/ru5bw8v16cmuFlnCFo76ZOCLATsI4KT0vkEzljQeEQcF7vfKTwIwRIdHnNKTNcOjKG/xhPgWIOzFlAjVLZCaDLCrbVEh2TLsM4iTCRCPciGcK1OQJMewkiuIVa0YgWXFhiHWvMBJc3hOuTkUClK5EwfQ4yA5Jdk6ww5WMxAIBwRlZGe7oAd0S1SEZtRgIBGQUyr6fYU0HsUmdQaQ5iQjiFNBQH3TukA9/4thz0CieivtvBVjzhMtojcAteh9hUJX2BSQ58cCic3kE1hCmGIEJt4Q8ZCqDQEtG9S3wkM7aY1NdFTxE6X4/z05zp3ggGLd3dF7jYtvYOraj5brl3l7gx7sf/m86t/R88/vP3vny/HB@@ffTp6@fX1u0NWnJtKdkusF2ftnV7/1tzJXrzbWpnzwWVrWvwwStyKC1MF3bL439wFvVj1RKc0VCJAqFTMSUCnBJcmd3TkVkQXosuDXaonqiPmpSmYC@IzAMeCQot5ci5UmUQryBnNB9vLHccf51fLVeTlktxyesJDHcZjIjD2l0B6PMlR5O04Uoo2IseyuChbN6YaapUXrAlUd8kChm0ElrAGDl4cHh5DAz6kPOH9Lfr85eGrj58O9j8@olIQ@KLHfWyZQXtnCSRD4wvM34CLrYO0y/ei06IqC5V0CJxdzxbLGa4WEVOyX/OsORkOpFrzUYdmJORyWm@alPqc9MqESZVA1GThYKjkJqpV3MiTSJ3hetI8ULjw2hy/zS5Xs0WkeWv15MmfZif@xaVh4zH10n@suIjTJC3FjTcQKroy1VmYhGMK2dB4t0O@af28Wi3hoWl@PDCZJjQtuf09LPffi7Rb3v8C "Ruby – Try It Online")
More golfed, but harder to see the pictures in the code.
# [Ruby](https://www.ruby-lang.org/), 974 bytes
This is a function, to be assigned to a variable such as `f` and called as `f[n]`. It prints to stdout.
Turned out longer than expected. I think there are a few more bytes to squeeze out by laying out the picture data differently, which I will try later.
I use symmetrical or near symmetrical pictures, and only the righthand half is found in the code. The left half may have up to 5 character subsitutions compared to the right. The code for making the substitutions is quite long, which partially negates the compression. Only about 60 bytes are saved.
```
->n{a=%q[8.
|/
|1
8'
.;..
|//|
|//
|=_
.W.
|*|
|*|
'M'
_ |
$) |
" o|
== |
~|
|
Y
|__
. .
i_i.
~8~|
___|
$
,|
|
_|_.
^/.
o<8>
v1`
_ .
O/{
*1{
**1
n_
")
o )<
o )
v')
11
/|
Y
*.
.1
8_|
o8.)
_.8
+.
W )
"`
3
_O_.
/1/|
""""
+
~1
*~1
~451
.
1__
.'
^.1
=|
1
%)|
__|
")_
. _)
: 1
1_)
_
X O)
^ 1
1/
_
v' )
/
V
^o
;')
+|/}
8b
b
''.
*=*}
_.'
i
%'.
~2~|
_.'_].split($/)
b=(0..34).map{?|+" "*77+?|}
96.times{|i|z="EAKUIFOCQLGDVYMPBTWHXJNR"[j=i/4].ord-65;y=z/5*7
t=j<n
b[l=1+y+k=i%4][x=z%5*15+3]=b[l][x+12+m=i/92*15]=?|
b[y+(k+4)%7][x,13+m]=["|%*d |"%[9+m,j+1],(t ?"| |":?|).ljust(12+m,?_)+?|,(t ?" \\|":"").ljust(13+m),?.+?-*(11+m)+?.][k]
w=i>91?["~%14s"%".-. ","~ MERRY ~ //`);","~ CHRISTMAS! ~ %% ","~~~~~ %-6s "%"// "][k].rjust(24):(a[i][1,3].reverse.tr("1/;o)8~`></1{)O3451')/bo}~2"[j,5],"/1, (~8'<>1/}(o1*~/`(1d.{^~"[j,5])+a[i]).tr('134528','\\\\/~*.-').center(9)
t&&b[l][x+1,11+m]="\\ | | |"[k*2,2]+w}
puts ?.+?-*77+?.,b,?|+?_*77+?|}
```
[Try it online!](https://tio.run/##PVL9U9s4EP19/wqdpq4ty1md8gEOieLh@n13NC3tlTKOI0hJZwwE08TQgyj@1@kqtJVHO9bbp6en1S5vZncPX81Da3S1PjXBtzxFYMwpHzSkIeAAEZxSzgdwxgLDI@K42P0M4UEIlujwRFDgrHJgDP01ngDHDJy1gAyhtCVCkxJurSU6JFuGdRZhqhCqYTqCW30CjPQQxmoNsaYZa7iywAVUTAwpMAG3oSCHWlMgZ@wYYgQkvyRbpSjAYgoS4YionPRYB@yYTlGa2JwGSGg0xDSbbk8D3UeTScYwhCnpGNLUEAjvlDYI798K2COQiP5oC5/ZWMB0i6gtcBsyn1HwCaYVDMihdGoD6QxmEIYIsYk3ZCyEkkFA66btK4GhLXB1fVnW0RMlYGaiPxE7XYGL0@t15iRnPN7dlZnbQH8H63IxX61d6e4Nf7H/z39vXo6fvf/31fNPxwfv/vp49Prz328PeX5uStUtsFqetXZ6gztzr3rxLtTmfHgFs/zSaHknL0wZdIv8f3Mf9GLdk53CUIoAqdtyQQL9NsGFyRxtuZPRheyKYJfyie7IRWFy7oL4jJ6dB3lfLpJzqYskqlnGHWF7mRN4eX6zqiMvl2RW0BUe82wyIQLnvwmkJ5IMZdaKI61pITMs8osCvpty1NdZzptAd1c84NhCxhPesIMXh4fHrGF@KHUiBlv02evDNx8@Hux/@INSQeCTHvdjywxaOytGMkpRwp@Ay62DdlfsRad5WeQ66RA4v50vV3OslxHXalCJtDkZDZVei3GHuiUUalZtmjbVOekVCVc6YVGThsORVpuo0nGjTiJ9hutp80gR0msLrxdqUminYRJOaKgmxlYo8Mv8qp4vo76A@unTX6@Q@FIUhk8mVGT/8fwibiftQn7fwPVNvWKPJfPNgcksoV7J7M9Wefiad4uHHw "Ruby – Try It Online")
[Answer]
# [Clojure](https://clojure.org "Clojure"), 1530
[Try it out](https://repl.it/@BrianGregg/AlarmedIroncladAustralianfurseal "Try it out")
The clojure solution probably could be a little shorter, but here's my first attempt.
```
(defn a[x](let[k clojure.string/join b" . _ . }\\O/{ }/*\\{ /***\\ _'_ ) (^.^ \\./v`v oO8 + /~\\ /~*~\\ /~*~~*\\ .^o (';') {\\|+|/} d-b _(\")_ (_ . _) / : \\ (_/ \\_) _n_ (\") >( o )<( o ) $ |,| | | ._|_|_. . __/ \\__`. .' /.^.\\ .\\^/. <->o<-> '/v\\` ____ /_%_/||_|_| ||_|_|/ __.==,_--|XX|- _| | (____' .*. /.\\ |_-_| (.-o-.) _ _ (O X O) / ^ \\ \\/ \\/ . . . .i_i_i.|-~~-~||_____|________j_j_j_ ||__| _|/$$|_ _ _ ( `v' ) \\ / V i .'%'. |^~~.~|_'._.'_ |~| | | Y _|_ //'`\\ //....\\||()()|||_[]_| |=| / \\ |(%)| |___| _{/ _{/ \\_/ /O \\ @__,/\\\\ , * + . + . ' .~~~~~~~\\ ====\\\\\\|+-|\\\\\\\\\\+|\\\\\\\\\\\\\\ b .'''. {*=*=*} '._.' " z(fn[n]#(.substring %1(* n %2)(+ (* n %2)n)))i(z 28)j(z 7)s str r #(apply s(repeat %1 %2))m[" ~ "" ~ MERRY ~ "" ~ CHRISTMAS! ~"" ~~~~~ "] c #(let[w(if(= 24 %)26 11)](concat[(s"."(r w"-")".")](for[i[0 1 2]](s"|"(r w" ")"|"))[(s"|"(r(- w 4)" ")(if(< % 10)" ")%" |")(s"|"(r w"_")"|")(r(+ w 2)" ")]))o #(let[w(if %2 26 11)](concat[(s"."(r w"-")".")(s"|\\ "(j %1 0)(if %2(m 0))" |")](for[i[1 2 3]](s"| | "(j %1 i)(if %2(m i))" |"))[(s"| |"(r(- w 2)"_")"|")(s" \\|"(r(- w 1)" "))]))d #(if(< x %)(c %)(o(i b(- % 1))(= % 24)))](println(s"."(r 77"-")".\n| "(->>(for[p[[2,17,8,12,1][6,11,20,5,22][3,10,15,23,7][16,9,24,18][4,13,19,21,14]]](map #(d %1)p))(mapcat #(apply map vector %))(map #(k" " %))(k" |\n| "))" |\n|"(r 77" ")"|\n""."(r 77"-")"."))))
```
] |
[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.
**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.
The challenge: Define `x` in such a way that the expression `(x == x+2)` would evaluate to true.
I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.
I intend to accept a C solution, but other languages can get my vote.
1. Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming `int` is 32bit 2's complement) is OK.
2. Simple - should be small, use basic language features.
3. Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. **Update**: Avoiding the preprocessor is interesting.
4. Quick - The first good answer will be accepted.
After getting 60 answers (I never expected such prticipation), It may be good to summarize them.
The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:
1. The C preprocessor. `#define x 2|0` was suggested, but there are many other possibilities.
2. Floating point. Large numbers, infinity or NaN all work.
3. Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.
The rest don't work with C:
4. Operator overloading - A `+` that doesn't add or a `==` that always returns true.
5. Making `x` a function call (some languages allow it without the `x()` syntax). Then it can return something else each time.
6. A one-bit data type. Then `x == x+2 (mod 2)`.
7. Changing `2` - some language let you assign `0` to it.
[Answer]
Fortran IV:
```
2=0
```
After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)
[Answer]
This seems to work:
```
#define x 2|0
```
Basically, the expression is expanded to `(2|0 == 2|(0+2))`. It is a good example of why one should use parentheses when defining macros.
[Answer]
## Brainfuck
```
x
```
This does of course stretch "evaluate to true" a bit, because in Brainfuck nothing actually *evaluates* to anything – you only manipulate a tape. But if you now append your expression
```
x
(x == x+2)
```
the program is equivalent to
```
+
```
(because everything but `<>+-[],.` is a comment). Which does nothing but increment the value where we are now. The tape is initialised with all zeros, so we end up with a 1 on the cursor position, which means "true": if we now started a conditional section with `[]`, it would enter/loop.
[Answer]
```
main()
{
double x=1.0/0.0;
printf("%d",x==x+2);
}
```
Outputs 1.
Link: <http://ideone.com/dL6A5>
[Answer]
# F#
```
let (==) _ _ = true
let x = 0
x == (x + 2) //true
```
[Answer]
## C
```
int main() { float x = 1e10; printf("%d\n", x == x + 2); }
```
Note: may not work if `FLT_EVAL_METHOD != 0` (see comments below).
[Answer]
**C#**
```
class T {
static int _x;
static int X { get { return _x -= 2; } }
static void Main() { Console.WriteLine(X == X + 2); }
}
```
Not a shortie, but somewhat elegant.
<http://ideone.com/x56Ul>
[Answer]
**Scala:** `{ val x = Set(2); (x == x + 2) }`
---
**Haskell:** Define ℤ/2ℤ on `Bool`eans:
```
instance Num Bool where
(+) = (/=)
(-) = (+)
(*) = (&&)
negate = id
abs = id
signum = id
fromInteger = odd
```
then for any `x :: Bool` we'll have `x == x + 2`.
*Update:* Thanks for the ideas in comment, I updated the instance accordingly.
[Answer]
## Python
```
class X(int):__add__=lambda*y:0
x=X()
# Then (x == x+2) == True
```
[Answer]
**GNU C** supports structures with no members and size 0:
```
struct {} *x = 0;
```
[Answer]
PHP:
```
$x = true;
var_dump($x == $x+2);
```
Or:
```
var_dump(!($x==$x+2));
```
Output:
>
> bool(true)
>
>
>
[Answer]
It's a common misconception that in C, whitespace doesn't matter. I can't imagine somebody hasn't come up with this in GNU C:
```
#include <stdio.h>
#define CAT_IMPL(c, d) (c ## d)
#define CAT(c, d) CAT_IMPL(c, d)
#define x CAT(a, __LINE__)
int main()
{
int a9 = 2, a10 = 0;
printf("%d\n", x ==
x + 2);
return 0;
}
```
Prints `1`.
[Answer]
**C**
It's more interesting without using macros and without abusing infinity.
```
/////////////////////////////////////
// At the beginning /
// We assume truth! /
int truth = 1;
int x = 42;
/////////////////////////////////////
// Can the truth really be changed??/
truth = (x == x + 2);
/////////////////////////////////////
// The truth cannot be changed! /
printf("%d",truth);
```
Try it if you don't believe it!
[Answer]
## Mathematica:
```
x /: x + 2 := x
x == x + 2
```
I think this solution is novel because it uses *Mathematica's* concept of Up Values.
EDIT:
I am expanding my answer to explain what Up Values mean in *Mathematica*.
The first line essentially redefines addition for the symbol `x`. I could directly store such a definition in the global function that is associated with the `+` symbol, but such a redefinition would be hazardous because the redefinition may propagate unpredictably through *Mathematica's* built-in algorithms.
Instead, using the tag `x/:`, I associated the definition with the symbol `x`. Now whenever *Mathematica* sees the symbol `x`, it checks to see whether it is being operated on by the addition operator `+` in a pattern of the form `x + 2 + ___` where the symbol `___` means a possible null sequence of other symbols.
This redefinition is very specific and utilizes *Mathematica's* extensive pattern matching capabilities. For example, the expression `x+y+2` returns `x+y`, but the expression `x+3` returns `x+3`; because in the former case, the pattern could be matched, but in the latter case, the pattern could not be matched without additional simplification.
[Answer]
Javascript:
```
var x = 99999999999999999;
alert(x == x+2);
```
[Test Fiddle](http://jsfiddle.net/briguy37/MYWjk/)
[Answer]
## **scheme**
```
(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t
```
[Answer]
Obvious answer:
# When this terminates:
```
while (x != x+2) { }
printf("Now");
```
[Answer]
Here is a solution for JavaScript that does not exploit the `Infinity` and `-Infinity` edge cases of floating-point addition. This works neither in Internet Explorer 8 and below nor in the opt-in ES5 strict mode. I would not call the `with` statement and getters particularly "advanced" features.
```
with ({ $: 0, get x() {return 2 * this.$--;} }) {
console.log(x == x+2);
}
```
**Edited to add:** The above trick is also possible without using `with` and `get`, as noted by [Andy E](https://codegolf.stackexchange.com/users/1793/andy-e) in [Tips for golfing in JavaScript](https://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript#4691) and also by [jncraton](https://codegolf.stackexchange.com/users/5385/jncraton) on this page:
```
var x = { $: 0, valueOf: function(){return 2 * x.$++;} };
console.log(x == x+2);
```
[Answer]
The following is not standards compliant **C**, but should work on just about any 64-bit platform:
```
int (*x)[0x2000000000000000];
```
[Answer]
Sage:
```
x=Mod(0,2)
x==x+2
```
returns True
In general for GF(2\*\*n) it's always true that x=x+2 for any x
This is not a bug or an issue with overflow or infinity, it's actually correct
[Answer]
## Common Lisp
```
* (defmacro x (&rest r) t)
X
* (x == x+2)
T
```
It's pretty easy when `x` doesn't have to be an actual value.
[Answer]
## APL (Dyalog)
```
X←1e15
X=X+2
```
APL does not even have infinity, it's just that the floats aren't precise enough to tell the difference between `1.000.000.000.000.000` and `1.000.000.000.000.002`. This is, as far as I know, the only way to do this in APL.
[Answer]
# Perl 6
I'm surprised to not see this solution before. Anyway, the solution is - what if `x` is `0` and `2` at once? `my \x` in this example declares sigilless variable - this question asks about `x`, not Perl-style `$x`. The `?? !!` is ternary operator.
```
$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES
```
But...
```
$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO
```
`x` is multiple values at once. `x` is equal to `0` and `2` at once. `x + 2` is equal to `2` and `4` at once. So, logically they're equal.
[Answer]
# Python 2.X (Using redefinition of (cached) integers)
I've noticed all of the python answers have defined classes that redefine the `+` operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)
In python, integers are stored more or less this way in C:
```
typedef struct { // NOTE: Macros have been expanded
Py_ssize_t ob_refcnt;
PyTypeObject *ob_type;
long ob_ival;
} PyIntObject;
```
That is, a struct with a `size_t`, `void *`, and `long` object, in that order.
Once we use, and therefore cache an integer, we can use python's `ctypes` module to redefine that integer, so that not only does `x == x+2`, but `2 == 0`
```
import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value
# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)
# Now we access the ob_ival by creating a C-int from the address of
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)
#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0
# Now for the output
x = 1
print x == x+2
print 2 == 0
```
Prints
```
True
True
```
[Answer]
## Perl
using a subroutine with side-effects on a package variable:
```
sub x () { $v -= 2 }
print "true!\n" if x == x + 2;
```
Output: `true!`
[Answer]
***Python***
exploiting floating point precision makes this very simple.
```
>>> x = 100000000000000000.0
>>> (x == x+2)
True
```
To make it less system specific requires an extra import
```
>>> import sys
>>> x = float(sys.maxint + 1)
>>> (x == x+2)
True
```
This should work in other languages too.
This works because the reprensentation of 100000000000000000.0 and 100000000000000002.0 are exactly the same for the machine, because of the way floating points are represented inside the machine.
see <http://en.wikipedia.org/wiki/IEEE_floating_point> for more information.
So this will basically work in any language that allows you to add integers to floats and have the result of this be a float.
[Answer]
Here is a solution for C++ based on operator overloading. It relies on implicit conversion from an `enum` to an `int`.
```
#include <iostream>
enum X {};
bool operator==(X x, int y)
{
return true;
}
int main()
{
X x;
std::cout << std::boolalpha << (x == x+2) << std::endl;
return 0;
}
```
[Answer]
I know it's a code challenge... but I golfed it. Sorry.
**Ruby - 13 characters - Infinity solution**
```
x=1e17;x==x+2
```
returns true
**Ruby - 41 characters - Op Overloading solutions**
```
class Fixnum;def + y;0 end end;x=0;x==x+2
```
or
```
class A;def self.+ y;A end end;x=A;x==x+2
```
[Answer]
If it is ok to exploit the question a little bit, then I will add some new Java. The trick is for sure not new, but perhaps interesting that this is possible in Java.
```
static void pleaseDoNotDoThis() throws Exception {
Field field = Boolean.class.getField("FALSE");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, true);
}
public static void main(String args[]) throws Exception {
pleaseDoNotDoThis();
doit(1);
doit("NO");
doit(null);
doit(Math.PI);
}
static void doit(long x) {
System.out.format("(x == x + 2) = (%d == %d) = %s\n", x, x+2, (x == x + 2));
}
static void doit(String x) {
System.out.format("(x == x + 2) = (%s == %s) = %s\n", x, x+2, (x == x + 2));
}
static void doit(double x) {
System.out.format("(x == x + 2) = (%f == %f) = %s\n", x, x+2, (x == x + 2));
}
```
And the results:
```
(x == x + 2) = (1 == 3) = true
(x == x + 2) = (NO == NO2) = true
(x == x + 2) = (null == null2) = true
(x == x + 2) = (3,141593 == 5,141593) = true
(x == x + 2) = (Infinity == Infinity) = true
```
[Answer]
This VBScript solution works similarly to my JavaScript solution. I did not use a preprocessor yet the solution seems trivial.
```
y = 0
Function x
x = y
y = -2
End Function
If x = x + 2 Then
WScript.Echo "True"
Else
WScript.Echo "False"
End If
```
] |
[Question]
[
In the popular (and essential) computer science book, *An Introduction to Formal Languages and Automata* by Peter Linz, the following formal language is frequently stated:
$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$
mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".
# Challenge
Write a working program/function which gets a string, **containing "a"s and "b"s only**, as input and **returns/outputs a truth value**, saying if this string **is valid the formal language L.**
* Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.
* Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. [More info here.](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)
* Standard code golf rules apply.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Good luck!
### Truthy test cases
```
"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
```
### Falsy test cases
```
""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
## Python 3, 32 bytes
```
eval(input().translate(")("*50))
```
[Try it online!](https://tio.run/##ZVFNbusgEN5zihEbzEtqJarexlaWPUVaWfBCWiQXEEyapgfoumfsRVJmcLp5yGL@vu@bGZwu@BLD/dW/ppgRfFyXS1m3aPZWHNwRJh/SCTs9wPMcrZkBXcERssNTDhyIabInP6MPZZp6hsNu4Y0QkwudJFzp00Wu5Vnq/pw9ui5LKa/uzczd0qPHbEKZTa1J3ck/fzdaXytovx3utk96hDpenwy@1C7FZew2a1Cq5j92G3GMGeoOgUEFDz4MAurxR/gYbsl4wqW5egxK3wC4r/q7HeUGoOlxTx25TKNTZgRXjdqols2XJk8n0b5Te7dpWraV@rfeRvh91z67OZpDlxrCvf9zCeGBjY8BTAGX89D6bdV4G74mb8NLtcKVkgMoWNV/kXJXi7r6vNbIuv@t7KgO359fIImGFMr2fNurscIYS1e92ZBtDnuL23wrhBGUEbZ@XCK6MDUkFcuVarncqCxNKIIYvojQGEwhDpEIYlmGdZpQU7I/ "Python 3 – Try It Online")
[Outputs via exit code](https://codegolf.meta.stackexchange.com/a/5330/20260): Error for false, no error for True.
The string is evaluated as Python code, replacing parens `(` for `a` and `)` for `b`. Only expressions of the form `a^n b^n` become well-formed expressions of parentheses like `((()))`, evaluating to the tuple `()`.
Any mismatched parens give an error, as will multiple groups like `(()())`, since there's no separator. The empty string also fails (it would succeed on `exec`).
The conversion `( -> a`, `) -> b` is done using `str.translate`, which replaces characters as indicated by a string that serves as a conversion table. Given the 100-length string ")("\*50, the tables maps the first 100 ASCII values as
```
... Z[\]^_`abc
... )()()()()(
```
which takes `( -> a`, `) -> b`.
In Python 2, conversions for all 256 ASCII values must be provided, requiring `"ab"*128`, one byte longer; thanks to isaacg for pointing this out.
[Try it online!](https://tio.run/##ZVBBjtswDLzrFYR6kNWkRrynwoaPfUVaGNJG2RXgSoJEd5t9QM99Yz@SkpLTSwVDpGY4Q9Lphq8xPN0/PMeLDy/zhlfhv6eYEXw8lls50ktc3BUWH9KGnR7hZY3WrICu4ATZ4ZYDuB9m7RjRYlns5lf0oSxLX0Uw7@oJYnKhk1xY@nSTR/kmdf@WPbouSynv1Wfv1GM2oayGOKk7@XF4@qz1narOw/hp@KYnoPn6ZPCV2hSXsTsdQSnC3@eTuMYMtESoRQVpu1EAHX@F9/EBxg337uprUPpRgGfyn2fGRuDx8cwdK82zE6KkOuCB7gkcP0@qsfnW2vBJvPjSfuey7GtL/Y9voxDfZ7dGc@lS49zPZ5cQvtTgYwBTwOU8tk6Dmh7jE7iPX6c6AI2rKGSXckekZogXm6rvf0s75uHPr98gWVYdZPuBw91YYYzli@4aOLakZnvaciuEEYwIS1@lWC4MPdnFVoZipZu0WnMVl5h6saApqoQ1LOISW22qTzNqTvYv "Python 2 – Try It Online") (Python 2, 33 bytes)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
```
tSP-
```
Prints a non-empty array of **1**s if the string belongs to **L**, and an empty array or an array with **0**s (both falsy) otherwise.
*Thanks to @LuisMendo for golfing off 1 byte!*
[Try it online!](http://matl.tryitonline.net/#code=dFNQLQ&input=J2FhYmIn)
### How it works
```
t Push a copy of the implicitly read input.
S Sort the copy.
P Reverse the sorted copy.
- Take the difference of the code point of the corresponding characters
of the sorted string and the original.
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 12 bytes
*Credits to FryAmTheEggman who found this solution independently.*
```
+`a;?b
;
^;$
```
Prints `1` for valid input and `0` otherwise.
[Try it online!](http://retina.tryitonline.net/#code=JShHYAorYGE7P2IKOwpeOyQ&input=YWIKYWFiYgphYWFhYmJiYgphYWFhYWFhYmJiYmJiYgoKYQpiCmJhCmFiYWIKYWFiCmFiYgphYWFhYmJi) (The first line enables a linefeed-separated test suite.)
### Explanation
Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.
**Stage 1**
```
+`a;?b
;
```
The `+` tells Retina to repeat this stage in a loop until the output stops changing. It matches either `ab` or `a;b` and replaces it with `;`. Let's consider a few cases:
* If the `a`s and the `b`s in the string aren't balanced in the same way that `(` and `)` normally need to be, some `a` or `b` will remain in the string, since `ba`, or `b;a` can't be resolved and a single `a` or `b` on its own can't either. To get rid of all the `a`s and the `b`s there has to be one corresponding `b` to the right of each `a`.
* If the `a` and the `b` aren't all nested (e.g. if we have something like `abab` or `aabaabbb`) then we'll end up with multiple `;` (and potentially some `a`s and `b`s) because the first iteration will find multiple `ab`s to insert them and further iterations will preserve the number of `;` in the string.
Hence, if and only if the input is of the form `anbn`, we'll end up with a single `;` in the string.
**Stage 2:**
```
^;$
```
Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either `0` or `1`.)
[Answer]
## Haskell, 31 bytes
```
f s=s==[c|c<-"ab",'a'<-s]&&s>""
```
The list comprehension `[c|c<-"ab",'a'<-s]` makes a string of one `'a'` for each `'a'` in `s`, followed by one `'b'` for each `'a'` in `s`. It avoids counting by [matching on a constant](https://codegolf.stackexchange.com/a/83103/20260) and producing an output for each match.
This string is checked to be equal to the original string, and the original string is checked to be non-empty.
[Answer]
## [Grime](http://github.com/iatorm/grime), 12 bytes
```
A=\aA?\b
e`A
```
[Try it online!](http://grime.tryitonline.net/#code=QT1cYUE_XGIKZWBB&input=YWFhYWJiYmI)
## Explanation
The first line defines a nonterminal `A`, which matches one letter `a`, possibly the nonterminal `A`, and then one letter `b`. The second line matches the entire input (`e`) against the nonterminal `A`.
## 8-byte noncompeting version
```
e`\a_?\b
```
After writing the first version of this answer, I updated Grime to consider `_` as the name of the top-level expression. This solution is equivalent to the above, but avoids repeating the label `A`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~23~~ 19 bytes
```
@2L,?lye:"ab"rz:jaL
```
[Try it online!](http://brachylog.tryitonline.net/#code=QDJMLD9seWU6ImFiInJ6OmphTA&input=ImFhYWFhYWFiYmJiYmJiIg)
### Explanation
```
@2L, Split the input in two, the list containing the two halves is L
?lye Take a number I between 0 and the length of the input
:"ab"rz Zip the string "ab" with that number, resulting in [["a":I]:["b":I]]
:jaL Apply juxtapose with that zip as input and L as output
i.e. "a" concatenated I times to itself makes the first string of L
and "b" concatenated I times to itself makes the second string of L
```
[Answer]
# Bison/YACC 60 (or 29) bytes
(Well, the compilation for a YACC program is a couple of steps so might want to include some for that. See below for details.)
```
%%
l:c'\n';
c:'a''b'|'a'c'b';
%%
yylex(){return getchar();}
```
The function should be fairly obvious if you know to interpret it in terms of a formal grammar. The parser accepts either `ab` or an `a` followed by any acceptable sequence followed by a `b`.
This implementation relies on a compiler that accepts K&R semantics to lose a few characters.
It's wordier than I would like with the need to define `yylex` and to call `getchar`.
Compile with
```
$ yacc equal.yacc
$ gcc -m64 --std=c89 y.tab.c -o equal -L/usr/local/opt/bison/lib/ -ly
```
(most of the options to gcc are specific to my system and shouldn't count against the byte count; you might want to count `-std=c89` which adds 8 to the value listed).
Run with
```
$ echo "aabb" | ./equal
```
or equivalent.
The truth value is returned to the the OS and errors also report `syntax error` to the command line. If I can count only the part of the code that defines the parsing function (that is neglect the second `%%` and all that follows) I get a count of 29 bytes.
[Answer]
# J, ~~17~~ 15 bytes
*-2 bytes thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)!*
```
#<.2&#-:'ab'#~#
```
This works correctly for giving falsey for the empty string. Error is falsey.
Other versions:
```
<e.'ab'<@#"{~#\ NB. alternate 15 bytes, thanks to Jonah
#<.(-:'ab'#~-:@#)
NB. the following do not handle the empty string correctly
-:'ab'#~-:@#
2&#-:'ab'#~# NB. thanks to miles
```
## Proof and explanation
*Outdated, but applicable to the old 17 byte version.*
The main verb is a fork consisting of these three verbs:
```
# <. (-:'ab'#~-:@#)
```
This means, "The lesser of (`<.`) the length (`#`) and the result of the right tine (`(-:'ab'#~-:@#)`)".
The right tine is a [4-train](http://www.jsoftware.com/help/learning/09.htm), consisting of:
```
(-:) ('ab') (#~) (-:@#)
```
Let `k` represent our input. Then, this is equivalent to:
```
k -: ('ab' #~ -:@#) k
```
`-:` is the match operator, so the leading `-:` tests for invariance under the monadic fork `'ab' #~ -:@#`.
Since the left tine of the fork is a verb, it becomes a constant function. So, the fork is equivalent to:
```
'ab' #~ (-:@# k)
```
The right tine of the fork halves (`-:`) the length (`#`) of `k`. Observe `#`:
```
1 # 'ab'
'ab'
2 # 'ab'
'aabb'
3 # 'ab'
'aaabbb'
'ab' #~ 3
'aaabbb'
```
Now, this is `k` only on valid inputs, so we are done here. `#` errors for odd-length strings, which *never* satisfies the language, so there we are also done.
Combined with the lesser of the length and this, the empty string, which is not a part of our language, yields its length, `0`, and we are done with it all.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes
Code:
```
.M{J¹ÔQ0r
```
Explanation:
```
.M # Get the most frequent element from the input. If the count is equal, this
results into ['a', 'b'] or ['b', 'a'].
{ # Sort this list, which should result into ['a', 'b'].
J # Join this list.
Ô # Connected uniquified. E.g. "aaabbb" -> "ab" and "aabbaa" -> "aba".
Q # Check if both strings are equal.
0r # (Print 0 if the input is empty).
```
The last two bytes can be discarded if the input is guaranteed to be non-empty.
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Lk17SsK5w5RR&input=YWFhYWJiYmI).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣ=Ṛ¬Pȧ
```
Prints the string itself if it belongs to **L** or is empty, and **0** otherwise.
[Try it online!](http://jelly.tryitonline.net/#code=4bmiPeG5msKsUMin&input=&args=YWFiYg) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmiPeG5msKsUMinCsOH4oKsauKBtw&input=&args=ImFiIiwgImFhYmIiLCAiYWFhYmJiIiwgImFhYWFiYmJiIiwgImFhYWFhYmJiYmIiLCAiYWFhYWFhYmJiYmJiIiwgIiIsICJhIiwgImIiLCAiYWEiLCAiYmEiLCAiYmIiLCAiYWFhIiwgImFhYiIsICJhYmEiLCAiYWJiIiwgImJhYSIsICJiYWIiLCAiYmJhIiwgImJiYiIsICJhYWFhIiwgImFhYWIiLCAiYWFiYSIsICJhYmFhIiwgImFiYWIiLCAiYWJiYSIsICJhYmJiIiwgImJhYWEiLCAiYmFhYiIsICJiYWJhIiwgImJhYmIiLCAiYmJhYSIsICJiYmFiIiwgImJiYmEiLCAiYmJiYiI).
### How it works
```
Ṣ=Ṛ¬Pȧ Main link. Argument: s (string)
Ṣ Yield s, sorted.
Ṛ Yield s, reversed.
= Compare each character of sorted s with each character of reversed s.
¬ Take the logical NOT of each resulting Boolean.
P Take the product of the resulting Booleans.
This will yield 1 if s ∊ L or s == "", and 0 otherwise.
ȧ Take the logical AND with s.
This will replace 1 with s. Since an empty string is falsy in Jelly,
the result is still correct if s == "".
```
## Alternate version, 4 bytes (non-competing)
```
ṢnṚȦ
```
Prints **1** or **0**. [Try it online!](http://jelly.tryitonline.net/#code=4bmibuG5msim&input=&args=) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmibuG5msimCsOH4oKsRw&input=&args=ImFiIiwgImFhYmIiLCAiYWFhYmJiIiwgImFhYWFiYmJiIiwgImFhYWFhYmJiYmIiLCAiYWFhYWFhYmJiYmJiIiwgIiIsICJhIiwgImIiLCAiYWEiLCAiYmEiLCAiYmIiLCAiYWFhIiwgImFhYiIsICJhYmEiLCAiYWJiIiwgImJhYSIsICJiYWIiLCAiYmJhIiwgImJiYiIsICJhYWFhIiwgImFhYWIiLCAiYWFiYSIsICJhYmFhIiwgImFiYWIiLCAiYWJiYSIsICJhYmJiIiwgImJhYWEiLCAiYmFhYiIsICJiYWJhIiwgImJhYmIiLCAiYmJhYSIsICJiYmFiIiwgImJiYmEiLCAiYmJiYiI).
### How it works
```
ṢnṚȦ Main link. Argument: s (string)
Ṣ Yield s, sorted.
Ṛ Yield s, reversed.
n Compare each character of the results, returning 1 iff they're not equal.
Ȧ All (Octave-style truthy); return 1 if the list is non-empty and all numbers
are non-zero, 0 in all other cases.
```
[Answer]
# JavaScript, ~~54~~ ~~55~~ 44
```
s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
```
Builds a simple regex based on the length of the string and tests it. For a length 4 string (`aabb`) the regex looks like: `^a{2}b{2}$`
Returns a truthy or falsey value.
11 bytes saved thanks to Neil.
```
f=s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
// true
console.log(f('ab'), !!f('ab'))
console.log(f('aabb'), !!f('aabb'))
console.log(f('aaaaabbbbb'), !!f('aaaaabbbbb'))
// false
console.log(f('a'), !!f('a'))
console.log(f('b'), !!f('b'))
console.log(f('ba'), !!f('ba'))
console.log(f('aaab'), !!f('aaab'))
console.log(f('ababab'), !!f('ababab'))
console.log(f('c'), !!f('c'))
console.log(f('abc'), !!f('abc'))
console.log(f(''), !!f(''))
```
[Answer]
## Perl 5.10, ~~35~~ 17 bytes (with *-n* flag)
```
say/^(a(?1)?b)$/
```
Ensures that the string starts with `a`s and then recurses on `b`s. It matches only if both lengths are equal.
Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for halving the byte count and teaching me a little about recursion in regexes :D
It returns the whole string if it matches, and nothing if not.
[Try it here!](http://ideone.com/jSHlcB)
[Answer]
## C, ~~57~~ 53 Bytes
```
t;x(char*s){t+=*s%2*2;return--t?*s&&x(s+1):*s*!1[s];}
```
Old 57 bytes long solution:
```
t;x(char*s){*s&1&&(t+=2);return--t?*s&&x(s+1):*s&&!1[s];}
```
Compiled with gcc v. 4.8.2 @Ubuntu
Thanks ugoren for tips!
[Try it on Ideone!](http://ideone.com/10U9t6)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ ~~6~~ ~~5~~ 4 bytes
```
I÷<g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZiIsIknDtzxnIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiScO3PGciLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f` header
Takes a list of characters as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise. This matches Vyxal's truthy/falsey semantics, which can be confirmed by putting `ḃ` (Boolify) in the Footer.
```
I # Into Two Pieces - Splits a list into two halves and wraps them in a list.
# If the input is odd in length, the left side gets 1 more character.
÷ # Item Split - Unwraps the list created above. Required so that the next
# operation can compare the two halves.
< # Less Than (vectorized) - Are items in the left half list less than the
# corresponding items in the right half list? Puts 1 where yes, 0 where no.
# The resulting list takes the size of whichever list was longer. For items
# at the end of that list with no corresponding item in the other list, it
# puts 0 if that position is empty in the right list, and 1 if it's empty in
# the left list (which can never happen in this program).
g # Minimum
```
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes:
```
I÷<A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZiIsIknDtzxBIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiScO3PEEiLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f` header
Takes a list of characters as input. Outputs `1` for true and `0` for false. Only the last element of the program is different:
```
A # Check if all items in a list are truthy (returns truthy for an empty list)
```
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~6~~ ~~5~~ 4 bytes
```
sṘ꘍g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZjoiLCJz4bmY6piNZyIsIiIsIlwiYWJcIlxuXCJhYWJiXCJcblwiYWFhYmJiXCJcblwiYWFhYWJiYmJcIlxuXCJhYWFhYWJiYmJiXCJcblwiYWFhYWFhYmJiYmJiXCJcblwiXCJcblwiYVwiXG5cImJcIlxuXCJhYVwiXG5cImJhXCJcblwiYmJcIlxuXCJhYWFcIlxuXCJhYWJcIlxuXCJhYmFcIlxuXCJhYmJcIlxuXCJiYWFcIlxuXCJiYWJcIlxuXCJiYmFcIlxuXCJiYmJcIlxuXCJhYWFhXCJcblwiYWFhYlwiXG5cImFhYmFcIlxuXCJhYmFhXCJcblwiYWJhYlwiXG5cImFiYmFcIlxuXCJhYmJiXCJcblwiYmFhYVwiXG5cImJhYWJcIlxuXCJiYWJhXCJcblwiYmFiYlwiXG5cImJiYWFcIlxuXCJiYmFiXCJcblwiYmJiYVwiXG5cImJiYmJcIiJd)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwic+G5mOqYjWciLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f:` header
Takes a list of characters as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise.
This is a port of [Dennis's MATL answer](https://codegolf.stackexchange.com/a/86037/17216), with an algorithm also used by many subsequent answers.
```
s # Pushes a copy of the input, sorted.
Ṙ # Reverses the sorted copy.
꘍ # Levenshtein distance (vectorized) - Used here to compare corresponding
# single-character strings between two lists, so it's effectively a vectorized
# Not Equals, giving 1 for unequal and 0 for equal. This works around the fact
# that Vyxal has no vectorizing Not Equals operator (even though it does have
# vectorizing versions of all the other basic comparison operators). For input
# in L, this will yield a non-empty list of all 1s. For an empty input it will
# yield an empty list. For all other inputs it yields a list of both 1s and 0s.
g # Minimum
```
To take a string as input, this becomes `f:sṘ꘍g` or alternatively `fṘḂs꘍g` (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see `AḂs꘍↓` below).
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in 4 bytes using this algorithm:
```
sṘ꘍A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZjoiLCJz4bmY6piNQSIsIiIsIlwiYWJcIlxuXCJhYWJiXCJcblwiYWFhYmJiXCJcblwiYWFhYWJiYmJcIlxuXCJhYWFhYWJiYmJiXCJcblwiYWFhYWFhYmJiYmJiXCJcblwiXCJcblwiYVwiXG5cImJcIlxuXCJhYVwiXG5cImJhXCJcblwiYmJcIlxuXCJhYWFcIlxuXCJhYWJcIlxuXCJhYmFcIlxuXCJhYmJcIlxuXCJiYWFcIlxuXCJiYWJcIlxuXCJiYmFcIlxuXCJiYmJcIlxuXCJhYWFhXCJcblwiYWFhYlwiXG5cImFhYmFcIlxuXCJhYmFhXCJcblwiYWJhYlwiXG5cImFiYmFcIlxuXCJhYmJiXCJcblwiYmFhYVwiXG5cImJhYWJcIlxuXCJiYWJhXCJcblwiYmFiYlwiXG5cImJiYWFcIlxuXCJiYmFiXCJcblwiYmJiYVwiXG5cImJiYmJcIiJd)
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwic+G5mOqYjUEiLCIiLCJbXCJhXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJhXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCIsXCJiXCJdXG5bXVxuW1wiYVwiXVxuW1wiYlwiXVxuW1wiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYVwiLFwiYlwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYVwiLFwiYlwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYVwiLFwiYlwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYVwiXVxuW1wiYlwiLFwiYlwiLFwiYlwiLFwiYlwiXSJd) - without the `f:` header
Takes a list of characters as input. Outputs `1` for true and `0` for false.
To take a string as input, this becomes `f:sṘ꘍A` or alternatively `fṘḂs꘍A` (6 bytes). It is, however, possible to do this with the sort-and-reverse algorithm in 5 bytes (see `AḂs꘍A` below).
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
fI÷<g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZknDtzxnIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true for inputs in \$\{a^n b^n:n∈\mathbb{Z}^+\}\$, and empty string or `0` for false otherwise. This is just one of the above 4 byte programs with `f` inserted at the beginning.
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
```
fI÷<A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZknDtzxBIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true and `0` for false.
This too is just one of the above 4 byte programs with `f` inserted at the beginning – but it can also be done without `f`, using a conceptually similar algorithm:
```
½C÷‹⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwr1Dw7figLnigbwiLCIiLCJcImFiXCJcblwiYWFiYlwiXG5cImFhYWJiYlwiXG5cImFhYWFiYmJiXCJcblwiYWFhYWFiYmJiYlwiXG5cImFhYWFhYWJiYmJiYlwiXG5cIlwiXG5cImFcIlxuXCJiXCJcblwiYWFcIlxuXCJiYVwiXG5cImJiXCJcblwiYWFhXCJcblwiYWFiXCJcblwiYWJhXCJcblwiYWJiXCJcblwiYmFhXCJcblwiYmFiXCJcblwiYmJhXCJcblwiYmJiXCJcblwiYWFhYVwiXG5cImFhYWJcIlxuXCJhYWJhXCJcblwiYWJhYVwiXG5cImFiYWJcIlxuXCJhYmJhXCJcblwiYWJiYlwiXG5cImJhYWFcIlxuXCJiYWFiXCJcblwiYmFiYVwiXG5cImJhYmJcIlxuXCJiYmFhXCJcblwiYmJhYlwiXG5cImJiYmFcIlxuXCJiYmJiXCIiXQ==)
Takes a string as input. Outputs `1` for true and `0` for false.
```
½ # Split in half. If odd in length, the left side gets 1 more character. This
# creates a list containing two strings.
C # Convert characters to their ASCII values. This results in a list containing
# two lists of ASCII values.
÷ # Item Split - split the list into its elements on stack; in this case, these
# are the left and right halves, each of which is a list of ASCII values.
‹ # Decrement - iff the right half is all 'b' (ASCII 98), this will change it to
# all 'a' (ASCII 97)
⁼ # Are the two top items on the stack exactly equal? This gives a boolean value
# that's 1 for true (equal counts of 'a' and 'b') and 0 for false.
```
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
AḂs꘍↓
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQeG4gnPqmI3ihpMiLCIiLCJcImFiXCJcblwiYWFiYlwiXG5cImFhYWJiYlwiXG5cImFhYWFiYmJiXCJcblwiYWFhYWFiYmJiYlwiXG5cImFhYWFhYWJiYmJiYlwiXG5cIlwiXG5cImFcIlxuXCJiXCJcblwiYWFcIlxuXCJiYVwiXG5cImJiXCJcblwiYWFhXCJcblwiYWFiXCJcblwiYWJhXCJcblwiYWJiXCJcblwiYmFhXCJcblwiYmFiXCJcblwiYmJhXCJcblwiYmJiXCJcblwiYWFhYVwiXG5cImFhYWJcIlxuXCJhYWJhXCJcblwiYWJhYVwiXG5cImFiYWJcIlxuXCJhYmJhXCJcblwiYWJiYlwiXG5cImJhYWFcIlxuXCJiYWFiXCJcblwiYmFiYVwiXG5cImJhYmJcIlxuXCJiYmFhXCJcblwiYmJhYlwiXG5cImJiYmFcIlxuXCJiYmJiXCIiXQ==)
Takes a string as input. Outputs `1` for true, and empty string or `0` for false.
This is an adaptation of the algorithm used in [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/86034/17216) and [MATL answer](https://codegolf.stackexchange.com/a/86037/17216) (and many subsequent answers):
```
A # Check if character is a vowel (vectorized)
# Converts each 'a' to 1, and each 'b' to 0. Pushes the result as a list if
# the input was a string of 2 characters or longer, but only pushes a single
# integer if it was a single-character string. This limits what useful
# operations can subsequently be done (for example, it can't be reliably
# split into two halves).
Ḃ # Bifurcate - Pushes the top of the stack then its reverse.
s # Sort - Operates on the non-reversed copy.
꘍ # Bitwise Xor (vectorized)
↓ # Minimum by tail. On a list of numbers, it picks the item with the minimum
# last digit. On a single number, it picks the minimum digit. Since the only
# numbers given to it here will be 0 and 1, that's the same as the standard
# minimum, except that it avoids the crash that happens with "g" (Minimum)
# when its argument is not a list.
```
It appears to be impossible to solve this challenge in Vyxal in less than 5 bytes taking a string as input.
---
Determining membership in \$\{a^n b^n:n∈\mathbb{Z}^0\}\$ can also be done in this way:
```
AḂs꘍A
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiQeG4gnPqmI1BIiwiIiwiXCJhYlwiXG5cImFhYmJcIlxuXCJhYWFiYmJcIlxuXCJhYWFhYmJiYlwiXG5cImFhYWFhYmJiYmJcIlxuXCJhYWFhYWFiYmJiYmJcIlxuXCJcIlxuXCJhXCJcblwiYlwiXG5cImFhXCJcblwiYmFcIlxuXCJiYlwiXG5cImFhYVwiXG5cImFhYlwiXG5cImFiYVwiXG5cImFiYlwiXG5cImJhYVwiXG5cImJhYlwiXG5cImJiYVwiXG5cImJiYlwiXG5cImFhYWFcIlxuXCJhYWFiXCJcblwiYWFiYVwiXG5cImFiYWFcIlxuXCJhYmFiXCJcblwiYWJiYVwiXG5cImFiYmJcIlxuXCJiYWFhXCJcblwiYmFhYlwiXG5cImJhYmFcIlxuXCJiYWJiXCJcblwiYmJhYVwiXG5cImJiYWJcIlxuXCJiYmJhXCJcblwiYmJiYlwiIl0=)
Takes a string as input. Outputs `1` for true and `0` for false. Only the last element of the program is different:
```
A # Check if all items in a list are truthy (returns truthy for an empty list)
```
[Answer]
The purpose of this post is to demonstrate and explain the full list of golfed pure regexes that solve this challenge, and the range of compatibility of each among seven different regex engines, and rank them by length, all together in one post. Others' answers used the best regexes before this post; they are listed below. I ported the **Java** one to three other sets of regex engines, including Python 3's `regex` library.
# Regex (Perl / PCRE / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 11 bytes
```
^(a(?1)?b)$
```
[Try it online!](https://tio.run/##TYxBa8MwDIXv/hWiGGJDR5rDLnHTUOh27KnHUWONFAJe2zntYYT0r2eSXNjASM9673vXLsXX@esHdHIwxstniKBLR99mvdsetptJnS7J6L5ZufXG0a7sCP2JLna8pv58g8XHeeEm0BEaGO443Cjuly/VsrLdN5vQ/ruvyLFQg/ZOAeQGYxh@QKlTadvikO5dDVDUxXuIA8nC/mV1dDB5/7bfeT8fTTBtZVu0ep4DqhCQB01ZvLMQ9ZRZo1JB8UUhPbEYV4G@3ILi0BY7o1LNKY4EGQxkQhBmGOIISo305KLchL8 "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MWwWULtKe2ha0IZAe2AwVUzaBCxy0ksaLU0sx1lHUf/6ujs7ZYWHRZF9vvu@785fkmp9lKfp5lVRpWU7Qxjr1ODx/CRI58pArG/vYQLT3sfl8mcybL8/PHy7mb9fzsXmh1DidCBPE/l6I1@WeyEc6kms3w6i4J90Y2dFzdq7KVNU@fNcUVMW1eIkKCoLmgA2RmNqI9K6aiy4yQ4X2DQqR/lIqqNRSgAYj6HLcujyWM3KCAza1lQwiNZOcqGKSkh4DIAefUvdSqyElkeD@0k/gpYww3exhZpPTMgpcGCn6Wemgm5tBOwXHBqMYHc6Gkdb49kGm7a0PuZ7ZFmDNoS6tdQ2t3NfqX9hamtzO7z3rUh14sTjtF7ookShQ@iH8MZL@2Cr1ZeeVGQg9gzK7Y0z514maG5Ch9D7cjY9d0MYUNTT0WF/NoL95q6ir7aj6ft0whkRBI@5Yk@cDTnasqhQeP@LKvSOyIgwg62726FWEqjG3oiDu@qgU/X3ZHe2d8XfmAqDIVx9vbzsFI/TmCwXcntsihXyqe/ezrcQhjui3LITHpM5O8O8qO5NgC2Jz6fT62l8df35w83ZJwmdbb1zdmoEPboUlg0@5S8UnVz@SXj9HHFjWgI8Q2RLU1gU/73TIGRza7bR8dbefYNIE8unP7n7pYL1RiWBUgkvtLqNdx@4qAt9nASBCjgTJPS6EtMDRUdWSVyFdlf2VCfNKIYotzDBMxyFOUxiSOJknI4X8krJnzQrVd5sjkr@zn8B "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNboMwEITvPIVrWYpdkR@ucRGXkipSlVQ0t9JaNjIByRBkyKnqs9Nd01Ml7B3vznwYhmaYn7KhGQjzJCV0S8mGDN5elbeD05Xlq@3mMVOq0W5S1a0bWmd9yUshy2I7rmKyglVDU10tGvrJ9tPIlTocX3OlREwSAUgAy6i@ec7adCeZS2uwj/z98nw8CSm@SVtz5j7GyTvbgxLr5DNNadlTAebxbmAC7XgXrxMhg7sVtmpuaJEEqImMCGFdGi7f6alqOPMxkCRB3/JRTo@Tst7DRcRD@lbkL@p0VnlRnIuM5tjfE7rnrMvoxd/tnsCJHrQbQVKBbwgsyhyVP/9@Chdy/uKaZ4nIjGDzrE2ktcEN9lCwLiKoP7loE0U6wk5k4AkjjEcajkgxYQI1jJdoQKMLLTpsGFgSIYIZDKHFBEzgLKCFZH4B "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##XVDbbpwwEH33V4xopNgtuy2N1AfoZqU@9AOqPLRKUmQ7BqywxjJGNFvl10s8Q65FaDzjM@fM8WjvN63WyzvrdD/dGPiqhmGMH4NpzZ9t5/05050MUPvLa9jBj@zbPN@qs@nX3d3Pi@7L3PHlN5d8X4i9EieL@B/Ocnjvd7X/UFTsZYZNI4KRh3NmXYSDtI4L@Msgff4yQb1x3ItNcb37VMGUes4@1xEGrJDQpoSax3hTlqnfujYBfooV6MGNEegRZUmvgGC4z99claXVcjSierodDzLqDuZOxlW5GQJwnHXEoTSnNbG3znAqtHX5OjKJHHfFk338bAP8KCBhuDp@euVORfWM@uQ2Nvy1nXo0MuiOk15OLvLkWsAesoswmRIggxKy77IfU5G9UmvmYKNZmVtdp11w8WhsO9qjwarI8QEDWiXePcVg4hQcpE3eL1IxKRWGFOnAc00oe0zXXDEmGd4wlX6CkM5kKlFFEZJOglcqSWMXtkgKSFgZREEOkrBFkQzprEKrkvqnm16247LpaX01be8B "C++ (gcc) – Try It Online") - Boost
[Try it online!](https://tio.run/##bY5BagMxDEX3PoUwhdiQDhm6czHZ9QTdTVuQG6cxuJ5B49Dm9FNLzrJgpC/p/4eXW73M5WlL38tMFdbbuqf4FX8VgQfSWm8fBs1xtMdgH7Y2T6N7HN@fIfmDOs8EGVLh2LDWUypOAaQzJAcLpVKN5dmPfZtjMdkClhPkqUG8372VnYPs83RgarPdSfO1Dj@UajT6la7RAWgmyNeGNSJ9XgztodFiXiPoF2zNgbb/IbLdMCjEwKVVady7EHWXXQelUPFGhfbkxHGFbWRKkEvrcu5RQbOLLSiFAz0hEc5wiC1BMMLpoE4Kfw "Python 3 – Try It Online") - Python `import regex`
Included for completeness. Already used in:
* [Martin Ender's Mathematica answer](https://codegolf.stackexchange.com/a/86104/17216)
* [Titus's PHP answer](https://codegolf.stackexchange.com/a/86365/17216)
* [Paul Picard's Perl answer](https://codegolf.stackexchange.com/a/86006/17216)
```
^ # Assert we're at the beginning of the string.
( # Define subroutine (?1):
a # Match one 'a'.
(?1)? # Optionally do a recursive subroutine call to (?1).
b # Match one 'b'.
)
$ # Assert we're at the end of the string.
```
When the regex engine hits the `(?1)?`, it has the choice of whether to do the call or not. Due to `?` being greedy by default, it first tries doing the call; if it then hits a `b` character instead of an `a`, it will backtrack, avoid doing the subroutine call, and then reach the part of the regex that matches a `b` character.
From that point forward, it will keep popping out of the recursive call stack, matching another `b` each time. This way, the number of times that it attempts to match `b` equals the number of `a` it matched at the beginning.
If it finds an `a` when attempting to match `b`, this will trigger a non-match. If it finishes popping and still finds more `b` characters, this will trigger a non-match at the `$` part of the regex. If it reaches the end of the string prematurely during this stage, it will pop out from that call and attempt to match another `b`, thus triggering a non-match.
The only backtracking left to be tried at the popping-out stage, in the case of any of those non-matches, is to stop calling `(?1)` at an earlier point, but this will also fail to match, as it will then be trying to match `a` where the string has a `b`; this will result in a top-level non-match.
# Regex (PCRE / Ruby), 12 bytes
```
^(a\g<1>?b)$
```
[Try it online!](https://tio.run/##fVJRb9MwEH7Pr7gVxpyRTS2VeGjaIZiGeBgbqoYE2kbkuJc0Ik0sx6FsU/865c5OS7sHosg@333fd@cvUVqf5EqtXxSVKtsZwlgrg6fzs0DNpYFE397DBKa9D8vlz3TYfn94@HYzf7uci/UPIe/y8eDsXRq@XIfP670IjvUk0a8HcfBPu7Gzombx3ZQpqnw/V9SURbk4C4rKgiaATdCY2ghVV40FN9rxAptG5hg@kepopAgA4zF0WQ5dHqtZGYNB25oKBvHKSS5kUYkQngKgR99StxIrocOTwf2kH0NLmOGbxELNJybkFDiw0/QzU0G3NgY2DI4NxrA7HY2jrfFsg01bWh/zPbKsQRtB3Vpqm9u5r9S/UNna3A7vfStSnTjxRNULXZQodAT9CF55aR9stPqhJxUZiAOD4ebGmXMvEzQ3oSPofTmfXrghDEjq6ehwOBvBYXNX0Vfb0fR9OuGMCILHfGRPnA052rKoUHj/iyryjoQxYQYbdzdDPYZANfZGHN1VR52qvye7s7kr/kYlDEZw9fXyslM8VQlZLsLNsSkekU9993a@RTDcEeWWnfCYzNkZ5ln1YAJsSXIxnV5Pk6vrz@9vzj@F0NnWu2CnRtCjS2HZ4Db/UdLJ5bfCq33EjWkJsIfIlqawKP57p0HE5tZso@OtvPsGkSYOt39y90sFq7VMAylTXmh1G@8@cFEX@jgNAhlwJkjpdSWmB5KOrJK6Cu2u7KlOmlEMkW5hgmc4CnOYxJDUyTgdL@SV0j8qK2XerE9K/s5/AQ "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNboMwEITvPIVrWYpdkR@ucSiXkipSlVQ0t9JaNjIBySHIkFPVZ6e7pqdK2Dvenfkw9E0/7bK@6QnzJCV0TcmK9N5elLe905Xli/XqMVOq0W5U1e3at876kpdClsV6WMRkAauGprpYNHSj7caBK7U/vOZKiZgkApAAllF985y16UYyl9ZgH/j7@flwFFJ8k7bmzH0Mo3e2AyWWyWea0rKjAszD3cAE2vEmXiZCBncrbNXc0CIJUBMZEcKuabj8VY9Vw5mPgSQJ@uaPcnoYlfUeLiIe0rcif1HHk8qL4lRkNMf@ltAtZ9eMnv3dbgmc6F67ASQV@IbAosxR@fPvp3Ahpy@uy8suecqMYNOkTaS1wQ32ULDOIqg/OWsTRTrCTmTgCSOMRxqOSDFhAjWM52hAowstOmwYmBMhghkMocUETODMoJlkfgE "PHP – Try It Online") - PCRE2
**[Try it online!](https://tio.run/##RYzBasMwEETv@oqpyKE9xMQ9RlVDIO0xh5JbkhotUV2BMEa2SXPJr7vaVaEgdmc18yZNdJsTLD5863/6qvNX7LaHbZW8uxgEuzK4fofoEW3rx0EB4Qvhgf/7aRwMfCe52rARj8v6bK0@ddpkIh5XVbV8Pksqo30K3YgIe0fCBvqQJr8GNNbQ7y4O@dD/sUI1zdt@1zTz56M7tS/164aeFvPsSDlHPPKUxbsIUX@yaFLKKf5RlJ9YjCuXT24hcfIWu6BSzSmOOBkMFEIQZhjiCEmN9JSi0kS/ "Ruby – Try It Online") - Ruby**
Included for completeness. Already used in [G B's Ruby answer](https://codegolf.stackexchange.com/a/182021/17216).
This is the same as the 11 byte version, but using Ruby's subroutine call syntax.
# Regex (Perl / PCRE / Java), 21 bytes
```
^(a(?=a*(\2?+b)))+\2$
```
[Try it online!](https://tio.run/##TYxBi8IwEIXv@RWDBJqsLrXCXhprEVyPnjyWDZOlQiGrbqoHKfWvd2eShV0IMy/z3veubfBv09cDZDAw@MsnepC5oW@13m2P280oTpegZFctzXpjaBd6gO5EFz1cQ3e@waw5z8wI0kMF/d31N4rbxWuxKHT7zSbU/@5LcjSUIK0RAKlBKYafkMuQ6zo7hntbAmRltkffk8z0X1Z6A6O174edtdOHQlVX@KKaVT13Wut5s5LThE4gOh404@KdRFS/MmknBAq@CEcvWowLpC@3uOjQjnZCYzWnOIJxMJCIiDDDEEdcrIk9qSg1uR8 "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9Fls7OL44Rzfjw7e7vhr4GdELp6HOvjfhT8a1LbeV5Rl/2UycvsZS6vMKvE8jzISwsaATZWxlSGyaqsLbgZu0tV1yJT/BlVh0OJABiNoM1S6PKqnBcRGGUbU0I/WjvJpchLxuE5AHz0PXYrVMk0P@k/jHsRNIgZnMUWKjoRIcPAgZ2mnxkLurERkHPQNSqC/elwHG2NZxtVN4X1Md0jTWtlQ6gai20zu/CV6peStjL3gwffClXHTjyW1VLnhWI6hF4I77y0D7ZaPe5JeQrswCi@vXHq3EsZzo3oEDpfLidXbggDAns6OhzOh3BYz0r8anuavk8rnCKB0ZhP5ImzIVO2yEvFvP95GXpHeISY/tbd7VBPHLBG3rCjWXnUqvp7kjvbu6rfSjKjQrj9enPTKp7KGC1nfHus8ydFp557W99CGOyJUstWeITm7A3zqnowBrIkvppM7ibx7d3nD9PLTxxa2zpX5NQQOngpVdRql78WeHL5nfD6JWJqGgS8QKQrk1vF/nunfkjmVmSj4629@0YpnJjv/uT2lwrWG5EEQiS04Oo22n3gojb0cRIEIqBMkODrSkQPBB5JJXEV3F3ZU500oQgi3EIEz3AU4hCJIImTcTpeyCslf2RaiKzenBT0nf8C "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZBRb4MgFIXf/RWMkBRa284@lhFfZpcmS7u4vs2NgMFqgtagfVr2290F97REuId7z/lE@7qfntK@7hFxSCC8xWiDemeu0pneqtLQxXazTKWslR1leWv7xhpX0ILxIt8OixgtYFXQlFfjDd1ounGgUh6Or5mULEYJAySAeVTdHCWNeOTEigrsA32/PB9PjLNv1FSU2I9hdNZ0oNg6@RQCFx1mYB7uGibQjh/jdcJ4cDfMlPXNWzgCasIjhEgrwuVbNZY1JS4GEkfeN3@UVcMojXNwEfYg3vLsRZ7OMsvzc57izPf3CO8paVN8cXezR3DCB2UHkJj5NwQWJhbzn38/hTI@fVFFU6GWtNilK80YWxU7Mk1KR0ppv8Eeiq@zCOpPzlpHkYp8J9LwhJGPRwqOnqLDBGoYz9GA9i5vUWHzgTkRIj7jQ96iAyZwZtBM0r8 "PHP – Try It Online") - PCRE2
**[Try it online!](https://tio.run/##bZHfb9MwEMff81fcIqTZLWRjj4usSkjsCRCivFEm2YnTukucYDtrUZW/vdzZAW2oUmTfr@/nfJe9fJbv9vXT2XRD7wLs0S9MXyxKeBkZg2kvxpze6iNlhlG1poKqld7DZ2ksnOaQDzLg9dybGjpMsHVwxm5Buq3/8ZND2Ln@4OHjsdJDMD0KM4AH02pohNWHaLK8qPpaF5jPeflhbBrtdP1Ny1o7ULHsdZD9Vc5uw3k59/VvQ3nYEZ8xLxSOIOtPxmrG@ZWwY9ty0zBf6F@jbD3LbxaLRc756XVpIjAWLgJOSAj/CAi4QYLCuqfSL8X1xl7THcopxaavMgTtLDgxWzhtN1ADz0vcxrqS1uKkxg5jAAE03Bxj698@6K4wluPvsQGMuC1hni/WFzvpv@hjwOfBCfBl5krc8lnWY37AtYTWMgKI99QPO6ZdtdgsQSwS5tHx94Zqh8/pMOuKLnmsxcz/1IZ1RWNszTisIP/uRn0PkMM95A@4GnTyCyIiTdOU0ebPj0yylZALtrlbLRXnfLm5e3OmlZ6lyqRUdOAZL7qTEa3ZTLbKMplRJFP4xRTJM4kuUVTM4B3TSRrRVEUlMh4kSIooIQ2JqERFTOQkUCKpPw "Java (JDK) – Try It Online") - Java**
Turned out to be used in [Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/86061/17216), but gave it a -6 byte golf.
This regex is the next-best thing to recursion, in engines that lack it. It works using group-building:
```
^ # Assert we're at the beginning of the string.
(
a # Match one more 'a' per each iteration of this loop.
# Lookahead assertion - when this finishes, the regex engine's "cursor"
# will jump back to the same position as it was in when it entered the
# lookahead here. It's atomic, so the regex engine can't backtrack into
# the lookahead once it has completed its match or non-match. This means
# the main loop will exit immediately if this lookahead fails to match
# (due to running out of 'b' characters to match), or if the 'a' above
# fails to match.
(?=
a* # Skip over as many 'a' as necessary to get to the first 'b'.
# Capture \2, embedding within it the previous contents of itself.
# If this is the first iteration, \2 will be unset, so capture a
# single 'b' in \2. Otherwise, append one more 'b' to the previous
# contents of \2.
(
\2?+ # Optionally match \2, but if it does match, lock that
# match in (don't backtrack to here and try not making the
# match, in the case that a non-match occurs after this
# point). This is guaranteed to fail to match if and only if
# we're on the first iteration, due to \2 being unset. On
# subsequent iterations, since \2 will have been captured
# starting at the first non-'a' character, and always starts
# its attempted match there, it will be guaranteed to match.
b # Match one 'b'.
)
)
)+
\2 # Match however many 'b' we captured in \2.
$ # Assert we're at the end of the string.
```
# Regex (.NET), 22 bytes
```
^(a)+(?<-1>b)+$(?(1)^)
```
[Try it online!](https://tio.run/##RY3BasMwEETv@gphBJJIXOqr3TSBQG@99VYaWKXrWqDKRnZwifG3u1qpUDA7s955o6GfMYwdOreJcHgP@IU/H3XtcVYnuV0U6J06PpXVs9E7oY6q0he9ydO@OPffg3X4WehG3A@PTdsHhGunhOPWc2H9cJv0Ylsl7nqZg52w7PpxWmO4av53Xvo@PuasR14IZVuuRHh4hena4RjLtOaLfAs3rLlcOboR4/4CUWu5ai5csW5gGIChEWcS0myS@7PZG8aA0R9m4pdOhDOIK7WYdImazhlN1ZSiCKRBQCYSQgxBFDGpJvXkotxkfgE "PowerShell – Try It Online")
Included for completeness. Already used in:
* [Leaky Nun's Retina answer](https://codegolf.stackexchange.com/a/86002/17216)
* [AdmBorkBork's PowerShell answer](https://codegolf.stackexchange.com/a/86011/17216)
* [Dion Williams's C# answer](https://codegolf.stackexchange.com/a/86300/17216) (with regex 7 bytes longer than it needs to be)
This regex uses the Balancing Groups feature of the .NET regex engine:
```
^ # Assert we're at the beginning of the string.
(a)+ # Match as many 'a' characters as we can, minimum of one, pushing
# each single-character capture onto the Group 1 capture stack.
(?<-1>b)+ # Pop the Group 1 capture stack as many times as we can, matching
# a single 'b' each time. This will stop looping when it hits a
# character other than 'b', or empties the Group 1 capture stack.
$ # Assert we're at the end of the string. If this fails to match
# (meaning there are more 'b' characters than 'a' characters), the
# regex engine will backtrack, but none of the choices it has will
# be able lead to a match, so there will be a top-level non-match.
(?(1)^) # If there are any remaining captures on the Group 1 stack (which
# means there were fewer 'b' characters than 'a' chracters), assert
# something which can never be true - that we're at the beginning
# of the string. Since the first thing the regex did was capture at
# least one 'a', the fact that we've reached this point means that
# was already done, so it's impossible for us to be at the beginning
# of the string. Thus this causes a non-match in the case that there
# are fewer 'b' than 'a'.
```
Some people use this regex in the form of `^(a)+(?<-1>b)+(?(1)^)$`, i.e. with the `$` at the end rather than the beginning, but I prefer `^(a)+(?<-1>b)+$(?(1)^)`, since it tries the slightly-less-complicated operation of `$` first, so in the case of a non-match, it will be ever so slightly more efficient. In theory.
The `^` in the `(?(1)^)` can be replaced with various other things that can't match, such as `(?(1).)` or `(?(1)c)`.
# Regex (Perl / PCRE / Java / .NET), 24 bytes
```
^(a(?=a*((?>\2?)b)))+\2$
```
[Try it online!](https://tio.run/##TYzNasMwEITveoolCKxtExwHcrFim0DaY085mgqpOGBQ8yMnh2LcV3d3pUILYne0M99cu@C38@cXyKBh9JcP60Hmmr7V7rA/7utJnC5Byb5a612taRc4Qn@iC47X0J/vsGjPCz2B9FDB8HDDneJmuSqWBXY3NqH5d1@Tg1CCNFoApAalGP6GXIYcm@wYHl0JkJXZq/UDyQz/stJrmIx5eTsYM78rq5rKPinV1O2mQYeIz@1GzrN1wlrHg2ZcvJOI6lcm7YSwgi/C0YsW48LSl1tcdGhHO6GxmlMcsXEwkIiIMMMQR1ysiT2pKDW5Hw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9Fl7OJ8dnbBE8758ezs7Ya/xnZC6OpxrI/7UfCvT23neUWN9lMmL7OXubzCrBLL8yAvLWgE2FgZUxkmq7K24MbsLlVdi0zxZ1QdDiUCYDSCNkuhy6tyXkRglG1MCf1o7SSXIi8Zh@cA8NH32K1QJdP8pP8w7kXQIGZwFluo6ESEDAMHdpp@ZizoxkZA5kHXqAj2p8NxtDWebVTdFNbHdI80rZUNoWosts3swleqX0raytwPHnwrVB078VhWS50XiukQeiG889I@2Gr1uCflKbADo/j2xqlzL2U4N6JD6Hy5nFy5IQwI7OnocDgfwmE9K/Gr7Wn6Pq1wigRGYz6RJ86GTNkiLxXz/udl6B3hEWL6W3e3Qz1xwBp5w45m5VGr6u9J7mzvqn4ryYwK4fbrzU2reCpjtJzx7bHOnxSdeu5tfQthsCdKLVvhEZqzN8yr6sEYyJL4ajK5m8S3d58/TC8/cWht61yRU0Po4KVUUatd/lrgyeV3wuuXiKlpEPACka5MbhX77536IZlbkY2Ot/buG6VwYr77k9tfKlhvRBIIkdCCq9to94GL2tDHSRCIgDJBgq8rET0QeCSVxFVwd2VPddKEIohwCxE8w1GIQySCJE7G6Xghr5T8kWkhsnpzUtB3/gs "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZBfb4MgFMXf@RSMkBQ6@8c@ljlfZpcmS7e4vs2NgMFqgtagfVr22d0F97REuId7z/mJ9nU/PaR93WPqcILJhuA17p25SGd6q0rDFpv1MpWyVnaU5bXtG2tcwQouinwzLCK8gFVBU16MN3Sj6caBSXk4vmRS8gjHHJAAFqi6OkabZCuoTSqwD@z9/HQ8ccG/cVMxaj@G0VnTgeKr@DNJSNERDubhpmEC7WgbrWIugrvhpqyv3iIwUGOBMKZtEi7fqrGsGXURkAT2vvmjrBpGaZyDi/C75C3PnuXpVWZ5/pqnJPP9PSZ7RtuUnN3N7DGcyEHZASTh/g2BRagl4uffT2FcTF9MsTRRS8bSx2KXcs05vy92dJqURkppv8Eeiq@zCOpPzlojpJDvIA1PGPk4UnD0FB0mUMN4jga0d3mLCpsPzIkQ8Rkf8hYdMIEzg2aS/gU "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bZHfb9MwEMff81fcIqTZHWRjj4tMJST2BAhR3uiQ7MRp3SVOsJ21qMrf3t3ZYWKoUmTfr@/nfJedfJLvdvXjyXRD7wLs0C9MXyxK@DcyBtOejTm90QfKDKNqTQVVK72HL9JYOM4hH2TA66k3NXSYYKvgjN2AdBv/84FD2Lp@7@HTodJDMD0KM4B702pohNX7aLK8qPpaF5jPeflxbBrtdP1dy1o7ULHsdZD9Vc5uw3k59/VvQ7nfEp8xLxSOIOvPxmrG@YWwY9ty0zBf6N@jbD3LrxeLRc758XVpIjAWzgKOSAgvBARcI0Fh3WPpr8Tl2l7SHcopxaZvMgTtLDgxWzhtN1ADz0vcxqqS1uKkxg5jAAE03Bxjqz8@6K4wluPvsQGMuClhni/WF1vpv@pDwOfBEfBl5kLc8FnWY37AtYTWMgKI99QPO6ZdtdgsQSwS5tHx94Zqi8/pMOuKLnmsxcz/1IZ1RWNszTgsIf/hRn0HkMMd5Pe4GnTyMyIiTdOU0eZPv5hkSyEXjC0/rG@XXHHOr9a3b0601ZNUmZSKDjzjRXcyojWbyVZZJjOKZAq/mCJ5JtEliooZvGM6SSOaqqhExoMESRElpCERlaiIiZwESiT1DA "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RY1BS8QwEIXv@RWhBJqoK7rHltoFwZs3b67CZHdqAzEpaZfKlv72mkkEocx703nfy@BnDGOP1m4iNO8Bv/Dno6oczvJQbp8SZNvAjZTt03HfKq2Uuj3uxVYe7opn/z0Yi@dC1eLaPNSdDwinXgrLjePCuOEyqcV0UlzVMgcz4a7347TG8GP9v/Od8/E5axzyQkjTcSnC/StMpx7HWKYUX8q3cMGKlytHO2LcXyBqVa6KC1usG2gGoGnEmYQ0m@T@bPaaMWD0h@n4pRPhDOJKLTpdoqZzRlM1pSgCaRCQiYQQQxBFdKpJPbkoN@lf "PowerShell – Try It Online") - .NET
This is a port of the **21 byte** Perl/PCRE/**Java** regex, with `\3?+` changed to `(?>\3?)` to allow the regex to also work on .NET (which lacks possessive quantifiers).
# Regex (Perl / PCRE / Java / Ruby / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 29 bytes
```
^(a(?=a*(?=(\3?+b))(\2)))+\2$
```
[Try it online!](https://tio.run/##TUzLasMwELzrK5YgsLZJcJzQixXHBNIee8rRVEjFAYOah5wcinF/3d2VCi2ImdHO49oG/zx9foEMGgZ/@bAeZK7pW20P@@N@N4rTJSjZVSu93WniAgfoTnTB4Rq68x1mzXmmR5AeKugfrr9T3CyWxaLA9sYm1P/uK3IQSpBGC4C0oBSXvyGXIcc6O4ZHWwJkZfZqfU8yw7@s9BpGY17eDsZM78qqurJPBKrZ1HOHqJo1Is6btZwm64S1joEwEnMSUf3KpJ0QVvBFOHrR4rqw9OUVFx3iaKdqnOYUR2wELqRGrHCHSxxxcSbupKG05H4A "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9HFhc0GF8cJ52x2xjk/np293fDXhE4IXT2O9XE/Cv41q@08r6jbfsrkZfYyl1eYVWJ5HuSlBY0AGytjKsNkVdYW3KzdpaprkSn@jKrDoUQAjEbQZil0eVXOiwiMso0poR@tneRS5CXj8BwAPvoeuxWqZJqf9B/GvQgaxAzOYgsVnYiQYeDATtPPjAXd2AjIQegaFcH@dDiOtsazjaqbwvqY7pGmtbIhVI3Ftpld@Er1S0lbmfvBg2@FqmMnHstqqfNCMR1CL4R3XtoHW60e96Q8BXZgFN/eOHXupQznRnQInS@Xkys3hAGBPR0dDudDOKxnJX61PU3fpxVOkcBozCfyxNmQKVvkpWLe/7wMvSM8Qkx/6@52qCcOWCNv2NGsPGpV/T3Jne1d1W8lmVEh3H69uWkVT2WMljO@Pdb5k6JTz72tbyEM9kSpZSs8QnP2hnlVPRgDWRJfTSZ3k/j27vOH6eUnDq1tnStyaggdvJQqarXLXws8ufxOeP0SMTUNAl4g0pXJrWL/vVM/JHMrstHx1t59oxROzHd/cvtLBeuNSAIhElpwdRvtPnBRG/o4CQIRUCZI8HUlogcCj6SSuAruruypTppQBBFuIYJnOApxiESQxMk4HS/klZI/Mi1EVm9OCvrOfwE "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNbsIwEITveQrXsoQXwk/oDdfKpVAhVVCl3JrWsiNDkByInHCq@ux07fRUKV6Pd2e@OGnr9v6Ut3VLmCeS0DklM9J6e1Letk5Xlo/ms3GuVK1dr6pr056d9SUvQZTFvBulZITriE11ssFw6e2l77hSm@3rWilISQaIRLBIjlfP2VkuBHPyiPaOvx@etzsQ8E3OR87cR9d7Zy@oYJp9SknLCwU0dzeDE2yni3SagYjuM9iqvgaLIEjNREIIa2S8fKP7qubMp0gSJPiGj3K665X1Hi8CD/KtWL@o3V6ti2Jf5HQd@itCV5w1OT34m10RPNGNdh1KCuENkUWZo@Ln30/hIO5fXPNc6jEWXj7mEwPAyyUATMolu9@1SbQ2oWCNW9gHEdWfHLRJEp2ETmLwiaMQTzQeA8XECe5xPEQjOriCRccSAkMiRkImhILFREzkDKCBZH4B "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bVHfb9MwEH7PX3GLkGankI3xtsiqhMSeACHKGwXJTpzWXeIE21mLqv7t3Z0dEEOVovv13fed77KTT/LNrnk8m34cXIAd5qUZyqKCfytTMN3FmtMbfSBknFRnaqg76T18ksbCcS75IAO6p8E00CPAVsEZuwHpNv77Dw5h64a9hw@HWo/BDEjMAB5Mp6EVVu9jyPKyHhpdIp7z6v3Uttrp5quWjXagYtvLIvvDnNOW82qe61@Har8lfca8ULiCbD4aqxnnV8JOXcdNy3ypf02y8yy/KYoi5/z4sjUpMBYuChxRIfxVQIEbVFDY91j5hbhe22vyoTql2umLDEE7C07MEW7bjzTA8wqvsaqltbipseMUQAAtN9fY6rcPui@N5fh7bAAjbiuY94v95Vb6z/oQ8HlwBHyZuRK3fKYNiI94ltBZRgLiLc3DielWHQ5LIhYV5tXx94Z6i8/pEXVlnzLWIfK/asv6sjW2YRyWkH9zk74HyOEe8gc8DSb5BRIpnU6njC5//skkWwpZoGHrd8uF4pyt7zjni/XdqzOd9ixVJqUigzY68imI0RymWGWZzKiSKfwiRPRMYkoqKiLoI5yoUZq6qEVGQ4TEiBTiEIlaVJSJOkkoKaln "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RYzBasMwEETv@oqtyMFqiEncW4QwgSTHHkpucWpWVE0FwhjZJumlv@5oV4GCmJ3Vzps42d85goEPd3X3vuzcDfa7066MDr80eLPWcPvxwUEwVzcOAsB/g3@h/34aBw2u49xG0yGcV5uLMbLppE5EOK/LclVdOJXQPvpuhADmDyLUIE9xclsACVuQRwxDWuR/LFNte3jft@38WWBRG3xNUjRv9dIqVTSVUmrZVIt5RisQLUlSHjSzYfe02VshUNCPsOnxiXCBaaUWy5c0@ZxRrqYURZCFgEwwQgxBFLFcwz25KDfZBw "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##bY5NagMxDIX3PoUwhdhNOuRn52Ky6wm6m2lBbpzE4HoGj0Ob008tOcuCkZ6k9z483ct1TIclfE9jLjDf5032F/8rMljIUsrlU6E6WnyuRQ2H49pprYa91no97J@W6uh35mX38QrBbsV5zBAhJAJ1czmFZARAOEMwMOWQitI0213bRp9U1IDpBLGvEGtXQ1oZiDb2W6JW24M03kr3k0PxSr7nmzcAkgj82W72mL@uKm@g0nycPcg3rM2A1P8hol7QCURHpVZu1Jtg9ZBNOyFQ0Ea4@vhEcYF1JIrjS@18blFGk4ssyIUCLcERylCILI4xzGmgRnJ/ "Python 3 – Try It Online") - Python `import regex`
This is a port of the **21 byte** Perl/PCRE/**Java** regex (see below) adding compatibility with engines that lack nested backreferences, but still have forward-declared backreferences and possessive quantifiers. This allows it to work in Python when using the `regex` library instead of `re`.
```
^ # Assert we're at the beginning of the string.
(
a # Match one 'a' per iteration of this loop.
(?=
a* # Skip over as many 'a' as necessary to get to the first 'b'.
(?=
# Capture \2. If this is the first iteration, \3 will be unset, so
# capture a single 'b' in \2. Otherwise, \2 = \3 concatenated with
# one more 'b'.
(
\3?+
b
)
)
# \3 = make a copy of \2, which was captured above
(
\2
)
)
)+
\2 # Match however many 'b' we captured in \2.
$ # Assert we're at the end of the string.
```
# Regex (Perl / PCRE / Java / Ruby / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / .NET), 32 bytes
```
^(a(?=a*(?=((?>\3?)b))(\2)))+\2$
```
[Try it online!](https://tio.run/##TUzLasMwELzrK5YgsLZJcZzSixXbBNIee8rRVEjFAYPyqJwcinF/3d2VCi2ImdHO49oF/zyfvkAGDaO/fFgPMtf0rbb73WFXT@J4CUr21Vpva01c4Aj9kS44XkN/vsGiPS/0BNJDBcPdDTeKm9VjsSqw@2QTmn/3NTkIJUijBUBaUIrL35DLkGOTHcK9KwGyMnu1fiCZ4V9Weg2TMS9ve2Pmd2VVU9kHAqWaun1q0CGqdoOIy3Yj59k6Ya1jIIzEnERUvzJpJ4QVfBGOXrS4Lix9ecVFhzjaqRqnOcURG4ELqREr3OESR1yciTtpKC25Hw "Perl 5 – Try It Online") - Perl
[Try it online!](https://tio.run/##fVJRT9swEH7Przi6MewSUEulPTQtaEOgPTCYqk7aRFnkuE4aLU0sx1kHqH993Z2ddoWHRZF9vvu@785fIrU@yaTcvMlLWTRzBSMtjTpdnAdyIQzE@v4BxjDpfFytfiaD5vvj47fp4v1qwTY/mGAXY9HFhbGL89nggiecs9kZ5/x4dvZ2w19zOiF09TjWx/0o@NevtvO8oob7KZOX2ctcXmFWieV5kJcWNAJsrIypDJNVWVtw43aXqq5Fpvgzqg6HEgEwGkGbpdDlVTkvIjDKNqaEfrR2kkuRl4zDcwD46HvsVqiSaX7Sfxj3ImgQMziLLVR0IkKGgQM7TT8zFnRjIyAToWtUBPvT4TjaGs82qm4K62O6R5rWyoZQNRbbZnbhK9UvJW1l7gcPvhWqjp14LKulzgvFdAi9EN55aR9stXrck/IU2IFRfHvj1LmXMpwb0SF0vlxOrtwQBgT2dHQ4nA/hsJ6V@NX2NH2fVjhFAqMxn8gTZ0OmbJGXinn/8zL0jvAIMf2tu9uhnjhgjbxhR7PyqFX19yR3tndVv5VkRoVw@/XmplU8lTFazvj2WOdPik4997a@hTDYE6WWrfAIzdkb5lX1YAxkSXw1mdxN4tu7zx@ml584tLZ1rsipIXTwUqqo1S5/LfDk8jvh9UvE1DQIeIFIVya3iv33Tv2QzK3IRsdbe/eNUjgx3/3J7S8VrDciCYRIaMHVbbT7wEVt6OMkCERAmSDB15WIHgg8kkriKri7sqc6aUIRRLiFCJ7hKMQhEkESJ@N0vJBXSv7ItBBZvTkp6Dv/BQ "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##XZDNbsMgEITvPAVFSGFT57e3UNeXOlWkKqnc3OoWgUXiSDixsHOq@uzpgnuqZJZhd@Yzdlu3t8esrVvKPU0pmzE6pa23R@Vt63RlxWg2HWdK1dr1qro07clZX4oSZFnMulFCR7gO2FRHGwzn3p77Tii13rzmSkFCF4BIBEtyuHjBT@lccpce0N6J9/3zZgsSvunpILj76Hrv7BkVTBafacrKMwM0d1eDE2wn82SyABndJ7BVfQkWSZG6kIRS3qTx8o3uq1pwnyBJ0uAbPsrprlfWe7wI3KVvRf6itjuVF8WuyFge@ivKVoI3Gdv7q11RPLG1dh1KBuENkcW4Y/Ln308RIG9fQoss1WMsQmRP5UMGBkCUSwC4L5f8dtOGaG1CwRq3sA8iqj85aEOIJqFDDD5xFOJE4zFQTJzgHsdDNKKDK1h0LCEwJGIkZEIoWEzERM4AGkjmFw "PHP – Try It Online") - PCRE2
[Try it online!](https://tio.run/##bVHfb9MwEH7PX3GLkGZ3kI3tbVGohMSeACHKG2WSnTitO8cJtrMWVfnby50dEEOVovv13fed77ITz@LNrnk66W7oXYAd5oXui0UJ/1bGoM3ZmlMbdSBkGKXRNdRGeA@fhLZwnEs@iIDuudcNdAiwVXDabkC4jf/@g0PYun7v4cOhVkPQPRIzgAdtFLSVVfsYsryo@0YViOe8fD@2rXKq@apEoxzI2PayyP4w57TlvJzn@teh3G9JnzFfSVxBNB@1VYzzi8qOxnDdMl@on6MwnuXXi8Ui5/z4sjUpMBbOChxRIfxVQIFrVJDY91T6q@pybS/Jh3JKtemLCEE5C66aI9y2G2iA5yVeY1ULa3FTbYcxQAW03Fxjq18@qK7QluPvsQF0dVPCvF/sL7bCf1aHgM@DI@DL9EV1w2daj/iAZwnGMhKo3tI8nJhuZXBYErGoMK@OvzfUW3xOh6grupQxg8j/qi3rilbbhnFYQv7NjeoeIId7yB/wNJjkZ0ikNE1TRpc/PTLBlpVYoGFs@W59t@SSc7a@5ZxfrW9fnei6JyEzISQZtNGRT0GM5jDFMstERpVM4hchomcCU1KREUEf4USN0tRFLSIaIiRGpBCHSNQio0zUSUJJSf4G "Java (JDK) – Try It Online") - Java
[Try it online!](https://tio.run/##RYzBasMwEETv@oqt6EFqiEncW4RiAmmPPZTc4tSsqJoKhDGyTdpLf93VrgoFMTurnTdpdt9LAguv/uq/hqr3NzgeTocqeXw3EOzGwO0zRA/RXv00CoDwAeGO/od5Gg34nnNbQ4d4Xm8v1sq2lyYT8bypqnV94VRGhxT6CSLYH0jQgDyl2e8AJOxAPmMc8yL/Y4XquqeXY9ctbwpVY/Ehi1LNvn1stNNatbXWetXW98uCTiA6kqw8aBbD7s8W74RAQT/C5ccnwgXmlVocX/Lkc0G5mlIUQRYCCsEIMQRRxHEN95Si0uR@AQ "Ruby – Try It Online") - Ruby
[Try it online!](https://tio.run/##bY7BbsMgDIbvPIWFJhW2LmraGxPLbU@wW7JJsNIWiZEIqLY@fYZNj5OQ/dv@/08st3KZ42H138ucCuRb3iZ3dr8sgYbEOV8/hRGDNo@1CDG8TodBWinFtJdSPk37h7Waxl499x8v4PWOneYEAXxEVpfL0UfFAPwJvIIl@ViExFn3bRtcFEGCiUcIY4VovZniRkHQYdwhtdrupPlaup/kixP8PV2dAuBIoP922Zn0dRFpC5XmQnbA30xtCrj8DxHkaiwzxmKplRr2JkjdZdOWMcNww2x9dMI4M3VEiqVL7XRuUUKjCy2GCgZagiKYwRBaLGGI00CNZP8A "Python 3 – Try It Online") - Python `import regex`
[Try it online!](https://tio.run/##RU3RSsQwEHzPV4QSaFY90fOtpfZA8M033zyFzbm1gdiWtEflSr@9ZhNBCDOz2ZnZoZ/Jjy05tylfvXn6op/3ouho1od8@9Co6wqvAmhdPx4fajAA@rgHgOvjXm354SZ76r8H6@gzg1Jdqruy6T3hqdXKSdtJZbvhPMFiG60usMzeTrRr@3Fag/m@/J/lruvDWWc7kpnStpFa@dsXnE4tjaEMQC75qz9TIfNVkhspzM8YuMhXkMpl64ZGIBqGgJGYk4jqTyZthEDBP8KEF1ccFxhGbjFxEziuUzRWs4stGIEDKREjnOEQW0ysiT2pKDWZXw "PowerShell – Try It Online") - .NET
This is a port of the above, with `\3?+` changed to `(?>\3?)` to allow the regex to work on .NET (which lacks possessive quantifiers), so it can support 6 different regex engines at once.
It is not supported by Boost, which lacks both forward-declared and nested backreferences. It might not be possible for a single regex to work on all 7 engines.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 22 bytes
Another shorter answer in the same language just came...
```
^(a)+(?<-1>b)+(?(1)c)$
```
[Try it online!](http://retina.tryitonline.net/#code=XihhKSsoPzwtMT5iKSsoPygxKWMpJA&input=YWFiYg)
This is a showcase of the balancing groups in regex, which is [explained fully by Martin Ender](https://stackoverflow.com/a/17004406/6211883).
As my explanation would not come close to half of it, I'll just link to it and not attempt to explain, as that would be detrimental to the glory of his explanation.
[Answer]
# Befunge-93, 67 bytes
```
0v@.< 0<@.!-$< >0\v
+>~:0`!#^_:"a" -#^_$ 1
~+1_^#!-"b" _ ^#`0: <
```
[Try it here!](http://www.quirkster.com/iano/js/befunge.html) Might explain how it works later. Might also try to golf it just a tad bit more, just for kicks.
[Answer]
## Mathematica, 45 bytes
```
#~StringMatchQ~RegularExpression@"(a(?1)?b)"&
```
Another recursive regex solution. This doesn't need anchors because `StringMatchQ` achors it implicitly, but unfortunately it just seems to do wrap the regex in `^(?:...)$` which means we can't use `(?R)` for the recursion, as that gets the anchors as well. Hence the seemingly useless group around the entire regex, so we can access only that part for the recursion.
[Answer]
# C, 69 bytes
69 bytes:
`#define f(s)strlen(s)==2*strcspn(s,"b")&strrchr(s,97)+1==strchr(s,98)`
For those unfamiliar:
* `strlen` determines the length of the string
* `strcspn` returns the first index in string where the other string is found
* `strchr` returns a pointer to the first occurrence of a character
* `strrchr` returns a pointer to the last occurrence of a character
A big thanks to Titus!
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 3 bytes
```
N;<
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fov9rG2WFCclF0P5C26-U0pMUuJSSkxMglBAGsoAsWBMMBvOgfBAXJAIEENkQAwwAVUIMRZEgoUhNiRB1YHZUOUwg6EOgOiDaEmEUhBjYOZADYKYBDEKoiEJagnUFpg1MHuSlCDeBgA)
```
N;<
N Check nonempty
; Split the list into two parts
< Check elementwise less than; fails if their lengths are different
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
vHI$e!d1=
```
[**Try it online!**](http://matl.tryitonline.net/#code=dkhJJGUhZDE9&input=J2FhYWJiYic)
The output array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are [some examples](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICUgaW5maW5pdGUgbG9vcCB0byB0YWtlIGFsbCBpbnB1dHMKPyd0cnV0aHknICAgICUgaWY6IHRydXRoeQp9J2ZhbHN5JyAgICAgJSBlbHNlOiBmYWxzeQpdICAgICAgICAgICAgJSBlbmQgaWYKRFQgICAgICAgICAgICUgZGlzcGxheSBhbmQgZW5kIGxvb3A&input=W10KWzAgMSAyXQpbMyA0IC01XQpbMSAxOyAxIDFd).
```
v % concatenate the stack. Since it's empty, pushes the empty array, []
H % push 2
I$ % specify three inputs for next function
e % reshape(input, [], 2): this takes the input implicitly and reshapes it in 2
% columns in column major order. If the input has odd length a zero is padded at
% the end. For input 'aaabbb' this gives the 2D char array ['ab;'ab';'ab']
! % transpose. This gives ['aaa;'bbb']
d % difference along each column
1= % test if all elements are 1. If so, that means the first tow contains 'a' and
% the second 'b'. Implicitly display
```
[Answer]
# x86 machine code, 29 27 bytes
Hexdump:
```
33 c0 40 41 80 79 ff 61 74 f8 48 41 80 79 fe 62
74 f8 0a 41 fe f7 d8 1b c0 40 c3
```
Assembly code:
```
xor eax, eax;
loop1:
inc eax;
inc ecx;
cmp byte ptr [ecx-1], 'a';
je loop1;
loop2:
dec eax;
inc ecx;
cmp byte ptr [ecx-2], 'b';
je loop2;
or al, [ecx-2];
neg eax;
sbb eax, eax;
inc eax;
done:
ret;
```
Iterates over the `a` bytes in the beginning, then over the following 'b' bytes. The first loop increases a counter, and the second loop decreases it. Afterwards, does a bitwise OR between the following conditions:
1. If the counter is not 0 at the end, the string doesn't match
2. If the byte that follows the sequence of `b`s is not 0, the string also doesn't match
Then, it has to "invert" the truth value in `eax` - set it to 0 if it was not 0, and vice versa. It turns out that the shortest code to do that is the following 5-byte code, which I stole from the output of my C++ compiler for `result = (result == 0)`:
```
neg eax; // negate eax; set C flag to 1 if it was nonzero
sbb eax, eax; // subtract eax and the C flag from eax
inc eax; // increase eax
```
[Answer]
# Ruby, 24 bytes
```
eval(gets.tr'ab','[]')*1
```
(This is just [xnor's brilliant idea](https://codegolf.stackexchange.com/a/86032/4372) in Ruby form. [My other answer](https://codegolf.stackexchange.com/a/86184/4372) is a solution I actually came up with myself.)
The program takes the input, transforms `a` and `b` to `[` and `]` respectively, and evaluates it.
Valid input will form a nested array, and nothing happens. An unbalanced expression will make the program crash. In Ruby empty input is evaluated as `nil`, which will crash because `nil` has not defined a `*` method.
[Answer]
# Sed, 38 + 2 = 40 bytes
```
s/.*/c&d/;:x;s/ca(.*)bd/c\1d/;tx;/cd/p
```
A non empty string output is truthy
Finite state automata can not do this, you say? What about finite state automata with *loops*. :P
Run with `r` and `n` flags.
### Explanation
```
s/.*/c&d/ #Wrap the input in 'c' and 'd' (used as markers)
:x #Define a label named 'x'
s/ca(.*)bd/c\1d/ #Deletes 'a's preceded by 'c's and equivalently for 'b's and 'd's. This shifts the markers to the center
tx #If the previous substitution was made, jump to label x
/cd/p #If the markers are next to one another, print the string
```
[Answer]
# JavaScript, ~~44~~ 42
[Crossed out 44 is still regular 44 ;(](http://meta.codegolf.stackexchange.com/a/7427/7796)
```
f=s=>(z=s.match`^a(.+)b$`)?f(z[1]):s=="ab"
```
Works by recursively stripping off the outer `a` and `b` and recursively using the inner value selected but `.+`. When there's no match on `^a.+b$` left, then the final result is whether the remaining string is the exact value `ab`.
**Test cases:**
```
console.log(["ab","aabb","aaabbb","aaaabbbb","aaaaabbbbb","aaaaaabbbbbb"].every(f) == true)
console.log(["","a","b","aa","ba","bb","aaa","aab","aba","abb","baa","bab","bba","bbb","aaaa","aaab","aaba","abaa","abab","abba","abbb","baaa","baab","baba","babb","bbaa","bbab","bbba","bbbb"].some(f) == false)
```
[Answer]
# ANTLR, 31 bytes
```
grammar A;r:'ab'|'a'r'b'|r'\n';
```
Uses the same concept as @dmckee's [YACC answer](https://codegolf.stackexchange.com/a/86049/56755), just slightly more golfed.
To test, follow the steps in ANTLR's [Getting Started tutorial](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md). Then, put the above code into a file named `A.g4` and run these commands:
```
$ antlr A.g4
$ javac A*.java
```
Then test by giving input on STDIN to `grun A r` like so:
```
$ echo "aaabbb" | grun A r
```
If the input is valid, nothing will be output; if it is invalid, `grun` will give an error (either `token recognition error`, `extraneous input`, `mismatched input`, or `no viable alternative`).
Example usage:
```
$ echo "aabb" | grun A r
$ echo "abbb" | grun A r
line 1:2 mismatched input 'b' expecting {<EOF>, '
'}
```
[Answer]
## R, ~~64~~ ~~61~~ 55 bytes, ~~73~~ 67 bytes (robust) or 46 bytes (if empty strings are allowed)
1. Again, [xnor's answer](https://codegolf.stackexchange.com/a/86032/49439) reworked. If it is implied by the rules that the input will consist of a string of `a`s and `b`s, it should work: returns NULL if the expression is valid, throws and error or nothing otherwise.
```
if((y<-scan(,''))>'')eval(parse(t=chartr('ab','{}',y)))
```
2. If the input is not robust and may contain some garbage, e.g. `aa3bb`, then the following version should be considered (must return `TRUE` for true test cases, not NULL):
```
if(length(y<-scan(,'')))is.null(eval(parse(t=chartr("ab","{}",y))))
```
3. Finally, if empty strings are allowed, we can ignore the condition for non-empty input:
```
eval(parse(text=chartr("ab","{}",scan(,''))))
```
Again, NULL if success, anything else otherwise.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 bytes
```
©¬n eȦUg~Y
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=qaxuIGXIplVnflk=&input=LW1SIFsKImFiIiwKImFhYmIiLAoiYWFhYmJiIiwKImFhYWFiYmJiIiwKImFhYWFhYmJiYmIiLAoiYWFhYWFhYmJiYmJiIiwKCiIiLAoiYSIsCiJiIiwKImFhIiwKImJhIiwKImJiIiwKImFhYSIsCiJhYWIiLAoiYWJhIiwKImFiYiIsCiJiYWEiLAoiYmFiIiwKImJiYSIsCiJiYmIiLAoiYWFhYSIsCiJhYWFiIiwKImFhYmEiLAoiYWJhYSIsCiJhYmFiIiwKImFiYmEiLAoiYWJiYiIsCiJiYWFhIiwKImJhYWIiLAoiYmFiYSIsCiJiYWJiIiwKImJiYWEiLAoiYmJhYiIsCiJiYmJhIiwKImJiYmIiLApd)
Gives either `true` or `false`, except that `""` gives `""` which is falsy in JS.
### Unpacked & How it works
```
U&&Uq n eXYZ{X!=Ug~Y
U&& The input string is not empty, and...
Uq n Convert to array of chars and sort
eXYZ{ Does every element satisfy...?
X!= The sorted char does not equal...
Ug~Y the char at the same position on the original string reversed
```
Adopted from [Dennis' MATL solution](https://codegolf.stackexchange.com/a/86037/78410).
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~34~~ 33 bytes
```
-[].
-L:-append([97|M],`b`,L),-M.
```
[Try it online!](https://tio.run/##ZZDBCsMgEETv@YoeFdxcS9NDfyCB3ENApbYEJBGT4qX/bpuWgju9OW9dZ8YQF7/caU1TzjSMdUVtQyYEN1/FcDo@u1Fpq1UrFXV1TqKXDfUqxWlzfhZbfDh5/qmb8auTdXWhQxKkjdWFMJbLtwawE0Qf9ge/tMTljeLMN8sBE2DAY5eKrfFGFt5nM7DDQvAx3J9bGpA8HuaDgDwhj8iNLJSDdlgP@@3T/AI "Prolog (SWI) – Try It Online")
[Answer]
# [Brachylog (newer)](https://github.com/JCumin/Brachylog), ~~11~~ ~~10~~ 6 bytes
```
o?ḅĊlᵛ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8z7d/uKP1SFfOw62z//@PVkpMUtJRSkxMglBAGsoAsWBMMBvOgfBAXJAIEENkQAwwAVUIMRZEgoUhNiRB1YHZUOUwg6EOgOiDaEmEUhBjYOZADYKYBDEKoiEJagnUFpg1MHuSlGIB "Brachylog – Try It Online")
The predicate succeeds if the input is in L and fails otherwise.
```
The input
o sorted
? is the input,
ḅ and the runs in the input
Ċ of which there are two
lᵛ have the same length.
```
] |
[Question]
[
## Challenge
Write a program that takes an 11x11 array of integers, and constructs a 3D ASCII block building, where each value in the array represents the height of a column of blocks at the coordinates matching the array position. A negative height is a "floating" column - only the top block is visible.
## Example
```
__________________
___ /\__\__\__\__\__\__\
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /\__\ /\/\__\__\__\__\__\__\
2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /\/__/ /\/\/__/__/__/__/__/__/
2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /\/\__\ /\/\/\__\ /\/\/__/
1, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0, \/\/\__\ /\/\/\/__/ /\/\/__/
0, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0, \/\/__/ /\/\/\/\__\ /\/\/__/
0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, \/\__\ /\/\/\/\/__/ /\/\/__/
0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, \/__/ \/\/\/\/\__\_ \/\/__/
1, 0, 0, 4, 3, 2, 1, 0, 0, 0, 1, \/\/\/\/__/_\_ \/__/
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ___ \/\/\/__/__/_\_ ___
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /\__\ \/\/__/__/__/_\ /\__\
1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, \/\__\ \/__/__/__/__/ \/\__\
\/\__\_________ ______\/\__\
\/\__\__\__\__\ /\__\__\__\__\
\/__/__/__/__/ \/__/__/__/__/
```
## Input
The input will be a list of 121 integers, either read from stdin (choice of separator is up to you), or passed in as an array (can be 1D or 2D).
Heights will be in the range -11 to 11.
## Output
The generated building can be written to stdout, displayed directly on the screen, or returned as a newline-separated string.
Leading and trailing whitespace is allowed.
## Building Rules
The shape of an individual 3D block looks like this:
```
___
/\__\
\/__/
```
And a 2x2x2 cube of blocks looks like this:
```
______
/\__\__\
/\/\__\__\
\/\/__/__/
\/__/__/
```
When blocks overlap, a higher block takes precedence over a lower one, blocks in front take precedence over those further back, and blocks to the left takes precedence over those to the right. The only special case is that the top line of a block should never overwrite any non-space character behind it.
The interpretation of column heights can best be explained by looking at a 2D representation from the side.
```
HEIGHT: 1 2 3 -3 -2 -1
__ __
__ |__| |__| __
__ |__| |__| |__| __
|__| |__| |__| |__|
```
## Test Cases
If you want to try out your solution on a few more inputs, I've put together a couple of test cases [here](https://gist.github.com/anonymous/8942545f3838de4a9130ff4966625d09).
## Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins.
[Answer]
# C, ~~376~~ ~~350~~ ~~313~~ ~~309~~ 285 bytes
*Thanks to @Jonathan Frech for saving four bytes!*
```
#define F for(
char*t,G[26][67],*s;i,j,e,k,v,x,y;b(){F s="\\/__//\\__\\ ___ ";*s;--y,s+=5)F e=5;e--;*t=*s<33&*t>32?*t:s[e])t=G[y]+x+e;}f(int*M){F;e<1716;++e)G[e/66][e%66]=32;F k=0;++k<12;)F i=0;i<11;++i)F j=11;j--;v+k||b())x=i+j*3+k,y=14+i-k,(v=M[i*11+j])>=k&&b();F;++e<26;)puts(G+e);}
```
[Try it online!](https://tio.run/##5ZfdbtowFMfveYqo0xBJbIHjxIEZd3dw1SdIoqhl6RaisanJEKjl2ZmT8hHwKbisY0WLjiC2f7KPz9@cg0f462i0XH74ktynk8QYGPc/HlqN0bfbB6tAw8BhUcD8CFk5T9EYJShDUzRDc37XMh8HRi6uwrAdx@12GMZxGBpxHBtXXNIYz1FuC88cGInweIIxtwph5X1Km1ZxTZ3PVvEpD5LILMQwmEf2zE744r6VTgrrRk7Nkz7xCeO2nZjDIGkz6UjyUX4K6vCBkYmOHMr6xOFyhVS20j4hsiuVzbGQr2O54tTOnp6kp@ZMpPbYonaG5oK4dooz1JqKmyC1CLHHkXktsmZTgnxQLth3GDd//iry1lCuzhdL6ZTx/TadtMzGY8OQT9mRTiRCgsgQVdfzQPlQZHQO2QZ03hwk6z4f4ZrJ5h7YeTXIjiy96fN0fXRRGSq5N1IDCQCCdiK4sdr42ipuwRvVd3kUS4HNVXsjuQNI3tEV6C@CLsJrK0P7Iohrg/i8oLaPZ4sjJLmjSE51JSfVeabl5jQ98HRBpgv6W9A9BOItiHVB7Rn1fXyjXR@L41YZSHKqSO4CkrtVcmM7SbPMmKzqr0l@uAJQ3cTunJDi3kMm@regkl3gX7mrSO4Bkj8L7EHm7xzjWu1UD3sd9HSP8f8JasexpgxeW00ZSHJPkZypkhOCDtsZwL2dXzZ4tjhCkjNFcv9ILQfSx7tIca5Sz3a9Bmu58m8Xu6@f8cISu69I3gUkl/mCreo37q5sVdfZXubSBC@qThIEXoZAEHo/Ewj4CEneVSTv1SQ/KUzgVfEFkK5NA/TgCzII@kgth@Bm5FnsaYLbuklXezsQHk8X3ETgGLgb1j@5pfWk5ovlbw)
**Unrolled:**
```
#define F for(
char *t, G[26][67], *s;
i, j, e, k, v, x, y;
b()
{
F s="\\/__//\\__\\ ___ "; *s; --y, s+=5)
F e=5; e--; *t=*s<33&*t>32?*t:s[e])
t = G[y]+x+e;
}
f(int*M)
{
F; e<1716; ++e)
G[e/66][e%66] = 32;
F k=0; ++k<12;)
F i=0; i<11; ++i)
F j=11; j--; v+k||b())
x = i+j*3+k,
y = 14+i-k,
(v=M[i*11+j])>=k && b();
F; ++e<26;)
puts(G+e);
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~70~~ ~~69~~ 68 bytes
```
≔E¹¹⮌I⪪S,θF²F¹¹F¹¹F¹¹«J⁻⁻⁺λκ×μ³ι⁻λκ≔§§θλμη¿∨⁼±η⊕κ‹κη¿ι“↗⊟&⁹κUhnI”___
```
[Try it online!](https://tio.run/##pU9LawIxED67v2LY0wQiGu3j0JOUHiy1leoxEBYd12A2rpusFEp/@zZrdbX0JTR888p885otk2K2TkxVDZzTqcVRkqMQHJ5pS4UjvE2cx0lutMehzUs/8YW2KTIOMY9ZeBw27CZarAvAHoOdFeI75zVq3ZdZPl3jSNvS7fXYBGU4rEKjqc7IYcahX7fVQT44u3QY0trvOPBDO6eXxm44mEDOgixrml4APhV4tykT4/CR0sQTLkN2aGcFZWQ9zXFVz3gg53BVlzEGdZlmMA4Heoyl7UiplJTSStlRqhMzIOPokFdKxWHYW1VBn0P3F0TQ@zdBHPxr3j5BCPeE7tmEqx9GNP7lXztc8PrksLM4IYjoU/gVZxIaHP8bVO2teQc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E¹¹⮌I⪪S,θ
```
Read the array, split each line on commas and cast to integer, but also reverse each line, since we want to draw right-to-left so that left columns overwrite right columns. (Other dimensions already have desired overwriting behaviour.)
```
F²F¹¹F¹¹F¹¹«
```
Loop through i) top lines and bodies k) height l) rows m) columns. (Looping through first top lines and then bodies avoids overwriting bodies with top lines.)
```
J⁻⁻⁺λκ×μ³ι⁻λκ
```
Jump to the position of the cube.
```
≔§§θλμη
```
Fetch the height at the current row and column.
```
¿∨⁼±η⊕κ‹κη
```
Test whether a cube should be drawn at this height for this row and column.
```
¿ι“↗⊟&⁹κUhnI”___
```
Draw the body or top of the cube.
[Answer]
# JavaScript (ES6), ~~277~~ 251 bytes
```
a=>(n=55,$=f=>[...Array(n)].map((_,i)=>f(i)),S=$(_=>$(_=>' ')),n=11,$(l=>$(z=>$(y=>$(x=>(x=10-x,X=x*3+y+z,Y=y-z+n,Z=a[y][x])<=z&&Z+z+1?0:l?['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s)):S[Y].splice(X+1,3,...'___'))))),S.map(r=>r.join``).join`
`)
```
```
f=
a=>(n=55,$=f=>[...Array(n)].map((_,i)=>f(i)),S=$(_=>$(_=>' ')),n=11,$(l=>$(z=>$(y=>$(x=>(x=10-x,X=x*3+y+z,Y=y-z+n,Z=a[y][x])<=z&&Z+z+1?0:l?['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s)):S[Y].splice(X+1,3,...'___'))))),S.map(r=>r.join``).join`
`)
console.log(f([
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, -11],
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0],
[0, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0],
[0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 4, 3, 2, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 11]
]))
```
Saved 26 bytes from [@Neil's suggestion](https://codegolf.stackexchange.com/questions/153109/3d-ascii-block-building/153135#comment374122_153135).
### Ungolfed
```
a=>(
n=55,
$=f=>[...Array(n)].map((_,i)=>f(i)),
S=$(_=>$(_=>' ')),
n=11,
$(l=>
$(z=>$(y=>$(x=>(
x=10-x,
X=x*3+y+z,
Y=y-z+n,
Z=a[y][x],
Z<=z && Z+z+1 || (
l
? ['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s))
: S[Y].splice(X+1,3,...'___')
)
))))
),
S.map(r=>r.join``).join`\n`
)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 243 bytes
```
a=input()
s=eval(`[[' ']*55]*23`)
for h in range(7986):
k=h%3;x=h/3%11;y=h/33%11;z=h/363%11;i=h/3993;u=y+z-x*3+30;v=y-z+10
if~-(z>=a[y][10-x]!=~z):
if i*k:s[v+k][u:u+5]='\//\____/\\'[k%2::2]
if~-i:s[v][u+1+k]='_'
for l in s:print''.join(l)
```
[Try it online!](https://tio.run/##lZDLboMwFETX5SvcBTLPgnEhBeT@iLESFqG4IEC8BCz4dWpHKq0ipUmtWczIR77j28x9XlfetqWEV83Qa7rSkfOYltqJUgggM3yfGR4@6UpWtyAHvAJtWn2ctUP4FuiRAgqSqzieSO5gFaF4lubiFumCi@XShiGOBzKbiz0Z2MRuPJLZXkzkKoBnq60t7ySlM6PItSf2TNZFvP7EM8CNIuroaBaMDtFg@ozAxHGSozhOkkBaqF4UeUyyq80lKkATCZ7AI7zULmXtLmpaXvUQvnzWvNJKfdsoxRZwbwsxC1DvT8R9EEHf6WDZvyTijrj/QIKbg/bk3@/yagGxANEeXX8a3d/LY8iun5tdjH0B "Python 2 – Try It Online")
A Python translation of Neil’s Charcoal approach.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~117~~ ~~116~~ 112 bytes[SBCS](https://github.com/abrudz/SBCS)
```
a←23 55⍴0⋄{i←11 0+⍵+.×3 2⍴3-7897⊤⍨6⍴5⋄(,2 5↑i↓a)←745366⊤⍨10⍴4⋄(3⍴i↓1⌽¯1⊖a)⌈←1}¨j[⍋-/↑j←⍸↑⎕↑¨⊂⌽1,11/⍳2]⋄' _/\'[a]
```
[Try it online!](https://tio.run/##zZLPTsJAEMbvfYq5oaHITsu28ixITBuDgZDg1RgvxCAp1GiM@gIeuPWgJl681DeZFylfaUAoTaPEA8nsZjr7@3b@bL2Lfu3s0usPzhO5e@oOZHSvDBnfdhIPrmWT1hK@K5ncXHURYCZVlfCjevT9YpOFI7vmHjddCV4lnDn41kAPTIu0jB6gePQOIXMb2nacDGIFqpFSNpwUYZl@xRFL8Ax4Ok7TXMezXkvCSa2Oa3qISPgJDyVij2cSDKFhk7ku4ZvVxm0VOq2fVFpeO0H1iU@pJhjaRKrEDN/MOOufOV6GXIqjzYXQJqt2YZ3y/KuQ/mWdDSLMCu3xGsfbXKHtxK3s53hlRsfAO/uGsXxHamIerNKNM48QWqiWK99aHGFGuW2dL9Lkz/eJzxrn9RHEUbNcszUD9291LRLs06DQesF/Mgc "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Tcl, 380 ~~409~~ bytes
User **[sergiol](https://codegolf.stackexchange.com/users/29325/sergiol)** has been busy crunching this down very nicely:
```
set X [read stdin]
proc L {a b c d e s} {time {incr z
set y -1
time {incr y
set x -1
time {if {abs([set Z [lindex $::X [expr ($y+1)*11-[incr x]-1]]])==$z|$z<$Z} {set s [string repl [string repl $s [set i [expr -3*$x+57*$y-55*abs($z)+701]] $i+$b $a] [incr i $c] $i+$e $d]}} 11} 11} 12
set s}
puts [L /\\__\\ 4 56 \\/__/ 4 [L "" -1 -55 ___ 2 [string repe [string repe \ 55]\n 23]]]
```
[Try it online!](https://tio.run/##lVHbaoNQEHw/XzGU85AoEo/xQkPzB/mAEhVJ9LQIqRW1oKZ@u10vpVpMSh8W3ZnZmV0twkvb5rLAM9xMniLkRRQnPkuz9xAHXE84I0QEibzBtYjfJK5xEmaoWTdVQRNsglY9Wk7QF/I45yu3w49wL3ESyRJ8t6NAWaYZVrxSxVoRQnN7i9LXhO/76/2e15@8fuJHCu6mc7h5kcXJKzKZXuYN70jSxKOptlV4qVqOwivNspRuA16vVUcna/BY5Wfwk48hMQYPB1SCR37TQIixjP6evGHpR0ERB2w8Lwg8DyYsG563CYINvRPx8EBHg8IQBAGM6Xpy3niAZfleAmNLd7YtoOOnBOb9rBgojMYXuOlcx5tseNpUzrKf5oy8NWq7/pHO0KnEpPQeH/j/as0x4y@tMbntxr4Y99Vs0hoY9N@csaA3Oi3YnQ/664PYN7QL5prF7v@wKW6yLw "Tcl – Try It Online")
### Original Content
```
set xs [read stdin]
proc L {a b c d e s} {set z 0
while {[incr z]<12} {set y -1
while {[incr y]<11} {set x -1
while {[incr x]<11} {set Z [lindex $::xs [expr ($y+1)*11-$x-1]]
if {abs($Z)==$z||$z<$Z} {set i [expr -3*$x+57*$y-55*abs($z)+701]
set s [string repl [string repl $s $i $i+$b $a] [incr i $c] $i+$e $d]}}}}
set s}
puts [L /\\__\\ 4 56 \\/__/ 4 [L "" -1 -55 ___ 2 [string repe [string repe \ 55]\n 23]]]
```
[Try it online!](https://tio.run/##lVHRboJAEHy/r5iYe1DJRQ5FU6N/4BcoF6JwbS8x1ABNEfXb7SLXFFq0KWEDuzM7O3uXR/vrNdM5igybVG9jZHlsEsUO6VuEFU5b7BAhhkZ2walilnDZx6vZa5w2JolSlGohPQseIWQbPRIqLVr8QosGusZmb5JYF@DzeeVHF4cUfX505GAopeCFkEox80yudlmfrwfLJS/PZ14u@NpqGNslxkNeOP5syI/C94c3fjlwZq5UrOKRepanJnlBqg/7dsIzcEOvw3fgW4XaKVUidatq8Fhd6KmVLuzwnpPeCqMgCMMgwAT@FEEwCsMR/RPQ69HiICMIwxBec5xuJwHg@ypI4I2VUtcr4OI7JNp5KxhoGLV3YM2@Cp@w@julmHXriZnFfcut8idaw6WQjXBv9Rr/L3diZ/zF9Rq73fEL61dMieuh5n9hXgffq7hgDw70x4FM73A7xIXPHl9Ysz5hnw)
Alas, it is what it is. It’s only a tad easier on the eyes when “ungolfed”
```
set s [string repeat [string repeat " " 55]\n 23]
proc loops {s0 i0 io s1 i1} {
set z 0; while {[incr z] < 12} {
set y -1; while {[incr y] < 11} {
set x -1; while {[incr x] < 11} {
set Z [lindex $::xs [expr {($y+1) * 11 - $x - 1}]]
if {abs($Z) == $z || $z < $Z} {
set i [expr {-3*$x + 57*$y - 55*abs($z) + 701}]
set ::s [string replace $::s $i $i+$i0 $s0]
incr i $io
set ::s [string replace $::s $i $i+$i1 $s1]
}
} } }
}
loops "" -1 -55 \
___ 2
loops /\\__\\ 4 56 \
\\/__/ 4
puts $s
```
Builds a string, as per requirements. Takes the array from stdin. Goes from bottom to top, front to back, right to left over the string data. Does it in two passes, once for the top edge and again for the rest of the body of each cube.
I tried to make it smaller using some sweet functional lambda mojo, but alas, that made it larger.
] |
[Question]
[
All bots at the battle arena suddenly got brainfucked and no one can explain why. But who cares as long as they are still able to fight - although Brainfuck is the only language they understand anymore.
---
It's been a while since the last submission so I'll finally annouce the winner of BrainFuckedBotsForBattling: **Congratulations to LymiaAluysia for winning with NyurokiMagicalFantasy!**
---
## Scoreboard
```
| Owner | Bot Score |
|--------------------|-------------------------------|
| LymiaAluysia | NyurokiMagicalFantasy - 600 |
| Sylwester | LethalLokeV2.1 - 585 |
| weston | MickeyV4 - 584 |
| Sp3000 | YandereBot - 538 |
| Comintern | CounterPunch - 512 |
| Sylwester | BurlyBalderV3 - 507 |
| LymiaAluysia | NestDarwin - 493 |
| IstvanChung | Bigger - 493 |
| Manu | DecoyMaster - 489 |
| archaephyrryx | Wut - 478 |
| DLosc | LightfootPlodder - 475 |
| archaephyrryx | 99BottlesOfBats - 461 |
| Sylwester | TerribleThorV2 - 458 |
| MikaLammi | WallE2.0 - 443 |
| Mikescher | MultiVAC - 441 |
| archaephyrryx | Twitcher - 439 |
| Timtech | MetalDetector - 438 |
| AndoDaan | BeatYouMate - 433 |
| csarchon | TheWallmaster - 427 |
| Sparr | SeeSawRush - 412 |
| archaephyrryx | Stitcher - 406 |
| PhiNotPi | RandomOscillator - 403 |
| ccarton | AnybodyThere - 398 |
| Comintern | 2BotsOneCup - 392 |
| kaine | SternBot - 387 |
| PhiNotPi | EvoBot2 - 385 |
| PhiNotPi | EvoBot1 - 381 |
| Brilliand | TimedAttack - 373 |
| Sylwester | ReluctantRanV2 - 373 |
| AndoDaan | PrimesAndWonders - 359 |
| Nax | TruthBot - 357 |
| DLosc | Plodder - 356 |
| weston | FastTrapClearBot - 345 |
| MikaLammi | PolarBearMkII - 340 |
| Sp3000 | ParanoidBot - 336 |
| Moop | Alternator - 319 |
| TestBot | FastClearBot - 302 |
| icedvariables | PyBot - 293 |
| TestBot | DecoyBot - 293 |
| kaine | BestOffense - 291 |
| Geobits | Backtracker - 289 |
| bornSwift | ScribeBot - 280 |
| IngoBuerk | Geronimo - 268 |
| flawr | CropCircleBot - 239 |
| plannapus | CleanUpOnAisleSix - 233 |
| frederick | ConBot - 230 |
| frederick | 128Bot - 222 |
| AndoDaan | EndTitled - 219 |
| PhiNotPi | CloakingDeviceBot - 215 |
| AndoDaan | GetOffMate - 206 |
| DLosc | ScaredyBot - 205 |
| isaacg | CleverAndDetermined - 202 |
| PhiNotPi | CantTouchThis - 202 |
| Moop | StubbornBot - 174 |
| Cruncher | StallBot - 168 |
| IngoBuerk | Gambler - 157 |
| BetaDecay | RussianRoulette - 129 |
| flawr | DoNothingBot - 123 |
| SebastianLamerichs | Dumbot - 115 |
| mmphilips | PacifistBot - 112 |
| SeanD | DontUnderstand - 92 |
| proudHaskeller | PatientBot - 83 |
| frederick | Dumberbot - 70 |
| flawr | MetaJSRandomBot - 68 |
| Darkgamma | TheRetard - 61 |
| BetaDecay | Roomba - 61 |
| BetaDecay | PrussianRoulette - 31 |
| frederick | Dumbestbot - 0 |
```
*Final Scores from 09.10.2014*
**EDIT6**: Discarded logs due to extreme size and runtime. You can generate them yourself by uncommenting the lines in `RunThisTournament.py`.
**EDIT5**: Implemented Abbreviation handling into the controller, no huge runtimes anymore. **This has the side effect that numbers and parentheses are not treated as comments anymore.** You can still use them if you want to provide an annotated version, but it would be very helpful if there would be **also an uncommented version of your code**, so I don't need to remove the comments manually. Thanks!
**EDIT4**: Changed the title, because the tournament got removed from the hot network questions. Thanks to @Geobits for pointing this out!
**EDIT3**: Removed comments in bf programs, due to an unexpected result, should be fixed now. If anyone has a problem with removing his comments, please report.
**EDIT2**: Since it caused an arcane runtime on my quite slow computer, I reduced the timeout limit from 100000 cycles to 10000 cycles. Not that anyone has turned the resultof a running game beyond this point anyway.
**EDIT1**: Fixed a bug in the convert script causing the interpreter to not ignore numbers in commented programs.
---
## Description
This is a [Brainfuck](http://esolangs.org/wiki/Brainfuck) tournament inspired by [BF Joust](http://esolangs.org/wiki/BF_Joust). Two bots (Brainfuck programs) are fighting each other in an arena which is represented by a memory tape. Each cell can hold values from -127 up to 128 and wrap at their limits (so 128 + 1 = -127).
Valid instructions are similiar to regular Brainfuck, which means:
```
+ : Increment cell at your pointer's location by 1
- : Decrement cell at your pointer's location by 1
> : Move your memory pointer by 1 cell towards the enemy flag
< : Move your memory pointer by 1 cell away from the enemy flag
[ : Jump behind the matching ']'-bracket if the cell at your pointer's location equals 0
] : Jump behind the matching '['-bracket if the cell at your pointer's location is not 0
. : Do nothing
```
The arena has a size of 10 to 30 cells which is pseudorandomly chosen each battle. At both ends is a 'flag' located which has an initial value of 128, while all other cells are zeroed. Your bot's goal is to zero the enemy's flag for 2 consecutive cycles before he zeroes your own flag.
Each bot starts at his own flag, which is cell [0] from his own perspective. The opponent is located on the other side of the tape.
```
[ 128 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 128 ]
^ ^
my bot other bot
```
Both bots execute their action simultaneously, this is considered one cycle. The game ends after 10000 cycles or as soon as one of the winning conditions is reached. If one of the programs reaches its end, it simply stops doing anthing until the end of the game, but can still win.
---
## Winning conditions
Your bot wins under one of the following conditions:
* Your enemy's flag is zeroed before yours
* Your enemy moves his pointer out of the tape (executes `>` on your flag or `<` on his own)
* Your flag's value is more far away from 0 than the value of your opponent's flag after 10000 cycles
---
## Rules
Your post should contain a name for your bot and its code.
* You can use the following abbreviation syntax to make your code more readable:
+ e.g. `(+)*4` is the same as `++++`, this is valid for any instruction **except unmatched brackets in parentheses** since the loop logic collides with the abbreviation logic. Please use `[-[-[-` instead of `([-)*3`
* Every other character than `+-><[].` is a comment and therefore ignored, except `()*` for abbreviations
Bots which do not follow the rules will excluded from the tournament.
* Only basic Brainfuck is allowed, no other variants which supports procedures or arithmetic operations
* Your bot's source code should not contain unmatched brackets
You may inform yourself about [basic strategies](http://esolangs.org/wiki/BF_Joust_strategies) but do **not** use another one's code for your own bot.
---
## Scoring
A bot's score is determined by the number of wins against all other bots.
An encounter between 2 bots consists of 10 matches with different memory tape lengths, which results in a maximum score of 10 points per encounter.
A draw results in no points for this match.
---
## Control program
You can find the [control program](https://github.com/redevined/brainfuck/tree/master/BrainFuckedBotsForBattling) on github, along with the full logs from the battles.
The leaderboard will be posted here once it is generated.
Feel free to clone the repository and try your bot against the others on your own. Use `python Arena.py yourbot.bf otherbot.bf` to run a match. You can modify the conditions with the command-line flags `-m` and `-t`. If your terminal does not support ANSI escape sequences, use the `--no-color` flag to disable colored output.
---
## Example bots
FastClearBot.bf
```
(>)*9 Since the tape length is at least 10, the first 9 cells can be easily ignored
([ Find a non-zero cell
+++ Increment at first, since it could be a decoy
[-] Set the cell to zero
]> Move on to the next cell
)*21 Repeat this 21 times
```
DecoyBot.bf
```
>(+)*10 Set up a large defense in front of your flag
>(-)*10 Set up another one with different polarity
(>+>-)*3 Create some small decoys
(>[-] Move on and set the next cell to zero
. Wait one round, in case it is the enemy's flag
)*21 Repeat this 21 times
```
The DecoyBot will win every match with a tape length greater than ten, since the FastClearBot can avoid the small decoys, but not the larger ones. The only situation in which the FastClearBot can win against DecoyBot, is when it is fast enough to reach the enemy's flag before his opponent has built up large decoys.
[Answer]
# Cloaking Device Bot
This bot basically tries to hide its base, making it so that other bots will move right past it and off the tape.
```
(-)*127(-+--+-++)*12500
```
[Answer]
# Burly Balder v3
Burly Balder is a medium slow rush. It makes two large decoys before going into
rush mode. In rush mode it has a loop that only uses 4
steps each zero cell and when a non zero cell it has a case analysis for
[-18,18] before blindly reducing with 107 before clearing with `[-.]`. He
clears an unchanged flag in 242 steps, 114 more than a uncertain `-*128`
and 14 less than a naive `[-]` clear. When a cell is cleared he continues
leaving a trail of -2 decoys. He has a special case only for index
9 to save some steps for size 10 games and it leaves the cell with a 1 decoy.
```
>((-)*18>)*2 Make two minus seventeen decoys
(->)*6 Move to cell nine
[ special case for ten cell game
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[ if not minus one to minus eighteen
(-)*18 decrease by eighteen
-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[ if not plus one to plus eighteen
(-)*107 decrease by hundred and seven
[-.] slow clear
]]]]]]]]]]]]]]]]]] end plus conditionals
]]]]]]]]]]]]]]]]]] end minus conditionals
] end special case
+
([> while true go right
[ start clear cell
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[ if not minus one to minus eighteen
(-)*18 decrease by eighteen
-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[ if not plus one to plus eighteen
(-)*107 decrease by hundred and seven
[-.] slow clear
]]]]]]]]]]]]]]]]]] end plus conditionals
]]]]]]]]]]]]]]]]]] end minus conditionals
] end clear cell
-- set to minus two
] while true end
- decrease and loop
)*5 In case of clash or initial column minus seven is zero
```
Trivia: Balder is a nordic god and son of Odin. He is known mostly for the [story of his death](http://ancienthistory.about.com/cs/norsegodspictures/a/baldersdeath.htm):
He was scared for his safety so the other gods tried to predict and shield against every threat.
He was eventually killed by Loki since while they protected him against swords and arrows they forgot to
protect him against Mistletoe.
[Answer]
# [Nyuroki Magical Fantasy](https://www.youtube.com/watch?v=i-C46RO4-a0)
I think it's about time to get serious~ I finished up my compiler for a little HLL to make writing BF Joust programs easier. This was my first serious attempt to make something with it. The bot's concept is pretty simple. It sets up a few decoys of varying polarities, then goes crazy with a large wiggle clear with a reverse offset clear in the middle.
Oh, by the way, the expected score is roughly 577 points against the last round's hill. That's a 93% win rate. <3
[Compiled](https://github.com/Lymia/JoustExt/blob/master/examples/nyuroki.bf) |
[Source Code](https://github.com/Lymia/JoustExt/blob/master/examples/nyuroki.jx)
```
Nyuroki Magical Fantasy by Lymia Aluysia
Released under the terms of MIT license
>>>>>>>>++<--<+<--<++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+<-------------------------------------------------------------<---------------
----------------------------------------------<++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++<(-)*19(>)*8(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-
[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-
[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[
-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3
+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[
-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>
[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[
-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*
82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(
-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[
+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+
[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[
+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-
[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-
[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*
41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[
(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[
-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-
[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[
-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.]
.]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[
-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+
[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[
+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+
[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16
+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+
[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[
-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+
[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[
-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-
[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+
[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-
[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[
-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-
[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82
[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)
*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[
+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(+)*16+[+[+[+
[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[+[+[+[+[+[+[
+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--(>[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[-[-[-[-[-[(
+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+[+[+[+[+[+[
+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]-->[-[-[-[(+)*3+[+[+[(-)*6-[-[-[-[-[
-[-[-[-[-[(+)*16+[+[+[+[+[+[+[+[(-)*24-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[-[(+)*41+
[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[+[(+)*82[[+.].]--]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]--)*2]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]--)*3]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]--)*4]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*5]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*6]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*7]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*8]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*9]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]--)*10]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]--)*11]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)
*12]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*13]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*14]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*15]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*16]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]]]]]]]]]]]--)*17]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]]]]]]]]]]]--)*18]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
]]]]]]--)*19]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*
20]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--)*21
```
---
**Edit**: I squeezed a few more wins out of Nyuroki.
**Edit 2**: Hey, look, I did it again!
**Edit 3**: After wrestling for a while with a stupid parsing bug in Arena.py, I finally got another improvement in~ This is what I mean by "time to get serious", you know. <3
[Answer]
# EvoBot 1
This is a simple bot created via genetic algorithm. I started with a template, and my program slowly adjusted the numbers to create a better warrior-bot. The code below has been edited to increase readability.
```
>+>---(>)*6(>[+++[-]])*30
```
I used the other entries in the competition to measure the fitness of the different candidates.
Since this was my first attempt at an evobot, I started with a simple template:
```
>(+)*n>(-)*n(>)*n(>[(+)*n[-]])*30 #template
```
I predict that this bot will receive a score in the 50s to 60s range.
~~I am currently working on a reverse decoy template.~~
# EvoBot 2
This is a bot created by the same genetic algorithm, but with the following template:
```
>>>>(-)*n<(+)*n<(-)*n<(+)*n(>)*8(>[+++[-]])*30 #template
```
This bot uses the reverse decoy strategy to set 4 decoys of varying height. The resulting bot is:
```
>>>>(-)*4<(+)*6<(-)*7<(+)*8(>)*8(>[+++[-]])*30
```
I expect this new bot to fare better than the previous bots, possibly earning a score in the 70s (probably much higher than that since there are many new entries).
[Answer]
# Alternator
It assumes most people will zero a cell by either adding or subtracting to it, so on average every cell will take 128 turns to zero.
```
(>+>-)*4>+(>[-][.])*21
```
Annotated version
```
(>+>-)*4 Move eight squares alternating polarity
>+ Move one more
(
> Move to the next square
[-] Zero it
[.] Wait while it is zero
)*21 Repeat
```
[Answer]
So, someone else here using an genetic algorithm to try and make programs here. Well... a long time ago, I wrote an BF Joust evolver for an ongoing hill in an IRC channel. I decided to give it a spin for this contest as well~
And... unlike the other person with an evolver, my evolver can actually change more of the program more than repeat counts. :)
# NestDarwin (Generation 309)
This is the best result my evolver has come up with so far. I'm not sure how much the nested structure helps in this case, but, structures like this was what the evolver is meant to be able to do. Expected performance on the 27.08.2014 hill is 474 points. (Calculated by running the battle on all 21 tape lengths, and multiplying by 10/21. Note that this isn't normalized for the fact that this hill has one extra program on it)
```
(-)*5(>[(-)*4----[.+]]--((-)*5(>[(-)*4----[.+]]--((-)*5(>[(-)*4----[.+]]--((-)*5(>[(-)*4----[.+]]--)*10000)*10000)*10000)*10000)*10000)*10000)*10000
```
---
**EDIT**: Changed list of programs I wanna enter into this hill. Ran evolver overnight. :)
---
**EDIT 2**: I went and manually analyzed the evolver's output. Despite looking very different, NestDarwin is basically an optimized version of TinyDarwin... Manually minimized (with identical functionality) and analyzed:
```
(-)*5 Break stuff that assumes flag size.
(>[(-)*8[.+]](-)*7)*3 Make a few larger decoys next to our flag.
The clear loop is basically dead code here.
Few things are going to approach so fast, so.
(>[(-)*8[.+]](-)*2)*10000 And go on an rampage with an offset clear!
I presume the slow clear is to beat tripwires.
```
So, an almost identical program would be as follows... which is basically a super-optimized version of TinyDarwin.
```
(-)*5(>.(-)*7)*3(>[(-)*8[.+]](-)*2)*10000
```
TinyDarwin was as follows. Not very different, hun? I'm just going to withdraw it from the hill. I thought it was distinct, but... well, I was wrong.
```
((-)*5>[(-)*4.[+.]].)*10000
```
It's become apparent that the current hill isn't strong enough to allow it to evolve much more complex things. :(
[Answer]
## Polar bear Mk II
There are two kinds of *polar bears*: those who get trapped and those who trap other people.
Tries to guess polarity of the opponent and then uses that information to lock opponent into infinite loop. Works well against simple clearing strategies and somewhat randomly against other. Traps can be quite easily avoided so I might add some backup strategies later.
```
>++>- create polar bear traps
[[]]<
[][
[[]]<
(+)*290 (>)*9 (+)*120 (.+)*16 (<)*9
(+)*112 (>)*10 (+)*120 (.+)*16 (<)*10
(+)*112 (>)*11 (+)*120 (.+)*16 (<)*11
(+)*112 (>)*12 (+)*120 (.+)*16 (<)*12
(+)*111 (>)*13 (+)*120 (.+)*16 (<)*13
(+)*111 (>)*14 (+)*120 (.+)*16 (<)*14
(+)*111 (>)*15 (+)*120 (.+)*16 (<)*15
(+)*110 (>)*16 (+)*120 (.+)*16 (<)*16
(+)*110 (>)*17 (+)*120 (.+)*16 (<)*17
(+)*110 (>)*18 (+)*120 (.+)*16 (<)*18
(+)*109 (>)*19 (+)*120 (.+)*16 (<)*19
(+)*109 (>)*20 (+)*120 (.+)*16 (<)*20
(+)*109 (>)*21 (+)*120 (.+)*16 (<)*21
(+)*108 (>)*22 (+)*120 (.+)*16 (<)*22
(+)*108 (>)*23 (+)*120 (.+)*16 (<)*23
(+)*108 (>)*24 (+)*120 (.+)*16 (<)*24
(+)*107 (>)*25 (+)*120 (.+)*16 (<)*25
(+)*107 (>)*26 (+)*120 (.+)*16 (<)*26
(+)*107 (>)*27 (+)*120 (.+)*16 (<)*27
(+)*106 (>)*28 (+)*120 (.+)*16 (<)*28
(+)*106 (>)*29 (+)*120 (.+)*16 (<)*29
(+)*106 (>)*29 [-]
]<
(-)*290 (>)*9 (+)*120 (.+)*16 (<)*9
(-)*112 (>)*10 (+)*120 (.+)*16 (<)*10
(-)*112 (>)*11 (+)*120 (.+)*16 (<)*11
(-)*112 (>)*12 (+)*120 (.+)*16 (<)*12
(-)*111 (>)*13 (+)*120 (.+)*16 (<)*13
(-)*111 (>)*14 (+)*120 (.+)*16 (<)*14
(-)*111 (>)*15 (+)*120 (.+)*16 (<)*15
(-)*110 (>)*16 (+)*120 (.+)*16 (<)*16
(-)*110 (>)*17 (+)*120 (.+)*16 (<)*17
(-)*110 (>)*18 (+)*120 (.+)*16 (<)*18
(-)*109 (>)*19 (+)*120 (.+)*16 (<)*19
(-)*109 (>)*20 (+)*120 (.+)*16 (<)*20
(-)*109 (>)*21 (+)*120 (.+)*16 (<)*21
(-)*108 (>)*22 (+)*120 (.+)*16 (<)*22
(-)*108 (>)*23 (+)*120 (.+)*16 (<)*23
(-)*108 (>)*24 (+)*120 (.+)*16 (<)*24
(-)*107 (>)*25 (+)*120 (.+)*16 (<)*25
(-)*107 (>)*26 (+)*120 (.+)*16 (<)*26
(-)*107 (>)*27 (+)*120 (.+)*16 (<)*27
(-)*106 (>)*28 (+)*120 (.+)*16 (<)*28
(-)*106 (>)*29 (+)*120 (.+)*16 (<)*29
(-)*106 (>)*29 [-]
```
[Answer]
# Pacifist Bot
My bot believes violence is never the answer and will try to avoid combat at all costs.
```
(.)*8 Since it takes at least 9 turns for a bot to come to mine, remain idle for 8
> Skedaddle over one spot
([(>)*8 If a bot has approached, RUN
[(<)*8 If you accidentally ran into a bot, run the other way this time
]]. If it's safe here, chill out
)*6249 keep running until the end of battle, or until tired
```
[Answer]
# AnybodyThere?
Periodically looks behind to determine when the enemy has started clearing it's decoys, then rushes ahead.
Seems to do well, but I'm not sure if that's because of the strategy or just because I'm adding 10 to every cell before clearing.
Edit: Fixed a logic problem. First time writing a brainfuck program. It lives up to it's name.
```
>>>+<(+)*5<(-)*5>> Initial defense
[ While he hasn't passed us yet
(>[([(+)*10[-]]>)*29])*4 Jump ahead four, checking for enemy
+ Front marker
<<<< Check behind
[ If he hasn't passed us yet
>>>
(+)*5<(-)*5 Set decoys in reverse
<<[-]
]
>>>> Check ahead
]
([-[(+)*10[-]]]>)*29 Clear to the end
```
[Answer]
## WALL-E 2.0
Rushes to location 9 and adds 128 to it, winning quickly in size 10 arena if opponent hasn't changed initial flag value. On larger arenas, this works as large decoy. After that it fills the space between location 9 and own flag with large decoys. When decoys are placed, it scans for non-empty locations and tries to clear them quickly.
**Version 2.0** builds larger decoys and has some tolerance against changing initial flag value. It can also switch to backup strategy if things start to look hairy.
```
(>)*9
(+)*128 <
< [ (<)*7 ((-+-)*256)*15 ] > [ (<)*8 ((+-+)*256)*15 ]
(-)*47 < (+)*63 < (-)*72 < (+)*69 <
(-)*84 < (+)*66 < (-)*76 < (+)*66 <
++++ (>)*9 +.+.+.----.-.-. (>[-[++[(+)*124.+.+.+.+.+.+.+.+.>]]])*21
```
Effectiveness of this bot is based on two facts:
1. Most bots do not change the initial value of their flag.
2. Building large decoys is faster than clearing them.
[Answer]
# Lethal Loke V2.1 (with Mistletoe)
This is of course a deadly bot and he kills not only beautiful Burly Balder a with mistletoe, but wins almost every time against the other bots as well. It is a combined medium and fast rush. My test gives me a score of 567
[Compiled BFJ file for battle](https://gist.githubusercontent.com/westerp/e86fc8413a572dc907fb/raw/035d17d371412c6ef5766823239ea42664580a4a/LethalLokeV2.1), Racket BFJ generator source:
```
#lang racket
;; bare minimum bfj support
(define (bf . args)
(apply string-append
(map (lambda (x)
(if (number? x)
(number->string x)
x))
args)))
(define (dup x num)
(let loop ((n num) (lst '()))
(cond ((< n 0) (error "Negative n"))
((zero? n) (apply bf lst))
(else (loop (sub1 n) (cons x lst))))))
;; Useful procedures
(define (wiggle amount default-zero n)
(let rec ((n n))
(if (zero? n)
""
(bf "["
(dup "-[" amount)
(bf "(+)*" amount)
(dup "+[" amount)
default-zero
">"
(rec (sub1 n))
(dup "]" (* amount 2))
"]"))))
(define (goto from to)
(let* ((dst (- to from))
(op (if (> dst 0) ">" "<"))
(abs (if (> dst 0) dst (- dst))))
(if (= from to)
""
(bf "(" op ")*" abs))))
(define max-position 30)
(define initial-decoy "(-)*17")
(define small-decoy "(+)*10")
(define large-decoy "(-)*32")
(define flag-position 7)
(define decoy-phase-end-position 14)
(define wiggle-amount 8)
(define plodd-clear "..(+)*120(+.)*27>")
(define plodd-inner-clear (bf "(+)*"
(- 78 wiggle-amount)
"..(+)*42(+.)*27"))
;; Main body of Loke V2
(define (generate-loke2)
(bf ">"
initial-decoy
">->+>->+>->"
(let gen-rec ((n flag-position) (p #t))
(if (> n decoy-phase-end-position)
(bf (medium-slow n))
(bf "["
(medium-slow n)
"]"
(if p small-decoy large-decoy)
">"
(gen-rec (+ n 1) (not p)))))))
;; Retreat goes back to home
;; leaving a trail of flags
;; from flag position
(define (medium-slow last-index)
(bf (goto last-index 2)
(let medium-rec ((n 2) (p #f))
(if (= n flag-position)
(fast-rush n last-index)
(bf (if p "-" "+")
"[" (fast-rush n (max 9 last-index)) "]"
(if p small-decoy large-decoy)
">"
(medium-rec (+ n 1) (not p)))))))
(define (fast-rush cur-position last-known)
(bf (goto cur-position last-known)
"([" plodd-clear
"("
(wiggle wiggle-amount
plodd-inner-clear
(- max-position last-known 1))
">)*" (- max-position last-known)
"]>)*" (- max-position last-known)))
(display (generate-loke2))
```
**Trivia**: Loke (Loki) is a god in Nordic mythology that likes to play with everyone and trick them. He is a shape shifter (into animals and people) and usually goes his own ways. In the stories he often travel with and assist the other gods and does small tricks and stir things up. Besides killing Balder he fathered Hel (godess of Hell/Helvete), the beast Fenrir, and the Midgard Serpent that starts Ragnarok (norse armageddon).
**How it works**
In the beginning he makes a large (-17) decoy then make `+-` pattern all the way to index 7. He scan forwards from to 13 leaving a trail of (+10,-32)+ decoys but when he detects a set he will abort and start a medium\*1 rush mode. If no cells are set he will also start the slow\*3 rush mode.
\*1 In medium rush mode he has detected opponent activity in one of index 7-13 and he starts from index 2. Some opponents leave a zero and other leave a different value and he now have means to detect opponent activity while before making decoys in index 2-6 (-32,+10)+. If cell is not expected value (-1, 1) or he finished making all decoys he goes in fast\*2 rush mode.
\*2 The fast rush mode he expects he has been detected so decoys won't work. We hope the ones we already have set is stopping the opponent and focus on running through opponents decoys. He starts rushing at the farthest point we know based on the previous scanning [9,14] or index 9 if we were made earlier than that. He has special case for first decoy where we just add 120 and plodd 27 since he doesn't want to reduce tha value below zero incase it's a trap, but for every decoy after we wiggle clear at [-8,8] before increasing by 120 and plodding 27 steps ebfore contiuing forward to next cell.
Slow rush mode was removed since it didn't affect the score with the current hill and it makes my bot a little smaller (but not much).
[Answer]
# Geronimo
Is even more offensive than kaine's BestOffense bot as it does not build up any defense. The strategy here is: Others will try to be clever, but being clever takes cycles. So let's just skip to the part we know the enemy is in and clear everything we find.
```
(>)*9(>[-])*21
```
Seems to win most matches against the OP's example bots and kaine's bot.
[Answer]
## SternBot
An actual half serious bot now that things are started. Addressing the simular nature of some of these bots.
```
(>->+>)*3(>[+]>[-])*21
```
[Answer]
# DoNothingBot
>
> The best defense (...) is ignorance.
>
>
>
```
.
```
It does nothing.
EDIT: Wow, I was astonished to see that it did a better job than more than the least 20% of all bots=) (Does this mean it uses a superior strategy or ....?)
[Answer]
# CounterPunch - Edited
Balanced combination of building a strong defense and then attacking.
```
(+)*6>(-)*12(>)*7(<(-)*12<(+)*12)*3(>)*7(([-([(-)*6[+.]])*5])*4>)*21
```
**Annotated:**
```
(+)*6 Switch polarity of the flag
>(-)*12 Build a quick decoy in front of the flag
(>)*7(<(-)*12<(+)*12)*3 Hop out and start building decoys backward
(>)*7 Tally ho!
(([-([(-)*6[+.]])*5])*4>)*21 Clear toward the opposite end
```
Defends similar to @Geobit's [Backtracker](https://codegolf.stackexchange.com/a/36658/7464), but defends against fast attackers by putting a quick decoy out in front of the flag first.
Attack is nested clearing with opposite polarity to quickly clear out decoys with smallish values. Worst case scenario should be a decoy of 64 (either polarity).
**Edit 1:** Improve attacking efficiency against decoys (had a logic error in the polarity switching).
**Edit 2:** Testing indicates that the pause performs slightly better in the inner-most loop.
[Answer]
# Backtracker
A reverse decoy strategy. Start laying decoys down from the front back, so nobody skips over the rest as I'm building them.
If the board is less than size 20 or so, this doesn't work against fast-attack bots, since we'll just pass each other before I start decoying.
```
(>)*9((-)*4<+<-<(+)*4<)*2(>)*8(>[-])*21
(>)*9 Jump ahead 9
((-)*4<+<-<(+)*4<)*2 Lay down alternating polarity/size decoys for 8 spots behind
(>)*8 Jump back forward
(>[-])*21 Clear until flag
```
Note: I don't BF, but this like it does what I want to me. If not, please let me now.
[Answer]
# Can't Touch This
This is a defense-oriented program that attempts to determine how the opponent is clearing cells, and builds a decoy of the appropriate size.
```
>--- create 1st decoy
>+ decoy for timing
>+ decoy for waiting
[]< tripwire activated!
[<-->] increase size of 1st decoy while opponent clears 2nd decoy
(>)*8 attack!
[+(<)*9(+)*20(>)*9] slowly clear, while going back to stop enemy progress
>[+(<)*10(+)*22(>)*10]
>[+(<)*11(+)*24(>)*11]
>[+(<)*12(+)*26(>)*12]
>[+(<)*13(+)*28(>)*13]
>[+(<)*14(+)*30(>)*14]
>[+(<)*15(+)*32(>)*15]
>[+(<)*16(+)*34(>)*16]
>[+(<)*17(+)*36(>)*17]
>[+(<)*18(+)*38(>)*18]
>[+(<)*19(+)*40(>)*19]
>[+(<)*20(+)*42(>)*20]
>[+(<)*21(+)*44(>)*21]
>[+(<)*22(+)*46(>)*22]
>[+(<)*23(+)*48(>)*23]
>[+(<)*24(+)*50(>)*24]
>[+(<)*25(+)*52(>)*25]
>[+(<)*26(+)*54(>)*26]
>[+(<)*27(+)*56(>)*27]
>[+(<)*28(+)*58(>)*28]
```
I am currently working on a version that can win against both polarities.
[Answer]
# ImpatientTripwire (a.k.a. YandereBot)
Tries to be a tripwire so that it can lay decoys of (mostly) the corresponding polarity, but gives up if you take too long and assumes you're the opposite parity instead. Has a reverse tripwire for small boards.
```
(+)*5 Toggles the base
>- Sets up reverse tripwire
>>++>--> Sets up basic decoys
(+)*20 Makes a massive antioffset tripwire
(([)*150 Waits for a while
<<<< Goes to check on the other tripwire
+[
< Bot found you and is furious
((+)*128 (>)*9 (+.)*55 (<)*9)*5 Tries to tie you up
((+)*128 (>)*10 (+.)*54 (<)*10)*5 And torture you
((+)*128 (>)*11 (+.)*53 (<)*11)*5 As it destroys the world
((+)*128 (>)*12 (+.)*52 (<)*12)*5
((+)*128 (>)*13 (+.)*51 (<)*13)*6
((+)*128 (>)*14 (+.)*50 (<)*14)*6
((+)*128 (>)*15 (+.)*49 (<)*15)*6
((+)*128 (>)*16 (+.)*48 (<)*16)*6
((+)*128 (>)*17 (+.)*47 (<)*17)*6
((+)*128 (>)*18 (+.)*46 (<)*18)*6
((+)*128 (>)*19 (+.)*45 (<)*19)*6
((+)*128 (>)*20 (+.)*44 (<)*20)*6
((+)*128 (>)*21 (+.)*43 (<)*21)*6
((+)*128 (>)*22 (+.)*42 (<)*22)*7
((+)*128 (>)*23 (+.)*41 (<)*23)*7
((+)*128 (>)*24 (+.)*40 (<)*24)*7
((+)*128 (>)*25 (+.)*39 (<)*25)*7
((+)*128 (>)*26 (+.)*38 (<)*26)*7
((+)*128 (>)*27 (+.)*37 (<)*27)*7
((+)*128 (>)*28 (+.)*36 (<)*28)*8
((+)*128 (>)*29 (+.)*35 (<)*29)*8
]-
>>>>)*2 Waits again
<(+)*20 Bot got stood up, is sad
<(+)*20 Sets up some decoys
<(+)*20 Grabs a knife
<(-)*20 Licks the blade
<(-)*5 Locks the house
>>>>>>>> Goes to hunt you down
(
> Start searching
[
+[+[+[ Search from minus three
---
-[-[-[ To plus three
(-)*17 If that's no good, do an offset
[+] Clear by adding
[-.--] Just in case
]]]]]] I would duplicate the program to skip these like at
] the bottom but the file would get too large
[--.---] Also just in case
- Leave a small trail
)*22
(
] Skip the bracket closing
<(-)*20 Bot found you and is happy
<(-)*20 Has just the perfect presents for you
<(-)*20 You like decoys right?
<(+)*20 Here's a plus one in case you are sneaky
<(-)*5
>>>>>>>> Time to hunt you down
(>[+[+[+[----[-[-[(-)*17[+][-.--]]]]]]]][--.---]-)*22
)*300
```
**Current version:** [1.3](http://pastebin.com/4GPDx0b0) - edited to do better on smaller boards, at the expense of losing games due to enemies sneaking past during tripwire checking
**Past versions:** [1.2.1](http://pastebin.com/SRJ5KnF7)
(I need a better clear algorithm :/ )
[Answer]
# Lightfoot Plodder - EDITED
Based on the [Plodder](https://codegolf.stackexchange.com/a/36685/16766), this speedy behemoth is able to "fast forward" through consecutive 0's quickly until it reaches something nonzero (at which point it starts plodding as expected).
Now improved with a more robust skimming algorithm, which also allows fast-forwarding through small decoys, and bigger decoys of its own.
**Edit #2**: Now is able to go back to skimming if it finds more pockets of zeros.
```
>(-)*4
>(-)*7
>(-)*4
>(+)*7
>(-)*17
>(+)*3
> -
>(-)*10
>(+)*16[-]<-
([
[>>
[+
[--
[+++
[<+>(+)*14[-]]
]
]
]<-
]>>
[(+)*126(+.)*4>]
<]+)*10
```
[Answer]
# Reluctant Rán v2
The strategy is easy. Try to get the opponent to think her flag is a decoy and precede past the board and loose (a kind of tripwire / vibrator). After 10 full rounds she gives up and tries to determine if opponent is at her flag and if not she will make -17 decoys until she hits a set cell. The clearing method she uses is special case for [-12,12] and starts plodding similar to Loke.
```
>>-<< set a flag
(.)*11 wait for sixteenth step
((-)*256)*10 reduce by ten rounds
We give up check flags
> [(>)*7 detected fast rush mode
(-[>[
-[-[-[-[-[-[-[-[-[-[-[-[ from plus one to twelve
(+)*12 reduce by twelwe
+[+[+[+[+[+[+[+[+[+[+[+[ from minus one to twelve
(+)*66..(+)*41(+.)*17> increase and plod
]]]]]]]]]]]]]]]]]]]]]]]]]-])*3
](-)*31
>+[(>)*6 detected fast rush mode
(-[>[
-[-[-[-[-[-[-[-[-[-[-[-[ from plus one to twelve
(+)*12 reduce by twelwe
+[+[+[+[+[+[+[+[+[+[+[+[ from minus one to twelve
(+)*66..(+)*41(+.)*17> increase and plod
]]]]]]]]]]]]]]]]]]]]]]]]]-])*3
](-)*21
[>[ propably a trapper so we move slow
..+..-(+)*119(+.)*17 plodd the first cell so we dont go to zero on low positive
([>[
-[-[-[-[-[-[-[-[-[-[-[-[ from plus one to twelve
(+)*12 reduce by twelwe
+[+[+[+[+[+[+[+[+[+[+[+[ from minus one to twelve
(+)*66..(+)*41(+.)*17> increase and plod
]]]]]]]]]]]]]]]]]]]]]]]]]-]-)*3
](-)*17
]
```
Trivia: Rán is a Nordic Mythology sea goddess that takes sailors before they die at sea.
[Answer]
# [Mickey V4](https://github.com/westonized/brain-fuck-java)
For V4 I used the same method as V3, against the updated bots but with more concurrent populations (30 not 10).
Developed against all 60 bots, including `BurlyBalderV3` and `LethalLoke` (but excluding 2botsonecup which is uncompilable by my strict implementation).
I discovered wildly different bots and success rates if I started with different random seeds. So I decided to separate these different starting points into populations and let them occasionally cross-pollinate.
In 1400 generations, 30 concurrently evolving populations created this program:
```
++>------>->---<<<------------->------>->
---->------------->>--->------<----------
------<------<-<<--<------------->-------
-<-->------>------->----------->---------
----->-------->------->----------------[>
[--[-[+]]]>[--[+]]-]-------[>[--[-[+]]]>[
--[+]]-]<--<------>------->--------------
--[>[--[-[+]]]>[--[+]]-]<--<-------------
--------->------>->-<-----
```
I calculate the win rate of this bot to be **90.0%** against the current crop. (1135/125/0 tape lengths won/lost/drawn).
## V3 info
Calculated win rate of 89.2% (1124/62/74 tape lengths won/lost/drawn).
## V2 info
The generation program now has analysis to tell which part of the end of the program is unused and trims it before generating the next generations from it. This means that random mutations happen in used parts of the program only and so evolution is faster.
72% against the current crop at the time. (892/204/143 tape lengths won/lost/drawn).
## V1 info
31500 generations, only 12 bots faced. 65% (165/80/7 tape lengths won/lost/drawn). I use all 21 tape lengths.
Potential bots are ranked by:
* most wins then;
* most draws then;
* quickest time drawn then;
* quickest time won
## Trivia
* Mickey is named after my cat and;
* To paraphrase T.S. Elliot: `The Naming of Cats is a difficult matter,
It isn't just one of your brainfuck bots`
* My java bf vm and genetic algorithm is on [github](https://github.com/westonized/brain-fuck-java).
* The vm is capable of running a complete tournament in under 4 seconds on a single core of an i7 (caution - results are not always identical to the tournaments engine).
[Answer]
# Gambler
This is closely related to my Geronimo bot. But where Geronimo is playing a sure thing, the Gambler tries to be quicker by doing what it does best -- gambling: It goes to the 20th cell and starts zero-ing from there.
That means that it might easily lose just because the arena isn't that big. But if it is, it might be the few cycles that count.
```
(>)*19(>[-])*11
```
Fun Fact: I was really considering entering a bunch of bots which all look like `(>)*X(>[-])*Y` where `X in 9..29` and `Y = 30 - X`. But I think entering twenty bots would be a little too much :) Or even forty if I had two versions, one which zero-s with `[+]` and one that does it with `[-]`.
[Answer]
## Dumbot
A remarkably stupid bot that just messes with the environment and hopes that the bots it battles all go off the tape.
```
(+)*50(>-)*7(([.])*50(+)*50>)*7([-])*256
```
(I'm not sure if this even works - it doesn't error out though!)
Annotated (with what I *think* it does):
```
(+)*50 Increase home cell by 50
(>-)*7 For next 7 cells, decrement once
( Open loop
([.])*50 If cell is non-zero, do nothing. If cell is zero... Still do nothing? I'unno.
(+)*50 Now let's increment it fifty times for some reason.
>)*7 And let's do the above two instructions ten times more, in the next 7 cells
([-])*256 If the cell we're on is non-zero, decrement it continuously and hope it's the enemy.
```
(I will be staggered if this wins a single battle)
[Answer]
# CropCircleBot
```
[>>[+][-]-<[-][+]+][>[+][-]<[-][+]++]
```
This Bot uses advanced algorithms that were transmitted by aliens throu crop circles they placed on earth. It will change mankind and provide huge technological advancements and even solve many environmental problems.
[Answer]
# BeatYouMate
And because everybody should post a bot that will beat the first bot they post, here's a 5+ decoy laying bot:
```
(>------>+++++++)*4>([(+)*6[-]]>)*21
```
[Answer]
# CleverAndDetermined
```
>+>-(>+++[-])*21
```
Sets a few small traps, then races over to the other side, and tries to clear everything, above or below zero. Fails on `----`.
[Answer]
# MetaJSRandomBot
```
+[[>-[->+]>>[-]>-<<[>][+]<]+<]->
```
The idea behind this bot is making something total random that is still a valid js code without too much uselessness. I wrote following code ([JSFiddle link](http://jsfiddle.net/flawr/wn5x831o/)) for generating it. Lets see how well it does=)
```
var nchars = 30;
var nbrack = 10;
var alphab = "+ - < >".split(' ');
var s = [];
for(var i=0;i<nchars;i++){
s.push(alphab[(Math.random()*alphab.length)|0]);
}
var ind1,ind2;
for(var i=0;i<nbrack;i++){
ind1 = (s.length*Math.random())|0;
s.splice(ind1,0,'[');
ind2 = ((s.length-ind1-1)*Math.random())|0 + ind1;
s.splice(ind2,0,']');
}
s = s.join('')
for(var i=0;i<Math.max(nchars,nbrack);i++){//remove useless stuff
s=s.replace('[]','');
s=s.replace('+-','+');
s=s.replace('-+','-');
s=s.replace('<>','');
s=s.replace('><','');
}
alert(s);
```
[Answer]
# Prussian Roulette
Russian Roulette made a bet with his friend Prussian, and now it's his turn to play.
```
>(+)*5(-.[>.[>(-)*10]]>>)*1000
```
[Answer]
# Bigger
**The arms race begins!!**
Both builds and destroys walls of height ~~16~~ 18, bigger than most competitors. Also has a little logic to beat the cloaker, flag-defenders, anti-alternators, and bots that assume an untouched flag
```
+>->+>+>-(>(-)*18>(+)*18)*2(>([(+)*18[-][-[+]]])*2)*21
```
## Annotated version
```
Off by one
==========
Adjust own flag a little for fun
-
Decoy stage
===========
Build decoys
>->+>+>- Add four quick walls to deter rushers
Also throw off bots depending on the alternation
(>(-)*18
>(+)*18)*2 Build four large decoys
Clear stage
===========
( Repeat the following forever:
> Move forward
([ Skip if the space is zeroed already
(+)*18 Bust negative decoys smaller than 18
[-] Clear
[-[+]] Check that the wall is actually cleared; if it isn't,
clear in the opposite direction to defeat bots that try
to sense our clear direction and defend the flag
])*2 Repeat the "non-zero" check to guard against the cloaker
)*21
```
[Answer]
# PatientBot
A partly serious bot.
this bot will attempt winning by the 100000 cycles limit.
it will go to the enemy flag while putting a few traps in the way, decrease it a bit, go back and defend the flag.
```
>++>->->+>+>->->+(>+[-[-[(<)*9--[<--](+)*10000]]])*20
```
it will assume everything bigger than 1 or smaller than -1 is the flag, and when it will encounter one, it will go back.
it defends by simply incrementing constantly. this assumes most programs will either use [] to check if the flag became 0, and so (+)\*100000 will be much faster
**Edit:** can't get it to work on the BF Joust interpreter. i'm giving up. maybe you should tell me how to improve my code.
**Edit:** now the bot makes the spot just before the flag 2, and after it decremented the flag a bit, it searches for a 2. this is meant to cancel the scenario where the bot would find a 0 cell other than the one before the flag.
] |
[Question]
[
Yes, really. **Print** it with a hardware printer üñ® to create a hard copy.
Send the necessary commands/data to your printer such that the following text is printed on a piece of paper:
>
> Hello, World!
>
>
>
You may use any local- or network-connected printer that is available to you.
If your printer allows, you should use 8pt or greater text in black ink on white paper.
The text should appear on its own line. It may be left or right positioned as you wish.
Digital photographic/video/GIF evidence of submissions will be helpful.
If your hardware cannot do paper, but allows other exotic hardcopy production such as 3D printing, CNC machining, or [printing at the atomic level](https://en.wikipedia.org/wiki/IBM_(atoms)), then I will happy to accept such interesting submissions.
---
To clarify, the question asks *"Send the necessary commands/data to your printer"*. The implication of this is that no further user input should be required. Opening a print dialog is not sufficient. Existing answers that do this as of 10:48am PST 31st Dec 2016 will be grandfathered (but not upvoted by me).
[Answer]
## Bash, ~~21~~ 19 bytes
```
lp<<<Hello,\ World!
```
[![actual printout](https://i.stack.imgur.com/IFr2a.jpg)](https://i.stack.imgur.com/IFr2a.jpg)
And there it is.
2 bytes saved thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 18 bytes
```
'Hello, World!'|lp
```
[Try it online!](https://tio.run/nexus/powershell#@6/ukZqTk6@jEJ5flJOiqF6TU/D/PwA "PowerShell – TIO Nexus")
[![enter image description here](https://i.stack.imgur.com/KWyJM.png)](https://i.stack.imgur.com/KWyJM.png)
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 11 bytes
```
'LPRINT `_h
```
Almost forgot I built a 'Hello, World!' command into QBIC...
```
' Starts a code literal. This used to be "$", finally changed it.
LPRINT ` Feeds everything from ` to the next ` directly to QBasic.
In this case, "LPRINT" and a space
_h Yields "Hello, World!"
```
Tested and found working identical to my QBasic answer:
[![enter image description here](https://i.stack.imgur.com/LPfJV.png)](https://i.stack.imgur.com/LPfJV.png)
[Answer]
# Batch, 22 bytes
```
echo Hello, World!>prn
```
This redirects the output of the `echo` command to the [device file PRN](https://en.wikipedia.org/wiki/Device_file#DOS.2C_OS.2F2.2C_and_Windows), meaning that it's sent directly to the default printer (usually LPT1).
I neither have a DOS machine nor a printer, so I'm afraid I can't test this right now, but I'm fairly certain I've done this back in the day. It doesn't work on Windows XP or later.
[Answer]
# Python 2.7, 43 bytes
```
import os;os.system("lp<<<'Hello, World!'")
```
Not very interesting, though. Here's a more interesting one:
```
import zlib,base64,os;os.system("s=$'%s';lp<<<\"$s\""%zlib.decompress(base64.decodestring("eNqVkk1qxDAMha/yupNgwNfoDboReDPdhQRmrcNXP3bixA3tGEMesj/r5wXoq+YysUemI0BWlYgV\npTyAEDKEQSDucxLxJaj6gUVKE8BFsH2TIOM5iMyrcTIL3YnMqCH4X0TLONTwF3H04Z0XuRPeR3Wi\nxDOi1EZY7gUTWFa8s+z5kTgcnK3sBtbZQRtCt5LPDlrliKouDh5DYz07KB6COuETUL/YRthGxHqZ\nbjyWBAU8EFk6z350Yt97Dol65hxUow9i3zr8YGxFS61nB4szPqvDnS7CU/nFwYLIYczn97JsD3xt\nr+X5wT/ARNN3\n")))
```
Seems a bit too long? Perhaps it's a bit overcomplicated.... :P
[![A lot of hello world](https://i.stack.imgur.com/GWzSg.jpg)](https://i.stack.imgur.com/GWzSg.jpg)
**Mod Note** edited the competitive submission to the top for clarity.
[Answer]
# HTML + Javascript, ~~37~~ 34 bytes
```
<body onload=print()>Hello, World!
```
Tested in Safari:
[![enter image description here](https://i.stack.imgur.com/rHEoF.png)](https://i.stack.imgur.com/rHEoF.png)
Thanks to [@jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013) for some savings.
[Answer]
# hello + lp + tr, ~~9~~ 15 bytes
```
hello|tr w W|lp
```
I originally had
```
hello|lp
```
But it had the wrong capitalisation on the `w`
`hello` is GNU hello from the Debian package [hello](https://packages.debian.org/sid/hello)
[Answer]
## ZX Spectrum BASIC, 16 bytes
```
LPRINT "Hello, World!"
```
`LPRINT` is a 1-byte keyword in ZX Spectrum BASIC, having codepoint 224.
[Answer]
# MATLAB, ~~40~~ ~~37~~ 36 bytes
Printing text is not something you'd normally do in Matlab, but it can be done.
```
title 'Hello, World!'
axis off;print
```
I saved 3 bytes thanks to Tom Carpenter (use `title` instead of `text(0,0,`. I saved an additional 2 bytes by substiting `title('Hello, World!') with` title 'Hello, World!' followed by a newline instead of a semicolon.
[`title`](https://se.mathworks.com/help/matlab/ref/title.html) adds a title to a figure. If a figure is not yet open, it will be created.
[`axis off`](https://se.mathworks.com/help/matlab/ref/axis.html) is used to get rid of the frame and axes, so that the text appears alone.
[`print`](https://se.mathworks.com/help/matlab/ref/print.html) prints the current figure to the default printer if no input arguments are given.
I printed this (successfully according to the dialog box) on my default printer at the office. I can retrieve it there and prove it but you'll have to wait two weeks. After changing the default to a pdf-printer, this is the output:
[![enter image description here](https://i.stack.imgur.com/EyOOB.png)](https://i.stack.imgur.com/EyOOB.png)
^^ Not the correct image anymore.
[Answer]
## QBasic, 21 bytes
```
LPRINT"Hello, World!"
```
`LPRINT` sends text directly to the printer. Unfortunately untested, DosBox doesn't natively support `NET USE`, so I can't reroute `LPT1:` to NovaPDF.
The problems I have...
UPDATE: Tested it in QB64. Resulting PDF opened in Microsoft Edge. Looks like this:
[![enter image description here](https://i.stack.imgur.com/rs79e.png)](https://i.stack.imgur.com/rs79e.png)
[Answer]
# 8086 machine code, 28 bytes
```
00000000 be 0f 01 b9 0d 00 31 d2 ac 98 cd 17 e2 fa c3 48 |......1........H|
00000010 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 |ello, World!|
0000001c
```
Uses the standard `int 0x17` BIOS call. I don't have my dot-matrix printer set up right now so this code is untested.
How it works:
```
| org 0x100
| use16
be 0f 01 | mov si, msg ; source pointer = msg
b9 0d 00 | mov cx, 13 ; counter = length of msg
31 d2 | xor dx, dx ; clear dx
ac | @@: lodsb ; al = *si++
98 | cbw ; sign-extend al->ax (simply clears ah)
cd 17 | int 0x17 ; send char in al to printer dx
e2 fa | loop @b ; loop while (cx-- > 0)
c3 | ret
48 65 6c | msg db "Hello, World!"
6c 6f 2c |
20 57 6f |
72 6c 64 |
21 |
```
[Answer]
# Stuck + Batch, 5 bytes
Inspired by [this answer](https://codegolf.stackexchange.com/a/55425/56477) an empty **stuck** program prints "Hello, World!".
1. Have a printer connected to your computers LPT1 port
2. Create an empty stuck file to be interpreted (filename a)
3. Run the stuck interpretter on the empty file and pipe the result to LPT1
## Code
```
stuck a>LPT1
```
[Answer]
# Java, 330 bytes
Golfed:
```
import java.awt.print.*;void f()throws Throwable{PrinterJob job=PrinterJob.getPrinterJob();job.setPrintable(new Printable(){public int print(java.awt.Graphics g,PageFormat f,int i){if(i==0){((java.awt.Graphics2D)g).translate(f.getImageableX(),f.getImageableY());g.drawString("Hello, World!",0,90);}return i>0?1:0;}});job.print();}
```
Ungolfed (import plus function only):
```
import java.awt.print.*;
void f() throws Throwable {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new Printable() {
public int print(java.awt.Graphics g, PageFormat f, int i) {
if (i == 0) {
((java.awt.Graphics2D) g).translate(f.getImageableX(), f.getImageableY());
g.drawString("Hello, World!", 0, 90);
}
return i > NO_SUCH_PAGE ? 1 : PAGE_EXISTS;
}
});
job.print();
}
```
Java is not a great golfing language, and certain does an exceptionally poor job golfing *anything* hardware-related, printing included.
While testing this program, I set my PDF printer as the default. It worked, but also sent a print job to my laser printer containing 87,792 pages of "Hello, World!" I pulled the paper tray and canceled the job, then retested. It did not happen again. Thanks, Windows 10.
[Answer]
## GFA-Basic, 22 bytes
Only tested on an Atari ST emulator with the parallel port redirected to a file. It should work on the [Windows version of GFA-Basic](http://gfabasic32.blogspot.fr/) (which is free), but this is untested.
```
LPRINT "Hello, World!"
```
*Note:* This turns out to be identical to the [QBasic](https://codegolf.stackexchange.com/a/105125/58563) syntax.
[Answer]
# Mathematica, 29 bytes
```
NotebookPrint@"Hello, World!"
```
[![enter image description here](https://i.stack.imgur.com/Rqrjj.png)](https://i.stack.imgur.com/Rqrjj.png)
[Answer]
## JavaScript, 37 36 bytes
```
print(document.write`Hello, World!`)
```
*Saved 15 bytes thanks to @manatwork and @xem!*
[Answer]
## c#, ~~259~~ 250 bytes
```
using System.Drawing;using System.Drawing.Printing;struct p{static void Main(){var p=new PrintDocument();p.PrintPage+=(s,e)=>e.Graphics.DrawString("Hello,World!",new Font("Arial",12),new SolidBrush(Color.Black),new Rectangle(0,0,999,99));p.Print();}}
```
[Example output](http://swdev.co.za/ftp/hello.pdf)
[Answer]
## Batch, 32 bytes
```
echo Hello, World!>t
notepad/P t
```
Should work on all versions of windows with no manual intervention required.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 50 bytes
Of course we could shell out and use a Batch/Bash solution, but let us instead create a real print job:
```
{'X.'⎕WC'Text' 'Hello, World!'⍵⊣'X'⎕WC'Printer'}⍳2
```
`‚éïWC`‚ÄÉis **W**indows **C**reate object
First we create a printer object (a print job) called `'X'`, then (`⊣`) in that (`'X.'`) we create a text object at `⍵` the argument of the anonymous function `{`…`}`. The argument is `⍳2`, which gives the first two integers (`1 2`) and means 1% from the top and 2% from the left. When the anonymous function terminates, all its local variables (`X`) are destroyed, which signals to Windows that the print job is ready to be printed:
---
## Print job
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
IO.write(?l,"Hello, World!");`lpr<<?l`
```
For Mac and Linux, your default printer must be set at [localhost:631](http://localhost:631).
For Windows, you need to add an lpr port in your printer settings.
[Answer]
## Racket 35 bytes
```
(system("echo 'Hello World!'\|lp"))
```
[Answer]
# ZPL ([Zebra Programming Language](https://en.wikipedia.org/wiki/Zebra_(programming_language))), 25 bytes
**Code:**
```
^XA^FDHello, World!^XZ~PS
```
**[Try it online!](http://labelary.com/viewer.html?density=6&width=1&height=1&units=inches&index=0&zpl=%5EXA%5EFDHello%2C%20World!%5EXZ%7EPS)**
**Explanation:**
```
^XA # Start Format
^FDHello, World! # Field Data "Hello, World!"
^XZ # End Format
~PS # Print Start
```
[Answer]
# Python 3 (Win32), 114 bytes
I used the win32api library to do this.
```
import win32api;open('h.txt', 'w').write('Hello, World!');win32api.ShellExecute(0, 'print', 'h.txt', None, '.', 0)
```
[Answer]
# Lua, 34 32 bytes
```
os.execute"lp<<<'Hello, World!'"
```
[Answer]
# HTML (33)
```
Hello, World!<svg onload=print()>
```
(Prompts a print window in the browser, doesn't print directly)
[Answer]
# JavaScript + HTML, 20 bytes
```
print()
```
```
Hello, World!
```
[Answer]
# C#, 174 bytes
```
namespace System.Drawing.Printing{_=>{var p=new PrintDocument();p.PrintPage+=(s,e)=>e.Graphics.DrawString("Hello, World!",new Font("Onyx",9),Brushes.Black,0,0);p.Print();};}
```
Full/Formatted version:
```
namespace System.Drawing.Printing
{
class P
{
static void Main(string[] args)
{
Action<float> f = _ =>
{
var p = new PrintDocument();
p.PrintPage += (s, e) =>
e.Graphics.DrawString("Hello, World!", new Font("Onyx", 9), Brushes.Black, 0, 0);
p.Print();
};
f(0);
}
}
}
```
[Answer]
## Javascript, 36 bytes
```
print(document.write`Hello, World!`)
```
] |
[Question]
[
What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.
---
If you are new to golfing in Haskell, please have a look at the **[Guide to Golfing Rules in Haskell](https://codegolf.meta.stackexchange.com/a/11935/56433)**. There is also a dedicated Haskell chat room: [Of Monads and Men](https://chat.stackexchange.com/rooms/66515/of-monads-and-men).
[Answer]
# Define infix operators instead of binary functions
This saves usually one or two spaces per definition or call.
```
0!(y:_)=y
x!(y:z)=(x-1)!z
```
vs.
```
f 0(y:_)=y
f x(y:z)=f(x-1)z
```
---
The available symbols for 1-byte operators are `!`, `#`, `%`, `&`, and `?`. All other ASCII punctuation is either already defined as an operator by the Prelude (such as `$`) or has a special meaning in Haskell's syntax (such as `@`).
If you need more than five operators, you could use combinations of the above, such as `!#`, or certain Unicode punctuation characters, such as these (all 2 bytes in UTF-8):
```
¡ ¢ £ ¤ ¥ ¦ § ¨ © ¬ ® ¯ ° ± ´ ¶ · ¸ ¿ × ÷
```
[Answer]
Use pointless (or -free) notation where appropriate
Often a function with one or two parameters can be written point free.
So a lookup for a list of tuples whose elements are swapped is naïvely written as:
```
revlookup :: Eq b => b -> [(a, b)] -> Maybe a
revlookup e l=lookup e(map swap l)
```
(the type is there just to help you understand what it's doing.)
for our purposes this is much better:
```
revlookup=(.map swap).lookup
```
[Answer]
Use guards not conditionals:
```
f a=if a>0 then 3 else 7
g a|a>0=3|True=7
```
Use semicolons not indents
```
f a=do
this
that
g a=do this;that
```
Use boolean expressions for boolean functions
```
f a=if zzz then True else f yyy
g a=zzz||f yyy
```
(SO is being a pain about letting me post these separately)
[Answer]
# Use the list monad
A quick review:
```
xs >> ys = concat $ replicate (length xs) ys
xs >>= f = concatMap f xs
mapM id[a,b,c] = cartesian product of lists: a × b × c
mapM f[a,b,c] = cartesian product of lists: f a × f b × f c
```
Examples:
* ### Repeating a list twice
```
Prelude> "aa">>[1..5]
[1,2,3,4,5,1,2,3,4,5]
```
* ### Shorter `concatMap`
```
Prelude> reverse=<<["Abc","Defgh","Ijkl"]
"cbAhgfeDlkjI"
```
* ### Shorter `concat` + list comprehension
```
Prelude> do x<-[1..5];[1..x]
[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5]
```
* ### Cartesian product
```
Prelude> mapM id["Hh","io",".!"]
["Hi.","Hi!","Ho.","Ho!","hi.","hi!","ho.","ho!"]
```
* ### List of coordinates on a lattice
```
Prelude> mapM(\x->[0..x])[3,2]
[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]]
```
[Answer]
# Use GHC 7.10
*The first version of GHC that contained this stuff was released on **March 27, 2015**.*
It's the latest version, and Prelude got some new additions that are useful for golfing:
## The `(<$>)` and `(<*>)` operators
These useful operators from `Data.Applicative` made it in! **`<$>` is just `fmap`, so you can replace `map f x` and `fmap f x` with `f<$>x` everywhere and win back bytes.** Also, `<*>` is useful in the `Applicative` instance for lists:
```
Prelude> (,)<$>[1..2]<*>"abcd"
[(1,'a'),(1,'b'),(1,'c'),(1,'d'),(2,'a'),(2,'b'),(2,'c'),(2,'d')]
```
## The `(<$)` operator
`x<$a` is equivalent to `fmap (const x) a`; i.e. replace every element in a container by `x`.
This is often a nice alternative to `replicate`: `4<$[1..n]` is shorter than `replicate n 4`.
## The Foldable/Traversable Proposal
The following functions got lifted from working on lists `[a]` to general `Foldable` types `t a`:
```
fold*, null, length, elem, maximum, minimum, sum, product
and, or, any, all, concat, concatMap
```
This means they now also work on `Maybe a`, where they behave just like "lists with at most one element". For example, `null Nothing == True`, or `sum (Just 3) == 3`. Similarly, `length` returns 0 for `Nothing` and 1 for `Just` values. Instead of writing `x==Just y` you can write `elem y x`.
You can also apply them on tuples, which works as if you'd called `\(a, b) -> [b]` first. It's almost completely useless, but `or :: (a, Bool) -> Bool` is one character shorter than `snd`, and `elem b` is shorter than `(==b).snd`.
## The Monoid functions `mempty` and `mappend`
Not often a life-saver, but if you can infer the type, `mempty` is one byte shorter than `Nothing`, so there's that.
[Answer]
Use `1<2` instead of `True` and `1>2` instead of `False`.
```
g x|x<10=10|True=x
f x|x<10=10|1<2=x
```
[Answer]
# `interact :: (String → String) → IO ()`
People often forget that this function exists - it grabs all of stdin and applies it to a (pure) function. I often see `main`-code along the lines of
```
main=getContents>>=print.foo
```
while
```
main=interact$show.foo
```
is quite a bit shorter. It is in the Prelude so no need for imports!
[Answer]
# Use list comprehensions (in clever ways)
Everyone knows they're useful syntax, often shorter than `map` + a lambda:
```
Prelude> [[1..x]>>show x|x<-[1..9]]
["1","22","333","4444","55555","666666","7777777","88888888","999999999"]
```
Or `filter` (and optionally a `map` at the same time):
```
Prelude> [show x|x<-[1..60],mod 60x<1]
["1","2","3","4","5","6","10","12","15","20","30","60"]
```
But there are some weirder uses that come in handy now and then. For one, a list comprehension doesn't need to contain any `<-` arrows at all:
```
Prelude> [1|False]
[]
Prelude> [1|True]
[1]
```
Which means instead of `if p then[x]else[]`, you can write `[x|p]`. Also, to count the number of elements of a list satisfying a condition, intuitively you would write:
```
length$filter p x
```
But this is shorter:
```
sum[1|y<-x,p y]
```
[Answer]
## Match a constant value
A list comprehension can pattern match on a constant.
---
```
[0|0<-l]
```
This extracts the 0's of a list `l`, i.e. makes a list of as many 0's as are in `l`.
---
```
[1|[]<-f<$>l]
```
This makes a list of as many `1`'s as there are elements of `l` that `f` takes to the empty list (using `<$>` as infix `map`). Apply `sum` to count these elements.
Compare:
```
[1|[]<-f<$>l]
[1|x<-l,f x==[]]
```
---
[Answer]
# Know your `Prelude`
Fire up GHCi and scroll through the [Prelude documentation](https://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html). Whenever you cross a function that has a short name, it can pay off to look for some cases where it might be useful.
For example, suppose you wish to transform a string `s = "abc\ndef\nghi"` into one that's space-separated, `"abc def ghi"`. The obvious way is:
```
unwords$lines s
```
But you can do better if you abuse `max`, and the fact that `\n < space < printable ASCII`:
```
max ' '<$>s
```
Another example is [`lex :: String -> [(String, String)]`](https://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html#v:lex), which does something quite mysterious:
```
Prelude> lex " some string of Haskell tokens 123 "
[("some"," string of Haskell tokens 123 ")]
```
Try `fst=<<lex s` to get the first token from a string, skipping whitespace. [Here](http://golf.shinh.org/reveal.rb?Divide+section/henkma_1292522156&hs) is a clever solution by henkma that uses `lex.show` on `Rational` values.
[Answer]
# Arguments can be shorter than definitions
I just got outgolfed in a very curious way by [henkma](http://golf.shinh.org/reveal.rb?String+in+String+in+String/henkma_1487067285&hs).
If an auxiliary function `f` in your answer uses an operator that isn’t used elsewhere in your answer, and `f` is called once, make the operator an argument of `f`.
This:
```
(!)=take
f a=5!a++3!a
reverse.f
```
Is two bytes longer than this:
```
f(!)a=5!a++3!a
reverse.f take
```
[Answer]
Use `words` instead of a long list of strings. This isn't really specific to Haskell, other languages have similar tricks too.
```
["foo","bar"]
words"foo bar" -- 1 byte longer
```
```
["foo","bar","baz"]
words"foo bar baz" -- 1 byte shorter
```
```
["foo","bar","baz","qux"]
words"foo bar baz qux" -- 3 bytes shorter
```
[Answer]
## Shorter conditional
```
last$x:[y|b]
```
is equivalent to
```
if b then y else x
```
Here's how it works:
```
[y|b] x:[y|b] last$x:[y|b]
if... +--------------------------------
b == False | [] [x] x
b == True | [y] [x,y] y
```
[Answer]
# Know your monadic functions
1)
simulate monadic functions using `mapM`.
a lot of times code will have `sequence(map f xs)`, but it can be replaced with `mapM f xs`. even when just using `sequence` alone it is longer then `mapM id`.
2)
combine functions using `(>>=)` (or `(=<<)`)
the function monad version of `(>>=)` is defined as so:
```
(f >>= g) x = g (f x) x
```
it can be useful for creating functions which can't be expressed as a pipeline. for example, `\x->x==nub x` is longer than `nub>>=(==)`, and `\t->zip(tail t)t` is longer than `tail>>=zip`.
[Answer]
# Shorter conditionals when one outcome is the empty list
When you need a conditional which returns the list `A` or the empty list `[]` depending on some condition `C`, then there exist some shorter alternatives to the usual conditional constructs:
```
if(C)then(A)else[] -- the normal conditional
last$[]:[A|C] -- the golfy all-round-conditional
concat[A|C] -- shorter and works when surrounded by infix operator
id=<<[A|C] -- even shorter but might conflict with other infix operators
[x|C,x<-A] -- same length and no-conflict-guarantee™
[0|C]>>A -- shortest way, but needs surrounding parenthesis more often than not
do[0|C];A -- longer but works in some places where the above would need parents
```
Examples: [1](https://codegolf.stackexchange.com/a/150747/56433), [2](https://codegolf.stackexchange.com/a/150784/56433)
[Answer]
## Don't waste the "otherwise" guard
A final guard that's a catch-all `True` (shorter as `1>0`) can be used to bind a variable. Compare:
```
... |1>0=1/(x+y)
... |z<-x+y=1/z
... |1>0=sum l-sum m
... |s<-sum=s l-s m
```
Since the guard is mandatory and is otherwise wasted, little is needed to make this worth it. It's enough to save a pair of parens or bind a length-3 expression that's used twice. Sometimes you can negate guards to make the final case be the expression that best uses a binding.
[Answer]
# Use the cons operator (:)
when concatenating lists, if the first is of length 1 then use `:` instead.
```
a++" "++b
a++' ':b -- one character shorter
[3]++l
3:l -- three characters shorter
```
[Answer]
Don't use backticks too often.
Backticks are a cool tool for making sections of prefix functions, but can sometimes be misused.
Once I saw someone write this subexpression:
```
(x`v`)
```
Although it is the same as just `v x`.
Another example is writing `(x+1)`div`y`
as opposed to `div(x+1)y`.
I see it happen around `div` and `elem` more often because these functions are usually used as infix in regular code.
[Answer]
# Use [pattern guards](https://wiki.haskell.org/Pattern_guard)
They're shorter than a `let` or a lambda that deconstructs the arguments of a function you're defining. This helps when you need something like `fromJust` from `Data.Maybe`:
```
f x=let Just c=… in c
```
is longer than
```
f x=(\(Just c)->c)$…
```
is longer than
```
m(Just c)=c;f x=m$…
```
is longer than
```
f x|Just c<-…=c
```
In fact, they’re shorter even when binding a plain old value instead of deconstructing: see [xnor’s tip](https://codegolf.stackexchange.com/a/76749/3852).
[Answer]
# Use GHC 8.4.1 (or later)
With the [Semigroup Monoid Proposal](https://prime.haskell.org/wiki/Libraries/Proposals/SemigroupMonoid) and the release of [GHC 8.4.1](https://downloads.haskell.org/%7Eghc/8.4.1/docs/html/users_guide/8.4.1-notes.html), `Semigroup` has been moved to the `Prelude`. This gives us:
```
(<>) :: Semigroup a => a -> a -> a
```
Now these might seem useless at first glance, but looking closer we notice that `Monoid a => (x -> a)` is an instance of `Monoid`1, in which case we have the implementation:
```
(f <> g) xs = f xs <> g xs
```
This can be quite useful with for example lists, knowing that `(<>)` is the same as `(++)` for lists. So we have for example:
```
(init <> reverse) [1,2,3] ≡ init [1,2,3] <> reverse [1,2,3]
≡ [1,2] <> [3,2,1]
≡ [1,2] ++ [3,2,1]
≡ [1,2,3,2,1]
```
However, this is not the only useful case: Knowing that `[x] -> [x]` is an instance of `Monoid`, we also have `a -> [x] -> [x]` an instance of `Monoid` (you can iterate this as many times as you want):
```
(drop <> take) 2 [1,2,3,4,5] ≡ (drop 2 <> take 2) [1,2,3,4,5]
≡ drop 2 [1,2,3,4,5] <> take 2 [1,2,3,4,5]
≡ [3,4,5] <> [1,2]
≡ [3,4,5,1,2]
```
1: Note that `Monoid a` \$\implies\$ `Semigroup a`.
## Overview what we gained so far
Using this trick we have these (not exhaustive) helpers, note that we can chain them:
```
duplicate = id <> id
triple² = id <> id <> id
palindromize = init <> reverse
rotateLeft = drop <> take
removeElementAt = take <> drop . succ
removeNElementsAt n = take <> drop . (+n)
```
2: This could ~~also be `([1..3]>>)` for the same bytecount~~ be shorter (see comment by [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen)).
## Where are the \$(\mathbb{Z},\texttt{+})\$ and \$(\mathbb{Z},\texttt{\*})\$ monoids?
If we want to use the \$(\mathbb{Z},\texttt{+})\$ monoid, we need to tell GHC that. It can not decide for us which one it should use, therefore there are two `newtype`s which allow this - `Sum` and `Product`.
Given that the consensus is [to allow implicitly typed functions](https://codegolf.meta.stackexchange.com/questions/11223/untyped-functions-in-static-languages/12747#12747), we are probably allowed to do so if the challenge does not talk about a specific implementation for integers. Using this we can for example write \$n\$th [oblong number](https://oeis.org/A002378) as
```
id<>(+1)
```
which is shorter than `f n=n*(n-1)` or even `(*)=<<succ`/`(*)<*>succ`.
[Try it online!](https://tio.run/##XY8xT8NADIX3@xVPVYdEkFO7RmkmFoYKpA4MBCHT3KUnkjvr4gj1zxOutBlgsAe/7/nZJxo/Td/PbuAQBQ8kpPfBB9ciw3MM7XSUTOv8HllV58iVUhZluUh49GI6E1HU/0fK7prZtVWd3W3zeSDnsUMbFFAUeInEcFdwBI2LuZAzG5BvQcz9GTbhA/H@HRnHxEPDprrROV43Wm83b@q69UCDwcckoH4MmPzXJUVOZoANERyNiEu3hkl4kmRJ/SARq8Y/xRvOpi0bWV3E37w1OiPLZ3/CUa3rJX/@PtqeunEujsw/ "Haskell – Try It Online")3
3: Note that we need to use `(+1)` and cannot use `succ` since GHC can't know that there is an instance of `Enum`.
## Other noteworthy related tricks
Instances that might be useful not covered above:
```
()
Ordering
(Monoid a, Monoid b) => Monoid (a,b) -- (also 3-,4- and 5-tuples)
Monoid a => Monoid (IO a)
Ord k => Monoid (Map k v) -- from Data.Map
```
---
It might be worth noting that there is `mconcat` too:
```
mconcat [f1,f2,…,fN] ≡ f1 <> f2 <> … <> fN
```
This will probably not be useful often, for it needs at least \$3-11\$ functions (depending on the need of parentheses, see comments), but it might be in case you have some list `Monoid a => [a]` already.
---
Furthermore `mempty` can be useful since it is shorter than `Nothing` or even `pure Nothing`, `([],[])` etc.
---
Another useful instance is `Monoid a => Monoid (IO a)` which has successfully been used for the currently [shortest quine](https://codegolf.stackexchange.com/a/161036/48198) as
```
(putStr <> print) "foo" ≡ putStr "foo" <> print "foo"
≡ do x <- putStr "foo"
y <- print "foo"
pure $ x <> y
≡ do putStr "foo"
print "foo"
pure ()
≡ putStr "foo" >> print "foo"
```
[Answer]
# Shorter syntax for local declarations
Sometimes you need to define a local function or operator, but it costs lots of bytes to write `where` or `let…in` or to lift it to top-level by adding extra arguments.
```
g~(a:b)=2!g b where k!l=k:take(a-1)l++(k+1)!drop(a-1)l
g~(a:b)=let k!l=k:take(a-1)l++(k+1)!drop(a-1)l in 2!g b
g~(a:b)=2!g b$a;(k!l)a=k:take(a-1)l++((k+1)!drop(a-1)l)a
```
Fortunately, Haskell has a confusing and seldom-used but reasonably terse syntax for [local declarations](https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-460003.13):
```
fun1 pattern1 | let fun2 pattern2 = expr2 = expr1
```
In this case:
```
g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b
```
You can use this syntax with multi-statement declarations or multiple declarations, and it even nests:
```
fun1 pattern1 | let fun2 pattern2 = expr2; fun2 pattern2' = expr2' = expr1
fun1 pattern1 | let fun2 pattern2 = expr2; fun3 pattern3 = expr3 = expr1
fun1 pattern1 | let fun2 pattern2 | let fun3 pattern3 = expr3 = expr2 = expr1
```
It also works for binding variables or other patterns, though [pattern guards](https://codegolf.stackexchange.com/a/54684/39242) tend to be shorter for that unless you’re also binding functions.
[Answer]
# Lambda parsing rules
A lambda-expression doesn't actually need parentheses around it - it just rather greedily grabs everything so the whole thing still parses, e.g. until
* a closing paren - `(foo$ \x -> succ x)`
* an in - `let a = \x -> succ x in a 4`
* the end of the line - `main = getContents>>= \x -> head $ words x`
* etc..
is encountered, and there are some weird edge-cases where this can save you a byte or two. I believe `\` can also be used to define operators, so when exploiting this you will need a space when writing a lambda directly after an operator (like in the third example).
[Here is an example](https://codegolf.stackexchange.com/questions/32757/etaoin-shrdlu-golf/32771#32771) of where using a lambda was the shortest thing I could figure out. The code basically looks like:
```
a%f=...
f t=sortBy(% \c->...)['A'..'Z']
```
[Answer]
## Working with the minus sign
The minus sign `-` is an annoying exception to many syntax rules.
This tip lists some short ways of expressing negation and subtraction in Haskell.
Please let me know if I've missed something.
### Negation
* To negate an expression `e`, just do `-e`. For example, `-length[1,2]` gives `-2`.
* If `e` is even moderately complex, you will need parentheses around `e`, but you can usually save a byte by moving them around: `-length(take 3 x)` is shorter than `-(length$take 3 x)`.
* If `e` is preceded by `=` or an infix operator of [fixity](https://www.haskell.org/onlinereport/decls.html#fixity) less than 6, you need a space: `f= -2` defines `f` and `k< -2` tests if `k` is less than `-2`. If the fixity is 6 or greater, you need parens: `2^^(-2)` gives `0.25`. You can usually rearrange stuff to get rid of these: for example, do `-k>2` instead of `k< -2`.
* Similarly, if `!` is an operator, then `-a!b` is parsed as `(-a)!b` if the fixity of `!` is at most 6 (so `-1<1` gives `True`), and `-(a!b)` otherwise (so `-[1,2]!!0` gives `-1`). The default fixity of user-defined operators and backticked functions is 9, so they follow the second rule.
* To turn negation into a function (to use with `map` etc), use the section `(0-)`.
### Subtraction
* To get a function that subtracts `k`, use the section `(-k+)`, which adds `-k`. `k` can even be a pretty complex expression: `(-2*length x+)` works as expected.
* To subtract 1, use `pred` instead, unless it would require a space on both sides. This is rare and usually happens with `until` or a user-defined function, since `map pred x` can be replaced by `pred<$>x` and `iterate pred x` by `[x,x-1..]`. And if you have `f pred x` somewhere, you should probably define `f` as an infix function anyway. See [this tip](https://codegolf.stackexchange.com/a/19259/32014).
[Answer]
## Try rearranging function definitions and/or arguments
You can sometimes save a couple of bytes by changing the order of pattern-matching cases in a function definition.
These savings are cheap, but easy to overlook.
As an example, consider the following earlier version of (a part of) [this answer](https://codegolf.stackexchange.com/a/58605/32014):
```
(g?x)[]=x
(g?x)(a:b)=g(g?x$b)a
```
This is a recursive definition of `?`, with the base case being the empty list.
Since `[]` is not a useful value, we should swap the definitions and replace it with the wildcard `_` or a dummy argument `y`, saving a byte:
```
(g?x)(a:b)=g(g?x$b)a
(g?x)y=x
```
From the same answer, consider this definition:
```
f#[]=[]
f#(a:b)=f a:f#b
```
The empty list occurs in the return value, so we can save two bytes by swapping the cases:
```
f#(a:b)=f a:f#b
f#x=x
```
Also, the order of function arguments can sometimes make a difference by allowing you to remove unnecessary whitespace. Consider an earlier version of [this answer](https://codegolf.stackexchange.com/a/60833/32014):
```
h p q a|a>z=0:h p(q+2)(a-1%q)|1<2=1:h(p+2)q(a+1%p)
```
There's an annoying piece of whitespace between `h` and `p` in the first branch.
We can get rid of it by defining `h a p q` instead of `h p q a`:
```
h a p q|a>z=0:h(a-1%q)p(q+2)|1<2=1:h(a+1%p)(p+2)q
```
[Answer]
## Use `,` instead of `&&` in guards
Multiple conditions in a guard that all have to hold can be combined with `,` instead of `&&`.
```
f a b | a/=5 && b/=7 = ...
f a b | a/=5 , b/=7 = ...
```
[Answer]
# Avoid `repeat n`
```
-- 8 bytes, whitespace might be needed before and after
repeat n
-- 8 bytes, whitespace might be needed before
cycle[n]
-- 7 bytes, whitespace might be needed before and after, can be reused,
-- needs an assignment, n needs to be global
l=n:l;l
-- 7 bytes, never needs whitespace, n needs to derive from Enum,
-- n has to be short enough to be repeated twice
[n,n..]
```
Either of those four expressions will produce an infinite list of `n`'s.
It's a very specific tip but it can save up to **3** bytes!
[Answer]
## Get suffixes
Use `scanr(:)[]` to get the suffixes of a list:
```
λ scanr(:)[] "abc"
["abc","bc","c",""]
```
This is much shorter than `tails` after `import Data.List`. You can do prefixes with `scanr(\_->init)=<<id` (found by Ørjan Johansen).
```
λ scanr(\_->init)=<<id $ "abc"
["","a","ab","abc"]
```
This saves a byte over
```
scanl(\s c->s++[c])[]
```
[Answer]
## Bind using guards
When defining a named function, you can bind an expression to a variable in a guard. For example,
```
f s|w<-words s=...
```
does the same as
```
f s=let w=words s in ...
f s=(\w->...)$words s
```
Use this to save on repeated expressions. When the expression is used twice, it breaks even at length 6, though spacing and precedence issues can change that.
(In the example, if the original variable `s` is not used, it's shorter to do
```
g w=...
f=g.words
```
but that's not true for binding more complex expressions.)
[Answer]
# Use `(0<$)` instead of `length` for comparisons
When testing if a list `a` is longer than a list `b`, one would usually write
```
length a>length b
```
However replacing each element of both lists with same value, e.g. `0`, and then comparing those two lists can be shorter:
```
(0<$a)>(0<$b)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1HBViHaUMdIxziWKwnKjuXKTczMA3JS8rkUCooy80oUVBRyUvPSSzIUEu2gjCSElIaBjUqiph2IStL8/x8A "Haskell – Try It Online")
The parenthesis are needed because `<$` and the comparison operators (`==`, `>`, `<=`, ...) have the same precedence level 4, though in some other cases they might not be needed, saving even more bytes.
[Answer]
# Shorter `transpose`
To use the `transpose` function `Data.List` has to be imported. If this is the only function needing the import, one can save a byte using the following `foldr` definition of `transpose`:
```
import Data.List;transpose
e=[]:e;foldr(zipWith(:))e
```
Note that the behaviour is only identical for a list of lists with the same length.
I successfully used this [here](https://codegolf.stackexchange.com/a/106587/56433).
] |
[Question]
[
Write a program that prints its own source code out backwards, in other words an *eniuq*.
**Scoring:**
* +50 if you use pull data from the Internet.
* +25 if you read your own source code.
* +1 point per character
* Lowest score wins.
**Rules:**
* No using other files (e.g. `reverse.txt`)
* Minimum code length is two characters.
* **Your program cannot be a palindrome.**
[Answer]
## [huh?](http://esolangs.org/wiki/Huh%3F), 5 characters
```
!hcuO
```
I actually have NO idea how it works, but If you download the interpreter, and if you write `!hcuO`, then you get `Ouch!`
To run this, you need to execute the program like this:
```
huh.exe !hcuO
```
It will actually look for a file called `!hcuO`, but it doesn't exist, so it outputs `Ouch!`
[Answer]
# Mathematica, 3 chars
```
a 2
```
`a 2` means `a` times 2. So the answer is `2 a`.
[Answer]
# GolfScript - 2
```
1
```
(ie `\n1` where `\n` is the newline character)
Output:
```
1
```
(ie `1\n`)
---
To quote [Ilmari](https://codegolf.stackexchange.com/questions/16021/print-your-code-backwards-reverse-quine/16040#16040):
>
> GolfScript automatically appends a newline to the end of the output
>
>
>
Thus a newline followed by a number will print the number followed by a newline.
[Answer]
## [H9+](http://esolangs.org/wiki/H9%2B), 13 characters
```
!dlrow ,olleH
```
As the web page says, all characters that are not `H`, `9` or `+` are ignored, so my program will print `Hello, world!`
[Answer]
## Javascript: 34 characters
```
reifitnedi detcepxenU :rorrExatnyS
```
outputs `SyntaxError: Unexpected identifier`, at least in the Chrome console
[Answer]
# Python, ~~43~~ 41
```
_=']0~::[_%%_ tnirp;%r=_';print _%_[::~0]
```
[Answer]
# Mathematica, 2 bytes
```
1#
```
Outputs:
>
> #1
>
>
>
[Answer]
## TI-BASIC, 2
```
i2
```
Where `i` is the imaginary number.
Outputs `2i`
[Answer]
# BASIC, ~~22~~ ~~12~~ 7 characters
:-)
```
1 enil ni rorre xatnyS
```
**EDIT:** If you're allowed to enter the program in immediate mode, then this could be reduced to `rorre xatnyS` (12 characters).
In BBC BASIC, you only need 7 characters:
```
ekatsiM
```
[Answer]
**ksh** (**21 chars**)
```
$ dnuof ton :found :hsk
ksh: dnuof: not found
```
---
**bash** (31 chars)
```
$ dnuof ton dnammoc :found :hsab-
-bash: dnuof: command not found
```
---
**sh** (29 chars)
```
$ dnuof ton dnammoc :found :hs-
sh: dnuof: command not found
```
This one could not work on some Linux distributions, but works on OSX.
---
**tcsh** (26 chars)
```
$ .dnuof ton dnammoC :found.
.dnuof: Command not found.
```
---
**csh** (26 chars)
```
% .dnuof ton dnammoC :found.
.dnuof: Command not found.
```
---
Above should work on all \*unix based OS.
---
Assumptions:
* You don't have `dnuof` command or alias present.
---
**bash** (2-4 chars)
This one most likely doesn't qualify, but I'll share it as curiosity.
Assuming the previous shell command in Bash was `$!`. The following command:
```
!$
```
will produce: `$!`.
[Answer]
# C++ 472 characters
A lot of characters but I cant think of a simpler way in a c-based language.
```
#include<iostream>
#include<string.h>
#define p(t) std::cout<<'}'<<';'<<')'<<strrev(&std::string(#t)[0])<<t;
char* strrev(char*p){char*t=p;char*q=p;while(q&&*q)++q;for(--q;p<q;++p,--q)*p=*p^*q,*q=*p^*q,*p=*p^*q;return t;}
int main(){p("(p{)(niam tni};t nruter;q*^p*=p*,q*^p*=q*,q*^p*=p*)q--,p++;q<p;q--(rof;q++)q*&&q(elihw;p=q*rahc;p=t*rahc{)p*rahc(verrts *rahc;t<<)]0[)t#(gnirts::dts&(verrts<<')'<<';'<<'}'<<tuoc::dts )t(p enifed#>h.gnirts<edulcni#>maertsoi<edulcni#");}
```
[Answer]
# Befunge 98 - 10 chars
```
"8k,'!1+,@
```
This works if your interpreter does not interpret wrapped lines after `"` as adding an extra space. If your interpreter does interpret wrapped lines like that, then this 11 char solution works ([because duplicate spaces in a string literal are interpreted as one](http://quadium.net/funge/spec98.html#Strings)):
```
"9k,'!1+,@
```
---
If I can use `g` without penalty, then these also work (7 and 8 chars respectively):
```
"5k,g,@
```
and
```
"6k,g,@
```
[Answer]
## GolfScript, 12 chars
```
"-1%.`"-1%.`
```
This code takes the double-quoted string `"-1%.`"`, reverses it (`-1%`), duplicates it (`.`) and un-evals (```) the second copy, restoring the double quotes around it.
### Previous entry (13 chars):
```
{`'.~'+-1%}.~
```
Based on the 8-char quine `{'.~'}.~` from [this answer](https://codegolf.stackexchange.com/questions/5083/create-a-rotating-quine/5160#5160); the extra 5 chars are needed to stringify and reverse the output.
Ps. Note that GolfScript automatically appends a newline to the end of the output. If this is counted as part of the output, a corresponding newline can be prepended to either version of the code without affecting the output, for a cost of one extra char.
[Answer]
# [Fission](http://esolangs.org/wiki/Fission), 6 bytes
A rare case of a generalised quine that is the same length as [the normal quine](https://codegolf.stackexchange.com/a/50968/8478):
```
"LO+!'
```
The idea is the same as that of the normal quine, but we're using a left-going atom (starting at the `L`) so that print mode traverses the code in the opposite order.
[Answer]
## Ruby, 60
```
puts(2,s=<<2.chop.reverse,s)
puts(2,s=<<2.chop.reverse,s)
2
```
Based on a classic Ruby quine.
[Answer]
## Perl, 41
```
$_=q{print~~reverse"\$_=q{$_};eval"};eval
```
Old 52 character answer (27+25 penalty)
```
open+0;print ~~ reverse <0>
```
Reads its own source, stores the reverse in a scalar, and prints that.
[Answer]
# J: 26
**Standard quining** *(26 chars)*: by defining a function and passing it its own definition, in quotes:
```
|.(,],2#{:)'|.(,],2#{:)'''
```
Could probably be made shorter.
**J-specific** *(33 chars)*: by defining a variable and asking what file the variable was defined in, i.e. this one, then printing out the contents of that file:
```
1!:2&2|.1!:1(4!:4 a=:<'a'){4!:3''
```
Must be saved & run from a script (i.e. not in the REPL, because then the answer to the question is "your argument wasn't defined in a file", so there's no file to read).
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 25 bytes
I was surprised to find this hadn't been done yet. :)
```
...yhsif sllems gnihtemoS
```
Paste code [here](https://fishlanguage.com/playground) and run it.
`.` is the Jump command, popping `x` and `y` off the stack, and moving the IP to `(x, y)` in the code box. In this case, the stack is empty, so the language's only error message is printed:
```
Something smells fishy...
```
[Answer]
# [Microscript](https://esolangs.org/wiki/Microscript), 11 bytes
I kind of had to do this.
```
0"Caxq"Caxq
```
Surprisingly, this is actually shorter than the language's shortest known true quine. `q` and `a` are otherwise equivalent, except `q` adds wrapping quotes while `a` does not.
[Answer]
## PHP, 41 characters (+25)
Don't know if I understood the assignment correctly. But here's a PHP try:
```
while(!isset($s) || $s) echo isset($s) ? array_pop($s) : ($s = str_split(file_get_contents(__FILE__)) and null);
```
**edit:** this can be much shorter:
```
echo strrev(file_get_contents(__FILE__));
```
But since it can be that simple, this is probably not what is being asked...
[Answer]
# JavaScript jQuery ~~119~~ ~~92~~ ~~74~~ 70 characters
```
alert($("#answer-16051 pre code").text().split("").reverse().join(""))
```
Now using jQuery, as minitech suggested in the comments, and manually wrapping with `<pre><code>` so I can use `text()` without fear of other code blocks in this post interfering. Manually wrapping with `<h4>` was incompatible with chromeium when I tested it, so now it should work in most browsers.
This program, if run from this page, finds the code block directly above, reverses its contents, and puts it in an alertbox.
Its easy enough to verify, just paste it into the dev console.
[Answer]
# UNIX shell, 31
Real solution at **52 characters:**
```
A='printf "A$ lave;\047`echo $A|rev`\047=A"';eval $A
```
But beware! Honesty doesn't pay off in today's world! Penalty is too low!!
**6 chars + 25 = 31:**
```
rev $0
```
[Answer]
## MATLAB, 78 characters:
```
|
.snoisserpxe ro stnemetats BALTAM ni dilav ton si retcarahc tupni ehT :rorrE
```
Note that the solution requires you to begin with a special character (alt+0160) and that it prints exactly the reversed message. (Unlike the python solution)
[Answer]
## MS-DOS, 24 bytes
```
eman elif ro dnammoc daB
```
Output:
```
Bad command or file name
```
[Answer]
# Windows 10 .EXE, 98 bytes
```
.rehsilbup erawtfos eht htiw kcehc ,CP ruoy htiw noisrev a dnif oT
.CP ruoy no nur t'nac ppa sihT
```
[![enter image description here](https://i.stack.imgur.com/Uo1FF.png)](https://i.stack.imgur.com/Uo1FF.png)
[Answer]
# JavaScript, 62
```
function f(){alert((f+'f()').split('').reverse().join(''))}f()
```
Works for me on latest Chrome (v 31.0.1650.63). Some other browsers may give a different output. (If you reverse that output, then it would work :P)
[Answer]
# SmileBASIC, ~~118~~ 102 bytes
```
FOR I=-101TO.?MID$(("+CHR$(34))*3,30,102)[-I];:NEXTFOR I=-100TO.?MID$(("+CHR$(34))*3,30,102)[-I];:NEXT
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
```
"iQ ²w"iQ ²w
```
[Try it online!](https://tio.run/##y0osKPn/XykzUOHQpnIo9f8/AA "Japt – Try It Online")
Based off the [standard Japt quine](https://codegolf.stackexchange.com/a/71932/39244)
### Explanation
```
"iQ ²w" // Take this string. iQ ²w
iQ // Insert a quote. "iQ ²w
² // Double. "iQ ²w"iQ ²w
w // Reverse. w² Qi"w² Qi"
// Implicitly output.
```
[Answer]
# Windows command prompt, 93 bytes
```
.elif hctab ro margorp elbarepo ,dnammoc lanretxe ro lanretni na sa dezingocer ton si 'file.'
```
[![enter image description here](https://i.stack.imgur.com/ZrM7A.png)](https://i.stack.imgur.com/ZrM7A.png)
[Answer]
## JavaScript, 56
```
($=_=>_!=$._?_?$(_.slice(1))+_[0]:')':$('($='+$+')('))()
```
] |
[Question]
[
## Challenge:
In the programming language of your choice, shut down the machine that your code was executed on.
# Rules
* No shutting down by resource exhaustion (e.g.: forkbomb to force shutdown)
* You are allowed to write code that only works in a specific environment/OS, if you wish.
* Standard loopholes are forbidden
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), thus the lowest amount of bytes wins!
[Answer]
# [Assembly (x86/x64, Linux, as)](https://sourceware.org/binutils/docs/as/index.html), ~~22~~ ~~21~~ 19 bytes
```
mov $0x58, %al # 2 bytes: b0 58
mov $0xfee1dead, %ebx # 5 bytes: bb ad de e1 fe
mov $0x28121969, %ecx # 5 bytes: b9 69 19 12 28
mov $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
int $0x80 # 2 bytes: cd 80
```
Must be run as root.
**This is equivalent to pressing the power button and not a safe way to power off your PC.** Make sure you close all open applications and execute `sync` to flush all file system buffers before executing this program, to at least minimize the risk of file corruption.
### Test run
```
$ as -o poweroff.o poweroff.s
$ ld -o poweroff poweroff.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
$ sudo sh -c 'sync && ./poweroff'
root's password:
```
Followed by darkness.
### How it works
`int $0x80` invokes a software interrupt. It works on both x86 and x64, but has been deprecated for over a decade now and should not be used in production code. x64 code should use `syscall` instead. x86 should use `sysenter`, but it is too cumbersome for code golf.
The resulting action from the syscall depends on registers EAX - EDX, ESI, and EDI. The [Linux Syscall Reference](http://syscalls.kernelgrok.com/) shows all syscalls that are available via `int $0x80`.
When EAX holds **0x58 (88)**, *[reboot](http://man7.org/linux/man-pages/man2/reboot.2.html)* is called, which can also be used to power off, put to sleep, or hibernate the computer, as well as switching kernels and disabling or enabling the **Ctrl - Alt - Del** key combo.
At the start of the program – and by compiling with `as` or `gcc -nostdlib`, we can make sure that we're actually at the start of the program – most registers are set to **0**. This includes EAX, so we can use `mov $0x58, %al` to set the lower 8 bits of EAX to **0x58**, thus setting EAX itself to **0x58**. This saves two bytes over manually zeroing the register with `xor %eax, %eax` and one more over the straighforward `mov $0x58, %eax` which encodes **0x58** in 32 bits.
The first two arguments to *reboot* are magic numbers, presumably to prevent accidental reboots, and are read from registers EBX and ECX. Unless these numbers are equal to certain constants, *reboot* refuses to perform any action.
* The first magic number must equal **0xfee1dead** (*feel dead*), probably referring to the power off / death of the PC.
* The second magic number can be equal to four different constants, although the latter three did not work in ancient versions of Linux. All of them seem to refer to the subsequent power on / birth of the PC.
+ **0x28121969** represents Linus Torvalds's birthday (December 28, 1969).
+ **0x05121996** represents Patricia Torvalds's birthday (December 5, 1996).
+ **0x16041998** represents Daniela Torvalds's birthday (April 16, 1998).
+ **0x20112000** represents Celeste Torvalds's birthday (November 20, 2000).Patricia, Daniela, and Celeste Torvalds are Linus Torvalds's three daughters.
* The EDX register selects the type of "reboot" we want. **0x4321fedc** is *RB\_POWER\_OFF*, shutting the PC down and powering it off.
* Finally, the value of the ESI register is ignored for *RB\_POWER\_OFF*; the value of the EDI register is ignored entirely by *reboot*.
### Alternate version, x64-only, 19 bytes
On x64, we can use a proper syscall for the same byte count.
```
mov $0xa9, %al # 2 bytes: b0 a9
mov $0xfee1dead, %edi # 5 bytes: bf ad de e1 fe
mov $0x28121969, %esi # 5 bytes: be 69 19 12 28
mov $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
syscall # 2 bytes: 0f 05
```
The only differences lie in the instruction (`syscall` vs `int $0x80`), the value of *\_\_NR\_REBOOT* (**0xa9** vs **0x58**), and the involved registers.
[Answer]
# PowerShell, 13 bytes
```
Stop-Computer
```
Pretty self-explanatory? Doesn't work on PowerShell core, so it won't work on PowerShell for Linux/MacOS (already tried it on TIO :-D ).
## Bonus Garbage Submission, 12 bytes
```
gcm s*r|iex
```
In my testing, this works on Windows 2003 with PowerShell 2.0. It won't work on most of the newer versions, and it may not work depending on which modules are installed. It's quite terrible!
This searches the list of commands for any with the pattern `s*r` and then runs all of them! To be clear, **this is dangerous, don't do this!**
The trick of course, is getting a list of commands that don't have any mandatory parameters, otherwise PowerShell will prompt for a value.
On my 2003 machine, the 3 commands it returns are:
>
>
> ```
> CommandType Name Definition
> ----------- ---- ----------
> Application scrnsave.scr C:\WINDOWS\system32\scrnsave.scr
> Application ssmarque.scr C:\WINDOWS\system32\ssmarque.scr
> Cmdlet Stop-Computer Stop-Computer [[-ComputerName] <String[]>] [[-Cr...
>
> ```
>
>
Yes, it does launch the marquee screensaver, but no, it does not wait for it to complete before launching `Stop-Computer`.
This approach can work on newer machines, again depending on which modules are installed, but the best I could do on Windows 2012 and 2016 was **14 bytes**:
```
gcm sto*er|iex
```
(and yeah, sure, the winbatch submission will work in PowerShell and it's shorter, but.. that's no fun)
[Answer]
## Batch, 10 bytes
On windows, this would suffice
```
shutdown/s
```
This will set up a shutdown in one minute.
Alternatively, as @flashbang points out:
```
shutdown/p
```
This shuts down the computer immediately.
[Answer]
## x86 machine code, Lenovo Z510, DOS COM or Bootloader, 7 bytes
```
BITS 16
mov ax, (1 << 13) | (7 << 10)
mov dx, 1804h
out dx, ax
```
Assembled into `B8 00 3C BA 04 18 EF`
I'm exploiting "*You are allowed to write code that only works in a specific environment/OS, if you wish*" to the ultimate level: this will only work on Lenovo Z5101.
This writes `SLP_TYPa << 10 | SLP_EN` to the `PM1a_CNT` ACPI register, I dumped this values from the ACPI tables [months ago for an answer about shutdown](https://stackoverflow.com/a/40002262/5801661) (where I give a bit of context to the code above).
This can be run either under DOS as a COM (just write the binary data into a file and change extension to "com") or as a bootloader.
For the latter write the standard signature and [beware of the issues with modern firmware](https://stackoverflow.com/a/39248323/5801661).
---
1 Not strictly true, any system that happens to have the same ACPI configuration will also shutdown.
[Answer]
# [GRUB shell](https://www.gnu.org/software/grub/manual/grub.html), 4 bytes
**Golfed**
```
halt
```
>
> Command: halt --no-apm
>
>
> The command halts the computer. If the --no-apm option is specified, no APM BIOS call is performed. Otherwise, the computer is shut down using APM.
>
>
>
**Bonus**
Here is a proof that GRUB shell is indeed Tur**n**ing-complete (see comments):
[![enter image description here](https://i.stack.imgur.com/P4rfO.gif)](https://i.stack.imgur.com/P4rfO.gif)
[Answer]
# 65C02 machine code, 1 byte
STP instruction (0xDB):
STP stops the clock input of the 65C02, effectively shutting down the 65C02 until a hardware reset occurs (i.e. the RES pin goes low). This puts the 65C02 into a low power state. This is useful for applications (circuits) that require low power consumption, but STP is rarely seen otherwise.
(Source: <http://www.6502.org/tutorials/65c02opcodes.html>)
xxd dump:
```
00000000: db .
```
[Answer]
# Matlab, 21 Bytes
```
system('shutdown -s')
```
~~I haven't tried this (closing all programs to do a restart in the middle of the day isn't really tempting), but it should work.~~. This works...
I'll add a short explanation later, my laptop is currently off.
[Answer]
# MATLAB, 11 bytes
```
!shutdown/p
```
Somewhat similar to [Stewie Griffin's approach](https://codegolf.stackexchange.com/a/107878/32352). However, MATLAB has ***way*** shorter ways of invoking system commands; in this case, `!` is used. Windows does not need `.exe` for command names, so that's left out as well. The `/` option is still supported (I'm running Windows 10), and negates the need for the space. Alternatives are:
```
system shutdown/p % 17 bytes; uses so-called 'command' syntax.
dos shutdown/p % 14 bytes; the 'dos' command can be used just as well.
```
[Answer]
# SmileBASIC, ~~14~~ ~~11~~ 6 bytes
```
OPTION
```
Triggers a crash causing the 3DS to restart.
I hope this counts.
Works in the most recent version.
[Answer]
# Bash, ~~7~~ 6 bytes
```
init 0
```
Assuming that the program is run as root.
[Answer]
# Commodore 64, 11 bytes
```
0 sys64738
```
This is from the BASIC prompt. Or...
### Commodore 64, 6502 assembly, 3 bytes (assembled), 16 bytes (source)
```
*=8000
JMP $FCE2
```
[Answer]
# Python 2, 29 bytes
```
import os;os.system('init 0')
```
Works on Linux systems and needs root privileges.
**For Windows, 33 bytes**
```
import os;os.system('shutdown/p')
```
[Answer]
# Java, 101 98 62 42 bytes
```
()->{Runtime.getRuntime().exec("init 0");}
```
As @Snowman pointed out, the question didn't specify if a full program was needed, so this should still be acceptable.
[Answer]
# AppleScript, 30 bytes
```
tell app "Finder" to shut down
```
Does exactly what it says: tells Finder to shut the computer off.
[Answer]
## TI-Nspire CX CAS, 3 bytes
```
" "+" "
```
*summing two empty strings.*
On an older version of the calculator, this would crash the device and cause it to reboot (there's no way to shutdown a device without reboot apart from physical button combinations).
[Video](https://www.youtube.com/watch?v=QvxFxzDgS2U) by Adriweb
[Answer]
# C++, 51 40 bytes
-11 bytes thanks to [Ingve](https://codegolf.stackexchange.com/users/64901/ingve)!
```
#include<os>
int main(){OS::shutdown();}
```
Only works in [IncludeOS](http://www.includeos.org/) (v0.10.0-rc.1)
Test:
```
$ pwd
/home/simon/IncludeOS/examples/demo_service
$ cat service.cpp
#include<os>
int main(){OS::shutdown();}
$ mkdir build && cd build && cmake .. && make && cd ..
[...]
$ boot build/IncludeOS_example
[...]
================================================================================
================================================================================
IncludeOS v0.10.0-rc.1-9-g151a2b9
+--> Running [ IncludeOS minimal example ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$
```
[Answer]
# AutoHotkey, ~~11~~ 10 Bytes
*Saved a byte thanks to [Gurupad Mamadapur](https://codegolf.stackexchange.com/users/47650/gurupad-mamadapur)*
```
Shutdown,9
```
AHK Supports a Shutdown command by default. The `9` is a flag, consisting of `Shutdown=1` + `PowerDown=8`.
[Answer]
# Machine code (x86, boot loader) 18 bytes
```
b8 01 53 33 db cd 15 b8 07 53 bb 01 00 b9 03 00 cd 15
```
Disassembly:
```
mov ax, 0x5301 ; connect to real-mode APM services
xor bx, bx ; device id 0 - APM BIOS
int 0x15 ; call APM
mov ax, 0x5307 ; set power state
mov bx, 0x0001 ; on all devices
mov cx, 0x0003 ; to Off
int 0x15 ; call APM
```
You can test it in Bochs' debugger with the following commands (after starting simulation, having some disk drive set up):
```
pb 0x7c00
c
setpmem 0x7c00 4 0x335301b8
setpmem 0x7c04 4 0xb815cddb
setpmem 0x7c08 4 0x01bb5307
setpmem 0x7c0c 4 0x0003b900
setpmem 0x7c10 2 0x15cd
c
```
This same machine code will also work as a DOS executable (`*.COM`).
[Answer]
## C#, 79 54 53 bytes
This works on Windows.
**79 bytes**:
```
class _{static void Main(){System.Diagnostics.Process.Start("shutdown","/s");}}
```
**53 bytes**, thanks to TheLethalCoder:
```
_=>System.Diagnostics.Process.Start("shutdown","/s");
```
[Answer]
# AutoIt, 11 bytes
```
Shutdown(1)
```
Shutdown function gets combination of following codes
```
0 = Logoff
1 = Shutdown
2 = Reboot
4 = Force
8 = Power down
16= Force if hung
32= Standby
64= Hibernate
```
To shutdown and power down, for example, the code would be 9 (shutdown + power down = 1 + 8 = 9).
[Answer]
# Windows - NativeAPI, 212 bytes
Ok this is not really the shortest version.
But maybe interesting to some.
This will *not* execute on the Win32 subsystem. However it will run when executed within the context of the native api (like autochk.exe does)
# Code
```
#define WIN32_NO_STATUS
#include <windef.h>
#include <winnt.h>
#include <ntndk.h>
NTSTATUS main() {
RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE,TRUE,FALSE,NULL);
return ZwShutdownSystem(ShutdownPowerOff);
}
```
# Build
To build this either use the WinDDK `build.exe` tool (with an appropriate `source` file for `NMAKE`)
Or use these commands to compile and link:
```
cl /Gd /D_X86_ /showIncludes /I%DDK_INC_PATH% /I%CRT_INC_PATH% /c main.c
link /verbose /nodefaultlib /subsystem:native /machine:X86 /entry:NtProcessStartup@4 C:\WinDDK\7600.16385.1\lib\win7\i386\nt.lib C:\WinDDK\7600.16385.1\lib\win7\i386\ntdllp.lib C:\WinDDK\7600.16385.1\lib\win7\i386\BufferOverflow.lib .\main.obj
```
Note: This will build an x86 native executable. Change the appropriate bits if you want to build this for a different architecture.
# Test
To test a native executable you have to execute it **before** the win32 subsystem is loaded. One common way to do it is to append the executable in the following registry key:
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute
```
# Warning
If you do this however, you need to have an option to edit the registry hive of the target OS from another OS. Since **you will not be able to boot the target OS anymore!**
I did it on a VM where i could easily revert to a previous snapshot!
[Answer]
# J, 14 bytes
```
2!:0'poweroff'
```
Works on Linux systems. `2!:0` executes the string in `/bin/sh`.
[Answer]
## Groovy, 23 bytes
```
'shutdown /p'.execute()
```
[Answer]
# Most Linux shells, 15 bytes
```
# echo o>/p*/*ger
```
It could be made to be 11 bytes long, if you happen to be in the `/proc` directory:
```
# echo o>*ger
```
This is very straightforward (has no side effects, like unmounting filesystems or killing processes) and rather brutal.
[Answer]
## Android shell, 9 bytes
```
reboot -p
```
[Answer]
## AppleScript, 44 bytes
```
tell application "Finder"
shut down
end tell
```
I don't know how AppleScript syntax works or anything, so if anybody knows how to shorten this, please tell.
Also, I'm doing this on my phone at school ("hacking"), so I can't test it.
At 14 fewer bytes (thanks to kindall) you can say
```
tell app "Finder" to shut down
```
[Answer]
# Clojure, ~~40~~ 39 bytes
```
(.exec(Runtime/getRuntime)"shutdown/s")
```
-1 byte by changing the flag from `-s` to `/s`, which allowed me to get rid of the space.
Basically the Java answer.
Testing this was fun. Windows decided to do a firmware update on my Surface the second it shut down. Of course.
```
(defn shutdown []
(.exec (Runtime/getRuntime) "shutdown -s"))
```
[Answer]
# Node.js, 39 bytes
Linux
```
require('child_process').exec('init 0')
```
[Answer]
## AHK, ~~19~~ 15 bytes
```
Run,Shutdown -s
```
Works on windows only.
[Answer]
## C++, ~~48~~ 47 (Windows) ~~46~~ 45 (Linux) bytes
Removed 1 byte thanks to Snowman
```
#include<cstdlib>
main(){system("shutdown/p");}
```
This should shutdown the system for windows
```
#include<cstdlib>
main(){system("poweroff");}
```
This should shutdown the system for Linux
] |
[Question]
[
Your task is to write code that will leak at least one byte of memory in as few bytes as possible. The memory must be leaked *not just allocated*.
Leaked memory is memory that the program allocates but loses the ability to access before it can deallocate the memory properly. For most high level languages this memory has to be allocated on the heap.
An example in C++ would be the following program:
```
int main(){new int;}
```
This makes a `new int` on the heap without a pointer to it. This memory is instantly leaked because we have no way of accessing it.
Here is what a leak summary from [Valgrind](http://valgrind.org/) might look like:
```
LEAK SUMMARY:
definitely lost: 4 bytes in 1 blocks
indirectly lost: 0 bytes in 0 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 0 bytes in 0 blocks
suppressed: 0 bytes in 0 blocks
```
Many languages have a memory debugger (such as [Valgrind](http://valgrind.org/)) if you can you should include output from such a debugger to confirm that you have leaked memory.
The goal is to minimize the number of bytes in your source.
[Answer]
# [Perl](https://www.perl.org/) (5.22.2), 0 bytes
[Try it online!](https://tio.run/nexus/perl "Perl – TIO Nexus")
I knew there'd be some language out there that leaked memory on an empty program. I was expecting it to be an esolang, but turns out that `perl` leaks memory on any program. (I'm assuming that this is intentional, because freeing memory if you know you're going to exit anyway just wastes time; as such, the common recommendation nowadays is to just leak any remaining memory once you're in your program's exit routines.)
## Verification
```
$ echo -n | valgrind perl
…snip…
==18517==
==18517== LEAK SUMMARY:
==18517== definitely lost: 8,134 bytes in 15 blocks
==18517== indirectly lost: 154,523 bytes in 713 blocks
==18517== possibly lost: 0 bytes in 0 blocks
==18517== still reachable: 0 bytes in 0 blocks
==18517== suppressed: 0 bytes in 0 blocks
==18517==
==18517== For counts of detected and suppressed errors, rerun with: -v
==18517== ERROR SUMMARY: 15 errors from 15 contexts (suppressed: 0 from 0)
```
[Answer]
# C, ~~48 31~~ 22 bytes
Warning: Don't run this too many times.
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for lots of help/ideas!
```
f(k){shmget(k,1,512);}
```
This goes one step further. `shmget` allocates shared memory that isn't deallocated when the program ends. It uses a key to identify the memory, so we use an uninitialized int. This is technically undefined behaviour, but practically it means that we use the value that is just above the top of the stack when this is called. This will get written over the next time that anything is added to the stack, so we will lose the key.
---
The only case that this doesn't work is if you can figure out what was on the stack before. For an extra 19 bytes you can avoid this problem:
```
f(){srand(time(0));shmget(rand(),1,512);}
```
---
Or, for 26 bytes:
```
main(k){shmget(&k,1,512);}
```
But with this one, the memory is leaked after the program exits. While running the program has access to the memory which is against the rules, but after the program terminates we lose access to the key and the memory is still allocated.
This requires address space layout randomisation (ASLR), otherwise `&k` will always be the same. Nowadays ASLR is typically on by default.
---
**Verification:**
You can use `ipcs -m` to see what shared memory exists on your system. I removed pre-existing entries for clarity:
```
$ cat leakMem.c
f(k){shmget(k,1,512);}
int main(){f();}
$ gcc leakMem.c -o leakMem
leakMem.c:1:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
f(k){shmget(k,1,512);}
^
leakMem.c: In function ‘f’:
leakMem.c:1:1: warning: type of ‘k’ defaults to ‘int’ [-Wimplicit-int]
leakMem.c:1:6: warning: implicit declaration of function ‘shmget’ [-Wimplicit-function-declaration]
f(k){shmget(k,1,512);}
ppcg:ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
$ ./leakMem
$ ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x0000007b 3375157 Riley 0 1 0
```
[Answer]
# [Unlambda](http://www.madore.org/~david/programs/unlambda/) (`c-refcnt/unlambda`), 1 byte
```
i
```
[Try it online!](https://tio.run/nexus/unlambda#@5/5/z8A "Unlambda – TIO Nexus")
This is really a challenge about finding a pre-existing interpreter which leaks memory on very simple programs. In this case, I used Unlambda. There's more than one official Unlambda interpreter, but `c-refcnt` is one of the easiest to build, and it has the useful property here that it leaks memory when a program runs successfully. So all I needed to give here was the simplest possible legal Unlambda program, a no-op. (Note that the empty program doesn't work here; the memory is still reachable at the time the interpreter crashes.)
## Verification
```
$ wget ftp://ftp.madore.org/pub/madore/unlambda/unlambda-2.0.0.tar.gz
…snip…
2017-02-18 18:11:08 (975 KB/s) - ‘unlambda-2.0.0.tar.gz’ saved [492894]
$ tar xf unlambda-2.0.0.tar.gz
$ cd unlambda-2.0.0/c-refcnt/
$ gcc unlambda.c
$ echo -n i | valgrind ./a.out /dev/stdin
…snip…
==3417== LEAK SUMMARY:
==3417== definitely lost: 40 bytes in 1 blocks
==3417== indirectly lost: 0 bytes in 0 blocks
==3417== possibly lost: 0 bytes in 0 blocks
==3417== still reachable: 0 bytes in 0 blocks
==3417== suppressed: 0 bytes in 0 blocks
==3417==
==3417== For counts of detected and suppressed errors, rerun with: -v
==3417== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
```
[Answer]
# TI-Basic, 12 bytes
```
While 1
Goto A
End
Lbl A
Pause
```
"... a memory leak is where you use a Goto/Lbl within a loop or If conditional (anything that has an End command) to jump out of that control structure before the End command is reached... " [(more)](http://tibasicdev.wikidot.com/memory-leaks)
[Answer]
## Python <3.6.5, 23 bytes
```
property([]).__init__()
```
`property.__init__` leaks references to the property's old `fget`, `fset`, `fdel`, and `__doc__` if you call it on an already-initialized `property` instance. This is a bug, eventually reported as part of CPython [issue 31787](https://bugs.python.org/issue31787) and fixed in [Python 3.6.5](https://github.com/python/cpython/commit/47316342417146f62653bc3c3dd505bfacc5e956) and [Python 3.7.0](https://github.com/python/cpython/commit/ef20abed7f2ae0ba54b1d287f5fe601be80c1128). (Also, yes, `property([])` is a thing you can do.)
[Answer]
# C#, 34 bytes
```
class L{~L(){for(;;)new L();}}
```
This *solution* does not require the Heap.
It just needs a real hard working GC ([Garbage Collector](https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=12&cad=rja&uact=8&ved=0ahUKEwjaqvXGqZzSAhXMXhQKHYlpDakQFghIMAs&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FGarbage_collection_(computer_science)&usg=AFQjCNHMuYt1SQmqd0Z2AE27JpDAP5rBfg&sig2=KvQoRPh3_BaQ0qFp86YodQ&bvm=bv.147448319,d.bGs)).
Essentially it turns the GC into its own enemy.
# Explanation
Whenever the *destructor* is called, It creates new instances of this evil class as long as the timeout runs out and tells the GC to just ditch that object without waiting for the destructor to finish. By then thousands of new instances have been created.
The "evilness" of this is, the harder the GC is working, the more this will blow up in your face.
*Disclaimer*: Your GC may be smarter than mine. Other circumstances in the program may cause the GC to ignore the first object or its destructor. In these cases this will not blow up. But in many variations it *will*. Adding a few bytes here and there might ensure a leak for every possible circumstances. Well except for the power switch maybe.
# Test
Here is a test *suite*:
```
using System;
using System.Threading;
using System.Diagnostics;
class LeakTest {
public static void Main() {
SpawnLeakage();
Console.WriteLine("{0}-: Objects may be freed now", DateTime.Now);
// any managed object created in SpawbLeakage
// is no longer accessible
// The GC should take care of them
// Now let's see
MonitorGC();
}
public static void SpawnLeakage() {
Console.WriteLine("{0}-: Creating 'leakage' object", DateTime.Now);
L l = new L();
}
public static void MonitorGC() {
while(true) {
int top = Console.CursorTop;
int left = Console.CursorLeft;
Console.WriteLine(
"{0}-: Total managed memory: {1} bytes",
DateTime.Now,
GC.GetTotalMemory(false)
);
Console.SetCursorPosition(left, top);
}
}
}
```
Output after 10 minutes:
```
2/19/2017 2:12:18 PM-: Creating 'leakage' object
2/19/2017 2:12:18 PM-: Objects may be freed now
2/19/2017 2:22:36 PM-: Total managed memory: 2684476624 bytes
```
That's 2 684 476 624 bytes.
The Total `WorkingSet` of the process was about 4.8 GB
This answer has been inspired by Eric Lippert's wonderful article: [When everything you know is wrong](https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/).
[Answer]
# Javascript, 14 bytes
**Golfed**
```
setInterval(0)
```
Registers an empty interval handler with a default delay, discarding the resulting timer id (making it impossible to cancel).
[![enter image description here](https://i.stack.imgur.com/v5YRe.png)](https://i.stack.imgur.com/v5YRe.png)
I've used a non-default interval, to create several million timers, to illustrate the leak, as using a default interval eats CPU like mad.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 15 bytes
```
f(){malloc(1);}
```
### Verification
```
$ cat leak.c
f(){malloc(1);}
main(){f();}
$ gcc -g -o leak leak.c
leak.c: In function ‘f’:
leak.c:1:5: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
f(){malloc(1);}
^
$ valgrind --leak-check=full ./leak
==32091== Memcheck, a memory error detector
==32091== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==32091== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==32091== Command: ./leak
==32091==
==32091==
==32091== HEAP SUMMARY:
==32091== in use at exit: 1 bytes in 1 blocks
==32091== total heap usage: 1 allocs, 0 frees, 1 bytes allocated
==32091==
==32091== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
==32091== at 0x4C29110: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==32091== by 0x40056A: f (leak.c:1)
==32091== by 0x40057A: main (leak.c:2)
==32091==
==32091== LEAK SUMMARY:
==32091== definitely lost: 1 bytes in 1 blocks
==32091== indirectly lost: 0 bytes in 0 blocks
==32091== possibly lost: 0 bytes in 0 blocks
==32091== still reachable: 0 bytes in 0 blocks
==32091== suppressed: 0 bytes in 0 blocks
==32091==
==32091== For counts of detected and suppressed errors, rerun with: -v
==32091== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
```
[Answer]
# Rust, 52 bytes
```
extern{fn malloc(_:u8);}fn main(){unsafe{malloc(9)}}
```
Allocates some bytes with the system malloc. This assumes the wrong ABI is acceptable.
---
# ~~Rust (in theory), 38 bytes~~
```
fn main(){Box::into_raw(Box::new(1));}
```
We allocate memory on the heap, extract a raw pointer, and then just ignore it, effectively leaking it. (`Box::into_raw` is shorter then `std::mem::forget`).
However, Rust by default uses jemalloc, [which valgrind can't detect any leakage](https://github.com/rust-lang/rust/issues/28224). We could switch to the system allocator but that [adds 50 bytes](https://doc.rust-lang.org/book/custom-allocators.html#switching-allocators) and requires nightly. Thanks so much for memory safety.
---
Output of the first program:
```
==10228== Memcheck, a memory error detector
==10228== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10228== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==10228== Command: ./1
==10228==
==10228==
==10228== HEAP SUMMARY:
==10228== in use at exit: 9 bytes in 1 blocks
==10228== total heap usage: 7 allocs, 6 frees, 2,009 bytes allocated
==10228==
==10228== LEAK SUMMARY:
==10228== definitely lost: 9 bytes in 1 blocks
==10228== indirectly lost: 0 bytes in 0 blocks
==10228== possibly lost: 0 bytes in 0 blocks
==10228== still reachable: 0 bytes in 0 blocks
==10228== suppressed: 0 bytes in 0 blocks
==10228== Rerun with --leak-check=full to see details of leaked memory
==10228==
==10228== For counts of detected and suppressed errors, rerun with: -v
==10228== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```
[Answer]
# Java, 10 bytes
Finally, a competitive answer in Java !
**Golfed**
```
". "::trim
```
This is a method reference (against a string constant), which can be used like that:
```
Supplier<String> r = ". "::trim
```
A literal string `". "` will be automatically added to the global *interned* strings pool, as maintained by the `java.lang.String` class,
and as we immediatelly trim it, the reference to it can not be reused further in the code (unless you declare exactly the same string again).
>
> ...
>
>
> A pool of strings, initially empty, is maintained privately by the class String.
>
>
> All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.
>
>
> ...
>
>
>
<https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern-->
You can turn this in a "production grade" memory leak, by adding the string to itself and then invoking the *intern()* method explicitly, in a loop.
[Answer]
## 8086 ASM, 3 bytes
This examples assumes that a C runtime is linked in.
```
jmp _malloc
```
this assembles to `e9 XX XX` where `XX XX` is the relative address of `_malloc`
This invokes `malloc` to allocate an unpredictable amount of memory and then immediately returns, terminating the processes. On some operating systems like DOS, the memory might not be reclaimable at all until the system is rebooted!
[Answer]
# Forth, 6 bytes
**Golfed**
```
s" " *
```
Allocates an empty string with `s" "`, leaving it's address and length (0) on the stack, then multiplies them (resulting in a memory address being lost).
**Valgrind**
```
%valgrind --leak-check=full gforth -e 's" " * bye'
...
==12788== HEAP SUMMARY:
==12788== in use at exit: 223,855 bytes in 3,129 blocks
==12788== total heap usage: 7,289 allocs, 4,160 frees, 552,500 bytes allocated
==12788==
==12788== 1 bytes in 1 blocks are definitely lost in loss record 1 of 22
==12788== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12788== by 0x406E39: gforth_engine (in /usr/bin/gforth-0.7.0)
==12788== by 0x41156A: gforth_go (in /usr/bin/gforth-0.7.0)
==12788== by 0x403F9A: main (in /usr/bin/gforth-0.7.0)
==12788==
...
==12818== LEAK SUMMARY:
==12818== definitely lost: 1 bytes in 1 blocks
==12818== indirectly lost: 0 bytes in 0 blocks
```
[Answer]
# Befunge ([fungi](https://hackage.haskell.org/package/Fungi-1.0.4)), 1 byte
```
$
```
This may be platform dependent and version dependent (I've only tested with version 1.0.4 on Windows), but *fungi* has historically been a very leaky interpreter. The `$` (drop) command shouldn't do anything on an empty stack, but looping over this code somehow manages to leak a lot of memory very quickly. Within a matter of seconds it will have used up a couple of gigs and will crash with an "out of memory" error.
Note that it doesn't necessarily have to be a `$` command - just about anything would do. It won't work with a blank source file though. There's got to be at least one operation.
[Answer]
# go 45 bytes
```
package main
func main(){go func(){for{}}()}
```
this creates an anonymous goroutine with an infinite loop inside of it. the program can continue to run as normal, as starting the goroutine is kind of like spawning a concurrently running small thread, but the program has no way to reclaim the memory that was allocated for the goroutine. the garbage collector will never collect it either since it is still running. some people call this 'leaking a goroutine'
[Answer]
# Java 1.3, 23 bytes
```
void l(){new Thread();}
```
Creating a thread but not starting it. The thread is registered in the internal thread pool, but will never be started, so never ended and therefore never be a candidate for the GC. It is an unretrievable object, stuck in Java limbos.
[It's a bug in Java until 1.3 included](https://bugs.java.com/view_bug.do?bug_id=4410846) as it was fixed afterwards.
## Testing
The following program makes sure to pollute the memory with new thread objects and show a decreasing free memory space. For the sake of leaks testing, I intensively makes the GC run.
```
public class Pcg110485 {
static
void l(){new Thread();}
public static void main(String[] args) {
while(true){
l();
System.gc();
System.out.println(Runtime.getRuntime().freeMemory());
}
}
}
```
[Answer]
## Swift 3, 38 bytes
New version:
```
class X{var x: X!};do{let x=X();x.x=x}
```
`x` has a strong reference to itself, so it will not be deallocated, leading to a memory leak.
Old version:
```
class X{var y:Y!}
class Y{var x:X!}
do{let x=X();let y=Y();x.y=y;y.x=x}
```
`x` contains a strong reference to `y`, and vice versa. Thus, neither will be deallocated, leading to a memory leak.
[Answer]
# Delphi (Object Pascal) - 33 bytes
Creating an object without a variable, full console program:
```
program;begin TObject.Create;end.
```
Enabling FastMM4 in the project will show the memory leak:
[![enter image description here](https://i.stack.imgur.com/Iy90o.png)](https://i.stack.imgur.com/Iy90o.png)
[Answer]
# C# - 84bytes
```
class P{static void Main(){System.Runtime.InteropServices.Marshal.AllocHGlobal(1);}}
```
This allocates exactly 1 byte of unmanaged memory, and then loses the `IntPtr`, which I believe is the only way to get at or free it. You can test it by stuffing it in a loop, and waiting for the application to crash (might want to add a few zeros to speed things up).
I considered `System.IO.File.Create("a");` and such, but I'm not convinced that these are necessarily memory leaks, as the application itself *will* collect the memory, it's the OS underneath that *might* leak (because `Close` or `Dispose` were not called). File access stuff also requires file system permissions, and no one wants to rely on those. *And it turns out this won't leak anyway, because there is nothing stopping the finaliser being called (which does free the underlying resources is possible), which the framework includes to mitigate these sorts of error of judgement (to some degree), and to confuse programmers with seemingly non-deterministic file locking (if you're a cynic). Thanks to Jon Hanna for putting me straight on this.*
I am a tad disappointed that I can't find a shorter way. The .NET GC works, I can't think of any `IDisposables` in mscorlib that will definitely leak *(and indeed they all seem to have finalisers, how annoying)*, I'm not aware of any other way to allocate unmanaged memory (short of PInvoke), and reflection ensures anything with a reference to it (regardless of language semantics (e.g. private members or classes with no accessors)) *can* be found.
[Answer]
# [Factor](http://factorcode.org), 13 bytes
Factor has automatic memory management, but also gives access to some libc functionality:
```
1 malloc drop
```
Manually allocates 1 byte of memory, returns it's address, and drops it.
`malloc` actually registers a copy to keep track of memory leaks adn double frees, but identifying the one you leaked is not an easy task.
If you prefer to make sure you really lose that reference:
```
1 (malloc) drop
```
Testing leaks with `[ 1 malloc drop ] leaks.` says:
```
| Disposable class | Instances | |
| malloc-ptr | 1 | [ List instances ] |
```
Testing leaks with `[ 1 (malloc) drop ] leaks.` says:
```
| Disposable class | Instances | |
```
Oh no! Poor factor, it's got Alzheimer now! D:
[Answer]
# [AutoIt](https://autoitscript.com), 39 bytes
```
#include<Memory.au3>
_MemGlobalAlloc(1)
```
Allocates one byte from the heap. Since the handle returned by `_MemGlobalAlloc` is discarded, there is no way to explicitly free that allocation.
[Answer]
## Common Lisp (SBCL only), ~~28~~ 26 bytes
```
sb-alien::(make-alien int)
```
You run it like so: `sbcl --eval 'sb-alien::(make-alien int)'`; nothing is printed nor returned, but the memory allocation happens. If I wrap the form inside a `(print ...)`, the pointer is displayed in the REPL.
1. `package::(form)` is a special notation in SBCL for temporarily binding the current package while reading a form. This is used here to avoid prefixing both `make-alien` and `int` with `sb-alien`. I think it would be cheating to assume the current package is set to this one, because that's not the case at startup.
2. `make-alien` allocates memory for a given type and an optional size (using malloc).
3. When executing this in the REPL, add `0` after the allocation so that the REPL does not return the pointer, but that value instead. Otherwise, that would no be a real leak because the REPL remembers the last three returned values (See [`*`, `**`, `***`](http://www.lispworks.com/documentation/HyperSpec/Body/v__stst_.htm)) and we could still have a chance to free the allocated memory.
2 bytes removed thanks to PrzemysławP, thanks!
[Answer]
## C++, 16 bytes
```
main(){new int;}
```
~~I don't have valgrind to check it leaks, but pretty sure it should.~~ Otherwise I would try:
```
main(){[]{new int;}();}
```
# Valgrind result
(It does leak indeed)
```
==708== LEAK SUMMARY:
==708== definitely lost: 4 bytes in 1 blocks
```
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 322 220 bytes
```
import sun.misc.*;class Main{static void main(String[]a)throws Exception{java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(1<2);((Unsafe)f.get(1)).allocateMemory(1);}}
```
[Try it online!](https://tio.run/nexus/java-openjdk9#NYy7asNAEEV/ZVG1m2LAaWUXgSSdK5MquBivZuUJq12zM/EDY1DvfKV@RFEs0l3uOZyRu0MuauQ7Qcfi4an2EUXMGjldRVHZm2PmxnTTYTdaOLWfW3S6L/kk5u3s6aCc0/ULjwgRUwuFQiSv8M4UGxNWH0kwEDy60JK@0jQLNQ9uK93TbFSuDiCkL96TCO8iDf3P0N/tYvnsamtny4W/xj9xDjDG7FFpTV0uFzuThatvt3H8BQ "Java (OpenJDK 9) – TIO Nexus")
This is a other Memory leak that don't use the String Cache. It Allocates half of your RAM and you can't do anything with it.
Thanks to zeppelin for saving all the bytes
[Answer]
## C#, 109 bytes
```
public class P{static void Main({for(;;)System.Xml.Serialization.XmlSerializer.FromTypes(new[]{typeof(P)});}}
```
We found the idea behind this leak in production code and researching it leads to [this article.](https://blogs.msdn.microsoft.com/tess/2006/02/15/net-memory-leak-xmlserializing-your-way-to-a-memory-leak/) The main problem is in this long quote from the article (read it for more info):
>
> Searching my code for `PurchaseOrde`r, I find this line of code in `page_load` of one of my pages `XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder), new XmlRootAttribute(“”));`
>
>
> This would seem like a pretty innocent piece of code. We create an `XMLSerializer` for `PurchaseOrder`. But what happens under the covers?
>
>
> If we take a look at the `XmlSerializer` constructor with Reflector we find that it calls `this.tempAssembly = XmlSerializer.GenerateTempAssembly(this.mapping, type, defaultNamespace, location, evidence);` which generates a temp (dynamic) assembly. So every time this code runs (i.e. every time the page is hit) it will generate a new assembly.
>
>
> The reason it generates an assembly is that it needs to generate functions for serializing and deserializing and these need to reside somewhere.
>
>
> Ok, fine… it creates an assembly, so what? When we’re done with it, it should just disappear right?
>
>
> Well… an assembly is not an object on the GC Heap, the GC is really unaware of assemblies, so it won’t get garbage collected. The only way to get rid of assemblies in 1.0 and 1.1 is to unload the app domain in which it resides.
>
>
> And therein lies the problem Dr Watson.
>
>
>
Running from the compiler in Visual Studio 2015 and using the Diagnostic Tools Window shows the following results after about 38 seconds. Note the Process memory is steadily climbing and the Garbage Collector (GC) keeps running but can't collect anything.
[![Diagnostic Tools Window](https://i.stack.imgur.com/2xuNb.png)](https://i.stack.imgur.com/2xuNb.png)
[Answer]
## C 30 bytes
```
f(){int *i=malloc(sizeof(4));}
```
## Valgrind Results:
```
==26311== HEAP SUMMARY:
==26311== in use at exit: 4 bytes in 1 blocks
==26311== total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==26311==
==26311== LEAK SUMMARY:
==26311== definitely lost: 4 bytes in 1 blocks
==26311== indirectly lost: 0 bytes in 0 blocks
==26311== possibly lost: 0 bytes in 0 blocks
==26311== still reachable: 0 bytes in 0 blocks
==26311== suppressed: 0 bytes in 0 blocks
==26311== Rerun with --leak-check=full to see details of leaked memory
```
[Answer]
## Dart, 76 bytes
```
import'dart:async';main()=>new Stream.periodic(Duration.ZERO).listen((_){});
```
A bit like the JavaScript answer. When you call `.listen` on a Dart stream object you are given back a StreamSubscription, which allows you to disconnect from the stream. However, if you throw that away, you can never unsubscribe from the stream, causing a leak. The only way the leak can be fixed is if the Stream itself gets collected, but its still referenced internally by a StreamController+Timer combo.
Unfortunately, Dart is too smart for the other stuff I've tried. `()async=>await new Completer().future` doesn't work because using await is the same as doing `new Completer().future.then(<continuation>)`, which allows the closure itself to be destroyed the second Completer isn't referenced (Completer holds a reference to the Future from `.future`, Future holds a reference to the continuation as a closure).
Also, Isolates (aka threads) are cleaned up by GC, so spawning yourself in a new thread and immediately pausing it (`import'dart:isolate';main(_)=>Isolate.spawn(main,0,paused:true);`) doesn't work. Even spawning an Isolate with an infinite loop (`import'dart:isolate';f(_){while(true){print('x');}}main()=>Isolate.spawn(f,0);`) kills the Isolate and exits the program.
Oh well.
[Answer]
# Swift, 12 bytes
```
[3,5][0...0]
```
## Explanation:
This is a de-facto memory leak that can occur in any language, regardless if the language uses memory manual management, automated reference counting (ARC, like Swift), or even sweeping garbage collection.
`[3,5]` is just an array literal. This array allocates enough memory for at least these those 2 elements. The `3` and `5` are just arbitrary.
Subscripting (indexing) an `Array<T>` produces an `ArraySlice<T>`. An `ArraySlice<T>` is a view into the memory of the Array it was created from.
`[3,5][0...0]` produces an `ArraySlice<Int>`, whose value is `[3]`. Note that the `3` in this slice is the same `3` element as the `3` in the original `Array` shown above, *not* a copy.
The resulting slice can then be stored into a variable and used. The original array is no longer referenced, so you would think it could be deallocated. However, it cannot.
Since the slice exposes a view onto the memory of the array it came from, the original array must be kept alive as long as the slice lives. So of the original `2` element-sizes worth of memory that were allocated, only first element-size worth of memory is being used, with the other the one being required to exist so as to not allocate the first. The second element-size of memory is de-factor leaked.
The solution to this problem is to not keep alive small slices of large arrays for long. If you need to persist the slice contents, then promote it to an Array, which will trigger the memory to be copied, thus removing the dependancy on the original array's memory:
```
Array([3,5][0...0])
```
[Answer]
# Solution 1: C (Mac OS X x86\_64), 109 bytes
The source for golf\_sol1.c
```
main[]={142510920,2336753547,3505849471,284148040,2370322315,2314740852,1351437506,1208291319,914962059,195};
```
The above program needs to be compiled with execution access on the \_\_DATA segment.
```
clang golf_sol1.c -o golf_sol1 -Xlinker -segprot -Xlinker __DATA -Xlinker rwx -Xlinker rwx
```
Then to execute the program run the following:
```
./golf_sol1 $(ruby -e 'puts "\xf5\xff\xff\xfe\xff\xff\x44\x82\x57\x7d\xff\x7f"')
```
## Results:
Unfortunately Valgrind does not watch for memory allocated from system calls, so I can't show a nice detected leak.
However we can look at vmmap to see the large chunk of allocated memory (MALLOC metadata).
```
VIRTUAL REGION
REGION TYPE SIZE COUNT (non-coalesced)
=========== ======= =======
Kernel Alloc Once 4K 2
MALLOC guard page 16K 4
MALLOC metadata 16.2M 7
MALLOC_SMALL 8192K 2 see MALLOC ZONE table below
MALLOC_TINY 1024K 2 see MALLOC ZONE table below
STACK GUARD 56.0M 2
Stack 8192K 3
VM_ALLOCATE (reserved) 520K 3 reserved VM address space (unallocated)
__DATA 684K 42
__LINKEDIT 70.8M 4
__TEXT 5960K 44
shared memory 8K 3
=========== ======= =======
TOTAL 167.0M 106
TOTAL, minus reserved VM space 166.5M 106
```
## Explanation
So I think I need to describe what's actually going on here, before moving onto the improved solution.
This main function is abusing C's missing type declaration (so it defaults to int without us needing to waste characters writing it), as well how symbols work. The linker only cares about whether of not it can find a symbol called `main` to call to. So here we're making main an array of int's which we're initializing with our shellcode that will be executed. Because of this, main will not be added to the \_\_TEXT segment but rather the \_\_DATA segment, reason we need to compile the program with an executable \_\_DATA segment.
The shellcode found in main is the following:
```
movq 8(%rsi), %rdi
movl (%rdi), %eax
movq 4(%rdi), %rdi
notl %eax
shrq $16, %rdi
movl (%rdi), %edi
leaq -0x8(%rsp), %rsi
movl %eax, %edx
leaq -9(%rax), %r10
syscall
movq (%rsi), %rsi
movl %esi, (%rsi)
ret
```
What this is doing is calling the syscall function to allocate a page of memory (the syscall mach\_vm\_allocate uses internally). RAX should equal 0x100000a (tells the syscall which function we want), while RDI holds the target for the allocation (in our case we want this to be mach\_task\_self()), RSI should hold the address to write the pointer to the newly created memory (so we are just pointing it to a section on the stack), RDX holds the size of the allocation (we're just passing in RAX or 0x100000a just to save on bytes), R10 holds the flags (we're indicating it can be allocated anywhere).
Now it's not plainly obvious where RAX and RDI are getting their values from. We know RAX needs to be 0x100000a, and RDI needs to be the value mach\_task\_self() returns. Luckily mach\_task\_self() is actually a macro for a variable (mach\_task\_self\_), which is at the same memory address every time (should change on reboot however). In my particular instance mach\_task\_self\_ happens to be located at 0x00007fff7d578244. So to cut down on instructions, we'll instead be passing in this data from argv. This is why we run the program with this expression `$(ruby -e 'puts "\xf5\xff\xff\xfe\xff\xff\x44\x82\x57\x7d\xff\x7f"')` for the first argument. The string is the two values combined, where the RAX value (0x100000a) is only 32 bits and has had a one's complement applied to it (so there's no null bytes; we just NOT the value to get the original), the next value is the RDI (0x00007fff7d578244) which has been shifted to the left with 2 extra junk bytes added to the end (again to exclude the null bytes, we just shift it back to the right to get it back to the original).
After the syscall we're writing to our newly allocated memory. The reason for this is because memory allocated using mach\_vm\_allocate (or this syscall) are actually VM pages, and are not automatically paged into memory. Rather they are reserved until data is written to them, and then those pages are mapped into memory. Wasn't sure if it would meet the requirements if it was only reserved.
For the next solution we'll be taking advantage of the fact that our shellcode has no null bytes, and so can move it outside of our program's code to reduce the size.
# Solution 2: C (Mac OS X x86\_64), 44 bytes
The source for golf\_sol2.c
```
main[]={141986632,10937,1032669184,2,42227};
```
The above program needs to be compiled with execution access on the \_\_DATA segment.
```
clang golf_sol2.c -o golf_sol2 -Xlinker -segprot -Xlinker __DATA -Xlinker rwx -Xlinker rwx
```
Then to execute the program run the following:
```
./golf_sol2 $(ruby -e 'puts "\xb8\xf5\xff\xff\xfe\xf7\xd0\x48\xbf\xff\xff\x44\x82\x57\x7d\xff\x7f\x48\xc1\xef\x10\x8b\x3f\x48\x8d\x74\x24\xf8\x89\xc2\x4c\x8d\x50\xf7\x0f\x05\x48\x8b\x36\x89\x36\xc3"')
```
The result should be the same as before, as we're making an allocation of the same size.
## Explanation
Follows much the same concept as solution 1, with the exception that we've moved the chunk of our leaking code outside of the program.
The shellcode found in main is now the following:
```
movq 8(%rsi), %rsi
movl $42, %ecx
leaq 2(%rip), %rdi
rep movsb (%rsi), (%rdi)
```
This basically copies the shellcode we pass in argv to be after this code (so after it has copied it, it will run the inserted shellcode). What works to our favour is that the \_\_DATA segment will be at least a page size, so even if our code isn't that big we can still "safely" write more. The downside is the ideal solution here, wouldn't even need the copy, instead it would just call and execute the shellcode in argv directly. But unfortunately, this memory does not have execution rights. We could change the rights of this memory, however it would require more code than simply copying it. An alternative strategy would be to change the rights from an external program (but more on that later).
The shellcode we pass to argv is the following:
```
movl $0xfefffff5, %eax
notl %eax
movq $0x7fff7d578244ffff, %rdi
shrq $16, %rdi
movl (%rdi), %edi
leaq -0x8(%rsp), %rsi
movl %eax, %edx
leaq -9(%rax), %r10
syscall
movq (%rsi), %rsi
movl %esi, (%rsi)
ret
```
This is much the same as our previous code, only difference being we're including the values for EAX and RDI directly.
# Possible Solution 1: C (Mac OS X x86\_64), 11 bytes
The idea of modifying the program externally, gives us the possible solution of moving the leaker to an external program. Where our actual program (submission) is just a dummy program, and the leaker program will allocate some memory in our target program. Now I wasn't certain if this would fall within the rules for this challenge, but sharing it nonetheless.
So if we were to use mach\_vm\_allocate in an external program with the target set to our challenge program, that could mean our challenge program would only need to be something along the lines of:
```
main=65259;
```
Where that shellcode is simply a short jump to itself (infinite jump/loop), so the program stays open and we can reference it from an external program.
# Possible Solution 2: C (Mac OS X x86\_64), 8 bytes
Funnily enough when I was looking at valgrind output, I saw that at least according to valgrind, dyld leaks memory. So effectively every program is leaking some memory. With this being the case, we could actually just make a program that does nothing (simply exits), and that will actually be leaking memory.
Source:
```
main(){}
==55263== LEAK SUMMARY:
==55263== definitely lost: 696 bytes in 17 blocks
==55263== indirectly lost: 17,722 bytes in 128 blocks
==55263== possibly lost: 0 bytes in 0 blocks
==55263== still reachable: 0 bytes in 0 blocks
==55263== suppressed: 16,316 bytes in 272 blocks
```
[Answer]
# c, 9 bytes
```
main(){}
```
Proof:
```
localhost/home/elronnd-10061: cat t.c
main(){}
localhost/home/elronnd-10062: valgrind gcc t.c
==10092== Memcheck, a memory error detector
==10092== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10092== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==10092== Command: gcc t.c
==10092==
t.c:1:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){}
^~~~
==10092==
==10092== HEAP SUMMARY:
==10092== in use at exit: 178,518 bytes in 73 blocks
==10092== total heap usage: 362 allocs, 289 frees, 230,415 bytes allocated
==10092==
==10092== LEAK SUMMARY:
==10092== definitely lost: 4,659 bytes in 8 blocks
==10092== indirectly lost: 82 bytes in 5 blocks
==10092== possibly lost: 0 bytes in 0 blocks
==10092== still reachable: 173,777 bytes in 60 blocks
==10092== suppressed: 0 bytes in 0 blocks
==10092== Rerun with --leak-check=full to see details of leaked memory
==10092==
==10092== For counts of detected and suppressed errors, rerun with: -v
==10092== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```
[Answer]
# [Plain English](https://github.com/Folds/english), ~~71~~ ~~70~~ ~~58~~ 35 bytes
Removed 1 byte by deleting a blank line. Removed 12 bytes by eliminating the "bogon" type definition, and using the parent "thing" type instead of the "bogon" subtype. Removed 23 bytes by switching from a complete program, to just a routine that leaks memory.
Golfed version:
```
To x:
Allocate memory for a thing.
```
Ungolfed version that is a complete program, uses a subtype definition, and does not leak memory:
```
A bogon is a thing.
To do something:
Allocate memory for a bogon.
Destroy the bogon.
To run:
Start up.
Do something.
Shut down.
```
If the golfed version of "x" is called, it will leak memory in proportion to the number of times "x" is called. In the golfed version, "Deallocate the thing." would fix the memory leak.
Plain English checks for memory leaks by default. When the version that leaks memory is run, a dialog box will appear just before the program shuts down. The dialog box has a title of "debug", a message of "1 drip", and an "OK" button. The more times the leaking function is called, the larger the number of "drips" in the message. When the version that does not leak memory is run, the dialog box does not appear.
In Plain English, a "thing" is a pointer to an item in a doubly-linked list. "Thing", "to start up", and "to shut down" are defined in a module called "the noodle", which needs to be copied in (usually as a separate file) into each project. "A", "the", "to", "to allocate memory", and "to destroy" are defined in the compiler.
] |
[Question]
[
Create a program which can rearrange pixels in image so it can't be recognized.
However your program should able to convert it back to original image.
You can write two functions - for encoding and decoding, however one function which applied repeatedly gives original image (example in math - `f(x) = 1 - x`) is a bonus.
Also producing some pattern in output gives bonus too.
Image may be represented as 1D/2D array or image object if your language supports it.
Note that you can only change order of pixels!
Will be logical to select as winner code which produces less recognizable image, however I don't know how to measure it exactly, all ways I can imagine can be cheated. Therefore I chose this question to be popularity contest - let users choose what the best answer!
Test image 1 (800 x 422 px):
![](https://i.stack.imgur.com/0RT8s.jpg)
Test image 2 (800 x 480 px):
![](https://i.stack.imgur.com/B5TbK.png)
Please provide with code output image.
[Answer]
## Python 2.7 (with PIL) - No Pseudorandomness
I break the image into 2 by 2 blocks (ignoring the remainder) and rotate each block by 180 degrees, then I do the same with 3 by 3 blocks, then 4, etc. up to some parameter BLKSZ. Then I do the same for BLKSZ-1, then BLKSZ-2, all the way back down to 3, then 2. This method reverses itself exactly; the unscramble function is the scramble function.
**The code**:
```
from PIL import Image
import math
im = Image.open("ST1.png", "r")
arr = im.load() #pixel data stored in this 2D array
def rot(A, n, x1, y1): #this is the function which rotates a given block
temple = []
for i in range(n):
temple.append([])
for j in range(n):
temple[i].append(arr[x1+i, y1+j])
for i in range(n):
for j in range(n):
arr[x1+i,y1+j] = temple[n-1-i][n-1-j]
xres = 800
yres = 480
BLKSZ = 50 #blocksize
for i in range(2, BLKSZ+1):
for j in range(int(math.floor(float(xres)/float(i)))):
for k in range(int(math.floor(float(yres)/float(i)))):
rot(arr, i, j*i, k*i)
for i in range(3, BLKSZ+1):
for j in range(int(math.floor(float(xres)/float(BLKSZ+2-i)))):
for k in range(int(math.floor(float(yres)/float(BLKSZ+2-i)))):
rot(arr, BLKSZ+2-i, j*(BLKSZ+2-i), k*(BLKSZ+2-i))
im.save("ST1OUT "+str(BLKSZ)+".png")
print("Done!")
```
Depending on the blocksize, you can make the computation eradicate all resemblance to the original image: (BLKSZ = 50)
![enter image description here](https://i.stack.imgur.com/fF5UB.jpg)
![enter image description here](https://i.stack.imgur.com/aqXGG.png)
Or make the computation efficient: (BLKSZ = 10)
![enter image description here](https://i.stack.imgur.com/jmUZM.jpg)
![enter image description here](https://i.stack.imgur.com/fDfQz.png)
[Answer]
# C#, Winform
**Edit** Changing the way you fill the coordinates array you can have different patterns - see below
Do you like this kind of pattern?
![LandScape](https://i.stack.imgur.com/uXGVH.jpg)
![Abstract](https://i.stack.imgur.com/AwbqU.png)
Bonus:
![Scream](https://i.stack.imgur.com/UPZ15.png)
![Scream Scrambled](https://i.stack.imgur.com/ho4Na.png)
Random swap exactly one time all pixels in upper half with all pixels in lower half.
Repeat the same procedure for unscrambling (bonus).
# Code
**Scramble.cs**
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
namespace Palette
{
public partial class Scramble : Form
{
public Scramble()
{
InitializeComponent();
}
public struct Coord
{
public int x, y;
}
private void Work(Bitmap srcb, Bitmap outb)
{
int w = srcb.Width, h = srcb.Height;
Coord[] coord = new Coord[w * h];
FastBitmap fsb = new FastBitmap(srcb);
FastBitmap fob = new FastBitmap(outb);
fsb.LockImage();
fob.LockImage();
ulong seed = 0;
int numpix = 0;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; numpix++, x++)
{
coord[numpix].x = x;
coord[numpix].y = y;
uint color = fsb.GetPixel(x, y);
seed += color;
fob.SetPixel(x, y, color);
}
fsb.UnlockImage();
fob.UnlockImage();
pbOutput.Refresh();
Application.DoEvents();
int half = numpix / 2;
int limit = half;
XorShift rng = new XorShift(seed);
progressBar.Visible = true;
progressBar.Maximum = limit;
fob.LockImage();
while (limit > 0)
{
int p = (int)(rng.next() % (uint)limit);
int q = (int)(rng.next() % (uint)limit);
uint color = fob.GetPixel(coord[p].x, coord[p].y);
fob.SetPixel(coord[p].x, coord[p].y, fob.GetPixel(coord[half+q].x, coord[half+q].y));
fob.SetPixel(coord[half+q].x, coord[half+q].y, color);
limit--;
if (p < limit)
{
coord[p]=coord[limit];
}
if (q < limit)
{
coord[half+q]=coord[half+limit];
}
if ((limit & 0xfff) == 0)
{
progressBar.Value = limit;
fob.UnlockImage();
pbOutput.Refresh();
fob.LockImage();
}
}
fob.UnlockImage();
pbOutput.Refresh();
progressBar.Visible = false;
}
void DupImage(PictureBox s, PictureBox d)
{
if (d.Image != null)
d.Image.Dispose();
d.Image = new Bitmap(s.Image.Width, s.Image.Height);
}
void GetImagePB(PictureBox pb, string file)
{
Bitmap bms = new Bitmap(file, false);
Bitmap bmp = bms.Clone(new Rectangle(0, 0, bms.Width, bms.Height), PixelFormat.Format32bppArgb);
bms.Dispose();
if (pb.Image != null)
pb.Image.Dispose();
pb.Image = bmp;
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\temp\\";
openFileDialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string file = openFileDialog.FileName;
GetImagePB(pbInput, file);
pbInput.Tag = file;
DupImage(pbInput, pbOutput);
Work(pbInput.Image as Bitmap, pbOutput.Image as Bitmap);
file = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(file) + ".scr.png";
pbOutput.Image.Save(file);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
//Adapted from Visual C# Kicks - http://www.vcskicks.com/
unsafe public class FastBitmap
{
private Bitmap workingBitmap = null;
private int width = 0;
private BitmapData bitmapData = null;
private Byte* pBase = null;
public FastBitmap(Bitmap inputBitmap)
{
workingBitmap = inputBitmap;
}
public BitmapData LockImage()
{
Rectangle bounds = new Rectangle(Point.Empty, workingBitmap.Size);
width = (int)(bounds.Width * 4 + 3) & ~3;
//Lock Image
bitmapData = workingBitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
pBase = (Byte*)bitmapData.Scan0.ToPointer();
return bitmapData;
}
private uint* pixelData = null;
public uint GetPixel(int x, int y)
{
pixelData = (uint*)(pBase + y * width + x * 4);
return *pixelData;
}
public uint GetNextPixel()
{
return *++pixelData;
}
public void GetPixelArray(int x, int y, uint[] Values, int offset, int count)
{
pixelData = (uint*)(pBase + y * width + x * 4);
while (count-- > 0)
{
Values[offset++] = *pixelData++;
}
}
public void SetPixel(int x, int y, uint color)
{
pixelData = (uint*)(pBase + y * width + x * 4);
*pixelData = color;
}
public void SetNextPixel(uint color)
{
*++pixelData = color;
}
public void UnlockImage()
{
workingBitmap.UnlockBits(bitmapData);
bitmapData = null;
pBase = null;
}
}
public class XorShift
{
private ulong x; /* The state must be seeded with a nonzero value. */
public XorShift(ulong seed)
{
x = seed;
}
public ulong next()
{
x ^= x >> 12; // a
x ^= x << 25; // b
x ^= x >> 27; // c
return x * 2685821657736338717L;
}
}
}
```
**Scramble.designer.cs**
```
namespace Palette
{
partial class Scramble
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.panel = new System.Windows.Forms.FlowLayoutPanel();
this.pbInput = new System.Windows.Forms.PictureBox();
this.pbOutput = new System.Windows.Forms.PictureBox();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.btnOpen = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbInput)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbOutput)).BeginInit();
this.SuspendLayout();
//
// panel
//
this.panel.AutoScroll = true;
this.panel.AutoSize = true;
this.panel.Controls.Add(this.pbInput);
this.panel.Controls.Add(this.pbOutput);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(748, 306);
this.panel.TabIndex = 3;
//
// pbInput
//
this.pbInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pbInput.Location = new System.Drawing.Point(3, 3);
this.pbInput.MinimumSize = new System.Drawing.Size(100, 100);
this.pbInput.Name = "pbInput";
this.pbInput.Size = new System.Drawing.Size(100, 300);
this.pbInput.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbInput.TabIndex = 3;
this.pbInput.TabStop = false;
//
// pbOutput
//
this.pbOutput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pbOutput.Location = new System.Drawing.Point(109, 3);
this.pbOutput.MinimumSize = new System.Drawing.Size(100, 100);
this.pbOutput.Name = "pbOutput";
this.pbOutput.Size = new System.Drawing.Size(100, 300);
this.pbOutput.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbOutput.TabIndex = 4;
this.pbOutput.TabStop = false;
//
// progressBar
//
this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.progressBar.Location = new System.Drawing.Point(0, 465);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(748, 16);
this.progressBar.TabIndex = 5;
//
// btnOpen
//
this.btnOpen.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnOpen.Location = new System.Drawing.Point(12, 429);
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(53, 30);
this.btnOpen.TabIndex = 6;
this.btnOpen.Text = "Start";
this.btnOpen.UseVisualStyleBackColor = true;
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// Scramble
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlDark;
this.ClientSize = new System.Drawing.Size(748, 481);
this.Controls.Add(this.btnOpen);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.panel);
this.Name = "Scramble";
this.Text = "Form1";
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbInput)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbOutput)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.FlowLayoutPanel panel;
private System.Windows.Forms.PictureBox pbOutput;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.PictureBox pbInput;
private System.Windows.Forms.Button btnOpen;
}
}
```
**Program.cs**
```
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Palette
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Scramble());
}
}
}
```
Check 'Unsafe code' in project property to compile.
**Complex pattern**
![Scramble](https://i.stack.imgur.com/lQ8Hd.png)
Change the first part of work function, up to Application.DoEvents:
```
int w = srcb.Width, h = srcb.Height;
string Msg = "Scramble";
Graphics gr = Graphics.FromImage(outb);
Font f = new Font("Arial", 100, FontStyle.Bold);
var size = gr.MeasureString(Msg, f);
f = new Font("Arial", w / size.Width * 110, FontStyle.Bold);
size = gr.MeasureString(Msg, f);
gr.DrawString(Msg, f, new SolidBrush(Color.White), (w - size.Width) / 2, (h - size.Height) / 2);
gr.Dispose();
Coord[] coord = new Coord[w * h];
FastBitmap fsb = new FastBitmap(srcb);
FastBitmap fob = new FastBitmap(outb);
fsb.LockImage();
fob.LockImage();
ulong seed = 1;
int numpix = h * w;
int c1 = 0, c2 = numpix;
int y2 = h / 2;
int p2 = numpix/2;
for (int p = 0; p < p2; p++)
{
for (int s = 1; s > -2; s -= 2)
{
int y = (p2+s*p) / w;
int x = (p2+s*p) % w;
uint d = fob.GetPixel(x, y);
if (d != 0)
{
c2--;
coord[c2].x = x;
coord[c2].y = y;
}
else
{
coord[c1].x = x;
coord[c1].y = y;
c1++;
}
fob.SetPixel(x, y, fsb.GetPixel(x, y));
}
}
fsb.UnlockImage();
fob.UnlockImage();
pbOutput.Refresh();
Application.DoEvents();
```
[Answer]
## C, arbitrary blurring, easily reversible
Late to the party. Here is my entry!
This method does a scrambling blur. I call it **scramblur**. It is extremely simple. In a loop, it chooses a random pixel and then swaps it with a randomly chosen nearby pixel in a toroidal canvas model. You specify the maximum distance defining what "nearby pixel" means (1 means always choose an adjacent pixel), the number of iterations, and optionally a random number seed. The larger the maximum distance and the larger the number of iterations, the blurrier the result.
It is reversible by specifying a negative number of iterations (this is simply a command-line interface convenience; there is actually no such thing as negative iterations). Internally, it uses a custom 64-bit LCPRNG (linear congruential pseudorandom number generator) and pre-generates a block of values. The table allows looping through the block either forward or reverse for scrambling or unscrambling, respectively.
## Demo
For the first two images, as you scroll down, each image is blurred using a higher maximum offset: Topmost is the original image (e.g., 0-pixel offset), followed by 1, 2, 4, 8, 16, 32, 64, 128, and finally 256. The iteration count is 10⁶ = 1,000,000 for all images below.
For the second two images, each image is blurred using a progressively *lower* offset — e.g., most blurry to least blurry — from a maximum offset of 256 down to 0. Enjoy!
![Landscape](https://i.stack.imgur.com/9DP0z.jpg)
![Abstract](https://i.stack.imgur.com/Ptjmy.jpg)
And for these next two images, you can see the progressions full-size **[here](https://i.stack.imgur.com/KtZvy.jpg)** and **[here](https://i.stack.imgur.com/tChbT.jpg)**:
![Breaking Bad](https://i.stack.imgur.com/se8qZ.png) ![Simpsons](https://i.stack.imgur.com/w4LoP.png)
## Code
I hacked this together in about an hour while waking up this morning and it contains almost no documentation. I might come back in a few days and add more documentation later if people request it.
```
//=============================================================================
// SCRAMBLUR
//
// This program is a image-processing competition entry which scrambles or
// descrambles an image based on a pseudorandom process. For more details,
// information, see:
//
// http://codegolf.stackexchange.com/questions/35005
//
// It is assumed that you have the NETPBM package of image-processing tools
// installed on your system. This can be obtained from:
//
// http://netpbm.sourceforge.net/
//
// or by using your system's package manager, e.g., yum, apt-get, port, etc.
//
// Input to the program is a 24-bit PNM image (type "P6"). Output is same.
// Example command-line invocation:
//
// pngtopnm original.png | scramblur 100 1000000 | pnmtopng >scrambled.png
// pngtopnm scrambled.png | scramblur 100 -1000000 | pnmtopng >recovered.png
//
//
// Todd S. Lehman, July 2014
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
typedef uint8_t uint8;
typedef uint64_t uint64;
//-----------------------------------------------------------------------------
// PIXEL STRUCTURE
#pragma pack(push, 1)
typedef struct
{
uint8 r, g, b; // Red, green, and blue color components
}
Pixel;
#pragma pack(pop)
//-----------------------------------------------------------------------------
// IMAGE STRUCTURE
typedef struct
{
int width; // Width of image in pixels
int height; // Height of image in pixels
int pixel_count; // Total number of pixels in image (e.g., width * height)
int maxval; // Maximum pixel component value (e.g., 255)
Pixel *data; // One-dimensional array of pixels
}
Image;
//-----------------------------------------------------------------------------
// 64-BIT LCG TABLE
static const long lcg64_table_length = 1000000; // 10⁶ entries => 8 Megabytes
static uint64 lcg64_table[lcg64_table_length];
//-----------------------------------------------------------------------------
// GET 64-BIT LCG VALUE FROM TABLE
uint64 lcg64_get(long const iteration)
{
return lcg64_table[iteration % lcg64_table_length];
}
//-----------------------------------------------------------------------------
// INITIALIZE 64-BIT LCG TABLE
void lcg64_init(uint64 const seed)
{
uint64 x = seed;
for (long iteration = 0; iteration < lcg64_table_length; iteration++)
{
uint64 const a = UINT64_C(6364136223846793005);
uint64 const c = UINT64_C(1442695040888963407);
x = (x * a) + c;
lcg64_table[iteration] = x;
}
}
//-----------------------------------------------------------------------------
// READ BINARY PNM IMAGE
Image image_read(FILE *const file)
{
Image image = { .data = NULL };
char *line = NULL;
size_t linecap = 0;
// Read image type. (Currently only P6 is supported here.)
if (getline(&line, &linecap, file) < 0) goto failure;
if (strcmp(line, "P6\n") != 0) goto failure;
// Read width and height of image in pixels.
{
if (getline(&line, &linecap, file) < 0) goto failure;
char *pwidth = &line[0];
char *pheight = strchr(line, ' ');
if (pheight != NULL) pheight++; else goto failure;
image.width = atoi(pwidth);
image.height = atoi(pheight);
image.pixel_count = image.width * image.height;
}
// Read maximum color value. (Currently only 255 is supported here.)
{
if (getline(&line, &linecap, file) < 0) goto failure;
image.maxval = atoi(line);
if (image.maxval != 255)
goto failure;
}
// Allocate image buffer and read image data.
if (!(image.data = calloc(image.pixel_count, sizeof(Pixel))))
goto failure;
if (fread(image.data, sizeof(Pixel), image.pixel_count, file) !=
image.pixel_count)
goto failure;
success:
free(line);
return image;
failure:
free(line);
free(image.data); image.data = NULL;
return image;
}
//-----------------------------------------------------------------------------
// WRITE BINARY PNM IMAGE
void image_write(const Image image, FILE *const file)
{
printf("P6\n");
printf("%d %d\n", image.width, image.height);
printf("%d\n", image.maxval);
(void)fwrite(image.data, sizeof(Pixel), image.pixel_count, file);
}
//-----------------------------------------------------------------------------
// DISCARD IMAGE
void image_discard(Image image)
{
free(image.data);
}
//-----------------------------------------------------------------------------
// SCRAMBLE OR UNSCRAMBLE IMAGE
void image_scramble(Image image,
int const max_delta,
long const iterations,
uint64 const lcg64_seed)
{
if (max_delta == 0) return;
int neighborhood1 = (2 * max_delta) + 1;
int neighborhood2 = neighborhood1 * neighborhood1;
lcg64_init(lcg64_seed);
long iteration_start = (iterations >= 0)? 0 : -iterations;
long iteration_end = (iterations >= 0)? iterations : 0;
long iteration_inc = (iterations >= 0)? 1 : -1;
for (long iteration = iteration_start;
iteration != iteration_end;
iteration += iteration_inc)
{
uint64 lcg64 = lcg64_get(iteration);
// Choose random pixel.
int pixel_index = (int)((lcg64 >> 0) % image.pixel_count);
// Choose random pixel in the neighborhood.
int d2 = (int)((lcg64 >> 8) % neighborhood2);
int dx = (d2 % neighborhood1) - (neighborhood1 / 2);
int dy = (d2 / neighborhood1) - (neighborhood1 / 2);
int other_pixel_index = pixel_index + dx + (dy * image.width);
while (other_pixel_index < 0)
other_pixel_index += image.pixel_count;
other_pixel_index %= image.pixel_count;
// Swap pixels.
Pixel t = image.data[pixel_index];
image.data[pixel_index] = image.data[other_pixel_index];
image.data[other_pixel_index] = t;
}
}
//-----------------------------------------------------------------------------
int main(const int argc, char const *const argv[])
{
int max_delta = (argc > 1)? atoi(argv[1]) : 1;
long iterations = (argc > 2)? atol(argv[2]) : 1000000;
uint64 lcg64_seed = (argc > 3)? (uint64)strtoull(argv[3], NULL, 10) : 0;
Image image = image_read(stdin);
if (!image.data) { fprintf(stderr, "Invalid input\n"), exit(1); }
image_scramble(image, max_delta, iterations, lcg64_seed);
image_write(image, stdout);
image_discard(image);
return 0;
}
```
[Answer]
# Python 3.4
* **Bonus 1:** Self inverse: repeating restores the original image.
* **Optional key image:** original image can only be restored by using the same key image again.
* **Bonus 2:** Producing pattern in the output: key image is approximated in the scrambled pixels.
When bonus 2 is achieved, by using an additional key image, bonus 1 is not lost. The program is still self inverse, provided it is run with the same key image again.
# Standard usage
### Test image 1:
![Scrambled test image 1](https://i.stack.imgur.com/k5jrq.jpg "Scrambled test image 1")
### Test image 2:
![Scrambled test image 2](https://i.stack.imgur.com/W6jLk.png "Scrambled test image 2")
Running the program with a single image file as its argument saves an image file with the pixels scrambled evenly over the whole image. Running it again with the scrambled output saves an image file with the scrambling applied again, which restores the original since the scrambling process is its own inverse.
The scrambling process is self inverse because the list of all pixels is split into 2-cycles, so that every pixel is swapped with one and only one other pixel. Running it a second time swaps every pixel with the pixel it was first swapped with, putting everything back to how it started. If there are an odd number of pixels there will be one that does not move.
**Thanks to [mfvonh's answer](https://codegolf.stackexchange.com/a/35032/20283) as the first to suggest 2-cycles.**
# Usage with a key image
### Scrambling Test image 1 with Test image 2 as the key image
![Scramble test 1 with test 2](https://i.stack.imgur.com/QIoxu.jpg "Scramble test 1 with test 2")
### Scrambling Test image 2 with Test image 1 as the key image
![Scramble test 2 with test 1](https://i.stack.imgur.com/rqvga.png "Scramble test 2 with test 1")
Running the program with a second image file argument (the key image) divides the original image into regions based on the key image. Each of these regions is divided into 2-cycles separately, so that all of the scrambling occurs within regions, and pixels are not moved from one region to another. This spreads out the pixels over each region and so the regions become a uniform speckled colour, but with a slightly different average colour for each region. This gives a very rough approximation of the key image, in the wrong colours.
Running again swaps the same pairs of pixels in each region, so each region is restored to its original state, and the image as a whole reappears.
**Thanks to [edc65's answer](https://codegolf.stackexchange.com/a/35034/20283) as the first to suggest dividing the image into regions.** I wanted to expand on this to use arbitrary regions, but the approach of swapping everything in region 1 with everything in region 2 meant that the regions had to be of identical size. My solution is to keep the regions insulated from each other, and simply shuffle each region into itself. Since regions no longer need to be of similar size it becomes simpler to apply arbitrary shaped regions.
# Code
```
import os.path
from PIL import Image # Uses Pillow, a fork of PIL for Python 3
from random import randrange, seed
def scramble(input_image_filename, key_image_filename=None,
number_of_regions=16777216):
input_image_path = os.path.abspath(input_image_filename)
input_image = Image.open(input_image_path)
if input_image.size == (1, 1):
raise ValueError("input image must contain more than 1 pixel")
number_of_regions = min(int(number_of_regions),
number_of_colours(input_image))
if key_image_filename:
key_image_path = os.path.abspath(key_image_filename)
key_image = Image.open(key_image_path)
else:
key_image = None
number_of_regions = 1
region_lists = create_region_lists(input_image, key_image,
number_of_regions)
seed(0)
shuffle(region_lists)
output_image = swap_pixels(input_image, region_lists)
save_output_image(output_image, input_image_path)
def number_of_colours(image):
return len(set(list(image.getdata())))
def create_region_lists(input_image, key_image, number_of_regions):
template = create_template(input_image, key_image, number_of_regions)
number_of_regions_created = len(set(template))
region_lists = [[] for i in range(number_of_regions_created)]
for i in range(len(template)):
region = template[i]
region_lists[region].append(i)
odd_region_lists = [region_list for region_list in region_lists
if len(region_list) % 2]
for i in range(len(odd_region_lists) - 1):
odd_region_lists[i].append(odd_region_lists[i + 1].pop())
return region_lists
def create_template(input_image, key_image, number_of_regions):
if number_of_regions == 1:
width, height = input_image.size
return [0] * (width * height)
else:
resized_key_image = key_image.resize(input_image.size, Image.NEAREST)
pixels = list(resized_key_image.getdata())
pixel_measures = [measure(pixel) for pixel in pixels]
distinct_values = list(set(pixel_measures))
number_of_distinct_values = len(distinct_values)
number_of_regions_created = min(number_of_regions,
number_of_distinct_values)
sorted_distinct_values = sorted(distinct_values)
while True:
values_per_region = (number_of_distinct_values /
number_of_regions_created)
value_to_region = {sorted_distinct_values[i]:
int(i // values_per_region)
for i in range(len(sorted_distinct_values))}
pixel_regions = [value_to_region[pixel_measure]
for pixel_measure in pixel_measures]
if no_small_pixel_regions(pixel_regions,
number_of_regions_created):
break
else:
number_of_regions_created //= 2
return pixel_regions
def no_small_pixel_regions(pixel_regions, number_of_regions_created):
counts = [0 for i in range(number_of_regions_created)]
for value in pixel_regions:
counts[value] += 1
if all(counts[i] >= 256 for i in range(number_of_regions_created)):
return True
def shuffle(region_lists):
for region_list in region_lists:
length = len(region_list)
for i in range(length):
j = randrange(length)
region_list[i], region_list[j] = region_list[j], region_list[i]
def measure(pixel):
'''Return a single value roughly measuring the brightness.
Not intended as an accurate measure, simply uses primes to prevent two
different colours from having the same measure, so that an image with
different colours of similar brightness will still be divided into
regions.
'''
if type(pixel) is int:
return pixel
else:
r, g, b = pixel[:3]
return r * 2999 + g * 5869 + b * 1151
def swap_pixels(input_image, region_lists):
pixels = list(input_image.getdata())
for region in region_lists:
for i in range(0, len(region) - 1, 2):
pixels[region[i]], pixels[region[i+1]] = (pixels[region[i+1]],
pixels[region[i]])
scrambled_image = Image.new(input_image.mode, input_image.size)
scrambled_image.putdata(pixels)
return scrambled_image
def save_output_image(output_image, full_path):
head, tail = os.path.split(full_path)
if tail[:10] == 'scrambled_':
augmented_tail = 'rescued_' + tail[10:]
else:
augmented_tail = 'scrambled_' + tail
save_filename = os.path.join(head, augmented_tail)
output_image.save(save_filename)
if __name__ == '__main__':
import sys
arguments = sys.argv[1:]
if arguments:
scramble(*arguments[:3])
else:
print('\n'
'Arguments:\n'
' input image (required)\n'
' key image (optional, default None)\n'
' number of regions '
'(optional maximum - will be as high as practical otherwise)\n')
```
# JPEG image burn
.jpg files are processed very quickly, but at the cost of running too hot. This leaves a burned in after image when the original is restored:
![jpg burn](https://i.stack.imgur.com/jg31j.jpg "Evidence of jpg overheating")
But seriously, a lossy format will result in some of the pixel colours being changed slightly, which in itself makes the output invalid. When a key image is used and the shuffling of pixels is restricted to regions, all of the distortion is kept within the region it happened in, and then spread out evenly over that region when the image is restored. The difference in average distortion between regions leaves a visible difference between them, so the regions used in the scrambling process are still visible in the restored image.
Converting to .png (or any non-lossy format) before scrambling ensures that the unscrambled image is identical to the original with no burn or distortion:
![png with no burn](https://i.stack.imgur.com/35SUh.png "png with no burn")
# Little details
* A minimum size of 256 pixels is imposed on regions. If the image were allowed to split into regions that are too small, then the original image would still be partially visible after scrambling.
* If there's more than one region with an odd number of pixels then one pixel from the second region is reassigned to the first, and so on. This means there can only ever be one region with an odd number of pixels, and so only one pixel will remain unscrambled.
* There is a third optional argument which restricts the number of regions. Setting this to 2 for example will give two tone scrambled images. This may look better or worse depending on the images involved. If a number is specified here, the image can only be restored using the same number again.
* The number of distinct colours in the original image also limits the number of regions. If the original image is two tone then regardless of the key image or the third argument, there can only be a maximum of 2 regions.
[Answer]
Here is a non-random transform for a change
1. Put all even columns on the left and all odd columns on the right.
2. repeat `nx` times
3. do the same for rows `ny` times
The transformation is almost self-inverse, repeating the transformation a total of `size_x` times (in x-direction) returns the original image. I didn't figure out the exact math, but using integer multiples of `int(log_2(size_x))` produces the best shuffling with the smallest ghost images
![shuffled mountains](https://i.stack.imgur.com/zosp7.jpg)
![enter image description here](https://i.stack.imgur.com/qJSB7.png)
```
from numpy import *
from pylab import imread, imsave
def imshuffle(im, nx=0, ny=0):
for i in range(nx):
im = concatenate((im[:,0::2], im[:,1::2]), axis=1)
for i in range(ny):
im = concatenate((im[0::2,:], im[1::2,:]), axis=0)
return im
im1 = imread('circles.png')
im2 = imread('mountain.jpg')
imsave('s_circles.png', imshuffle(im1, 7,7))
imsave('s_mountain.jpg', imshuffle(im2, 8,9))
```
This is how the first steps 20 iterations look like (nx=ny, note the effect of different resolutions)
![enter image description here](https://i.stack.imgur.com/Tz0BP.jpg)
[Answer]
## Mathematica
This is pretty straightforward. I pick `5 * nPixels` random coordinate pairs and swap those two pixels (which completely obscures the picture). To unscramble it I do the same in reverse. Of course, I need to seed the PRNG to get the same coordinate pairs on both steps.
```
scramble[image_] := Module[
{data, h, w, temp},
data = ImageData@image;
{h, w} = Most@Dimensions@data;
SeedRandom[42];
(
temp = data[[#[[1]], #[[2]]]];
data[[#[[1]], #[[2]]]] = data[[#2[[1]], #2[[2]]]];
data[[#2[[1]], #2[[2]]]] = temp;
) & @@@
Partition[
Transpose@{RandomInteger[h - 1, 10*h*w] + 1,
RandomInteger[w - 1, 10*h*w] + 1}, 2];
Image@data
];
unscramble[image_] := Module[
{data, h, w, temp},
data = ImageData@image;
{h, w} = Most@Dimensions@data;
SeedRandom[42];
(
temp = data[[#[[1]], #[[2]]]];
data[[#[[1]], #[[2]]]] = data[[#2[[1]], #2[[2]]]];
data[[#2[[1]], #2[[2]]]] = temp;
) & @@@
Reverse@
Partition[
Transpose@{RandomInteger[h - 1, 10*h*w] + 1,
RandomInteger[w - 1, 10*h*w] + 1}, 2];
Image@data
];
```
The only difference between the two functions is `Reverse@` in `unscramble`. Both functions take an actual image object. You can use them as follows:
```
in = Import["D:\\Development\\CodeGolf\\image-scrambler\\circles.png"]
scr = scramble[im]
out = unscramble[scr]
```
`out` and `in` are identical. Here is what `scr` looks like:
![enter image description here](https://i.stack.imgur.com/bjTqo.jpg)
![enter image description here](https://i.stack.imgur.com/7RLtt.png)
[Answer]
## C# (+ Bonus for Symmetric Algorithm)
This works by finding an `x` such that `x^2 == 1 mod (number of pixels in image)`, and then multiplying each pixel's index by `x` in order to find its new location. This lets you use the exact same algorithm to scramble and unscramble an image.
```
using System.Drawing;
using System.IO;
using System.Numerics;
namespace RearrangePixels
{
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
ScrambleUnscramble(arg);
}
static void ScrambleUnscramble(string fileName)
{
using (var origImage = new Bitmap(fileName))
using (var newImage = new Bitmap(origImage))
{
BigInteger totalPixels = origImage.Width * origImage.Height;
BigInteger modSquare = GetSquareRootOf1(totalPixels);
for (var x = 0; x < origImage.Width; x++)
{
for (var y = 0; y < origImage.Height; y++)
{
var newNum = modSquare * GetPixelNumber(new Point(x, y), origImage.Size) % totalPixels;
var newPoint = GetPoint(newNum, origImage.Size);
newImage.SetPixel(newPoint.X, newPoint.Y, origImage.GetPixel(x, y));
}
}
newImage.Save("scrambled-" + Path.GetFileName(fileName));
}
}
static BigInteger GetPixelNumber(Point point, Size totalSize)
{
return totalSize.Width * point.Y + point.X;
}
static Point GetPoint(BigInteger pixelNumber, Size totalSize)
{
return new Point((int)(pixelNumber % totalSize.Width), (int)(pixelNumber / totalSize.Width));
}
static BigInteger GetSquareRootOf1(BigInteger modulo)
{
for (var i = (BigInteger)2; i < modulo - 1; i++)
{
if ((i * i) % modulo == 1)
return i;
}
return modulo - 1;
}
}
}
```
![first test image, scrambled](https://i.stack.imgur.com/MuZdY.jpg)
![second test image, scrambled](https://i.stack.imgur.com/XeHkl.png)
[Answer]
# C#, self-inverse, no randomness
If the original image has dimensions that are powers of two, then each row and column is exchanged with the row and column that has the reversed bit pattern, for example for a image of width 256 then row 0xB4 is exchanged with row 0x2D. Images of other sizes are split into the rectangles with sides of powers of 2.
```
namespace CodeGolf
{
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
Scramble(arg);
}
static void Scramble(string fileName)
{
using (var origImage = new System.Drawing.Bitmap(fileName))
using (var tmpImage = new System.Drawing.Bitmap(origImage))
{
{
int x = origImage.Width;
while (x > 0) {
int xbit = x & -x;
do {
x--;
var xalt = BitReverse(x, xbit);
for (int y = 0; y < origImage.Height; y++)
tmpImage.SetPixel(xalt, y, origImage.GetPixel(x, y));
} while ((x & (xbit - 1)) != 0);
}
}
{
int y = origImage.Height;
while (y > 0) {
int ybit = y & -y;
do {
y--;
var yalt = BitReverse(y, ybit);
for (int x = 0; x < origImage.Width; x++)
origImage.SetPixel(x, yalt, tmpImage.GetPixel(x, y));
} while ((y & (ybit - 1)) != 0);
}
}
origImage.Save(System.IO.Path.GetFileNameWithoutExtension(fileName) + "-scrambled.png");
}
}
static int BitReverse(int n, int bit)
{
if (bit < 4)
return n;
int r = n & ~(bit - 1);
int tmp = 1;
while (bit > 1) {
bit >>= 1;
if ((n & bit) != 0)
r |= tmp;
tmp <<= 1;
}
return r;
}
}
}
```
First image:
![Scrambled first image](https://i.stack.imgur.com/1Ciaj.jpg)
Second image:
![Scrambled second image](https://i.stack.imgur.com/nGiei.png)
[Answer]
# Python 2 (self-inverse, no randomness, context-sensitive)
This won't win any prizes for "least recognizable", but maybe it can score as "interesting". :-)
I wanted to make something context-sensitive, where the scrambling of the pixels actually depends on the image itself.
The idea is quite simple: Sort all pixels according to some arbitrary value derived from the pixel's colour and then swap the positions of the first pixel in that list with the last, the second with the second to last, and so on.
Unfortunately in this simple approach there is a problem with pixels of the same colour, so to still make it self-inverse my program grew a bit more complicated...
```
from PIL import Image
img = Image.open('1.png', 'r')
pixels = img.load()
size_x, size_y = img.size
def f(colour):
r,g,b = colour[:3]
return (abs(r-128)+abs(g-128)+abs(b-128))//128
pixel_list = [(x,y,f(pixels[x,y])) for x in xrange(size_x) for y in xrange(size_y)]
pixel_list.sort(key=lambda x: x[2])
print "sorted"
colours = {}
for p in pixel_list:
if p[2] in colours:
colours[p[2]] += 1
else:
colours[p[2]] = 1
print "counted"
for n in set(colours.itervalues()):
pixel_group = [p for p in pixel_list if colours[p[2]]==n]
N = len(temp_list)
for p1, p2 in zip(pixel_group[:N//2], pixel_group[-1:-N//2:-1]):
pixels[p1[0],p1[1]], pixels[p2[0],p2[1]] = pixels[p2[0],p2[1]], pixels[p1[0],p1[1]]
print "swapped"
img.save('1scrambled.png')
print "saved"
```
This is the result:
![(abs(r-128)+abs(g-128)+abs(b-128))//128](https://i.stack.imgur.com/2WQAV.jpg)
![(abs(r-128)+abs(g-128)+abs(b-128))//128](https://i.stack.imgur.com/goOQ6.png)
You can achieve quite different results by changing the hash function `f`:
* `r-g-b`:
![r-g-b](https://i.stack.imgur.com/bvle5.png)
* `r+g/2.**8+b/2.**16`:
![r+g/2.**8+b/2.**16](https://i.stack.imgur.com/bGJtE.png)
* `math.sin(r+g*2**8+b*2**16)`:
![math.sin(r+g*2**8+b*2**16)](https://i.stack.imgur.com/WgPND.png)
* `(r+g+b)//600`:
![(r+g+b)//600](https://i.stack.imgur.com/GErMI.png)
* `0`:
![0](https://i.stack.imgur.com/7PweL.png)
[Answer]
# C#
Same method for scrambling and unscrambling.
I would appreciate suggestions on improving this.
```
using System;
using System.Drawing;
using System.Linq;
public class Program
{
public static Bitmap Scramble(Bitmap bmp)
{
var res = new Bitmap(bmp);
var r = new Random(1);
// Making lists of even and odd numbers and shuffling them
// They contain numbers between 0 and picture.Width (or picture.Height)
var rX = Enumerable.Range(0, bmp.Width / 2).Select(x => x * 2).OrderBy(x => r.Next()).ToList();
var rrX = rX.Select(x => x + 1).OrderBy(x => r.Next()).ToList();
var rY = Enumerable.Range(0, bmp.Height / 2).Select(x => x * 2).OrderBy(x => r.Next()).ToList();
var rrY = rY.Select(x => x + 1).OrderBy(x => r.Next()).ToList();
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < rX.Count; x++)
{
// Swapping pixels in a row using lists rX and rrX
res.SetPixel(rrX[x], y, bmp.GetPixel(rX[x], y));
res.SetPixel(rX[x], y, bmp.GetPixel(rrX[x], y));
}
}
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < rY.Count; y++)
{
// Swapping pixels in a column using sets rY and rrY
var px = res.GetPixel(x, rrY[y]);
res.SetPixel(x, rrY[y], res.GetPixel(x, rY[y]));
res.SetPixel(x, rY[y], px);
}
}
return res;
}
}
```
Outputs results in psychedelic plaid
![First one](https://i.stack.imgur.com/9H231.jpg)
![Second one](https://i.stack.imgur.com/agw85.png)
[Answer]
# Mathematica (+ bonus)
This collapses the color channels and scrambles the image as one long list of data. The result is an even less recognizable scrambled version because it does not have the same color distribution as the original (since that data was scrambled too). This is most obvious in the second scrambled image, but if you look closely you will see the same effect in the first as well. The function is its own inverse.
There was a comment that this may not be valid because it scrambles per channel. I think it should be, but it's not a big deal. The only change necessary to scramble whole pixels (instead of per channel) would be to change `Flatten @ x` to `Flatten[x, 1]` :)
```
ClearAll @ f;
f @ x_ :=
With[
{r = SeedRandom[Times @@ Dimensions @ x], f = Flatten @ x},
ArrayReshape[
Permute[f, Cycles @ Partition[RandomSample @ Range @ Length @ f, 2]],
Dimensions @ x]]
```
### Explanation
Defines a function `f` that takes a 2-dimensional array `x`. The function uses the product of the image's dimensions as a random seed, and then flattens the array to a 1-dimensional list `f` (locally shadowed). Then it creates a list of the form `{1, 2, ... n}` where `n` is the length of `f`, randomly permutes that list, partitions it into segments of 2 (so, e.g., `{{1, 2}, {3, 4}, ...}` (dropping last number if the dimensions are both odd), and then permutes `f` by swapping the values at the positions indicated in each sublist just created, and finally it reshapes the permuted list back to the original dimensions of `x`. It scrambles per channel because in addition to collapsing the image dimensions the `Flatten` command also collapses the channel data in each pixel. The function is its own inverse because the cycles include only two pixels each.
### Usage
```
img1=Import@"https://i.stack.imgur.com/2C2TY.jpg"//ImageData;
img2=Import@"https://i.stack.imgur.com/B5TbK.png"//ImageData;
f @ img1 // Image
```
![enter image description here](https://i.stack.imgur.com/P513d.jpg)
```
f @ f @ img1 // Image
```
![enter image description here](https://i.stack.imgur.com/dhW1c.jpg)
```
f @ img2 // Image
```
![enter image description here](https://i.stack.imgur.com/CyFJH.png)
```
f @ f @ img2 // Image
```
![enter image description here](https://i.stack.imgur.com/ln0gK.png)
Here's using `Flatten[x, 1]`.
```
g@x_ := With[{r = SeedRandom[Times @@ Dimensions @ x], f = Flatten[x, 1]},
ArrayReshape[
Permute[f, Cycles@Partition[RandomSample@Range@Length@f, 2]],
Dimensions@x]]
g@img2 // Image
```
![enter image description here](https://i.stack.imgur.com/iJ7zq.png)
[Answer]
# Matlab (+ bonus)
I basically switch the position of two pixels at random and tag each pixel that has been switched so it will not be switched again. The same script can be used again for the 'decryption' because I reset the random number generator each time. This is done untill almost all pixels are switched (thats why stepsize is greater than 2)
EDIT: Just saw that Martin Büttner used a similar approach - I did not intend to copy the idea - I began writing my code when there were no answers, so sorry for that. I still think my version uses some different ideas=) (And my algorithm is far more inefficient if you look at the bit where the two random coordinates get picked^^)
## Images
![1](https://i.stack.imgur.com/zyrk8.jpg)
![2](https://i.stack.imgur.com/iwUlw.png)
## Code
```
img = imread('shuffle_image2.bmp');
s = size(img)
rand('seed',0)
map = zeros(s(1),s(2));
for i = 1:2.1:s(1)*s(2) %can use much time if stepsize is 2 since then every pixel has to be exchanged
while true %find two unswitched pixels
a = floor(rand(1,2) .* [s(1),s(2)] + [1,1]);
b = floor(rand(1,2) .* [s(1),s(2)] + [1,1]);
if map(a(1),a(2)) == 0 && map(b(1),b(2)) == 0
break
end
end
%switch
map(a(1),a(2)) = 1;
map(b(1),b(2)) = 1;
t = img(a(1),a(2),:);
img(a(1),a(2),:) = img(b(1),b(2),:);
img(b(1),b(2),:) = t;
end
image(img)
imwrite(img,'output2.png')
```
[Answer]
# Mathematica-Use a permutation to scramble and its inverse to unscramble.
A jpg image is an three-dimensional array of `{r,g,b}` pixel colors. (The 3 dimensions structure the set of pixels by row, column, and color). It can be flattened into a list of `{r,g,b}` triples, then permuted according to a "known" cycle list, and finally re-assembled into an array of the original dimensions. The result is a scrambled image.
Unscrambling takes the scrambled image and processes it with the reverse of the cycle list. It outputs, yes, the original image.
So a single function (in the present case, `scramble`) serves for scrambling as well as unscrambling pixels in an image.
An image is input along with a seed number (to ensure that the Random number generator will be in the same state for scrambling and unscrambling). When the parameter, reverse, is False, the function will scramble. When it is True, the function will unscramble.
---
**scramble**
The pixels are flattened and a random list of cycles is generated.
Permute uses cycles to switch positions of pixels in the flattened list.
**unscramble**
The same function, `scramble` is used for unscrambling.
However the order of the cycle list is reversed.
```
scramble[img_,s_,reverse_:False,imgSize_:300]:=
Module[{i=ImageData[img],input,r},input=Flatten[i,1];SeedRandom[s];
r=RandomSample@Range[Length[input]];Image[ArrayReshape[Permute[input,
Cycles[{Evaluate@If[reverse,Reverse@r,r]}]],Dimensions[i]],ImageSize->imgSize]]
```
---
## Examples
The same seed (37) is used for scrambling and unscrambling.
This produces the scrambled image of the mountain. The picture below shows that the variable scrambledMount can be substituted by the actual image of the mountain scene.
```
scrambledMount=scramble[mountain, 37, True]
```
![mount1](https://i.stack.imgur.com/EK1i9.png)
---
Now we run the inverse; scrambledMount is entered and the original picture is recuperated.
```
scramble[scrambledMount, 37, True]
```
![mount2](https://i.stack.imgur.com/pPqzN.png)
---
Same thing for the circles:
![circles1](https://i.stack.imgur.com/EUBR1.png)
---
```
scramble[scrambledCircles, 37, True]
```
![circles2](https://i.stack.imgur.com/YlBm9.png)
[Answer]
# Python
I like this puzzle, he seemed interesting and I came with a wraped and Movement function to apply on the image.
### Wraped
I read the picture as a text (from left to right, up and down) and write it as a snail shell.
This function is cyclic: there is a n in N, f^(n)(x)=x
for example, for a picture of 4\*2, f(f(f(x)))=x
### Movement
I take a random number and move each column and ligne from it
## Code
```
# Opening and creating pictures
img = Image.open("/home/faquarl/Bureau/unnamed.png")
PM1 = img.load()
(w,h) = img.size
img2 = Image.new( 'RGBA', (w,h), "black")
PM2 = img2.load()
img3 = Image.new( 'RGBA', (w,h), "black")
PM3 = img3.load()
# Rotation
k = 0
_i=w-1
_j=h-1
_currentColMin = 0
_currentColMax = w-1
_currentLigMin = 0
_currentLigMax = h-1
_etat = 0
for i in range(w):
for j in range(h):
PM2[_i,_j]=PM1[i,j]
if _etat==0:
if _currentColMax == _currentColMin:
_j -= 1
_etat = 2
else:
_etat = 1
_i -= 1
elif _etat==1:
_i -= 1
if _j == _currentLigMax and _i == _currentColMin:
_etat = 2
elif _etat==2:
_j -= 1
_currentLigMax -= 1
if _j == _currentLigMin and _i == _currentColMin:
_etat = 5
else:
_etat = 3
elif _etat==3:
_j -= 1
if _j == _currentLigMin and _i == _currentColMin:
_etat = 4
elif _etat==4:
_i += 1
_currentColMin += 1
if _j == _currentLigMin and _i == _currentColMax:
_etat = 7
else:
_etat = 5
elif _etat==5:
_i += 1
if _j == _currentLigMin and _i == _currentColMax:
_etat = 6
elif _etat==6:
_j += 1
_currentLigMin += 1
if _j == _currentLigMax and _i == _currentColMax:
_etat = 1
else:
_etat = 7
elif _etat==7:
_j += 1
if _j == _currentLigMax and _i == _currentColMax:
_etat = 8
elif _etat==8:
_i -= 1
_currentColMax -= 1
if _j == _currentLigMax and _i == _currentColMin:
_etat = 3
else:
_etat = 1
k += 1
if k == w * h:
i = w
j = h
# Movement
if w>h:z=w
else:z=h
rand.seed(z)
a=rand.randint(0,h)
for i in range(w):
for j in range(h):
if i%2==0:
PM3[(i+a)%w,(j+a)%h]=PM2[i,j]
else:
PM3[(i-a)%w,(j-a)%h]=PM2[i,j]
# Rotate Again
```
## Pictures
First rotation:
![enter image description here](https://i.stack.imgur.com/PcTEf.jpg)
then permutation:
![enter image description here](https://i.stack.imgur.com/srRdm.jpg)
And with the last rotaion:
![enter image description here](https://i.stack.imgur.com/CiZpr.jpg)
As for the other example:
![enter image description here](https://i.stack.imgur.com/vrhCv.png)
[Answer]
# VB.NET (+ bonus)
This uses flawr's idea, thanks to him, however this uses different swapping and checking algorithm. Program encodes and decodes the same way.
```
Imports System
Module Module1
Sub swap(ByVal b As Drawing.Bitmap, ByVal i As Integer, ByVal j As Integer)
Dim c1 As Drawing.Color = b.GetPixel(i Mod b.Width, i \ b.Width)
Dim c2 As Drawing.Color = b.GetPixel(j Mod b.Width, j \ b.Width)
b.SetPixel(i Mod b.Width, i \ b.Width, c2)
b.SetPixel(j Mod b.Width, j \ b.Width, c1)
End Sub
Sub Main(ByVal args() As String)
For Each a In args
Dim f As New IO.FileStream(a, IO.FileMode.Open)
Dim b As New Drawing.Bitmap(f)
f.Close()
Dim sz As Integer = b.Width * b.Height - 1
Dim w(sz) As Boolean
Dim r As New Random(666)
Dim u As Integer, j As Integer = 0
Do While j < sz
Do
u = r.Next(0, sz)
Loop While w(u)
' swap
swap(b, j, u)
w(j) = True
w(u) = True
Do
j += 1
Loop While j < sz AndAlso w(j)
Loop
b.Save(IO.Path.ChangeExtension(a, "png"), Drawing.Imaging.ImageFormat.Png)
Console.WriteLine("Done!")
Next
End Sub
End Module
```
Output images:
![](https://i.stack.imgur.com/R1z9u.jpg)
![](https://i.stack.imgur.com/sU0ch.png)
[Answer]
After being reminded that this is about to swap pixels and not alter them, here is my solution for this:
Scrambled:
![enter image description here](https://i.stack.imgur.com/s4xT7.jpg)
Restored:
![enter image description here](https://i.stack.imgur.com/N2CD3.jpg)
This is done by randomizing the pixel order, but to be able to restore it, the randomization is fixed. This is done by using a pseudo-random with a fixed seed and generate a list of indexes that describe which pixels to swap. As the swap will be the same, the same list will restore the original image.
```
public class ImageScramble {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("Usage: ImageScramble <fileInput> <fileOutput>");
} else {
// load image
final String extension = args[0].substring(args[0].lastIndexOf('.') + 1);
final BufferedImage image = ImageIO.read(new File(args[0]));
final int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
// create randomized swap list
final ArrayList<Integer> indexes = IntStream.iterate(0, i -> i + 1).limit(pixels.length).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Collections.shuffle(indexes, new Random(1337));
// swap all pixels at index n with pixel at index n+1
int tmp;
for (int i = 0; i < indexes.size(); i += 2) {
tmp = pixels[indexes.get(i)];
pixels[indexes.get(i)] = pixels[indexes.get(i + 1)];
pixels[indexes.get(i + 1)] = tmp;
}
// write image to disk
final BufferedImage imageScrambled = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
imageScrambled.setRGB(0, 0, imageScrambled.getWidth(), imageScrambled.getHeight(), pixels, 0, imageScrambled.getWidth());
ImageIO.write(imageScrambled, extension, new File(args[1]));
}
}
}
```
Note that using this algorithm on a lossy compression format will not produce the same result, as the image format will alter the data. This should work fine with any loss-less codec like PNG.
[Answer]
# Mathematica
We define a helper function `h` and the scrambling function `scramble` as:
```
h[l_List, n_Integer, k_Integer: 1] :=
With[{ m = Partition[l, n, n, 1, 0] },
Flatten[
Riffle[
RotateLeft[ m[[ ;; , {1} ]] , k ],
m[[ ;; , 2;; ]]
], 1
] [[ ;; Length[l] ]]
];
scramble[img_Image, k_Integer] :=
Module[{ list , cNum = 5 },
Which[
k > 0, list = Prime@Range[cNum],
k < 0, list = Reverse@Prime@Range[cNum],
True, list = {}
];
Image[
Transpose[
Fold[ h[ #1, #2, k ] &, #, list ] & /@
Transpose[
Fold[ h[#1, #2, k] &, #, list ] & /@ ImageData[img]
]
]
]
];
```
After loading an image, you can call `scramble[img, k]` where `k` is any integer, to scramble the image. Calling again with `-k` will descramble. (If `k` is `0`, then no change is made.) Typically `k` should be chosen to be something like `100`, which gives a pretty scrambled image:
![Example output 1](https://i.stack.imgur.com/NgPhf.jpg)
![Example output 2](https://i.stack.imgur.com/5kFz9.jpg)
[Answer]
# Matlab: Row and Column Scrambling based on row/column sum invariances
This seemed like a fun puzzle, so I had a think about it and came up with the following function. It is based on the invariance of row and column pixel-value sums during circular shifting: it shifts each row, then each column, by the total sum of the row/column's pixel values (assuming a uint8 for whole number in the shift-variable). This can then be reversed by shifting each column then row by their sum-value in the opposite direction.
It's not as pretty as the others, but I like that it is non-random and fully specified by the image - no choosing parameters.
I originally designed it to shift each color channel separately, but then I noticed the specification to only move full pixels.
```
function pic_scramble(input_filename)
i1=imread(input_filename);
figure;
subplot(1,3,1);imagesc(i1);title('Original','fontsize',20);
i2=i1;
for v=1:size(i1,1)
i2(v,:,:)=circshift(i2(v,:,:),sum(sum(i2(v,:,:))),2);
end
for w=1:size(i2,2)
i2(:,w,:)=circshift(i2(:,w,:),sum(sum(i2(:,w,:))),1);
end
subplot(1,3,2);imagesc(i2);title('Scrambled','fontsize',20);
i3=i2;
for w=1:size(i3,2)
i3(:,w,:)=circshift(i3(:,w,:),-1*sum(sum(i3(:,w,:))),1);
end
for v=1:size(i3,1)
i3(v,:,:)=circshift(i3(v,:,:),-1*sum(sum(i3(v,:,:))),2);
end
subplot(1,3,3);imagesc(i3);title('Recovered','fontsize',20);
```
![First test image](https://i.stack.imgur.com/JTzwd.jpg)
![Secont test image](https://i.stack.imgur.com/uM9WW.png)
[Answer]
# Java
This program randomly swaps pixels (creates pixel to pixel mapping), but instead of random function it uses Math.sin() (integer x).
It's fully reversible. With test images it creates some patterns.
Parameters:
integer number (number of passes, negative number to reverse, 0 does nothing), input mage and output image (can be the same).
Output file should be in format that uses lossless compression.
1 pass:
![enter image description here](https://i.stack.imgur.com/28CZe.jpg)
![enter image description here](https://i.stack.imgur.com/PsdAn.png)
100 passes (it takes a few minutes to do it):
![enter image description here](https://i.stack.imgur.com/dfVSe.jpg)
![enter image description here](https://i.stack.imgur.com/a4c1X.png)
Code:
```
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Test{
public static void main(String... args) {
String in = "image.png";
String out = in;
int passes = 0;
if (args.length < 1) {
System.out.println("no paramem encryptimg, 1 pass, reading and saving image.png");
System.out.println("Usage: pass a number. Negative - n passes of decryption, positive - n passes of encryption, 0 - do nothing");
} else {
passes = Integer.parseInt(args[0]);
if (args.length > 1) {
in = args[1];
}
if(args.length > 2){
out = args[2];
}
}
boolean encrypt = passes > 0;
passes = Math.abs(passes);
for (int a = 0; a < passes; a++) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(a == 0 ? in : out));
} catch (IOException e) {
e.printStackTrace();
return;
}
int pixels[][] = new int[img.getWidth()][img.getHeight()];
int[][] newPixels = new int[img.getWidth()][img.getHeight()];
for (int x = 0; x < pixels.length; x++) {
for (int y = 0; y < pixels[x].length; y++) {
pixels[x][y] = img.getRGB(x, y);
}
}
int amount = img.getWidth() * img.getHeight();
int[] list = new int[amount];
for (int i = 0; i < amount; i++) {
list[i] = i;
}
int[] mapping = new int[amount];
for (int i = amount - 1; i >= 0; i--) {
int num = (Math.abs((int) (Math.sin(i) * amount))) % (i + 1);
mapping[i] = list[num];
list[num] = list[i];
}
for (int xz = 0; xz < amount; xz++) {
int x = xz % img.getWidth();
int z = xz / img.getWidth();
int xzMap = mapping[xz];
int newX = xzMap % img.getWidth();
int newZ = xzMap / img.getWidth();
if (encrypt) {
newPixels[x][z] = pixels[newX][newZ];
} else {
newPixels[newX][newZ] = pixels[x][z];
}
}
BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < pixels.length; x++) {
for (int y = 0; y < pixels[x].length; y++) {
newImg.setRGB(x, y, newPixels[x][y]);
}
}
try {
String[] s = out.split("\\.");
ImageIO.write(newImg, s[s.length - 1],
new File(out));
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
```
[Answer]
# Python 2.7 with PIL
A little late to the party, but I thought it would be fun to convert the images into plaids (and back of course). First we shift columns up or down by 4 times the columns number (even columns down, odd columns up). Then, we shift rows left or right by 4 times the row number (even columns left, odd columns right).
The result is quite Tartanish.
To reverse, we just do these in the opposite order and shift by the opposite amount.
## Code
```
from PIL import Image
def slideColumn (pix, tpix, x, offset, height):
for y in range(height):
tpix[x,(offset+y)%height] = pix[x,y]
def slideRow (pix, tpix, y, offset, width):
for x in range(width):
tpix[(offset+x)%width,y] = pix[x,y]
def copyPixels (source, destination, width, height):
for x in range(width):
for y in range(height):
destination[x,y]=source[x,y]
def shuffleHorizontal (img, tmpimg, factor, encoding):
xsize,ysize = img.size
pix = img.load()
tpix = tmpimg.load()
for y in range(ysize):
offset = y*factor
if y%2==0:
offset = xsize-offset
offset = (xsize + offset) % xsize
if encoding:
slideRow(pix,tpix,y,offset,xsize)
else:
slideRow(pix,tpix,y,-offset,xsize)
copyPixels(tpix,pix,xsize,ysize)
def shuffleVertical (img, tmpimg, factor, encoding):
xsize,ysize = img.size
pix = img.load()
tpix = tmpimg.load()
for x in range(xsize):
offset = x*factor
if x%2==0:
offset = ysize-offset
offset = (ysize + offset) % ysize
if encoding:
slideColumn(pix,tpix,x,offset,ysize)
else:
slideColumn(pix,tpix,x,-offset,ysize)
copyPixels(tpix,pix,xsize,ysize)
def plaidify (img):
tmpimg = Image.new("RGB",img.size)
shuffleVertical(img,tmpimg,4,True)
shuffleHorizontal(img,tmpimg,4,True)
def deplaidify (img):
tmpimg = Image.new("RGB",img.size)
shuffleHorizontal(img,tmpimg,4,False)
shuffleVertical(img,tmpimg,4,False)
```
## Results
The plaid from image 1:
![the plaidified 1.jpg](https://i.stack.imgur.com/ENDdi.jpg)
The plaid form image 2:
![the plaidified 2.png](https://i.stack.imgur.com/ROjru.png)
[Answer]
## 47
94 lines. 47 for encoding, 47 for decoding.
```
require 'chunky_png'
require_relative 'codegolf-35005_ref.rb'
REF = {:png => ref, :w => 1280, :h => 720}
REF[:pix] = REF[:png].to_rgb_stream.unpack('C*').each_slice(3).to_a
SEVENTH_PRIME = 4*7 - 4-7 - (4&7)
FORTY_SEVEN = 4*7 + 4+7 + (4&7) + (4^7) + 7/4
THRESHOLD = FORTY_SEVEN * SEVENTH_PRIME
class RNG
@@m = 2**32
@@r = 0.5*(Math.sqrt(5.0) - 1.0)
def initialize(n=0)
@cur = FORTY_SEVEN + n
end
def hash(seed)
(@@m*((seed*@@r)%1)).floor
end
def _next(max)
hash(@cur+=1) % max
end
def _prev(max)
hash(@cur-=1) % max
end
def advance(n)
@cur += n
end
def state
@cur
end
alias_method :rand, :_next
end
def load_png(file, resample_w = nil, resample_h = nil)
png = ChunkyPNG::Image.from_file(file)
w = resample_w || png.width
h = resample_h || png.height
png.resample_nearest_neighbor!(w,h) if resample_w || resample_h
pix = png.to_rgb_stream.unpack('C*').each_slice(3).to_a
return {:png => png, :w => w, :h => h, :pix => pix}
end
def make_png(img)
rgb_stream = img[:pix].flatten.pack('C*')
img[:png] = ChunkyPNG::Canvas.from_rgb_stream(img[:w],img[:h],rgb_stream)
return img
end
def difference(pix_a,pix_b)
(pix_a[0]+pix_a[1]+pix_a[2]-pix_b[0]-pix_b[1]-pix_b[2]).abs
end
def code(img, img_ref, mode)
img_in = load_png(img)
pix_in = img_in[:pix]
pix_ref = img_ref[:pix]
s = img_in[:w] * img_in[:h]
rng = RNG.new(mode==:enc ? 0 : FORTY_SEVEN*s+1)
rand = mode == :enc ? rng.method(:_next) : rng.method(:_prev)
s.times do
FORTY_SEVEN.times do
j = rand.call(s)
i = rng.state % s
diff_val = difference(pix_ref[i],pix_ref[j])
if diff_val > THRESHOLD
pix_in[i], pix_in[j] = pix_in[j], pix_in[i]
end
end
end
make_png(img_in)
end
case ARGV.shift
when 'enc'
org, cod = ARGV
encoded_image = code(org,REF,:enc)
encoded_image[:png].save(cod)
when 'dec'
org, cod = ARGV
decoded_image = code(cod,REF,:dec)
decoded_image[:png].save(org)
else
puts '<original> <coded>'
puts 'specify either <enc> or <dec>'
puts "ruby #{$0} enc codegolf-35005_inp.png codegolf-35005_enc.png"
end
```
[codegolf-35005\_ref.rb](http://pastebin.com/xsT7bGbN)
![enter image description here](https://i.stack.imgur.com/KO3HR.jpg)
![enter image description here](https://i.stack.imgur.com/1m9FH.png)
(converted to jpg)
![enter image description here](https://i.stack.imgur.com/ZU8TH.jpg)
(original downscaled)
![enter image description here](https://i.stack.imgur.com/x4A9F.jpg)
[Answer]
# Python (+ bonus) - permutation of the pixels
In this method, every pixel will be placed on another position, with the constraint that the other pixel will be placed on the first position. Mathematically, it is a permutation with cycle length 2. As such, the method is it's own inverse.
In retrospect, it is very similar to mfvonh, but this submission is in Python and I had to construct that permutation myself.
```
def scramble(I):
result = np.zeros_like(I)
size = I.shape[0:2]
nb_pixels = size[0]*size[1]
#Build permutation
np.random.seed(0)
random_indices = np.random.permutation( range(nb_pixels) )
random_indices1 = random_indices[0:int(nb_pixels/2)]
random_indices2 = random_indices[-1:-1-int(nb_pixels/2):-1]
for c in range(3):
Ic = I[:,:,c].flatten()
Ic[ random_indices2 ] = Ic[random_indices1]
Ic[ random_indices1 ] = I[:,:,c].flatten()[random_indices2]
result[:,:,c] = Ic.reshape(size)
return result
```
First test image:
![First test image](https://i.stack.imgur.com/yOe0C.jpg)
Second test image:
![Second test image](https://i.stack.imgur.com/ils1u.png)
[Answer]
# Python 2.7 + PIL, Inspiration from the Sliding Puzzles
Just had another idea. Basically, this method divides an image into equal sized blocks and then shuffles their order. Since the new order is based on a fixed seed, it's possible to completely revert the process using the same seed. Besides, with the additional parameter called granularity, it's possible to achieve different and unrecognizable results.
## Results:
### Original
![original](https://i.stack.imgur.com/ss93A.jpg)
### Granularity 16
![16](https://i.stack.imgur.com/erydr.png)
### Granularity 13
![13](https://i.stack.imgur.com/wXcyX.png)
### Granularity 10
![10](https://i.stack.imgur.com/jVh3X.png)
### Granularity 3
![3](https://i.stack.imgur.com/Ln90s.png)
### Granularity 2
![2](https://i.stack.imgur.com/xQLIR.jpg)
### Granularity 1
![enter image description here](https://i.stack.imgur.com/8qstN.jpg)
### Original
![original](https://i.stack.imgur.com/jkSJL.png)
### Granularity 16
![16](https://i.stack.imgur.com/zF44G.png)
### Granularity 13
![13](https://i.stack.imgur.com/KDl3V.png)
### Granularity 10
![10](https://i.stack.imgur.com/bwzGp.png)
### Granularity 3
![3](https://i.stack.imgur.com/MVr3u.png)
### Granularity 2
![2](https://i.stack.imgur.com/Uf4oo.png)
### Granularity 1
![1](https://i.stack.imgur.com/vLJ3S.png)
## Code:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
import random
def scramble_blocks(im,granularity,password,nshuffle):
set_seed(password)
width=im.size[0]
height=im.size[1]
block_width=find_block_dim(granularity,width) #find the possible block dimensions
block_height=find_block_dim(granularity,height)
grid_width_dim=width/block_width #dimension of the grid
grid_height_dim=height/block_height
nblocks=grid_width_dim*grid_height_dim #number of blocks
print "nblocks: ",nblocks," block width: ",block_width," block height: ",block_height
print "image width: ",width," image height: ",height
print "getting all the blocks ..."
blocks=[]
for n in xrange(nblocks): #get all the image blocks
blocks+=[get_block(im,n,block_width,block_height)]
print "shuffling ..."
#shuffle the order of the blocks
new_order=range(nblocks)
for n in xrange(nshuffle):
random.shuffle(new_order)
print "building final image ..."
new_image=im.copy()
for n in xrange(nblocks):
#define the target box where to paste the new block
i=(n%grid_width_dim)*block_width #i,j -> upper left point of the target image
j=(n/grid_width_dim)*block_height
box = (i,j,i+block_width,j+block_height)
#paste it
new_image.paste(blocks[new_order[n]],box)
return new_image
#find the dimension(height or width) according to the desired granularity (a lower granularity small blocks)
def find_block_dim(granularity,dim):
assert(granularity>0)
candidate=0
block_dim=1
counter=0
while counter!=granularity: #while we dont achive the desired granularity
candidate+=1
while((dim%candidate)!=0):
candidate+=1
if candidate>dim:
counter=granularity-1
break
if candidate<=dim:
block_dim=candidate #save the current feasible lenght
counter+=1
assert(dim%block_dim==0 and block_dim<=dim)
return block_dim
def unscramble_blocks(im,granularity,password,nshuffle):
set_seed(password)
width=im.size[0]
height=im.size[1]
block_width=find_block_dim(granularity,width) #find the possible block dimensions
block_height=find_block_dim(granularity,height)
grid_width_dim=width/block_width #dimension of the grid
grid_height_dim=height/block_height
nblocks=grid_width_dim*grid_height_dim #number of blocks
print "nblocks: ",nblocks," block width: ",block_width," block height: ",block_height
print "getting all the blocks ..."
blocks=[]
for n in xrange(nblocks): #get all the image blocks
blocks+=[get_block(im,n,block_width,block_height)]
print "shuffling ..."
#shuffle the order of the blocks
new_order=range(nblocks)
for n in xrange(nshuffle):
random.shuffle(new_order)
print "building final image ..."
new_image=im.copy()
for n in xrange(nblocks):
#define the target box where to paste the new block
i=(new_order[n]%grid_width_dim)*block_width #i,j -> upper left point of the target image
j=(new_order[n]/grid_width_dim)*block_height
box = (i,j,i+block_width,j+block_height)
#paste it
new_image.paste(blocks[n],box)
return new_image
#get a block of the image
def get_block(im,n,block_width,block_height):
width=im.size[0]
grid_width_dim=width/block_width #dimension of the grid
i=(n%grid_width_dim)*block_width #i,j -> upper left point of the target block
j=(n/grid_width_dim)*block_height
box = (i,j,i+block_width,j+block_height)
block_im = im.crop(box)
return block_im
#set random seed based on the given password
def set_seed(password):
passValue=0
for ch in password:
passValue=passValue+ord(ch)
random.seed(passValue)
if __name__ == '__main__':
filename="0RT8s.jpg"
# filename="B5TbK.png"
password="yOs0ZaKpiS"
nshuffle=1
granularity=1
im=Image.open(filename)
new_image=scramble_blocks(im,granularity,password,nshuffle)
new_image.show()
new_image.save(filename.split(".")[0]+"_puzzled.png")
new_image=unscramble_blocks(new_image,granularity,password,nshuffle)
new_image.save(filename.split(".")[0]+"_unpuzzled.png")
new_image.show()
```
[Answer]
# Matlab with a pinch of Group Theory (+ bonus)
In this approach we assume that we have an even number of total pixels. (If not, we just ignore one pixel) So we need to choose half of the pixels to swap with the other half. For this, we index all the pixels from `0` up to `2N-1` and consider these indices as a [cyclic group.](https://en.wikipedia.org/wiki/Cyclic_group)
Among the primes we search for a number `p` that is not too small and not too big, and that is coprime to `2N`, the order of our group. This means `g` [generates](https://en.wikipedia.org/wiki/Generating_set_of_a_group) our group or `{k*g mod 2N | k=0,1,...,2N-1} = {0,1,...,2N-1}`.
So we choose the first `N` multiples of `g` as one set, and all the remaining indeces as the other set, and just swap the corresponding set of pixels.
If `p` is chosen the right way, the first set is evenly distributed over the whole image.
The two test cases:
![](https://i.stack.imgur.com/yjyAH.jpg)![](https://i.stack.imgur.com/ydBYb.png)
### Slightly off topic but interesting:
During testing I noticed, that if you save it to a (lossy compressed) jpg (instead of a losslessly compressed png) and apply the transformation back and forth, you quite quickly see artefacts of the compression, this shows the results of two consecutive rearrangements:
![](https://i.stack.imgur.com/E14Yq.png)
![](https://i.stack.imgur.com/M9c1L.jpg)
![](https://i.stack.imgur.com/fbl7E.jpg)
As you can see, the jpg compression makes the result look almost black and white!
```
clc;clear;
inputname = 'codegolf_rearrange_pixels2.png';
inputname = 'codegolf_rearrange_pixels2_swapped.png';
outputname = 'codegolf_rearrange_pixels2_swapped.png';
%read image
src = imread(inputname);
%separate into channels
red = src(:,:,1);
green = src(:,:,2);
blue = src(:,:,3);
Ntotal = numel(red(:)); %number of pixels
Nswap = floor(Ntotal/2); %how many pairs we can swap
%find big enough generator
factors = unique(factor(Ntotal));
possible_gen = primes(max(size(red)));
eliminated = setdiff(possible_gen,factors);
if mod(numel(eliminated),2)==0 %make length odd for median
eliminated = [1,eliminated];
end
generator = median(eliminated);
%set up the swapping vectors
swapindices1 = 1+mod((1:Nswap)*generator, Ntotal);
swapindices2 = setdiff(1:Ntotal,swapindices1);
swapindices2 = swapindices2(1:numel(swapindices1)); %make sure both have the same length
%swap the pixels
red([swapindices1,swapindices2]) = red([swapindices2,swapindices1]);
green([swapindices1,swapindices2]) = green([swapindices2,swapindices1]);
blue([swapindices1,swapindices2]) = blue([swapindices2,swapindices1]);
%write and display
output = cat(3,red,green,blue);
imwrite(output,outputname);
subplot(2,1,1);
imshow(src)
subplot(2,1,2);
imshow(output);
```
[Answer]
# JavaScript (+bonus) - pixel divide swap repeater
>
> The function takes an image element and
>
>
> 1. Divides the pixels by 8.
> 2. Does a reversible swap of pixel groups.
> 3. Recurses swapping if the pixel group >= 8.
>
>
>
```
function E(el){
var V=document.createElement('canvas')
var W=V.width=el.width,H=V.height=el.height,C=V.getContext('2d')
C.drawImage(el,0,0)
var id=C.getImageData(0,0,W,H),D=id.data,L=D.length,i=L/4,A=[]
for(;--i;)A[i]=i
function S(A){
var L=A.length,x=L>>3,y,t,i=0,s=[]
if(L<8)return A
for(;i<L;i+=x)s[i/x]=S(A.slice(i,i+x))
for(i=4;--i;)y=[6,4,7,5,1,3,0,2][i],t=s[i],s[i]=s[y],s[y]=t
s=[].concat.apply([],s)
return s
}
var N=C.createImageData(W,H),d=N.data,A=S(A)
for(var i=0;i<L;i++)d[i]=D[(A[i>>2]*4)+(i%4)]
C.putImageData(N,0,0)
el.src=C.canvas.toDataURL()
}
```
![Mountains](https://i.stack.imgur.com/CpNjI.jpg)
![Circles](https://i.stack.imgur.com/7iI50.png)
[Answer]
# Python 2.7 + PIL, Column/Row Scrambler
This method simply scrambles the rows and columns of the image. It's possible to scramble only one of the dimensions or both. Besides, the order of the new scrambled row/column is based on a password. Also, another possibility is scrambling the entire image array without considering the dimensions.
## Results:
### Scrambling the entire image:
![enter image description here](https://i.stack.imgur.com/ubBH2.jpg)
![enter image description here](https://i.stack.imgur.com/BI0oE.png)
### Scrambling the columns:
![enter image description here](https://i.stack.imgur.com/Axx9A.jpg)
![enter image description here](https://i.stack.imgur.com/4dy7r.png)
### Scrambling the rows:
![enter image description here](https://i.stack.imgur.com/uAN4P.png)
![enter image description here](https://i.stack.imgur.com/c94sd.png)
### Scrambling both columns and rows:
![enter image description here](https://i.stack.imgur.com/lO55c.jpg)
![enter image description here](https://i.stack.imgur.com/Ft4AW.png)
I also tried to apply several runs to the image, but the end results didn't differ much, only the difficulty to decrypt it.
## Code:
```
from PIL import Image
import random,copy
def scramble(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(columns*rows)
random.shuffle(newOrder) #shuffle
newpixels=copy.deepcopy(pixels)
for i in xrange(len(pixels)):
newpixels[i]=pixels[newOrder[i]]
im.putdata(newpixels)
def unscramble(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(columns*rows)
random.shuffle(newOrder) #unshuffle
newpixels=copy.deepcopy(pixels)
for i in xrange(len(pixels)):
newpixels[newOrder[i]]=pixels[i]
im.putdata(newpixels)
def scramble_columns(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(columns)
random.shuffle(newOrder) #shuffle
newpixels=[]
for i in xrange(rows):
for j in xrange(columns):
newpixels+=[pixels[i*columns+newOrder[j]]]
im.putdata(newpixels)
def unscramble_columns(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(columns)
random.shuffle(newOrder) #shuffle
newpixels=copy.deepcopy(pixels)
for i in xrange(rows):
for j in xrange(columns):
newpixels[i*columns+newOrder[j]]=pixels[i*columns+j]
im.putdata(newpixels)
def scramble_rows(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(rows)
random.shuffle(newOrder) #shuffle the order of pixels
newpixels=copy.deepcopy(pixels)
for j in xrange(columns):
for i in xrange(rows):
newpixels[i*columns+j]=pixels[columns*newOrder[i]+j]
im.putdata(newpixels)
def unscramble_rows(im,columns,rows):
pixels =list(im.getdata())
newOrder=range(rows)
random.shuffle(newOrder) #shuffle the order of pixels
newpixels=copy.deepcopy(pixels)
for j in xrange(columns):
for i in xrange(rows):
newpixels[columns*newOrder[i]+j]=pixels[i*columns+j]
im.putdata(newpixels)
#set random seed based on the given password
def set_seed(password):
passValue=0
for ch in password:
passValue=passValue+ord(ch)
random.seed(passValue)
def encrypt(im,columns,rows,password):
set_seed(password)
# scramble(im,columns,rows)
scramble_columns(im,columns,rows)
scramble_rows(im,columns,rows)
def decrypt(im,columns,rows,password):
set_seed(password)
# unscramble(im,columns,rows)
unscramble_columns(im,columns,rows)
unscramble_rows(im,columns,rows)
if __name__ == '__main__':
passwords=["yOs0ZaKpiS","NA7N3v57og","Nwu2T802mZ","6B2ec75nwu","FP78XHYGmn"]
iterations=1
filename="0RT8s.jpg"
im=Image.open(filename)
size=im.size
columns=size[0]
rows=size[1]
for i in range(iterations):
encrypt(im,columns,rows,passwords[i])
im.save(filename.split(".")[0]+"_encrypted.jpg")
for i in range(iterations):
decrypt(im,columns,rows,passwords[iterations-i-1])
im.save(filename.split(".")[0]+"_decrypted.jpg")
```
[Answer]
## C# Winforms
Image1:
[![enter image description here](https://i.stack.imgur.com/A3faP.png)](https://i.stack.imgur.com/A3faP.png)
Image 2:
[![enter image description here](https://i.stack.imgur.com/zQYc5.png)](https://i.stack.imgur.com/zQYc5.png)
Source code:
```
class Program
{
public static void codec(String src, String trg, bool enc)
{
Bitmap bmp = new Bitmap(src);
Bitmap dst = new Bitmap(bmp.Width, bmp.Height);
List<Point> points = new List<Point>();
for (int y = 0; y < bmp.Height; y++)
for (int x = 0; x < bmp.Width; x++)
points.Add(new Point(x, y));
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
int py = Convert.ToInt32(y + 45 * Math.Sin(2.0 * Math.PI * x / 128.0));
int px = Convert.ToInt32(x + 45 * Math.Sin(2.0 * Math.PI * y / 128.0));
px = px < 0 ? 0 : px;
py = py < 0 ? 0 : py;
px = px >= bmp.Width ? bmp.Width - 1 : px;
py = py >= bmp.Height ? bmp.Height - 1 : py;
int srcIndex = x + y * bmp.Width;
int dstIndex = px + py * bmp.Width;
Point temp = points[srcIndex];
points[srcIndex] = points[dstIndex];
points[dstIndex] = temp;
}
}
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Point p = points[x + y * bmp.Width];
if (enc)
dst.SetPixel(x, y, bmp.GetPixel(p.X, p.Y));
else
dst.SetPixel(p.X, p.Y, bmp.GetPixel(x, y));
}
}
dst.Save(trg);
}
static void Main(string[] args)
{
// encode
codec(@"c:\shared\test.png", @"c:\shared\test_enc.png", true);
// decode
codec(@"c:\shared\test_enc.png", @"c:\shared\test_dec.png", false);
}
}
```
[Answer]
# Python 3.6 + pypng
## Riffle/Master Shuffle
```
#!/usr/bin/env python3.6
import argparse
import itertools
import png
def read_image(filename):
img = png.Reader(filename)
w, h, data, meta = img.asRGB8()
return w, h, list(itertools.chain.from_iterable(
[
(row[i], row[i+1], row[i+2])
for i in range(0, len(row), 3)
]
for row in data
))
def riffle(img, n=2):
l = len(img)
base_size = l // n
big_groups = l % n
base_indices = [0]
for i in range(1, n):
base_indices.append(base_indices[-1] + base_size + int(i <= big_groups))
result = []
for i in range(0, base_size):
for b in base_indices:
result.append(img[b + i])
for i in range(big_groups):
result.append(img[base_indices[i] + base_size])
return result
def master(img, n=2):
parts = [[] for _ in range(n)]
for i, pixel in enumerate(img):
parts[i % n].append(pixel)
return list(itertools.chain.from_iterable(parts))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('infile')
parser.add_argument('outfile')
parser.add_argument('-r', '--reverse', action='store_true')
parser.add_argument('-i', '--iterations', type=int, default=1)
parser.add_argument('-n', '--groupsize', type=int, default=2)
parser.add_argument('-c', '--complex', nargs='+', type=int)
args = parser.parse_args()
w, h, img = read_image(args.infile)
if args.complex:
if any(-1 <= n <= 1 for n in args.complex):
parser.error("Complex keys must use group sizes of at least 2")
if args.reverse:
args.complex = [
-n for n in reversed(args.complex)
]
for n in args.complex:
if n > 1:
img = riffle(img, n)
elif n < -1:
img = master(img, -n)
elif args.reverse:
for _ in range(args.iterations):
img = master(img, args.groupsize)
else:
for _ in range(args.iterations):
img = riffle(img, args.groupsize)
writer = png.Writer(w, h)
with open(args.outfile, 'wb') as f:
writer.write_array(f, list(itertools.chain.from_iterable(img)))
if __name__ == '__main__':
main()
```
My algorithm applies the riffle shuffle in one direction and a master shuffle in the other (since the two are inverses of one another), several iterations each, but each is generalized to split into any number of subgroups instead of just two. The effect is that you could make a multi-iteration permutation key since the image won't be restored without knowing the exact sequence of riffle and master shuffles. A sequence can be specified with a series of integers, with positive numbers representing riffles and negative numbers representing masters.
I shuffled the landscape with the key [3, -5, 2, 13, -7]:
[![Landscape 3 -5 2 13 -7](https://i.stack.imgur.com/k23ni.png)](https://i.stack.imgur.com/k23ni.png)
Interestingly enough, some interesting things happen from [3, -5], where some artifacts from the original image are left over:
[![Landscape 3 -5](https://i.stack.imgur.com/kBeLV.png)](https://i.stack.imgur.com/kBeLV.png)
Here's the abstract pattern shuffled with the key [2, 3, 5, 7, -11, 13, -17]:
[![Circles 2 3 5 7 -11 13 -17](https://i.stack.imgur.com/8g7g4.png)](https://i.stack.imgur.com/8g7g4.png)
If just one parameter is wrong in the key, the unshuffle won't restore the image:
[![Bad Unshuffle](https://i.stack.imgur.com/RlLX2.png)](https://i.stack.imgur.com/RlLX2.png)
] |
[Question]
[
Write a program or function that prints or outputs this exact text (consisting of 142 characters):
```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
Your program must take no input (except in languages where this is impossible, such as `sed`), and produce the above text (and *only* the above text) as output. A trailing newline is acceptable.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins.
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~70~~ ~~68~~ 67 bytes
```
'()'12:)l10:&<toYP43Y$51hb(!10Xy'\::\'FFhZ++'|'3$Yc'||\'3:(95'Zd'o(
```
[Try it online!](http://matl.tryitonline.net/#code=JygpJzEyOilsMTA6Jjx0b1lQNDNZJDUxaGIoITEwWHknXDo6XCdGRmhaKysnfCczJFljJ3x8XCczOig5NSdaZCdvKA&input=)
### Explanation
What a mess. But hey, there's a convolution!
The explanation will be clearer if you can *inspect the stack contents after a given statement*. To do it, just insert `X#0$%` at that point. (This means: `X#` show stack contents, `0$` don't implicitly display anything else, `%` comment out rest of the code). For example, [see the stack right after the convolution](http://matl.tryitonline.net/#code=JygpJzEyOilsMTA6Jjx0b1lQNDNZJDUxaGIoITEwWHknXDo6XCdGRmhaK1gjMCQlKyd8JzMkWWMnfHxcJzM6KDk1J1pkJ28o&input=).
```
'()' % Push this string
12: % Range [1 2 ... 12]
) % Index into string (modular, 1-based): gives '()()()()()()'
l % Push 1 (will be used later)
10: % Range [1 2 ... 10]
&< % All pairwise "less than" comparisons. Gives matrix with "true"
% below the main diagonal, and the remining entries equal to "false"
to % Duplicate. Convert to numbers (true becomes 1, false becomes 0)
YP43Y$ % Compute pi with 43 significant digits (42 decimals). Gives a string
51h % Append last decimal, '3' (ASCII 51). This is needed to avoid rounding
b % Bubble up the true-false matrix, to be used as logical index
( % Fill the chars from the pi string into the 0-1 matrix, at the positions
% indicated by the true-false matrix. Thus each 1 is replaced by a char
% from the pi string. Entries that were 0 remain as 0. This is done in
% columm-major order...
! % ...so transpose to make it row-major
10Xy % Identity matrix of size 10
'\::\' % Push this string...
FFh % ...and append two zeros
Z+ % 2D convolution keeping size. The identity matrix convolved with the
% above string gives the diagonal bands with chars '\' and ':'
+ % Add to the matrix containing the digits of pi. At each entry, only one
% of the two matrices is nonzero
'|' % Push this string
3$Yc % Three-input string concatenation. This prepends the 1 (which was pushed
% a while ago) and appends '|' to each row of the matrix. This converts
% the matrix to char. Note that char 1 will be displayed as a space. We
% used char 1 and not char 0 (which would be displayed as a space too)
% because function `Yc` (`strcat`) strips off trailing space from the
% inputs, counting char 0 as space, but not char 1
'||\' % Push this string
3:( % Assign it to the first 3 entries of the matrix (column-major), that is,
% to the top of the first column
95 % Push ASCII for '_'
'Zd'o % Push string 'Zd' and convert to numbers: gives [90 100]. These are the
% (column-major) indices where the '_' char should appear in the last row
( % Fill those chars
% Implicitly display. (Chars 0 and 1 are displayed as space)
```
[Answer]
# Perl, 93 bytes
```
$_=bpi$=;printf'()'x6x!$`.'
%12s',F.ee x!$\--^substr"\32::\\$&|",-12while/.{$\}/g
```
Requires the command line option `-l71Mbignum=bpi`, counted as 14. The `\32` should be replaced by a literal character 26.
**Sample Usage**
```
$ perl -l71Mbignum=bpi pi-slice.pl
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
---
### Perl, 111 bytes
```
$_=bpi$_*($l=($.=$_)-3);printf'()'x($./2)x!$`."
%$.s",F.ee x!$l--^substr"\32::\\$&|",-$.while/.{$l}/g
```
Parameterized version. Requires the command line option `-nMbignum=bpi`, counted as 12.
**Sample Usage**
```
$ echo 10 | perl -nMbignum=bpi pi-slice.pl
()()()()()
|\3.14159|
|:\265358|
\::\97932|
\::\3846|
\::\264|
\::\33|
\::\8|
\__\|
$ echo 20 | perl -nMbignum=bpi pi-slice.pl
()()()()()()()()()()
|\3.141592653589793|
|:\2384626433832795|
\::\028841971693993|
\::\75105820974944|
\::\5923078164062|
\::\862089986280|
\::\34825342117|
\::\0679821480|
\::\865132823|
\::\06647093|
\::\8446095|
\::\505822|
\::\31725|
\::\3594|
\::\081|
\::\28|
\::\4|
\__\|
```
[Answer]
## JavaScript (ES6), ~~187~~ 174 bytes
This is *1 byte shorter* than just displaying the plain text.
```
for(y=n=0,s=`()()()()()()
`;y<10;y++,s+=`|
`)for(x=-2;x++<9;)s+=x>y?(Math.PI+'2384626433832795028841971693')[n++]:`\\${y>8?'__':x+1|y>2?'::':'||'}\\`[y-x]||' ';console.log(s)
```
[Answer]
# [///](http://esolangs.org/wiki////), ~~129~~ 127 bytes
```
/-/\\\\//&/--::--//%/ //#/|
%//!/()()/!!!
|-3.1415926|
|:-53589793|
&2384626|
&433832#&79502# &8841#%&971#% &69#%%&3#%% -__-|
```
[Try it online!](http://slashes.tryitonline.net/#code=Ly0vXFxcXC8vJi8tLTo6LS0vLyUvICAvLyMvfAolJS8vIS8oKSgpLyEhIQp8LTMuMTQxNTkyNnwKfDotNTM1ODk3OTN8CiYyMzg0NjI2fAogJjQzMzgzMnwKJSY3OTUwMnwKJSAmODg0MSMmOTcxIyAmNjkjJSYzIyUgLV9fLXw)
[Answer]
# Python 2, 131 bytes
```
print'()'*6+'\n|\\3.1415926|\n|:\\53589793|'
for n in 2384626,433832,79502,8841,971,69,3,'':print'%11s|'%('\%s'*2%('_:'[n<'']*2,n))
```
Joint effort between Sp3000 and Lynn. Copper saved a byte, too! [Ideone link.](https://ideone.com/JrC2Nl)
[Answer]
# Bash, 153 bytes
```
cat << _
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
_
```
[Answer]
## Batch, 195 bytes
```
@echo ()()()()()()
@echo ^|\3.1415926^|
@echo ^|:\53589793^|
@set i=\
@for %%d in (2384626 433832 79502 8841 971 69 3)do @call:l %%d
@echo %i%__\^|
@exit/b
:l
@set i= %i%
@echo%i%::\%1^|
```
[Answer]
# Fourier, ~~196~~ 190 bytes
***New feature alert!***
## Code
```
|SaCaaSa|f|~Y0~jY(32aj^~j)|w6(40a41ai^~i)10a~N124a~W92a~S3o46a1415926oWaNaWa58a~CSa53589793oWaNaf2384626oWaNa1wf433832oWaNa2wf79502oWaNa3wf8841oWaNa4wf971oWaNa5wf69oWaNa6wf3oWaNa7wSa95aaSaWa
```
## Explanation
This program is my first demonstration of functions in Fourier:
Functions are defined like so:
```
|code goes here|f
```
The first pipe starts the function declaration. You then put the code in between the pipes. The last pipe ends the function declaration. Finally, the `f` is the variable in which the function is stored. This can be any character, as long as it isn't a reserved function.
For example, in my code, one of the function s is:
```
|SaCaaSa|f
```
Where the variable `S` stores the number 92 and `C` stores the number 58.
When called, the function outputs the following:
```
\::\
```
Since it is the most repeated thing in the pie.
Similarly, to golf down the output, I have used a loop:
```
6(40a41ai^~i)
```
Which repeats the code `40a41a` 6 times. `40a41a` on its own outputs:
```
()
```
So repeating the code six times outputs:
```
()()()()()()
```
Thereby outputting the crust of the pie.
[**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=fFNhQ2FhU2F8Znx-WTB-alkoMzJhal5-ail8dzYoNDBhNDFhaV5-aSkxMGF-TjEyNGF-VzkyYX5TM280NmExNDE1OTI2b1dhTmFXYTU4YX5DU2E1MzU4OTc5M29XYU5hZjIzODQ2MjZvV2FOYTF3ZjQzMzgzMm9XYU5hMndmNzk1MDJvV2FOYTN3Zjg4NDFvV2FOYTR3Zjk3MW9XYU5hNXdmNjlvV2FOYTZ3ZjNvV2FOYTd3U2E5NWFhU2FXYQ)
Because I haven't implemented functions in the Python interpreter, this program will not work on <http://tryitonline.net>
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/Turtl-d), ~~135~~ 129 bytes
(the interpreter isn't really ~~slightly~~ buggèd (anymore :])~~, but it does not affect this program~~)
By restructuring and rewriting my program, I golfed... six bytes
And now I have to make new explanation...
Still could be shorter probs though
---
At least the best solution in this lang isn't just writing in the raw data ¯\*(ツ)*/¯
---
[Answer]
# Pyth, 89 bytes
```
J_2K+.n0."09\07´\C2\84J\01£\07Nl:?í"*"()"6Vr9Zp*dJp?!Z\|?qZ9"|:""\::"p\\p:KZ+ZN\|=+ZN=hJ)p*dJ"\__\|"
```
[Try it online!](http://pyth.herokuapp.com/?code=J_2K%2B.n0.%2209%07%C2%B4%C2%84J%01%C2%A3%07Nl%3A%3F%C3%AD%22%2a%22%28%29%226Vr9Zp%2adJp%3F%21Z%5C%7C%3FqZ9%22%7C%3A%22%22%5C%3A%3A%22p%5C%5Cp%3AKZ%2BZN%5C%7C%3D%2BZN%3DhJ%29p%2adJ%22%5C__%5C%7C%22&debug=0)
Replace `\xx` (hexadecimal) with the corresponding ASCII character if you copy/paste the code from this answer; it contains unprintable characters in the packed string which SE filters out.
### Explanation
```
J_2 Sets J to -2
.n0 Pi; returns 3.141592653589793
."(...)" Packed string; returns "2384626433832795028841971693"
+ Concatenation; returns "3.1415926535897932384626433832795028841971693"
K Sets K to that string
*"()"6 Repetition; returns "()()()()()()", which is implicitly printed with a newline
r9Z Range; returns [9, 8, 7, 6, 5, 4, 3, 2, 1] (Z is initialized to 0)
V Loop through r9Z, using N as the loop variable
*dJ Repetition; d is initialized to " " (returns an empty string if J <= 0)
p Print without a newline
?!Z Ternary; if not Z
\| then return "|"
?qZ9 else, ternary; if Z == 9
"|:" then return "|:"
"\::" else, return "\::"
p Print without a newline
\\ One-character string; returns "\"
p Print without a newline
:KZ+ZN Slice; returns K[Z:Z+N], not including K[Z+N]
p Print without a newline
\| One-character string; returns "|", which is implicitly printed with a newline.
=+ZN Adds N to Z
=hJ Increments J by 1
) Ends loop
*dJ Repetition; d is initialized to " "
p Print without a newline
"\__\|" Returns "\__\|", which is implicitly printed with a newline
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 83 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
surely still quite golfabale
```
7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7
⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|”
```
**[TryItOnline](http://jelly.tryitonline.net/#code=N-G4tuKBtuG6izvigqzigJxcOjpc4oCd4oCcfDpc4oCd4bmt4bmZNwrigb4oKeG6izbigbfigb58XDjDmFDDpnDigJ184oG3OFJVUuKCrMK14oCc4oG-4biFfFphIn7huYXhu7XDvsi3XuG5h-KBt8SK4oCZROG5gTvigqzigJ18xbxAwqJZ4oG3w7jigbbhuos34oCcXF9fXHzigJ0&input=&args=)**
How?
```
7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 - Link 1, left side padding and filling
7Ḷ - lowered range of 7 ([0,1,2,3,4,5,6])
“\::\” - filling ("\::\")
⁶ẋ;€ - space character repeated that many times and concatenate for each
“|:\” - top crust edge filling ("|:\")
ṭ - tack (append to the end)
ṙ7 - rotate to the left by 7 (move top crust filling to the top)
⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ - Main Link (divided into two for formatting)
⁾()ẋ6⁷ - "()" repeated 6 times and a line feed
⁾|\ - "|\"
ØP - pi
8 æp - round to 8 significant figures (top edge of the glaze)
”|⁷ - "|" and a line feed
8R - range of 8 ([1,2,3,4,5,6,7,8])
U - reverse ([8,7,6,5,4,3,2,1])
R€ - range for each ([[1,2,..8],[1,2,..7],...,[1,2],[1]])
µ - monadic chain separation
“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” - Main link (continued)
“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’ - base 250 representation of the rest of the digits
D - decimalise (makes it a list)
ṁ - mould (into the shape of the array formed above)
”| - "|"
;€ - concatenate for each
¢ - call last link (1) as a nilad
ż@ - zip (with reversed operands)
Y⁷ - join with line feeds, and another line feed
ø - niladic chain separation
⁶ẋ7 - space character repeated 7 times
“\__\|” - "\__\|" the very bottom of the pie wedge
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 105 bytes
```
'()'*6
'|\3.1415926|
|:\53589793|'
2384626,433832,79502,8841,971,69,3|%{" "*$i+++"\::\$_|"}
' '*7+'\__\|'
```
[Try it online!](https://tio.run/nexus/powershell#BcHBDcMgDADAP1NEKJEbsKKCwdjMYol3Z6g7O73b8LohcQA3ekorXSt78GmduuhQcgiVpHFlbERCFYf2d0WRVlBHQVYkv77xiOn85JyjzWnn8vgLcEAaGWwtc9j7Dw "PowerShell – TIO Nexus")
*Not sure how I never answered this challenge ... I upvoted it and several of the other answers. Oh well, better late than never?*
This puts six balanced parens as a string on the pipeline, then a literal string (saves two bytes) of the next two rows. Then, we loop through the rest of the numbers, each iteration incrementing the number of prepended spaces (`$i`) concatenated with `\::<number>|`. Finally, we create a string of the tip of the pie. Those strings are all left on the pipeline, and an implicit `Write-Output` sticks a newline between.
This is 39 bytes shorter than [just printing the pie.](https://tio.run/nexus/powershell#RcnBDYAgDEDRO1NwQy9GaAstszRhke6O0mDMP738mY7zL5jClTGTlGrBuhIQSxOwoL1rAca6TlxCAIbywtWEboeLGbPDJW3DVWXDBR@ijqGW5nwA "PowerShell – TIO Nexus")
[Answer]
# Python 2, ~~193~~ 176 bytes
```
P="3.1415926 53589793 2384626 433832 79502 8841 971 69 3".split()
f="()"*6+"\n|\%s|\n|:\%s|\n"%(P[0],P[1])
for s in range(7):f+=" "*s+"\::\\"+P[s+2]+"|\n"
print f+" "*7+"\__\|"
```
Or a shorter, more boring answer:
```
print r"""()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|"""
```
[Answer]
# C# 220 213 209 208 202 201 (171\*) Bytes
\*I find this to be unoriginal and cheating
```
void F()=>Console.Write(@"()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|");
```
201 Bytes:
```
void f(){var s="()()()()()()\n";for(int i=0;i<9;)s+=(i<1?"|":i<2?"|:":"\\::".PadLeft(i+1))+$"\\{new[]{3.1415926,53589793,2384626,433832,79502,8841,971,69,3}[i++]}|\n";Console.Write(s+@" \__\|");}
```
220 bytes:
I'm sure that there is something to be golfed here
```
void f(){string s="()()()()()()\n",x=" ";for(int i=9,j=0;i>0;j+=i--)s+=(i>7?"|"+(i<9?":":"")+"\\":x.Substring(i)+@"\::\")+$"{Math.PI}32384626433832795028841971693".Substring(j,i)+"|\n";Console.Write(s+x+@"\__\|");}
```
[Answer]
# Ruby, ~~140~~ ~~138~~ 137 bytes
My solution to this problem in ruby, this is my first code golf answer :D
```
[0,2384626,433832,79502,8841,971,69,3,1].map{|n|puts n<1?"()"*6+"\n|\\3.1415926|\n|:\\53589793|":"\\#{n>1?"::\\#{n}":"__\\"}|".rjust(12)}
```
**Readable version and explanation:**
```
for n in [-1,2384626,433832,79502,8841,971,69,3,0]
if n < 0 # n == -1
puts "()"*6+"\n|\\3.1415926|\n|:\\53589793|"
else
if n > 0 # digits of pi
puts "\\::\\#{n}|".rjust(12)
else # edge of pie
puts "\\__\\|".rjust(12)
end
end
end
```
Nothing really clever, just using some simple loops :)
**Output:**
```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤UGPi
```
[Try it online!](https://tio.run/nexus/charcoal#@394@qPGbRqaj9pmPmqbfGjno8YNj9qmARGUORkkuulR24xHjTve71n7qG1ifDxYwYRDS6wetU0/tOT9nq3v9ywPyPz/HwA)
You may be wondering: what is this sorcery? How can you fill with `UGPi`? Well, Charcoal is starting to get Wolfram Language support, in the hope that one day it can be competitive in more challenges!
## Previous, 71 bytes
```
×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤3.141592653589793238462643383279502884197169
```
[Try it online!](https://tio.run/nexus/charcoal#@394@qPGbRqaj9pmPmqbfGjno8YNj9qmARGUORkkuulR24xHjTve71n7qG1ifDxYwYRDS6wetU0/tMRYz9DE0NTSyMzU2NTC0tzS2MjYwsTMyMzE2NjC2Mjc0tTAyMLCxNDS3NDM8v9/AA "Charcoal – TIO Nexus")
## Verbose
```
Print(Multiply(6, "()"));
Move(:DownLeft)
Print(:Down, 10)
Move(:UpLeft)
Print(:UpLeft, 10)
Move(:Down)
Print(:Down, 2)
Print(:DownRight, 8)
Move(:Up)
Print("__")
Move(:UpLeft)
Move(:Left)
Fill(":")
Move(:UpRight)
Fill("3.141592653589793238462643383279502884197169")
```
Note that this is different as the deverbosifier automatically compresses strings and does not remove redundant commands.
## With compressed strings, 52 bytes
```
×⁶¦()↙↓¹⁰↖↖¹⁰↓↓²↘⁸↑__↖←¤:M↗¤”i¶∧²uτ¶R› §Q´⌈#_⮌POÞ”
```
## xxd output
```
0000000: aab6 ba28 291f 14b1 b01c 1cb1 b014 14b2 ...()...........
0000010: 1eb8 125f 5f1c 11ef 3acd 1def 0469 0a01 ...__...:....i..
0000020: b275 f40a 52be 0999 9fa4 d1e0 1a23 5f86 .u..R........#_.
0000030: d04f de04 .O..
```
[Try it online!](https://tio.run/nexus/charcoal#XY3NDoIwEITvPAXpqU3Q0G5/8Wo8SWJMPHNCadIAMRXj01elEoHbzs43M@F0t63H5cN527sXllmKMEGE7JKyG2pc7Ltne6yvniSRHB9ZSnPyAy79wo5yDnwDqzRb6LO9NZ@E/jdONqoqtN6JKt4H6xxGxYwZuyYDtpRTYZgUILRRBhhoLpnkABqYMiJnWnNqFJUGkRDCZngD "Charcoal – TIO Nexus")
[Answer]
# PHP, 170 bytes
no arbritrary precision Pi in PHP? Calculating takes much more space than Copy&Paste. Doesn´t matter that the last digit here is cut, not rounded; but in 64 bit Pi the last digit gets rounded up.
```
for(;$i<11;)echo str_pad($i?["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)].[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1]."|
":"
",13,$i++?" ":"()",0);
```
Run with `php -r '<code>'`
**uncommented breakdown**
```
for(;$i<11;)
echo str_pad($i?
["\\__\\","|\\","|:\\","\\::\\"][$i>9?0:min(3,$i)]
.[3.1415926,53589793,2384626,433832,79502,8841,971,69,3][$i-1]
."|\n"
:"\n"
,13,$i++?" ":"()",0);
```
[Answer]
# Python 2, ~~183~~ 171 bytes
```
p,d=[2384626,433832,79502,8841,971,69,3],"|\n"
c=("()"*6)+d[1]+"|\\"+`3.1415926`+d+"|:\\"+`53589793`+d
for x in range(7):c+=" "*x+"\\::\\"+`p[x]`+d
print c+" "*7+"\\__\\|"
```
Does't really do anything clever. Just builds up a big string then prints it out.
**EDIT**
Reduced to 171 after reading @Lynn's answer and learning. Sorry if it is wrong to (shamelessly) steal some bytes from you without you suggesting it. Please tell me if so and I will roll back the change.
**Output**
```
python pi.pie.py
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 63 bytes
```
ü?½Pi<Θ*q}ü¿▒5Ç>cdƒ±<Gw►,─ô╟▒g•iâÑ♠514Φ⌂!Ñεùáèè♂ÑD╔«dÿ47¡ô#UV•╧
```
[Run and debug online!](https://staxlang.xyz/#p=813fab50693ce92a717d81a8b135803e63649ff13c4777102cc493c7b167076983a506353134e87f21a5ee97a08a8a0ba544c9ae64983437ad9323555607cf&a=1)
Shorter than the accepted MATL answer. It would definitely be shorter if more digits were stored as the constant pi in Stax.
(What is that `Pi<0` in the code?)
## Explanation
Uses the ASCII equivalent to explain, which is
```
.()6*PVP$2ME.|\a+"|:\"a+"!RNyb2L$-!mV=223w+&O-"!{"\::\"s$+mELr"\__\"]+|>m'|+
```
Expalantion:
```
.()6*PVP$2ME.|\a+"|:\"a+
.() "()"
6*P Print 6 times
VP$ First two lines of pi in the output
2ME Push the two lines separately on the stack
.|\a+ Prepend the first line with "|\"
"|:\"a+ Prepend the second line with "|:\"
"..."!{"\::\"s$+mELr"\__\"]+|>m'|+
"..."! [2384626,433832,79502,8841,971,69,3]
{"\::\"s$+m Convert each element to a string and prepend "\::\"
ELr Prepend the first two lines to array
"\__\"]+ Append "\__\" to the converted array
|> Right align text
m'|+ Append "|" to each array element and print
```
[Answer]
# Java 7, ~~260~~ ~~236~~ 191 bytes
```
String d(){return"()()()()()()\n|\\3.1415926|\n|:\\53589793|\n\\::\\2384626|\n \\::\\433832|\n \\::\\79502|\n \\::\\8841|\n \\::\\971|\n \\::\\69|\n \\::\\3|\n \\__\\|";}
```
Sigh, simply outputting the pie is shorter, even with all the escaped backslashes.. >.>
Here is previous answer with a tiny bit of afford, although still not very generic or fancy (**236 bytes**):
```
String c(){String n="\n",p="|",q=p+n,x="\\::\\",s=" ",z=s;return"()()()()()()"+n+p+"\\"+3.1415926+q+p+":\\53589793"+q+x+2384626+q+s+x+433832+q+(z+=s)+x+79502+q+(z+=s)+x+8841+q+(z+=s)+x+971+q+(z+=s)+x+69+q+(z+=s)+x+3+q+(z+=s)+"\\__\\|";}
```
A pretty boring answer, since simply outputting the result without too much fancy things is shorter in Java than a generic approach.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/FW4KmJ)
```
class M{
static String c(){
String n = "\n",
p = "|",
q = p + n,
x = "\\::\\",
s = " ",
z = s;
return "()()()()()()" + n + p + "\\" + 3.1415926 + q + p + ":\\53589793" + q + x + 2384626 + q + s
+ x + 433832 + q + (z += s) + x + 79502 + q + (z += s) + x + 8841 + q
+ (z += s) + x + 971 + q + (z += s) + x + 69 + q + (z += s) + x + 3 + q
+ (z += s) + "\\__\\|";
}
public static void main(String[] a){
System.out.println(c());
}
}
```
**Output:**
```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
[Answer]
# Qbasic, 175 bytes
```
?"()()()()()()":?"|\3.1415926|":?"|:\53589793|":?"\::\2384626|":?" \::\433832|":?" \::\79502|":?" \::\8841|":?" \::\971|":?" \::\69|":?" \::\3|":?" \__\|"
```
[Answer]
# Lua, 152 Bytes
```
print[[()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|]]
```
Try as I might I could not compress this pi.
Lua is just too verbose to do it, maybe a pi of greater size, but not this one.
Another solution, 186 Bytes.
```
s="()()()()()()\n|\\3.1415926|\n|:\\53589793|\n"i=0 for z in('2384626|433832|79502|8841|971|69|3|'):gmatch'.-|'do s=s..(' '):rep(i)..'\\::\\'..z.."\n"i=i+1 end print(s..' \\__\\|')
```
Annoyingly Lua's pi isn't accurate enough to even fill the pi. :(
[Answer]
# Javascript, 172 bytes
Paste into your console to run.
```
for(y=n=0,s=`()()()()()()
`;y<10;y++,s+=`|
`)for(x=-2;x++<9;)s+=x>y(Math.PI+'2384626433832795028841971693'[n++]:`\\${y>8?'__':x+1|y>1?'::':'||'}\\`[y-x]||' ';console.log(s)
```
[Answer]
# [Deadfish~](https://github.com/TryItOnline/deadfish-), 871 bytes
```
{iiii}cicdcicdcicdcicdcicdcic{ddd}dc{{i}}{i}iiiic{ddd}ddc{dddd}dcdddddciiiciiicdddciiiiciiiic{d}iiiciiiic{{i}ddd}c{{d}}{d}ddddc{{i}}{i}iiiic{dddddd}ddddddc{iii}iiiic{dddd}icddciiciiicicddciicddddddc{{i}ddd}iiic{{d}}{d}ddddc{{i}dd}iic{ddd}ddddcc{iii}iiiic{dddd}ddciciiiiicddddciicddddciiiic{{i}ddd}c{{d}}{d}ddddc{ii}iic{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}cdcciiiiicdddddcdc{{i}ddd}iiiic{{d}}{d}ddddc{ii}iicc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiiciicddddcdddddciic{{i}ddd}iiiic{{d}}{d}ddddc{ii}iiccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}ddddddccddddcdddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iicccc{iiiiii}c{ddd}ddddcc{iii}iiiic{ddd}dddddcddcddddddc{{i}ddd}iiiiic{{d}}{d}ddddc{ii}iiccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}iiciiic{{i}ddd}dddc{{d}}{d}ddddc{ii}iicccccc{iiiiii}c{ddd}ddddcc{iii}iiiic{dddd}dc{{i}ddd}iiic{{d}}{d}ddddc{ii}iiccccccc{iiiiii}ciiiccdddc{iii}iic{{d}}{d}ddddc
```
[Try it online!](https://tio.run/##jdJdDsMgCADgE@1QC2wZz3s0nN3xO@lmG5oYieInweLjjk96v25zDpKPgQA3YyAiI4xBzDI0NdbQZt3USXJlR0fEBJHLKxZAT0iAoqmBG9p139PK1garDnFPxpkauF/049t61i1rf7BSVqR7sObzuk0wyfp3oUsnCy4Nq9XSlm253lmvNB@hQTfsfICvfWDP3DYMWXDTbXYD6ms5vuda3tU/VahlaRqU3/Z4Zs4P "Deadfish~ – Try It Online")
Just because.
[Answer]
**JavaScript (ES6), ~~170 bytes~~ 165 bytes**
is a bit "cheated", since if run on the console, the return value would be displayed
```
v=0;("()()()()()()\n|9|:87654321".replace(/\d/g,(o)=>"\\"+(Math.PI+'2384626433832795028841971693').substr(v,o,v-=-o)+"|\n"+(o<9?" ".repeat(8-o)+(o>1?"\\::":"\\__\\|"):""))
```
After some teaking, the function looks like this(function must be called with parameter with the value 0):
```
v=>`()()()()()()
|9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)
```
If you want to call the function 167 bytes:
```
z=v=>`()()()()()()
|9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)
/*could be run like this or directly in the console*/
console.info("\n"+z(0));
```
[Answer]
# PHP, 142 bytes
Sneaky-sneaky :) `php` just prints everything out without trying to interpret them as PHP code if it does not see any `<?php ?>` pairs.
```
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
\::\433832|
\::\79502|
\::\8841|
\::\971|
\::\69|
\::\3|
\__\|
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 76 bytes
```
`:+R' 7"¦__¦|":*"()"6§+(mo:'|t↑2)↓2m↓3z+zR¢" "Nmo`:'|+"¦::¦"Cṫ9Γ·::'.ṁs↑54İπ
```
[Try it online!](https://tio.run/##yygtzv7/P8FKO0hdwVzp0LL4@EPLapSstJQ0NJXMDi3X1sjNt1KvKXnUNtFI81HbZKNcIGFcpV0VdGiRkoKSX25@AlBaG6jRyurQMiXnhztXW56bfGi7lZW63sOdjcVAfaYmRzacb/j/HwA "Husk – Try It Online")
There's probably some interesing way to shorten this further.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 64 bytes
```
‛()6*15∆Iṅ\.1Ṁ½÷$‛|\p$`|:\\`p"43∆I16ȯ7ɾṘẇvṅ‛\:mvp‛\_mJJ\|vJJ12↳⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJsoKTYqMTXiiIZJ4bmFXFwuMeG5gMK9w7ck4oCbfFxccCRgfDpcXFxcYHBcIjQz4oiGSTE2yK83yb7huZjhuod24bmF4oCbXFw6bXZw4oCbXFxfbUpKXFx8dkpKMTLihrPigYsiLCIiLCIiXQ==)
] |
[Question]
[
*Note to mods, if the title doesn't do justice, change it to whatever, I thought it was funny.*
---
You're tasked with hanging up the lights for this Christmas season, and your family has decided that for it to be a merry Christmas, you need to hang at least 2 Christmas lights on your house. So, your challenge is, given a number `1 < n`, output the corresponding number of christmas lights you're going to be hanging according to the following specifications...
---
Here is the structure of a basic christmas light:
```
_?_
[___]
/:' \
|:: |
\::. /
\::./
'='
```
The only uncertain part is the question mark, as depending on where the light lands in the chain, the connection will greatly differ.
***For the first light in the chain, you will need to output:***
```
.--._
_(_
[___]
/:' \
|:: |
\::. /
\::./
'='
```
***For the last light in the chain, you will need to output:***
```
_.--.
_)_
[___]
/:' \
|:: |
\::. /
\::./
'='
```
***And for all lights in the middle:***
```
_.--.--._
_Y_
[___]
/:' \
|:: |
\::. /
\::./
'='
```
---
# Example:
***N=2***:
```
.--.__.--.
_(_ _)_
[___] [___]
/:' \ /:' \
|:: | |:: |
\::. / \::. /
\::./ \::./
'=' '='
```
***N=6***:
```
.--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.
_(_ _Y_ _Y_ _Y_ _Y_ _)_
[___] [___] [___] [___] [___] [___]
/:' \ /:' \ /:' \ /:' \ /:' \ /:' \
|:: | |:: | |:: | |:: | |:: | |:: |
\::. / \::. / \::. / \::. / \::. / \::. /
\::./ \::./ \::./ \::./ \::./ \::./
'=' '=' '=' '=' '=' '='
```
---
# Credit
ASCII-Art was taken from: <http://www.chris.com/ascii/index.php?art=holiday/christmas/other>
It was developed by a user named "jgs", who is responsible for around 40% of content on that site.
---
# Rules
* Trailing spaces are fine, same with a trailing newline.
* There is 1 more space between the first and last bulb from the rest of the chain.
* You may only take 1 integer as input, and the output MUST be a string, no arrays.
* Your program may have undefined functions for values less than 2.
This is [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'")[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins.
---
[Sanbox post link here.](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/14432#14432)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~73~~ ~~71~~ ~~70~~ 66 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
.”L7:±¹‘Ο4↕ooā.⁾ Y*¾(){"}^ņF⁵),WοΓy⅜¬κ8ΕL▓‚7m~Ε⅝Γ‘7n┼F (=f⁄2=+⁽{@┼
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=LiV1MjAxREw3JTNBJUIxJUI5JXUyMDE4JXUwMzlGNCV1MjE5NW9vJXUwMTAxLiV1MjA3RSUyMFkqJUJFJTI4JTI5JTdCJTIyJTdEJTVFJXUwMTQ2RiV1MjA3NSUyOSUyQ1cldTAzQkYldTAzOTN5JXUyMTVDJUFDJXUwM0JBOCV1MDM5NUwldTI1OTMldTIwMUE3bSU3RSV1MDM5NSV1MjE1RCV1MDM5MyV1MjAxODduJXUyNTNDRiUyMCUyOCUzRGYldTIwNDQyJTNEKyV1MjA3RCU3QkAldTI1M0M_,inputs=NA__,v=0.12)
-4 bytes by looping over a string like `(YYY)` like [the Charcoal answer](https://codegolf.stackexchange.com/a/151287/59183)
[63 bytes](https://dzaima.github.io/SOGLOnline/?code=LiV1MjAxREw3JTNBJUIxJUI5JXUyMDE4JXUwMzlGNCV1MjE5NW9vJXUwMTAxLiV1MjA3RSUyMFkqJUJFJTI4JTI5JTdCJTIyJTdEJTVFJXUwMTQ2RiV1MjA3NSUyOSUyQ1cldTAzQkYldTAzOTN5JXUyMTVDJUFDJXUwM0JBOCV1MDM5NUwldTI1OTMldTIwMUE3bSU3RSV1MDM5NSV1MjE1RCV1MDM5MyV1MjAxODduZjJXRiV1MjI2MCV1MjA3RCU3QkAldTI1M0MlN0QldTI1M0M_,inputs=NQ__,v=0.12) would work if 2 didn't need to be handled :/
[Answer]
# Python 3, ~~200~~ ~~195~~ ~~191~~ ~~190~~ 186 bytes
```
d,*l=" _%c_ , [___] , /:' \ ,|:: | ,\::. / , \::./ , '=' ".split(',')
x=int(input())-2
print(' '*3,-~x*'.--.__.--'+'.\n',d%'(',d%'Y'*x,d%')')
for s in l:print(s,s*x,s)
```
-1 byte from dylnan
-4 bytes from Rod
Takes input on stdin.
[Try it online!](https://tio.run/##JYzBCsMgEETv@YolEFatGmigByEfUprioaFUCEaiBQuhv27ddA8zj53dCZ/0Wv1QyizFMrZgu4cFGgk3a@39oN4gTES7MdX2SpMxGqCnlLA/7gBHpN9Wx7C4xFAib/LofGLOh3dinKtzEzZaIKAYpPpmgVopbW1VPKGePMq5Q3boFUUm57XnuW4QwXlYzL8hyljTyEu5/AA "Python 3 – Try It Online")
Explanation:
```
d,*l=" _%c_ , [___] , /:' \ ,|:: | ,\::. / , \::./ , '=' ".split(',')
# d is the second row, without the (, Y, or ) to connect the light to the strand
# l is the third through eighth rows in a list
x=int(input())-2
# x is the number of lights in the middle of the strand
print(' '*3,-~x*'.--.__.--'+'.\n',d%'(',d%'Y'*x,d%')')
# print x+1 wire segments and a trailing dot, starting four spaces over
# on the next line, print the connectors, _(_, then _Y_ * x, then _)_
for s in l:print(s,s*x,s)
# on the Nth line, print the Nth light row, a space,
# x * the Nth light row, a space, and the Nth light row
```
[Additional Festive Version!](https://repl.it/@pizzapants111/Festive-Christmas-Lights)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~113~~ 107 bytes
```
+" ."*=tQ"--.__.--."++" _(_ "j"_Y_"*Q]*6d" _)_"jms[d;jd*Q]*2;;d)c5" /:' \ |:: |\::. / \::./ '=' "
```
[Try it online!](http://pyth.herokuapp.com/?code=%2B%22++++.%22%2a%3DtQ%22--.__.--.%22%2B%2B%22++_%28_+%22j%22_Y_%22%2aQ%5D%2a6d%22+_%29_%22jms%5Bd%3Bjd%2aQ%5D%2a2%3B%3Bd%29c5%22+%2F%3A%27+%5C+%7C%3A%3A+++%7C%5C%3A%3A.++%2F+%5C%3A%3A.%2F+++%27%3D%27++%22&input=6&debug=0)
Not exactly the golfiest version...
[Answer]
# JavaScript (ES6), 180 bytes
```
n=>` .${'--.__.--.'.repeat(n-1)}
`+` _Y_
[___]
/:' \\
|:: |
\\::. /
\\::./
'=' `.replace(/.+/g,(r,p)=>`${p?r:' _(_ '} ${` ${r} `.repeat(n-2)} ${p?r:' _)_'}`)
```
**Test**
```
var f=
n=>` .${'--.__.--.'.repeat(n-1)}
`+` _Y_
[___]
/:' \\
|:: |
\\::. /
\\::./
'=' `.replace(/.+/g,(r,p)=>`${p?r:' _(_ '} ${` ${r} `.repeat(n-2)} ${p?r:' _)_'}`)
function update()
{
var n=+I.value
P.textContent=f(n)
}
update()
```
```
<input id=I type=number value=2 min=2 oninput='update()'>
<pre id=P></pre>
```
[Answer]
# JavaScript (ES6), ~~204~~ ~~201~~ ~~196~~ ~~194~~ 192 bytes
```
N=>` ${(r=x=>x.repeat(N-1))(`.--.__.--`)}.
_(_ ${N--,r(` _Y_ `)} _)_
`+` [___]
/:' \\
|:: |
\\::. /
\\::./
'=' `.split`
`.map(x=>`${x=` ${x} `} ${r(x)} `+x).join`
`
```
```
f=
N=>` ${(r=x=>x.repeat(N-1))(`.--.__.--`)}.
_(_ ${N--,r(` _Y_ `)} _)_
`+` [___]
/:' \\
|:: |
\\::. /
\\::./
'=' `.split`
`.map(x=>`${x=` ${x} `} ${r(x)} `+x).join`
`
for(let i = 2; i <= 5; i++){
console.log(f(i))
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~78~~ 74 bytes
```
M⁴→×….--.__⁹⊖θ.⸿F⪫()×Y⁻貫M⁼ι)→P“ ▷υ ρ1↗N⁷Σ⭆ C✂⪪⟲⦃¬≡↘↨H℅⌕Σêλ⍘” _ι_M⁺⁴⁼ι(→
```
[Try it online!](https://tio.run/##TZDBasMwEETPzlcsungFsgOlFKqQU9pLwRBKL6EqwjhKLFCkWLYDpcm3q4pdik47u8MMj23a2jeuNiFU7qLwkQF/18d2oKvF1ms74Ic@qR43341Rm9adkZRFUUpJGDxTBi@q8eqk7KD22FH6nyKl8CRuB@cB35y2SJDGzNxGdlFW2o49dgweYo7CzyKbCF67sTY9agaEEprgZNVoBn2e64WFTynlV5xLnoMQwl45B4CrsEJwXgIsozfJu4B8nd95sj88AJmsOnHm@4SyNREwfiRBQkJTplsIT6G4mF8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes by simplifying the way the wiring is printed. Saved 2 bytes because the new code automatically casts the input to integer. Explanation:
```
M⁴→×….--.__⁹⊖θ.⸿
```
Print the wiring by taking the string `.--.__`, moulding it to length 9, then repeating it once for each join, finishing with a final `.` before moving to the start of the next line for the bulbs.
```
F⪫()×Y⁻貫
```
Loop over a string of connectors: `(` and `)` at the ends, and `Y`s in the middle.
```
M⁼ι)→
```
Move right one character if this is the last bulb.
```
P“ ▷υ ρ1↗N⁷Σ⭆ C✂⪪⟲⦃¬≡↘↨H℅⌕Σêλ⍘”
```
Print the body of the bulb without moving the cursor.
```
_ι_
```
Print the cap of the bulb including the connector.
```
M⁺⁴⁼ι(→
```
Move to the start of the next bulb (an extra character if this is the first bulb).
[Answer]
# Excel VBA, ~~224~~ ~~207~~ 205 Bytes
Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window.
Prints the bulbs line by line, from top left to bottom right
```
?Spc(4)[Rept(".--.__.--",A1-1)]".":?" _(_ "[Rept(" _Y_",A1-2)]" _)_":For i=0To 5:b=Split(" [___] 1 /:' \ 1|:: | 1\::. / 1 \::./ 1 '=' ",1)(i):[B1]=b:?b" "[Rept(B1,A1-2)]" "b:Next
```
Sample I/O
```
[A1]=7 '' Input to worksheet, may also be done manually
?Spc(4)[Rept(".--.__.--",A1-1)]".":?" _(_ "[Rept(" _Y_",A1-2)]" _)_":For i=0To 5:b=Split(" [___] 1 /:' \ 1|:: | 1\::. / 1 \::./ 1 '=' ",1)(i):[B1]=b:?b" "[Rept(B1,A1-2)]" "b:Next
.--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.
_(_ _Y_ _Y_ _Y_ _Y_ _Y_ _)_
[___] [___] [___] [___] [___] [___] [___]
/:' \ /:' \ /:' \ /:' \ /:' \ /:' \ /:' \
|:: | |:: | |:: | |:: | |:: | |:: | |:: |
\::. / \::. / \::. / \::. / \::. / \::. / \::. /
\::./ \::./ \::./ \::./ \::./ \::./ \::./
'=' '=' '=' '=' '=' '=' '='
```
-17 Bytes thanks to [@YowE3k](https://codegolf.stackexchange.com/users/76990/yowe3k)
-2 bytes for addition of temporary variable `b`
[Answer]
# C, ~~279~~ ~~278~~ ~~272~~ ~~262~~ 259 bytes
*Thanks to @NieDzejkob for saving six bytes!*
```
#define P;printf(
i,j;f(n){char*S=" [___] \0 /:' \\ \0|:: | \0\\::. / \0 \\::./ \0 \'=\' \0"P" ");for(i=n--;--i P".--.__.--"))P".\n _(_ ");for(;++i<n P" _Y_"))P" _)_\n%s ",S);for(;*S P"%10s\n%s ",S,S+10),S+=10)for(i=n;--i P S));}
```
[Try it online!](https://tio.run/##NY/BboMwDIbvPMWvTBVxIUBvUzLeASmnaZ6iijVdJi2b6G5tn52FQC/2/9ufbXlU53Gc56ePkw/xhMH8TiH@eVmE@st4Gek6fh6nve0F3pxz7wC4Q6tLMGd90zrl2yKZtW6ANiPZtCsOLnsukY0YxCIEGf8zydBHpYxSAYNolGqcS1EQJccRcNI9SFNV4SVinU6dV5cxbJYcx90ForYbvreJ3R26y6Ne2@rQUYp9Stvt9TIskbnP6W98H0OUVFyLZamXz2SK@/wP)
**Unrolled:**
```
#define P;printf(
i, j;
f(n)
{
char*S = " [___] \0 /:' \\ \0|:: | \0\\::. / \0 \\::./ \0 \'=\' \0"
P" ");
for (i=n--; --i P".--.__.--"))
P".\n _(_ ");
for (; ++i<n P" _Y_"))
P" _)_\n%s ",S);
for (; *S P"%10s\n%s ", S, S+10), S+=10)
for(i=n; --i P S));
}
```
[Answer]
# Java, ~~310~~ ~~307~~ ~~300~~ 275 bytes
Thanks to DevelopingDeveloper for converting it to a lambda expression
```
i->{int j=1;String o=" .";for(;j++<i;)o+="--.__.--.";o+="\n _(_ ";for(;--j>2;)o+=" _Y_ ";o+=" _)_";String[]a={" [___] "," /:' \\ "," |:: | "," \\::. / "," \\::./ "," '=' "};for(String b:a)for(j=0;j++<i;)o+=j==1?"\n"+b+" ":j==i?" "+b:b;return o;};
```
Expanded:
```
i->
{
int j=1;
String o=" .";
for(;j++<i;)
o+="--.__.--.";
o+="\n _(_ ";
for(;--j>2;)
o+=" _Y_ ";
o+=" _)_";
String[]a={" [___] "," /:' \\ "," |:: | "," \\::. / "," \\::./ "," '=' "};
for(String b:a)
for(j=0;j++<i;)
o+=j==1?"\n"+b+" ":j==i?" "+b:b;
return o;
};
```
Looking into shorter ways to multiply strings, and found that streams are surprisingly [more verbose](https://stackoverflow.com/a/6857936/5475891)
[Try it online!](https://tio.run/##TVBBbsIwELzzipUvJAoxpVIvdg3iAT31VBFkORCQ3WBHiUGqQt6eroNb4YO145nRjseom8pdU1lz/B6ba1nrAxxq1XXwobTtZ9r6qj2pQwVb6GcQz6dvtT2DSpAGnfKJGGadVx79W1AgYNT5ug@8ESseDU6QyU8JP7k24SbL3jVPXSZInlMpKd6EB1hYlMlEBnUU57lZvz7EgfuSExUhyFSSuGa3V6LHx52Uco@aBc5LNoeieIA7Y2i4T3NRMEaRfqgmtIwWmIt5WDFM6@MPSqbSAI14eUpvhFhtMDPJyowAYYj1BoesZCVvK39tLTg@8DEkjS3Hsm5OH@GCXSd/4UG15y59bvun89WFuqunDUp8bRNFVfKW/hc/jL8)
[Answer]
## PHP, ~~276~~, ~~307~~, ~~303~~, ~~301~~, ~~293~~, ~~283~~, ~~280~~, 278 Bytes
```
function g($n){$a=[" .--._".r("_.--.--._",$n)."_.--.",r("_(_")." ".r(_Y_,$n)." ".r("_)_")];foreach(explode(9,"[___]9/:' \9|:: |9\::. /9\::./9'='")as$b)$a[]=r($b)." ".r($b,$n)." ".r($b);return join("\n",$a);}function r($s,$n=3){return str_repeat(str_pad($s,9," ",2),$n-2);}
```
Readable version for testing:
```
function g($n){
$a=[
" .--._".r("_.--.--._",$n)."_.--.",
r("_(_")." ".r(_Y_,$n)." ".r("_)_")
];
foreach(explode(9, "[___]9/:' \9|:: |9\::. /9\::./9'='") as$b)
$a[]=r($b)." ".r($b,$n)." ".r($b);
return join("\n",$a);
}
function r($s,$n=3){
return str_repeat(str_pad($s,9," ",2),$n-2);
}
```
Check minified version out [here](http://sandbox.onlinephpfunctions.com/code/29be1431ca8c7e0de6bff30572c17f9edcaef965)
Check readable version out [here](http://sandbox.onlinephpfunctions.com/code/e2c061fa3a23012d8cae9407d7e35fced8569c9b)
**UPDATE**
Wrapped it in a function,
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~305~~ ~~292~~ ~~288~~ 275 bytes
```
import StdEnv
f c=mklines[' _',c,'_ \n [___] \n /:\' \\ \n|:: |\n\\::. /\n \\::./ \n \'=\' ']
@n=flatlines[a++b++c\\a<-[[' .--._']:[e++[' ']\\e<-f'(']]&b<-map(flatten o(repeatn(n-2)))[['_.--.--._']:[[' ':e]++[' ']\\e<-f'Y']]&c<-[['_.--. ']:[[' ':e]\\e<-f')']]]
```
[Try it online!](https://tio.run/##PZDBSsQwEIbv@xRzMi3ZtODBQ2hhD3oQvO1JMiGkaSrFJi27URD22Y1JrN7@Yb75fhizWO2jW8ePxYLTs4@z29ZLgHMYn/znYQLTu/dl9vYqCIAiR3MkCgA9CKWUzKHlSAAxxRvnAHBDj8h5A9CmbYlt5gBJn0gg8nDy/bTo8OvVlA6UGkTdMZFbABrGGkUkF5ZSUU4QbccmUhEp74aOOb1V2RCsh7W62M3q4CvP7uu6Tg6VBX@OJCDcymL6F71mkSmFBc6tO1zoHasTJuM56PSSHk7wEL9N6n27RjZENn557WaThueX@LgPPw "Clean – Try It Online")
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), ~~365~~ ~~316~~ ~~315~~ ~~251~~ 245 bytes
-21 thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack)
-43 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)
-6 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
```
v,p=' \n'
a,l,n=".--._",["[___]"," /:' \ ","|:: |","\::. /"," \::./ "," '=' "],input()-2
e,b=v*5+"_)_",a[::-1]
r=v*4,a,(b[:4]+a)*n,b,p+" _(_ ",(v*4+"_Y_ ")*n,e+p+v
for i in l:b=4-2*(i in l[1:]);r+=i+v*-~b,(i+v*b)*n,v+i+p
print''.join(r)
```
[Try it online!](https://tio.run/##JY1Ri8MgEITf/RWLL9G4JjSkLxZ/yGFFIvQ4j2Ik5IRA6V9PV@5tZmfm23LsP2uedDnKcZ6bdf5WsdgO7rljCz4xWz5oPQSOjrsQgufIYTRUAFIvYwDgRepuzAAwtrTJsaUAHZGAe0y5/O1C6ok9MNraXxUPkpiLM0ZfPNsUHWdcUERnZq8W2WeMWBQxggj0g6OgBs2@yPEWP1RRlX2vGyRIGZ4m2llPvfh37mK8vBE3qdrrd0TRRGzDqpIqrGwp7103/K4pi02e5/UD "Python 2 (PyPy) – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 261 bytes
```
{val c=" [___]\n/:' \\\n |::|\n \\::./\n \\::./\n '='"
(0..7).map{i->print(" .--._\n _(_\n$c".lines()[i].padEnd(10))
(0..L-3).map{print("_.--.--._\n _Y_\n$c".lines()[i].padEnd(9))}
if(i>1)print(' ')
print("_.--.\n _)_\n$c".lines()[i])
println()}}
```
## Beautified
```
{
val c = " [___]\n /:' \\\n |:: |\n \\::. /\n \\::./\n '='"
(0..7).map {i->
print(" .--._\n _(_\n$c".lines()[i].padEnd(10))
(0..L - 3).map {
print("_.--.--._\n _Y_\n$c".lines()[i].padEnd(9))
}
if (i > 1) print(' ')
print("_.--.\n _)_\n$c".lines()[i])
println()
}
}
```
## Test
```
fun f(L: Int)
{val c=" [___]\n/:' \\\n |::|\n \\::./\n \\::./\n '='"
(0..7).map{i->print(" .--._\n _(_\n$c".lines()[i].padEnd(10))
(0..L-3).map{print("_.--.--._\n _Y_\n$c".lines()[i].padEnd(9))}
if(i>1)print(' ')
print("_.--.\n _)_\n$c".lines()[i])
println()}}
fun main(args: Array<String>) {
f(6)
}
```
## TIO
[TryItOnline](https://tio.run/##ddDBisJADAbg+zxFKMIkh47KwoqDFvbgYcGbp8WRYahWBmu21Logtc/eHVtBQcwlOfz5Ajn8VrnnVmRnhgyXGr65orb+czmk8whgba3dGB5qCcYYhqvW19CM0VoNw/A0gZzLSOBIqQmpoytqHydF6bnC4IRScaxsF7QY+iCNVDi9OyGt/UYVbrvgLY5HRJ2xjD965U7Y2/pD+HkrTIka4TP0yZj6XQmSxDPTEWDpxbjHckZqmv4pR+cZXbk/afgqS3eZraoQ2ScEtbgpGX6SaNp/)
[Answer]
# Google Sheets, 190 Bytes
Anonymous worksheet function that take input from range `A1` and outputs to the calling cell
```
=" "&Rept(".--.__.--",A1-1)&".
_(_ "&Rept(" _Y_ ",A1-2)&" _)_"&RegexReplace("
[___]
/:' \
|:: |
\::. /
\::./
'='
","
(.*)","
$1 "&Rept("$1",A1-2)&" $1
```
] |
[Question]
[
### Challenge
Create a program that returns a truthy value when run on Microsoft Windows (for simplicity we'll stick with Windows 7, 8.1 and 10) and a falsey value when run on any other operating system (OSX, FreeBSD, Linux).
### Rules
* Code that fails to run/compile on a platform doesn't count as a falsey value.
### Winning criteria
I'm labelling this as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest score wins, but I'm also very interested in seeing creative solutions to this problem.
[Answer]
# MATLAB, 4 bytes
```
ispc
```
From the [documentation](https://se.mathworks.com/help/matlab/ref/ispc.html):
>
> `tf = ispc` returns logical 1 (true) if the version of MATLAB® software is for the Microsoft® Windows® platform. Otherwise, it returns logical 0 (false).
>
>
>
There are also the functions [`ismac`](https://se.mathworks.com/help/matlab/ref/ismac.html) and [`isunix`](https://se.mathworks.com/help/matlab/ref/isunix.html). ~~I'll leave it to the reader to figure out what those functions do.~~ [Mego](https://codegolf.stackexchange.com/users/45941/mego) kindly asked for diagrams explaining `ismac` and `isunix` so I've tried to illustrate it here:
[![enter image description here](https://i.stack.imgur.com/o9q7r.jpg)](https://i.stack.imgur.com/o9q7r.jpg)
It was not asked for a diagram of `ispc` but I can reveal that the behaviour is pretty similar, except substitute `OSX` and `Unix` with `Windows`.
---
**Second approach:**
Here's a second approach with [`getenv`](https://www.mathworks.com/help/matlab/ref/getenv.html) using 23 bytes that should be bullet proof, unless there's another operating system starting with `W`:
```
x=getenv('OS');x(1)==87
```
>
> `getenv 'name'` searches the *underlying operating system environment
> list* for text of the form `name=value`, where `name` is the input
> character vector. If found, MATLAB® returns the character vector
> value. If the specified name cannot be found, an empty matrix is
> returned.
>
>
>
[Answer]
# Vim, 2 bytes
```
<C-a>1
```
On Windows, `<C-a>` (ctrl+a) is mapped by default to `Select All`. If you type a `1` in select mode in Windows, it replaces the selection with what you typed (1) leaving a 1 in the buffer.
On other operating systems, `<C-a>` by default is mapped to `Increment number`. Because there's no number to increment, it's a no-op, and then the 1 increases the count but in terms of the buffer is a no-op.
1 is truthy in Vim, and an empty string is falsy
[Answer]
# [Python 2.7.10](https://docs.python.org/2/), 24 bytes
```
import os
0/('['>os.sep)
```
Thanks to FlipTack for 3 bytes
This program takes advantage of the fact that Windows is the only OS to use `\` as a path separator. Normally this is frustrating and bad, but for once it is actually an advantage. On Windows, `'['>os.sep` is false, and thus `0/0` is computed, causing a `ZeroDivisionError` and exiting with a non-zero exit code. On non-Windows platforms, `'['>os.sep` is true, making the expression `0/1`, which does nothing, and the program exits with exit code 0.
[Answer]
## ~~x86 Assembly, 7 bytes~~ (Inspired by [Runemoro's answer](https://codegolf.stackexchange.com/a/106180/63767))
```
31 DB 89 D8 40 CD 80
```
Or
```
xor ebx, ebx
mov eax, ebx
inc eax
int 0x80
```
## Description
First of all, we'll set `eax` to `1` (the system call number for `exit(int val)` for `Linux`, `FreeBSD` and `OSX`).
Then, we'll call the interrupt gate `0x80` which is the system call gate for `Linux`, `FreeBSD` and `OSX`. That would cause the program to exit with status of `ebx` which is `0` (`false`).
On Windows `int 0x80` is an invalid gate (It uses `2e` as a syscall gate) and would crash the program, causing it to end with a positive exit code (`true`).
**Edit:** Would not work on `OSX` since it has a different argument-passing convention on 32 bit (by the stack).
## References and further reading
* [`FreeBSD - System Calls`](https://www.freebsd.org/doc/en/books/developers-handbook/x86-system-calls.html): Information about system calls in `FreeBSD`.
* [`System calls in the Linux kernel. Part 2.`](https://0xax.gitbooks.io/linux-insides/content/SysCall/syscall-2.html): A great article about Linux's system calls.
* [`Linux Syscall Reference`](http://syscalls.kernelgrok.com/): a system call numbers reference for `Linux`.
* [`Windows Syscall Shellcode`](https://www.symantec.com/connect/articles/windows-syscall-shellcode) : An article about directly calling system calls in `windows` from assembly.
* [`Making system calls from Assembly in Mac OS X`](https://filippo.io/making-system-calls-from-assembly-in-mac-os-x/): An article about system calls on `OSX`.
[Answer]
# PHP, 22 bytes
```
`<?=PATH_SEPARATOR>":";`
```
prints `1` if the path separator is semicolon (colon or empty for all other OSs except for DOS and OS/2), else nothing.
**also 22 bytes**, but not that safe:
```
<?=strpos(__FILE__,92);
```
prints a positive integer if the file path contains a backslash; else nothing.
A safe alternative with **27 bytes**: `<?=DIRECTORY_SEPARATOR>"/";` prints `1` or nothing.
**A strange find**: `<?=__FILE__[1]==":";` (**20 bytes**) should be, not safe either, but ok.
But although `__FILE__` pretends to be a string (I tried `var_dump` and `gettype`), indexing it throws an error, unless you copy it somewhere else (concatenation also works) or use it as a function parameter.
Edit:
`<?=(__FILE__)[1]==":";` (also **22 bytes**) works in PHP 7; but that´s because the parentheses copy the constant´s value to a temporary variable.
**27 bytes**: `<?=stripos(PHP_OS,win)===0;`
tests if predefined `PHP_OS` constant starts with `win` (case insensitive; Windows,WIN32,WINNT, but not CYGWIN or Darwin); prints `1` for Windows, else nothing.
**17/18 bytes**:
```
<?=strlen("
")-1;
```
prints `1` if it was stored with Windows linebreak (also on DOS, OS/2 and Atari TOS - although I doubt that anyone ever compiled PHP for TOS), else `0`.
You could also check the constant `PHP_EOL`.
**more options:**
`PHP_SHLIB_SUFFIX` is `dll` on Windows, but not necessarily only there.
`php_uname()` returns info on the operating system and more; starts with `Windows` for Windows.
`$_SERVER['HTTP_USER_AGENT']` will contain `Windows` when called in a browser on Windows.
`<?=defined(PHP_WINDOWS_VERSION_BUILD);` (38 bytes) works in PHP>=5.3
**conclusion**
The only failsafe way to tell if it´s really Windows, not anything looking like it, seems to be a check on the OS name. For PHP: `php_os()` may be disabled for security reasons; but `PHP_OS` will probably always contain the desired info.
[Answer]
# C, ~~44~~ ~~43~~ ~~38~~ 36 bytes
*Thanks to @Downgoat for a byte! crossed out 44 is still regular 44*
*Thanks to @Neil for two bytes!*
```
f(){return
#ifdef WIN32
!
#endif
0;}
```
[Answer]
# Befunge-98, 7 bytes
```
6y2%!.@
```
[Try it online!](http://befunge-98.tryitonline.net/#code=NnkyJSEuQA&input=)
This works by querying the system path separator, which is `\` on Windows and `/` on other operating systems.
```
6y System information query: #6 returns the path separator.
2% Test the low bit - this will be 1 for '/' and 0 for '\'.
! Not the value, so it becomes 0 for '/' and 1 for '\'.
.@ Output the result and exit.
```
[Answer]
# Mathematica, 28 bytes
```
$OperatingSystem=="Windows"&
```
[Answer]
# Java 8, 33 bytes
*Special thanks to Olivier Grégoire for suggesting `separatorChar`, and Kritixi Lithos for -1 byte!*
This is a lambda expression which returns a boolean. This can be assigned to `Supplier<Boolean> f = ...;` and called with `f.get()`.
```
()->java.io.File.separatorChar>90
```
[**Try it online!**](https://tio.run/nexus/java-openjdk#NY2xCsIwFEXn5CvemAwGV6l2UHBz6igOz5rWJ2kSkpeCSL@9lqLThXsP59IQQ2J44YimMDnTFd8yBW@aEqMjmyoZy91RC63DnOGC5OEjAX5tZuQlxkAPGJZNNZzI99cbYOqzXlGAv2x/DMFZ9DV0cJiV3tTrMwVzJmdNthETckinJ6Z6t52FqJp3ZjuYUNjExczOq870lpXWlRRCiklOcv4C) - the server isn't windows, so this prints `false`. However, in my windows machine, the same code prints `true`.
What this code does is get the System's file seperator, and check whether its codepoint is larger than the character `[`. This true for Windows, as it uses `\` as the seperator - but every other OS uses `/`, which has a lower code in the ASCII table.
[Answer]
# R, 15 bytes
```
.Platform$O>"v"
```
Thanks to [plannapus](https://codegolf.stackexchange.com/users/6741/plannapus) for the suggestion to use partial matching for list element extraction.
[.Platform](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Platform.html) is a list with some details of the platform under which R was built. There is an element `OS.type` (the only element with name starting with "O") which is character string, giving the Operating System (family) of the computer. One of `"unix"` or `"windows"`.
So `"unix"` is less then `"v"`, but `"windows"` is greater then `"v"`. Other valid 15 bytes answers are
```
.Platform$O>"V"
.Platform$O>"w"
.Platform$O>"W"
```
[R is being developed for the Unix-like, Windows and Mac families of operating systems](https://cloud.r-project.org/doc/FAQ/R-FAQ.html#What-machines-does-R-run-on_003f). Other OS families are not supported.
[Answer]
# J, 7 bytes
```
6=9!:12
```
This is a verb (similar to a function) that uses the builtin foreign conjunction `9!:12` to acquire the system type where 5 is Unix and 6 is Windows32.
[Answer]
## x86 machine code, 9 bytes
```
40 39 04 24 75 02 CD 80 C3
```
Compiled from:
```
inc eax ; set eax to 1
cmp [esp], eax ; check if [esp] == 1 (linux)
jne windows ; jump over "int 0x80" if on windows
int 0x80 ; exit with exit code 0 (ebx)
windows:
ret ; exit with exit code 1 (eax)
```
[Answer]
## Perl, 11 bytes
```
print$^O=~MS
```
`^O` should be replaced by a literal Control-O.
Outputs `1` on windows, nothing on another OS.
Note that I'm not using `say` as it adds a trailing newline, which is truthy in Perl.
*-2 bytes thanks to primo. (and fixed potential issues)*
*-1 bytes thanks to ais523.*
[Answer]
# julia, 10 bytes
```
is_windows
```
A function that returns true for windows
[Answer]
# C#, ~~61~~ 48 bytes
```
()=>(int)System.Environment.OSVersion.Platform<4
```
Saved 13 bytes thanks to TheLethalCoder
Or a full program at 83 bytes:
```
class P{static int Main(){return(int)System.Environment.OSVersion.Platform<4?1:0;}}
```
Various Windows variants use enum values 0 to 3 in the [Microsoft .NET implementation](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/platformid.cs). 4 is Unix, 5 is Xbox [360] (which I won't consider "Windows"), 6 is MacOSX. [Mono uses the same values](http://mono.wikia.com/wiki/Detecting_the_execution_platform), adding 128 for Unix/Linux in earlier versions.
Therefore, anything < 4 is Windows, and everything else is not Windows.
[Answer]
# JavaScript, ~~42~~ ~~30~~ ~~26~~ 25 bytes
```
console.log((
//Begin
_=>navigator.oscpu[0]>'V'
//End
)())
```
Tested with Firefox. (Chrome doesn't have the `oscpu` property.)
Since lowercase letters have a higher character code than uppercase letters, this depends on the first letter of `navigator.oscpu` being uppercase and not being *W*, *X*, *Y* or *Z* on any platform that Firefox supports (other than Windows, of course). According to [this post](https://stackoverflow.com/a/9514476/1419007), that is the case.
### Edits
1. Saved 12 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
2. Saved another four bytes
3. Saved another byte thanks to [Blender](https://codegolf.stackexchange.com/users/7800/blender).
[Answer]
## Batch, 50 bytes
```
@if %OS%==Windows_NT if not exist Z:\bin\sh echo 1
```
Edit: Fixed to ignore DOS instead of claiming that it's Windows.
The ~~only~~ other way I know of running Batch outside of Windows is to use WINE which by default will map `Z:` to `/`. Therefore if `Z:\bin\sh` exists, chances are that it's `/bin/sh`, so not MS Windows.
I don't know what WINE sets %OS% to, but if it's not `Windows_NT` then I could save 23 bytes.
[Answer]
# QBasic, 31 bytes
```
?INSTR(ENVIRON$("COMSPEC"),"W")
```
Prints non-zero under Windows, 0 under everything else.
`COMSPEC` is an environment variable unique to Microsoft OSs. It points to the command interpreter, typically `command.com` or `cmd.exe`. Under Windows, the command interpreter sits somewhere in the Windows directory; under MS-DOS, it sits in the DOS directory or on the root of the disk, and under any other OS, it doesn't exist.
By checking to see if the value of `COMSPEC` contains a "W", we can tell the difference between Windows and not-Windows.
[Answer]
# Node.js, ~~27~~ ~~16~~ ~~15~~ 13 bytes
Thanks to **@Patrick**, who shaved 12 bytes off my solution using Node's REPL:
```
_=>os.EOL>`
`
```
Original solution:
```
_=>require('path').sep!='/'
```
[Answer]
# Excel VBA, ~~41~~ ~~40~~ ~~30~~ ~~29~~ ~~26~~ 24 Bytes
Immediate windows function that returns `true` if the system's OS code starts is longer than length 3, because the info is restricted to output either else `mac` or `pcdos` this returns `true` only on windows pcs
```
?[Len(Info("SYSTEM"))>3]
```
**Previous Versions**
```
''# Ignore the second `"` that follows every `\` - its only there for highlighting
?Left(Environ("OS"),1)="W" # 24 Bytes
?InStr(ThisWorkbook.Path,"\"") # 29 Bytes
?Mid(ThisWorkbook.Path,3,1)="\"" # 30 Bytes, Restricted to local Files
?Application.PathSeparator="\"" # 30 Bytes
?Left(Application.OperatingSystem,1)="W" # 40 Bytes
```
**Changes**
-1 Thanks to Neil for using `Left(...,1)` over `Mid(...,1,1)`
-10 Thanks to ChrisH for pointing out [@Mego's Path Separator Trick](https://codegolf.stackexchange.com/a/106084/44821 "@Mego's Path Separator Trick")
-1 For Checking the `WorkbookPath` for `"\"` rather than using `Application.Path Separator`
-4 For switching to `Environ()`
-2 For switching to `[Len(Info(...`
**Novel Solution, 51 bytes**
Novel `sub`routine that outputs, to the VBE immediates window, a `1 (truthy)` under windows and `0 (falsey)` under mac by method of conditional compilation.
```
Sub a
i=1
#If Mac Then
i=0
#End If
Debug.?i
End Sub
```
[Answer]
# [Perl 6](https://perl6.org), ~~19~~ 18 bytes
```
put $*DISTRO.is-win
```
```
put ?($*CWD~~/\\/)
```
Both output `True` or `False` depending on the system it is run on.
[Answer]
# bash + coreutils, 5 bytes
```
rm $0
```
Also works in most other POSIXy shells. (Note that Windows ports of `bash` and `rm` exist; even though they're only normally used with more heavily POSIXy operating systems, this isn't an entirely vacuous entry.) Outputs via exit code (0 = false, 1 = true). Can be counted as 4 bytes if you're allowed to assume a filename (e.g. `rm a`). Note that this can potentially fail in the case of very weird filenames (which `rm` will interpret as arguments due to the lack of quoting, and possibly delete files you care about, so I'd advise against running this program from a file with a weird name).
Note: deletes the program from disk as a side effect, or at least tries to. In the case where we're running on Windows, the OS will fail to delete the running file (an operation that Windows disallows either by default or full stop), and thus `rm` will error out. `bash` catches the error and converts it into an exit code (thus the program as a whole terminates normally). Most of the other entries here are using 0 for falsey and 1 for truthy in exit codes, so this does the same; note that `bash`'s `if` statement doesn't accept integers at all (rather, it accepts *commands* and branches based on whether they run successfully, and arithmetic tests are done via the means of programs like `test` that intentionally report a "crash" on a failed comparison), so this is on shakier ground in terms of legality than programs that output via exit code in languages where 0 is valid in an `if` statement test and sends the program to the `else` branch.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 21 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
'W'∊∊#⎕WG'APLVersion'
```
[Try it online!](https://tio.run/nexus/apl-dyalog#@///v3q4@qOOLiBSftQ3Ndxd3THAJyy1qDgzP08dAA "APL (Dyalog Unicode) – TIO Nexus")
`#⎕WG'APLVersion'` Root (**#**) **W**indow **G**et property **APL Version**
`∊` enlist (flatten)
`'W'∊` is **W** a member? (no non-Windows return values contain a capital W)
[Answer]
# [TrumpScript](https://github.com/samshadwell/TrumpScript), 17 bytes
```
America is great.
```
[Try it online!](https://tio.run/##KykqzS0oTi7KLCj5/98xN7UoMzlRIbNYIb0oNbFE7/9/AA "TrumpScript – Try It Online")
---
This program, if run on windows, will print:
```
The big problem this country has is being PC
```
This is considered a truthy value.
---
Empty output and the following value are falsy:
```
Boycott all Apple products until such time as Apple gives cellphone info to authorities regarding radical Islamic terrorist couple from Cal
```
The empty output will occur on any linux system (for this program), the long apple response obviously occurs on Mac (for any program). On TIO, the backend (I'm assuming) is a Unix operating system, so you can only get the falsy value; on my computer I get the PC message.
---
Not 100% sure if this counts as an error message (which would invalidate the answer), but if you didn't know about this it was probably worth a laugh for you.
[Answer]
# tcl, 38 bytes
```
expr [lsearch $tcl_platform windows]>0
```
[Answer]
# PHP 17 Bytes
The following will output 1 if windows and nothing if anything else. Ignoring notices of string convertion.
`<?=PHP_OS==WINNT;`
[Try online](https://3v4l.org/ra15J) Online tests for linux because the sandbox is linux for PoC.
[Answer]
# Java 8, 49 bytes
```
()->System.getenv().get("OS").contains("Windows")
```
Longer than the [other Java answer](https://codegolf.stackexchange.com/a/106092), but takes a different approach.
This lambda fits in a `Supplier<Boolean>` and can be tested with the following program:
```
public class DetectMSWindows {
public static void main(String[] args) {
System.out.println(f(() -> System.getenv().get("OS").contains("Windows")));
}
private static boolean f(java.util.function.Supplier<Boolean> s) {
return s.get();
}
}
```
[Answer]
# Haskell, ~~39~~ 31 bytes
```
import System.Info
f=os!!0=='m'
```
I check for the first letter output of "m", which should be "mingw" for windows. As far as I could tell, there is no other OS which starts with M. The information comes from <https://github.com/ghc/ghc/blob/master/compiler/utils/Platform.hs>
[Answer]
# [8th](http://8th-dev.com/), 11 bytes
```
os 1- not .
```
Prints `true` on Windows, `false` on Linux and macOS. Other platforms supported by 8th are Android, iOS and Raspberry Pi, but I am not able to test on them.
Ungolfed version (with comments)
```
G:os \ Return a number n indicating the operating system
\ 0 for Linux
\ 1 for Windows
\ 2 for macOS
\ 3 for Android
\ 4 for iOS
\ 5 for Raspberry Pi
n:1- \ Subtract 1
G:not \ If Windows --> true, otherwise --> false
. \ Print result
```
[Answer]
# Python 3 (13 bytes)
```
import winreg
```
Returns with exit code zero (generally true in shells) if on windows, and with a non-zero exit code otherwise.
If you prefer it the other way round, there is a 12 bytes solution: `import posix`.
] |
[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/31695/edit).
Closed 2 years ago.
[Improve this question](/posts/31695/edit)
Your goal is to print (to the standard output) the largest number possible, using just ten characters of code.
* You may use any features of your language, except built-in exponentiation functions.
+ Similarly, you may not use scientific notation to enter a number. (Thus, no `9e+99`.)
* The program must print the number without any input from the user. Similarly, no reading from other files, or from the Web, and so on.
* Your program must calculate a single number and print it. You can not print a string, nor can you print the same digit thousands of times.
* You may exclude from the 10-character limit any code necessary to print anything. For example, in Python 2 which uses the `print x` syntax, you can use up to 16 characters for your program.
* The program must actually succeed in the output. If it takes longer than an hour to run on the fastest computer in the world, it's invalid.
* The output may be in any format (so you can print `999`, `5e+100`, etc.)
* [Infinity is an abstract concept](https://en.wikipedia.org/wiki/Infinity), not a number. So it's not a valid output.
[Answer]
# Perl, >1.96835797883262e+18
```
time*time
```
Might not be the largest answer... today! But wait enough millennia and it will be!
---
**Edit:**
To address some of the comments, by "enough millenia," I do in fact mean n100s of years.
To be fair, if the big freeze/heat death of the universe is how the universe will end (estimated to occur ~10100 years), the "final" value would be ~10214, which is certainly much less than some of the other responses (though, "random quantum fluctuations or quantum tunneling can produce another Big Bang in 101056 years"). If we take a more optimistic approach (e.g. a cyclic or multiverse model), then time will go on infinitely, and so some day in some universe, on some high-bit architecture, the answer would exceed some of the others.
On the other hand, as pointed out, `time` is indeed limited by the size of integer/long, so in reality something like `~0` would always produce a larger number than `time` (i.e. the max `time` supported by the architecture).
This wasn't the most serious answer, but I hope you guys enjoyed it!
[Answer]
# Wolfram ‚âÖ 2.003529930 √ó 1019728
Yes, it's a language! It drives the back-end of the popular Wolfram Alpha site.
It's the only language I found where the Ackermann function is built-in **and** abbreviated to less than 6 characters.
In eight characters:
```
$ ack(4,2)
200352993...719156733
```
Or ‚âÖ 2.003529930 √ó 1019728
`ack(4,3)`, `ack(5,2)` etc. are much larger, but too large. `ack(4,2)` is probably the largest Ackermann number than can be completely calculated in under an hour.
Larger numbers are rendered in symbolic form, e.g.:
```
$ ack(4,3)
2↑²6 - 3 // using Knuth's up-arrow notation
```
The rules say any output format is allowed, so this might be valid. This is greater than 101019727, which is larger than any of the other entries here except for the repeated factorial.
However,
```
$ ack(9,9)
2↑⁷12 - 3
```
is larger than the repeated factorial. The largest number I can get in ten characters is:
```
$ ack(99,99)
2↑⁹⁷102 - 3
```
This is insanely huge, the Universe isn't big enough to represent a significant portion of its digits, even if you took repeated logs of the number.
[Answer]
# Python2 shell, 3,010,301 digits
```
9<<9999999
```
Calculating the length: Python will append a "L" to these long numbers, so it reports 1 character more than the result has digits.
```
>>> len(repr( 9<<9999999 ))
3010302
```
First and last 20 digits:
```
40724177878623601356... ...96980669011241992192
```
[Answer]
# CJam, 2 √ó 10268,435,457
```
A28{_*}*K*
```
This computes *b*, defined as follows:
* a0 = 10
* an = an - 12
* b = 20 √ó a28
```
$ time cjam <(echo 'A28{_*}*K*') | wc -c
Real 2573.28
User 2638.07
Sys 9.46
268435458
```
### Background
This follows the same idea as [Claudiu's answer](https://codegolf.stackexchange.com/a/31718), but it isn't based on it. I had a similar idea which I posted [just a few minutes](https://codegolf.stackexchange.com/revisions/31713/3) after [he posted his](https://codegolf.stackexchange.com/revisions/31718/3), but I discarded it since it didn't come anywhere near the time limit.
However, [aditsu's suggestion](https://codegolf.stackexchange.com/questions/31695/largest-number-in-ten-digits-of-code/31718?noredirect=1#comment66589_31713) to upgrade to Java 8 and [my idea](https://codegolf.stackexchange.com/questions/31695/largest-number-in-ten-digits-of-code/31718?noredirect=1#comment66575_31718) of using powers of 10 allowed CJam to calculate numbers beyond the reach of GolfScript, which seems to be due to some bugs/limitations of Ruby's Bignum.
### How it works
```
A " Push 10. ";
28{ " Do the following 28 times: ";
_* " Duplicate the integer on the stack and multiply it with its copy. ";
}* " ";
K* " Multiply the result by 20. ";
```
---
# CJam, ≈ 8.1 × 101,826,751
```
KK,{)*_*}/
```
Takes less than five minutes on my machine, so there's still room for improvement.
This computes a20, defined as follows:
* a0 = 20
* an = (n √ó an - 1)2
### How it works
```
KK, " Push 20 [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ]. ";
{ " For each integer in the array: ";
)* " Increment it and compute the its product with the accumulator. ";
_* " Multiply the result with itself. ";
}/
```
[Answer]
**Wolfram Language**
```
ack(9!,9!)
```
[Try it online!](http://www.wolframalpha.com/input/?i=ack%289!,9!%29)
$$\text{ack}(9!,9!) = 2 \uparrow^{362878} 362883 - 3$$
Output is in Arrow Notation.
[Answer]
# Any language with short enough constant names, 18 digits approx.
```
99/sin(PI)
```
I would post this as a PHP answer but sadly `M_PI` makes this just a little too long! But PHP yields 8.0839634798317E+17 for this. Basically, it abuses the lack of absolute precision in PI :p
[Answer]
# Python 3, 9\*2^(7\*2^33) > 10^18,100,795,813
# 9\*2^(2^35) > 10^10,343,311,894
Edit:
My new answer is:
```
9<<(7<<33)
```
Old answer, for posterity:
```
9<<(1<<35)
```
Ten characters exactly.
I am printing the number in hex, and
>
> You may exclude from the 10-character limit any code necessary to print anything. For example, in Python 2 which uses the print x syntax, you can use up to 16 characters for your program.
>
>
>
Therefore, my actual code is:
```
print(hex(9<<(7<<33)))
```
Proof that it runs in the specified time and generates a number of the specified size:
```
time python bignum.py > bignumoutput.py
real 10m6.606s
user 1m19.183s
sys 0m59.171s
wc -c bignumoutput.py
15032385541 bignumoutput.py
```
My number > 10^(15032385538\*log(16)) > 10^18100795813
3 less hex digits than the above wc printout because of the initial `0x9`.
Python 3 is necessary because in python 2, `7<<33` would be a long, and `<<` doesn't take longs as inputs.
I can't use 9<<(1<<36) instead because:
```
Traceback (most recent call last):
File "bignum.py", line 1, in <module>
print(hex(9<<(1<<36)))
MemoryError
```
Thus, this is the largest possible number of the form `a<<(b<<cd)` printable on my computer.
In all likelihood, the fastest machine in the world has more memory than I do, so my alternate answer is:
```
9<<(9<<99)
```
9\*2^(9\*2^99) > 10^(1.7172038461\*10^30)
However, my current answer is the largest anyone has submitted, so it's probably good enough. Also, this is all assuming bit-shifting is allowable. It appears to be, from the other answers using it.
[Answer]
# **HTML, 9999999999**
```
9999999999
```
.. nailed it.
[Answer]
# Haskell
Without any tricks:
```
main = print -- Necessary to print anything
$9999*9999 -- 999890001
```
Arguably without calculating anything:
```
main = print
$floor$1/0 -- 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
```
Adapting [Niet's answer](https://codegolf.stackexchange.com/questions/31695/largest-number-in-ten-digits-of-code/31711#31711):
```
main = print
$99/sin pi -- 8.083963479831708e17
```
[Answer]
## Powershell - 1.12947668480335E+42
```
99PB*9E9PB
```
Multiplies 99 Pebibytes times 9,000,000,000 Pebibytes.
[Answer]
# J (`((((((((9)!)!)!)!)!)!)!)!`)
Yeah, that's a lot. `10^(10^(10^(10^(10^(10^(10^(10^6.269498812196425)))))))` to be not very exact.
```
!!!!!!!!9x
```
[Answer]
# [K/Kona](https://github.com/kevinlawler/kona): ~~8.977649e261~~ 1.774896e308
```
*/1.6+!170
```
* `!170` creates a vector of numbers from 0 to 169
* `1.6+` adds one to each element of the vector & converts to reals (range is 1.6 to 170.6)
* `*/` multiplies each element of the array together
If Kona supported quad precision, I could do `*/9.+!999` and get around 1e2584. Sadly, it doesn't and I'm capped to double precision.
---
old method
```
*/9.*9+!99
```
* `!99` creates a vector of numbers from 0 to 98
* `9+` adds 9 to each element of the vector (now ranges 9 to 107)
* `9.*` multiplies each element by 9.0 (implicitly converting to reals, so 81.0 through 963.0)
* `*/` multiplies each element of the vector together
[Answer]
# Python - Varies, up to 13916486568675240 (so far)
Not entirely serious but I thought it would be kinda fun.
```
print id(len)*99
```
Out of all the things I tried, `len` was most consistently getting me large ids.
Yielded 13916486568675240 (17 digits) on my computer and 13842722750490216 (also 17 digits) on [this site](http://www.compileonline.com/execute_python_online.php). I suppose it's possible for this to give you as low as 0, but it could also go higher.
[Answer]
# Golfscript, 1e+33,554,432
```
10{.*}25*
```
Computes `10 ^ (2 ^ 25)`, without using exponents, runs in 96 seconds:
```
$ time echo "10{.*}25*" | ruby golfscript.rb > BIG10
real 1m36.733s
user 1m28.101s
sys 0m6.632s
$ wc -c BIG10
33554434 BIG10
$ head -c 80 BIG10
10000000000000000000000000000000000000000000000000000000000000000000000000000000
$ tail -c 80 BIG10
0000000000000000000000000000000000000000000000000000000000000000000000000000000
```
It can compute up to `9 ^ (2 ^ 9999)`, if only given enough time, but incrementing the inner exponent by one makes it take ~triple the time, so the one hour limit will be reached pretty soon.
**Explanation**:
Using a previous version with the same idea:
```
8{.*}25*
```
Breaking it down:
```
8 # push 8 to the stack
{...}25* # run the given block 25 times
```
The stack at the start of each block consists of one number, the current number. This starts off as `8`. Then:
```
. # duplicate the top of the stack, stack is now | 8 | 8 |
* # multiply top two numbers, stack is now | 64 |
```
So the stack, step by step, looks like this:
```
8
8 8
64
64 64
4096
4096 4096
16777216
16777216 16777216
```
... etc. Written in math notation the progression is:
```
n=0, 8 = 8^1 = 8^(2^0)
n=1, 8*8 = 8^2 = 8^(2^1)
n=2, (8^2)*(8^2) = (8^2)^2 = 8^4 = 8^(2^2)
n=3, (8^4)^2 = 8^8 = 8^(2^3)
n=4, (8^8)^2 = 8^16 = 8^(2^4)
```
[Answer]
# [wxMaxima](http://andrejv.github.io/wxmaxima/) ~3x1049,948 (or 108,565,705,514 )
```
999*13511!
```
Output is
```
269146071053904674084357808139[49888 digits]000000000000000000000000000000
```
---
Not sure if it quite fits specs (particularly the output format one), but I can hit even larger:
```
bfloat(99999999!)
```
Output is
```
9.9046265792229937372808210723818b8565705513
```
That's roughly 108,565,705,514 which is *significantly* larger than most of the top answers and was computed in about 2 seconds. The `bfloat` function gives [arbitrary precision](http://maxima.sourceforge.net/docs/intromax/intromax.html).
[Answer]
# Haskell, 4950
Aww man, that's not a lot! 10 characters start after the dollar sign.
```
main=putStr.show$sum[1..99]
```
[Answer]
## Mathematica, 2.174188391646043\*10^20686623745
```
$MaxNumber
```
Ten characters exactly.
[Answer]
# Casio fx-350 ES PLUS, approx. 9.999882753E99
Do calculators count?
![](https://i.stack.imgur.com/0B0tI.jpg)
At `70!` the calculator throws error because apparently it has a number range limit `-1E100 ~ 1E100`
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 1.79769e308 (float64) or 9.99999e6144 (decimal128), 3 bytes
This is the minimum reduction of an empty list:
```
⌊/⍬
```
`‚åä`‚ÄÉminimum
`/`‚ÄÉreduction
`⍬` empty list
When reducing an empty list, APL will return the [identity element](https://en.wikipedia.org/wiki/Identity_element) of the function used (if known). For minimum reduction of a system without infinities (e.g. ISO APL, to which Dyalog APL adheres), the identity element for minimum is the largest representable number:
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jni79R71rQJz/aQA "APL (Dyalog Unicode) – Try It Online") (IEEE 754 64-bit floating-point)
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmXI862tP@P@rp0n/Uu@Y/kPM/DQA "APL (Dyalog Unicode) – Try It Online") (IEEE 754-2008 128-bit decimal floating-point)
[Answer]
# Binary Lambda Calculus, \$ f\_{\omega+2} (2)\$, 9.75 bytes
This program outputs a number larger than Graham's Number while using 78 bits, which is 9.75 bytes, within the 10-byte budget given to me:
```
010101000001110011101000000101011000000101101101011010000110100000011100111010
```
If you prefer an ASCII display of the binary number, here it is:
```
TÔøΩÔøΩmhh:
```
(Inspired, but not copied, by the entry mentioned [here](https://codegolf.stackexchange.com/questions/83873/theoretically-output-grahams-number))
## How it works:
This Binary Lambda Calculus expression encodes the following expression below:
```
(\f x.f (f x))(\f n.n (\g m.m g m) f n)(\x.x x)(\f x.f (f x))
```
This Lambda Calculus expression uses [Church Numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals). Church Numerals are generally considered to be the standard representation of natural numbers. What makes Church Numerals powerful is that they are defined using recursion:
`[n] f m = f (f (f (...(f m)...)))` with n f's.
What this means is that if we have a function \$f\$ and a natural number \$n\$, we can simply concatenate them into \$n f\$ to make a much faster function. You can read the article I linked above if you want to see how Church Numerals can be encoded in Lambda Calculus.
### Exponentiation
What is more, Church Numerals can even act on themselves! `n m` represents \$m^n\$ using exponentiation!
Example: \$2^3\$
(Here, we will apply that to the function f n, to show the true power of recursion)
* `3 2 f n`
* `2 (2 (2 f)) n`
* `(2 (2 f)) ((2 (2 f)) n)`
* `(2 f) ((2 f) ((2 f) ((2 f) n)))`
* `f (f (f (f (f (f (f (f n)))))))`
* `= 8 f n`
We can create a function that captures the true power of exponentiation!
```
\x.x x
```
When applied to a Church Numeral \$n\$, it returns \$n^n\$. Viola! Let's call our exponential combinator \$E\$, such that:
```
E = (\x.x x)
```
### Recursion
In order to get beyond exponentiation, we must recurse our \$E\$ combinator. Remember how popping a number before a function recurses it? Well, we can do this with the E combinator, provided that it is a unary function. Define the \$R\$ combinator as followed:
```
R = (\g. \m.m g m)
```
Here, how it works is that for a function \$f\$ applied to an number \$n\$, \$Rfn\$ reduces down to \$nfn\$. This is awesome, because Church numerals naturally recurse functions, meaning \$nfn\$ reduces down to \$f (f (f ...(f n)...))\$.
What if we let our function be our exponential combinator \$E\$? \$REn\$ grows tetrationally. But there is no reason to stop here. We can merge \$R\$ and \$E\$ into a single combinator, \$(RE)\$, and recurse that to have \$R(RE)n\$. This grows pentationally.
We can have \$R(R(RE))n\$, \$R(R(R(RE)))n\$, and so on. But notice how the \$R\$ combinator is being recursed over \$E\$. Well, this is where Church Numeral Recursion comes back into play.
### Super-Recursion
Define a new combinator, \$S\$, as the following:
```
S = (\f n.n R f n) = (\f n.n (\g m.m g m) f n)
```
Cool, now one thing that makes this powerful is that while the \$R\$ combinator recurses over a function \$f\$, the \$S\$ combinator repeatedly applies the \$R\$ combinator to a function \$f\$. Consider this:
$$SE3$$
The first thing that \$S\$ combinator is going to do is to reduce to \$nR\$ where n is the number after the \$E\$. So our reduction will look like this:
$$3RE3$$
The Church Numeral recursion applies on \$R\$ over \$E\$, thus nesting \$R\$ three times, thus giving us this:
$$R(R(RE))3$$
As we seen above, each \$R\$ increases the size of the number considerably, and now the \$S\$ combinator recurses over the \$R\$ combinator! The combinator (SE) grows at \$f\_{\omega}\$ in the Fast Growing Hierarchy, about the limit of the Ackermann Function. We can take this a step forward.
* \$R(SE)\$ recurses over the (SE) combinator, growth rate similar to Graham's Number
* \$R(R(SE))\$ has \$f\_{\omega+2}\$ growth in the fast growing hierarchy
* \$S(SE)\$ has \$f\_{\omega2}\$ growth in the fast growing hierarchy
* \$S(S(SE))\$ has \$f\_{\omega3}\$ growth in the fast growing hierarchy
Similar to how inserting a church numeral before \$R\$ can recurse the recursion function over \$E\$, inserting a church numeral before \$S\$ recurse the super-recursion function over \$E\$. For example, \$2SE\$ = \$S(SE)\$.
## The Number:
The number is \$2SE2\$ using Church Numerals and the combinators defined above. This translates to about \$f\_{\omega+2} (2)\$ in the Fast Growing Hierarchy, which is greater than Graham's Number. Graham's Number is far greater than even \$Ack(9!,9!)\$ in Wolfram-Alpha. Expanding \$2SE2\$ will yield:
```
(\f x.f (f x))(\f n.n (\g m.m g m) f n)(\x.x x)(\f x.f (f x))
```
The lambda expression for \$2\$ is `(\f x.f (f x))`, as you can see it is a Church Numeral. By decoding this Lambda Calculus Expression in [Binary Lambda Calculus](https://esolangs.org/wiki/Binary_lambda_calculus), one could expect a 9.75-byte expression:
```
010101000001110011101000000101011000000101101101011010000110100000011100111010
```
We proved that we can beat Graham's Number in 10 bytes! Ridiculous?
[Answer]
# Python shell, 649539 999890001
Beats Haskell, not really a serious answer.
```
99999*9999
```
[Answer]
I'd rather post this as a comment above, but apparently I can't since I'm a noob.
Python:
`9<<(2<<29)`
I'd go with a larger bit shift, but Python seems to want the right operand of a shift to be a non-long integer. I think this gets closer to the theoretical max:
`9<<(7<<27)`
The only problem with these is that they might not satisfy rule 5.
[Answer]
## Befunge-93 (1,853,020,188,851,841)
Glad nobody has done Befunge yet (it's my niche), but dammit I can't find any clever trick to increase the number.
```
9:*:*:*:*.
```
So it's 9^16.
```
:*
```
Basically multiplies the value at the top of the stack with itself. So, value at the top of the stack goes:
```
9
81
6561
43046721
1853020188851841
```
and
```
.
```
Outputs the final value.
I would be interested to see if anybody has any better ideas.
[Answer]
## At least Python 3.5.0 (64-bit), more than 10^242944768872896860
```
print("{:x}".format( 9<<(7<<60) ))
```
In an ideal world, this would be `9<<(1<<63)-1`, but there aren't enough bytes for that. This number is so big that it requires almost 1 EiB of memory to hold it, which is a little bit more than I have on my computer. Luckily, you only need to use around 0.2% of the world's storage space as swap to hold it. The value in binary is `1001` followed by 8070450532247928832 zeros.
If Python comes out for 128-bit machines, the maximum would be `9<<(9<<99)`, which requires less than 1 MiYiB of memory. This is good, because you'd have enough addressable space left to store the Python interpreter and the operating system.
[Answer]
# Matlab (1.7977e+308)
Matlab stores the value of the largest (double-precision) floating-point number in a variable called `realmax`. Invoking it in the command window (or at the command line) prints its value:
```
>> realmax
ans =
1.7977e+308
```
[Answer]
# Python, ca. 1.26e1388
```
9<<(9<<9L)
```
Gives:
>
> 126026689735396303510997749074166929355794746000200933374690887068497279540873057344588851620847941756785436041299246554387020554314993586209922882758661017328592694996553929727854519472712351667110666886882465827559219102188617052626543482184096111723688960246772278895906137468458526847698371976335253039032584064081316325315024075215490091797774136739726784527496550151562519394683964055278594282441271759517280448036277054137000457520739972045586784011500204742714066662771580606558510783929300569401828194357569630085253502717648498118383356859371345327180116960300442655802073660515692068448059163472438726337412639721611668963365329274524683795898803515844109273846119396045513151325096835254352967440214290024900894106148249792936857620252669314267990625341054382109413982209048217613474462366099211988610838771890047771108303025697073942786800963584597671865634957073868371020540520001351340594968828107972114104065730887195267530118107925564666923847891177478488560095588773415349153603883278280369727904581288187557648454461776700257309873313090202541988023337650601111667962042284633452143391122583377206859791047448706336804001357517229485133041918063698840034398827807588137953763403631303885997729562636716061913967514574759718572657335136386433456038688663246414030999145140712475929114601257259572549175515657577056590262761777844800736563321827756835035190363747258466304L
>
>
>
[Answer]
# Perl, non competing
I'm using this to highlight a little know corner of perl.
Perl can't really compete on this one because it doesn't have builtin bignums (of course you could load a bignum library).
But what everybody knows isn't completely true. One core function actually can handle big numbers.
The `pack` format `w` can actually convert any size natural number between base `10` and base `128`. The base 128 integer is however represented as string bytes. The bitstring `xxxxxxxyyyyyyyzzzzzzz` become the bytes: `1xxxxxxx 1yyyyyyy 0zzzzzzz` (every byte starts with 1 except the last one). And you can convert such a string to base 10 with unpack. So you can write code like:
```
unpack w,~A x 4**4 .A
```
which gives:
```
17440148077784539048602210552864286760481312243331966651657423831944908597692986131110771184688683631223604950868378426010091037391551287028966465246275171764867964902846884403624214574779667949236313638077978794791039372380746518407204456880869394123452212674801443116750853569815557532270825838757922217314748231826241930826238846175896997055564919425918463307658663171965135057749089077388054942032051553760309927468850847772989423963904144861205988704398838295854027686335454023567793114837657233481456867922127891951274737700618284015425
```
You can replace the `4**4` by larger values until you feel it takes too long or uses too much memory.
Unfortunately this is way too long for the limit of this challenge, and you can argue that the base 10 result is converted to a string before it becomes the result so the expression doesn't really produce a number. But internally perl really does the needed arithmetic to convert the input to base 10 which I always considered rather neat.
[Answer]
# TI-36 (not 84, 36), 10 bytes, approx. 9.999985426E99
Older calculators can be programmed to an extent as well ;)
`69!58.4376`
This is very close to the maximum range a TI calculator can display: `-1E100<x<1E100`
[![enter image description here](https://i.stack.imgur.com/FaFPp.jpg)](https://i.stack.imgur.com/FaFPp.jpg)
[Answer]
## [><>](http://esolangs.org/wiki/Fish)
**2020 update:**
`'*:*l1=?n!`
[Try it online!](https://tio.run/##S8sszvj/X13LSivH0NY@T/H/fwA)
A nice, big number.
6607775919524790651439701166707789489378797865523309469653600804966653717124420234900643695716633983263105744751733811265946551350757473520290996592227365993351117075631863250858664418726460620430636874466736708735091515674858617262672061392356105274688381926671523379031815127376998794734801639561117309008230181917173237247958670364395979998445068443549603086925428413456037483510188036968643022754136876546302694036337733250775972540791054488317803988268522700511802405629821189614545680714572177873101991977461377780062066275613653646526353437038254323542049537486740164431723433218814788820554530926749282165106713414138827765731299184793201063834591836604608194080942136186867241173559749340134123556348756219648917627921044482452298279885527390296021299809895208344965720017693561708427752229404713795765501476321809083160697802384075712539404128882728723305116462257211512254983151160419880169748505483542215949682009001146040637299350914438311533945478015790682139849329365319957805121129755402607972548916020445921204515251014341335241310585757251648664383763145215969276240907124147926204015695626240000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
---
## ~~3147440830160257032480100000000~~ 319626579315078487616775634918212890625
**Edit:**
Seems like I am allowed to exclude the characters needed for printing, the `n` in this case, so here is an updated version:
```
':*:*:*:*nÿ
```
**Original answer:**
```
'*:*:*:*n;
```
Here, `'` activates stringmode, and pushes all the following characters to the stack, before wrapping and exiting stringmode. Then it does a multiply-and-copy chain, printing the number, and exits. Of interest here is the ascii value of `n` 110, and `;` 59.
However, if we allow it to terminate with an error, we can abuse the fact that the official interpreter supports Unicode. The title of the question says bytes, but the text says characters, so the following program is just for the fun of it.
```
'*:*:*:*nüøø
```
Outputting 1867215243681462552708446358738678532523702556144100000000
Alternatively, to stick to bytes, `ÿ` at the end gives us 383233022803952503175039062500000000, and that is still nice.
(New "for fun" program `':*:*:*:*nüøø` prints 7587624076546380447593767884781979512738274729546264306618287972087303430335365121)
[Answer]
# ARM Thumb, multiword integer, ~~~1.157921e+77~~ ~4.973232e+86
Machine code:
```
2306 1fd9 000a b407 b407
```
Assembly
```
.globl main
.thumb
.thumb_func
main:
push {r4, lr}
// start number generation code
movs r3, #6 // 2
subs r1, r3, #7 // 4
movs r2, r1 // 6
push {r1, r2, r3} // 8
push {r1, r2, r3} // 10
// end number generation code
// now printf everything
adr r0, .Lprintf_str
bl printf
pop {r1, r2, r3}
pop {r1, r2, r3, r4, pc}
// print 32 bits at a time
.Lprintf_str:
.asciz "%#08x%08x%08x%08x%08x%08x%08x%08x%08x\n"
```
[Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/471966547#L435)
Assembles a 288-bit big endian unsigned integer (with little endian words) with the high 96 bits in `r1-r3` and the low 192 bits on the stack.
The number is, in hex, `0xffffffffffffffff00000006ffffffffffffffff00000006ffffffffffffffff00000006`, or in base 10, `497323236409786642128422301523609912453495901056838330362914156057471888398396751347718`.
# Explanation
You may be wondering why I chose `6` and `7`. The reason is because of the limitations of narrow instructions.
[`movs Rd, #imm` can only encode an 8-bit immediate from `0-255`](https://www.keil.com/support/man/docs/armasm/armasm_dom1361289878994.htm). No negatives allowed, which would make this almost *too* easy.
[`subs Rd, Rn, #imm` can only encode a 3-bit immediate from `0-7`](https://www.keil.com/support/man/docs/armasm/armasm_dom1361289908389.htm). I can only subtract `0-255` if I use the same destination register, which isn't very helpful.
So therefore, since `r1` will be more significant, we put `6` in `r3`, then subtract `7` to get `-1`, or `0xFFFFFFFF`, in `r1`.
```
movs r3, #6 // 2
subs r1, r3, #7 // 4
```
Now, time for things to get super dumb.
First, we duplicate `0xFFFFFFFF` to `r2` using `movs`.
```
movs r2, r1 // 6
```
Then, we (ab)use ARM's `push` instruction. ARM's `push` instruction (as well as its sibling `stm`) can push multiple registers at once to the stack, effectively doing a block copy.
We abuse this to copy `r1`, `r2`, and `r3` to the stack twice, tripling the width of the integer.
You could say this is some form of exponentiation, but all I'm doing is pushing to the stack. Nothing suspicious here. üòá
```
push {r1, r2, r3} // 8
push {r1, r2, r3} // 10
```
Now, it looks like this:
```
r1: 0xFFFFFFFF r2: 0xFFFFFFFF
r3: 0x00000006
sp+0: 0xFFFFFFFF sp+4: 0xFFFFFFFF
sp+8: 0x00000006 sp+12: 0xFFFFFFFF
sp+16: 0xFFFFFFFF sp+20: 0x00000006
```
# ARM Thumb-2, softfloat, 1.797693e+308
Machine code:
```
f248 0310 041b 17da 43db
```
Assembly:
```
.thumb
.globl main
.thumb_func
main:
push {r4, lr}
// Begin number generation code
movw r3, #0x8010 // 4
lsls r3, r3, #16 // 6
asrs r2, r3, #31 // 8
mvns r3, r3 // 10
// End number generation code
adr r0, .printf_str
bl printf
pop {r4, pc}
.align 4
.printf_str:
.asciz "%f\n"
```
[Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/471966548#L421)
Creates the 64-bit constant `0x7fefffffffffffff`, which is `DBL_MAX`, in `r2-r3` (since the AAPCS aligns 64-bit integers to even registers)
Specifically, `179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000`
We do this by first putting `~(*(long long*)&DBL_MAX) >> 48` in `r3`, shifting left by 16, doing an arithmetic shift right into `r2` to make it `0xFFFFFFFF`, then do a one's complement to get `r3` to `0x7fefffff`.
# ARM Thumb-2, (non-competing), softfloat + printf merging, 2.148532e+319
Machine code:
```
f248 0110 0409 43ca 0013
```
Assembly:
```
.thumb
.globl main
.thumb_func
main:
push {r4, lr}
// Begin number generation code
movw r1, #0x8010 // 4
lsls r1, r1, #16 // 6
mvns r2, r1 // 8
movs r3, r2 // 10
// End number generation code
adr r0, .printf_str
bl printf
pop {r4, pc}
// Combine 0x80100000u (2148532224) with the same double we had before.
.printf_str:
.asciz "%u%f\n"
```
[Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/471967696#L424)
This is obviously cheating, as it is actually generating an unsigned integer and a double and printing them together, but decided to add it for the lulz. üòÇ
It basically does this:
```
uint32_t r1 = (~0x7fef) & 0xffff;
// 0x80100000
r1 <<= 16;
uint32_t r2 = ~r1;
uint32_t r3 = r2;
// 0x7fefffff7fefffff
uint64_t r2r3 = r2 | ((uint64_t)r3 << 32);
double d = *(double*)&r2r3;
printf("%u%f\n", r1, d);
```
] |
[Question]
[
Your task is to write a program that outputs the *exact* string `Programming Puzzles` (trailing newline optional), but when all spaces, tabs, and newlines are removed it outputs `Code Golf` (trailing newline optional.)
Your byte count is the count of the first program, with spaces still there.
# Notes
* The spaces in `Code Golf` *and* `Programming Puzzles` will be removed as part of the removal, so plan accordingly.
* In encodings where 0x09, 0x0A and 0x20 aren't tabs, newlines or spaces respectively, those chars will be removed.
* If your code is
```
42 $@ rw$
@42
```
then that must output `Programming Puzzles`. Also, in the same language,
```
42$@rw$@42
```
must output `Code Golf`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! Good luck!
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
print["Code\40Golf","Programming Puzzles"][" ">""]
```
[Try it online!](https://tio.run/nexus/python2#@19QlJlXEq3knJ@SGmNi4J6fk6akoxRQlJ9elJibm5mXrhBQWlWVk1qsFButpKBkp6QU@/8/AA "Python 2 – TIO Nexus")
With all spaces removed:
```
print["Code\40Golf","ProgrammingPuzzles"]["">""]
```
[Try that online!](https://tio.run/nexus/python2#@19QlJlXEq3knJ@SGmNi4J6fk6akoxRQlJ9elJibm5mXHlBaVZWTWqwUG62kZKekFPv/PwA)
Thanks to Stephen S for 3 bytes, and Erik the Outgolfer for 1
[Answer]
# [Python 2](https://docs.python.org/2/), ~~48~~ 47 bytes
-1 byte thanks to Erik the Outgolfer
```
print' 'and'Programming Puzzles'or'Code\40Golf'
```
[Try it online!](https://tio.run/nexus/python2#@19QlJlXoq6gnpiXoh5QlJ9elJibm5mXrhBQWlWVk1qsnl@k7pyfkhpjYuCen5Om/v8/AA "Python 2 – TIO Nexus")
```
print''and'ProgrammingPuzzles'or'Code\40Golf'
```
[Try it online!](https://tio.run/nexus/python2#@19QlJlXoq6emJeiHlCUn16UmJubmZceUFpVlZNarJ5fpO6cn5IaY2Lgnp@Tpv7/PwA "Python 2 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
“Ñ1ɦ+£)G“½ċṭ6 Ỵ»Ṃ
```
[Try it online!](https://tio.run/nexus/jelly#@/@oYc7hiYYnl2kfWqzpDuQc2nuk@@HOtWYKD3dvObT74c6m//8B "Jelly – TIO Nexus")
### How it works
As in the other Jelly answer, `Ñ1ɦ+£)G` and `½ċṭ6Ỵ` encode the strings **Programming Puzzles** and **Code Golf**. `“` begins a string literal and separates one string form another, while `»` selects the kind of literal (dictionary-based compression), so this yields
```
["Programming Puzzles", "Code Golf"]
```
`Ṃ` then takes the minimum, yielding **Code Golf**.
However, by adding a space between `½ċṭ6` and `Ỵ`, we get a completely different second string, and the literal evaluates to
```
["Programming Puzzles", "caird coinheringaahing"]
```
Since **caird coinheringaahing** is lexicographically larger than **Programming Puzzles**, `Ṃ` selects the first string instead.
[Answer]
# C, ~~64~~ ~~62~~ ~~53~~ 52 bytes
```
f(){puts(*" "?"Programming Puzzles":"Code\40Golf");}
```
[Try it Online!](https://tio.run/nexus/c-gcc#@5@moVldUFpSrKGlpKBkrxRQlJ9elJibm5mXrhBQWlWVk1qsZKXknJ@SGmNi4J6fk6akaV37PzOvRCE3MTMPqBeoHygAAA)
Uses the fact that C strings end with a null character
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
”ƒËŠˆ”" "v”–±ÇÀ
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oYe6xSYe7jy443QZkKikolQGpRw2TD2083H644f9/AA "05AB1E – TIO Nexus")
**Explanation**
```
”ƒËŠˆ” # push "Code Golf"
" "v # for each character in the string " " do
”–±ÇÀ # push "Programming Puzzles"
# implicitly output top of stack
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
“½ċṭ6Ỵ»ḷ
“Ñ1ɦ+£)G»
```
[Try it online!](https://tio.run/nexus/jelly#ASYA2f//4oCcwr3Ei@G5rTbhu7TCu@G4twrigJzDkTHJpivCoylHwrv//w "Jelly – TIO Nexus")
## Explanation
In the program as written, the first line is a helper function that's never run. The second line (the last in the program) is the main program, and is the compressed representation of the string `"Programming Puzzles"` (which is then printed implicitly).
If you remove the newline, the whole thing becomes one large program. `“½ċṭ6Ỵ»` is the compressed representation of the string `"Code Golf"`. `ḷ` evaluates but ignores its right hand argument, leaving the same value as before it ran; it can be used to evaluate functions for their side effects (something I've done before now), but it can also be used, as here, to effectively comment out code.
Interestingly, the actual logic here is shorter than the 05AB1E entry, but the code as a whole comes out longer because the string compressor is less good at compressing these particular strings.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 38 bytes
```
" ""Programming Puzzles""Dpef!Hpmg":(?
```
[Try it online!](https://tio.run/nexus/cjam#@6@koKQUUJSfXpSYm5uZl64QUFpVlZNarKTkUpCapuhRkJuuZKVh//8/AA "CJam – TIO Nexus") or [with spaces removed](https://tio.run/nexus/cjam#@6@kpBRQlJ9elJibm5mXrhBQWlWVk1qspORSkJqm6FGQm65kpWH//z8A)
**Explanation**
```
" " e# Push this string.
"Programming Puzzles" e# Push "Programming Puzzles".
"Dpef!Hpmg":( e# Push "Dpef!Hpmg" and decrement each char, giving "Code Golf".
? e# If the first string is true (non-empty) return the second string,
e# else return the third.
```
Whether spaces are in the program or not determines if the first string is truthy or falsy.
[Answer]
# Javascript, ~~46~~ ~~43~~ 42 Bytes
```
x=>" "?"Programming Puzzles":"Code\40Golf"
```
```
console.log((x=>" "?"Programming Puzzles":"Code\40Golf")())
console.log((x=>""?"ProgrammingPuzzles":"Code\40Golf")())
```
[Answer]
## Haskell, 48 bytes
```
a _="Programming Puzzles";a4="Code\32Golf";f=a 4
a_="ProgrammingPuzzles";a4="Code\32Golf";f=a4
```
Defines function `f` which returns the corresponding string.
For reference, the old version is:
### Haskell, 49/47 bytes
```
f""="Code\32Golf";f(_)="Programming Puzzles";f" "
```
with spaces removed
```
f""="Code\32Golf";f(_)="ProgrammingPuzzles";f""
```
Two simple pattern matches. `(_)` matches all patterns. You can improve the without-spaces version by one byte by defining the second pattern as `f" "=`/`f""=`, but this gives a "Pattern match is redundant" warning.
Alternative solution with the same byte count:
```
last$"Code\32Golf":["Programming Puzzles"|" ">""]
last$"Code\32Golf":["ProgrammingPuzzles"|"">""]
```
[Answer]
## Wolfram language, 62 bytes
```
"Programming Puzzles"[ToExpression@"\"Code\\.20Golf\""][[0 1]]
```
The space in `[[0 1]]` is implicit multiplication, so this is equivalent to `[[0]]`. Without a space, `01` is just `1`. The 0th and 1st parts of this expression are the strings we want.
Another solution of questionable validity (44 bytes, 2 saved by Kelly Lowder):
```
"Programming Puzzles"["Code\.20Golf"][[0 1]]
```
The `\.20` gets replaced by a space immediately when typed into a Mathematica environment, so it's not clear if it gets removed along with the other spaces…
[Answer]
## Excel - 56 Bytes
```
=IF(""=" ","Code"&CHAR(32)&"Golf","Programming Puzzles")
```
Very similar to most of the other answers... nothing fancy here.
[Answer]
# [Ohm](https://github.com/MiningPotatoes/Ohm), ~~33~~ 32 bytes
Uses CP437 encoding.
```
▀Bn¬i≈╣Ü╝Rb╡°╧S½uÇ▀
▀4>~H├MS░l╬δ
```
[Try it online!](https://tio.run/nexus/ohm#AT8AwP//4paAQm7CrGniiYjilaPDnOKVnVJi4pWhwrDiladTwr11w4filoAK4paAND5@SOKUnE1T4paRbOKVrM60//8 "Ohm – TIO Nexus") or [try without whitespace](https://tio.run/nexus/ohm#AT4Awf//4paAQm7CrGniiYjilaPDnOKVnVJi4pWhwrDiladTwr11w4filoDiloA0Pn5I4pScTVPilpFs4pWszrT//w)
### Explanation
**With whitespace:**
```
▀Bn¬i≈╣Ü╝Rb╡°╧S½uÇ▀ Main wire
▀Bn¬i≈╣Ü╝Rb╡°╧S½uÇ▀ Push "Programming Puzzles" (compressed string)
Implicitly output the top stack element
▀4>~H├MS░l╬δ Helper wire (never called)
```
**Without whitespace:**
```
▀Bn¬i≈╣Ü╝Rb╡°╧S½uÇ▀▀4>~H├MS░l╬δ Main wire
▀Bn¬i≈╣Ü╝Rb╡°╧S½uÇ▀ Push "Programming Puzzles" (compressed string)
▀4>~H├MS░l╬δ Push "Code Golf" (compressed string)
Implicitly output top stack element
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 29 bytes
With spaces:
```
`Co¸{S}Golf`r `PžgŸmÚÁ Puzz¤s
```
[Try it online!](https://tio.run/nexus/japt#@5/gnH9oR3VwrXt@TlpCkUJCwKF56Yfm5x6edbhRIaC0qurQkuL//wE "Japt – TIO Nexus")
Without spaces:
```
`Co¸{S}Golf`r`PžgŸmÚÁPuzz¤s
```
[Try it online!](https://tio.run/nexus/japt#@5/gnH9oR3VwrXt@TlpCUULAoXnph@bnHp51uDGgtKrq0JLi//8B "Japt – TIO Nexus")
---
This takes advantage of the fact that in Japt, a space closes a method call. With spaces, the code is roughly equivalent to this JavaScript code:
```
("Code"+(S)+"Golf").r(),"Programming Puzzles"
```
This is evaluated as JavaScript, and the result is sent to STDOUT. Since the last expression is `"Programming Puzzles"`, that string is printed.
Without spaces, the code is roughly equivalent to:
```
("Code"+(S)+"Golf").r("ProgrammingPuzzles")
```
(If you haven't figured it out by now, the `S` variable is a single space.) The `.r()` method on a string, if given one argument, removes all instances of that argument from the string. Since `"Code Golf"` does not contain `"ProgrammingPuzzles"`, it returns `"Code Golf"` unchanged, which is then sent to STDOUT.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes
```
" "Ṣ∧"Programming Puzzles"w|"Code"wṢw"Golf"w
```
[Try it online!](https://tio.run/nexus/brachylog2#@6@koPRw56JHHcuVAory04sSc3Mz89IVAkqrqnJSi5XKa5Sc81NSlcqBasqV3PNz0pTK////DwA "Brachylog – TIO Nexus")
### Explanation
```
" "Ṣ If " " = Ṣ (which is itself " ")
∧"Programming Puzzles"w Write "Programming Puzzles"
| Else
"Code"w Write "Code"
Ṣw Write " "
"Golf"w Write "Golf"
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 44 bytes
```
/"floG!"t"edoC"#
/"selzzuP gnimmargorP"d&o@
```
[Try it online!](https://tio.run/nexus/alice#@6@vlJaT766oVKKUmpLvrKTMpaCvVJyaU1VVGqCQnpeZm5tYlJ5fFKCUopbv8P8/AA "Alice – TIO Nexus")
Without whitespace:
```
/"floG!"t"edoC"#/"selzzuPgnimmargorP"d&o@
```
[Try it online!](https://tio.run/nexus/alice#@6@vlJaT766oVKKUmpLvrKSsr1ScmlNVVRqQnpeZm5tYlJ5fFKCUopbv8P8/AA "Alice – TIO Nexus")
### Explanation
In the first program, the two mirrors `/` redirect the instruction pointer onto the second line. `"selzzuP gnimmargorP"` pushes the required code points in revere order, `d` pushes the stack depth and `&o` prints that many bytes. `@` terminates the program.
Without the whitespace, the program is all on a single line. In that case, the instruction pointer can't move in Ordinal mode, so the `/` effectively become no-ops (technically, the IP simply doesn't move for one step, the same `/` gets executed again, and the IP reflects back to Cardinal mode). So if we drop those from the program, it looks like this:
```
"floG!"t"edoC"#"selzzuPgnimmargorP"d&o@
```
To include the space in `Code Golf`, we use an exclamation mark instead and decrement it with `t`. After we've got all the code points on the stack, `#` skips the next command, which is the entire second string. `d&o` then prints the stack again, and `@` terminates the program.
[Answer]
# PHP, 44 Bytes
ternary operator
```
<?=" "?"Programming Puzzles":"Code\x20Golf";
```
## PHP, 51 Bytes
comment
```
<?=/** /"Code\x20Golf"/*/"Programming Puzzles"/**/;
```
## PHP, 57 Bytes
array switch
```
<?=["Code\x20Golf","Programming Puzzles"][(ord("
")/10)];
```
[Answer]
# Common Lisp (SBCL), 52 bytes
```
(format`,t"~[Programming Puzzles~;Code~@TGolf~]"0 1)
```
Prints `Programming Puzzles`
```
(format`,t"~[ProgrammingPuzzles~;Code~@TGolf~]"01)
```
Prints `Code Golf`
Ungolfed:
```
(format t "~[Programming Puzzles~;Code Golf~]" 0 1)
```
Explaination:
The trick basically comes from how `#'format` works in Common Lisp.
In CL, most whitespace can be omitted provided that there is no ambiguity about where tokens start or end. The first trick was separating the `format` and `t` symbols. I had to unambiguously end the `format` symbol without changing how `t` was interpreted. Luckily, ` in CL ends the preceding token before it gets processed, and `,` cancels the effect of ` (` is used to implement templating, where the next expression following it gets "quoted", but any sub-expression prefixed with a `,` is evaluated and the result included in the template, so `, is nearly a no-op).
The third argument to `format` is the template string. `format` is similar to printf in C, but has much more powerful formatting directives and use ~ to indicate them instead of %. ~[ and ~] allow you to select between multiple options for printing, with ~; separating them. An additional argument is supplied to format- the numeric index of which one you want printed. In order to ensure that the " " in Code Golf survives, I used the tabulation directive ~T, which is used to insert whitespace, generally to align text into columns. ~@T is a variation which just inserts a given number of spaces, defaulting to 1.
Finally, there are two arguments to format- 0 and 1. Before whitespace is removed, the 0 is used by ~[~;~] to select "Programming Puzzles" and the extra format argument (the 1) is dropped (I'm not sure how standard dropping extra format arguments is, but this works on Steel Bank Common Lisp). After whitespace is removed, there is only one argument (01) which selects "Code Golf" instead.
[Answer]
# [Perl 5](https://www.perl.org/), ~~43~~ 41 bytes
```
say" "?"Programming Puzzles":Code.$".Golf
```
[Try it online!](https://tio.run/##bY7NCoJAFIX3PsVlEtqU1sKNEi0iWuYDDNSQNxVm7gw6o2j07Kb9QFDr853zHYOVjAZXI0TBar1KYKYJLlopQRnIknABrXYyg8oRtKUt4GzGCiz3Z88/beZDLToGbMvSSueVUKqkHFLX9xJrFu90hoHPgoOW12GeeCMMHzIG/3a6H501zsYs8bARctRPHlsgmBfldSFwyykMsylEpRuEtigt1kZc8LXI6b35fKid/SJiTpOH01/TLz88AA "Perl 5 – Try It Online")
Uses the fact that `' '` is true in perl and `''` is false. The `$"` variable is set to a space by default.
Thanks to @NahuelFouilleul for removing two bytes.
[Answer]
# R, 50 bytes
I think this is the same as [this Javascript answer](https://codegolf.stackexchange.com/a/117953), and basically the same idea as all the others.
```
`if`(' '=='','Code\x20Golf','Programming Puzzles')
```
[Answer]
# Pyth, 37 bytes
```
?" ""Programming Puzzles""Code\40Golf
```
[Try it here.](//pyth.herokuapp.com?code=?%22+%22%22Programming+Puzzles%22%22Code%5C40Golf)
```
?"""ProgrammingPuzzles""Code\40Golf
```
[Try it here.](//pyth.herokuapp.com?code=?%22%22%22ProgrammingPuzzles%22%22Code%5C40Golf)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 42 bytes
With whitespace
```
\"floG"48*"edoC"
/>o<"Programming Puzzles"
```
[Try it online!](https://tio.run/nexus/fish#@x@jlJaT765kYqGllJqS76zEpW@Xb6MUUJSfXpSYm5uZl64QUFpVlZNarPT/PwA "><> – TIO Nexus")
Without whitespace
```
\"floG"48*"edoC"/>o<"ProgrammingPuzzles"
```
[Try it online!](https://tio.run/nexus/fish#@x@jlJaT765kYqGllJqS76ykb5dvoxRQlJ9elJibm5mXHlBaVZWTWqz0/z8A "><> – TIO Nexus")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 50
```
[pq]sm[Programming Puzzles]dZ19=m[Code]n32P[Golf]p
```
[Try it online](https://tio.run/nexus/bash#S0mOT85PSbVV@h9dUBhbnBsdUJSfXpSYm5uZl64QUFpVlZNaHJsSZWhpmxvtDFQYm2dsFBDtnp@TFlvwX4krNTkjX0FJJQViipJCjUJKMkywGiqqr6@gXwuR@g8A).
`[ ]` defines a string - `Z` measures its length. If the length is 19 then it contains a space and the macro stored in the m register is called, which prints `Programming Puzzles` and quits. Otherwise `Code Golf` is printed.
[Answer]
# C# ~~88~~ ~~81~~ ~~70~~ 63 bytes
```
Func<string>@a=()=>" "==""?"Code\x20Golf":"Programming Puzzles";
```
With whitespace stripped:
```
Func<string>@a=()=>""==""?"Code\x20Golf":"ProgrammingPuzzles";
```
Thanks to BrianJ for showing me how to have no space between a method return type and the method name, PeterTaylor for saving ~~7~~ 18 bytes, and Patrick Huizinga for saving 7 bytes.
Same method as everyone else really, ~~technically this could be considered invalid because the method doesn't specify a return type for the method, but there *has* to be whitespace between the return type and the method name.~~
[Answer]
# Java 8, ~~74~~ ~~50~~ 48 bytes
```
()=>" "==""?"Code\040Golf":"Programming Puzzles"
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~47~~ 45 bytes
```
! v"floG!"1-"edoC"!
o<>"selzzuP gnimmargorP">
```
[Try it online!](https://tio.run/nexus/fish#@6@oUKaUlpPvrqhkqKuUmpLvrKTIlW9jp1ScmlNVVRqgkJ6XmZubWJSeXxSgZPf/PwA "><> – TIO Nexus")
*Thanks to [randomra](/u/7311) for -2 (clever two `!`s so that I can use only one `>o<`.)*
The code shouts "Flog! Flog! Flog!" and resembes a fish.
[Answer]
# [Befunge](https://esolangs.org/wiki/Befunge), 47 bytes
```
# <"floG"84*"edoC">:#,_@#" Programming Puzzles"
```
[Try it Online](https://tio.run/##S0pNK81LT/3/X1nBRiktJ99dycJESyk1Jd9Zyc5KWSfeQVlJIaAoP70oMTc3My9dIaC0qiontVjp/38A)
Without spaces it skip the first < and prints Code Golf instead
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~₄₅~~ ~~₄₁~~ 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous lambda. Takes dummy argument.
```
{'Programming Puzzles'
⊢4⌽9↑'GolfCode'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rq9YCi/PSixNzczLx0hYDSqqqc1GJ1rkddi0we9ey1fNQ2Ud09PyfNOT8lVb0WpKV3DQA "APL (Dyalog Unicode) – Try It Online")
This function is a so called "dfn" which terminates with and returns the first non-assignment, i.e. `Programming Puzzles`.
Removing all whitespace gives:
```
{'ProgrammingPuzzles'⊢4⌽9↑'GolfCode'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rq9YCi/PSixNzczLx0hYDSqqqc1GL1R12LTB717LV81DZR3T0/J805PyVVvRako3cNAA "APL (Dyalog Unicode) – Try It Online")
This takes the last nine characters of `GolfCode` thus padding with a trailing space, then cyclically rotates that 4 steps to the left. `⊢` ignores the text on its left and returns the text on its right.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~**72**~~ **68 bytes**
Had output backwards at first, thanks Draco18s, then saved 4 bytes, thanks Jo King
```
a=0;ab="Programming";a
b="Code";ad="Puzzles";a
d="Golf";print(ab,ad)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P9HWwDoxyVYpoCg/vSgxNzczL13JOpELKOKcn5IKZKYA5UqrqnJSi0HiQJ57fk6aknVBUWZeiUZikk5iiub//wA)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 32 bytes
```
" "?`PžgŸmÚÁ Puzz¤s`:`Co¸{S}Golf
```
[Try it online!](https://tio.run/nexus/japt#@6@koGSfEHBoXvqh@bmHZx1uVAgorao6tKQ4wSrBOf/QjurgWvf8nLT//wE "Japt – TIO Nexus")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 56 bytes
```
('Programming Puzzles',('Code'+[char]32+'Golf'))[!(' ')]
```
[Try it online!](https://tio.run/nexus/powershell#@6@hHlCUn16UmJubmZeuEFBaVZWTWqyuo6HunJ@Sqq4dnZyRWBRrbKSt7p6fk6auqRmtqKGuoK4Z@///17x83eTE5IxUAA "PowerShell – TIO Nexus")
Pretty basic I would say, but it gets the job done
] |
[Question]
[
This is the Collatz Conjecture (OEIS [A006577](https://oeis.org/A006577)):
* Start with an integer *n* > 1.
* Repeat the following steps:
+ If *n* is even, divide it by 2.
+ If *n* is odd, multiply it by 3 and add 1.
It is proven that for all positive integers up to *5 \* 260*, or about *5764000000000000000*, *n* will eventually become *1*.
Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach *1*.
[Relevant xkcd](http://xkcd.com/710/) :)
Rules:
* Shortest code wins.
* If a number < 2 is input, or a non-integer, or a non-number, output does not matter.
Test cases
```
2 -> 1
16 -> 4
5 -> 5
7 -> 16
```
[Answer]
# C - ~~50~~ 47 characters
Poor little C unfortunately requires an awful amount of code for basic I/O, so shorting all that down has made the UI slightly unintuitive.
```
b;main(a){return~-a?b++,main(a&1?3*a+1:a/2):b;}
```
Compile it with for example `gcc -o 1 collatz.c`. The input is in unary with space-separated digits, and you will find the answer in the exit code. An example with the number 17:
```
$> ./1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
$> echo $?
12
$>
```
[Answer]
## GolfScript, ~~24~~ ~~23~~ ~~21~~ ~~20~~ 18 chars
```
~{(}{3*).2%6\?/}/,
```
Assumes input on stdin. [Online test](http://golfscript.apphb.com/?c=O1syIDE2IDUgN117YAp%2Beyh9ezMqKS4yJTZcPy99LywKcH0v)
[Answer]
# [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN), 8 fractions (45 bytes)
$$\frac{5120}{33}, \frac{15}{11}, \frac{22}{105}, \frac{33}{560}, \frac{13}{5}, \frac{3}{2}, \frac{7}{9}, \frac{11}{7}$$
Takes input as \$3^n\$; halts at \$3 \cdot 13^m\$ for a sequence with \$m\$ iterations.
[Try it online!](https://tio.run/##DcVBCoAwDATAr@QDkm6WWPyMUMSCl1Zq3290LlNHOeYoLcJhSUmBKyBmiuRCqq9J8CdUk6ybAJojgnt@@z2v3p5YTvAD "FRACTRAN – Try It Online")
### How it works
If the current state is \$3^n \cdot 13^m\$, if \$n = 1\$, the program halts immediately; if \$n = 2k\$ is even, we have
$$\begin{multline\*}3^{2k} \cdot 13^m
\xrightarrow{\left(\frac{7}{9}\right)^k}
7^k \cdot 13^m
\xrightarrow{\frac{11}{7}}
7^{k - 1}\cdot 11 \cdot 13^m
\xrightarrow{\frac{15}{11}}
3 \cdot 5 \cdot 7^{k - 1} \cdot 13^m
\\
\xrightarrow{\left(\frac{22}{105} \cdot \frac{15}{11}\right)^{k - 1}}
2^{k - 1} \cdot 3 \cdot 5 \cdot 13^m
\xrightarrow{\frac{13}{5}}
2^{k - 1} \cdot 3 \cdot 13^{m + 1}
\xrightarrow{\left(\frac{3}{2}\right)^{k - 1}}
3^k \cdot 13^{m + 1};\end{multline\*}$$
and if \$n = 2k + 1\$ is odd, we have
$$\begin{multline\*}
3^{2k + 1} \cdot 13^m
\xrightarrow{\left(\frac{7}{9}\right)^k}
3 \cdot 7^k \cdot 13^m
\xrightarrow{\frac{11}{7}}
3 \cdot 7^{k - 1} \cdot 11 \cdot 13^m
\xrightarrow{\frac{5120}{33}}
2^{10} \cdot 5 \cdot 7^{k - 1} \cdot 13^m
\\
\xrightarrow{\left(\frac{33}{560} \cdot \frac{5120}{33}\right)^{k - 1}}
2^{6k + 4} \cdot 5 \cdot 13^m
\xrightarrow{\frac{13}{5}}
2^{6k + 4} \cdot 13^{m + 1}
\xrightarrow{\left(\frac{3}{2}\right)^{6k + 4}}
3^{6k + 4} \cdot 13^{m + 1},\end{multline\*}$$
where \$6k + 4 = 3n + 1\$.
[Answer]
## Perl 34 (+1) chars
```
$\++,$_*=$_&1?3+1/$_:.5while$_>1}{
```
Abusing `$\` for final output, as per usual. Run with the `-p` command line option, input is taken from `stdin`.
Saved one byte due to [Elias Van Ootegem](https://codegolf.stackexchange.com/posts/comments/162982?noredirect=1). Specifically, the observeration that the following two are equivalent:
```
$_=$_*3+1
$_*=3+1/$_
```
Although one byte longer, it saves two bytes by shortening `$_/2` to just `.5`.
Sample usage:
```
$ echo 176 | perl -p collatz.pl
18
```
---
## PHP 54 bytes
```
<?for(;1<$n=&$argv[1];$c++)$n=$n&1?$n*3+1:$n/2;echo$c;
```
Javascript's archnemesis for the Wooden Spoon Award seems to have fallen a bit short in this challenge. There's not a whole lot of room for creativity with this problem, though. Input is taken as a command line argument.
Sample usage:
```
$ php collatz.php 176
18
```
[Answer]
# Mathematica (35)
```
If[#>1,#0@If[OddQ@#,3#+1,#/2]+1,0]&
```
Usage:
```
If[#>1,#0[If[OddQ@#,3#+1,#/2]]+1,0]&@16
>> 4
```
[Answer]
**Java, 165, 156, 154,134,131,129,128,126** (verbose languages need some love too)
```
class a{public static void main(String[]a){for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y));}}
```
All is done inside the for
```
for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y))
```
That's freaking beautiful man. Thanks to Pater Taylor!!!, and the idea of using a for loop was stolen from ugoren
I replaced Integer for Short.
[Answer]
As I usually do, I will start the answers off with my own.
## JavaScript, ~~46~~ 44 chars (run on console)
```
for(n=prompt(),c=1;n>1;n=n%2?n*3+1:n/2,++c)c
```
[Answer]
## Python repl, 48
I'm not convinced that there isn't a shorter expression than `n=3*n+1;n/=1+n%2*5;`. I probably found a dozen different expressions of all the same length...
```
i=0
n=input()
while~-n:n=3*n+1;n/=1+n%2*5;i+=1
i
```
edit: I've found another solution that will never contend, but is too fun not to share.
```
s='s'
i=s
n=i*input()
while 1:
while n==n[::2]+n[::2]:i+=s;n=n[::2]
if n==s:i.rindex(s);break
n=3*n+s
i+=s
```
[Answer]
### [Rebmu](http://hostilefork.com/rebmu): 28
```
u[++jE1 AeEV?a[d2A][a1M3a]]j
```
On a problem this brief and mathy, GolfScript will likely win by some percent against Rebmu (if it's not required to say, read files from the internet or generate JPG files). Yet I think most would agree the logic of the Golfscript is nowhere near as easy to follow, and the total executable stack running it is bigger.
Although Rebol's own creator [Carl Sassenrath](http://en.wikipedia.org/wiki/Carl_Sassenrath) told me he found Rebmu "unreadable", he is busy, and hasn't time to really practice the pig-latin-like transformation via [unmushing](https://github.com/hostilefork/rebmu/blob/2965e013aa6e0573caa326780d97522a425103f0/mushing.rebol#L18). This really is merely transformed to:
```
u [
++ j
e1 a: e ev? a [
d2 a
] [
a1 m3 a
]
]
j
```
Note that the space was required to get an **a:** instead of an **a**. This is a "set-word!" and the evaluator notices that symbol type to trigger assignment.
If it were written in unabbreviated (yet awkwardly-written Rebol), you'd get:
```
until [
++ j
1 == a: either even? a [
divide a 2
] [
add 1 multiply 3 a
]
]
j
```
Rebol, like Ruby, evaluates blocks to their last value. The UNTIL loop is a curious form of loop that takes no loop condition, it just stops looping when its block evaluates to something not FALSE or NONE. So at the point that `1 ==` the result of assigning A (the argument to rebmu) to the result of the Collatz conditional (either is an IF-ELSE which evaluates to the branch it chooses)... the loop breaks.
J and K are initialized to integer value zero in Rebmu. And as aforementioned, the whole thing evaluates to the last value. So a J reference at the end of the program means you get the number of iterations.
**Usage:**
```
>> rebmu/args [u[++jE1 AeEV?a[d2A][a1M3a]]j] 16
== 4
```
[Answer]
### J, 30 characters
```
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:
```
Turned out quite a bit longer than desired
usage:
```
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:2
1
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:16
4
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:5
5
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:7
16
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:27
111
```
* `-:`(1+3&*)`]` is a gerund composed of three verbs, used on three occasions. `-:` means "halve", `(1+3&*)` or `(1+3*])` encodes the multiplication step and `]` (identity) aids termination.
* `2&|+1&=` forms an index to the gerund. literally, "the remainder after division by two plus whether it equals one".
* `#verb^:a:` iterates the function until the result is stable (here, forced explicitly), while collecting the steps, then counts them. [Stolen from @JB](https://codegolf.stackexchange.com/a/1257/7209). `<:` decrements the step count by one to align with the question requirements.
[Answer]
## [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes
```
1b|{/₂ℕ|×₃+₁}↰+₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1snlP83TKqp1n/U1PSoZWrN4emPmpq1gTK1QAUg@v//aFMdMx1zHQsdI4tYAA "Brachylog – Try It Online")
### Explanation
```
Either:
1 The input is 1.
b In which case we unify the output with 0 by beheading the 1
(which removes the leading digit of the 1, and an "empty integer"
is the same as zero).
| Or:
{ This inline predicate evaluates a single Collatz step on the input.
Either:
/₂ Divide the input by 2.
ℕ And ensure that the result is a natural number (which is
equivalent to asserting that the input was even).
| Or:
×₃+₁ Multiply the input by 3 and add 1.
}
↰ Recursively call the predicate on this result.
+₁ And add one to the output of the recursive call.
```
An alternative solution at the same byte count:
```
;.{/₂ℕ|×₃+₁}ⁱ⁾1∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1snlP@31qvWf9TU9Khlas3h6Y@amrWBErWPGjc@atxn@Khj@f//0aY6ZjrmOhY6RhY6FqaxAA "Brachylog – Try It Online")
```
;. The output of this is a pair [X,I] where X is the input and
I will be unified with the output.
{/₂ℕ|×₃+₁} This is the Collatz step predicate we've also used above.
ⁱ⁾ We iterate this predicate I times on X. Since we haven't actually
specified I, it is still a free variable that Brachylog can backtrack
over and it will keep adding on iterations until the next
constraint can be satisfied.
1 Require the result of the iteration to be 1. Once this is
satisfied, the output variable will have been unified with
the minimum number of iterations to get here.
∧ This AND is just used to prevent the 1 from being implicitly
unified with the output variable as well.
```
[Answer]
# [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN), 24 fractions
Uses 180 bytes, for the more conventional counters...
```
68/13, 133/102, 341/51, 115/17, 17/19, 87/161, 17/23, 23/29, 53/93,
26973/217, 410/259, 43/111, 976/37, 37/41, 329/215, 37/43, 43/47,
118/265, 1/53, 53/59, 67/305, 1/61, 61/67, 117/4
```
[Try it online!](https://tio.run/##JY1RDsMgDEOv0gMwBScQ4DKTqmmT9tNOXc8/ZuiX5RfHfh3r4zzWrXevAgsLzARRw2IJkkGALCjUImhhqRTHtMq4mihpNmnDeSsEI54QRTNPiX3gQysuxoMVSbSmjcF8eZuxNFZQRZ2Y4zZ7R4cXsTjhmHbKjPKz9673pL/9c7737dtvT@AP "FRACTRAN – Try It Online")
### Explanation
Am a bit lazy to add an explanation now; happy to do so if it gets attention/upvotes! However, I do have some notes for when I first wrote up the Collatz Conjecture code which you can run [here](https://tio.run/##JY1RDsMgDEOvwgGoQhIIcJlJ1bRJ@2mrrudfZuiX9RzHfp/r8zrXzd0ascbAqsRJYlCmwmAuxBVaiXsMDWI8UZAWJYFblPog6xXGiGdOJAWnjDrGQ69GioNWykCVjmC5WWcsjxVuJAYb4zp7R4dV0jTNMW2QGcWnu8sjy28/rs@@fX05xJeX/AE). It's almost the same, but the TIO command line arguments are set to print every number in the sequence along the way, which makes it less of a blackbox!
### State Diagrams for COLLATZGAME
Here are the state diagrams, for which I used Conway's original notation which he presents in this [article](https://link.springer.com/chapter/10.1007/978-1-4612-4808-8_2).
[![Original CollatzGame](https://i.stack.imgur.com/ad8sYm.jpg)](https://i.stack.imgur.com/ad8sYm.jpg)[![Cleaned-up CollatzGame](https://i.stack.imgur.com/MhQKCm.jpg)](https://i.stack.imgur.com/MhQKCm.jpg)
### Change Made
The above is simply to calculate the Collatz sequence for `n` given an input of the form `2^n`. The only change I made to also keep count of the steps taken was to make the 1/3 from states Q -> D into an 11/3, 11 being the smallest unused prime. This fraction is only executed once for every number in the sequence; it's the state that figures out whether the number is even or odd to figure out what's next. Therefore, the `11` prime register is incremented once per number in the sequence, except one, yielding the number of steps.
### Note
I simply encoded the state diagram as below and wrote an interpreter which did the dirty work. However, the work done to convert a state diagram to FRACTRAN is also detailed in Conway's article above:
* A: 9/4 -> T
* T: 4/1 -> Q
* Q: 7/6\*, 11/3 -> D, 5/1 -> R
* R: 3/7\*|Q
* D: 1/3 -> E, 729/7 -> M
* M: 10/7\*, 1/3 -> N, 16/1 -> O
* N: 7/5\*|M
* E: 2/5\*|A
* O: 1/5\*|A
[Answer]
## APL (31)
```
A←0⋄A⊣{2⊤⍵:1+3×⍵⋄⍵÷2}⍣{⍺=A+←1}⎕
```
[Answer]
## 80386 assembly, 16 bytes
This example uses AT&T syntax and the fastcall calling convention, the argument goes into `ecx`:
```
collatz:
or $-1,%eax # 3 bytes, eax = -1;
.Loop: inc %eax # 1 byte, eax += 1;
lea 1(%ecx,%ecx,2),%edx # 4 bytes, edx = 3*ecx + 1;
shr %ecx # 2 bytes, CF = ecx & 1;
# ecx /= 2;
# ZF = ecx == 0;
cmovc %edx,%ecx # 3 bytes, if (CF) ecx = edx;
jnz .Loop # 2 bytes, if (!ZF) goto .Loop;
ret # 1 byte, return (eax);
```
Here are the resulting 16 bytes of machine code:
```
83 c8 ff 40 8d 54 49 01 d1 e9 0f 42 ca 75 f4 c3
```
[Answer]
## PowerShell: 77 74 71 70 61
**Golfed code:**
```
for($i=(read-host);$i-ne1;$x++){$i=(($i/2),(3*$i+1))[$i%2]}$x
```
---
**Notes:**
I originally tried taking the user input without forcing it to an integer, but that broke in an interesting way. Any odd inputs would process inaccurately, but even inputs would work fine. It took me a minute to realize what was going on.
When performing multiplication or addition, PowerShell treats un-typed input as a string first. So, `'5'*3+1` becomes '5551' instead of 16. The even inputs behaved fine because PowerShell doesn't have a default action for division against strings. Even the even inputs which would progress through odd numbers worked fine because, by the time PowerShell got to an odd number in the loop, the variable was already forced to an integer by the math operations anyway.
>
> Thanks to [Danko Durbic](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture/15220?noredirect=1#comment29077_15220) for pointing out I could just invert the multiplication operation, and not have to cast `read-host` to int since PowerShell bases its operations on the first object.
>
>
>
PowerShell Golfer's Tip: For some scenarios, like this one, `switch` beats `if/else`. Here, the difference was 2 characters.
>
> Protip courtesy of [Danko Durbic](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture/15220?noredirect=1#comment29076_15220): For this particular scenario, an array can be used instead of `switch`, to save 8 more characters!
>
>
>
There's no error checking for non-integer values, or integers less than two.
If you'd like to audit the script, put `;$i` just before the last close brace in the script.
I'm not sure exactly how well PowerShell handles numbers that progress into very large values, but I expect accuracy is lost at some point. Unfortunately, I also expect there's not much that can be done about that without seriously bloating the script.
---
**Ungolfed code, with comments:**
```
# Start for loop to run Collatz algorithm.
# Store user input in $i.
# Run until $i reaches 1.
# Increment a counter, $x, with each run.
for($i=(read-host);$i-ne1;$x++)
{
# New $i is defined based on an array element derived from old $i.
$i=(
# Array element 0 is the even numbers operation.
($i/2),
# Array element 1 is the odd numbers operation.
(3*$i+1)
# Array element that defines the new $i is selected by $i%2.
)[$i%2]
}
# Output $x when the loop is done.
$x
# Variable cleanup. Don't include in golfed code.
rv x,i
```
---
**Test cases:**
Below are some samples with auditing enabled. I've also edited the output some for clarity, by adding labels to the input and final count and putting in spacing to set apart the Collatz values.
```
---
Input: 2
1
Steps: 1
---
Input: 16
8
4
2
1
Steps: 4
---
Input: 5
16
8
4
2
1
Steps: 5
---
Input: 7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 16
---
Input: 42
21
64
32
16
8
4
2
1
Steps: 8
---
Input: 14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 17
---
Input: 197
592
296
148
74
37
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 26
---
Input: 31
94
47
142
71
214
107
322
161
484
242
121
364
182
91
274
137
412
206
103
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1
Steps: 106
---
Input: 6174
3087
9262
4631
13894
6947
20842
10421
31264
15632
7816
3908
1954
977
2932
1466
733
2200
1100
550
275
826
413
1240
620
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1
Steps: 111
---
Input: 8008135
24024406
12012203
36036610
18018305
54054916
27027458
13513729
40541188
20270594
10135297
30405892
15202946
7601473
22804420
11402210
5701105
17103316
8551658
4275829
12827488
6413744
3206872
1603436
801718
400859
1202578
601289
1803868
901934
450967
1352902
676451
2029354
1014677
3044032
1522016
761008
380504
190252
95126
47563
142690
71345
214036
107018
53509
160528
80264
40132
20066
10033
30100
15050
7525
22576
11288
5644
2822
1411
4234
2117
6352
3176
1588
794
397
1192
596
298
149
448
224
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 93
---
```
Interesting bits about the input numbers which are not from the question's test cases:
* `14` and `197` are [Keith Numbers](http://numberphile.com/videos/197_keith.html)
* `31` is a [Mersenne Prime](http://numberphile.com/videos/31.html)
* `6174` is [Kaprekar's Constant](http://numberphile.com/videos/6174.html)
* And lastly, I just like `8008135`. And [Numberphile](http://numberphile.com), obviously.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~59~~ 56 bytes
```
,-[<->[[>]+<[-<]>>]>[-<<[++>+<]>->]<<[+>+++<]<<+>>>]<<<.
```
[Try it online!](https://tio.run/##dVFNT8MwDL33V/gIyoqYhBBSrfwG7lEOWeNt0bpkSrIy@PPF7lrtAr7En8/vObvsQtxf@9O0MVrNZlpsF9MWcU2LYWu13licWoOtNkZbhdzOSav5RaOUVhzeB5VMIntKa0ng9JlDrAUc9DQMMLrhSvBU3Yki7HM6A5U0uHgosNvDxR3ouTE8Pc@3AtAY9hQ7wkNJ2KKB7usYBlrg6BZKLQ0A4IO3hu7MW3jx9lVKItEwMJMzrFc4z5EWs9D5MAa/Iu6@lymWKrUUK0QiD/UYyqxEiuuq9Vwovc57ePuAmiDTmQ/tKd@BZhXSUWrKxEj0b8eBZN2t3tlIUevGom344tDRUGhhk2DR@EM5zSD4B6nGNt1FvgFc9NAP5DKQ648wM/EPGhAiByPlQrzqhbXzJ0/b918) (Slightly modified for ease of use)
Input and output as character codes. This is more useful with arbitrarily sized cells, but can still work with small values in limited cell sizes.
### How It Works
```
Tape Format:
Counter 0 Copy Number Binary...
^End ^Start
,-[ Get input, decrement by 1 and start loop
<-> Initialises the copy of the value at -1
[[>]+<[-<]>>] Converts the input to binary while preserving a negative copy
<+>>[-<<[++>+<]>->] If the last digit of the binary is 1 (n-1 is odd), divide by 2 and decrement
<<[+>+++<] If the last digit of the binary is 0 (n-1 is even), multiply by 3
<<+>>> Increment counter and end on n-1
]<<<. End loop and print counter
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
×3‘ƊHḂ?Ƭi2
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//w5cz4oCYxopI4biCP8asaTL/w4figqz//zIsMTYsNSw3 "Jelly – Try It Online")
### How it works
```
×3‘ƊHḂ?Ƭi2 Main link (monad). Input: integer >= 2
? Create a "ternary-if" function:
Ḃ If the input is odd,
×3‘Ɗ compute 3*n+1;
H otherwise, halve it.
Ƭ Repeat until results are not unique; collect all results
i2 Find one-based index of 2
```
Example: The result of `...Ƭ` for input 5 is `[5, 16, 8, 4, 2, 1]`. The one-based index of 1 is 6, which is 1 higher than expected. So we choose the index of 2 (which is guaranteed to come right before 1) instead.
[Answer]
# ngn/k, 21 bytes
```
#{(2|-2!x;1+3*x)2!x}\
```
I converted the operation to be `x = max(2, x/2)` so the sequence had a fixed point, and converges (`\`) handled the rest. `#` counts the number of steps, including the beginning.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
×3‘$HḂ?ß0’?‘
```
[Try it online!](http://jelly.tryitonline.net/#code=w5cz4oCYJEjhuII_w58w4oCZP-KAmA&input=&args=Nw)
### How it works
```
×3‘$HḂ?ß0’?‘ Main link. Argument: n (integer)
Ḃ? Yield the last bit of n is 1:
$ Evaluate the three links to the left as a monadic chain:
×3 Multiply n by 3.
‘ Increment the product by 1.
H Else, halve n.
’? If n-1 is non-zero:
ß Recursively call the main link.
0 Else, yield 0.
‘ Increment the result by 1.
```
[Answer]
# Gambit scheme, ~~106~~ 98 characters, 40 parentheses
```
(let((f(lambda(x)(cond((= x 1) 0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))))(f(read)))
```
**~~91~~ 89 chars** with define directly
```
(define(f x)(cond((= x 1)0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))(f(read))
```
[Answer]
# Python 2, ~~68~~ ~~58~~ ~~54~~ 52 bytes
```
f=lambda n:1+(n-2and f((n/2,3*n+1)[n%2]));f(input())
```
Thanks to @Bakuriu and @boothby for the tips :)
[Answer]
## GolfScript (23 chars)
```
~{.1&{.3*)}*.2/.(}do;],
```
[Online test](http://golfscript.apphb.com/?c=O1syIDE2IDUgN117YAp%2Bey4xJnsuMyopfSouMi8uKH1kbztdLApwfS8%3D)
[Answer]
## F# - 65 chars
```
let rec c n=function 1->n|i->c(n+1)(if i%2=0 then i/2 else i*3+1)
```
[Answer]
# dc, 27 characters
Applying [boothby's black magic](https://codegolf.stackexchange.com/a/12209/4372):
```
?[d3*1+d2%5*1+/d1<x]dsxxkzp
```
I'm not really sure if I understand how - or *that* - it works.
Usage:
```
$ dc collatz.dc <<< 7
16
```
# dc, 36 characters
My own creation; a somewhat more traditional approach, even tho I had to wrangle with the language a fair bit to overcome the lack of an `else` part to `if` statements:
```
?[2/2Q]se[dd2%[0=e3*1+]xd1<x]dsxxkzp
```
Internally it produces all numbers of the sequence and stores them on the stack, then pops the final `1` and displays the stack height.
[Answer]
# Ruby 1.9, 49 characters
Rubyfied Valentin CLEMENT's [Python answer](https://codegolf.stackexchange.com/a/12195/4372), using the stabby lambda syntax. Sqeezed it into one statement for added unreadability.
```
(f=->n{n>1&&1+f[[n/2,3*n+1][n%2]]||0})[gets.to_i]
```
Some overhead because Ruby, unlike Python, is not happy about mixing numbers with booleans.
[Answer]
# [Retina](https://github.com/mbuettner/retina), 43 bytes
```
11
2
(2+)1
$1$1$0$0$0$0
2.*
$0x
)`2
1
1?x
1
```
Takes input and prints output in unary.
Each line should go to its own file. 1 byte per extra file added to byte-count.
You can run the code as one file with the `-s` flag. E.g.:
```
> echo -n 1111111|retina -s collatz
1111111111111111
```
The algorithm is a loop of doing a Collatz step with the unary number and adding a new step-marker `x` at the end of the string if the number isn't 1.
When the loop ends with `1`, we convert the markers to a unary number (removing the leading `1`) which is the desired output.
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), ~~48~~ 44 bytes
```
?(]$_)"){{?{*')}/&!/={:<$["/>&_(.<@2'%<>./>=
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99eI1YlXlNJs7ravlpLXbNWX01R37baykYlWknfTi1eQ8/GwUhd1cZOT9/O9v9/I3MA "Hexagony – Try It Online")
Expanded:
```
? ( ] $ _
) " ) { { ?
{ * ' ) } / &
! / = . { < $ [
" / > & _ ( . < @
2 ' % < > : / >
= . . . . . .
. . . . . .
. . . . .
```
~~Note that this fails on `1` for uhh... *reasons*. Honestly, I'm not really sure how this works anymore. All I know is that the code for odd numbers is run backwards for even numbers? Somehow?~~
The new version is much cleaner than the previous, but has a few more directionals in comparison and also ends in a divide-by-zero error. The only case it doesn't error is when it actually handles `1` correctly.
[Answer]
# ><>, 27 26 23 bytes
```
\ln;
\::2%:@5*1+2,*+:2=?
```
Like the other ><> answers, this builds the sequence on the stack. Once the sequence reaches 2, the size of the stack is the number of steps taken.
Thanks to @Hohmannfan, saved 3 bytes by a very clever method of computing the next value directly. The formula used to calculate the next value in the sequence is:
$$f(n)=n\cdot\frac{5(n\bmod2)+1}{2}+(n\bmod2)$$
The fraction maps even numbers to 0.5, and odd numbers to 3. Multiplying by `n` and adding `n%2` completes the calculation - no need to choose the next value at all!
**Edit 2:** Here's the pre-@Hohmannfan version:
```
\ln;
\:::3*1+@2,@2%?$~:2=?
```
The trick here is that both `3n+1` and `n/2` are computed at each step in the sequence, and the one to be dropped from the sequence is chosen afterwards. This means that the code doesn't need to branch until 1 is reached, and the calculation of the sequence can live on one line of code.
**Edit:** Golfed off another character after realising that the only positive integer that can lead to 1 is 2. As the output of the program doesn't matter for input < 2, the sequence generation can end when 2 is reached, leaving the stack size being the exact number of steps required.
Previouser version:
```
\~ln;
\:::3*1+@2,@2%?$~:1=?
```
[Answer]
# Julia 0.6, ~~29~~ 27 bytes
```
!n=n>1&&1+!(n%2>0?3n+1:n/2)
```
I can't seem to compile Julia 0.1 on my machine, so there's a chance this is non-competing.
[Try it online!](http://julia.tryitonline.net/#code=IW49bj4xJiYxKyEobiUyPjA_M24rMTpuLzIpCgpwcmludGxuKCEyKQpwcmludGxuKCExNikKcHJpbnRsbighNSkKcHJpbnRsbighNyk&input=)
[Answer]
## C, 70 69 chars
Quite simple, no tricks.
Reads input from stdin.
```
a;
main(b){
for(scanf("%d",&b);b-1;b=b%2?b*3+1:b/2)a++;
printf("%d",a);
}
```
] |
[Question]
[
Write a program that counts up forever, starting from one.
Rules:
* Your program must log to `STDOUT` or an acceptable alternative, if `STDOUT` is not available.
* Your program must be a full, runnable program, and not a function or snippet.
* Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.
* You may print the numbers in decimal, [in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) or in [base 256 where each digit is represented by a byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values).
* Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.
* Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.
Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.
* This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.
### Catalogue
The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63834; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39069; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 5 bytes
```
):
\!
```
♫ The IP in the code goes round and round ♫
Relevant instructions:
```
) Increment top of stack (stack has infinite zeroes at bottom)
: Duplicate top of stack
! Output top of stack
\ Output newline
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 8 bytes
```
01+:nao!
```
Steps:
* Push 0 on the stack
* Add 1 to the top stack element
* Duplicate top stack element
* Output the top of the stack as number
* Output a newline
* Go to step 2 by wrapping around and jumping the next instruction (step 11)
*(A less memory efficient (hence invalid) program is `llnao`.)*
[Answer]
# C (64-bit architecture only), 53 bytes
Relies on pointers being at least 64 bits and prints them in hex using the `%p` specifier. The program would return right when it hits 2^128.
```
char*a,*b;main(){for(;++b||++a;)printf("%p%p ",a,b);}
```
[Answer]
## Haskell, 21 bytes
```
main=mapM_ print[1..]
```
Arbitrary-precision integers and infinite lists make this easy :-)
Luckily `mapM_` is in the Prelude. If `Data.Traversable` was as well, we even could shrink it to 19 bytes:
```
main=for_[1..]print
```
[Answer]
# [Gol><>](https://golfish.herokuapp.com/), 3 bytes
```
P:N
```
Steps:
* Add 1 to the top stack element (at start it is an implicit 0)
* Duplicate top stack element
* Pop and output the top of the stack as number and a newline
* Wrap around to step 1 as we reached the end of the line
[Answer]
# [Marbelous](https://github.com/marbelous-lang/marbelous.py), ~~11450~~ 4632 bytes
Printing decimals is a pain!!
Definitely not winning with this one, but I thought I'd give it a shot. I hope it's ok that it pads the output to 40 zeros (to fit 2^128).
```
00@0..@1..@2..@3..@4..@5..@6..@7..@8..@9..@A..@B..@C..@D..@E..@F..@G..@H..@I..@J
\\++..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00..00
..EhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhunEhun
....AddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddtAddt
..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7..&7\/
../\&8..........................................................................
....@0..........................................................................
....../\&8......................................................................
....//..@1......................................................................
........../\&8..................................................................
......////..@2..................................................................
............../\&8..............................................................
........//////..@3..............................................................
................../\&8..........................................................
..........////////..@4..........................................................
....................../\&8......................................................
............//////////..@5......................................................
........................../\&8..................................................
..............////////////..@6..................................................
............................../\&8..............................................
................//////////////..@7..............................................
................................../\&8..........................................
..................////////////////..@8..........................................
....................................../\&8......................................
....................//////////////////..@9......................................
........................................../\&8..................................
......................////////////////////..@A..................................
............................................../\&8..............................
........................//////////////////////..@B..............................
................................................../\&8..........................
..........................////////////////////////..@C..........................
....................................................../\&8......................
............................//////////////////////////..@D......................
........................................................../\&8..................
..............................////////////////////////////..@E..................
............................................................../\&8..............
................................//////////////////////////////..@F..............
................................................................../\&8..........
..................................////////////////////////////////..@G..........
....................................................................../\&8......
....................................//////////////////////////////////..@H......
........................................................................../\&8..
......................................////////////////////////////////////..@I..
............................................................................../\&8
........................................//////////////////////////////////////..@J
&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9&9
Sixteenbytedecimalprintermodulewitharegi
:Sixteenbytedecimalprintermodulewitharegi
}J}J}I}I}H}H}G}G}F}F}E}E}D}D}C}C}B}B}A}A}9}9}8}8}7}7}6}6}5}5}4}4}3}3}2}2}1}1}0}00A
/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A/A%A
%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..%A..
+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O..
+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O+O..
:/A
..}0..}0..
..>>}0....
..>>>>\\..
....//..//
../\>>\\..
....>>..//
....>>\\..
....>>....
\\>>//....
..>>......
..>>......
../\......
..../\<<..
......<<..
..\\<<//..
....~~....
....++....
....\\..//
\\....>9\/
..\\..?0..
......++..
....\\....
......{0..
:%A
@0..
}0..
<A-A
{0@0
:Eg
}0}0}0}0}0}0}0}0
^7^6^5^4^3^2^1^0
~~....~~~~..~~~~
^0^0^0^0^0^0^0^0
{0{0{0{0{0{0{0{0
:Ehun
}0..}0
Eg..&0
=8&0{0
&1\/00
0100&0
&1&1{1
{1{0
:Addt
}0}1
{1{1
```
[Answer]
## [Hexagony](https://github.com/mbuettner/hexagony), ~~12~~ ~~11~~ ~~10~~ 7 bytes
*Thanks to alephalpha for fitting the code into side-length 2.*
```
10})!';
```
Unfolded:
```
1 0
} ) !
' ;
```
This one is fairly simple. `10` writes a 10, i.e. a linefeed to the initial memory edge. Then `})!';` is repeatedly executed in a loop:
* `}` move to the next memory edge.
* `)` increment it.
* `!` print it as an integer.
* `'` move back to the 10.
* `;` print it as a character.
I believe that this is optimal (although by far not unique). I've let the brute force script I wrote [for this answer](https://codegolf.stackexchange.com/a/62812/8478) search for 6-byte solutions under the assumption that it would have to contain at least one each of `;` and `!` and either `(` or `)`, and would not contain `?`, `,` or `@`, and it didn't find any solutions.
[Answer]
# bc, 10
```
for(;;)++i
```
Unusual that `bc` is shorter than [`dc`](https://codegolf.stackexchange.com/a/63861/11259).
From `man bc`:
>
> DESCRIPTION
>
>
> bc is a language that supports arbitrary precision numbers
>
>
>
[Answer]
# Pyth, 4 bytes
```
.V1b
```
### Explanation:
```
.V1 for b in range(1 to infinity):
b print b
```
[Answer]
# Java, ~~139~~ ~~138~~ ~~127~~ 123 bytes
```
class K{public static void main(String[]a){java.math.BigInteger b=null;for(b=b.ZERO;;)System.out.println(b=b.add(b.ONE));}}
```
[Answer]
# Mathematica, 22 bytes
```
i=0;While[Echo[++i]>0]
```
[`Echo`](http://reference.wolfram.com/language/ref/Echo.html) is a new function in Mathematica 10.3.
[Answer]
# Python 3, ~~33~~ 25 bytes
As far as I understand, Pythons integers are arbitrary precision, and `print()` automatically produces newlines.
Thanks for @Jakub and @Sp3000 and @wnnmaw! I really don't know much python, the only think I knew was that it supports arbitrary size integers=)
```
k=1
while 1:print(k);k+=1
```
[Answer]
# Ruby, ~~15~~ 12 bytes
```
loop{p$.+=1}
```
* `p`, when given an integer, prints the integer as-is (courtesy of [@philomory](https://codegolf.stackexchange.com/users/47276/philomory))
* `$.` is a magical variable holding the number of lines read from stdin. It is obviously initialized to 0, and also assignable :)
[Answer]
# [Samau](https://github.com/AlephAlpha/Samau), 2 bytes
```
N)
```
Explanation:
```
N push the infinite list [0 1 2 ...] onto the stack
) increase by 1
```
When the output of a program is a list, the outmost brackets are omitted.
[Answer]
# [Microsoft PowerPoint](https://www.youtube.com/watch?v=uNjxe8ShM-8) (33 Slides, 512 shapes to meet minimum requirements)
Storage representation is in hexadecimal.
## Directions
* Click the blue square to advance the counter (or propagate the carry), or make an AutoHotKey Script to click it for you.
* You can view the number's digits at any time using the green buttons. (It causes unintended behavior if you click the blue buttons after viewing another digit.) This is just for a better UX. It still counts up as normal as long as you keep clicking the blue button. In other words, no user decision is required.
* If you reach the end, it displays a congratulatory message.
You can get the PPTX [here](https://drive.google.com/open?id=1JTbg0fSnWV2ig7PYYb1jB5kWCteW9XgU). Requires PowerPoint to run.
Before you comment that Microsoft PowerPoint is not a programming language, it has been shown that PowerPoint is Turing complete (in the same sense that conventional languages such as C are Turing complete). A brief discussion is given [here](https://www.andrew.cmu.edu/user/twildenh/PowerPointTM/Paper.pdf).
[Answer]
# [makina](https://github.com/GingerIndustries/makina), 22 bytes
```
v
>Pv
^>OC
^Uu>n0;
^O<
```
I AM REAL HUMAN YOU SHOULD TRUST ME AND DO WHAT I SAY
[Answer]
# Matlab, 132 bytes
```
a=0;while 1;b=a==9;n=find(cumsum(b)-(1:numel(b)),1);a(n)=a(n)+1;a(1:n-1)=0;if ~numel(n);a=[0*a,1];end;disp([a(end:-1:1)+'0','']);end
```
Ok, I think this is the *first serious* answer that accomplishes this task without a trivial builtin abitrary size integer. This program implements an arbitrary size integer as an array of integers. Each integer is always between 0 and 9, so each array element represents one decimal digit. The array size wil be increased by one as soon as we are at e.g. `999`. The memory size is no problem here, as `2^128` only requires an array of length 39.
```
a=0;
while 1
b=a==9;
%first number that is not maxed out
n=find(cumsum(b)-(1:numel(b)),1);
%increase that number, and sett all maxed out numbers to zero
a(n)=a(n)+1;
a(1:n-1)=0;
if ~numel(n) %if we maxed out all entries, add another digit
a=[0*a,1];
end
disp([a(end:-1:1)+'0',''])%print all digits
end
```
[Answer]
# [Processing](http://www.processing.org), ~~95~~ ~~85~~ 71 bytes
```
java.math.BigInteger i;{i=i.ZERO;}void draw(){println(i=i.add(i.ONE));}
```
I tried something with a while loop but it causes all of Processing to crash, so I'll stick with this for now.
(Thanks to @SuperJedi224 and @TWiStErRob for suggestions.)
[Answer]
# JavaScript (ES6), ~~99~~ ~~94~~ 67 bytes
```
for(n=[i=0];;)(n[i]=-~n[i++]%10)&&alert([...n].reverse(i=0).join``)
```
`alert` is the generally accepted `STDOUT` equivalent for JavaScript but using it means that consecutive numbers are automatically separated. I've assumed that outputting a character after the number is not necessary because of this.
[Answer]
## C++, ~~146~~ ~~141~~ 138 bytes
Using a standard bigint library is perhaps the *most* boring way of answering this question, but someone had to do it.
```
#include<stdio.h>
#include<boost/multiprecision/cpp_int.hpp>
int main(){for(boost::multiprecision::uint512_t i=1;;){printf("%u\n",i++);}}
```
Ungolfed:
```
#include<cstdio>
#include<boost/multiprecision/cpp_int.hpp>
int main()
{
for(boost::multiprecision::uint512_t i=1;;)
{
std::printf("%u\n", i++);
}
}
```
The reason the golfed version uses `stdio.h` and not `cstdio` is to avoid having to use the `std::` namespace.
This is my first time golfing in C++, let me know if there's any tricks to shorten this further.
[Answer]
## Intel 8086+ Assembly, 19 bytes
```
68 00 b8 1f b9 08 00 31 ff f9 83 15 00 47 47 e2 f9 eb f1
```
Here's a breakdown:
```
68 00 b8 push 0xb800 # CGA video memory
1f pop ds # data segment
b9 08 00 L1: mov cx, 8 # loop count
31 ff xor di, di # ds:di = address of number
f9 stc # set carry
83 15 00 L2: adc word ptr [di], 0 # add with carry
47 inc di
47 inc di
e2 f9 loop L2
eb f1 jmp L1
```
It outputs the 128 bit number on the top-left 8 screen positions. Each screen position holds a 8-bit ASCII character and two 4 bit colors.
*Note: it wraps around at 2128; simply change the `8` in`mov cx, 8` to `9` to show a 144 bit number, or even `80*25` to show numbers up to 232000.*
## Running
### 1.44Mb bzip2 compressed, base64 encoded bootable floppy Image
Generate the floppy image by copy-pasting the following
```
QlpoOTFBWSZTWX9j1uwALTNvecBAAgCgAACAAgAAQAgAQAAAEABgEEggKKAAVDKGgAaZBFSMJgQa
fPsBBBFMciogikZcWgKIIprHJDS9ZFh2kUZ3QgggEEh/i7kinChIP7HrdgA=
```
into this commandline:
```
base64 -d | bunzip2 > floppy.img
```
and run with, for instance, `qemu -fda floppy.img -boot a`
### 1.8Mb bootable ISO
This is a base64 encoded bzip2 compressed ISO image. Generate the iso by pasting
```
QlpoOTFBWSZTWZxLYpUAAMN/2//fp/3WY/+oP//f4LvnjARo5AAQAGkAEBBKoijAApcDbNgWGgqa
mmyQPU0HqGCZDQB6mQ0wTQ0ZADQaAMmTaQBqekyEEwQaFA0AA0AxBoAAA9Q0GgNAGg40NDQ0A0Bi
BoDIAANNAA0AyAAABhFJNIJiPSmnpMQDJpp6nqeo0ZDQaAANB6IA0NAGj1EfIBbtMewRV0acjr8u
b8yz7cCM6gUUEbDKcCdYh4IIu9C6EIBehb8FVUgEtMIAuvACCiO7l2C0KFaFVABcpglEDCLmQqCA
LTCAQ5EgnwJLyfntUzNzcooggr6EnTje1SsFYLFNW/k+2BFABdH4c4vMy1et4ZjYii1FbDgpCcGl
mhZtl6zX+ky2GDOu3anJB0YtOv04YISUQ0JshGzAZ/3kORdb6BkTDZiYdBAoztZA1N3W0LJhITAI
2kSalUBQh60i3flrmBh7xv4TCMEHTIOM8lIurifMNJ2aXr0QUuLDvv6b9HkTQbKYVSohRPsTOGHi
isDdB+cODOsdh31Vy4bZL6mnTAVvQyMO08VoYYcRDC4nUaGGT7rpZy+J6ZxRb1b4lfdhtDmNwuzl
E3bZGU3JTdLNz1uEiRjud6oZ5kAwqwhYDok9xaVgf0m5jV4mmGcEagviVntDZOKGJeLjyY4ounyN
CWXXWpBPcwSfNOKm8yid4CuocONE1mNqbd1NtFQ9z9YLg2cSsGQV5G3EhhMXKLVC2c9qlqwLRlw4
8pp2QkMAMIhSZaSMS4hGb8Bgyrf4LMM5Su9ZnKoqELyQTaMAlqyQ3lzY7i6kjaGsHyAndc4iKVym
SEMxZGG8xOOOBmtNNiLOFECKHzEU2hJF7GERK8QuCekBUBdCCVx4SDO0x/vxSNk8gKrZg/o7UQ33
Fg0ad37mh/buZAbhiCIAeeDwUYjrZGV0GECBAr4QVYaP0PxP1TQZJjwT/EynlkfyKI6MWK/Gxf3H
V2MdlUQAWgx9z/i7kinChITiWxSo
```
into
```
base64 -d bunzip2 > cdrom.iso
```
and configure a virtual machine to boot from it.
### DOS .COM
This is a base64 encoded [DOS .COM](https://en.wikipedia.org/wiki/COM_file) executable:
```
aAC4H7kIADH/+YMVAEdH4vnr8Q==
```
Generate a .COM file using
```
/bin/echo -n aAC4H7kIADH/+YMVAEdH4vnr8Q== | base64 -d > COUNTUP.COM
```
and run it in (Free)DOS.
[Answer]
## sed, ~~116~~ ~~92~~ 83 bytes
```
:
/^9*$/s/^/0/
s/.9*$/_&/
h
s/.*_//
y/0123456789/1234567890/
x
s/_.*//
G
s/\n//p
b
```
**Usage:**
Sed operates on text input and it *needs* input do anything. To run the script, feed it with just one empty line:
```
$ echo | sed -f forever.sed
```
**Explanation:**
To increment a number, the current number is split up into a prefix and a suffix where the suffix is of the form `[^9]9*`. Each digit in the suffix is then incremented individually, and the two parts are glued back together. If the current number consists of `9` digits only, a `0` digit is appended, which will immediately incremented to a `1`.
[Answer]
## Clojure, 17 bytes
```
(map prn (range))
```
Lazy sequences and arbitrary precision integers make this easy (as for Haskell and CL). `prn` saves me a few bytes since I don't need to print a format string. `doseq` would probably be more idiomatic since here we're only dealing with side effects; `map` doesn't make a lot of sense to use since it will create a sequence of `nil` (which is the return value of each `prn` call.
Assuming I count forever, the null pointer sequence which results from this operation never gets returned.
[Answer]
## C# .NET 4.0, ~~111~~ ~~103~~ ~~102~~ 97 bytes
```
class C{static void Main(){System.Numerics.BigInteger b=1;for(;;)System.Console.WriteLine(b++);}}
```
I didn't find any C# answer here, so I just had to write one.
.NET 4.0 is required, because it's the first version that includes [BigInteger](https://msdn.microsoft.com/library/system.numerics.biginteger(v=vs.100).aspx). You have to reference [System.Numerics.dll](https://msdn.microsoft.com/en-us/library/system.numerics(v=vs.100).aspx) though.
With indentation:
```
class C
{
static void Main()
{
System.Numerics.BigInteger b = 1;
for (;;)
System.Console.WriteLine(b++);
}
}
```
*Thanks to sweerpotato, Kvam, Berend for saving some bytes*
[Answer]
# [MarioLANG](http://esolangs.org/wiki/MarioLANG), 11 bytes
```
+<
:"
>!
=#
```
Inspired by [Martin Büttner's answer in another question](https://codegolf.stackexchange.com/questions/62230/simple-cat-program/62425#62425).
[Answer]
## CJam, 7 bytes
```
0{)_p}h
```
Explanation:
```
0 e# Push a zero to the stack
{ e# Start a block
) e# Increment top of stack
_ e# Duplicate top of stack
p e# Print top of stack
} e# End block
h e# Do-while loop that leaves the condition on the stack
```
Note: Must use Java interpreter.
[Answer]
## C, 89 bytes
A new approach (implementing a bitwise incrementer) in C:
```
b[999],c,i;main(){for(;;)for(i=c=0,puts(b);i++<998;)putchar(48+(c?b[i]:(b[i]=c=!b[i])));}
```
**Less golfed**
```
int b[999], c, i;
main() {
for(;;)
for(i=c=0, puts(b); i++ < 998;)
putchar(48 + (c ? b[i] : (b[i] = c = !b[i])));
}
```
**Terminate**
This version has the slight flaw, that it does not terminate (which isn't a requirement at the moment). To do this you would have to add 3 characters:
```
b[129],c=1,i;main(){for(;c;)for(i=c=0,puts(b);i++<128;)putchar(48+(c?b[i]:(b[i]=c=!b[i])));}
```
[Answer]
# [Foo](http://esolangs.org/wiki/Foo), 6 bytes
```
(+1$i)
```
---
### Explanation
```
( ) Loop
+1 Add one to current element
$i Output current element as a decimal integer
```
[Answer]
# [Acc!](https://codegolf.stackexchange.com/a/62404), ~~64~~ 65 bytes
Also works in [*Acc!!*](https://codegolf.stackexchange.com/a/62493).
```
Count q while 1 {
Count x while q-x+1 {
Write 7
}
Write 9
}
```
This prints the numbers out in unary using [Bell characters](https://en.wikipedia.org/wiki/Bell_character) seperated by tabs. If I have to use a more standard character, that would make the program **66 bytes**.
The Acc! interpreter provided in the linked answer translates Acc! to Python, which does support arbritrary-precision integers.
[Answer]
## [Minkolang](https://github.com/elendiastarman/Minkolang), 4 bytes
```
1+dN
```
[Try it here.](http://play.starmaninnovations.com/minkolang/?code=1%2BdN) (Well, actually, be careful. 3 seconds of run time was enough to get up to ~40,000.)
`1+` adds 1 to the top of stack, `d` duplicates it, and `N` outputs the top of stack as an integer with a trailing space. This loops because Minkolang is toroidal, so when the program counter goes off the right edge, it reappears on the left.
] |
[Question]
[
# Background
We already have a challenge [about throwing SIGSEGV](https://codegolf.stackexchange.com/questions/4399/shortest-code-that-return-sigsegv), so why not a challenge about throwing SIGILL?
# What is SIGILL?
SIGILL is the signal for an illegal instruction at the processor, which happens very rarely. The default action after receiving SIGILL is terminating the program and writing a core dump. The signal ID of SIGILL is 4. You encounter SIGILL very rarely, and I have absolutely no idea how to generate it in your code except via `sudo kill -s 4 <pid>`.
# Rules
You will have root in your programs, but if you don't want to for any reasons, you may also use a normal user. I'm on a Linux computer with German locale and I do not know the English text which is displayed after catching SIGILL, but I think it's something like 'Illegal instruction'. The shortest program which throws SIGILL wins.
[Answer]
# PDP-11 Assembler (UNIX Sixth Edition), 1 byte
```
9
```
Instruction 9 is not a valid instruction on the PDP-11 (in octal, it would be `000011`, which does not appear on [the list of instructions](http://www.cdf.toronto.edu/%7Eajr/258/pdp11.pdf) (PDF)). The PDP-11 assembler that ships with UNIX Sixth Edition apparently echoes everything it doesn't understand into the file directly; in this case, 9 is a number, so it generates a literal instruction 9. It also has the odd property (unusual in assembly languages nowadays) that files start running from the start, so we don't need any declarations to make the program work.
You can test out the program using [this emulator](http://pdp11.aiju.de/), although you'll have to fight with it somewhat to input the program.
Here's how things end up once you've figured out how to use the filesystem, the editor, the terminal, and similar things that you thought you already knew how to use:
```
% a.out
Illegal instruction -- Core dumped
```
I've confirmed with the documentation that this is a genuine `SIGILL` signal (and it even had the same signal number, 4, all the way back then!)
[Answer]
# C (x86\_64, [tcc](http://savannah.nongnu.org/projects/tinycc)), 7 bytes
```
main=6;
```
Inspired by [this answer](https://codegolf.stackexchange.com/a/100540/12012).
[Try it online!](https://tio.run/##S9YtSU7@/z83MTPP1sz6/38A "C (tcc) – Try It Online")
### How it works
The generated assembly looks like this.
```
.globl main
main:
.long 6
```
Note that TCC doesn't place the defined "function" in a *data* segment.
After compilation, *\_start* will point to *main* as usual. When the resulting program is executed, it expects code in *main* and finds the little-endian(!) 32-bit integer **6**, which is encoded as **0x06 0x00 0x00 0x00**. The first byte – **0x06** – is an invalid opcode, so the program terminates with *SIGILL*.
---
# C (x86\_64, [gcc](https://gcc.gnu.org/)), 13 bytes
```
const main=6;
```
[Try it online!](https://tio.run/##S9ZNT07@/z85P6@4RCE3MTPP1sz6/38A "C (gcc) – Try It Online")
### How it works
Without the *const* modifier, the generated assembly looks like this.
```
.globl main
.data
main:
.long 6
.section .note.GNU-stack,"",@progbits
```
GCC's linker treats the last line as a hint that the generated object does not require an executable stack. Since *main* is explicitly placed in a *data* section, the opcode it contains isn't executable, so the program terminates will *SIGSEGV* (segmentation fault).
Removing either the second or the last line will make the generated executable work as intended. The last line could be ignored with the compiler flag `-zexecstack` ([Try it online!](https://tio.run/##S9ZNT07@/z83MTPP1sz6//9/yWk5ienF/3WrUitSk4tLEpOzAQ "C (gcc) – Try It Online")), but this costs **12 bytes**.
A shorter alternative is to declare *main* with the *const* modifier, resulting in the following assembly.
```
.globl main
.section .rodata
main:
.long 6
.section .note.GNU-stack,"",@progbits
```
This works without any compiler flags. Note that `main=6;` would write the defined "function" in *data*, but the *const* modifier makes GCC write it in *rodata* instead, which (at least on my platform) is allowed to contain code.
[Answer]
# Swift, 5 bytes
```
[][0]
```
Access index 0 of an empty array. This calls `fatalError()`, which prints an error message and crashes with a SIGILL. [You can try it here](http://swiftlang.ng.bluemix.net/#/repl/5831ec1d892718588ddb0ddb).
[Answer]
# GNU C, 25 bytes
```
main(){__builtin_trap();}
```
GNU C (a specific dialect of C with extensions) contains an instruction to crash the program intentionally. The exact implementation varies from version to version, but often the developers make an attempt to implement the crash as cheaply as possible, which normally involves the use of an illegal instruction.
The specific version I used to test is `gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0`; however, this program causes a SIGILL on a fairly wide range of platfoms, and thus is fairly portable. Additionally, it does it via actually executing an illegal instruction. Here's the assembly code that the above compiles into with default optimization settings:
```
main:
pushq %rbp
movq %rsp, %rbp
ud2
```
`ud2` is an instruction that Intel guarantees will always remain undefined.
[Answer]
# C (x86\_64), 11, 30, 34, or 34+15 = 49 bytes
```
main[]="/";
```
```
c=6;main(){((void(*)())&c)();}
```
```
main(){int c=6;((void(*)())&c)();}
```
I've submitted a couple of solutions that use library functions to throw `SIGILL` via various means, but arguably that's cheating, in that the library function solves the problem. Here's a range of solutions that use no library functions, and make varying assumptions about where the operating system is willing to let you execute non-executable code. (The constants here are chosen for x86\_64, but you could change them to get working solutions for most other processors that have illegal instructions.)
`06` is the lowest-numbered byte of machine code that does not correspond to a defined instruction on an x86\_64 processor. So all we have to do is execute it. (Alternatively, `2F` is also undefined, and corresponds to a single printable ASCII character.) Neither of these are guaranteed to always be undefined, but they aren't defined as of today.
The first program here executes `2F` from the read-only data segment. Most linkers aren't capable of producing a working jump from `.text` to `.rodata` (or their OS's equivalent) as it's not something that would ever be useful in a correctly segmented program; I haven't found an operating system on which this works yet. You'd also have to allow for the fact that many compilers want the string in question to be a wide string, which would require an additional `L`; I'm assuming that any operating system that this works on has a fairly outdated view of things, and thus is building for a pre-C94 standard by default. It's possible that there's nowhere this program works, but it's also possible that there's somewhere this program works, and thus I'm listing it in this collection of more-dubious-to-less-dubious potential answers. (After I posted this answer, Dennis also mentioned the possibility `main[]={6}` in chat, which is the same length, and which doesn't run into problems with character width, and even hinted at the potential for `main=6`; I can't reasonably claim these answers as mine, as I didn't think of them myself.)
The second program here executes `06` from the read-write data segment. On most operating systems this will cause a segmentation fault, because writable data segments are considered to be a bad design flaw that makes exploits likely. This hasn't always been the case, though, so it probably works on a sufficiently old version of Linux, but I can't easily test it.
The third program executes `06` from the stack. Again, this causes a segmentation fault nowadays, because the stack is normally classified as nonwritable for security reasons. The linker documentation I've seen heavily implies that it used to be legal to execute from the stack (unlike the preceding two cases, doing so is occasionally useful), so although I can't test it, I'm pretty sure there's some version of Linux (and probably other operating systems) on which this works.
Finally, if you give `-Wl,-z,execstack` (15 byte penalty) to `gcc` (if using GNU `ld` as part of the backend), it will explicitly turn off executable stack protection, allowing the third program to work and give an illegal operation signal as expected. I *have* tested and verified this 49-byte version to work. (Dennis mentions in chat that this option apparently works with `main=6`, which would give a score of 6+15. I'm pretty surprised that this works, given that the 6 blatantly isn't on the stack; the link option apparently does more than its name suggests.)
[Answer]
# GNU as (x86\_64), 3 bytes
```
ud2
```
---
$ xxd sigill.S
```
00000000: 7564 32 ud2
```
$ as --64 sigill.S -o sigill.o ; ld -S sigill.o -o sigill
```
sigill.S: Assembler messages:
sigill.S: Warning: end of file not at end of a line; newline inserted
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
```
$ ./sigill
```
Illegal instruction
```
$ objdump -d sigill
```
sigill: file format elf64-x86-64
Disassembly of section .text:
0000000000400078 <__bss_start-0x200002>:>
400078: 0f 0b ud2
```
[Answer]
## Bash on Raspbian on QEMU, 4 (1?) bytes
Not my work. I merely report the work of another. I'm not even in a position to test the claim. Since a crucial part of this challenge seems to be finding an environment where this signal will be raised and caught, I'm not including the size of QEMU, Raspbian, or bash.
On Feb 27, 2013 8:49 pm, user [emlhalac](https://www.raspberrypi.org/forums/memberlist.php?mode=viewprofile&u=59462&sid=0e95d50056c1d75daa9a3183a3596b4e) reported "[Getting 'illegal instruction' when trying to chroot](https://www.raspberrypi.org/forums/viewtopic.php?p=298537)" on the Raspberry Pi fora.
```
ping
```
producing
```
qemu: uncaught target signal 4 (Illegal instruction) - core dumped
Illegal instruction (core dumped)
```
I imagine much shorter commands will produce this output, for instance, `tr`.
EDIT: Based on [@fluffy's comment](https://codegolf.stackexchange.com/questions/100532/shortest-code-to-throw-sigill/100628#comment244372_100628), reduced the conjectured lower bound on input length to "1?".
[Answer]
# x86 MS-DOS COM file, 2 bytes
**EDIT:** As pointed out in the comments, DOS itself will not trap the CPU exception and will simply hang (not just the app, the entire OS). Running on a 32-bit NT-based OS such as Windows XP will, indeed, trigger an illegal instruction signal.
```
0F 0B
```
From the [documentation](http://x86.renejeschke.de/html/file_module_x86_id_318.html):
>
> Generates an invalid opcode. This instruction is provided for software testing to explicitly generate an invalid opcode.
>
>
>
Which is pretty self-explanatory. Save as a .com file, and run in any DOS emulator DOS emulators will just crash. Run on Windows XP, Vista, or 7 32-bit.
[![SIGILL on Windows XP](https://i.stack.imgur.com/85VuO.png)](https://i.stack.imgur.com/85VuO.png)
[Answer]
# C (32-bit Windows), 34 bytes
```
f(i){(&i)[-1]-=9;}main(){f(2831);}
```
This only works if compiling without optimizations (else, the illegal code in the `f` function is "optimized out").
Disassembly of the `main` function looks like this:
```
68 0f 0b 00 00 push 0b0f
e8 a1 d3 ff ff call _f
...
```
We can see that it uses a `push` instruction with a literal value `0b0f` (little-endian, so its bytes are swapped). The `call` instruction pushes a return address (of the `...` instruction), which is situated on the stack near the parameter of the function. By using a `[-1]` displacement, the function overrides the return address so it points 9 bytes earlier, where the bytes `0f 0b` are.
These bytes cause an "undefined instruction" exception, as designed.
[Answer]
# Java, ~~50~~ ~~43~~ 24 bytes
```
a->a.exec("kill -4 $$");
```
This is a `java.util.function.Consumer<Runtime>`1 whose command is stolen from [fluffy's answer](https://codegolf.stackexchange.com/a/100678). It works because you *must* call it as `whateverNameYouGiveIt.accept(Runtime.getRuntime())`!
Note that this will create a new process and make it throw a SIGILL rather than throwing a SIGILL itself.
1 - Technically, it can also be a `java.util.function.Function<Runtime, Process>` because `Runtime#exec(String)` returns a `java.lang.Process` which can be used to control the process you just created by executing a shell command.
---
For the sake of doing something more impressive in such a verbose language, here's a ~~72~~ ~~60~~ 48-byte bonus:
```
a->for(int b=0;;b++)a.exec("sudo kill -s 4 "+b);
```
This one is another `Consumer<Runtime>` that goes through ALL processes (including itself), making each of them throw a SIGILL. Better brace for a violent crash.
---
And another bonus (a `Consumer<ANYTHING_GOES>`), which at least *pretends* to throw a SIGILL in 20 bytes:
```
a->System.exit(132);
```
[Answer]
# Perl, 9 bytes
```
kill+4,$$
```
Simply calls the appropriate library function for signalling a process, and gets the program to signal itself with `SIGILL`. No actual illegal instructions are involved here, but it produces the appropriate result. (I think this makes the challenge fairly cheap, but if anything's allowed, this is the loophole you'd use…)
[Answer]
# ARM Unified Assembler Language (UAL), 3 bytes
```
nop
```
For example:
```
$ as ill.s -o ill.o
$ ld ill.o -o ill
ld: warning: cannot find entry symbol _start; defaulting to 00010054
$ ./ill
Illegal instruction
```
After executing `nop`, the processor interprets the `.ARM.attributes` section as code and encounters an illegal instruction somewhere there:
```
$ objdump -D ill
ill: file format elf32-littlearm
Disassembly of section .text:
00010054 <__bss_end__-0x10004>:
10054: e1a00000 nop ; (mov r0, r0)
Disassembly of section .ARM.attributes:
00000000 <.ARM.attributes>:
0: 00001341 andeq r1, r0, r1, asr #6
4: 61656100 cmnvs r5, r0, lsl #2
8: 01006962 tsteq r0, r2, ror #18
c: 00000009 andeq r0, r0, r9
10: 01080106 tsteq r8, r6, lsl #2
```
Tested on a Raspberry Pi 3.
[Answer]
# Microsoft C (Visual Studio 2005 onwards), 16 bytes
```
main(){__ud2();}
```
I can't easily test this, but according to [the documentation](https://msdn.microsoft.com/en-us/library/aa983360(v=vs.80).aspx) it should produce an illegal instruction by intentionally trying to execute a kernel-only instruction from a user-mode program. (Note that because the illegal instruction crashes the program, we don't have to try to return from `main`, meaning that this K&R-style `main` function is valid. Visual Studio never having moved on from C89 is normally a bad thing, but it came in useful here.)
[Answer]
# Ruby, 13 bytes
```
`kill -4 #$$`
```
I guess it's safe to assume that we are running this from a \*nix shell. The backtick literals runs the given shell command. `$$` is the running Ruby process, and the `#` is for string interpolation.
---
Without calling the shell directly:
# Ruby, 17 bytes
```
Process.kill 4,$$
```
[Answer]
# ELF + x86 machine code, 45 bytes
This should be the smallest executable program on an Unix machine that throws SIGILL (due to Linux not recognizing the executable if made any smaller).
Compile with `nasm -f bin -o a.out tiny_sigill.asm`, tested on an x64 virtual machine.
Actual 45 bytes binary:
```
0000000 457f 464c 0001 0000 0000 0000 0000 0001
0000020 0002 0003 0020 0001 0020 0001 0004 0000
0000040 0b0f c031 cd40 0080 0034 0020 0001
```
Assembly listing (see source below):
```
;tiny_sigill.asm
BITS 32
org 0x00010000
db 0x7F, "ELF" ; e_ident
dd 1 ; p_type
dd 0 ; p_offset
dd $$ ; p_vaddr
dw 2 ; e_type ; p_paddr
dw 3 ; e_machine
dd _start ; e_version ; p_filesz
dd _start ; e_entry ; p_memsz
dd 4 ; e_phoff ; p_flags
_start:
ud2 ; e_shoff ; p_align
xor eax, eax
inc eax ; e_flags
int 0x80
db 0
dw 0x34 ; e_ehsize
dw 0x20 ; e_phentsize
db 1 ; e_phnum
; e_shentsize
; e_shnum
; e_shstrndx
filesize equ $ - $$
```
Disclaimer: code from the following tutorial on writing the smallest assembly program to return a number, but using opcode ud2 instead of mov:
<http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html>
[Answer]
# [AutoIt](http://autoitscript.com), 93 bytes
Using flatassembler inline assembly:
```
#include<AssembleIt.au3>
Func W()
_("use32")
_("ud2")
_("ret")
EndFunc
_AssembleIt("int","W")
```
When run in SciTE interactive mode, it'll crash immediately. The Windows debugger should popup for a fraction of a second. The console output will be something like this:
```
--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
0x0F0BC3
!>14:27:09 AutoIt3.exe ended.rc:-1073741795
```
Where `-1073741795` is the undefined error code thrown by the WinAPI. This can be any negative number.
Similar using my own assembler [LASM](https://www.autoitscript.com/forum/topic/173946-light-assembler-lasm-and-a-bunch-of-examples/):
```
#include<LASM.au3>
$_=LASM_ASMToMemory("ud2"&@CRLF&"ret 16")
LASM_CallMemory($_,0,0,0,0)
```
[Answer]
# Any shell (sh, bash, csh, etc.), any POSIX (10 bytes)
Trivial answer but I hadn't seen anyone post it.
```
kill -4 $$
```
Just sends SIGILL to the current process. Example output on OSX:
```
bash-3.2$ kill -4 $$
Illegal instruction: 4
```
[Answer]
# Python, 32 bytes
```
from os import*;kill(getpid(),4)
```
[Answer]
# NASM, 25 bytes
I don't know how this works, just that it does on my computer specifically (Linux x86\_64).
```
global start
start:
jmp 0
```
Compile & run like:
```
$ nasm -f elf64 ill.asm && ld ill.o && ./a.out
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
Illegal instruction
```
[Answer]
# TI-83 Hex Assembly, 2 bytes
```
PROGRAM:I
:AsmPrgmED77
```
Run as `Asm(prgmI)`. Executes the illegal 0xed77 opcode. I count each pair of hex digits as one byte.
[Answer]
# Linux shell, 9 bytes
```
kill -4 0
```
Sends `SIGILL` to the process with PID 0. I don't know what process has PID 0, but it always exists.
[Try it online!](https://tio.run/##S0oszvj/PzszJ0dB10TB4P9/AA)
[Answer]
# x86 .COM, 1 byte
```
c
```
`ARPL` causes `#UD` in 16-bit mode
[Answer]
# Rust, 53 bytes
```
fn main(){unsafe{std::hint::unreachable_unchecked()}}
```
This piece of code generates no `main` function because main is marked as unreached, hence SIGILL being triggered when run. [Try it online!](https://tio.run/##BcHBDcAgCADAVfrUFVimoYjBtPIQeBlnp3crzDO7XhOHlrpDDTtv8wYgQx0gdDGS4PPxHUrC9HIr9ZzMHw "Rust – Try It Online")
[Answer]
# GNU C, ~~24~~ ~~19~~ 18 bytes
-4 thanks to Dennis
-1 thanks to ceilingcat
```
main(){goto*&"'";}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7M6Pb8kX0tNSV3Juvb/fwA) This assumes ASCII and x86\_64. It attempts to run the machine code `27`, which ... is illegal.
---
# [shortC](//git.io/shortC), ~~10~~ ~~5~~ 4 bytes
```
AV"'
```
Equivalent to the GNU C code above. [Try it online!](https://tio.run/##K87ILypJ/v/fMUwpxuz/fwA)
[Answer]
# [MachineCode](//github.com/aaronryank/MachineCode) on x86\_64, ~~2~~ 1 bytes
```
7
```
[Try it online!](https://tio.run/##y01MzsjMS03OT0n9/9/I/P9/AA)
Simply calls the x86\_64 instruction `0x07` (ceilingcat suggested 0x07 instead of 0x27)
[Answer]
# MMIXAL, 13 bytes
`Main RESUME 2`
`RESUME` is legal in all code; `RESUME 1` throws a protection violation in user mode; any other argument throws an illegal instruction violation.
] |
[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/22877/edit).
Closed 7 years ago.
[Improve this question](/posts/22877/edit)
# Undefined Behavior Killed My Cat
It's well known that undefined behavior can kill your cat [citation needed].
But can it?
## Your Task
1. Write a program that invokes undefined behavior.
2. Describe a scenario that starts with the above program being run, resulting in a [*Felis catus*](http://en.wikipedia.org/wiki/Cat) ending its life while in your ownership, as a result of the aforementioned UB.
3. Estimate the probability for each stage in the scenario.
4. Calculate the total probability that a single run of the program would kill your cat.
## Rules
1. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so be creative if you can.
2. This is a programming related challenge, so the chain of events should be mostly within the computer, not in the real world (of course, if has to reach the real world if that's where your cat is).
3. If you choose a language that doesn't have undefined behavior, use something similar.
4. No animals may be harmed in the production of your answer.
## Scoring
Vote count plus the scenario's total probability (which can't exceed 1).
## Example in C:
```
main(){printf();}
```
Scenario:
1. `printf` called with garbage from the stack - undefined behavior. Probablity: 100%.
2. The first parameter happens to be the string `Your cat is ugly!`. Probablity: (1/256)17 = (1.148 \* 10-37)%.
3. Seeing the message, you pick up your gun and shoot your cat. Probability: 3%.
4. The cat dies. Probability: 93%.
Total probability: (3.202 \* 10-39)%.
[Answer]
# C
Most answers to this question misinterpreted the question in that it was killing the `cat` process on a UNIX system. Here is a program which can cause the demise of a biological lifeform of the species Felis Cattus as specificed by the question.
This example runs on Windows, but it could be easily ported to most UNIX operating systems by replacing `iexplore -k` with the command to launch an installed web browser.
```
#include <stdlib.h>
#include <stdio.h>
int main() {
char i; // uninitialised
printf("Redirecting you to a website which will inform you how to properly feed your cat.");
if (i != 42) {
system("iexplore -k https://pets.stackexchange.com/questions/tagged/cats+diet");
} else {
system("iexplore -k https://cooking.stackexchange.com/questions/tagged/chocolate");
}
return 0;
}
```
This program pretends to provide advise about cat diet to the user.
It will start Internet Explorer and direct the user to [pets stackexchange](https://pets.stackexchange.com/) listing lots of helpful questions about how to feed cats. There is, however, a low (1/256) chance that it will send the user to [cooking stackexchange](https://cooking.stackexchange.com/) instead listing tips how to prepare dishes containing chocolate, [which is **highly toxic** to cats](http://www.petmd.com/cat/conditions/digestive/c_ct_chocolate_toxicity). To make matters worse, it will launch internet explorer in kiosk mode (fullscreen), which hides the address bar and is hard to escape from for a non-tech-savy user.
This clever ruse will coax the user into feeding their cat chocolate believing that it is an appropriate diet for it, thus causing them to inadvertedly kill it.
[Answer]
# Bash
[According to this](http://blog.regehr.org/archives/887), `INT_MIN % -1` may or may not be undefined *(what ???)*, and so might cause trouble for any language implemented in c/c++.
```
#!/bin/bash
cat <<< $((2**63%-1))
```
The `cat` will be killed early if the parent `bash` process crashes, which may or may not happen.
On my VM I get this output:
```
$ ./schroedinger.sh
./schroedinger.sh: line 3: 7805 Floating point exception(core dumped) cat <<< $((2**63/-1))
$
```
---
*(I don't really understand the scoring for this question, but here goes anyway)*
Calculate `$((2**63%-1))`. Crash always happens on bash 4.2.25, but seems to just hang on some 3.x versions. More uncertainty. I could tell you the exact probability, but due to the Heisenburg uncertainty principle I would then fall down a black hole. Or something. So I think we can safely say they probability is approximately 42%.
[Answer]
# C (sequence point)
**deadcat.c:**
```
#include <stdio.h>
int main()
{
int i=3;
int k=0;
k=i+(++i);
if (k==7)
printf("The cat is fine. k=i+(++i) =%d\n",k);
else
printf("Urgent Notice: Your cat has rabies. k=i+(++i) =%d\n",k);
}
```
**Execution (or not):**
```
$ clang -w deadcat.c -o deadcat; ./deadcat
The cat is fine. k=i+(++i) =7
$ gcc deadcat.c -o deadcat; ./deadcat
Urgent Notice: Your cat has rabies. k=i+(++i) =8
```
**Scenario and probability**
Assuming that five percent of people running this program use clang for compiling C code (versus 90 percent using gcc and 5 percent using other C compilers):
```
Probability of getting "The cat is fine." = .050
Probability of getting "Urgent Notice: Your cat has rabies." = .950
Probability of reacting to "Your cat has rabies" by putting it down = .040
Probability of ignoring the notice = .900
Probability of taking the cat to the vet for treatment = .060
Total probability of cat living:.05 + .95 * (.90 + .06) = .962
Total probability of cat dying: .95 * .04 = .038
Check: Total probability of cat living or dying: = 1.000
```
**Explanation:**
k=i+(++i) accesses and changes "i" between sequence points.
The probability is not determinable by the program; it depends upon the
choice of compiler, which is made by the user. "Undefined" does not
necessarily mean "random".
See <https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points>
[Answer]
# C
### Backstory
My wife inherited a cat from family.† Unfortunately, I am very allergic to animals. The cat was well past its prime and should have been euthanized even before we got it, but she could not bring herself to get rid of it due to its sentimental value. I hatched a plan to end my its suffering.
We were going on an extended vacation, but she did not want to board the cat at the veterinarian's office. She was concerned about it contracting illness or being mistreated. I created an automatic cat feeder so that we could leave it at home. I wrote the microcontroller's firmware in C. The file containing `main` looked similar to the code below.
However, my wife is also a programmer and knew my feelings towards the cat, so she insisted on a code-review before agreeing to leave it at home unattended. She had several concerns, including:
* `main` does not have a standards compliant signature (for a hosted implementation)
* `main` does not return a value
* `tempTm` is used uninitialized since `malloc` was called instead of `calloc`
* the return value of `malloc` should not be cast
* the microcontroller time may be inaccurate or roll over (similar to the Y2K or Unix time 2038 problems)
* the `elapsedTime` variable may not have sufficient range
It took a lot of convincing, but she finally agreed that theses weren't problems for various reasons (it didn't hurt that we were already late for our flight). Since there was no time for live testing, she approved the code and we went on vacation. When we returned a few weeks later, my the cat's misery was over (though as a result I've now got plenty more).
† Entirely fictitious scenario, no worries.
---
### Code
```
#include <time.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
//#include "feedcat.h"
// contains extern void FeedCat(struct tm *);
// implemented in feedcat.c
// stub included here for demonstration only
#include <stdio.h>
// passed by pointer to avoid putting large structure on stack (which is very limited)
void FeedCat(struct tm *amPm)
{
if(amPm->tm_hour >= 12)
printf("Feeding cat dinner portion\n");
else
printf("Feeding cat breakfast portion\n");
}
// fallback value calculated based on MCU clock rate and average CPI
const uintmax_t FALLBACK_COUNTER_LIMIT = UINTMAX_MAX;
int main (void (*irqVector)(void))
{
// small stack variables
// seconds since last feed
int elapsedTime = 0;
// fallback fail-safe counter
uintmax_t loopIterationsSinceFeed = 0;
// last time cat was fed
time_t lastFeedingTime;
// current time
time_t nowTime;
// large struct on the heap
// stores converted calendar time to help determine how much food to
// dispense (morning vs. evening)
struct tm * tempTm = (struct tm *)malloc(sizeof(struct tm));
// assume the cat hasn't been fed for a long time (in case, for instance,
// the feeder lost power), so make sure it's fed the first time through
lastFeedingTime = (size_t)(-1);
while(1)
{
// increment fallback counter to protect in case of time loss
// or other anomaly
loopIterationsSinceFeed++;
// get current time, write into to nowTime
time(&nowTime);
// calculate time since last feeding
elapsedTime = (int)difftime(nowTime, lastFeedingTime);
// get calendar time, write into tempTm since localtime uses an
// internal static variable
memcpy(&tempTm, localtime(&nowTime), sizeof(struct tm));
// feed the cat if 12 hours have elapsed or if our fallback
// counter reaches the limit
if( elapsedTime >= 12*60*60 ||
loopIterationsSinceFeed >= FALLBACK_COUNTER_LIMIT)
{
// dispense food
FeedCat(tempTm);
// update last feeding time
time(&lastFeedingTime);
// reset fallback counter
loopIterationsSinceFeed = 0;
}
}
}
```
---
### Undefined behavior:
For those who don't want to bother finding the UB themselves:
>
> There's definitely local-specific, unspecified, and implementation-defined behavior in this code, but that all should work correctly. The problem is in the following lines of code:
>
>
>
>
>
>
---
### Probability of killing the cat:
* Given the constrained execution environment and build chain, the undefined behavior always occurs.
* Similarly, the undefined behavior always prevents the cat feeder from working as intended (or rather, allows it to "work" as intended).
* If the feeder does not work, it is extremely likely the cat will die. This is not a cat that can fend for itself, and I failed to ask the neighbor to look in on it.
I estimate that the cat dies with probability **0.995**.
[Answer]
# bash
### Classic version
```
cat & # This is your cat.
pkill -$RANDOM cat
```
Has the advantage of killing *all* cats in its range.
Note that the process is *stopped* immediately, so the only way to end it with a single invocation of *pkill* is to send SIGKILL (9).
Therefore:
`p(SUCCESS) = p(RANDOM == 9) = 0.0275 %`
---
### Quantum version
```
schroedinger=/dev/null # We'll need this guy.
heisenberg=/dev/urandom # Also needed, for uncertainty principle.
cat $heisenberg > $schroedinger & # Steal cat from Heisenberg and give it to Schrödinger.
felix=$! # Name cat for future references.
exec 2> $schroedinger # Send all results to Schrödinger.
kill -SIGSTOP $felix # Catch Felix and put him into a box.
if (($RANDOM & 1)) # Flip a coin.
then kill $felix # Heads: Kill! Kill! Kill!
fi # By now, Felix can be thought of as both alive and dead.
read -sn 1 # Wait for somebody to open the box.
kill -SIGCONT $felix # Let him open it.
if ps p $felix > $schroedinger # Let Schrödinger check on Felix.
then echo The cat is alive. # Hooray for tails!
else echo The cat is dead. # At least, now we know.
fi # This concludes the experiment.
kill -SIGKILL $felix # Felix is no longer required.
```
Probability of killing the cat during the experiment: 50 %
[Answer]
# C
Note that this only works on linux.
```
main() {
FILE *f = fopen("skynet", "w");
srand(time(0));
while(rand() != rand())
fputc(rand()%256, f);
fclose(f);
system("chmod +x skynet");
system("./skynet");
}
```
1. Write random data to a file and invoke it (100%)
2. Random data happens to be the source code to skynet (1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.)
3. Cat dies in resulting doomsday (99.999%)
Total probability: 1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.
[Answer]
# C++
Your Cat is Both Dead and Alive until you are Curious. Then you realize that there is a 0.5 probability that your Cat is Dead.
```
#ifdef WIN32
#pragma warning(disable: 4700)
#endif
#include <random>
#include <iostream>
#include <vector>
#include <climits>
#include <memory>
class Cat
{
public:
enum class State {DEAD, ALIVE};
Cat()
{
int x; // Uninitialized Variable on Stack
if (x % 2 == 0) // Is the Uninitialized Variable even? 50-50
{
m_dead = State::DEAD;
}
else
{
m_dead = State::ALIVE;
}
};
operator State() //Check if your Cat is Dead / Alive
{
if (m_dead == State::DEAD)
{
delete this; //Boom Cat is dead
std::cout<<"Your Curiosity killed your Cat"<<std::endl;
return false;
}
return m_dead;
}
private:
State m_dead;
};
class Schrödinger
{
public:
Schrödinger(size_t size):m_size(size)
{
for(size_t i = 0; i < size; i++)
{
cats.push_back(new Cat());
}
}
~Schrödinger()
{
}
void Curiosity()
{
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,m_size);
if(*cats[distribution(generator)] == Cat::State::ALIVE)
{
std::cout<<"You Cat is alive and still kicking" <<std::endl;
}
}
private:
std::vector<Cat *> cats;
size_t m_size;
};
int main()
{
int size;
std::cout<<"How Big is Your Example Space ?";
std::cin>>size;
Schrödinger your(size);
your.Curiosity();
return 0;
}
```
[Answer]
# C
Runs on Linux.
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(char x) {
if(sleep(1)==x) system("killall cat");
}
int main() {
char x; // uninitialised
system("cat /dev/urandom &");
f(x);
return 0;
}
```
Probability of killing the cat: 1/256 (The `sleep(1)` returns 0, so it will be killed if `x` is zero.)
As a bonus, it kills all cats currently running on your system.
---
If you hate cats so much, I present to you:
### The Cat Centipede (Bash)
```
echo "Hello World"|cat|cat|cat
```
Based on the fact that, in *The Human Centipede (First Sequence)*, all three dogs of the dog centipede died, and two out of three people of the human centipede died, I estimate that the probability of killing one cat is 5/6.
[Answer]
# JavaScript
```
~"cat".localeCompare("dead")
? "Cat is dead"
: "Cat is fine"
```
**Execution:**
* **Chrome:** Results in `"Cat is fine"`
* **Firefox:** Results in `"Cat is dead"`
**Explanation:**
>
> [15.5.4.9 String.prototype.localeCompare (that)](http://es5.github.com/#x15.5.4.9)
>
>
> The two Strings are compared in an **implementation-defined** fashion
>
>
>
Quoting Glenn Randers-Pehrson, the probability is not determinable by the program; it depends upon the choice of browser, which is made by the user.
[Answer]
```
int foo() {}
void main() {
int x = foo();
}
```
Reading a value of function supposed to return a value results in undefined behaviour. Now, it is obvious,[citation needed] that "Every time you reach undefined behaviour, God kills a kitty." Using this we conclude:
* Probability you reach undefined behaviour - 100%
* Probability it is your kitty which god killed - 1/200 000 000 [see why](http://answers.ask.com/science/nature/how_many_cats_are_in_the_world)
* So probability is 0.0000005%
Can be easily extended by loop to exterminate all cats in the world.
[Answer]
# Java (Garbage Collection)
Although code can invoke System.gc() is does not make sure that the Garbage Collector will collect all of the unused objects. Thus, for the following code, it's unpredictable if the cat will be killed or not.
```
public class KillTheCat {
public static void main(String[] args) throws InterruptedException {
KillTheCat cat = new KillTheCat();
cat = null;
System.gc();
System.out.println("Cat is still alive.");
}
@Override
protected void finalize() throws Throwable {
System.out.println("Cat has been killed.");
System.exit(0);
}
}
```
The probability cannot be calculated.
Note that there's still a chance that the cat will be "revived" if there's a context switch in the GC thread after sysout and before System.exit(0) but I preferred not to cover it to keep the concept simpler.
[Answer]
# C
If your cat's name is too long, it dies. `gets` causes cat deaths, along with other problems.
```
#include <stdio.h>
#include <stdbool.h>
/* Stores instances of cats. */
struct cat {
/* 6 bytes are more than enough. */
char name[6];
/* Stores whether your cat is dead. */
bool dead;
};
int main(void) {
/* This is your cat. */
struct cat your_cat;
/* It lives. */
your_cat.dead = false;
/* Determine its name. */
printf("Your cat name: ");
gets(your_cat.name);
/* Output the cat state. */
const char *state = your_cat.dead ? "dead" : "alive";
printf("Your cat, %s, is %s.\n", your_cat.name, state);
return your_cat.dead;
}
```
[Answer]
Anybody having thought of really killing (a) `cat`?
```
[ $[ $RANDOM % 6 ] == 0 ] && rm /bin/cat || echo Meow
```
### Probabilitiy of `cat` dying
For the probability... I guess we need to distinguish some cases:
1. **Windows user**: Probably will not be able to execute it. Chance of dying `cat`s is very low, can safely be assumed to be zero. If he's got Cygwin installed, he'll count as unix user.
2. **Unix user, running without root privileges**: Killing the `cat` will fail.
3. **Unix user, running with root privileges**: While each call will only kill `cat`s with a chance of 1/6, he will very probably repeat it until something unexpected occurs. Without loss of generality, I assume `cat` will definitely die.
Overall probability depends on how the users are mixed and is hard to determine. But we can surely say: Windows is a safe place for kittens.
### Testing for obedience of the rules
>
> No animals may be harmed in the production of your answer.
>
>
>
This did not kill animals, the answer is approved by the *American Humane Association*.
```
$ file `which cat`
/bin/cat: Mach-O 64-bit executable x86_64
```
clearly proves that `cat` is no animal (as long `file` does not know any kind of hidden file type inheritance).
[Answer]
## Haskell
```
import Acme.Missiles
import System.IO.Unsafe
main = print (unsafePerformIO launchMissiles, undefined)
```
Here, we apply [`unsafePerformIO`](http://hackage.haskell.org/package/base-4.6.0.1/docs/System-IO-Unsafe.html#v:unsafePerformIO) to [an action that has observable side-effects](http://hackage.haskell.org/package/acme-missiles-0.3/docs/Acme-Missiles.html#v:launchMissiles). That is always undefined behaviour, at least so is the order of effects. So either will the program first crash on trying to evaluate [`undefined`](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:undefined) (that one, ironically, is *not* undefined behaviour: it must never yield a value that would allow the program to carry on with something else), or it will in fact incur the serious international side-effects. In that case, survival chance is [only 0.001%](https://codegolf.stackexchange.com/a/22884/2183).
Probability of killing the cat thus: 49.9995%.
[Answer]
# Thue
Since the question allows for a language that doesn't have undefined behavior as long as the effect is similar, I choose Thue for its **non-determinism** in choosing which rule to execute when there are more than 1 rule which can be applied on the current state.
The program will be fed into the controller for a microwave oven, inside of which is my cat. The door to the microwave oven is closed and reinforced by a zip tie. The output of the program will decide whether the microwave oven starts to microwave the cat or not.
* If the output is 0, we will start the experiment on the effect of long exposure of microwave on live mammal (which is currently insufficiently researched).
* If the output is 1, we will just be satisfied with the fact that the cat has just lost one of its 9 lives and let it out.
---
```
i::=~0
i::=~1
::=
i
```
The probability of killing the cat is dependent on the implementation of the interpreter, but let's say it's 50%. Then the probability that the cat will die is **0.5**.
[Answer]
## Java
According to [spec](http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html#Date%28int,%20int,%20int%29 "spec") `java.util.Date` will have undefined behaviour. So try your luck:
```
import java.util.Date;
public class App3
{
public static void main (String args[])
{
String aliveOrDead;
Date d = new Date(-1000,-1000,-1000);
aliveOrDead = (d.getTime()<0)? "dead" : "alive";
System.out.println("The cat is:" +aliveOrDead );
}
}
```
] |
[Question]
[
My dog is called Rex. Every time I scold him, he seems not very impressed and the only times I see him react is when I pronounce his name. If I say
`Rex, I told you not to do this! You're making me angry Rex!`
all he hears is
`Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!`
**The challenge** : given an input string, your program must output the same string where all alphabetic characters have been turned to stars, except the characters in the appearances of the word `Rex`, who must be left untouched. The non-alphabetic characters are also left untouched.
**Details** : The challenge is case-insensitive, thus `rex` must be left untouched also. The word `Rex` can be part of another word, so for example `anorexic` must be rendered as `***rex**`.
**Update** : as the initial text of this challenge did not clarify how underscores or numbers or accentuated characters should be treated, I do not make any special requirement on those characters. Thus, a solution is valid as long as characters in `a-zA-Z` (and also the one mentioned in the examples, `,!".`) are handled correctly.
Test cases :
Input : `Rex lives in Rexland.`
Output : `Rex ***** ** Rex****.`
Input : `To call Rex, just say "Rex".`
Output : `** **** Rex, **** *** "Rex".`
Input : `My cat is getting anorexic.`
Output : `** *** ** ******* ***rex**.`
[Answer]
## \*\*REXX ~~151~~ ~~148~~ 141 bytes \*\*
(Kinda seemed appropriate)
```
i=arg(1)
m=i
o=translate(m,'',xrange('A','z'),'*')
p=0
do forever
p=pos('REX',m,p+1)
if p=0 then leave
o=overlay(substr(i,p,3),o,p)
end
say o
```
[Try it here](https://www.tutorialspoint.com/execute_rexx_online.php "Try it here")
Notes for non-REXXers:
1. translate is a character replacement function (name comes from an assembler instruction on IBM MF). It searches string1 for the characters in string3. Every time it finds one it replaces it with the same positioned one in string2. If string2 is too short it is padded with the pad character.
[See here for translate function](http://www.rexxinfo.org/html/functions.html#translate)
2. overlay simply overlays the string1 on top of string2 at the specified position.
[See here for overlay function](http://www.rexxinfo.org/html/functions.html#overlay)
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~24~~ 21 bytes
```
i`(rex)|(\w)
$1$#2$**
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/ifmaBRlFqhWaMRU67JpWKoomykoqX1/39QaoVCTmZZarFCZp4CkJOTmJeixxWSr5CcmJMDEtBRyCotLlEoTqxUUAJylfS4fCuBkiUKmcUK6aklJZl56QqJeflAszOT9QA "Retina – TIO Nexus")
### Explanation
Skipping `rex`s is easiest by matching them as well, because matches can't overlap. So if we give priority to `rex` over other letters, those will be covered in a single match and not touched by the individual-letter matches.
But how do we do different things depending on the alternative that was used for the match? Unfortunately, Retina doesn't (yet) have any conditional substitution syntax like the Boost regex flavour. But we can fake it by including both substitutions in a single replacement and making sure that only one of them is non-empty:
* `$1` is the first capturing group, i.e. the `(rex)`. If we did match `rex` this simply writes it back (so it does nothing), but if we didn't match `rex` then `$1` is an empty string and vanishes.
* `$#2$**` should be read as `($#2)$*(*)`. `$#2` is the number of times group `2` was used, i.e. the `(\w)`. If we matched `rex` this is `0`, but if we matched any other individual letter, this is `1`. `$*` repeats the next character as many times as its left-hand operand. So this part inserts a single `*` for individual-letter matches and nothing at all for `rex`.
[Answer]
# JavaScript (ES6), ~~42~~ ~~41~~ 38 bytes
```
s=>s.replace(/rex|\w/gi,m=>m[1]?m:"*")
```
---
## Try It
```
o.innerText=(f=
s=>s.replace(/rex|\w/gi,m=>m[1]?m:"*")
)(i.value="Rex, I told you not to do this! You're making me angry Rex!")
oninput=_=>o.innerText=f(i.value)
```
```
<input id=i><pre id=o>
```
---
## Explanation
```
s=> :Anonymous function that takes the string as an argument via parameter s.
s.replace(x,y) :Replace x in s with y.
/rex|\w/gi :Case-insenstive regular expression that globally matches all occurrences
of "rex" or any single letter, number or underscore.
(numbers & underscores will never be included in the input.)
m=> :Anonymous function that takes each match as an argument via parameter m.
m[1]? :If string m has a second character, ...
(Equivalent to m.charAt(1))
m :Return m, ...
:"*" :Otherwise return "*".
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [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")
```
'rex' '\w'⎕R'\0' '*'⍠1
```
[Try it online!](https://tio.run/nexus/apl-dyalog#PY4xDoJAEEV7T/GhmcQYorfQwobYmNBMYIOry27CDspewE5jY@/ZuAguJlK@/Df/z7hV3A73F7WqJ1Bxo@H5zqlYR1jS8PhsxnFSQLnqV9hBnKkQXAfrJAIqBzlpn@DoOootaPiibY1GgW3dBsS7hBZzB4y@Kg9tp8CwrbJ/eHAo2Rj8hs6dF3gOSCOms7MP0RFoj1qJTDtsXXxdlxl9AQ "APL (Dyalog Unicode) – TIO Nexus")
Simple PCRE **R**eplace.
`⍠1` sets case insensitivity. Simply replaces `rex` with itself and all other word characters with asterisks.
[Answer]
# [Perl 5](https://www.perl.org/), 24 bytes
23 bytes of code + `-p` flag.
I used Martin Ender's regex from his [Retina answer](https://codegolf.stackexchange.com/a/119734/55508) (which happens to be shorter in Perl, thanks to `\pl`), and only had to adapt the right side of the s///.
```
s%(rex)|\pl%$1//"*"%gie
```
[Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@sqlGUWqFZE1OQo6piqK@vpKWkmp6Z@v9/UGqFQnJiiUJmsUJ6aklJZl66QmJePlBtZrIeAA "Perl 5 – TIO Nexus")
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~32~~ 31 bytes
```
iS`(rex)
%iT`Ll`*`^(?!rex).*
¶
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/ifGZygUZRaocmlmhmS4JOToJUQp2GvCBLR0@I6tI3r//@g1AqFnMyy1GKFzDwFICcnMS9FjyskXyE5MScHJKCjkFVaXKJQnFipoATkKulx@VYCJUsUMosV0lNLSjLz0hUS8/KBZmYm6wEA "Retina – TIO Nexus") Explanation: Splits the string into occurrences of the word `rex` and everything else, but keeps the matches. Then, on lines that don't begin `rex` (i.e. the "everything else"), change letters to `*`s. Finally, join everything back together.
[Answer]
## C, ~~99~~ ~~97~~ ~~92~~ ~~86~~ ~~74~~ ~~73~~ ~~72~~ 65 bytes
```
f(char*s){*s&&f(s+=strnicmp("Rex",s,3)?!isalpha(*s)||(*s=42):3);}
```
Pelles IDE environment provides (compile with /Go) the function strnicmp. This function is identical to strncasecmp. See it [work here](https://tio.run/nexus/c-gcc#jZBNbsIwEIX3nOI1C2STqEXQbppGPUE3VXcBVVbigKvgRBkHQUPOntoWLSD1bxaj8Ty/z@MZCpatRTMh3k1oPC4YhQmZRmeCZLapWfAsd0FE0Zw/XikSZb0WzF4@HGxObmf8fs7jflDaYCOUZthWKgcfdSPYcGTkwoh0mc7upksk6OCVH6KDew@l2kqC0rCHUuj8OkCP6A/jS4VMlKXzRHhryYDEHgsHXAT/IjztLcFAEVbSGKVXELpq5E5lv9t7xF7yya3Cffk1q1pbJiD1LquC@SY4bi4aqV0KP7cXVcM8Q@ncbiLBFPGxfjjnHpthaJftx/8a7pPs9RPdRd0a@l7tTxOM@uED) (with the replacement function).
The output is stored in the first parameter which is an in/out parameter.
Thanks to [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit) for letting me know that recursion is slightly shorter.
[Answer]
# Ruby, ~~36~~ ~~35~~ 32 bytes
```
->s{s.gsub(/(rex)|\w/i){$1||?*}}
```
As a test:
```
f=->s{s.gsub(/(rex)|\w/i){$1||?*}}
tests = [
["Rex, I told you not to do this! You're making me angry Rex!", "Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!"],
["Rex lives in Rexland.", "Rex ***** ** Rex****."],
["To call Rex, just say \"Rex\".", %q(** **** Rex, **** *** "Rex".)],
["My cat is getting anorexic.", "** *** ** ******* ***rex**."]
]
tests.each do |input, output|
if f.call(input) == output
puts "Fine for #{input.inspect}"
else
puts "Problem with :\n#{input.inspect}"
puts f.call(input)
puts output
end
puts
end
```
It outputs:
```
Fine for "Rex, I told you not to do this! You're making me angry Rex!"
Fine for "Rex lives in Rexland."
Fine for "To call Rex, just say \"Rex\"."
Fine for "My cat is getting anorexic."
```
[Answer]
# PHP, 78 Bytes
```
<?=preg_replace("#[a-df-qs-wyz]|r(?!ex)|(?<!r)e|e(?!x)|(?<!re)x#i","*",$argn);
```
[Try it online!](https://tio.run/nexus/php#NY9BT4NAEIXv/Ipha8JigD8AysH00IOamF5M2zQbmMLqdhdnFwVF/zouNR7fvHlf3ivKru0CJDJ0JOwMOakb/rM@PjxuN3frOA9OhlBULd@xJxwS2IAzqobR9KCN8wJqA66VNoRn00eEcBavngFnBKEbGsHHQpYESxyUfEcLUi9HJXSdeSPaGqiEUnDhv/TWgRUjLP8si3zwfvS@A2mhQbf082BfapBVxg7CXglqdPxV3s5FedMRNssQJSrkbLUTaX1K32z6MX4eJuJliEM88bIIKcYJvf6XGA8ryRJ2zZI/YD5j1Rq213vN8u/5Fw "PHP – TIO Nexus")
# PHP, 84 Bytes
```
<?=preg_replace_callback("#(rex)|\pL#i",function($t){return$t[1]?$t[1]:"*";},$argn);
```
-1 Byte `\w` instead `\pl` in this case underscore and numbers are replaced too
`\pL` is shorter as `[a-z]` or `[[:alpha:]]`
[Try it online!](https://tio.run/nexus/php#JY9Na8MwDIbv@RWqG0gyQmDXpVsOo4fCPmD0MpoSPEdNvLp2kJ3R0G1/PbO7i0Dvx4O0qoZ@iJDIUEM4GHJSd@nvunl53W4e11kZHQwhF326Y294zmEDzqgWJjOCNs4v0BpwvbQLeDdjQggnfvQMOCFw3dEEvrZgeRTqoOQXWpA6iIrrtvBGsjUguFJw5X@O1oHlE4Q8KxJffJ6870Ba6NCF@zzYH3WWomB7bmNOnc4u1cO8qu4Hwi48orjAJlA/uDimbJn6fPZdD09LyfLDqIWTRqexyy6EbiQdu93tvrrOO3bDyp/8H1vOKHrDal1rL85/ "PHP – TIO Nexus")
[Answer]
# C (GCC on POSIX), ~~167~~ ~~118~~ ~~93~~ 87 bytes
```
i,j;f(char*s){for(i=0;j=s[i];i++)strncasecmp("Rex",s+i,3)?s[i]=isalpha(j)?42:j:(i+=2);}
```
[Try it online!](https://tio.run/nexus/c-gcc#LY7NCsIwEIRfZfGU2LT4dzIEn8CLeBMPS0x1Q0xLNxZF@uyxLd5mdoZvJ5Pyuhb2gd2S5bduOkFmpb3hC101FYXk1EWL7OyzFYuTey8UF6S28jA1DDGG9oHCy8Nus/d7QYXZSD3kJ1IUVvVyRi97PbO1LctyrcdHor/Yq9TtK/FfDkPOIx8C9Y6BIowmYLxV@dyAxRCmgwL/4gSMH5jHVPn4GcMExHB3KVG8A8amc2@y1Q8 "C (gcc) – TIO Nexus")
[Answer]
# Python 2 or 3, ~~75~~ ~~73~~ 70 bytes
```
import re;f=lambda s:re.sub('(?i)(rex)|\w',lambda x:x.group(1)or'*',s)
```
Basically the same as my Ruby's [answer](https://codegolf.stackexchange.com/questions/119718/what-my-dog-really-hears/119755#119755).
-2 bytes thanks to @Wondercricket.
As a test:
```
tests = [
["Rex, I told you not to do this! You're making me angry Rex!", "Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!"],
["Rex lives in Rexland.", "Rex ***** ** Rex****."],
["To call Rex, just say \"Rex\".", "** **** Rex, **** *** \"Rex\"."],
["My cat is getting anorexic.", "** *** ** ******* ***rex**."]
]
for test_in, test_out in tests:
print(test_in)
print(f(test_in))
print(f(test_in) == test_out)
```
[Answer]
# Java 8, ~~187~~ ~~192~~ ~~168~~ ~~164~~ ~~159~~ 138 bytes
```
s->{for(int i=0;i<s.length();System.out.print(s.regionMatches(0<1,i,"rex",0,3)?s.substring(i,i+=3):s.replaceAll("\\w","*").charAt(i++)));}
```
-28 bytes thanks to @OlivierGrégoire.
**Explanation:**
[Try it online.](https://tio.run/##jZAxb8IwEIV3fsXJk12MRcXWQCt@AAylW9PBNSYcNU6UcygI5benlzRTp0r2cLbed@@9k73YWVn5eNp/dS5YIthYjPcJAMbk64N1Hrb9CHApcQ9O7lKNsQBSGb@2fPlQsgkdbCHCCjqaPd8PZS2ZALiaZ7gkE3ws0lGqbHej5M@mbJKpGJQkmdoXWMaNTe7oSc6Xjxq1qP1V6LleqBcy1HzSsFWixulqoZ56URXY3DoEKfL8W2jxIJRxR1uvk8TpVCmVtV02YXdV8xnY3WhyiHHmkGOS9w@w6jdhNE6KV3@FgBdP3ADwEGzcGzGkBfjrPkQ5/gzatxKcDaGXaTg1lIDsDfKemYv/QjY3hnBzBIVPqe/axpLrQDcS2knb/QA)
```
s->{ // Method with String parameter and no return-type
for(int i=0;i<s.length(); // Loop over the characters of the input-String
System.out.print // Print:
s.regionMatches(1>0,i,"rex",0,3)?
// If we've found "rex" (case-insensitive):
s.substring(i,i+=3) // Print this REX-word (case-sensitive)
: // Else:
s.replaceAll("\\w","*").charAt(i++));
// Print the current character,
// or '*' if it's an alpha-numeric character
```
[Answer]
## Python 2, 87 Bytes
```
import re
print re.sub(r'(?i)[a-df-qs-wyz]|r(?!ex)|(?<!r)e|e(?!x)|(?<!re)x','*',input())
```
I guess that can be shortened? :)
[Answer]
# [sed](https://www.gnu.org/software/sed/), 37 33 bytes
36 bytes sourcecode + 1 byte for -r flag.
```
s:(rex)|\w:\1*:Ig
s:(rex)\*:\1:Ig
```
[Try it online!](https://tio.run/nexus/sed#LY7BCsIwEETv@YqxF7VowWv/oAcv4kXoJbShRtOsJFttwG83bsXLwHvLDpNjvQlm3r7bV90eyroZ1N@0pQjhnE9m3qEBk@uRaIInFkBP4KuNK1xoWgeDUd@tHzAaaD@EBHlbKQk4@zQR1i/Gad9X6kzotHP4Nd@myIg6oRAsKnVMcmTYiMEwL5XakyyyXfWhB1vyMe/DFw "sed – TIO Nexus")
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), ~~11~~ 10 + 1 = 11 bytes
+1 byte for the `i` flag.
```
rex
\w
&
*
```
[Try it online!](https://tio.run/##HY6xDsIwEEP3fIXbASSE8h8MLIgFieXUROUgzYnkAs3Xh5TF0rNly@9CLrWW/GruX7Mzh9Yufj3iBJXgUKUginaAE@iD84CblH3yWOjFccbiQXFOFb02mC4I/PEZHDcnUHTWXAUThYD/8rNkRaaKseNozbn2UMEZs1fdJilK/8OTbfwD "QuadR – Try It Online")
Explanation: Case-insensitively replace `rex` and word-chars with itself and asterisks, respectively.
[Answer]
# Gema, 25 characters
```
/[rR][eE][xX]/=$0
<L1>=\*
```
Sample run:
```
bash-4.3$ gema '/[rR][eE][xX]/=$0;<L1>=\*' <<< "Rex, I told you not to do this! You're making me angry Rex!
Rex lives in Rexland.
To call Rex, just say \"Rex\".
My cat is getting anorexic."
Rex, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!
Rex ***** ** Rex****.
** **** Rex, **** *** "Rex".
** *** ** ******* ***rex**.
```
Painful fact that could be `\CRex=$0;<L1>=\*`, but unfortunately `$0` contains the template, not the match. ☹
[Answer]
## PowerShell, 60 bytes
```
{$args|%{$_-replace'(rex)|\p{L}','$1*'-replace'(x)\*','$1'}}
```
[Try it online](https://tio.run/nexus/powershell#RY/BCsIwEETvfsVYoqulCn6AHyDoRbwIhRLbUKNpIkkqLW2/vaa9eFpmHjs7yx7HsWPclq5fdSzbWfFRPBe0saLZ9umnOw@UEDvE9EfNNo1nk4ZhjK6iSXCCN6pAa2po44NAYeCf0i1xNzVZgYq/pS5RCXBd2hZhbRklCwoTSn6Fg9STqbgu9hTAzSDnSmHOf9XOw/EW07lo5pc2cA/pUArvp2yuTWgt8z2FX9bsAZYN4w8)
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~54~~ ~~50~~ 49 bytes
*Golfed 5 bytes thanks to @MartinEnder*
```
i(`[\w-[rex]]
*
(?<!r)e|e(?!x)|r(?!ex)|(?<!re)x
*
```
[Try it online!](https://tio.run/nexus/retina#HY7BCsIwEETv@YqpILai/QKhR/HgRbyIFhrapUbTBJJUE/Df67aXHeYts7Pr/NhMKm/uj@/@7ijWtdiKvDpkrqAf5VUWi59jIdYFUxHFdpouFHc4IVjdIdkRxgY26CzCU/kMNztuHGGQb2V6DARpepfAsUzwgFYf8lBmJlqarkTHlKK4WrRSaywFr9EHeJmwYrsqxTnxMkB59BTCfFkay1@rtvwD "Retina – TIO Nexus")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 24 bytes
```
42y3Y2mFGk'rex'Xf!3:q+((
```
The input is a string enclosed in single quotes.
[Try it online!](https://tio.run/nexus/matl#@29iVGkcaZTr5p6tXpRaoR6RpmhsVaitofH/v3pQaoVCTmZZarFCZp4CkJOTmJeipxCSr5CcmJMDEtBRyCotLlEoTqxUUAJylfQUfCuBkiUKmcUKfv4hCumpJSWZeekKiXn5QLMzk/XUAQ "MATL – TIO Nexus")
### Explanation
Consider input `'Rex lives in Rexland.'`
```
42 % Push 42 (ASCII for '*')
% STACK: 42
y % Implicit input. Duplicate from below
% STACK: 'Rex lives in Rexland.', 42, 'Rex lives in Rexland.'
3Y2 % Push string 'ABC...YZabc...yz'
% STACK: 'Rex lives in Rexland.', 42, 'Rex lives in Rexland.', 'ABC...YZabc...yz'
m % Ismember
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0]
F % Push false
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0
Gk % Push input lower-cased
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0, 'rex lives in rexland'
'rex' % Push this string
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0, 'rex lives in rexland', 'rex'
Xf! % Strfind and transpose: gives indices of matchings as a column vector
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0, [1; 14]
3:q % Push [0 1 2]
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0, [1; 14], [0 1 2]
+ % Addition, element-wise with broadcast
% STACK: 'Rex lives in Rexland.', 42, [1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0], 0, [1 2 3; 14 15 16]
( % Assignment indexing: sets indicated entries to 0
% STACK: 'Rex lives in Rexland.', 42, [0 0 0 0 1 1 1 1 1 0 1 1 0 0 0 0 1 1 1 1 0]
( % Assignment indexing: sets indicated entries to 42 (that is, '*'). Implicit display
% 'Rex ***** ** Rex****.'
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ 92 bytes
```
f=lambda s:s and("rex"==s[:3].lower()and s[:3]+f(s[3:])or("*"+s)[s[0].isalpha()<1]+f(s[1:]))
```
[Try it online!](https://tio.run/nexus/python2#Jc1BCsMgEEDRqwyuZhqQhuykHqEnEBc20VSwGhwh7emttNvPg9@DTu712BywYnB5Q1H9W2jNRi1WpnL6ijQ6/MIUkM2iLJWK4iImJsPmamVkl46nQ7rNfzMPQ/2oMTcIKO4fWF2DyLD71mLex6qMUVyloP4F "Python 2 – TIO Nexus")
[Answer]
# Perl, 31 bytes
```
s/(rex)|[a-z]/$1||"*"/ieg;print
```
Invoke perl with `-n` option. For example:
```
echo 'To call rex, just say "Rex".'| perl -ne 's/(rex)|[a-z]/$1||"*"/ieg;print'
** **** rex, **** *** "Rex".
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 128 bytes
```
r=REXrex;a=`tr -c $r'",. !
' l<<<$1`;for i in {r,R}{e,E}{x,X};{
a=`echo ${a[@]//$i/$(tr $r f-k<<<$i)}`;}
tr $r l<<<$a|tr f-l $r*
```
[Try it online!](https://tio.run/nexus/bash#JYxBC4IwGIbv/orXGFgxk84qdOnQ1VMRgUNXjnSDrwXG2s/ubLOO7/PyPBOV1f5IcsxFWVtC2oBRsuAbxFGCvigKtq3zqyEoKA1HvPJO8r13Iz/63EVBk01nwJw47y5ZxlTGliHECNf0Pvtq5evcR3/2K4q3nd8@gPU0TZUcOQ6wpm/xMk9oY8NAa2A79YhxMs@EJAZxV/qGQULoG70QtPijTdqIppNf "Bash – TIO Nexus")
I'm sticking to tr on my previous answer, non-functional bash array string replace and no preg replace!
Less golfed:
```
a=`echo $1 |tr -c 'REXrex.,\"! ' 'z'`; -> a replaces with z chars in input not matching REXrex or punctuation
for i in {r,R}{e,E}{x,X}; { -> iterates over rex .. rEx .. REX
j=$(tr 'REXrex' 'ABCabc' <<<$i)} -> holds a for r, A for R, ando so on
a=`echo ${a[@]//$i/$j`; -> replace each combination of rex .. rEx .. REX with abc ... aBc.. ABC
}
tr 'REXrex' 'z' <<<$a |tr 'ABCabcz' 'REXrex*' -> replaces each remainig r,e,x,R,E,X with z and finally each ABC with REX and z with *
```
Had to use z instead of \* because of expansion
[Answer]
## C#, ~~93~~ 90 bytes
```
s=>System.Text.RegularExpressions.Regex.Replace(s,"(?i)rex|\w",m=>m.Length>1?m.Value:"*");
```
Believe this is the first time I've used a regex in a C# answer here because of the long namespace `System.Text.RegularExpressions`.
---
Didn't realise it when I wrote my answer but this seems to be the C# version of [@Shaggy's JavaScript answer](https://codegolf.stackexchange.com/a/119742/38550).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 39 bytes
```
q{_3<_el"rex"=3{elc_'{,97>&'*@?1}?\o>}h
```
[Try it online!](https://tio.run/nexus/cjam#@19YHW9sE5@ao1SUWqFka1ydmpMcr16tY2lup6au5WBvWGsfk29Xm/H/f1BqhY6Cp0JJfk6KQmV@qUJefgmQo5CSr1CSkVmsqBCZX6pelKqQm5idmZeukJuqkJiXXlSpANSmCAA "CJam – TIO Nexus")
**How it works**
```
q e# Read the input.
{ e# Do:
_3< e# Copy the string and get its first three characters.
_el"rex"= e# Check case-insensitively if they equal "rex".
3 e# If they do, push 3.
{ e# If they don't:
elc_ e# Take the first character of the three, and make it lowercase.
'{,97>& e# Take its set intersection with the lowercase alphabet. Returns a non-empty
e# string (truthy) if it's a letter or an empty string (falsy) if not.
'*@? e# Push a * if the char is a letter, or itself if it's not.
1 e# Push 1.
}? e# (end if)
\o e# Print the second-from-the-top stack item.
> e# Slice the string after the first 3 or 1 characters, depending on previous outcome.
}h e# Repeat the above until the string is empty.
```
[Answer]
# VimScript, 34 bytes
```
s/\v(rex|r@<=ex|(re)@<=x)@!\w/*/gi
```
And here's an interesting substitution that almost works:
```
s/\vr(ex)@!|<e|<x|[rex]@!\w/*/gi
```
Imagine running this repeatedly on the string `Rex, dex, I told you not to do this! You're making me angry Rex!` After the first line, the string is `Rex, *ex, * **** *** *** ** ** ****! ***'*e ****** *e ***** Rex!` The second pass will result in `Rex, **x, * **** *** *** ** ** ****! ***'** ****** ** ***** Rex!`, and the third pass will finish it. Any subsequent passes will not change the string. However, it could take more than 3 substitutions to get there, for example on string `xxxxxxxx`. So, if there were an easy way to run the above substitution until it stopped changing things, or as many times as the length of the input, that would be another solution. I bet it could be done in V, but it would still probably be longer than 34 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/CodePage)
*No response in over 24 hours to [my question regarding case](https://codegolf.stackexchange.com/questions/119718/what-my-dog-really-hears?answertab=votes#comment293505_119718), so I'll post this tentative 23 byter.*
```
“rex”
Œlœṣ¢µØaW;”*yµ€j¢
```
See the test cases at **[Try it online!](https://tio.run/nexus/jelly#@/@oYU5RasWjhrlcRyflHJ38cOfiQ4sObT08IzHcGiioVXlo66OmNVmHFv0/uudwO5AZCeI@atz@cMeSQ0v@/49WD0qtUMjJLEstVsjMUwBychLzUvTUdRTUQ/IVkhNzckBiOgpZpcUlCsWJlQpKQK4SWN63EihfopBZrJCeWlKSmZeukJiXD3RLZrKeeiwA)**
### How?
```
“rex” - Link 1, get "rex": no arguments
“rex” - literal "rex"
Œlœṣ¢µØaW;”*yµ€j¢ - Main link: string s (or list of characters)
Œl - convert s to lowercase
¢ - call the last link (1) as a nilad (get "rex")
œṣ - split left (s) at sublists equal to right ("rex")
µ - call the result t
µ€ - for each word, w, in t:
Øa - literal: lowercase alphabet
W - wrap it in a list
”* - literal: '*'
; - concatenate the wrapped alphabet with the asterisk
y - translate: replace all lowercase letters with asterisks.
¢ - call the last link (1) as a nilad (get "rex")
j - join left (translated, split text) with copies of right ("rex")
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 26 bytes (uppercase output) / 36 bytes (case-preserving)
```
qeu"REX":R/{__el-'*@?}f%R*
```
[Try it online!](https://tio.run/nexus/cjam#@1@YWqoU5BqhZBWkXx0fn5qjq67lYF@bphqk9f9/UGqFjoKnQkl@TopCZX6pQl5@CZCjkJKvUJKRWayoEJlfql6UqpCbmJ2Zl66Qm6qQmJdeVKkA1KYIAA "CJam – TIO Nexus")
If letter case needs to be preserved (since [that's still a little bit unclear](https://codegolf.stackexchange.com/questions/119718/what-my-dog-really-hears#comment293505_119718)), that can be accomplished with 10 extra bytes:
```
q_32f&:i\eu"REX":R/{__el-'*@?}f%R*.|
```
[Try it online!](https://tio.run/nexus/cjam#@18Yb2yUpmaVGZNaqhTkGqFkFaRfHR@fmqOrruVgX5umGqSlV/P/f1BqhY6Cp0JJfk6KQmV@qUJefgmQo5CSr1CSkVmsqBCZX6pelKqQm5idmZeukJuqkJiXXlSpANSmCAA "CJam – TIO Nexus")
By the way, while writing this answer, I found what I would consider to be a design bug in CJam: the bitwise operators `&` and `|` are not defined between two char values, so I can't use `.|` to take the bitwise OR of two strings. The solution, which ended up costing me two extra bytes, is to first convert one of the strings with `:i` into an array of integers, which then can be ORed with the other string. (Actually it cost me *three* bytes, because if `&` worked between two chars, I could've also used `Sf&` instead of `32f&` to save the letter case information.)
On the positive side, I did discover that `{...}f%` indeed works as expected for iterating over the characters in an array of strings. Nice.
Anyway, here's a (lightly) commented version of the 36-byte code:
```
q "read input";
_32f&:i\ "save the case bit of each input char";
eu"REX":R/ "uppercase input and split it on 'REX'";
{ "start code block:"
__el-'*@? "c = (c != lowercase(c) ? '*' : c)";
}f% "apply block to chars in each substring";
R* "join the substrings with 'REX' again";
.| "bitwise OR the case bits back in";
```
The case-saving trick works because the case of ASCII letters is solely determined by the fifth bit of the ASCII code: this bit is 0 for uppercase and 1 for lowercase letters. Thus, taking the bitwise AND of the character code with 32 = 25 extracts the case bit, and bitwise ORing this bit with the uppercased letters restores their original case.
Of course, non-alphabetic characters may have arbitrary values for the fifth bit (although, due to the way ASCII characters are organized, most punctuation characters have the fifth bit set to 1) but this doesn't matter, since those characters are left untouched by uppercasing and the letter censoring loop anyway, and ORing a character with its own fifth bit does't change it. Also, conveniently, the `*` character already has the fifth bit set, so it is also left unchanged by the final `.|`.
[Answer]
# Java 7, ~~96~~ ~~98~~ ~~97~~ 96 bytes
+2 bytes for missing e's preceded by r or followed by x but not both
-1 byte for changing `[a-z&&[^rex]]` to `(?![rex])\\w`
```
String a(String s){return s.replaceAll("(?i)r(?!ex)|(?<!r)e|e(?!x)|(?<!re)x|(?![rex])\\w","*");}
```
[Try it online!](https://tio.run/nexus/java-openjdk#hY8xbsMwDEXn9BS0JqkIfIG0MHqALEm3OAOrEIYKWTZEOrHR@Owuk6ZrO5Gf5Pvg9xGZYYshwdfTqh8@YvDAgqLl3IUTtLqye8khNYcjYG7Y6eHqTrSvkOhyp63b6HQ/sVBbdoOUvRISk21LtGZHI8RwJgalVERMp9K4P5n3DjzGeDtfw@fAAowT1Dev2vwHbyeFBQJDQyL6O2DqMo3BP8h5@ckE@AgHmiuTDDkBl5n6iJ7eYrTGVsFlWxU0uqutXors6EqqfyW5UZvioO5HV9cXszbPxm3mZV6@AQ)
A regex version for replacing using Java
Replaces everything in this regex with a \* (note in Java \w has to be escaped as \\w)
```
(?i)r(?!ex)|(?<!r)e|e(?!x)|(?<!re)x|(?![rex])\w
(?i) // Case Insensitive
r(?!ex) // Any r not followed by ex
|(?<!r)e // Or any e not preceded by r
|e(?!x) // Or any e not followed by x
|(?<!re)x // Or any x not preceded by re
|(?![rex])\w // Or any other word character
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~21~~ 19 bytes
```
qR-`(rex)|\w`{b|'*}
```
Takes input from stdin, outputs to stdout. [Try it online!](https://tio.run/##K8gs@P@/MEg3QaMotUKzJqY8oTqpRl2r9v//oNQKhZzMstRihcw8BSAnJzEvRe8/AA "Pip – Try It Online")
### Explanation
```
q Read a line of stdin
R and replace
`(rex)|\w` a regex matching `rex` or any single alphanumeric character,
- case-insensitive
{ } with this callback function:
b|'* If the 1st capture group (rex) matched, return it, else asterisk
The result of the replacement is auto-printed
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~27~~, 24 bytes
I'm leaving both answers up, because I think they're equally interesting.
# 27 bytes
```
òÓãr¨ex©À!ü¼eü¼xü[rex]À!÷/*
```
[Try it online!](https://tio.run/##K/v///Cmw5MPLy46tCK14tDKww2Kh/cc2pMKIioO74kuSq2IBYlt19f6/z8otUJHIQVEeCqU5OekKFTmlyrk5ZcAOQop@QolGZnFigqR@aXqRakKuYnZmXnpCrmpCol56UWVCkC9igA "V – Try It Online")
Thanks to Brian McCutchon for his idea to [do this in V](https://codegolf.stackexchange.com/a/119887/31716)
Hexdump:
```
00000000: f2d3 e372 a865 78a9 c021 fcbc 65fc bc78 ...r.ex..!..e..x
00000010: fc5b 7265 785d c021 f72f 2a .[rex].!./*
```
Explanation:
```
ò " Until the output stops changing...
Óãr¨ex©À!ü¼eü¼xü[rex]À!÷/* " Run the compressed vim regex:
:s/\vr(ex)@!|<e|<x|[rex]@!\w/*/gi
```
# 24 bytes
```
Óãrex/ò&ò
HòÓ÷/*/e
jjòÍî
```
[Try it online!](https://tio.run/##K/v///Dkw4uLUiv0D29SO7yJy@PwJqDAdn0t/VSurCwgp/fwuv//g1IrdBRSQISnQkl@TopCZX6pQl5@CZCjkJKvUJKRWayoEJlfql6UqpCbmJ2Zl66Qm6qQmJdeVKkA1KsIAA "V – Try It Online")
```
Ó " Substitute
ã " (case-insensitive)
rex " 'rex'
/ " with
& " 'rex'
ò ò " Surrounded in new lines
ò " Recursively...
Ó " Substitute...
÷ " A word character
/ " with
* " An asterisk
/e " (don't break if there are 0 matches)
jj " Move down 2 lines
ò " end the recursive loop
Íî " Remove all newlines
```
] |
[Question]
[
[Matthias Goergens](https://github.com/matthiasgoergens/Div7/blob/master/regex7) has a 25,604-character (down from the original 63,993-character) regex to match numbers divisible by 7, but that includes a lot of fluff: redundant parentheses, distribution (`xx|xy|yx|yy` rather than `[xy]{2}`) and other issues, though I'm sure a fresh start would be helpful in saving space. How small can this be made?
Any reasonable variety of regular expressions are allowed, but no executable code in the regex.
The regular expression should match all strings containing the decimal representation of a number divisible by 7 and no others. Extra credit for a regex that does not allow initial 0s.
[Answer]
# 13,755 12,699 12,731 Characters
This regex does not reject leading zero.
```
(0|7|[18]5*4|(2|9|[18]5*6)(3|[29]5*6)*(1|8|[29]5*4)|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))|(4|[18]5*[18]|(2|9|[18]5*6)(3|[29]5*6)*(5|[29]5*[18])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(2|9|35*4|(4|35*6)(3|[29]5*6)*(1|8|[29]5*4)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4)))|(5|[18]5*[29]|(2|9|[18]5*6)(3|[29]5*6)*(6|[29]5*[29])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(4|[18]5*[18]|(2|9|[18]5*6)(3|[29]5*6)*(5|[29]5*[18])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))(4|[07]5*[29]|(1|8|[07]5*6)(3|[29]5*6)*(6|[29]5*[29])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))*(6|[07]5*4|(1|8|[07]5*6)(3|[29]5*6)*(1|8|[29]5*4)|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(2|9|35*4|(4|35*6)(3|[29]5*6)*(1|8|[29]5*4)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))))|(6|[18]5*3|(2|9|[18]5*6)(3|[29]5*6)*(0|7|[29]5*3)|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3))|(4|[18]5*[18]|(2|9|[18]5*6)(3|[29]5*6)*(5|[29]5*[18])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(1|8|35*3|(4|35*6)(3|[29]5*6)*(0|7|[29]5*3)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3)))|(5|[18]5*[29]|(2|9|[18]5*6)(3|[29]5*6)*(6|[29]5*[29])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(4|[18]5*[18]|(2|9|[18]5*6)(3|[29]5*6)*(5|[29]5*[18])|(3|[18]5*[07]|(2|9|[18]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))(4|[07]5*[29]|(1|8|[07]5*6)(3|[29]5*6)*(6|[29]5*[29])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))*(5|[07]5*3|(1|8|[07]5*6)(3|[29]5*6)*(0|7|[29]5*3)|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(1|8|35*3|(4|35*6)(3|[29]5*6)*(0|7|[29]5*3)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3)))))(2|9|45*3|(5|45*6)(3|[29]5*6)*(0|7|[29]5*3)|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3))|(0|7|45*[18]|(5|45*6)(3|[29]5*6)*(5|[29]5*[18])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(1|8|35*3|(4|35*6)(3|[29]5*6)*(0|7|[29]5*3)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3)))|(1|8|45*[29]|(5|45*6)(3|[29]5*6)*(6|[29]5*[29])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(0|7|45*[18]|(5|45*6)(3|[29]5*6)*(5|[29]5*[18])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))(4|[07]5*[29]|(1|8|[07]5*6)(3|[29]5*6)*(6|[29]5*[29])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))*(5|[07]5*3|(1|8|[07]5*6)(3|[29]5*6)*(0|7|[29]5*3)|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(1|8|35*3|(4|35*6)(3|[29]5*6)*(0|7|[29]5*3)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(4|65*3|(0|7|65*6)(3|[29]5*6)*(0|7|[29]5*3)))))*(3|45*4|(5|45*6)(3|[29]5*6)*(1|8|[29]5*4)|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))|(0|7|45*[18]|(5|45*6)(3|[29]5*6)*(5|[29]5*[18])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(2|9|35*4|(4|35*6)(3|[29]5*6)*(1|8|[29]5*4)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4)))|(1|8|45*[29]|(5|45*6)(3|[29]5*6)*(6|[29]5*[29])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(0|7|45*[18]|(5|45*6)(3|[29]5*6)*(5|[29]5*[18])|(6|45*[07]|(5|45*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))(4|[07]5*[29]|(1|8|[07]5*6)(3|[29]5*6)*(6|[29]5*[29])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(0|7|35*[29]|(4|35*6)(3|[29]5*6)*(6|[29]5*[29])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(3|65*[29]|(0|7|65*6)(3|[29]5*6)*(6|[29]5*[29]))))*(6|[07]5*4|(1|8|[07]5*6)(3|[29]5*6)*(1|8|[29]5*4)|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))|(3|[07]5*[18]|(1|8|[07]5*6)(3|[29]5*6)*(5|[29]5*[18])|(2|9|[07]5*[07]|(1|8|[07]5*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))(6|35*[18]|(4|35*6)(3|[29]5*6)*(5|[29]5*[18])|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(2|9|65*[18]|(0|7|65*6)(3|[29]5*6)*(5|[29]5*[18])))*(2|9|35*4|(4|35*6)(3|[29]5*6)*(1|8|[29]5*4)|(5|35*[07]|(4|35*6)(3|[29]5*6)*(4|[29]5*[07]))(1|8|65*[07]|(0|7|65*6)(3|[29]5*6)*(4|[29]5*[07]))*(5|65*4|(0|7|65*6)(3|[29]5*6)*(1|8|[29]5*4))))))*
```
This is tested with [The Regex Coach](http://weitz.de/regex-coach/).
# How We Get There
The Regex above produced by first constructing a [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton) which would accept the input we want (decimals divisible by 7) and then converting to a [Regular Expression](http://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory) and fixing the notation
To understand this, it helps to first make a DFA which accepts the following language:
```
L = {w | w is a binary representation of an integer divisible by 7 }
```
That is, it will 'match' binary numbers that are divisible by 7.
The DFA looks like this:
![Mod 7 NFA](https://i.stack.imgur.com/sCDOF.png)
## How it works
You keep a current value `A` that represents the value of the bits the DFA has read. When you read a `0` then `A = 2*A` and when you read a `1` `A = 2*A + 1`. At each step you calculate `A mod 7` then you go to the state that represents the answer.
### So a test run
We're reading in `10101` which is the binary representation for 21 in decimal.
1. We start at state `q0`, currently `A=0`
2. We read a `1`, from the 'rule' above `A = 2*A + 1` so `A = 1`. `A mod 7 = 1` so we move to state `q1`
3. We read a `0`, `A = 2*A = 2`, `A mod 7 = 2` so we move to `q2`
4. Read a `1`, `A = 2*A + 1 = 5`, `A mod 7 = 5`, move to `q5`
5. Read a `0`, `A = 2*A = 10`, `A mod 7 = 3`, move to `q3`
6. Read a `1`, `A = 2*A + 1 = 21`, `A mod 7 = 0`, move to `q0`
7. The input is accepted so the number `10101` is divisible by 7!
Converting the DFA to a Regular Expression is a tricky task so I got [JFLAP](https://www.jflap.org/) to do it for me, producing the following:
```
(0|111|100((1|00)0)*011|(101|100((1|00)0)*(1|00)1)(1((1|00)0)*(1|00)1)*(01|1((1|00)0)*011)|(110|100((1|00)0)*010|(101|100((1|00)0)*(1|00)1)(1((1|00)0)*(1|00)1)*(00|1((1|00)0)*010))(1|0(1((1|00)0)*(1|00)1)*(00|1((1|00)0)*010))*0(1((1|00)0)*(1|00)1)*(01|1((1|00)0)*011))*
```
# For Decimal Numbers
The process is much the same:
I constructed a DFA which accepts the language:
```
L = {w | w is a decimal number that is divisible by 7}
```
Here's the DFA:
![](https://i.stack.imgur.com/StGDs.png)
The logic is similar, same number of states just many more transitions to handle all the extra digits decimal numbers bring.
Now the rule to change `A` at each step is: when you read a decimal digit `n`: `A = 10*A + n`. Then again you just `mod` `A` by 7 and go to the next state.
## Revisions
### Revision 5
The above regular expression now rejects numbers leading zeros - apart from zero itself of course.
This makes the DFA slightly different, basically you branch off from the initial node when you read the first zero. Reading another zero puts you into an infinite loop on the branched state. I **haven't** fixed the diagram to show this.
### Revision 7
Did some "metaregex" and shortened my regex by replacing some of the unions with character classes.
### Revision 10 and 11 (by nhahtdh)
The author's modification to reject leading zero is incorrect. It makes the regexes fail to match valid numbers, such as 1110 (decimal = 14) in the case of binary regex, and 70 in the case of decimal regex. These revision reverts the modification, and consequently, allows arbitrary leading zeros and empty string to match.
This revision increases the size of the decimal regex, since it corrects a bug in the original regex, caused by a missing an edge (9) from state 5 to state 3 in the original DFA.
[Answer]
# .NET regex, ~~119~~ ~~118~~ 105 bytes
```
^(?>(?=[1468](?<4>)|)(?=[2569](?<4>){2}|)([3-6]()|\d)((?<-2>)(){3}|){7}((?<-4>){7}|(?<2-4>)|){9})+$(?!\2)
```
111 characters disallowing initial 0s:
```
^(?!0.)(?>(?=[1468](?<4>)|)(?=[2569](?<4>){2}|)([3-6]()|\d)((?<-2>)(){3}|){7}((?<-4>){7}|(?<2-4>)|){9})+$(?!\2)
```
113 characters disallowing initial 0s and supporting negative numbers:
```
^-?(?>(?=[1468](?<4>)|)(?=[2569](?<4>){2}|)([3-6]()|\d)((?<-2>)(){3}|){7}((?<-4>){7}|(?<2-4>)|){9})+$(?!\2)
```
[Try it here.](http://retina.tryitonline.net/#code=R2BeKD8-KD89WzE0NjhdKD88ND4pfCkoPz1bMjU2OV0oPzw0Pil7Mn18KShbMy02XSgpfFxkKSgoPzwtMj4pKCl7M318KXs3fSgoPzwtND4pezd9fCg_PDItND4pfCl7OX0pKyQoPyFcMik&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKMTEKMTIKMTMKMTQKMTUKMTYKMTcKMTgKMTkKMjAKMjEKMjIKMTExMTExCjEyMzExNQo1MTc4MjMKNTc2MTI4)
### Explanation (of the previous version)
It uses the techniques used by various answers in this question: [Cops and Robbers: Reverse Regex Golf](https://codegolf.stackexchange.com/q/39829/25180). The .NET regex has a feature called balancing group, which can be used for doing arithmetic. `(?<a>)` pushes a group `a`. `(?<-a>)` pops that and doesn't match if there isn't a group `a` matched before.
* `(?>...)` Match and don't backtrack later. So it will always match only the first matched alternative.
* `((?<-t>)(){3}|){6}` Multiply the number of group t by 3. Save the result in the number of group 2.
* `(?=[1468](?<2>)|)(?=[2569](?<2>){2}|)([3-6](?<2>){3}|\d)` Match a number, and that number of group 2.
* `((?<-2>){7}|){3}` Remove group 2 a multiple of 7 times.
* `((?<t-2>)|){6}` Remove group 2 and match the same number of group t.
* `$(?(t)a)` If there is still a group t matched, match `a` after the end of string, which is impossible.
I thought this 103 byte version should also work, but didn't find a workaround of the bug in the compiler.
```
^(?(?(?((?<3>){2}[2569]|)([3-6])?((?<-1>)(){3}|){7})(?<3>[1468])?((?<-3>){7}|(?<1-3>)|){9})\d)+$(?(1)a)
```
[Answer]
## 468 characters
Ruby's regex flavor allows recursion (although it's sort of cheating), so it is straightforward to implement a DFA that recognizes numbers divisible by 7 using that. Each named group corresponds to a state, and each branch in the alternations consumes one digit and then jumps to the appropriate state.
If the end of the number is reached, the regex matches only if the engine is in the "A" group, otherwise it fails.
It recognizes leading zeros.
```
(?!$)(?>(|(?<B>4\g<A>|5\g<B>|6\g<C>|[07]\g<D>|[18]\g<E>|[29]\g<F>|3\g<G>))(|(?<C>[18]\g<A>|[29]\g<B>|3\g<C>|4\g<D>|5\g<E>|6\g<F>|[07]\g<G>))(|(?<D>5\g<A>|6\g<B>|[07]\g<C>|[18]\g<D>|[29]\g<E>|3\g<F>|4\g<G>))(|(?<E>[29]\g<A>|3\g<B>|4\g<C>|5\g<D>|6\g<E>|[07]\g<F>|[18]\g<G>))(|(?<F>6\g<A>|[07]\g<B>|[18]\g<C>|[29]\g<D>|3\g<E>|4\g<F>|5\g<G>))(|(?<G>3\g<A>|4\g<B>|5\g<C>|6\g<D>|[07]\g<E>|[18]\g<F>|[29]\g<G>)))(?<A>$|[07]\g<A>|[18]\g<B>|[29]\g<C>|3\g<D>|4\g<E>|5\g<F>|6\g<G>)
```
[Answer]
# 10791 characters, leading zeros allowed
```
(0|7|46*[29]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(4|63*[18]|(1|8|63*5)(6|43*5)*(2|9|43*[18]))|(2|9|46*4)(3|56*4)*(1|8|56*[29])|(3|46*5|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4))|(2|9|46*4)(3|56*4)*(4|56*5)|(5|46*[07]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(2|9|46*4)(3|56*4)*(6|56*[07]))(4|36*[07]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4))|(1|8|36*4)(3|56*4)*(4|56*5)))(1|8|(0|7|[29]6*4)(3|56*4)*(4|56*5)|[29]6*5|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))*(5|34*6|(0|7|34*[18]|(2|9|34*3)(6|[07]4*3)*(4|[07]4*[18]))(3|56*4|(6|56*[07])(4|36*[07])*(1|8|36*4))*(1|8|64*6|(5|64*3)(6|[07]4*3)*(2|9|[07]4*6))|(2|9|34*3)(6|[07]4*3)*(2|9|[07]4*6)|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(4|63*[18]|(1|8|63*5)(6|43*5)*(2|9|43*[18])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(6|36*[29]|(1|8|36*4)(3|56*4)*(1|8|56*[29]))))|(5|46*[07]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(2|9|46*4)(3|56*4)*(6|56*[07]))(4|36*[07]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(1|8|36*4)(3|56*4)*(6|56*[07]))*(6|36*[29]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(4|63*[18]|(1|8|63*5)(6|43*5)*(2|9|43*[18]))|(1|8|36*4)(3|56*4)*(1|8|56*[29]))|(6|46*[18]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(3|63*[07]|(1|8|63*5)(6|43*5)*(1|8|43*[07]))|(2|9|46*4)(3|56*4)*(0|7|56*[18])|(3|46*5|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4))|(2|9|46*4)(3|56*4)*(4|56*5)|(5|46*[07]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(2|9|46*4)(3|56*4)*(6|56*[07]))(4|36*[07]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4))|(1|8|36*4)(3|56*4)*(4|56*5)))(1|8|(0|7|[29]6*4)(3|56*4)*(4|56*5)|[29]6*5|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))*(4|34*5|(0|7|34*[18]|(2|9|34*3)(6|[07]4*3)*(4|[07]4*[18]))(3|56*4|(6|56*[07])(4|36*[07])*(1|8|36*4))*(0|7|64*5|(5|64*3)(6|[07]4*3)*(1|8|[07]4*5))|(2|9|34*3)(6|[07]4*3)*(1|8|[07]4*5)|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(3|63*[07]|(1|8|63*5)(6|43*5)*(1|8|43*[07])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(5|36*[18]|(1|8|36*4)(3|56*4)*(0|7|56*[18]))))|(5|46*[07]|(1|8|46*3|(2|9|46*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(2|9|46*4)(3|56*4)*(6|56*[07]))(4|36*[07]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))|(1|8|36*4)(3|56*4)*(6|56*[07]))*(5|36*[18]|(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(3|63*[07]|(1|8|63*5)(6|43*5)*(1|8|43*[07]))|(1|8|36*4)(3|56*4)*(0|7|56*[18])))(2|9|53*[07]|(0|7|53*5)(6|43*5)*(1|8|43*[07])|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(5|36*[18]|(1|8|36*4)(3|56*4)*(0|7|56*[18]))|(4|[07]6*3|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(5|[07]6*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(3|63*[07]|(1|8|63*5)(6|43*5)*(1|8|43*[07])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(5|36*[18]|(1|8|36*4)(3|56*4)*(0|7|56*[18])))|(6|53*4|(0|7|53*5)(6|43*5)*(5|43*4)|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(4|[07]6*3|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(5|[07]6*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))(1|8|(0|7|[29]6*4)(3|56*4)*(4|56*5)|[29]6*5|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))*(4|34*5|(0|7|34*[18]|(2|9|34*3)(6|[07]4*3)*(4|[07]4*[18]))(3|56*4|(6|56*[07])(4|36*[07])*(1|8|36*4))*(0|7|64*5|(5|64*3)(6|[07]4*3)*(1|8|[07]4*5))|(2|9|34*3)(6|[07]4*3)*(1|8|[07]4*5)|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(3|63*[07]|(1|8|63*5)(6|43*5)*(1|8|43*[07])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(5|36*[18]|(1|8|36*4)(3|56*4)*(0|7|56*[18])))))*(3|53*[18]|(0|7|53*5)(6|43*5)*(2|9|43*[18])|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(6|36*[29]|(1|8|36*4)(3|56*4)*(1|8|56*[29]))|(4|[07]6*3|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(5|[07]6*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(4|63*[18]|(1|8|63*5)(6|43*5)*(2|9|43*[18])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(6|36*[29]|(1|8|36*4)(3|56*4)*(1|8|56*[29])))|(6|53*4|(0|7|53*5)(6|43*5)*(5|43*4)|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(4|[07]6*3|(1|8|53*6|(0|7|53*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(5|[07]6*4)(3|56*4)*(2|9|56*3))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))(1|8|(0|7|[29]6*4)(3|56*4)*(4|56*5)|[29]6*5|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(0|7|63*4|(1|8|63*5)(6|43*5)*(5|43*4)|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(2|9|36*5|(1|8|36*4)(3|56*4)*(4|56*5))))*(5|34*6|(0|7|34*[18]|(2|9|34*3)(6|[07]4*3)*(4|[07]4*[18]))(3|56*4|(6|56*[07])(4|36*[07])*(1|8|36*4))*(1|8|64*6|(5|64*3)(6|[07]4*3)*(2|9|[07]4*6))|(2|9|34*3)(6|[07]4*3)*(2|9|[07]4*6)|(6|(0|7|[29]6*4)(3|56*4)*(2|9|56*3)|[29]6*3|(3|[07]3*6|(2|9|[07]3*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3)))(5|[18]6*3|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(0|7|36*3|(1|8|36*4)(3|56*4)*(2|9|56*3))|(6|[18]6*4)(3|56*4)*(2|9|56*3))*(4|63*[18]|(1|8|63*5)(6|43*5)*(2|9|43*[18])|(2|9|63*6|(1|8|63*5)(6|43*5)*(0|7|43*6))(4|36*[07]|(1|8|36*4)(3|56*4)*(6|56*[07]))*(6|36*[29]|(1|8|36*4)(3|56*4)*(1|8|56*[29]))))))+
```
# 10795 characters, leading zeros forbidden
`0|((foo)0*)+`, where the above regex is `(0|foo)+`.
# Explanation
Numbers divisible by 7 are matched by the obvious finite automaton with 7 states Q = {0, …, 6}, initial and final state 0, and transitions d: i ↦ (10i + d) mod 7. I converted this finite automaton into a regular expression, using recursion on the set of allowed intermediate states:
Given i, j ∈ Q and S ⊆ Q, let f(i, S, j) be a regular expression that matches all automaton paths from i to j using only intermediate states within S. Then,
f(i, ∅, j) = (j − 10i) mod 7,
f(i, S ∪ {k}, j) = f(i, S, j) ∣ f(i, S, k) f(k, S, k)\* f(k, S, j).
I used dynamic programming to choose k so as to minimize the length of the resulting expression.
[Answer]
I was really impressed by Griffin's answer and needed to figure out how it worked! The result is the following JavaScript. (It's 3.5k characters, which is shorter in a way!) The `gen` function takes a divisor and base and generates a regular expression that matches numbers in the specified base that are divisible by that divisor.
I've generalized Griffin's NFA for any base: the `nfa` function takes a divisor and base and returns a two dimensional array of transitions. The input required to go from state 0 to state 2, for example, is `states[0][2] == "1"`.
The `reduce` function takes in the `states` array and runs it through [this algorithm](http://www.cs.umbc.edu/~squire/cs451_l7.html) to translate the NFA to regex. The regexes that are generated are huge and look like they have a lot of redundant clauses, despite my attempts at optimization. The regex for 7 base 10 is about ~67k characters long; Firefox throws an "InternalError" for n > 5 trying to parse the regex; running the regex on Chrome starts getting slow for n > 6.
There's also the `test` function that takes a regex and base and runs it against the numbers 0 to 100, so `test(gen(5)) == [0, 5, 10, 15, ...]`.
Despite the suboptimal result, this was a fantastic learning opportunity, and I hope some of this code will be useful in the future!
```
function gen(b, base) {
var states = nfa(b, base)
for (var i = 0; i < states.length; i++)
states = reduce(states, i);
return states[0][0] != 'phi' && new RegExp('^' + wrap(states[0][0]) + '$');
}
function test(reg, base) {
if (!base)
base = 10;
var x = [];
for (var i = 0; i < 100; i++)
x.push(i);
return x.map(function (a) {return a.toString(base)}).filter(reg.test.bind(reg)).map(function (a) {return parseInt(a, base)})
}
function nfa(b, base) {
if (!base)
base = 10;
var states = [];
for (var i = 0; i < b; i++) {
states[i] = [];
for (var j = 0; j < b; j++)
states[i][j] = [];
}
for (var i = 0; i < b; i++)
for (var n = 0; n < base; n++)
states[i][(i * base + n) % b].push(n.toString());
for (var i = 0; i < b; i++)
for (var j = 0; j < b; j++)
states[i][j] = states[i][j].length > 1 ? '[' + states[i][j].join('') + ']' : (states[i][j][0] || 'phi');
return states;
}
// http://www.cs.umbc.edu/~squire/cs451_l7.html
function reduce(states, n) {
var s = states.length;
var reduced = [];
for (var i = 0; i < s; i++) {
reduced[i] = [];
for (var j = 0; j < s; j++) {
// reduced[i][j] = wrap(states[i][n] + wrap(states[n][n]) + '*' + states[n][j] + '|' + states[i][j]);
reduced[i][j] = '';
if (states[i][n] == 'phi' || states[n][j] == 'phi') {
reduced[i][j] = states[i][j];
continue;
}
if (states[i][n] != states[n][n])
reduced[i][j] += wrap(states[i][n]);
if (states[n][n] != 'phi') {
reduced[i][j] += wrap(states[n][n]);
if (states[i][n] == states[n][n] && states[n][j] == states[n][n])
reduced[i][j] += wrap(states[n][n]);
if (states[i][n] == states[n][n] || states[n][j] == states[n][n])
reduced[i][j] += '+';
else
reduced[i][j] += '*';
}
if (states[n][j] != states[n][n])
reduced[i][j] += wrap(states[n][j]);
reduced[i][j] = states[i][j] == 'phi' ? wrap(reduced[i][j]) : alternate(reduced[i][j], states[i][j]);
}
}
return reduced;
}
function matching(x, open, close) {
// Test if the parens are actually matching
if ('(['.indexOf(x.charAt(open)) != -1 && ')]'.indexOf(x.charAt(close)) != -1) {
var count = 0;
for (var i = open; i <= close; i++) {
if ('(['.indexOf(x.charAt(i)) != -1)
count++;
else if (')]'.indexOf(x.charAt(i)) != -1) {
count--;
if (count == 0)
return i == close;
}
}
}
return false;
}
function wrap(x) {
if (x.length < 2 || matching(x, 0, x.length - 1))
return x;
return '(' + x + ')';
}
function optional(cond) {
if (matching(cond, 0, cond.length - 2)) {
var op = cond.charAt(cond.length - 1);
if (op == '+')
return cond.slice(0, -1) + '*';
else if (op == '*' || op == '?')
return cond;
} else if (matching(cond, 0, cond.length - 1))
return optional(cond.slice(1, -1));
return wrap(cond) + '?';
}
function alternate(cond1, cond2) {
cond2 = wrap(cond2);
var index = cond1.indexOf(cond2);
var len = cond2.length;
var cond = '';
if (index == 0) {
var op = cond1.charAt(len);
if (op == '*')
cond = cond2 + '+' + optional(cond1.slice(len));
else if (op == '+')
cond = cond1;
else
cond = cond2 + optional(cond1.slice(len));
} else if (index == cond1.length - len)
cond = optional(cond1.slice(0, index)) + cond2;
else if (cond1.length == 1 && cond2.length == 1)
cond = '[' + cond1 + cond2 + ']';
else
cond = cond1 + '|' + cond2;
return wrap(cond);
}
```
[Answer]
# Perl/PCRE, 370 characters
```
^(?!$|0.)([07]*(?:[18](?2)|[29](?3)|3(?4)|4(?5)|5(?7)|6(?9)|$))|(5*(?:[07](?4)|[18](?5)|[29](?7)|4(?1)|6(?3)|3(?9)))(3*(?:[18](?1)|[29](?2)|[07](?9)|4(?4)|5(?5)|6(?7)))([18]*(?:[07](?3)|[29](?5)|5(?1)|6(?2)|3(?7)|4(?9)))(6*([29](?1)|[07](?7)|[18](?9)|3(?2)|4(?3)|5(?4)))(4*([07](?2)|[18](?3)|[29](?4)|6(?1)|3(?5)|5(?9)))([29]*([07](?5)|[18](?7)|3(?1)|4(?2)|5(?3)|6(?4)))
```
Rejects the empty string, as well as strings with leading 0’s (except "0").
] |
[Question]
[
Consider these 10 images of various amounts of uncooked grains of white rice.
**THESE ARE ONLY THUMBNAILS. Click an image to view it at full size.**
**A:** [![A](https://i.stack.imgur.com/8T6W2s.jpg)](https://i.stack.imgur.com/8T6W2.jpg)
**B:** [![B](https://i.stack.imgur.com/pgWt1s.jpg)](https://i.stack.imgur.com/pgWt1.jpg)
**C:** [![C](https://i.stack.imgur.com/M0K5ws.jpg)](https://i.stack.imgur.com/M0K5w.jpg)
**D:** [![D](https://i.stack.imgur.com/eUFNos.jpg)](https://i.stack.imgur.com/eUFNo.jpg)
**E:** [![E](https://i.stack.imgur.com/2TFdis.jpg)](https://i.stack.imgur.com/2TFdi.jpg)
**F:** [![F](https://i.stack.imgur.com/wX48vs.jpg)](https://i.stack.imgur.com/wX48v.jpg)
**G:** [![G](https://i.stack.imgur.com/eXCGts.jpg)](https://i.stack.imgur.com/eXCGt.jpg)
**H:** [![H](https://i.stack.imgur.com/9na4Js.jpg)](https://i.stack.imgur.com/9na4J.jpg)
**I:** [![I](https://i.stack.imgur.com/UMP9Vs.jpg)](https://i.stack.imgur.com/UMP9V.jpg)
**J:** [![J](https://i.stack.imgur.com/nP3Hrs.jpg)](https://i.stack.imgur.com/nP3Hr.jpg)
**Grain Counts:** `A: 3, B: 5, C: 12, D: 25, E: 50, F: 83, G: 120, H:150, I: 151, J: 200`
Notice that...
* **The grains may touch each other but they never overlap.** The layout of grains is never more than one grain high.
* The images have different dimensions but the scale of the rice in all of them is consistent because the camera and background were stationary.
* The grains never go out of bounds or touch the image boundaries.
* The background is always the same consistent shade of yellowish-white.
* Small and large grains are counted alike as one grain each.
These 5 points are guarantees for all images of this sort.
# Challenge
Write a program that takes in such images and, as accurately as possible, counts the number of grains of rice.
Your program should take the filename of the image and print the number of grains it calculates. Your program must work for at least one of these image file formats: JPEG, Bitmap, PNG, GIF, TIFF (right now the images are all JPEGs).
You *may* use image processing and computer vision libraries.
**You may not hardcode the outputs of the 10 example images.** Your algorithm should be applicable to all similar rice-grain images. It should be able to run in less than 5 minutes on a [decent modern computer](https://teksyndicate.com/forum/general-discussion/average-steam-users-computer-specs/150190) if the image area is less than 2000\*2000 pixels and there are fewer than 300 grains of rice.
# Scoring
For each of the 10 images take the absolute value of the actual number of grains minus the number of grains your program predicts. Sum these absolute values to get your score. The lowest score wins. A score of 0 is perfect.
In case of ties the highest voted answer wins. I may test your program on additional images to verify its validity and accuracy.
[Answer]
# Python, Score: ~~24~~ 16
This solution, like Falko's one, is based on measuring the "foreground" area and dividing it by the average grain area.
In fact, what this program tries to detect is the background, not so much as the foreground.
Using the fact that rice grains never touch the image boundary, the program starts by flood-filling white at the top-left corner.
The flood-fill algorithm paints adjacent pixels if the difference between theirs and the current pixel's brightness is within a certain threshold, thus adjusting to gradual change in the background color.
At the end of this stage, the image might look something like this:
![Figure 1](https://i.stack.imgur.com/CS5CX.jpg)
As you can see, it does a pretty good job at detecting the background, but it leaves out any areas that are "trapped" between the grains.
We handle these areas by estimating the background brightness at each pixel and painting all equal-or-brighter pixels.
This estimation works like so:
during the flood-fill stage, we calculate the average background brightness for each row and each column.
The estimated background brightness at each pixel is the average of the row and column brightness at that pixel.
This produces something like this:
![Figure 2](https://i.stack.imgur.com/WUDVw.jpg)
**EDIT:**
Finally, the area of each continuous foreground (i.e. non-white) region is divided by the average, precalculated, grain area, giving us an estimate of the grain count in the said region. The sum of these quantities is the result.
Initially, we did the same thing for the entire foreground area as a whole, but this approach is, literally, more fine-grained.
---
```
from sys import argv; from PIL import Image
# Init
I = Image.open(argv[1]); W, H = I.size; A = W * H
D = [sum(c) for c in I.getdata()]
Bh = [0] * H; Ch = [0] * H
Bv = [0] * W; Cv = [0] * W
# Flood-fill
Background = 3 * 255 + 1; S = [0]
while S:
i = S.pop(); c = D[i]
if c != Background:
D[i] = Background
Bh[i / W] += c; Ch[i / W] += 1
Bv[i % W] += c; Cv[i % W] += 1
S += [(i + o) % A for o in [1, -1, W, -W] if abs(D[(i + o) % A] - c) < 10]
# Eliminate "trapped" areas
for i in xrange(H): Bh[i] /= float(max(Ch[i], 1))
for i in xrange(W): Bv[i] /= float(max(Cv[i], 1))
for i in xrange(A):
a = (Bh[i / W] + Bv[i % W]) / 2
if D[i] >= a: D[i] = Background
# Estimate grain count
Foreground = -1; avg_grain_area = 3038.38; grain_count = 0
for i in xrange(A):
if Foreground < D[i] < Background:
S = [i]; area = 0
while S:
j = S.pop() % A
if Foreground < D[j] < Background:
D[j] = Foreground; area += 1
S += [j - 1, j + 1, j - W, j + W]
grain_count += int(round(area / avg_grain_area))
# Output
print grain_count
```
Takes the input filename through the comand line.
## Results
```
Actual Estimate Abs. Error
A 3 3 0
B 5 5 0
C 12 12 0
D 25 25 0
E 50 48 2
F 83 83 0
G 120 116 4
H 150 145 5
I 151 156 5
J 200 200 0
----------
Total: 16
```
![A](https://i.stack.imgur.com/WNEIw.png)
![B](https://i.stack.imgur.com/dLUj2.png)
![C](https://i.stack.imgur.com/KFcSU.png)
![D](https://i.stack.imgur.com/OhWix.png)
![E](https://i.stack.imgur.com/Kkrmk.png)
![F](https://i.stack.imgur.com/1cXu9.png)
![G](https://i.stack.imgur.com/fhFH9.png)
![H](https://i.stack.imgur.com/sxUQo.png)
![I](https://i.stack.imgur.com/upzvU.png)
![J](https://i.stack.imgur.com/TavE7.png)
[Answer]
# Python + OpenCV : Score 27
## Horizontal line scanning
Idea : scan the image, one row at a time. For each line, count the number rice grains encountered (by checking if pixel turns black to white or the opposite). If number of grains for the line increase (compared to previous line), it means we encountered a new grain. If that number decrease, it means we passed over a grain. In this case, add +1 to the total result.
![enter image description here](https://i.stack.imgur.com/YTOd5.png)
```
Number in red = rice grains encountered for that line
Number in gray = total amount of grains encountered (what we are looking for)
```
Because of the way algorithm works, it is important to have a clean, b/w image. Lot of noise produce bad results. First main background is cleaned using floodfill (solution similar to Ell answer) then threshold is applied to produce black and white result.
![enter image description here](https://i.stack.imgur.com/qq9Wn.jpg)
It is far from perfect, but it produce good results regarding simplicity. There is probably many way to improve it (by providing better b/w image, scanning in other directions (eg : vertical, diagonal) taking the average etc...)
```
import cv2
import numpy
import sys
filename = sys.argv[1]
I = cv2.imread(filename, 0)
h,w = I.shape[:2]
diff = (3,3,3)
mask = numpy.zeros((h+2,w+2),numpy.uint8)
cv2.floodFill(I,mask,(0,0), (255,255,255),diff,diff)
T,I = cv2.threshold(I,180,255,cv2.THRESH_BINARY)
I = cv2.medianBlur(I, 7)
totalrice = 0
oldlinecount = 0
for y in range(0, h):
oldc = 0
linecount = 0
start = 0
for x in range(0, w):
c = I[y,x] < 128;
if c == 1 and oldc == 0:
start = x
if c == 0 and oldc == 1 and (x - start) > 10:
linecount += 1
oldc = c
if oldlinecount != linecount:
if linecount < oldlinecount:
totalrice += oldlinecount - linecount
oldlinecount = linecount
print totalrice
```
The errors per image : 0, 0, 0, 3, 0, 12, 4, 0, 7, 1
[Answer]
# Mathematica, score: 7
```
i = {"https://i.stack.imgur.com/8T6W2.jpg", "https://i.stack.imgur.com/pgWt1.jpg",
"https://i.stack.imgur.com/M0K5w.jpg", "https://i.stack.imgur.com/eUFNo.jpg",
"https://i.stack.imgur.com/2TFdi.jpg", "https://i.stack.imgur.com/wX48v.jpg",
"https://i.stack.imgur.com/eXCGt.jpg", "https://i.stack.imgur.com/9na4J.jpg",
"https://i.stack.imgur.com/UMP9V.jpg", "https://i.stack.imgur.com/nP3Hr.jpg"};
im = Import /@ i;
```
I think the functions' names are descriptive enough:
```
getSatHSVChannelAndBinarize[i_Image] := Binarize@ColorSeparate[i, "HSB"][[2]]
removeSmallNoise[i_Image] := DeleteSmallComponents[i, 100]
fillSmallHoles[i_Image] := Closing[i, 1]
getMorphologicalComponentsAreas[i_Image] := ComponentMeasurements[i, "Area"][[All, 2]]
roundAreaSizeToGrainCount[areaSize_, grainSize_] := Round[areaSize/grainSize]
```
Processing all the pictures at once:
```
counts = Plus @@@
(roundAreaSizeToGrainCount[#, 2900] & /@
(getMorphologicalComponentsAreas@
fillSmallHoles@
removeSmallNoise@
getSatHSVChannelAndBinarize@#) & /@ im)
(* Output {3, 5, 12, 25, 49, 83, 118, 149, 152, 202} *)
```
The score is:
```
counts - {3, 5, 12, 25, 50, 83, 120, 150, 151, 200} // Abs // Total
(* 7 *)
```
Here you can see the score sensitivity wrt the grain size used:
![Mathematica graphics](https://i.stack.imgur.com/0DhXI.png)
[Answer]
# Python + OpenCV: Score 84
Here is a first naive attempt. It applies an adaptive threshold with manually tuned parameters, closes some holes with subsequent erosion and dilution and derives the number of grains from the foreground area.
```
import cv2
import numpy as np
filename = raw_input()
I = cv2.imread(filename, 0)
I = cv2.medianBlur(I, 3)
bw = cv2.adaptiveThreshold(I, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 101, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (17, 17))
bw = cv2.dilate(cv2.erode(bw, kernel), kernel)
print np.round_(np.sum(bw == 0) / 3015.0)
```
Here you can see the intermediate binary images (black is foreground):
![enter image description here](https://i.stack.imgur.com/e1DJw.png)
The errors per image are 0, 0, 2, 2, 4, 0, 27, 42, 0 and 7 grains.
[Answer]
## C# + OpenCvSharp, Score: 2
This is my second attempt. It is quite different from my [first attempt](https://codegolf.stackexchange.com/a/40897/26549), which is a lot simpler, so I am posting it as a separate solution.
The basic idea is to identify and label each individual grain by an iterative ellipse fit. Then remove the pixels for this grain from the source, and try to find the next grain, until every pixel has been labeled.
This is not the most pretty solution. It is a giant hog with 600 lines of code.
It needs 1.5 minutes for the biggest image. And I really apologize for the messy code.
There are so many parameters and ways to thinker in this thing that I am quite afraid of overfitting my program for the 10 sample images. The final score of 2 is almost definitely a case of overfitting: I have two parameters, `average grain size in pixel`, and `minimum ratio of pixel / elipse_area`, and at the end I simply exhausted all combinations of these two parameters until I got the lowest score. I am not sure whether this is all that kosher with the rules of this challenge.
`average_grain_size_in_pixel = 2530`
`pixel / elipse_area >= 0.73`
But even without these overfitting clutches, the results are quite nice.
Without a fixed grain size or pixel-ratio, simply by estimating the average grain size from the training images, the score is still 27.
And I get as the output not only the number, but the actual position, orientation and shape of each grain. there are a small number of mislabeled grains, but overall most of the labels accurately match the real grains:
A[![A](https://i.stack.imgur.com/O9Fxxs.png)](https://i.stack.imgur.com/O9Fxx.png)
B[![B](https://i.stack.imgur.com/1SVOjs.png)](https://i.stack.imgur.com/1SVOj.png)
C[![C](https://i.stack.imgur.com/0KH4Gs.png)](https://i.stack.imgur.com/0KH4G.png)
D[![D](https://i.stack.imgur.com/QzUDos.png)](https://i.stack.imgur.com/QzUDo.png)
E[![E](https://i.stack.imgur.com/kmsAOs.png)](https://i.stack.imgur.com/kmsAO.png)
F[![F](https://i.stack.imgur.com/GgWc8s.png)](https://i.stack.imgur.com/GgWc8.png)
G[![G](https://i.stack.imgur.com/xI8Nqs.png)](https://i.stack.imgur.com/xI8Nq.png)
H[![H](https://i.stack.imgur.com/596Ats.png)](https://i.stack.imgur.com/596At.png)
I[![I](https://i.stack.imgur.com/ChDWhs.jpg)](https://i.stack.imgur.com/ChDWh.jpg)
J[![J](https://i.stack.imgur.com/LRdbhs.jpg)](https://i.stack.imgur.com/LRdbh.jpg)
*(click on each image for the full-sized version)*
After this labeling step, my program looks at each individual grain, and estimates based on the number of pixels and the pixel/ellipse-area ratio, whether this is
* a single grain (+1)
* multiple grains mislabeled as one (+X)
* a blob too small to be a grain (+0)
The error scores for each image are
`A:0; B:0; C:0; D:0; E:2; F:0; G:0 ; H:0; I:0, J:0`
However the actual error is probably a little higher. Some errors within the same image cancel each other out. Image H in particular has some badly mislabeled grains, whereas in image E the labels are mostly correct
The concept is a little contrived:
* First the foreground is separated via otsu-thresholding on the saturation channel (see my previous answer for details)
* repeat until no more pixels left:
+ select the largest blob
+ choose 10 random edge pixels on this blob as starting positions for a grain
+ for each starting point
- assume a grain with height and width 10 pixels at this position.
- repeat until convergence
* go radially outwards from this point, at different angles, until you encounter an edge pixel (white-to-black)
* the found pixels should hopefully be the edge pixels of a single grain. Try to separate inliers from outliers, by discarding pixels that are a more distant from the assumed ellipse than the others
* repeatedly try to fit an ellipse through a subset of the inliers, keep the best ellipse (RANSACK)
* update the grain position, orientation, width and height with the found elipse
* if the grain position does not change significantly, stop
+ among the 10 fitted grains, choose the best grain according to shape, number of edge pixels. Discard the others
+ remove all pixels for this grain from the source image, then repeat
+ finally, go through the list of found grains, and count each grain either as 1 grain, 0 grains (too small) or 2 grains (too big)
One of my main problems was that I did not want to implement a full ellipse-point distance metric, since calculating that in itself is a complicated iterative process. So I used various workarounds using the OpenCV functions Ellipse2Poly and FitEllipse, and the results are not too pretty.
Apparently i also broke the size limit for codegolf.
An answer is limited to 30000 characters, i am currently at 34000. So I'll have to shorten the code below somewhat.
The full code can be seen at <http://pastebin.com/RgM7hMxq>
Sorry for this, I was not aware that there was a size limit.
```
class Program
{
static void Main(string[] args)
{
// Due to size constraints, I removed the inital part of my program that does background separation. For the full source, check the link, or see my previous program.
// list of recognized grains
List<Grain> grains = new List<Grain>();
Random rand = new Random(4); // determined by fair dice throw, guaranteed to be random
// repeat until we have found all grains (to a maximum of 10000)
for (int numIterations = 0; numIterations < 10000; numIterations++ )
{
// erode the image of the remaining foreground pixels, only big blobs can be grains
foreground.Erode(erodedForeground,null,7);
// pick a number of starting points to fit grains
List<CvPoint> startPoints = new List<CvPoint>();
using (CvMemStorage storage = new CvMemStorage())
using (CvContourScanner scanner = new CvContourScanner(erodedForeground, storage, CvContour.SizeOf, ContourRetrieval.List, ContourChain.ApproxNone))
{
if (!scanner.Any()) break; // no grains left, finished!
// search for grains within the biggest blob first (this is arbitrary)
var biggestBlob = scanner.OrderByDescending(c => c.Count()).First();
// pick 10 random edge pixels
for (int i = 0; i < 10; i++)
{
startPoints.Add(biggestBlob.ElementAt(rand.Next(biggestBlob.Count())).Value);
}
}
// for each starting point, try to fit a grain there
ConcurrentBag<Grain> candidates = new ConcurrentBag<Grain>();
Parallel.ForEach(startPoints, point =>
{
Grain candidate = new Grain(point);
candidate.Fit(foreground);
candidates.Add(candidate);
});
Grain grain = candidates
.OrderByDescending(g=>g.Converged) // we don't want grains where the iterative fit did not finish
.ThenBy(g=>g.IsTooSmall) // we don't want tiny grains
.ThenByDescending(g => g.CircumferenceRatio) // we want grains that have many edge pixels close to the fitted elipse
.ThenBy(g => g.MeanSquaredError)
.First(); // we only want the best fit among the 10 candidates
// count the number of foreground pixels this grain has
grain.CountPixel(foreground);
// remove the grain from the foreground
grain.Draw(foreground,CvColor.Black);
// add the grain to the colection fo found grains
grains.Add(grain);
grain.Index = grains.Count;
// draw the grain for visualisation
grain.Draw(display, CvColor.Random());
grain.DrawContour(display, CvColor.Random());
grain.DrawEllipse(display, CvColor.Random());
//display.SaveImage("10-foundGrains.png");
}
// throw away really bad grains
grains = grains.Where(g => g.PixelRatio >= 0.73).ToList();
// estimate the average grain size, ignoring outliers
double avgGrainSize =
grains.OrderBy(g => g.NumPixel).Skip(grains.Count/10).Take(grains.Count*9/10).Average(g => g.NumPixel);
//ignore the estimated grain size, use a fixed size
avgGrainSize = 2530;
// count the number of grains, using the average grain size
double numGrains = grains.Sum(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize));
// get some statistics
double avgWidth = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) == 1).Average(g => g.Width);
double avgHeight = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) == 1).Average(g => g.Height);
double avgPixelRatio = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) == 1).Average(g => g.PixelRatio);
int numUndersized = grains.Count(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) < 1);
int numOversized = grains.Count(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) > 1);
double avgWidthUndersized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) < 1).Select(g=>g.Width).DefaultIfEmpty(0).Average();
double avgHeightUndersized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) < 1).Select(g => g.Height).DefaultIfEmpty(0).Average();
double avgGrainSizeUndersized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) < 1).Select(g => g.NumPixel).DefaultIfEmpty(0).Average();
double avgPixelRatioUndersized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) < 1).Select(g => g.PixelRatio).DefaultIfEmpty(0).Average();
double avgWidthOversized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) > 1).Select(g => g.Width).DefaultIfEmpty(0).Average();
double avgHeightOversized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) > 1).Select(g => g.Height).DefaultIfEmpty(0).Average();
double avgGrainSizeOversized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) > 1).Select(g => g.NumPixel).DefaultIfEmpty(0).Average();
double avgPixelRatioOversized = grains.Where(g => Math.Round(g.NumPixel * 1.0 / avgGrainSize) > 1).Select(g => g.PixelRatio).DefaultIfEmpty(0).Average();
Console.WriteLine("===============================");
Console.WriteLine("Grains: {0}|{1:0.} of {2} (e{3}), size {4:0.}px, {5:0.}x{6:0.} {7:0.000} undersized:{8} oversized:{9} {10:0.0} minutes {11:0.0} s per grain",grains.Count,numGrains,expectedGrains[fileNo],expectedGrains[fileNo]-numGrains,avgGrainSize,avgWidth,avgHeight, avgPixelRatio,numUndersized,numOversized,watch.Elapsed.TotalMinutes, watch.Elapsed.TotalSeconds/grains.Count);
// draw the description for each grain
foreach (Grain grain in grains)
{
grain.DrawText(avgGrainSize, display, CvColor.Black);
}
display.SaveImage("10-foundGrains.png");
display.SaveImage("X-" + file + "-foundgrains.png");
}
}
}
}
public class Grain
{
private const int MIN_WIDTH = 70;
private const int MAX_WIDTH = 130;
private const int MIN_HEIGHT = 20;
private const int MAX_HEIGHT = 35;
private static CvFont font01 = new CvFont(FontFace.HersheyPlain, 0.5, 1);
private Random random = new Random(4); // determined by fair dice throw; guaranteed to be random
/// <summary> center of grain </summary>
public CvPoint2D32f Position { get; private set; }
/// <summary> Width of grain (always bigger than height)</summary>
public float Width { get; private set; }
/// <summary> Height of grain (always smaller than width)</summary>
public float Height { get; private set; }
public float MinorRadius { get { return this.Height / 2; } }
public float MajorRadius { get { return this.Width / 2; } }
public double Angle { get; private set; }
public double AngleRad { get { return this.Angle * Math.PI / 180; } }
public int Index { get; set; }
public bool Converged { get; private set; }
public int NumIterations { get; private set; }
public double CircumferenceRatio { get; private set; }
public int NumPixel { get; private set; }
public List<EllipsePoint> EdgePoints { get; private set; }
public double MeanSquaredError { get; private set; }
public double PixelRatio { get { return this.NumPixel / (Math.PI * this.MajorRadius * this.MinorRadius); } }
public bool IsTooSmall { get { return this.Width < MIN_WIDTH || this.Height < MIN_HEIGHT; } }
public Grain(CvPoint2D32f position)
{
this.Position = position;
this.Angle = 0;
this.Width = 10;
this.Height = 10;
this.MeanSquaredError = double.MaxValue;
}
/// <summary> fit a single rice grain of elipsoid shape </summary>
public void Fit(CvMat img)
{
// distance between the sampled points on the elipse circumference in degree
int angularResolution = 1;
// how many times did the fitted ellipse not change significantly?
int numConverged = 0;
// number of iterations for this fit
int numIterations;
// repeat until the fitted ellipse does not change anymore, or the maximum number of iterations is reached
for (numIterations = 0; numIterations < 100 && !this.Converged; numIterations++)
{
// points on an ideal ellipse
CvPoint[] points;
Cv.Ellipse2Poly(this.Position, new CvSize2D32f(MajorRadius, MinorRadius), Convert.ToInt32(this.Angle), 0, 359, out points,
angularResolution);
// points on the edge of foregroudn to background, that are close to the elipse
CvPoint?[] edgePoints = new CvPoint?[points.Length];
// remeber if the previous pixel in a given direction was foreground or background
bool[] prevPixelWasForeground = new bool[points.Length];
// when the first edge pixel is found, this value is updated
double firstEdgePixelOffset = 200;
// from the center of the elipse towards the outside:
for (float offset = -this.MajorRadius + 1; offset < firstEdgePixelOffset + 20; offset++)
{
// draw an ellipse with the given offset
Cv.Ellipse2Poly(this.Position, new CvSize2D32f(MajorRadius + offset, MinorRadius + (offset > 0 ? offset : MinorRadius / MajorRadius * offset)), Convert.ToInt32(this.Angle), 0,
359, out points, angularResolution);
// for each angle
Parallel.For(0, points.Length, i =>
{
if (edgePoints[i].HasValue) return; // edge for this angle already found
// check if the current pixel is foreground
bool foreground = points[i].X < 0 || points[i].Y < 0 || points[i].X >= img.Cols || points[i].Y >= img.Rows
? false // pixel outside of image borders is always background
: img.Get2D(points[i].Y, points[i].X).Val0 > 0;
if (prevPixelWasForeground[i] && !foreground)
{
// found edge pixel!
edgePoints[i] = points[i];
// if this is the first edge pixel we found, remember its offset. the other pixels cannot be too far away, so we can stop searching soon
if (offset < firstEdgePixelOffset && offset > 0) firstEdgePixelOffset = offset;
}
prevPixelWasForeground[i] = foreground;
});
}
// estimate the distance of each found edge pixel from the ideal elipse
// this is a hack, since the actual equations for estimating point-ellipse distnaces are complicated
Cv.Ellipse2Poly(this.Position, new CvSize2D32f(MajorRadius, MinorRadius), Convert.ToInt32(this.Angle), 0, 360,
out points, angularResolution);
var pointswithDistance =
edgePoints.Select((p, i) => p.HasValue ? new EllipsePoint(p.Value, points[i], this.Position) : null)
.Where(p => p != null).ToList();
if (pointswithDistance.Count == 0)
{
Console.WriteLine("no points found! should never happen! ");
break;
}
// throw away all outliers that are too far outside the current ellipse
double medianSignedDistance = pointswithDistance.OrderBy(p => p.SignedDistance).ElementAt(pointswithDistance.Count / 2).SignedDistance;
var goodPoints = pointswithDistance.Where(p => p.SignedDistance < medianSignedDistance + 15).ToList();
// do a sort of ransack fit with the inlier points to find a new better ellipse
CvBox2D bestfit = ellipseRansack(goodPoints);
// check if the fit has converged
if (Math.Abs(this.Angle - bestfit.Angle) < 3 && // angle has not changed much (<3°)
Math.Abs(this.Position.X - bestfit.Center.X) < 3 && // position has not changed much (<3 pixel)
Math.Abs(this.Position.Y - bestfit.Center.Y) < 3)
{
numConverged++;
}
else
{
numConverged = 0;
}
if (numConverged > 2)
{
this.Converged = true;
}
//Console.WriteLine("Iteration {0}, delta {1:0.000} {2:0.000} {3:0.000} {4:0.000}-{5:0.000} {6:0.000}-{7:0.000} {8:0.000}-{9:0.000}",
// numIterations, Math.Abs(this.Angle - bestfit.Angle), Math.Abs(this.Position.X - bestfit.Center.X), Math.Abs(this.Position.Y - bestfit.Center.Y), this.Angle, bestfit.Angle, this.Position.X, bestfit.Center.X, this.Position.Y, bestfit.Center.Y);
double msr = goodPoints.Sum(p => p.Distance * p.Distance) / goodPoints.Count;
// for drawing the polygon, filter the edge points more strongly
if (goodPoints.Count(p => p.SignedDistance < 5) > goodPoints.Count / 2)
goodPoints = goodPoints.Where(p => p.SignedDistance < 5).ToList();
double cutoff = goodPoints.Select(p => p.Distance).OrderBy(d => d).ElementAt(goodPoints.Count * 9 / 10);
goodPoints = goodPoints.Where(p => p.SignedDistance <= cutoff + 1).ToList();
int numCertainEdgePoints = goodPoints.Count(p => p.SignedDistance > -2);
this.CircumferenceRatio = numCertainEdgePoints * 1.0 / points.Count();
this.Angle = bestfit.Angle;
this.Position = bestfit.Center;
this.Width = bestfit.Size.Width;
this.Height = bestfit.Size.Height;
this.EdgePoints = goodPoints;
this.MeanSquaredError = msr;
}
this.NumIterations = numIterations;
//Console.WriteLine("Grain found after {0,3} iterations, size={1,3:0.}x{2,3:0.} pixel={3,5} edgePoints={4,3} msr={5,2:0.00000}", numIterations, this.Width,
// this.Height, this.NumPixel, this.EdgePoints.Count, this.MeanSquaredError);
}
/// <summary> a sort of ransakc fit to find the best ellipse for the given points </summary>
private CvBox2D ellipseRansack(List<EllipsePoint> points)
{
using (CvMemStorage storage = new CvMemStorage(0))
{
// calculate minimum bounding rectangle
CvSeq<CvPoint> fullPointSeq = CvSeq<CvPoint>.FromArray(points.Select(p => p.Point), SeqType.EltypePoint, storage);
var boundingRect = fullPointSeq.MinAreaRect2();
// the initial candidate is the previously found ellipse
CvBox2D bestEllipse = new CvBox2D(this.Position, new CvSize2D32f(this.Width, this.Height), (float)this.Angle);
double bestError = calculateEllipseError(points, bestEllipse);
Queue<EllipsePoint> permutation = new Queue<EllipsePoint>();
if (points.Count >= 5) for (int i = -2; i < 20; i++)
{
CvBox2D ellipse;
if (i == -2)
{
// first, try the ellipse described by the boundingg rect
ellipse = boundingRect;
}
else if (i == -1)
{
// then, try the best-fit ellipsethrough all points
ellipse = fullPointSeq.FitEllipse2();
}
else
{
// then, repeatedly fit an ellipse through a random sample of points
// pick some random points
if (permutation.Count < 5) permutation = new Queue<EllipsePoint>(permutation.Concat(points.OrderBy(p => random.Next())));
CvSeq<CvPoint> pointSeq = CvSeq<CvPoint>.FromArray(permutation.Take(10).Select(p => p.Point), SeqType.EltypePoint, storage);
for (int j = 0; j < pointSeq.Count(); j++) permutation.Dequeue();
// fit an ellipse through these points
ellipse = pointSeq.FitEllipse2();
}
// assure that the width is greater than the height
ellipse = NormalizeEllipse(ellipse);
// if the ellipse is too big for agrain, shrink it
ellipse = rightSize(ellipse, points.Where(p => isOnEllipse(p.Point, ellipse, 10, 10)).ToList());
// sometimes the ellipse given by FitEllipse2 is totally off
if (boundingRect.Center.DistanceTo(ellipse.Center) > Math.Max(boundingRect.Size.Width, boundingRect.Size.Height) * 2)
{
// ignore this bad fit
continue;
}
// estimate the error
double error = calculateEllipseError(points, ellipse);
if (error < bestError)
{
// found a better ellipse!
bestError = error;
bestEllipse = ellipse;
}
}
return bestEllipse;
}
}
/// <summary> The proper thing to do would be to use the actual distance of each point to the elipse.
/// However that formula is complicated, so ... </summary>
private double calculateEllipseError(List<EllipsePoint> points, CvBox2D ellipse)
{
const double toleranceInner = 5;
const double toleranceOuter = 10;
int numWrongPoints = points.Count(p => !isOnEllipse(p.Point, ellipse, toleranceInner, toleranceOuter));
double ratioWrongPoints = numWrongPoints * 1.0 / points.Count;
int numTotallyWrongPoints = points.Count(p => !isOnEllipse(p.Point, ellipse, 10, 20));
double ratioTotallyWrongPoints = numTotallyWrongPoints * 1.0 / points.Count;
// this pseudo-distance is biased towards deviations on the major axis
double pseudoDistance = Math.Sqrt(points.Sum(p => Math.Abs(1 - ellipseMetric(p.Point, ellipse))) / points.Count);
// primarily take the number of points far from the elipse border as an error metric.
// use pseudo-distance to break ties between elipses with the same number of wrong points
return ratioWrongPoints * 1000 + ratioTotallyWrongPoints+ pseudoDistance / 1000;
}
/// <summary> shrink an ellipse if it is larger than the maximum grain dimensions </summary>
private static CvBox2D rightSize(CvBox2D ellipse, List<EllipsePoint> points)
{
if (ellipse.Size.Width < MAX_WIDTH && ellipse.Size.Height < MAX_HEIGHT) return ellipse;
// elipse is bigger than the maximum grain size
// resize it so it fits, while keeping one edge of the bounding rectangle constant
double desiredWidth = Math.Max(10, Math.Min(MAX_WIDTH, ellipse.Size.Width));
double desiredHeight = Math.Max(10, Math.Min(MAX_HEIGHT, ellipse.Size.Height));
CvPoint2D32f average = points.Average();
// get the corners of the surrounding bounding box
var corners = ellipse.BoxPoints().ToList();
// find the corner that is closest to the center of mass of the points
int i0 = ellipse.BoxPoints().Select((point, index) => new { point, index }).OrderBy(p => p.point.DistanceTo(average)).First().index;
CvPoint p0 = corners[i0];
// find the two corners that are neighbouring this one
CvPoint p1 = corners[(i0 + 1) % 4];
CvPoint p2 = corners[(i0 + 3) % 4];
// p1 is the next corner along the major axis (widht), p2 is the next corner along the minor axis (height)
if (p0.DistanceTo(p1) < p0.DistanceTo(p2))
{
CvPoint swap = p1;
p1 = p2;
p2 = swap;
}
// calculate the three other corners with the desired widht and height
CvPoint2D32f edge1 = (p1 - p0);
CvPoint2D32f edge2 = p2 - p0;
double edge1Length = Math.Max(0.0001, p0.DistanceTo(p1));
double edge2Length = Math.Max(0.0001, p0.DistanceTo(p2));
CvPoint2D32f newCenter = (CvPoint2D32f)p0 + edge1 * (desiredWidth / edge1Length) + edge2 * (desiredHeight / edge2Length);
CvBox2D smallEllipse = new CvBox2D(newCenter, new CvSize2D32f((float)desiredWidth, (float)desiredHeight), ellipse.Angle);
return smallEllipse;
}
/// <summary> assure that the width of the elipse is the major axis, and the height is the minor axis.
/// Swap widht/height and rotate by 90° otherwise </summary>
private static CvBox2D NormalizeEllipse(CvBox2D ellipse)
{
if (ellipse.Size.Width < ellipse.Size.Height)
{
ellipse = new CvBox2D(ellipse.Center, new CvSize2D32f(ellipse.Size.Height, ellipse.Size.Width), (ellipse.Angle + 90 + 360) % 360);
}
return ellipse;
}
/// <summary> greater than 1 for points outside ellipse, smaller than 1 for points inside ellipse </summary>
private static double ellipseMetric(CvPoint p, CvBox2D ellipse)
{
double theta = ellipse.Angle * Math.PI / 180;
double u = Math.Cos(theta) * (p.X - ellipse.Center.X) + Math.Sin(theta) * (p.Y - ellipse.Center.Y);
double v = -Math.Sin(theta) * (p.X - ellipse.Center.X) + Math.Cos(theta) * (p.Y - ellipse.Center.Y);
return u * u / (ellipse.Size.Width * ellipse.Size.Width / 4) + v * v / (ellipse.Size.Height * ellipse.Size.Height / 4);
}
/// <summary> Is the point on the ellipseBorder, within a certain tolerance </summary>
private static bool isOnEllipse(CvPoint p, CvBox2D ellipse, double toleranceInner, double toleranceOuter)
{
double theta = ellipse.Angle * Math.PI / 180;
double u = Math.Cos(theta) * (p.X - ellipse.Center.X) + Math.Sin(theta) * (p.Y - ellipse.Center.Y);
double v = -Math.Sin(theta) * (p.X - ellipse.Center.X) + Math.Cos(theta) * (p.Y - ellipse.Center.Y);
double innerEllipseMajor = (ellipse.Size.Width - toleranceInner) / 2;
double innerEllipseMinor = (ellipse.Size.Height - toleranceInner) / 2;
double outerEllipseMajor = (ellipse.Size.Width + toleranceOuter) / 2;
double outerEllipseMinor = (ellipse.Size.Height + toleranceOuter) / 2;
double inside = u * u / (innerEllipseMajor * innerEllipseMajor) + v * v / (innerEllipseMinor * innerEllipseMinor);
double outside = u * u / (outerEllipseMajor * outerEllipseMajor) + v * v / (outerEllipseMinor * outerEllipseMinor);
return inside >= 1 && outside <= 1;
}
/// <summary> count the number of foreground pixels for this grain </summary>
public int CountPixel(CvMat img)
{
// todo: this is an incredibly inefficient way to count, allocating a new image with the size of the input each time
using (CvMat mask = new CvMat(img.Rows, img.Cols, MatrixType.U8C1))
{
mask.SetZero();
mask.FillPoly(new CvPoint[][] { this.EdgePoints.Select(p => p.Point).ToArray() }, CvColor.White);
mask.And(img, mask);
this.NumPixel = mask.CountNonZero();
}
return this.NumPixel;
}
/// <summary> draw the recognized shape of the grain </summary>
public void Draw(CvMat img, CvColor color)
{
img.FillPoly(new CvPoint[][] { this.EdgePoints.Select(p => p.Point).ToArray() }, color);
}
/// <summary> draw the contours of the grain </summary>
public void DrawContour(CvMat img, CvColor color)
{
img.DrawPolyLine(new CvPoint[][] { this.EdgePoints.Select(p => p.Point).ToArray() }, true, color);
}
/// <summary> draw the best-fit ellipse of the grain </summary>
public void DrawEllipse(CvMat img, CvColor color)
{
img.DrawEllipse(this.Position, new CvSize2D32f(this.MajorRadius, this.MinorRadius), this.Angle, 0, 360, color, 1);
}
/// <summary> print the grain index and the number of pixels divided by the average grain size</summary>
public void DrawText(double averageGrainSize, CvMat img, CvColor color)
{
img.PutText(String.Format("{0}|{1:0.0}", this.Index, this.NumPixel / averageGrainSize), this.Position + new CvPoint2D32f(-5, 10), font01, color);
}
}
```
I am a little embarrassed with this solution because a) I am not sure whether it is within the spirit of this challenge, and b) it is too big for a codegolf answer and lacks the elegance of the other solutions.
On the other hand, I am quite happy with the progress I achieved in *labeling* the grains, not merely counting them, so there is that.
[Answer]
# **C++, OpenCV, score: 9**
Basic idea of my method is quite simple - try to erase single grains(and "double grains" - 2 (but not more!) grains, close to each other) from image and then count rest using method based on area (like Falko, Ell and belisarius). Using this approach is a bit better than standard "area method", because it is easier to find good averagePixelsPerObject value.
(1st step)First of all we need to use Otsu binarization on S channel of image in HSV. The next step is using dilate operator to improve quality of extracted foreground. Than we need to find contours. Of course some contours are not grains of rice - we need to delete too small contours (with area smaller then averagePixelsPerObject/4. averagePixelsPerObject is 2855 in my situation). Now finally we can start counting grains :) (2nd step) Finding single and double grains is quite simple - just look in contours list for contours with area within specific ranges - if the contour area is in range, delete it from list and add 1 (or 2 if it was "double" grain) to grains counter. (3rd step) The last step is of course dividing area of remaining contours by averagePixelsPerObject value and add result to grains counter.
Images (for image F.jpg) should show this idea better than words:
1st step (without small contours(noise)):
![1st step (without small contours(noise))](https://i.stack.imgur.com/EUdgZ.png)
2nd step - only simple contours:
![2nd step - only simple contours](https://i.stack.imgur.com/AVIx6.png)
3rd step - remaining contours:
![3rd step - remaining contours](https://i.stack.imgur.com/nXXvR.png)
Here is the code, it's rather ugly, but should work without any problem. Of course OpenCV is required.
```
#include "stdafx.h"
#include <cv.hpp>
#include <cxcore.h>
#include <highgui.h>
#include <vector>
using namespace cv;
using namespace std;
//A: 3, B: 5, C: 12, D: 25, E: 50, F: 83, G: 120, H:150, I: 151, J: 200
const int goodResults[] = {3, 5, 12, 25, 50, 83, 120, 150, 151, 200};
const float averagePixelsPerObject = 2855.0;
const int singleObjectPixelsCountMin = 2320;
const int singleObjectPixelsCountMax = 4060;
const int doubleObjectPixelsCountMin = 5000;
const int doubleObjectPixelsCountMax = 8000;
float round(float x)
{
return x >= 0.0f ? floorf(x + 0.5f) : ceilf(x - 0.5f);
}
Mat processImage(Mat m, int imageIndex, int &error)
{
int objectsCount = 0;
Mat output, thresholded;
cvtColor(m, output, CV_BGR2HSV);
vector<Mat> channels;
split(output, channels);
threshold(channels[1], thresholded, 0, 255, CV_THRESH_OTSU | CV_THRESH_BINARY);
dilate(thresholded, output, Mat()); //dilate to imporove quality of binary image
imshow("thresholded", thresholded);
int nonZero = countNonZero(output); //not realy important - just for tests
if (imageIndex != -1)
cout << "non zero: " << nonZero << ", average pixels per object: " << nonZero/goodResults[imageIndex] << endl;
else
cout << "non zero: " << nonZero << endl;
vector<vector<Point>> contours, contoursOnlyBig, contoursWithoutSimpleObjects, contoursSimple;
findContours(output, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); //find only external contours
for (int i=0; i<contours.size(); i++)
if (contourArea(contours[i]) > averagePixelsPerObject/4.0)
contoursOnlyBig.push_back(contours[i]); //add only contours with area > averagePixelsPerObject/4 ---> skip small contours (noise)
Mat bigContoursOnly = Mat::zeros(output.size(), output.type());
Mat allContours = bigContoursOnly.clone();
drawContours(allContours, contours, -1, CV_RGB(255, 255, 255), -1);
drawContours(bigContoursOnly, contoursOnlyBig, -1, CV_RGB(255, 255, 255), -1);
//imshow("all contours", allContours);
output = bigContoursOnly;
nonZero = countNonZero(output); //not realy important - just for tests
if (imageIndex != -1)
cout << "non zero: " << nonZero << ", average pixels per object: " << nonZero/goodResults[imageIndex] << " objects: " << goodResults[imageIndex] << endl;
else
cout << "non zero: " << nonZero << endl;
for (int i=0; i<contoursOnlyBig.size(); i++)
{
double area = contourArea(contoursOnlyBig[i]);
if (area >= singleObjectPixelsCountMin && area <= singleObjectPixelsCountMax) //is this contours a single grain ?
{
contoursSimple.push_back(contoursOnlyBig[i]);
objectsCount++;
}
else
{
if (area >= doubleObjectPixelsCountMin && area <= doubleObjectPixelsCountMax) //is this contours a double grain ?
{
contoursSimple.push_back(contoursOnlyBig[i]);
objectsCount+=2;
}
else
contoursWithoutSimpleObjects.push_back(contoursOnlyBig[i]); //group of grainss
}
}
cout << "founded single objects: " << objectsCount << endl;
Mat thresholdedImageMask = Mat::zeros(output.size(), output.type()), simpleContoursMat = Mat::zeros(output.size(), output.type());
drawContours(simpleContoursMat, contoursSimple, -1, CV_RGB(255, 255, 255), -1);
if (contoursWithoutSimpleObjects.size())
drawContours(thresholdedImageMask, contoursWithoutSimpleObjects, -1, CV_RGB(255, 255, 255), -1); //draw only contours of groups of grains
imshow("simpleContoursMat", simpleContoursMat);
imshow("thresholded image mask", thresholdedImageMask);
Mat finalResult;
thresholded.copyTo(finalResult, thresholdedImageMask); //copy using mask - only pixels whc=ich belongs to groups of grains will be copied
//imshow("finalResult", finalResult);
nonZero = countNonZero(finalResult); // count number of pixels in all gropus of grains (of course without single or double grains)
int goodObjectsLeft = goodResults[imageIndex]-objectsCount;
if (imageIndex != -1)
cout << "non zero: " << nonZero << ", average pixels per object: " << (goodObjectsLeft ? (nonZero/goodObjectsLeft) : 0) << " objects left: " << goodObjectsLeft << endl;
else
cout << "non zero: " << nonZero << endl;
objectsCount += round((float)nonZero/(float)averagePixelsPerObject);
if (imageIndex != -1)
{
error = objectsCount-goodResults[imageIndex];
cout << "final objects count: " << objectsCount << ", should be: " << goodResults[imageIndex] << ", error is: " << error << endl;
}
else
cout << "final objects count: " << objectsCount << endl;
return output;
}
int main(int argc, char* argv[])
{
string fileName = "A";
int totalError = 0, error;
bool fastProcessing = true;
vector<int> errors;
if (argc > 1)
{
Mat m = imread(argv[1]);
imshow("image", m);
processImage(m, -1, error);
waitKey(-1);
return 0;
}
while(true)
{
Mat m = imread("images\\" + fileName + ".jpg");
cout << "Processing image: " << fileName << endl;
imshow("image", m);
processImage(m, fileName[0] - 'A', error);
totalError += abs(error);
errors.push_back(error);
if (!fastProcessing && waitKey(-1) == 'q')
break;
fileName[0] += 1;
if (fileName[0] > 'J')
{
if (fastProcessing)
break;
else
fileName[0] = 'A';
}
}
cout << "Total error: " << totalError << endl;
cout << "Errors: " << (Mat)errors << endl;
cout << "averagePixelsPerObject:" << averagePixelsPerObject << endl;
return 0;
}
```
If you want to see results of all steps, uncomment all imshow(..,..) function calls and set fastProcessing variable to false. Images(A.jpg, B.jpg,...) should be in directory images. Alternatively course you can give name of one image as a parameter from command line.
Of course if something is unclear i can explain it and/or provide some images/informations.
[Answer]
## C# + OpenCvSharp, score: 71
This is most vexing, I tried to get a solution that actually identifies each grain using [watershed](http://en.wikipedia.org/wiki/Watershed_%28image_processing%29), but I just. can't. get. it. to. work.
I settled for a solution that at least separates *some* individual grains and then uses those grains to estimate the average grain size. However so far I cannot beat the solutions with hardcoded grain size.
So, the main highlight of this solution: it does not presume a fixed pixel size for grains, and should work even if the camera is moved or the type of rice is changed.
```
A.jpg; number of grains: 3; expected 3; error 0; pixels per grain: 2525,0;
B.jpg; number of grains: 7; expected 5; error 2; pixels per grain: 1920,0;
C.jpg; number of grains: 6; expected 12; error 6; pixels per grain: 4242,5;
D.jpg; number of grains: 23; expected 25; error 2; pixels per grain: 2415,5;
E.jpg; number of grains: 47; expected 50; error 3; pixels per grain: 2729,9;
F.jpg; number of grains: 65; expected 83; error 18; pixels per grain: 2860,5;
G.jpg; number of grains: 120; expected 120; error 0; pixels per grain: 2552,3;
H.jpg; number of grains: 159; expected 150; error 9; pixels per grain: 2624,7;
I.jpg; number of grains: 141; expected 151; error 10; pixels per grain: 2697,4;
J.jpg; number of grains: 179; expected 200; error 21; pixels per grain: 2847,1;
total error: 71
```
My solution works like this:
Separate the foreground by transforming the image to [HSV](http://en.wikipedia.org/wiki/HSL_and_HSV) and applying [Otsu thresholding](http://en.wikipedia.org/wiki/Otsu%27s_method) on the saturation channel. This is very simply, works extremely well, and I would recommend this for everyone else who wants to try this challenge:
```
saturation channel --> Otsu thresholding
```
![enter image description here](https://i.stack.imgur.com/uxuPam.png) --> ![enter image description here](https://i.stack.imgur.com/uZBukm.png)
This will cleanly remove the background.
I then additionally removed the *grain shadows* from the foreground, by applying a fixed threshold to the value-channel. (Not sure if that actually helps much, but it was simple enough to add)
![enter image description here](https://i.stack.imgur.com/k3t5Jm.png)
Then I apply a [distance transform](http://en.wikipedia.org/wiki/Distance_transform) on the foreground image.
![enter image description here](https://i.stack.imgur.com/us6yIm.png)
and find all local maxima in this distance transform.
This is where my idea breaks down. to avoid getting mutiple local maxima within the same grain, I have to filter a lot. Currently I keep only the strongest maximum within a 45 pixel radius, which means not every grain has a local maximum. And I don't really have a justification for the 45 pixel radius, it was just a value that worked.
![enter image description here](https://i.stack.imgur.com/9YFWxm.png)
(as you can see, those are not nearly enough seeds to account for each grain)
Then I use those maxima as seeds for the watershed algorithm:
![enter image description here](https://i.stack.imgur.com/qxOmMm.png)
The results are *meh*. I was hoping for mostly individual grains, but the clumps are still too big.
Now I identify the smallest blobs, count their average pixel size, and then estimate the number of grains from that. This is *not* what I planned to do at the start, but this was the only way to salvage this.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCvSharp;
namespace GrainTest2
{
class Program
{
static void Main(string[] args)
{
string[] files = new[]
{
"sourceA.jpg", "sourceB.jpg", "sourceC.jpg",
"sourceD.jpg", "sourceE.jpg", "sourceF.jpg",
"sourceG.jpg", "sourceH.jpg", "sourceI.jpg", "sourceJ.jpg",
};
int[] expectedGrains = new[]{3, 5, 12, 25, 50, 83, 120, 150, 151, 200,};
int totalError = 0;
int totalPixels = 0;
for(int fileNo = 0;fileNo markers = new List();
using (CvMemStorage storage = new CvMemStorage())
using (CvContourScanner scanner = new CvContourScanner(localMaxima, storage, CvContour.SizeOf, ContourRetrieval.External,ContourChain.ApproxNone))
{
// set each local maximum as seed number 25, 35, 45,...
// (actual numbers do not matter, chosen for better visibility in the png)
int markerNo = 20;
foreach (CvSeq c in scanner)
{
markerNo += 5;
markers.Add(markerNo);
waterShedMarkers.DrawContours(c, new CvScalar(markerNo), new CvScalar(markerNo), 0, -1);
}
}
waterShedMarkers.SaveImage("08-watershed-seeds.png");
source.Watershed(waterShedMarkers);
waterShedMarkers.SaveImage("09-watershed-result.png");
List pixelsPerBlob = new List();
// Terrible hack because I could not get Cv2.ConnectedComponents to work with this openCv wrapper
// So I made a workaround to count the number of pixels per blob
waterShedMarkers.ConvertScale(waterShedThreshold);
foreach (int markerNo in markers)
{
using (CvMat tmp = new CvMat(waterShedMarkers.Rows, waterShedThreshold.Cols, MatrixType.U8C1))
{
waterShedMarkers.CmpS(markerNo, tmp, ArrComparison.EQ);
pixelsPerBlob.Add(tmp.CountNonZero());
}
}
// estimate the size of a single grain
// step 1: assume that the 10% smallest blob is a whole grain;
double singleGrain = pixelsPerBlob.OrderBy(p => p).ElementAt(pixelsPerBlob.Count/15);
// step2: take all blobs that are not much bigger than the currently estimated singel grain size
// average their size
// repeat until convergence (too lazy to check for convergence)
for (int i = 0; i p Math.Round(p/singleGrain)).Sum());
Console.WriteLine("input: {0}; number of grains: {1,4:0.}; expected {2,4}; error {3,4}; pixels per grain: {4:0.0}; better: {5:0.}", file, numGrains, expectedGrains[fileNo], Math.Abs(numGrains - expectedGrains[fileNo]), singleGrain, pixelsPerBlob.Sum() / 1434.9);
totalError += Math.Abs(numGrains - expectedGrains[fileNo]);
totalPixels += pixelsPerBlob.Sum();
// this is a terrible hack to visualise the estimated number of grains per blob.
// i'm too tired to clean it up
#region please ignore
using (CvMemStorage storage = new CvMemStorage())
using (CvMat tmp = waterShedThreshold.Clone())
using (CvMat tmpvisu = new CvMat(source.Rows, source.Cols, MatrixType.S8C3))
{
foreach (int markerNo in markers)
{
tmp.SetZero();
waterShedMarkers.CmpS(markerNo, tmp, ArrComparison.EQ);
double curGrains = tmp.CountNonZero() * 1.0 / singleGrain;
using (
CvContourScanner scanner = new CvContourScanner(tmp, storage, CvContour.SizeOf, ContourRetrieval.External,
ContourChain.ApproxNone))
{
tmpvisu.Set(CvColor.Random(), tmp);
foreach (CvSeq c in scanner)
{
//tmpvisu.DrawContours(c, CvColor.Random(), CvColor.DarkGreen, 0, -1);
tmpvisu.PutText("" + Math.Round(curGrains, 1), c.First().Value, new CvFont(FontFace.HersheyPlain, 2, 2),
CvColor.Red);
}
}
}
tmpvisu.SaveImage("10-visu.png");
tmpvisu.SaveImage("10-visu" + file + ".png");
}
#endregion
}
}
Console.WriteLine("total error: {0}, ideal Pixel per Grain: {1:0.0}", totalError, totalPixels*1.0/expectedGrains.Sum());
}
}
}
```
A small test using a hard-coded pixel-per-grain size of 2544.4 showed a total error of 36, which is still bigger than most other solutions.
![enter image description here](https://i.stack.imgur.com/ZxjPg.png)
![enter image description here](https://i.stack.imgur.com/cvz4om.png)
![enter image description here](https://i.stack.imgur.com/riXDDm.png)
![enter image description here](https://i.stack.imgur.com/WzhC3m.png)
[Answer]
# HTML + Javascript: Score 39
The exact values are:
```
Estimated | Actual
3 | 3
5 | 5
12 | 12
23 | 25
51 | 50
82 | 83
125 | 120
161 | 150
167 | 151
223 | 200
```
It breaks down (isn't accurate) on the larger values.
```
window.onload = function() {
var $ = document.querySelector.bind(document);
var canvas = $("canvas"),
ctx = canvas.getContext("2d");
function handleFileSelect(evt) {
evt.preventDefault();
var file = evt.target.files[0],
reader = new FileReader();
if (!file) return;
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
start();
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
function start() {
var imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imgdata.data;
var background = 0;
var totalPixels = data.length / 4;
for (var i = 0; i < data.length; i += 4) {
var red = data[i],
green = data[i + 1],
blue = data[i + 2];
if (Math.abs(red - 197) < 40 && Math.abs(green - 176) < 40 && Math.abs(blue - 133) < 40) {
++background;
data[i] = 1;
data[i + 1] = 1;
data[i + 2] = 1;
}
}
ctx.putImageData(imgdata, 0, 0);
console.log("Pixels of rice", (totalPixels - background));
// console.log("Total pixels", totalPixels);
$("output").innerHTML = "Approximately " + Math.round((totalPixels - background) / 2670) + " grains of rice.";
}
$("input").onchange = handleFileSelect;
}
```
```
<input type="file" id="f" />
<canvas></canvas>
<output></output>
```
Explanation: Basically, counts the number of rice pixels and divides it by the average pixels per grain.
[Answer]
An attempt with php, Not the lowest scoring answer but its fairly simple code
SCORE : 31
```
<?php
for($c = 1; $c <= 10; $c++) {
$a = imagecreatefromjpeg("/tmp/$c.jpg");
list($width, $height) = getimagesize("/tmp/$c.jpg");
$rice = 0;
for($i = 0; $i < $width; $i++) {
for($j = 0; $j < $height; $j++) {
$colour = imagecolorat($a, $i, $j);
if (($colour & 0xFF) < 95) $rice++;
}
}
echo ceil($rice/2966);
}
```
Self scoring
95 is a blue value which seemed to work when testing with GIMP 2966 is average grain size
] |
[Question]
[
Say I have text like this (each word on one line, with no spaces)
```
Programming
Puzzles
&
Code
Golf
```
That makes no sense! It totally defies the laws of physics.
Your challenge is to remedy this impossible situation and collapse the text like so:
```
P
Prog
&uzz
Coderam
Golflesming
```
So that there is no empty space underneath any character but the characters retain their vertical order.
The goal is to satisfy the requirements but use the fewest bytes of source code possible.
[Answer]
# Pyth, 10 bytes
```
jb_.T.T_.z
```
Try it online in the [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=jb_.T.T_.z&input=Programming%0APuzzles%0A%26%0ACode%0AGolf&debug=0).
### Idea
We can achieve the desired output by applying four simple transformations:
1. Reverse the order of the lines:
```
Golf
Code
&
Puzzles
Programming
```
2. Transpose rows and columns:
```
GC&PP
oour
ldzo
fezg
lr
ea
sm
m
i
n
g
```
This top justifies, collapsing the original columns.
3. Transpose rows and columns:
```
Golflesming
Coderam
&uzz
Prog
P
```
4. Reverse the order of the lines:
```
P
Prog
&uzz
Coderam
Golflesming
```
### Code
```
.z Read the input as a list of strings, delimited by linefeeds.
_ Reverse the list.
.T.T Transpose the list twice.
_ Reverse the list.
jb Join its strings; separate with linefeeds.
```
[Answer]
# Haskell, 62 bytes
```
import Data.List
p=reverse;o=transpose
f=unlines.p.o.o.p.lines
```
I'm very mature.
[Answer]
## Python 2, 104 bytes
```
l=[]
for x in input().split('\n'):n=len(x);l=[a[:n]+b[n:]for a,b in zip(l+[x],['']+l)]
print'\n'.join(l)
```
An iterative one-pass algorithm. We go through each line in order, updating the list `l` of lines to output. The new word effectively pushes from the bottom, shifting all letters above it one space. For example, in the test case
```
Programming
Puzzles
&
Code
Golf
```
after we've done up to `Code`, we have
```
P
Prog
&uzzram
Codelesming
```
and then adding `Golf` results in
```
P
Prog
&uzz
Coderam
Golflesming
```
which we can view as the combination of two pieces
```
P |
Prog |
&uzz |
Code | ram
Golf | lesming
```
where the first piece got shifted up by `golf`. We perform this shifting with a `zip` of the output list with the element at the end (left side) and output list precedence by a blank line (right side), cutting off each part at the length of the new element.
It might seem more natural to instead iterate backwards, letting new letters fall from the top, but my attempt at that turned out longer.
For comparison, here's a `zip`/`filter` approach, with `map(None,*x)` used for `iziplongest` (109 bytes):
```
f=lambda z:[''.join(filter(None,x))for x in map(None,*z)]
lambda x:'\n'.join(f(f(x.split('\n')[::-1]))[::-1])
```
[Answer]
# CJam, 11 bytes
```
qN/W%zzW%N*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2FW%25zzW%25N*&input=Programming%0APuzzles%0A%26%0ACode%0AGolf).
### How it works
The idea in the same as in my [Pyth answer](https://codegolf.stackexchange.com/a/55229).
```
q e# Read from STDIN.
N/ e# Split at linefeeds.
W% e# Reverse the resulting array.
zz e# Transpose it twice.
W% e# Reverse the resulting array.
N* e# Join its strings; separate with linefeeds.
```
[Answer]
# JavaScript (ES6), 146
(The 2 newlines inside template strings are significant and counted)
The idea of @Dennis implemented in JavaScript. The lengthy S function do the transposition line by line and char by char, leaving the result in the `t` array.
```
a=>(S=z=>{for(t=[];z.join``;t.push(w))for(w='',n=z.length;n--;z[n]=z[n].slice(1))w+=z[n][0]||''},S(a.split`
`),S(t.reverse()),t.reverse().join`
`)
```
Less golfed inside the snippet (try in Firefox)
```
F=a=>(
S=z=>{
for(t=[];z.join``;t.push(w))
for(w='',n=z.length;n--;z[n]=z[n].slice(1))
w+=z[n][0]||''
},
S(a.split`\n`),
S(t.reverse()),
t.reverse().join`\n`
)
```
```
#I,#O { margin:0; width: 200px; height:100px; border: 1px solid #ccc }
```
```
<table><tr><td>
Input<br><textarea id=I>Programming
Puzzles
&
Code
Golf
</textarea></td><td>
Output<pre id=O></pre>
</td></tr></table>
<button onclick='O.innerHTML=F(I.value)'>go</button>
```
[Answer]
# R, 223 bytes
```
function(x){a=apply(do.call(rbind,lapply(p<-strsplit(strsplit(x,"\n")[[1]],""),function(x)c(x,rep(" ",max(lengths(p))-length(x))))),2,function(x)c(x[x==" "],x[x!=" "]));for(i in 1:nrow(a))cat(a[i,][a[i,]!=" "],"\n",sep="")}
```
This is an absurdly long, naïve way of doing it.
Ungolfed:
```
f <- function(x) {
# Start by spliting the input into a vector on newlines
s <- strsplit(x, "\n")[[1]]
# Create a list consisting of each element of the vector
# split into a vector of single characters
p <- strsplit(s, "")
# Pad each vector in p to the same length with spaces
p <- lapply(p, function(x) c(x, rep(" ", max(lengths(p)) - length(x))))
# Now that the list has nice dimensions, turn it into a matrix
d <- do.call(rbind, p)
# Move the spaces to the top in each column of d
a <- apply(d, 2, function(x) c(x[x == " "], x[x != " "]))
# Print each row, omitting trailing whitespace
for (i in 1:nrow(a)) {
cat(a[i, ][a[i, ] != " "], "\n", sep = "")
}
}
```
You can [try it online](http://www.r-fiddle.org/#/fiddle?id=XgfuPBKd&version=1).
[Answer]
## Matlab / Octave, 99 bytes
```
function f(s)
c=char(strsplit(s,[10 '']));[~,i]=sort(c>32);[m,n]=size(c);c(i+repmat((0:n-1)*m,m,1))
```
**Example**:
Define an input string in a variable, say `s`. `10` is the line feed character:
```
>> s = ['Programming' 10 'Puzzles' 10 '&' 10 'Code' 10 'Golf'];
```
Call function `f` with input `s`:
```
>> f(s)
ans =
P
Prog
&uzz
Coderam
Golflesming
```
Or [**try it online**](http://ideone.com/XzvAoZ) (thanks to [@beaker](https://codegolf.stackexchange.com/users/42892/beaker) for help with the online Octave interpreter)
[Answer]
# JavaScript ES6, 119 bytes
```
F=s=>(C=o=>--a.length?C(a.reduce((p,c,i)=>c+p.slice((a[i-1]=p.slice(0,c.length)).length)))+`
`+o:o)(a=(s+`
`).split`
`)
```
Here it is ungolfed and in ES5 with comments explaining how it works:
```
function F(s) {
var arr = (s+'\n').split('\n'); // Create an array of words and append an empty member
return (function C(output) {
return --arr.length ? // Remove the last item from the array
C(arr.reduce(function(p,c,i) { // If the array still has length reduce it to a string and recurse
var intersection = (arr[i-1] = p.slice(0, c.length)) // Overwrite the previous word with the part that intersects the current word
return c + p.slice(intersection.length) // Add the part of the previous word that doesn't intersect to the current value
})) + '\n' + output : output // Add the last level of recursions output on to the end of this
})(arr);
}
input.addEventListener('input', updateOutput, false);
function updateOutput() {
var oldLength = input.value.length;
var start = this.selectionStart;
var end = this.selectionEnd;
input.value = input.value.split(/ +/).join('\n');
var newLength = input.value.length;
input.setSelectionRange(start, end + (newLength - oldLength));
output.value = F(input.value).trim();
}
updateOutput();
```
```
textarea {
width: 50%;
box-sizing: border-box;
resize: none;
float: left;
height: 10em;
}
label {
width: 50%;
float: left;
}
```
```
<p>Type in the input box below, spaces are automatically converted to newlines and the output updates as you type</p>
<label for="input">Input</label>
<label for="output">Output</label>
<textarea id="input">
Type inside me :)
</textarea>
<textarea id="output" disabled>
</textarea>
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~13~~ 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")
-2 with my extensions to Dyalog APL.
Anonymous tacit function, taking and returning a character matrix.
```
~∘' '⍤1⍢⍉⍢⊖
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v@5Rxwx1BfVHvUsMH/UuetTbCSK7pv1Pe9Q24VFv36O@qZ7@j7qaD603ftQ2EcgLDnIGkiEensH/0xSAQuoBRfnpRYm5uZl56UBzAkqrqnJSi4EsNSB2zk9JBVLu@Tlp6gA "APL (Dyalog Extended) – Try It Online")
`~` remove
`∘` the
`' '` spaces
`⍤` from
`1` rows (lit. 1D sub-arrays)
`⍢` while
`⍉` transposed
`⍢` while
`⊖` flipped
[Answer]
# R, ~~190~~ ~~178~~ 175 Bytes
Probably still some room for golfing in this. Probably a couple of unnecessary operations in there
```
l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')
```
Ungolfed and explained
```
a<-scan(,'') # get STDIN
h<-length(a) # number of lines
w=max(nchar(a)) # length of longest line
M<-lapply(a,substring,1:w,1:w) # create a list of split strings with empty chars
M<-do.call(rbind,M)[h:1,] # turn it into a matrix with line order reversed
M<-apply(M,1,paste0,collapse='') # paste together the columns
M<-lapply(M,substring,1:h,1:h) # split them back up
M<-do.call(rbind,M)[,h:1] # reform a matrix
M<-rbind(M,'\n') # add some carriage returns
cat(M,sep='') # output with seperators
```
Test Run. It is interesting to note that due to the way that scan works, the whole sentence can be input with spaces and still give the output as specified.
```
> l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')
1: Programming
2: Puzzles
3: &
4: Code
5: Golf
6:
Read 5 items
P
Prog
&uzz
Coderam
Golflesming
> l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')
1: Programming Puzzles & Code Golf beta
7:
Read 6 items
P
Prog
&uzz
Code
Golfram
betalesming
>
```
[Answer]
## STATA, 323 bytes
Takes input in a file called a.b
Only works for up to 24 characters now. Will update later to make it work with more. Also, doesn't work in the online compiler. Requires the non-free compiler.
```
gl l=24/
forv x=1/$l{
gl a="$a str a`x' `x'"
}
infix $a using a.b
gl b=_N
forv k=1/$l{
gen b`k'=0
qui forv i=$b(-1)1{
forv j=`i'/$b{
replace b`k'=1 if _n==`j'&a`k'==""
replace a`k'=a`k'[_n-1] if _n==`j'&a`k'==""
replace a`k'="" if _n==`j'-1&b`k'[_n+1]==1
replace b`k'=0
}
}
}
forv i=1/$b{
forv k=1/$l{
di a`k'[`i'] _c
}
di
}
```
Edit: moved the quietly (to suppress output) to the loop itself from each statement in the loop, saving 8 bytes.
[Answer]
# R, 171 bytes
```
S=scan(,"");while(any((D<-diff(N<-sapply(S,nchar)))<0)){n=max(which(D<0));S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]));S[n]=substr(S[n],1,N[n]+D[n])};cat(S,sep="\n")
```
With newlines and indentation:
```
S=scan(,"") #Takes input from stdin
while(any((D<-diff(N<-sapply(S,nchar)))<0)){
n=max(which(D<0))
S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]))
S[n]=substr(S[n],1,N[n]+D[n])
}
cat(S,sep="\n")
```
Usage:
```
> S=scan(,"");while(any((D<-diff(N<-sapply(S,nchar)))<0)){n=max(which(D<0));S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]));S[n]=substr(S[n],1,N[n]+D[n])};cat(S,sep="\n")
1: Programming
2: Puzzles
3: &
4: Code
5: Golf
6:
Read 5 items
P
Prog
&uzz
Coderam
Golflesming
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) (non-competing)
```
ỴṚZZṚY
```
[Try it online!](http://jelly.tryitonline.net/#code=4bu04bmaWlrhuZpZ&input=&args=UHJvZ3JhbW1pbmcKUHV6emxlcwomCkNvZGUKR29sZg)
### How it works
The idea in the same as in my [Pyth answer](https://codegolf.stackexchange.com/a/55229).
```
ỴṚZZṚY Main link. Argument: s (string)
Ỵ Split at linefeeds.
Ṛ Reverse the order of the lines.
ZZ Zip/transpose twice.
Ṛ Reverse the order of the lines.
Y Join, separating by linefeeds.
```
[Answer]
# [Turtlèd](https://github.com/Destructible-Watermelon/turtl-d/), 72 bytes, noncompeting
Fairly sure I could change approach to save bytes, but later.
:p Non-golf esolang beats regular langs :p
The odd thing about Turtlèd is it was originally made after discussion about ascii art langs, but it actually seems to be best at these kinds of challenges
Turtlèd can not take newline input but for multiple inputs, and this takes only one input: terminate each word with a space, including the last one.
```
!l[*,+r_][ l]ur[*,[ -.]+.[ r{ d}u+.]-.[ -.]{ l}[ l]r[ u]_]' d[ d]u[ ' r]
```
### [Try it online!](http://turtled.tryitonline.net/#code=IWxbKiwrcl9dWyBsXXVyWyosWyAtLl0rLlsgcnsgZH11Ky5dLS5bIC0uXXsgbH1bIGxdclsgdV1fXScgZFsgZF11WyAnIHJd&input=UHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZiA)
## Explanation:
```
! Take string input
l Move left, off the asterisk at the start of grid
[* ] Until cell is *
,+r_ write *, string pointer+=1, move right, write * if pointed char is last char
[ l]ur move left until finding a space, move up and right
[* ] Until cell is *
, write *
[ ] until cell is [space]
-. decrement string pointer, write pointed char
+. increment and write string pointer
[ ] until cell is [space]
r{ d} move right, move down until finding nonspace
u+. move up, string pointer+=1 and write pointed char
-. decrement string pointer and write pointed char
[ ] until cell is [space]
-. string pointer-=1 and write pointed char
{ l} move left until finding nonspace
[ l] move left until finding space
r move right
[ u] move up until finding space
_ write * if pointed char is last char
(if it is written, loop ends)
' d[ d]u[ ' r] just cleanup
```
[Answer]
## Perl, 133 bytes
This was one of those challenges that changed in my head from being too hard, to being easy, to being a lot more code than I'd anticipated... I'm not particularly happy with the approach, I'm sure there's a much better way to reduce the `print pop@F...` bit perhaps using `-n` or just pure regex, but I can't get there right now... Originally I was using `say`, but I think I'd have to score that higher (`use 5.01`) because of `$'`.
```
@F=(/.+/g,@F)for<>;$_%=$#F,($x=length$F[$_++])<length$F[$_]&&($F[$_]=~/.{$x}/,$F[$_-1].=$',$F[$_]=$&)for 0..1e2;print pop@F,$/while@F
```
### Usage
Save as `vertically-collapse-text.pl`.
```
perl vertically-collapse-text.pl <<< 'Programming
Puzzles
&
Code
Golf'
P
Prog
&uzz
Coderam
Golflesming
```
[Answer]
# SmileBASIC, 90 bytes
```
X=RND(50)Y=RND(20)G=CHKCHR(X,Y+1)<33LOCATE X,Y+G?CHR$(CHKCHR(X,Y));
LOCATE X,Y?" "*G
EXEC.
```
Applies gravity to all text in the console. I'm not sure if this is valid, or if I have to use a string array.
[Answer]
# Ruby, ~~99~~ 82 bytes
Getting there...
```
f=->a,i=-1{a.map{|l|i+=1;(0...l.size).map{|c|a.map{|x|x[c]}.join[~i]}*''}.reverse}
```
An attempted explanation:
```
f=->a,i=-1{a.map{|l|i+=1; # For each line `l` with index `i` in string array `a`
(0...l.size).map{|c| # For each column `c` in `l`
a.map{|x|x[c]}.join # Make a string of non-nil characters `c` across `a`...
[~i] # ...and grap the `i`th character *from the end*, if any
}*''}.reverse} # Join the characters grabbed from each column and reverse the result
```
Run it like this:
```
a = %w[
Programming
Puzzles
&
Code
Golf
]
puts f[a]
```
[Answer]
# K, 30
```
{+{(-#x)$x@&~^x}'+x@\:!|/#:'x}
```
.
```
k){+{(-#x)$x@&~^x}'+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"P "
"Prog "
"&uzz "
"Coderam "
"Golflesming"
```
Explanation
`x@\:!|/#:'x` extends each string to create a square char matrix.
```
k){x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"Programming"
"Puzzles "
"& "
"Code "
"Golf "
```
`+` transposes it
```
k){+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"PP&CG"
"ru oo"
"oz dl"
"gz ef"
"rl "
"ae "
"ms "
"m "
"i "
"n "
"g "
```
`{(-#x)$x@&~^x}` will remove any spaces from a string and then pad the string by its original length
```
k){(-#x)$x@&~^x}"a b c de f"
" abcdef"
```
Apply that function to each of the transposed strings, then flip the output to get the result
```
k){+{(-#x)$x@&~^x}'+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"P "
"Prog "
"&uzz "
"Coderam "
"Golflesming"
```
[Answer]
# [pb](https://esolangs.org/wiki/Pb) - 310 bytes
```
^w[B!0]{w[B=32]{vb[1]^b[0]}>}b[1]vb[1]>b[2]<[X]w[B!2]{t[T+B]b[0]>}b[0]v[T]w[X!-1]{b[1]<}b[1]vb[1]w[B!0]{w[B!0]{^w[B!0]{>}<<<<^[Y+1]w[B!0]{<}>t[B]b[0]w[B!1]{v}v<[X]w[B!0]{>}b[T]}b[0]vb[1]^w[X!0]{<vb[1]^t[B]b[0]^w[B!0]{^}b[T]w[B!0]{v}}vw[B!0]{^^w[B!0]{>}<b[0]vvw[B=0]{<}b[0]<[X]}^^>w[B=0]{vb[1]}v<<}>>^b[0]^<b[0]
```
What a disaster. I barely remember anything about how it works.
Because of the way pb's input works (a single line all at once), you have to use spaces instead of newlines in the input. If the interpreter wasn't garbage and you could include newlines in the input, the only change would be the `[B=32]` at the beginning becoming `[B=10]`.
I'm working on an update to pbi (the interpreter) that will clean up the visuals if you want to watch the program run. It still needs a lot of work but in the mean time, you can [watch this program on YouTube](https://www.youtube.com/watch?v=PLxVRia6a3A).
[Answer]
# J, 17 bytes
```
-.&' '"1&.(|:@|.)
```
Quite pleasant solution.
Explanation:
```
-.&' '"1&.(|:@|.) input: list of strings y
|. reverse lines
|:@ then transpose
-.&' '"1 remove blanks from columns
&. and undo the inside
|:@|. (that is, transpose and reverse again.)
```
## Test case explained
```
s
Programming
Puzzles
&
Code
Golf
|.s
Golf
Code
&
Puzzles
Programming
|:|.s
GC&PP
oo ur
ld zo
fe zg
lr
ea
sm
m
i
n
g
-.&' '"1|:|.s
GC&PP
oour
ldzo
fezg
lr
ea
sm
m
i
n
g
|.-.&' '"1|:|.s
g
n
i
m
sm
ea
lr
fezg
ldzo
oour
GC&PP
|.|:-.&' '"1|:|.s
P
Prog
&uzz
Coderam
Golflesming
(-.&' '"1)&.(|:@|.)s
P
Prog
&uzz
Coderam
Golflesming
-.&' '"1&.(|:@|.)s
P
Prog
&uzz
Coderam
Golflesming
```
## Test cases
```
f =: -.&' '"1&.(|:@|.)
f
-.&' '"1&.(|:@|.)
f >'Programming';'Puzzles';'&';'Code';'Golf'
P
Prog
&uzz
Coderam
Golflesming
g =: [: > [: <;._1 '|'&,
g 'Programming|Puzzles|&|Code|Golf'
Programming
Puzzles
&
Code
Golf
f g 'Programming|Puzzles|&|Code|Golf'
P
Prog
&uzz
Coderam
Golflesming
F =: f @ g
F &. > 'Programming|Puzzles|&|Code|Golf' ; '1|23|456|7890' ; '1234|567|89|0'
+-----------+----+----+
|P |1 |1 |
|Prog |23 |52 |
|&uzz |456 |863 |
|Coderam |7890|0974|
|Golflesming| | |
+-----------+----+----+
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 13 bytes
This uses the algorithm described in [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/55229/47581). Input and output are both lists of strings. Unfortunately, the builtin transpose function does not work very well if the inner lists or strings aren't all the same length, which would kind of defeat the point of vertically collapsing in the first place. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=UjJgO2kobFrimYLOo2BuUg&input=WyJQcm9ncmFtbWluZyIsIlB1enpsZXMiLCImIiwiQ29kZSIsIkdvbGYiXQ)
```
R2`;i(lZ♂Σ`nR
```
**Ungolfing**
```
Implicit input s.
R Reverse s.
2`...`n Run the following function twice.
;i Duplicate and flatten onto the stack.
(l Get the number of strings in the list.
Z Zip len strings together, which results in a list of lists of characters.
♂Σ Sum each list of characters, which essentially joins them together.
This function essentially transposes
R Reverse the result.
Implicit return.
```
[Answer]
## Racket 312 bytes
```
(let((lr list-ref)(ls list-set)(sl string-length)(ss substring)(l(string-split s)))(let p((ch #f))
(for((i(-(length l)1)))(define s(lr l i))(define r(lr l(+ 1 i)))(define n(sl s))(define m(sl r))
(when(> n m)(set! l(ls l i(ss s 0 m)))(set! l(ls l(+ 1 i)(string-append r(ss s m n))))(set! ch #t)))(if ch(p #f)l)))
```
Ungolfed:
```
(define (f s)
(let ((lr list-ref)
(ls list-set)
(sl string-length)
(ss substring)
(l (string-split s)))
(let loop ((changed #f))
(for ((i (sub1 (length l))))
(define s (lr l i))
(define r (lr l (add1 i)))
(define n (sl s))
(define m (sl r))
(when (> n m)
(set! l (ls l i (ss s 0 m)))
(set! l (ls l (add1 i)(string-append r (ss s m n))))
(set! changed #t)))
(if changed (loop #f)
l))))
```
Testing:
```
(f "Programming Puzzles & Code Golf")
```
Output:
```
'("P" "Prog" "&uzz" "Coderam" "Golflesming")
```
[Answer]
# JavaScript (ES6), 103 bytes
```
v=>(v=v.split`
`).map(_=>v=v.map((x,i)=>v[++i]?x.slice(0,n=v[i].length,v[i]+=x.slice(n)):x))&&v.join`
`
```
Split on CR, outer map ensures we loop enough times to allow "gravity" to drop letters as far as they need to drop.
Inner map first checks if there is a next line, if so, and it is shorter, drop the overflow to the next line. i.e if the 1st line has "ABCD" and the 2nd line has "FG", drop the "CD" from 1st line to the 2nd so that the 1st line becomes "AB" and the 2nd becomes "FGCD".
As we do this as many times as there are lines, the letters drop as far as they should, leaving us with the desired outcome.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 bytes
```
y kS ù y
```
[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=eSBrUyD5IHk=&input=IlByb2dyYW1taW5nClB1enpsZXMKJgpDb2RlCkdvbGYi)
### How it works
```
Uy kS ù y
Uy Transpose at newline
kS Replace spaces with nothing
ù Left-pad to fit the longest line
y Transpose at newline
```
There's also `z` which rotates the 2D string by a multiple of 90 degrees, but it somehow truncates the string when `height > length`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¶¡RζðмζR»
```
[Try it online.](https://tio.run/##MzBNTDJM/f//0LZDC4PObTu84cKec9uCDu3@/19JSSmgKD@9KDE3NzMvnSugtKoqJ7WYS43LOT8llcs9PycNqAIA)
or with alternative start:
```
.BRøðмζR»
```
[Try it online.](https://tio.run/##MzBNTDJM/f9fzyno8I7DGy7sObct6NDu//@VlJQCivLTixJzczPz0rkCSquqclKLudS4nPNTUrnc83PSgCoA)
Similar approach as [@Dennis♦' Pyth answer](https://codegolf.stackexchange.com/a/55229/52210).
-1 byte thanks to *@Emigna* replacing `ðõ:` with `ðм`.
**Explanation:**
```
¶¡ # Split on new-lines
R # Reverse the list
ζ # Zip/Transpose with unequal-length items (with space filler by default)
ðм # Remove all spaces
ζ # Zip/Transpose unequal-length items (with space filler) again
R # Reverse the list again
» # Join the list by newlines, and output implicitly
```
**Alternative explanation:**
```
.B # Box (implicitly splits on new-lines and appends spaces)
ø # Zip/Transpose with equal-length items
# Rest is the same
```
[Answer]
# R, ~~s81~~ 52 bytes
```
function(x)apply(x,2,function(.).[order(!is.na(.))])
#old,longer version did the same but less efficiently
#function(x)apply(x,2,function(x){n<-na.omit(x);c(rep("",length(x)-length(n)),n)}))
```
I took some liberty in interpreting the question and presumed that the text is represented in a matrix with one character per cell, thus:
```
x <- as.matrix(read.fwf(textConnection("Programming
Puzzles
&
Code
Golf"), widths=rep(1, 11)))
```
So x becomes:
```
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
[1,] "P" "r" "o" "g" "r" "a" "m" "m" "i" "n" "g"
[2,] "P" "u" "z" "z" "l" "e" "s" NA NA NA NA
[3,] "&" NA NA NA NA NA NA NA NA NA NA
[4,] "C" "o" "d" "e" NA NA NA NA NA NA NA
[5,] "G" "o" "l" "f" NA NA NA NA NA NA NA
```
Now I use `order` and `[` to sort the columns so that the NA's come first and then all other values:
```
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
[1,] "P" NA NA NA NA NA NA NA NA NA NA
[2,] "P" "r" "o" "g" NA NA NA NA NA NA NA
[3,] "&" "u" "z" "z" NA NA NA NA NA NA NA
[4,] "C" "o" "d" "e" "r" "a" "m" NA NA NA NA
[5,] "G" "o" "l" "f" "l" "e" "s" "m" "i" "n" "g"
```
It becomes longer if it is required that the output be words:
```
s <- (function(x)apply(x,2,function(.).[order(!is.na(.))]))(x)
s[is.na(s)]<-""
apply(s, 1, paste, collapse="")
# [1] "P" "Prog" "&uzz" "Coderam" "Golflesming"
```
[Answer]
# R, ~~196~~ ~~189~~ 170 bytes
```
function(x){l=nchar;o=function(y)which(diff(l(y))<0)[1];d=function(x,i)"[<-"(x,i:(j<-i+1),c(a<-substr(x[i],1,l(x[j])),sub(a,x[j],x[i])));while(!is.na(o(x)))x=d(x,o(x));x}
```
A human-readable version:
```
f<-function(x){
l=nchar;
# find the first line in x that is longer than the next line
# if no such line exists o(x) will be NA
o = function(y) which(diff(l(y))<0)[1]
# d(x,i) --> clips the line i in x, adding the remainder to x[i+1]
d = function(x,i) "[<-"(x,i:(j<-i+1),
c(a<-substr(x[i],1,l(x[j])), sub(a,x[j],x[i])))
# a --> clipped x[i], sub(a,x[j],x[i]) --> expanded x[j]
while(!is.na(o(x)))x=d(x,o(x));x
}
```
How it works:
1. Take the first "bad" line, i.e., line which is longer than the next line, take the "extra" part and add it to the next line
2. Check if there are any "bad" lines left, if yes go to #1
(Or in other words, "superfluous" parts fall down until everything that can fall down has fallen down.)
Input: a character vector.
```
x<-readLines(textConnection("Programming\nPuzzles\n&\nCode\nGolf"))
f(x)
# [1] "P" "Prog" "&uzz" "Coderam" "Golflesming"
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
□Ṙ∩∩Ṙ⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqHhuZjiiKniiKnhuZjigYsiLCIiLCJQcm9ncmFtbWluZ1xuUHV6emxlc1xuJlxuQ29kZVxuR29sZiJd)
Uses the same idea as Pyth answer
# Explanation:
```
□ Input as a list separated by newlines
Ṙ Reverse
∩ Transpose rows and columns
∩ Same as above
Ṙ Reverse
⁋ Join by newlines
Implicit output the result
```
[Answer]
# [Julia 0.6](http://julialang.org/), 141 bytes
```
l=length
g(z,i)=(n=z[i];m=z[i+1];(N,M)=l.([n,m]);z[i:i+1]=[n[1:min(N,M)],m*n[M+1:N]])
f(s,w=split(s),d=1:l(w)-1)=(g.([w],[d d]);join(w,"\n"))
```
[Try it online!](https://tio.run/##HY0/C8IwEMX3@xSSQe40ClkcWjI5OCnuMYPQNkYuV2kjlX75Gp0evD@/93xzvB@WhS23EvIDAs46kkWxs4u@Tj/ZGl/jRZ/J8h6d6OSpLnb1C6wTZ6oU5V/wOm3EnbemunhP0OGoJzu@OGYcSTfWVIwT7Uw5CAU1ee2aVVNwz74QJq1uooiW/MlWKXUd@jDcU4EHuL7nmdsR1nDsmxZOPXelAfAaomQW7LCMiGD5Ag "Julia 0.6 – Try It Online")
Broadcasting with `g.([w], [d d])` allows me to get rid of any map statement and saves me around 7 bytes.
] |
[Question]
[
*This is a tips question for golfing in Python concerning the [Evil Numbers](http://golf.shinh.org/p.rb?Evil%20Numbers) question on [Anarchy Golf](http://golf.shinh.org/).*
An number is [evil](https://en.wikipedia.org/wiki/Evil_number) if its binary expansion has an even number of 1's. The challenge is to print the first 400 evil numbers `0,3,5,...,795,797,798`, one per line.
[The Python 2 submissions](http://golf.shinh.org/p.rb?Evil%20Numbers#Python) are led by llhuii with a 42-byte solution. The next best is 46 bytes by mitchs, followed by five 47-byte submissions. It seems llhuii has found something truly magical that has eluded many strong Python golfers for over 2 years. Saving 4 or 5 bytes is huge for such a short golf.
[![Table of Python 2 scores](https://i.stack.imgur.com/JHpOc.png)](https://i.stack.imgur.com/JHpOc.png)
I'm still at 47 bytes. I'm hoping we can crack this puzzle as a community. If we get an answer jointly, I'd submit it under the names of everyone who contributed. An answer to this question can be a piece of code or a new idea or a piece of analysis. If you are llhuii, please don't spoil it for us yet.
Though submissions are not revealed because this problem is Endless, we're given some leads. The winning submission took 0.1699 seconds to run, much longer than any other, suggesting an inefficient method. From the byte statistics, of the 42 characters, 23 are alphanumeric `[0-9A-Za-z]` and 19 are ASCII symbols. This means there is no whitespace in llhuii's solution.
You can test your code on the [problem page](http://golf.shinh.org/p.rb?Evil%20Numbers), choosing Python from the language dropdown or uploading a `.py` file. Note that:
* Python 2.7 is used
* Your code must be a full program that prints
* There's no input for this problem, like [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'")
* Your program just has to print the 400 values as given, even if it would break on larger values
* Programs have 2 seconds to run
* Programs may terminate with error
* You may use `exec`; the "exec is denied" refers to shell exec
[Answer]
This isn't the same solution as llhuii's, but it's also 42 bytes long.
```
n=0;exec'print n;n^=(n^n+2)%3/2;n+=2;'*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WwDq1IjVZvaAoM69EIc86L85WIy8uT9tIU9VY38g6T9vWyFpdy8TA4P9/AA "Python 2 – Try It Online")
Thanks to @JonathanFrech, we're now at 40 bytes.
```
n=0;exec'print n;n=n+2^(n^n+2)/2%3;'*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WwDq1IjVZvaAoM69EIc86zzZP2yhOIy8OSGnqG6kaW6trmRgY/P8PAA "Python 2 – Try It Online")
There's another byte to be saved, for a total of 39.
```
n=0;exec'print n;n=n+2^-(n^n+2)%3;'*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WwDq1IjVZvaAoM69EIc86zzZP2yhOVyMvDkhrqhpbq2uZGBj8/w8A "Python 2 – Try It Online")
[Answer]
## Getting 39 bytes
This is an explanation of how I got a 39-byte solution, which [Dennis and JonathanFrech](https://codegolf.stackexchange.com/a/144075/20260) found separately as well. Or, rather, it explains how one could arrive at the answer in hindsight, in a way that's much nicer than my actual path to it, which was full of muddy reasoning and dead ends.
```
n=0
exec"print n;n=n+2^-(n+2^n)%3;"*400
```
Writing this a bit less golfed and with more parens, this looks like:
```
n=0
for _ in range(400):
print n
n=(n+2)^(-((n+2)^n))%3
```
**Bit parities**
We start with an idea from my [47-byte solution](https://codegolf.stackexchange.com/a/144019/20260) to output all numbers of the form `n=2*k+b` where `k` counts up `0,1,...,399` and `b` is a parity bit that makes the overall number of 1's even.
Let's write `par(x)` for the *bit parity* of `x`, that is the xor (`^`) all of bits in `x`. This is 0 if there's an even number of 1-bits (number is evil), and 1 if there's an odd number of 1-bits. For `n=2*k+b`, we have `par(n) = par(k)^b`, so to achieve evil `par(n)==0` we need `b=par(k)`, i.e. the last bit of `n` to be the bit parity of the preceding bits.
My first efforts at golfing were on expressing the `par(k)`, [at first directly](https://codegolf.stackexchange.com/a/144019/20260) with `bin(k).count('1')%2`, and then with [bit manipulation](https://codegolf.stackexchange.com/a/144027/20260).
**Parity updates**
Still, there didn't seem to be a short expression. Instead, it helped to realize that there's more info to work with. Rather than just computing the bit parity of the current number,
```
k ----> par(k)
```
we can update the bit parity as we increment `k` to `k+1`.
```
k ----> par(k)
|
v
k+1 ----> par(k+1)
```
That is, since we're counting up `k=0,1,2,...`, we merely need to maintain the current bit parity rather than calculating it from scratch each time. The bit parity update `par(k+1)^par(k)` is the parity of the number of bits flipped in going from `k` to `k+1`, that is `par((k+1)^k)`.
```
par(k+1) ^ par(k) = par((k+1)^k)
par(k+1) = par(k) ^ par((k+1)^k)
```
**Form of `(k+1)^k`**
Now we need to compute `par((k+1)^k)`. It might seem like we've gotten nowhere because computing bit parity is exactly the problem we're trying to solve. But, numbers expressed as `(k+1)^k` have the form `1,3,7,15,..`, that is one below a power of 2, a fact often [used in bit hacks](https://graphics.stanford.edu/~seander/bithacks.html). Let's see why that is.
When we increment `k`, the effect of the binary carries is to invert the last `0` and all `1`'s to its right, creating a new leading `0` if there were none. For example, take `k=43=0b101011`
```
**
101011 (43)
+ 1
------
= 101100 (44)
101011 (43)
^101100 (44)
------
= 000111 (77)
```
The columns causing a carry are marked with `*`. These have a `1` change to a `0` and pass on a carry bit of `1`, which keeps propagating left until it hits a `0` in `k`, which changes to `1`. Any bits further to the left are unaffected. So, when `k^(k+1)` checks which bit positions change `k` to `k+1`, it finds the positions of the rightmost `0` and the `1`'s to its right. That is, the changed bits form a suffix, so result is 0's followed by one or more 1's. Without the leading zeroes, there are binary numbers `1, 11, 111, 1111, ...` that are one below a power of 2.
**Computing `par((k+1)^k)`**
Now that we understand that `(k+1)^k` is limited to `1,3,7,15,...`, let's find a way to compute the bit parity of such numbers. Here, a useful fact is that `1,2,4,8,16,...` alternate modulo `3` between `1` and `2`, since `2==-1 mod 3` . So, taking `1,3,7,15,31,63...` modulo `3` gives `1,0,1,0,1,0...`, which are exactly their bit parities. Perfect!
So, we can do the update `par(k+1) = par(k) ^ par((k+1)^k)` as
```
par(k+1) = par(k) ^ ((k+1)^k)%3
```
Using `b` as the variable we're storing the parity in, this looks like
```
b^=((k+1)^k)%3
```
**Writing the code**
Putting this together in code, we start `k` and the parity bit `b` both at `0`, then repeatedly print `n=2*k+b` and update `b=b^((k+1)^k)%3` and `k=k+1`.
*46 bytes*
```
k=b=0
exec"print 2*k+b;b^=(k+1^k)%3;k+=1;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9s2ydaAK7UiNVmpoCgzr0TBSCtbO8k6Kc5WI1vbMC5bU9XYOlvb1tBaScvEwOD/fwA "Python 2 – Try It Online")
We removed parens around `k+1` in `((k+1)^k)%3` because [Python precedence](http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html) does the addition first anyway, weird as it looks.
**Code improvements**
We can do better though by working directly with a single variable `n=2*k+b` and performing the updates directly on it. Doing `k+=1` corresponds to `n+=2`. And, updating `b^=(k+1^k)%3` corresponds to `n^=(k+1^k)%3`. Here, `k=n/2` before updating `n`.
*44 bytes*
```
n=0
exec"print n;n^=(n/2+1^n/2)%3;n+=2;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCu1IjVZqaAoM69EIc86L85WI0/fSNswDkhqqhpb52nbGlkraZkYGPz/DwA "Python 2 – Try It Online")
We can shorten `n/2+1^n/2` (remember this is `(n/2+1)^n/2`) by rewriting
```
n/2+1 ^ n/2
(n+2)/2 ^ n/2
(n+2 ^ n)/2
```
Since `/2` removes the last bit, it doesn't matter if we do it before or after xor-ing. So, we have `n^=(n+2^n)/2%3`. We can save another byte by noting that modulo `3`, `/2` is equivalent to `*2` is equivalent to `-`, noting that `n+2^n` is even so the division is actual halving without flooring. This gives `n^=-(n+2^n)%3`
*41 bytes*
```
n=0
exec"print n;n^=-(n+2^n)%3;n+=2;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCu1IjVZqaAoM69EIc86L85WVyNP2yguT1PV2DpP29bIWknLxMDg/38A "Python 2 – Try It Online")
Finally, we can combine the operations `n^=c;n+=2` into `n=(n+2)^c`, where `c` is a bit. This works because `^c` acts only on the last bit and `+2` doesn't care about the last bit, so the operations commute. Again, precedence lets us omit parens and write `n=n+2^c`.
*39 bytes*
```
n=0
exec"print n;n=n+2^-(n+2^n)%3;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCu1IjVZqaAoM69EIc86zzZP2yhOVwNE5mmqGlsraZkYGPz/DwA "Python 2 – Try It Online")
[Answer]
*This gives my (xnor's) 47-byte solution and the thinking that led me to it. Don't read this if you want to figure this out yourself.*
A natural first idea is to iterate through the numbers 0 to 799, printing only those with an even number of 1's in binary.
**52 bytes**
```
for n in range(800):
if~bin(n).count('1')%2:print n
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFPITNPoSgxLz1Vw8LAQNOKSyEzrS4pM08jT1MvOb80r0RD3VBdU9XIqqAoM69EIe//fwA "Python 2 – Try It Online")
Here, the `~` takes the bit complement so as to switch `even<->odd` in the count and give a truthy value only on even counts.
We can improve this method by generating all the values instead of filtering. Observe that the output values are the numbers 0 to 399, each with a bit appended to make the number of 1 bits even.
```
0 = 2*0 + 0
3 = 2*1 + 1
5 = 2*2 + 1
6 = 2*3 + 0
...
```
So, the `n`th number is either `2*n+b` with either `b=0` or `b=1`. The bit `b` can be found by counting `1`'s in the bits of `n` and taking the count modulo 2.
**49 bytes**
```
for n in range(400):print 2*n+bin(n).count('1')%2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFPITNPoSgxLz1Vw8TAQNOqoCgzr0TBSCtPOykzTyNPUy85vzSvREPdUF1TFagFAA "Python 2 – Try It Online")
We can cut the 2 bytes for `2*` by iterating over `0,2,4,...`, which doesn't chance the count of `1`'s. We can do this by using an `exec` loop that runs 400 times and increasing `n` by 2 each loop.
**47 bytes**
```
n=0;exec"print n+bin(n).count('1')%2;n+=2;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WwDq1IjVZqaAoM69EIU87KTNPI09TLzm/NK9EQ91QXVPVyDpP29bIWknLxMDg/38A "Python 2 – Try It Online")
And, that's my 47-byte solution. I suspect most if not all the other 47-byte solutions are the same.
[Answer]
# llhuii’s Python 3 submission
Here are the Python 3 submissions for Evil Numbers at the time of writing:
[![enter image description here](https://i.stack.imgur.com/MbATO.png)](https://i.stack.imgur.com/MbATO.png)
llhuii probably ported their trick to Python 3, and came up with a solution that is
* 3 bytes longer than their Python 2 solution, and
* has 45 − (25 + 18) = 2 bytes of whitespace.
Porting xnor’s 47B to Python 3 literally, we get this 50B:
```
n=0;exec("print(n+bin(n).count('1')%2);n+=2;"*400)
```
I submitted it as `ppcg(xnor)`. (It adds parentheses to `exec` and `print`, which are now functions.) It has different code stats from the other Python 3 answers, which all have some amount of whitespace in them. Interesting!
There’s a shorter way to rewrite it though (`exec` tends to lose its competitive edge in Python 3):
```
n=0
while n<800:print(n+bin(n).count('1')%2);n+=2
```
It’s 49 bytes. I submitted it as `ppcg(xnor,alternative)`. This has two bytes of whitespace, just like llhui’s answer! This leads me to believe that llhuii’s Python 3 answer looks kinda like this (newline, then a `while` loop.) So llhuii probably used `exec` in Python 2 and `while` in Python 3, just like us; this explains the whitespace discrepancy.
---
Our 47B became a 49B in Python 3. What’s interesting, now, is that llhuii’s 42B didn’t become a 44B, it became a 45B! **Something about llhuii’s solution takes one byte extra in Python 3.** This could mean a variety of things.
* The first thing that comes to mind is **division**: maybe llhuii uses `/` in Python 2, which became `//` in Python 3. (If they’re counting in twos like us, then `n/2` might be used to shift `n` back to the right by one bit?)
* The other thing that comes to mind is **unary operators after print**. Our `print blah` became `print(blah)` (1 byte extra), but if llhuii wrote something like `print~-blah` in Python 2, it’d become `print(~-blah)` in Python 3.
* Maybe there are other ideas. Please let me know.
Code statistics for all Py3 solutions, including mine now:
[![enter image description here](https://i.stack.imgur.com/YERuq.png)](https://i.stack.imgur.com/YERuq.png)
[Answer]
# Other approaches
### 1) Using a formula for A001969
Rather than converting to binary, it might be possible to take advantage of the following formula (from [OEIS](http://oeis.org/A001969)):
>
>
> ```
> a(1) = 0
> for n > 1: a(n) = 3*n-3-a(n/2) if n is even
> a(n) = a((n+1)/2)+n-1 if n is odd
>
> ```
>
>
I'm very bad at golfing in Python, so I'm not even going to try. But here is a quick attempt in JS.
*NB: I don't think it would be a valid JS submission as it's just filling an array without displaying it. And even so, it's 5 bytes longer than the current best JS solution (which is 45 bytes). But that's not the point here anyway.*
```
for(a=[n=0,3];n<199;)a.push(2*++n+a[n],6*n+3-a[n])
```
```
for(a=[n=0,3];n<199;)a.push(2*++n+a[n],6*n+3-a[n])
console.log(a.join`, `)
```
Hopefully it may give some inspiration.
Using an array is probably not a good idea because it needs to be initialized and updated. It might be more efficient (code size wise) to use a ***recursive function*** instead, which would explain why the winning solution is ***taking more time*** than the other ones.
### 2) Building the Thue-Morse sequence with substitutions
In theory, this code should work:
```
n=0;a="1";b="0";exec"t=a;a+=b;b+=t;print(int(b[n]))+n;n+=2;"*400
```
[Try it online!](https://tio.run/##FcMxCoAwDAXQu2SyZqlZPzmJODRS0CUWyaCnj/jgjTeOyyXTtaIpLQRTqoT@9J1CGxqrwVgD4z49pr@tvpXCDmcV0Cw18wM) (runnable version limited to 20 terms)
It computes the Thue-Morse sequence with consecutive substitutions and looks for the position of 1's (Evil Numbers) in the same loop.
But:
* It's far too long in its current form
* It quickly leads to a memory overflow
### 3) Building the Thue-Morse sequence with bitwise operations
Starting from Wikipedia's [Direct Definition of the Thue-Morse sequence](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence#Direct_definition), I've come to this algorithm (switching back to JS ... sorry):
```
for(e=n=0;n<799;)(e^=!(((x=n++^n)^x/2)&170))||console.log(n)
```
where we keep track of the current *evilness* of the sequence in ***e*** and use ***170*** as a bitmask of odd bits in a byte.
[Answer]
By construction, `n+n^n` is always evil, but my poor Python skills could only come up with a 61-byte solution:
```
for n in sorted(map(lambda n:n+n^n,range(512)))[:400]:print n
```
Thanks to @Peilonrayz for saving 5 bytes and @Mr.Xcoder for saving 1 byte:
```
for n in sorted(n^n*2for n in range(512))[:400]:print n
```
[Answer]
# Nested counters approach
I have an idea for a different approach, but I am not experienced enough in python golfing, so I'll leave it here for you guys to consider as another possible starting point for golfing.
### The ungolfed idea:
```
n=0
i=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
for _ in"01":
i^=1
if n<800:print i+n
n+=2
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WgCvT1pArLb9IIV4hM0/JwFDJikshMw4opoAmCBXFEIaJY0rAZbBIIeSwSSLJYpVGlseuAEUFDiVoioDcNIU8GwsDA6uCosy8EoVM7TwkyTxtW2CIAQA "Python 2 – Try It Online")
Nine levels nesting depth, all the loops are the same, so in my mind they should be built by `exec"something"*9+"deepest stuff"`. In practice I don't know if it is possible to do something like this with a for cycle.
Things to consider for golfing:
* maybe there is some other possibility to cycle twice other than a for loop (I tried a quine-like approach with the string to be executed passed to itself as a formatting argument twice,but my head exploded).
* there could also be a better alternative to `if n<800:`, which is needed here because otherwise we would keep printing evil numbers up to 2^10
[Answer]
## Idea: Shorter bit parity
It takes many characters to do `bin(n).count('1')%2` to compute the parity of the bit-count. Maybe an arithmetic way is shorter, especially given a limited bit length.
A cute same-length way is `int(bin(n)[2:],3)%2`, interpreting the binary value as base `3` (or any odd base). Unfortunately, 4 of the bytes are spend removing the `0b` prefix. It also works to do `int(bin(n)[2:])%9%2`.
Another idea comes from combining bits using xor. If `n` has binary representation `abcdefghi`, then
```
n/16 = abcde
n%16 = fghi
r = n/16 ^ n%16 has binary representation (a)(b^f)(c^g)(d^h)(e^i)
```
So, `r=n/16^n%16` is evil if and only if `n` is evil. We can then repeat that as `s=r/4^r%4`, a value `s` in `0,1,2,3`, of which `1` and `2` are not evil, checkable with `0<s<3`.
**52 bytes**
```
n=0;exec"r=n/16^n%16;print(0<r/4^r%4<3)+n;n+=2;"*400
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8/WwDq1IjVZqcg2T9/QLC5P1dDMuqAoM69Ew8CmSN8krkjVxMZYUzvPOk/b1shaScvEwOD/fwA "Python 2 – Try It Online")
This turned out a good deal longer. There's many knobs to turn though of how to split the number, how to check the final number (maybe a bit-based lookup table). I suspect these can only go so far though.
[Answer]
# Idea: Reduce over XOR
If you XOR all the bits of `n` together, it will be `0` for evil and `1` for non-evil. You can do this with a recursive function (which may have thus taken more time?), like so:
```
f=lambda n:f(n/2^n&1)if n>1else-~-n
```
This returns 1 for evil.
That's 35 bytes, and checks whether or not a number is evil. Unfortunately, `filter` is already 6 bytes so this wasn't the optimal solution verbatim but this idea can probably be golfed.
[Answer]
# Substitution method : {1 -> {1, -1}, -1 -> {-1, 1}}
You can also make this substitution 10 times {1 -> {1, -1}, -1 -> {-1, 1}}, then flatten and check the positions of 1's
here is the mathematica code
```
(F = Flatten)@
Position[F@Nest[#/.{1->{1,-1},-1->{-1,1}}&,1,10],1][[;; 400]] - 1
```
[Answer]
# Idea: [A006068](https://oeis.org/A006068) (“a(n) is Gray-coded into n”)
Neil’s idea of sorting all the `2n XOR n` intrigued me, so I tried to find the indices behind this sort. I wrote [this code](https://tio.run/##K6gsycjPM/r/P7UsM6dYwVYhOlM7My5TIS2/SCFTITNPoSgxLz1Vw9TQSDOWC03QyEDTiksBCEB6gVqNtDK1kzLzNDI19ZLzS/NKNNQN1TVVjcBKCooy80rACov1MvNSUis0QGzN//8B), and it reveals that we can write something like this:
```
for n in range(400):x=a(n);print 2*x^x
```
Where `a(n)` is A006068(n). [Try it online!](https://tio.run/##RY5BDoIwFET3nOIvwVUlrirlFK5JavyVRjOQ3xLr6asVIrOZzMtkMvM7jhPafGNHtkajK/oqmOPPX6N/Ml1k4ZUXIRj0ffhn7woyStNV2D72nsGAvRa6bhsVjouAUGU3CYE8SCzuXJ@UanQy5cZ5Fo9I7SENKecP "Python 2 – Try It Online")
However, this assumes we have some short way to compute A006068. This is already 38 bytes, assuming we can calculate it in 4 bytes (the `a(n)` part). The real implementation (in the TIO header) is far longer than that. Not much hope for this I think.
] |
[Question]
[
Sleep Sort is an integer sorting algorithm I found on the Internet. It opens an output stream, and for each input numbers in parallel, delay for the number seconds and output that number. Because of the delays, the highest number will be outputted last. I estimate it has O(n + m), where n is the number of elements and m is the highest number.
Here is the original code in Bash
```
#!/bin/bash
function f() {
sleep "$1"
echo "$1"
}
while [ -n "$1" ]
do
f "$1" &
shift
done
wait
```
Here is the pseudocode
```
sleepsort(xs)
output = []
fork
for parallel x in xs:
sleep for x seconds
append x to output
wait until length(output) == length(xs)
return output
```
Your task is to implement Sleep Sort as a function in the programming language of your choice. You can neglect any concurrency factors such as race conditions and never lock any shared resources. The shortest code wins. The function definition counts toward the code length.
The input list is limited to non-negative integers only, and the length of the input list is expected to reasonably long (test at least 10 numbers) so race conditions never happen.
and assuming race conditions never happen.
[Answer]
**C**, 127 characters, a rather obvious solution:
```
main(int c,char**v){
#pragma omp parallel for num_threads(c)
for(int i=1;i<c;++i){int x=atoi(v[i]);sleep(x);printf("%d ",x);}}
```
(Compiled with `gcc -std=c99 -fopenmp sort.c` and ignoring all warnings.)
[Answer]
A kind of lame **Perl** attempt, 59 55 52 38 **32 characters**:
`map{fork||exit print sleep$_}@a`
**Barebones: 25 Characters:**
...if you don't mind the sort results as die output:
`map{fork||die sleep$_}@a`
**With all the trimmings:**
(for maximum challenge compliance, **44** characters)
`sub t{map{fork||exit print sleep$_}@_;wait}`
If you let perl do the wait for you, **39** characters:
`sub t{map{fork||exit print sleep$_}@_}`
And again, if you don't mind `die()`, **32** characters...
`sub t{map{fork||die sleep$_}@_}`
Note that in Perl 6, or when the 'say' feature is declared, it is possible to replace the `print` function with `say`, saving a character in each instance. Obviously since `die` both terminates the forked process and writes the output, it remains the shortest solution.
[Answer]
## APL (~~15~~ 13)
```
{⎕←⍵⊣⎕DL⍵}&¨⎕
```
What it does:
```
¨⎕ : for each element of the input
& : do on a separate thread
‚éïDL‚çµ : wait approx. ‚çµ seconds
‚éï‚Üê‚çµ : output ‚çµ
```
[Answer]
## Ruby 1.9, 32 characters
As a function:
```
s=->a{a.map{|i|fork{p sleep i}}}
```
If we can just use a predefined variable, it reduces to 25 characters:
```
a.map{|i|fork{p sleep i}}
```
[Answer]
**JavaScript**, 65 characters *(depending on whether you use `console.log` or something else for outputting the result)*
```
a.map(function(v){setTimeout(function(){console.log(v)},v*1000)})
```
This assumes that `a` is an array of non-negative integers and that `map()` exists on the array prototype (JavaScript 1.6+).
[Answer]
Four tries in Erlang:
Output to the console, have taken the liberty to do this each `9ms * Number` since this is plenty enough to make it work (tested on a Atom embedded board = slow):
**Needs 60 chars**
```
s(L)->[spawn(fun()->timer:sleep(9*X),io:write(X)end)||X<-L].
```
Output to the console is total un-Erlangish, so we send a message to process `P` instead:
**Needs 55 chars**
```
s(P,L)->[spawn(fun()->timer:sleep(9*X),P!X end)||X<-L].
```
Sending after a time can also be done differently (this even works with `1ms * Number`):
**Needs 41 chars**
```
s(P,L)->[erlang:send_after(X,P,X)||X<-L].
```
Actually this is a bit unfair since the built in function `send_after` is a late comer and needs the namespace `erlang:` prefixed, if we consider this namespace imported (done on module level):
**Needs 34 chars**
```
s(P,L)->[send_after(X,P,X)||X<-L].
```
[Answer]
## C# - 137 characters
Here is an answer in C# (updated with degrees of parallelism as commented)
```
void ss(int[]xs){xs.AsParallel().WithDegreeOfParallelism(xs.Length).Select(x=>{Thread.Sleep(x);return x;}).ForAll(Console.WriteLine);}
```
[Answer]
# Python - 81 ~~93~~ ~~148~~ ~~150~~ ~~153~~
Tweaking @BiggAl's code, since that's the game we're playing....
```
import threading as t,sys
for a in sys.argv[1:]:t.Timer(int(a),print,[a]).start()
```
**... or 97 ~~175~~ with delayed thread starting**
```
import threading as t,sys
for x in [t.Timer(int(a),print,[a]) for a in sys.argv[1:]]:x.start()
```
---
Takes input via the command line, ala
```
./sleep-sort\ v0.py 1 7 5 2 21 15 4 3 8
```
---
As with many python golfs, there comes a point where the code is compact enough that aliasing variables to shorten names doesn't even save characters.
This one is funky though because it aliases sys and threading BOTH as t, so sys.argv becomes t.argv. Shorter than from foo import \*, and a net character savings! However I suppose Guido wouldn't be pleased...
~~Note to self - learn c and stop golfing in python.~~ HOLY COW THIS IS SHORTER THAN THE C SOLUTION!
[Answer]
## Java (aka never wins at codegolf) : ~~234~~ ~~211~~ 187 chars
```
public class M{public static void main(String[]s){for(final String a:s)new Thread(){public void run(){try{sleep(Long.parseLong(a));}catch(Exception e){}System.out.println(a);}}.start();}}
```
ungolfed:
```
public class M {
public static void main(String[] s) {
for(final String a:s) new Thread(){
public void run() {
try {
sleep(Long.parseLong(a));
} catch(Exception e){}
System.out.println(a);
}
}.start();
}
}
```
[Answer]
### Scala - 42 40 characters (special case)
If you have a thread pool at least the size of the number of list elements:
```
a.par.map{i=>Thread.sleep(i);println(i)}
```
### Scala - 72 characters (general)
```
a.map(i=>new Thread{override def run{Thread.sleep(i);println(i)}}.start)
```
[Answer]
# ColdFusion (8+), 109 bytes
```
<cfloop array="#a#" index="v"><cfthread><cfthread action="sleep" duration="#v*1000#"/>#v#</cfthread></cfloop>
```
Ungolfed:
```
<cfloop array="#a#" index="v">
<cfthread><cfthread action="sleep" duration="#v*1000#"/>#v#</cfthread>
</cfloop>
```
This assumes that `<cfoutput>` is in effect. A few characters could be saved by writing it all on one line.
[Answer]
## Javascript - 52 characters
```
for(i in a)setTimeout("console.log("+a[i]+")",a[i])
```
[Answer]
## Haskell - 143 characters
```
import Control.Concurrent
import System
d=threadDelay
f x=d(10^6*x)>>print x
g s=mapM(forkIO.f)s>>d(10^6*maximum s+1)
main=getArgs>>=g.map read
```
This probably could be made a shorter by taking input on stdin if that were an option, but it's late and either way, it's still 104 characters for the function itself.
[Answer]
# Befunge-98, 38 31 bytes
I know this is an old challenge, but I just recently discovered both sleepsort and 2D languages, had an idea about how to combine them, and looked for a place to post it, so here we are.
```
&#vt6j@p12<'
v:^ >$.@
>:!#^_1-
```
The main IP reads a number (`&`), then hits the `t` which clones it: one proceeds on the same line and cycles, reading new numbers and generating new childs until it reaches EOF which terminates the sequence.
All the child processes get stuck in a closed loop (the `v` and `^` of the third column) until the main IP finishes reading the input and executes the sequence of commands `'<21p`, which puts the character `<` at position (1,2), overwriting the `^` and freeing all the child processes, which start to simultaneously cycle, reducing by 1 their number at each iteration. Since execution speed of different IPs is synchronized in befunge, they will terminate (and print their value) in order, sorting the input list.
[Answer]
A little late to the party:
## Maple - 91 83 characters
In 91:
```
M:=():use Threads in p:=proc(n)Sleep(n);:-M:=M,n;end:Wait(map(i->Create(p(i)),L)[])end:[M];
```
In 83:
```
M:=():use Threads in Wait(seq(Create(proc(n)Sleep(n);:-M:=M,n end(i)),i=L))end:[M];
```
(This needs Maple version 15, and expects the list to be sorted in L)
[Answer]
## C, 70 69 chars
Doesn't wait for child processes to return, otherwise works.
```
main(n) {
while(~scanf("%d",&n)?fork()||!printf("%d\n",n,sleep(n)):0);
}
```
[Answer]
## Haskell, 90
```
import Control.Concurrent
s::[Int]->IO()
s=mapM_(\x->forkIO$threadDelay(x*9999)>>print x)
```
I hope this meets all the requirements.
[Answer]
# Rust, 125 bytes
Used the depricated `sleep_ms` function so I don't need to write a long duration.
```
|p:Vec<u32>|p.into_iter().for_each(|i|{use std::thread::{spawn,sleep_ms};spawn(move||{sleep_ms(i*1000);println!("{}",i)});});
```
[playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e90408419661dd444e15e816786bc5a9)
[Answer]
# JavaScript, 38 bytes
```
a=>a.map(x=>setTimeout(alert,x*1e3,x))
```
[Answer]
## PHP 57 bytes
```
<?for(;$i=fgets(STDIN);)pcntl_fork()?:die($i.usleep($i));
```
pcntl\_fork() is only available under linux.
[Answer]
Bash (38):
```
xargs -P0 -n1 sh -c 'sleep $0;echo $0'
```
Edit: Floating-point from stdin, separated by spaces or newlines.
[Answer]
# ùîºùïäùïÑùïöùïü, 11 chars / 22 bytes
```
ïć⇝שĤ⇀ôa,a⸩
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin//interpreter.html?eval=true&input=%5B...Array%281e3%29%5D.map%28%28v%2Ci%29%3D%3Ei%29&code=%C3%AF%C4%87%E2%87%9D%D7%A9%C4%A4%E2%87%80%C3%B4a%2Ca%E2%B8%A9)`
`שĤ⇀ôa`, this looks cool.
[Answer]
## PowerShell 7, 40 bytes
[Filters are a kind of function](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7):
```
filter f{$args|% -Pa{sleep $_;$_}-Th 99}
PS C:\> f 3 2 1
1
2
3
```
It uses Powershell 7's [ForEach-Object -Parallel](https://devblogs.microsoft.com/powershell/powershell-foreach-object-parallel-feature/) feature, which defaults to 5 threads, so has `-ThrottleLimit 99` to make it at work for the required 10 numbers.
[Answer]
Just some tweaking from @rmckenzie 's version:
## Python delayed thread start in ~~155~~ ~~152~~ ~~114~~ ~~108~~ 107:
```
import sys, threading as t
for x in [t.Timer(int(a),sys.stdout.write,[a]) for a in sys.argv[1:]]:x.start()
```
## Python without delay in ~~130~~ ~~128~~ ~~96~~ ~~95~~ 93:
```
import sys,threading as t
for a in sys.argv[1:]:t.Timer(int(a),sys.stdout.write,[a]).start()
```
Managed a few more optimisations, using `Timer` instead of `Thread`, which has a more concise call and removed the need to import `time`. Delayed thread start method benefits from list comprehension as it removes the need to initialise the list seperately at the start, although it's two characters longer (`"["+"]"+" "-":"`) than the for loop so it's useless without delayed start, and you have to be careful to use a list rather than a generator, or you're not actually creating the timer threads until you chunk through the generator.
Does anyone else have any optimisations?
---
The trick with `as` helps, but in 2.7.1 you can only import one module into an alias, and after some playing about you can't even `import mod1,mod2 as a,b`, you have to `import mod1 as a, mod2 as b`. It still saves a few characters, but isn't quite the cure-all I thought it was... And in fact it's better to leave sys as sys. Aliasing threading still helps though...
[Answer]
## Clojure, 54
`(defn s[n](doseq[i n](future(Thread/sleep i)(prn i))))`
[Answer]
# C++11, 229 bytes
```
#import<future>
#import<iostream>
using namespace std;int main(int a,char**v){auto G=new future<void>[a];while(--a){G[a]=move(async([=](){this_thread::sleep_for(chrono::seconds(atoi(v[a])));cout<<v[a]<<" "<<flush;}));}delete[]G;}
```
Ungolfed and usage:
```
#import<future>
#import<iostream>
using namespace std;
int main(int a,char**v){
auto G=new future<void>[a];
while(--a){
G[a]=move(async(
[=](){
this_thread::sleep_for(chrono::seconds(atoi(v[a])));
cout<<v[a]<<" "<<flush;
}
));
}
delete[]G;
}
```
[Answer]
# Rust - 150 bytes
And this is why you don't code golf in Rust, it's more verbose than Java ;). Depends on external crate `crossbeam`, it would be even worse without it.
```
|x|{extern crate crossbeam;crossbeam::scope(|s|for&v in x{s.spawn(move||{std::thread::sleep(std::time::Duration::from_secs(v));println!("{}",v)});})}
```
Complete test program:
```
fn main() {
let z =
|x|{extern crate crossbeam;crossbeam::scope(|s|for&v in x{s.spawn(move||{std::thread::sleep(std::time::Duration::from_secs(v));println!("{}",v)});})}
;
z(&[4, 2, 3, 5, 7, 8, 9, 1, 6, 10])
}
```
[Answer]
# [Julia 1.0](http://julialang.org/), 41 bytes
```
!l=@sync l.|>i->@async sleep(i)println(i)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/XzHH1qG4Mi9ZIUevxi5T184hEcwrzklNLdDI1CwoyswryckDsv4rRhsa6JjomOkY6xjqGOmY6ljoWOqY6xjE/gcA "Julia 1.0 – Try It Online")
`@async` adds the task to the machine's scheduler queue, and `@sync` waits for all `@async`s to finish
[Answer]
# [C (clang)](http://clang.llvm.org/), 72 bytes
```
main(n){~scanf("%d",&n)?fork()?wait(main()):printf("%d ",n+sleep(n)):0;}
```
I chose clang but it also works on gcc.
1. takes input from stdin
2. fork()
3. if it's the child, then sleep (returns 0 if sleep succeeded, see `sleep(3)`) and print the number... if it's the parent call main recursively (which implicitly returns 0 since C99).
4. when there's no more input we return from `main()` and start waiting for the children, the children also call `wait()` a number of times depending on the recursion depth but they don't have any children so that fails immediately for them.
[Try it online!](https://tio.run/##S9ZNzknMS///PzcxM08jT7O6rjg5MS9NQ0k1RUlHLU/TPi2/KFtD0748MbNEA6xGU9OqoCgzrwSsRkFJJ0@7OCc1tQCoV9PKwLr2/39DAwUTBTMFYwVDBSMFUwULBUsFcwUDAA "C (clang) – Try It Online")
[Answer]
Kind of boring, port of C#, just to get started with the language again:
**F# - 90 characters**
```
PSeq.withDegreeOfParallelism a.Length a|>PSeq.iter(fun x->Thread.Sleep(x);printfn "%A" x)
```
] |
[Question]
[
Write a program or function that transforms an input string into [Zalgo](https://stackoverflow.com/questions/6579844/how-does-zalgo-text-work) text.
For example, for an input string `Zalgo`, a possible output might look like:
>
> Z̗̄̀ȧ̛̛̭̣̖̇̀̚l̡̯̮̠̗̩̩̥̭̋̒̄̉̏̂̍̄̌ģ̨̭̭̪̯̫̒̇̌̂o̢̟̬̪̬̙̝̫̍̈̓̅̉̇
>
>
>
## Zalgoification specs
* Each letter (upper or lower case) must be zalgoified, and nothing else (spaces, punctuation).
* The [combining characters](https://en.wikipedia.org/wiki/Combining_character) that can be placed on letters here are all those between U+0300 ̀ and U+032F ̯
* Each letter must have a total number of combining characters on it (above and under combined) which is randomly chosen according to a normal distribution of mean 10 and standard deviation 5 (If a negative number is chosen, 0 combining characters must be added).
* Each combining character placed on a letter is chosen uniformly at random between the 48 possible combining characters (see 2nd item).
## Inputs, Outputs
* Input is a single line string that contains only characters between ASCII 32 (space) and ASCII 126 (tilde). No line breaks. You may assume there is at least one letter in the string. The input can be taken as command line argument, function parameter, or STDIN.
* Output is the Zalgoified string. It can be written to a file, or printed to STDOUT, or returned from a function. A trailing line feed is fine. **The output doesn't have to display properly in your interpreter/whatever, as long as when you copy it to a Stack Exchange answer it displays properly like here**.
## Test cases
* The Zalgo example above.
* Input: `Programming Puzzles & Code Golf`
Possible output:
>
> P̢̭̟̟̮̍̅̏̍̀̊̕̚̚r̢̫̝̟̩̎̔̅̈̑o̡̠̣̪̠̍̈̐̏̌̆g̡̬̯̟̠̩̎̐́̅̚ȑ̢̨̩̠̙̭̤̩̟̔̕ą̟̟̯̠̪̜́̉̒̎̂̍̃́̚̚̚m̪̈̅̈m̨̛̛̪̤̟̔̍̓i̢̛̬̠̠̇̈̂̓̒̀̋̔̚̚n̛̝̩̜̓̐̑̅̅g̨̩̪̊ P̨̧̢̟̙̮̋̆ų̨̙̞̙̫̤̫̭̊̓̒̃̒̚z̜̤̮̪̫̄̌̃̈̉̑̋́̕z̡̥̯̠̬̜̥̑̌̓̌̋́̅ľ̫̙̟̪̖̉ė̢̨̘̦̘̖s̛̜̙̘̚ & C̨̠̟̯̟̙̠̉̄̄́̄̑̈̔̆̀ö̭̟̗̯̥̏̐̄̏̌d̞̬̀̆́̀é̟̙̩̗̙̣̋̎̌̌̋ Ğ̨̡̧̡̣̪̝̝̘̩̮̉̋̀̉̉̕̕ọ̠̠̘̟̑̇́̀̃̎̓̋̚ḽ̡̢̟̪̥̍̍̅̀́̎̆̕f̧̢̪̠̠̀̉̒̍̍̊́
>
>
>
* Input: `Golf is a club and ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.`
Possible output:
>
> Ǧ̡̧̄̐̊ò̡̞̟̖̌́̄́̆̈̒l̡̬̣̜̫̞̘̪̇̈̏̊̆̃̑̉̓̒f̙̐̍̇́̐̍̉ į̦̘̝̣̊̒̎̚s à̡̛̠̜̙̣̙̞̣̗̯̝̘̩̅̊̓̄̒̃ ć̬̗̫̯̫̎́̚l̒̎̋ű̯̜̑̎b̯̣̮̭̤̃̊́ a̡̨̟̘̭̣̍̈̀̃̎́̐̋̆̂ń̨̖̭̝̬̘̦̣̓̇̚̕d̨̤̣̙̜̪̖̪̍̓̔̍̔̃̒̍̆̏̚̚̕̚ ḃ̬̪̇̕a̡̟̖̬̬̖̬̋́̎̎̔̄̏̒̑̚l̨̖̜̬̠̭̭̇l̡̡̛̛̬̤̆̔̑̍ s̠̙̣̠̖̜̜̅p̤̖̃́̅̕̕ǫ̢̥̬̠̞̭̭̘̟̞̋̊̌r̡̛̞̬̈̇̑̎̄̚t̟̩̏̀ ï̡̧̢̨̜̜̝̝̜̜̫̔̇̂̔̐n̞̖̫̪̟̤̦̫̂̓̍̑̆̒̚ w̨̧̟̠̯̜̙̘̏̎̈̆̂̅̔hi̧̝̖̗̖̒̆̆̈̚ć̪̜̫̖̠̣̞̋̈́̀̌̋h̢̢̨̥̮ p̜̣̋̔̆l̨̧̛̘̫̝̙̠̯̂̑̌̈̒̐ā̩̗̟̐ẏ̢̛̫̠̦̤̫̞̦̯̥̜̀̀̈̅̉̈̄ẹ̡̑̔̄̉̀̎̒̑r̛̫̭̤̋̄̓̀̅̓ș̜̯̆̋̒̍̔ ų̛̘̭̜̝̈̃̂̅̌̍̆̚s̡̡̡̨̫̥̪̋̈̀̀̆ê̢̡̡̥̖̮̞̫̪̥̘̥̯̎́ v̡̢̢̟̠̞̬̥̩̣̫̫̦̞̂̐̓̇ặ̢̧̙̝̥̪̗̆̎̓ŗ̦̙̩̑̒̕í̫̣̊̚ō̡̧̤̘̟̩̠̫̗̃̍̉̊̕ụ̡̪̠̈̈́̊̅s̢̢̘̤̝̪̀̎̅ c̡̢̛̖̫̗̑̒̆́̎̚l̥̥̖̘̉̎̓̔̀̔ų̘̘̣̟̃̆̓̉̏̅̓̂́̇b̡̝̗̙̗̮̖̩̗̦̏̌̏š̛̮̣̮̜̒̓̌ ṭ̣̫̗̮̙̈̔̅̂̎̃̌̈ò̮̘̍̅̃̃̅̚̕ ḩ̜̞̮̠̇i̮t̝̗̦̖̮̞̗̩̞̤̎̍̒̐ bȁ̢̮̩̝̣̉ļ̛̮̘̏ĺ̨̖̮̑s̢̬̪̗̬̖̟̅̀ i̢̗̖̊̃ń̨̧̛̫̮̞̎t̡̗̞̩̙̑̐̏̔̏ơ̧̯̮̦̖̇̆̔ ạ̧̉̍̚ s̤̬̫̠̉e̎̃r̟̪̥̗̜̥̍̆̍̇̕̕i̧̧̭̝̫̪̯̖̞̪̅̇̎̈̐̅̍ȇ̟̬́̄̃̐̊̕s̢̢̛̝̤̙̭̘̩̩̍̑̂̈̀̀̍̄̔̒̒ o̡̢̘̩̣̅̐̆̌̂̉̇̆̋̕f̡̯̜̝̘̮̠̖̐̂̒̃̚̕ h̪̘̫̪́ǫ̭̦̔̋̆̚̕l̢̡̧̨̙̯̤̔̅̓̆̑̍́ȅ̪̬̝̙̅̋̍s̪̖̭̫̪̟̖̐̀̕ ǫ̦̠̫̍̊̉̄̚n̐̎̂̀ ą̡̛̛̤̦̪̣̭̈̐̂̎ c̪̩̠̗̟̜̘̐̂̈̐̑̏̈ọ̡̡̙̫̞̜̐̇̄̓̏u̥̖̙̝̔̂̎̅̚̚r̙̜̬̭̠̮̙̙̪̫̝̙̬̥̥̯̐́̈́̊̈̍̍ș̀́e̞̜̒̌̚ ĩ̧̦̝̪̆n̛̞̞̆̆̀ a̟̅̐̈̍̉̚̚̕ş̫̭̍̐̚ f̘̝̠̪̦̜́̌̍̇̀̕e̩̫̣̊̎̇̚w̪ ŝ̨̨̠̠̝̦̣̜̦̗̮̞̞̥̥̅̄̄̕t̢̡̢̙̞̟̩̭̤̅̎̌̒̃̇̕r̞̤̙̄̊̃̇̅̈̏̈̌ǫ̝̬̀̋̏̐̌̈k̡̢̧̪̭̝̙̆̈̒̀ȩ̛̙̣̠̗̞̮̅̅s̙̣̒̉̎́̂̅ à̧̛̖̘̞̫̘̎̃̀̑̎̕̕s̢̟̟̭̩̈̏̇ p̣̟̭̗̪̜̫̦̝̣̎̋̎̀̐̏o̧̢̪̮̤̦̎́̐̒̀̚̕s̛̯̦̗̬̬̊̊̄̓̐̉̏́̚s̢̠̣̬̥̬̔̅̕̕i̡̠̣̣̫̞̣̮̥̟̅̎̇̄̋̌̌̇b̡̧̡̖̖̃̄̋̈̋l̢̢̙̪̣̉̉̐̑̆ẹ̢̒̎.
>
>
>
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes ẁ̨̛̭̙̥̖̏̏̐̐̉̃̅̚i̜̟̭̤̞̘̗̐̐̔̈̍̋̏̚n̘̯̥̩̗̯̠̘̮̋̈̃̀̊̉̎̈̕s̛̬̦̙̮̩̜̄̑̐́̎̆̚.
[Answer]
# CJam, ~~57~~ ~~56~~ ~~49~~ 47 bytes
*Thanks to Sp3000 for saving 7 bytes.*
```
q{_eu_el={Pmrmc1.mrml-50*mq*A+mo{48mr'̀+}*}|}/
```
[Test it here.](http://cjam.aditsu.net/#code=q%7B_eu_el%3D%7BPmrmc1.mrml-50*mq*A%2Bmo%7B48mr'%CC%80%2B%7D*%7D%7C%7D%2F&input=Programming%20Puzzles%20%26%20Code%20Golf)
# Explanation
This uses Box–Muller for the normal distribution: the basic algorithm generates two uniform variables in the range `[0,1)`, `U` and `V` and then computes two normally distributed values from them. We only need one and the simpler one is `X = √(-2 ln U) cos(2πV)`. This generates a distribution with mean `0` and standard deviation `1`, so we need to multiply it by `5` to correct the standard deviation and add `10` to correct the mean. We can also simplify the cosine, because omitting the `2` gives the same distribution. So we compute `X = √(-50 ln U) cos(πV) + 10` before rounding to get the number of combining marks.
Here is the code:
```
q{ e# For each character in the input...
_eu_el= e# Make an upper case and a lower case copy and check if they are equal.
{ e# If they aren't... (i.e. if this is a letter)
Pmr e# Generate a uniformly random value in [0,π).
mc e# Take the cosine.
1.mr e# Generate a uniformly random value in [0,1).
ml e# Take the natural logarithm.
-50* e# Multiply by -50.
mq* e# Take the square root and multiply by the cosine.
A+ e# Add 10.
mo e# Round to nearest integer.
{ e# That many times...
48mr e# Generate a uniformly random integer in [0,47].
'̀+ e# Add it to the first combining mark.
}*
}|
}/
```
This means we just dump all the characters and combining marks on the stack in the correct order, where they are printed automatically at the end of the program.
[Answer]
## Python3, ~~162~~ 156 bytes
```
from random import*
q=lambda z:''.join([v,v+''.join(choice(list(map(chr,range(768,815))))for i in range(int(normalvariate(10,5))))][v.isalpha()]for v in z)
```
Possible usage:
```
print(q(u"Programming Puzzles and Code Golf"))
```
I import random, generate a string of all combining characters, return a random subset of combining characters according to mean 10, stddev 5 normal distribution and append to each alpha letter in then string, then join the results.
Test input:
```
Programming Puzzles and Code Golf
```
Test Output:
>
> P̡̣̝̬̞̃̏̋r̫̤̒̇̋̂̉̔̂̕ó̘̫̔g̭̤̝̖̅̏̍̆̇̍ȑ̮̭̃̎̒̄̅̊̚ḁ̉̅̎̑m̧̠̤̎̒̅̂̓̒m̨̮̏̐̓̐̇ī̘̌́̄̆̋̏̉̇ń̝̀̑̔̅̏́̑̕g̢̞̬̥̜̩̖̎̍́ P̨̞̮̭̂̄̄ử̝̔̍̋̀̕zž̧̥́l̩̫̣̉̊̍̋̐̊̌ĕ̡̛̤̖̤̄̅̈̚s̨̨̞̝ ą̙̦̖̄̓̊̌̉̌n̢̙̜̪̤̣̪̔d̘̙̠̝̫̭̜̑̔̕ C̢̛̝̦̬̝̈̄̏̏ȏ̡̇̓̐̎̆̉̌̄d̗̝̞̤̟̭̓̐̈̕ė̡̛̜̥̥̠̟̦̌ G̖̟̘̅̄̈́̚o̧̗̬̗̥̞̙̐̌̊l̢̞̖̟̑̇f̢̛̩̀̒̃̌̈
>
>
>
[Answer]
# MATLAB, 89 bytes
Credits go out to DankMemes, but as I am not able to comment yet I'm forced to place my improvements w.r.t. his MATLAB submission in a separate answer.
```
function o=z(a),o=[];for c=a,o=[o,c,randi(49,[1,isletter(c)*fix(normrnd(5,10))])+767];end
```
Slightly more golfed by replacing the newlines with commas and semicolons (which also suppresses the intermediate outcomes from the loop).
* *9 bytes* can be won by replacing **isstrprop(c,'alpha')** with **isletter(c)**.
* We don't need the dots in front of \* and +, as we multiply with a scalar. That's another *2 bytes*.
* **fix** instead of **floor** for *2 bytes*. It does give a slight bias towards 0 though, so alternatively **ceil** can be used to gain *1 byte*.
* I changed the random character pick to work with random integers between 1 and 49 to reduce the amount of operations and save some additional bytes.
Using it with
```
z('Simple check for proper functionality results in this beautiful text!')
```
Results in
>
> Ś̜̬̭̃̑̓́̃i̩̰̗̙̫̜̇̀̑mplë̥̟̣̩̙̗̐̌̇ cḧ̢̛̰̝̣̝̋̋̑eç̛̞̖̖̰̰̝̭̞̜̝̥̋̎̇̄̂̆̆̔̎̊k̢̟̠̞̈̌̂ for̢̡̫̥̩ ṗ̝̥̗̬̯̯̝̍̑̈̊rop̡̡̨̢̝̫̤̠̫̠̏̎̄́̒ė̦̋̕ŕ̦̣̇̊ f̧̜̦̏̏̉̇unc̨̢̗̟̙̩̝̠̄̈̋̑̏̎̄̇̌̒́̇̚ti̝ỏ̧̯̰̥̣̜̎̓̀̊̔̒̉̔̑̑̔̋̚n̡̘̠̮̤̖̥̤̂̔̇̇al̩̫̇̇̔it̫̮̔̎̕y̡̰̰̦̔̇̏̎̋ r̛̙̯̉ĕ̬̟̉̓̌s̛̝̝̭ul̨̧̧̛̙̤̥̜̟̞̔̓̓̊̀̂t̡̠́̓̀̉̎̒̈̚ş̗̠̋̍̏̌̎̕ ǐ̛̗̭̪̤̃̏̍̎̈̓̐̚n̞̮̞̬̝̭̎̔̍ th̢̧̛̬̬̖̠̗̮̰̠̖̖̠̞̦̞̎̄̓̎̇̆̚̕is̟̬̍̂̎ bea̭̗̝ṳ̝̞̠̦̣̤̦̅̂̒̄̒̔̉̏tỉ̪̩̅̓̂f̢̝̰̬̤̰̊̊̉̎̕̕u̡̝̇l tex̰̤̥̍̕t̡̝̥̣̟̩̟̉̂̆̋̈̈̈̍̔!
>
>
>
[Answer]
# Javascript (ES6), ~~199~~ 196 bytes
Uses a [Box-Muller transform](https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform) for the normal distribution (which ends up taking a lot of space, unfortunately. JS is not the best language when it comes to normal distributions)
```
i=>i.split``.map(e=>e.match(/[a-z]/i)?e+Array((i=~~((M=Math).sqrt(-50*M.log((R=M.random)()||.1))*M.cos(M.PI*R()||.1)+10))<0?0:i).fill().map(f=>String.fromCharCode(~~(R()*48+768))).join``:e).join``
```
[Fiddle](http://jsfiddle.net/Leq5kyf9/3/)
Edit: I made a mistake and had to add one byte. This should now zalgoify capital letters as well as lowercase ones.
Edit 2: Simplified the transform as in Martin Buttner's answer.
[Answer]
# Perl, ~~81~~ 79(?) bytes
Gee, you guys are all using variables! Who needs variables? :)
Here’s the simple code, which is just 79 bytes, most of it taken up by silly identifiers(but not variables :):
```
use Math::Random;s/\pL\K/(x x random_normal 1,10,5)=~s,.,chr 768+rand 48,reg/eg
```
Which, written more normally without compression, might be:
```
use Math::Random;
s{
\pL # find a Letter
\K # and Keep it, so the insertion point is right afterwards
}{
# make a string of x's and replace each with a random combining character
("x" x random_normal(1,10,5)) =~ s{
. # take any character, including our x
}{
chr( int(768 + rand(48)) );
}xreg;
}xeg;
```
## How It Works
1. Load the [Math::Random](https://metacpan.org/pod/Math::Random) module, importing the *random\_normal* function.
2. For each letter of the input:
1. Get 1 random real number from a normal distribution whose mean is 10 and whose standard deviation is 5.
2. Create a string containing as many *x*’s as the integer truncation of that random normal real number.
3. For each of those *x*’s:
1. Generate an evenly distributed random real number in the range [768, 768+48).
2. Derive the character whose code point is the integer truncation of that random number.
3. Replace the current *x* with that character.
4. Place the resulting string of combining characters after that letter.
## How to Count?
But I’m not quite sure how to count it because I’m not clear on the output requirements and the function requirements and how these impact counting.
## File Execution
The solution above transforms its input and leaves the result where it is using the normal input space as with *sed*. If you want it printed, you would need to add a `-p` switch.
So for example, if you put that in a file named *zalgo* then you could test it this way:
```
echo These are not the zebras you are looking for. |
perl -p zalgo
```
which produces
>
> # T̛̝̠̟̙̭̗̮̘̠̪̖̤̍́̇ĥ̫̞̥̙̞̈̈e̢̨̛̟̥̥̫̐̒̄s̛̮̊̒̆́ę̨̛̪̗̝̙̥̘̯̈̃̏̑̄̆̍ à̢̨̖̫̟̮̂̍̒̍̓ř̛̜̌̎̅ȩ̛̗̣̗̬̒̉̄̇̉ n̥̟̪̪̙̞̠̝̪̄̓̅̈̎ȏ̧̭̭̫̤̥̒̉ţ̛̛̜̅̔̏̍̆̓̊̔̍̍̕ t̝̬̜̫̦̜̭̄̀̂̈̎ȟ̛̗̭̌̏̐̍̀̚ē̯̬̙̖̘̒̕ z̡̨̛̯̠̥̪̣̤̟̐̍̀̉ë̬̫̪̟̟̔̚b̗̝̣̎́̚r̞̟̋ã̢̛̪̪̗̝̞̝̃̄̄s̡̢̧̛̙̖̙̘̊̐́̀̎̚ ÿ̢̪̥̤̮̫̏̇̌̆o̡̜̝̓ŭ̜̖̦̥̦̞̑̏ á̡̤̫̞̟̥̘̒̔̋̑̐r̛̛̮̥̘̫̅ȩ̦̗̞̯̮̄́̂̈ ľ̠̉̈̀̒̚ò̖̘̖̉̋̀̊̔̏̇̕o̡̦̦̜̫̫̬̅̇́̌̏̚k̡̪̔̄̉̍̄̋̂̊ȉ̢̨̙̭̥̫̟̉̑́̏̌̚̚n̜̣̎̄̄̐̈̋g̖̞̭̘̜̞̑̂̃̅̅ f̡̧̡̛̤̓̀̏̚o̓ṙ.
>
>
>
I’ll revise the byte count once I learn how you’d like this to be counted.
---
## Zalgotic Beowulf
If might be better to test this on something with more interesting letters so show that it doesn’t get stuck on some 1960s notion of what letters are. For example, it should be well-behaved on stuff like *æþelingas*. So given this text with the three first lines of *Beowulf*:
>
> Hwæt, we gar-dena in geardagum,
>
> þeodcyninga þrym gefrunon,
>
> hu ða æþelingas ellen fremedon!
>
>
>
Here’s how to make a zalgotic Beowulf:
```
perl -p zalgo beowulf
```
Which emits:
>
> H̝̙̓̒w̢̩̞̫̠̖̍̅̉̚̕̚æ̛̖̭̭̝̊̄̒t̢̬̩̒̑̑̇̔, w̨̢̢̘̥̎̆̑̉̐̇̃́̃̌ę̛̛̩̥̩̣̗̮̜̗̋̂̋̒̒̑̆̆̑̒̀ g̗̦̟̯̑ā̖̦̮̀̐̏̓r̢̫̄̈̊̉-d̨̗̪̜̃́̂̅̕ḙ̡̨̠̣̠̣̎̉̄̊̐̒̂̏̓̔n̟̤̫̓̄̉̓̔ą̗̪̃̈̔ i̡̤̤̣̠̮̍̚n̨̟̝̥̊̈̌̀̏̂̌̍ g̡̛̜̘̮̈̋̈̂̒̓̕e̢̞̤̐̒a̢̨̪̟̟̘̦̗̬̓̐̉̎́̏̓r̡̫̙̐̑̉ḋ̛̖̮̫̜̫̒ą̢̣̮̦̪̙̮̙̠̏̂̎̄̉́̅̚g̛̭̣̩̜̙̓̑̎̊̑̏̏u̡̢̞m̡̫̝̞̗̟̞̈̉̆̋̒,
>
> þ̢̧̛̩̟̬̘̣̟̦̣̃̊̋̌̎ḙ̭̖̋̊́̎ọd̪̙̉c̝̭̩̦̠̓̅̅̍̐ỷ̖̞̥̦̐̍̏̄́n̬̥̥̣̗̂̀̄̕ĩ̡̡̗̞̩̗̋̒̆̏ṅ̢̢̫̬̝̑̉̌̈̌̐ĝ̥̭̬̤̇̂̅̎̂̅́̊̇ā̫̦̥̗̙̙́̀̕ þ̢̙̥̝̬̖̣̦̬̗̗̎̌̓̄̐̑r̡̢̨̯̬̮̝̮̜̩̃̉̅̐̀̑̓̐̉̈y̖̜̫̠̜̐̕m̧̟̜̣̘ g̢̧̪̗̫̘̖̃̍̓̑e̡̯̓f̛̬̥̔̌̒ř̨̜̙̠̥̒́̋ú̗̘̊̆̆̄̕̕n̢̛̜̫̍̐̐̋̉o̤̘̬̜̥̖̜̫̎̋̔̏̍̀̋̉n̨̧̮̆̑̅̇,
>
> h̨̬̪̝̭̀́̐̕̚̚ú̜̖̭̭̯̘̗̠̊̊̆̌̀̀̕̕̕̚ ð̦̦̤̠̬̖̏̉̑̓̆̍̒̋̚̕ẳ̧̫̦̚ æ̯̙̘̣̯̋̆̑̑̀̅þ̢̝̣̯́̆̇̈̐̊̅̈ệ̗̙̣̙̪l̢̧̝̗̦̖̟̔̄̐̄̊̚i̡̬̝̘̜̍̉̏̑̍̊̐̋̔̉ņ̥̩̣̋̐̊̇̔̎̉̋̓ģ̝̬̯̪̥̞̪̃̅à̧̨̤̫̖̊̅̓̄̑̏̊̋̚̚s̨̡̥̭̞̙̎̓ ê̜̆̊̆́l̘̪̟̙̙̝̎̀́̂ľ̢̛̬̥̗̋̀̐̅̎̔̔̄̉ẽ̡̨̤̬̭̦̞̤̯̬̍̀̋̚ň̢̨̖̘̣̖̝̞̙̍̀̆̄̂̕ f̩̘̦̦̜̦̞̑̏̄̋r̘̓ẹ̤̠̟̀̅̔m̢̪̮̙̗̆̉̒̚̕̚e̎d̬̘̓̒̈̆̓̒̄̑̚ò̡̝̥̮̯̝̜̯̜̘̞̑̐̌̇̓̐n̪̣̗̤̈̎́̆̊!
>
>
>
>
---
## All CLI, No Files
If you wanted to go all command line, you could inline it this way:
```
echo "This particularly rapid unintelligible patter isn’t generally heard and if it is, it doesn’t matter." |
perl -CS -MMath::Random -ple's/\pL\K/(x x random_normal 1,10,5)=~s,.,chr 768+rand 48,reg/eg'
```
and generate this from it:
>
> # T̢̜̪̜̬̥̝̂̉̆̈̏̏̒̂̋̊̕h̢̛̙̝̦̥̫̉̌̑̐̚į̧̧̪̀̉̌̐š̙̗̘̑̉̒̋̈̍̐̊ p̡̛̛̗̞̜̙̔́̊̊̊̆a̬̦̫̠̦̜̐̂̈́̅r̢̩̩̝̣̖̔̊̇̈t̢̘̫̪̜̄̍̏̌̄̚i̞̟̜̊̍̒́̄̂c̟̑̑̃̌̋ư̧̫̫̝̠̟̦̎̋̍̓l̛̥̞̖̟̩̈̋̈̍̍a̢̜̦̘̫̓̉̇̂̇̒̓̆ȓ̪̤ļ̬̫̟̣̬̬̆̃y̌ ŕ̩̞̟̖̝̬̟̪́̒̐̔ȧ̡̟̖̙̤̜́́̎̍̀̒̌̋p̪̤̦̜̒̉̈̌̌̆̇̉̚ỉ̧̡̟̪̔̔̀̈̅̆ḑ̖̣̐̆̍́̃ ṳ̩̗̫̦̦̗̤̅̃̒̊̆nį̧̢̫̪̦̩̞̞̎̉̅̇̆̔́̋̐̍ņ̡̧̛̩̘̪̪̪̎̈̕̕t̥̤̬̩̦̓̄̍̑̇̄e̡ĺ̢̠̓̂̇̅̐̚ľ̗̭̝̪̀̅̕í̤̬̥̙̭̠̊̅́̒ģ̩̬̣̃̐̆̇̓i̛̗̦̭̙̝̐̔̇̄̉̄̇bl̖̭̘̣̙̤̇̎̔̅̒̔̚e̘̤̖̞̎̎̅̍̕ p̧̢̡̟̠̜̬̩̃̀̆̃̆̍a̧̡̭̙̥̤̟̟̔̄̎̔̓̕t̖̦̎̊̏̉̕ţ̤̥̦̝̜̭̤̈̆̊̓̈̊̎̚ȇ̡̛̖̈̊̓̎̕r̟̫̍̒̅̈̈ i̧̘̪̠̟̗̙̭̍̇̄̊ş̛̩̖̦̬̞̣̤̘̫̓̊̆̈̌̓̐̎̕n̡̧̜̥̤̪̩̋̇’t̓̈̑̀̈̔̈̐̔̊̒ g̛̤̋̇̋ę̢̛̛̠̤̥̟̞̣̫̞̬̝̙̐́̂̂̍̕n̩̟̙̞̖̭̫̂̂̌̃̔̉̑ȩ̗̥̥̠̂̈̉̅r̪̫̩̂̀̄aḽ̢̜̖̝̌̇̓́̒̑ļ̢̧̫̦̥̬̤̑̎̒̒̓̑̚̚̕ỳ̛̥̖̭̍̐̃̑̍ h̖̬̠̠̝̜̝̪̗̒̊̊̋̄ȩ̛̞̭̪̜̤̟̘̣̅̆̃́̂̔a̛̝̕r̝̦̅̅̍̍̎̂̊ḑ̩̞̬̘̪̝̝̍̏̂̓̔̄̑̕ ą̡̧̬̞̝̟̍̓̉́̈̀ň̛̟̩̙̈d̡̜̥̣̦̫́̅̌̚ ĩ̖̜̔f̧̅̌ į̡̢̪̬̫̟̜̄̑̑̓̊̚̕̚t̪̘̦̩̐̄́̐ ỉ̥s̪̝̤̀̈̚, ǐ̪̭t̛̬̭̝̋̄̋̇̏̉̆̚̕̕ d̝̗̭̓̒̂o̡̝̙̒̅̒̏̉̚e̢̦̦̝̘̘̣̔̓ş̛̤̤̊̇̃̋̎ṅ̨̧̬̤̜̚’ţ̪̗̭̘̟̝̔̋̑̀̇̃̈ m̢̛̦̭̖̥̪̫̙̤̈̅̏̃̂̆̋̈̌̕ả̛̜̝̝̗̣̦̅̚t̫̤̜̘̒̅̅̚t̪̬̗̘̑́̔̓̏̅̉̆ȇ̡̦̘̣̘̭̖̞̥̄̔̑̆̂̃̀̀̍̇̉̚̕r̛̭̙̘̬̉̄̆̉̇̅́̕̕.
>
>
>
---
### The Fine Print
To really make this work well, you may need to have something in your environment or on the command line or in the file to say this is Unicode throughout. That might be `-CS` or `-CSD`, or `PERL_UNICODE=S` or `PERL_UNICODE=SD` depending on which way you’re going at it. However, because the problem says we don’t actually have to print anything, and that the input is mere ASCII, these are not needed for the small specific case given in the problem description.
[Answer]
# Groovy, 201 196 182 174 170 154 146 130 129 124 bytes
My first golf, not really aiming to win here but figured I'd give it a shot anyway.
Run it as `groovy zalgo.groovy 'input'`
```
o='';r=new Random();args[0].chars.any{o+=it;if(it.letter)(r.nextGaussian()*5+10).times{o+=(char)(768+r.nextInt(48))}}print o
```
Ungolfed ([with syntax highlighting](https://gist.github.com/unascribed/500f6acaed7d01657abd)):
```
// By making this a Groovy script, the weight of
// a full Java-like class definition can be avoided
////
// Originally, this part of the answer used the 'def'
// keyword to infer the type of the variable, but it
// turns out you can define a variable in Groovy
// without any type at all.
buffer = '';
rand = new Random();
// There used to be a for loop here using def, but now it's a
// .any closure. .any saves a byte over .each.
////
// Groovy automatically defines an args variable for
// scripts, which we use here.
args[0].chars.any {
// As in Java, += works on a String. Previous versions of the
// answer used a StringBuffer, but a String works just as well.
buffer += it;
// Another Groovy extension; we can use the primitive char like
// a Character object, and use .letter instead of .isLetter()
if (it.letter)
// Since Gaussian is already a normal distribution with mean 0
// stddev 1, we can fix that with a quick multiply and add.
((rand.nextGaussian() * 5) + 10).times {
// I use the literal number '768' here, as it's the same size
// as a Java char literal, and Groovy doesn't have char literals.
buffer += (char)(768+rand.nextInt(48));
}
}
// Finally, we can take a quick shortcut here by using the
// parentheses-less syntax for print in Groovy. Using print
// instead of println saves a whole two bytes!
print buffer
```
Example output:
>
> P̊r̡̜̋̎̎̆ȍ̧̨̖̣̖̠̪̬̘̂̚g̩̯̗̈̃̆r̡̮̭̬̙̟̟̭̗̅̐̀̑̕ą̢̛̜̗̗̩̂̓̂̎̕m̝̬̊̂̒̐̕m̤̠̪̣̍̓̍̂̍̚į̫̣̞̝̬̪̘̟̎̅̒n̛̬̦̗g̝̦̏̇̏̀̆̓ P̨̨̡̉́̓̒̕ų̠̤̪̬̘̪̪̤̪̏̀̎z̛̜̀̒̐̕ž̛̙̮̩̔̌̉̉̎̍́̑l̨̡̤̗̮̜̣̬̩̜̜̭̦̈̒̊̃̊̌̉ȩ̘̬̖̞̗̦̘̪̬̇̅̅̈s̒̄́̌̎ & Ĉ̢̣̜̗̟̤̌̒ơ̡̜̪̖̫̂̉̍̆̐̊̇̔̍̕̚d̛̛̦̫̫̯̥̯̭̍̋̔̆̂̕ê̫̪̆̍̒̄ G̙̪̅ȏ̢̥̖̘̦̟̜̪̈̔̌̑l̯̘̞̅f̬̗
>
>
>
[Answer]
## Moonscript - 118 117 112 110 105 96 bytes
This needs to be saved as Latin 1, but generates utf-8. It uses the central limit theorem to approximate the normal distribution. `math.random!` returns a number with a uniform distribution 0 to 1, which has a mean of 0.5 and a standard deviation of 1/sqrt(12). If we add 300 samples, we get a number with a mean of 150 and a standard deviation of 5, with an approximately normal distribution. We subtract 140, and the distribution now has the correct mean.
In utf-8, the character codes U+300 to U+32F are encoded as 11001100:10000000 to 11001100:10101111. So it is the byte 204 followed by a random byte 128 to 175.
```
r=math.random
=>@gsub '%a',(b=-140)=>
b=b+r!for _=1,300
@=@[[email protected]](/cdn-cgi/l/email-protection)(204,127+r 48)for _=1,b
@
```
This is a code block which returns an anonymous function taking one argument, the string, and returning the zalgo-fied version. Assuming this is saved in zalgo.moon, a full program that uses this would be:
```
print require'zalgo' io.read!
```
Edit:
* Turns out it's cheaper to use char code 204 instead of an embedded Latin 1 character.
* Can access string.char using a.char
* Switch to command line args, rather than stdin.
* use method for implicit parameter @.
* Switch to a function that returns a value
[Answer]
# MATLAB, 106 bytes
I thought I'd submit another answer from a language which actually has a built in normal distribution function. I don't think I've ever tried MATLAB before so this may not be the most golfed it can be.
```
function o=z(a)
o=[]
for c=a
o=[o c floor(rand(1,floor(normrnd(5,10)*isstrprop(c,'alpha'))).*48.+768)]
end
```
[Answer]
## AutoIt - (sad) 219 bytes
```
dim $r=random,$f
for $u in stringsplit($i,"",3)
do
dim $a=2*$r()-1,$b=$a^2+(2*$r()-1)^2
until $b<1
$f&=$u
for $m=1 to $a*sqrt(-2*(log($b)/$b))*5+10
$f&=stringregexp($u,"\p{L}")?chrw($r(768,815)):""
next
next
clipput($f)
```
What's really bloating up the code is the distribution calculation. I cheated a bit by writing the output directly to the clipboard, because `clipput` is the shortest output function in AutoIt. The RegEx `\p{L}` matches all letters.
---
You have to supply the input using a global variable `$i`:
```
$i = "A study in scarlet."
```
yields
>
> Ą̣̘̤̪̜̮̎̊ s̭̫t̡̢̢̡̢̩̝̙̍̏̂̇̎̍̂̈ǖ̮̮̭̬̋̕ḑ̦̗̟̄̀̒̌̂̕y̨̧̙̪̩̎̀̓̋ į̣̦̥̮̔̈̃̅̐̌n̗̜̑ s̘̦̞̘̗̠̣̤̏̊̐c̨̡̛̭̝̬̭̜̟̥̝̮̍̄̊̎̔á̡̬̤̠̦̠̗̟̆̍̄̈̕r̛̤̥̬̠̋̍̒̚ļ̨̞̫̤̆̊̋̑ë̟̪̝̞̑̌̎̆̓̇̇̀̚̕t̢̖̟̞̟̘̮̅̎̂̐.
>
>
>
[Answer]
# Javascript, ~~190~~ ~~169~~ 136 bytes
```
function q(z){var o="",r=Math.random;for(var v in z){o+=z[v];for(var k=0;k<r()*100;k+=r()*10){o+=String.fromCharCode(768+~~k)}}return o}
```
usage :
```
var d=q("There is snow on the ground \
And the valleys are cold \
And a midnight profound \
Blackly squats o'er the wold; \
But a light on the hilltops half-seen hints of feastings un-hallowed and old. \
")
```
output :
...
>
> T̡̗̙̀̅̎h̀è̇̋r̖̀̄̉̍̔̕è̀̅̉̏ ̀ì̘̟̥̫̱̀̇̐s̖̟̦̀̀̀̉̊̍
> ̗̀̇̉̎̕s̗̀̃̈̊̑ǹ́̈̍̏̐ò̅̈̎ẁ̃̅̋ ̀̉ò̜̟̦̬́̄̌̓ǹ̘̀̉̌̍̒
> ̛̝̀̈̒t̀̀̀h̘̀̈̐è̇̊̋̍̐ ̙̝̥̪̮̱̀̂̋̔g̗̀̉̒r̖̀̉̑ò̅̋̎̏̓̓ù̙̈̋̑ǹ̄d̖̀̉̏̑̔
> ̀̆̊̍̕ ̀́̆̍ ̛̀̂̂̆̍̏̕ ̀̉̎ ̀̈̌̍̒À̖̜̠̅̍̏ǹ̀d̀́
> ̀t̢̙̀̆̎̐̓h̜̤̤̀̈̉̊̊̏̓è̢̘̣̈̋̎̓
> ̀̂̄̅̇̍̎v̗̙̀́̄̋̍̓̓̔̚à̛́̅̋̎̓̚l̀̂̊l̀̀̆̎̕è̗̈̑̕ỳ̃̊̍s̀̀̅̉̑
> ̀̀̂̈à̈̊̌̎̑̒r̢̢̘̤̀̂̃̃̋̑̓è̖̗̇̉̏ ̀̈̈̍̎̑c̀̃̈̏ò̄l̀̆̍d̀̅̈̉ ̀̉̒̓
> ̷̡̨̙̥̬̮̰̀̄̍̒̿̓͌̕ ̛̀̉̌̒ ̀̃ ̀́̈̊̐̑À̈̊̏̏̑ǹ̂̌̎d̖̀̉̑̕ ̙̀̃̆̋̔à
> ̖̀̀̄̆̌̍̕m̛̖̀̃̄̇̇̍ì̀̄̅̆̋̕d̀̈̊̏̕ǹ̀́̇̉ì́̊̎̕g̘̘̀̇̍̑h̗̟̟̀̅̎t̜̞̣̀̀̃̋̍̏̒
> ̛̖̀̇̍p̖̟̥̀̈̍̓̚r̛̠̀̅̍̍̕ò̢̖̜̃̄̎̎̓̓f̘̙̜̀̂̇̊̒ò̙̅̉̐̕̚ù̡̖̙́̂̈̉̋̔̔ǹ́̇d̀̂̇̇̉
> ̘̘̀̄̇̑ ̨̖̖̗̣̀̄̆̊̏̑̑̚ ̀̉̒ ̀̀̅̈̋̑
> ̢̗̙̀̀́̅̍̎B̀̆̋l̤̫̀̀̇̍̔̚̚à̂̃̋c̀̄̄k̜̥̪̀̄̇̋̎̓̓l̀̂̉̊̐ỳ̃
> ̖̘̀̉̍̎̐s̀̆̇̊̑q̀́̂̄̄̇̍ùà̈̎̑t̀̂̅̈s̀̀̀́̃̅̅̍
> ̛̀́̂̇̉̌̓̔ò̅̅̇̇'̀́̄̇è̄r̡̛̀̀̈̈̒ ̀́̉t̀̀̂̊h̀̂̆è̢̂̋̔̚
> ̀̀́̄ẁ̞̦̫̰̀̇̌̍̕ò̂̃̄l̝̀̇̎̏̒̒̕̚d̘̜̜̞̥̀̃̉̐;̡̙̤̪̬̀̇̋̑ ̘̙̠̀̆̎̚ ̀̅̉̓ ̖̀̃̌
> ̖̙̀́̄̅̉̒ ̀B̀̈̐̔ừ̘̆̎̏̑t̘̟̀̃̉̊̍̏ ̀̉̋à́̈̋̐
> ̀̉̊̒̒̔l̀̀̇̊̍̓̚ì̃g̀̈̐h̨̖̟̮̀̂̆̋̔t̀̇̌̍ ̀̇ǫ̗̠̠̀̆̈̉̑ǹ̇̌̍
> ̙̣̀̀́̉̏̒t̀̀h̗̜̀̃̊̊̌̎è̙́̈̋̍̔
> ̀̂h̗̀̂̇̈̏ì̙̝̣̉̑̓̓l̗̜̀̃̃̇̑l̞̀̈̏̑̕t̙̟̀̅̍̎̕̚ò̂̄p̀̂̋̍s̀̄̇̐
> ̖̀̄̋̍h̗̀̅̋̐̓à̶̢̧̝̮̈̏̕l̀̂̊f̀̀̇̇-̀̄̄̉̓s̀̂̇̍è̘̈̏è̖̟̤̥̩̰̇̏ǹ̇̋̏
> ̀̇̋̐̕h̀̉̏ì́̃̈̈ǹ̅̏̓t̀̇̈s̀̄̌ ̀̃̇̊̒ò̖̖̃̋̋̏f̛̀́̅̉̑
> ̀́̃̈f̀̅è́̅̉à̃̅̌̓s̛̗̣̤̀́̃̄̌̎̑t̀̆̉ì̞̤̭̃̈̑̚ǹ̗̟̦̂̂̅̆̊̊̊̏g̗̀̅̊̓̓s̀̂
> ̀̄̉̑̓̔ù̅̋ǹ́̊̎̒-̀́̄̈h̀́́̊̓̔à̀̈̊l̛̀̄̌̎̔l̢̛̖̣̀̉̋̕ò̆̊ẁ̉̐̚è̆̌̍d̜̥̦̭̀̀̂̈̑̔̕
> ̀̇̍̓à̈̊ǹ̗́̆̋̑̔̕ḍ̴̛̪̬̀̅̊̌̑ ̨̙̜̤̭̀̀́̈̎̏ò̈l̀̈̎̏̐d̢̝̬̀̂̃̋̌̔.̨̝̝̤̪̀̅̇̊̓
> ̀̈̌̐̓̕ ̛̗̤̮̮̰̀̃̉̊̏̐̒ ̀̄̇̏ ̀̉̐ ̀́̅̇̎
>
>
>
[Answer]
## Perl, 73 bytes
```
s!\w\K!$x=-140;$x+=rand for 1..300;(x x $x) =~ s/x/chr 768+rand 48/ger!ge
```
Input is taken as newline-separated strings.
If you want to ignore the warnings printed to STDERR, use the `-C7` command-line flag.
This uses the same approximation for a normal distribution as the Moonscript solution.
[Answer]
# [Haskell](https://www.haskell.org/), 223 bytes
```
import System.Random
import Data.Char
a!b=round$10+sqrt(-50*log a)*cos(2*pi*b::Double)
r=randomIO
m=mapM
z s=concat.zipWith(\c r->c:[x|x<-r,isAlpha c])s<$>(m(\_->(!)<$>r<*>r)s>>=m(\x->m(\_->randomRIO('\768','\815'))[1..x]))
```
`(!)` does a Box-Muller transform on a pair of numbers, z maps each letter into random normally distributed number `x`, which is then mapped into the range `[1..x]`, in which all numbers are replaced by a uniformly random punctuation. The original characters are then appended to these lists.
Sample output:
[T̢̨̮̝̘̖̗̣̟̝̞̘́̔̇̅̌̐̐̋̕ŗ̦̘̬̄y̩̦̯̞̍̂̑ ï̛̘̣̟̭̮̩̄̍̑̂̅̚t ȯ̖̤̞̎̓̔̏̕̕̚ń̢̦̖̟̠̜̯̒̀̏̑̕ļ̨̛̫̟̝̎̇̃̍̑̊̇ĩ̛̯̙̦̦̐̚n̮̪̮̞̞̈̄̔̀̚ȩ̨̜̟̬̟̫̩̦̌̂̆̋̏̄̏́!](https://tio.run/##LY1dS8MwGEbv@yvejUGTupZVmI7SBMTdDJTBJnixDkmzYoP5MkmhK/73WpyXz3ngnJb5r0bKcRTKGhfgePWhUdmB6YtR0T/cssCy55a5iM1q4kynL4t8dee/XUDpepVI8wkMJ9x4dJ9YkdRFsTVdLRscOeL@VLt9pIhi9jUawBNuNGchG4R9F6FFFQeXUl6c@p@@TN1S@CdpWwb8jH25oEih6iOlaIan4cqEOuwpJRPtU3r7bpHDbo/i6vFhEy/japOvY4xPeZb1Z4xHxYQGAgPM39wVRACjpdDNbA6TCmwXjsG96PEX "Haskell – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~68~~ ~~63~~ 59 bytes
```
{S:g/./{chrs roll max(0,-140+sum rand xx 300),768..815}$//}
```
[Try it online!](https://tio.run/##PYxLC4JAAITv/oqhInr6oLIoOoTYA9IN7GK3pRYNVld2DRTpt9t6aRj4LjNfwSR326zGkO3bJtomlmk1z1QqSME5MlqN7NncWdpT9ckgaf5CVWFh2@PZ2t2Y5sZZfQeW9W13hmH0YSjaqUa9MmV4P1MhUTCZMVoyBaqFQYzjwfP/TJGIF3KBkOjqIIQqRYFOQPNJwrujZHpSQjLK8ThcTwSXCHcS1riffdxIGEPTI4Ef9ca79gc "Perl 6 – Try It Online")
>
> t̤̣̜̉̌̂̇̍h̢̙̦̩̉ȇ̡̡̢̛̞̠̔̑̃̊̑̓ ̗̩̜̎̒̑i̛̭̤̘̒c̛̤̮̔́̑̃̔̅̐̑̚hǫ̘̣̩̣̙̙̆̎̂̉̋̊̕r̨̦̯̋̀̊̀ ̥̙̉̓̃̇̑p̢̨̛̯̗̥̞̞̘̬̪̗̠̖̅̅̉̃́̀̐̉e̖̋r̒̐m̧̖̪̉̐ẻä̪̞ţ̯̠̦̖̍̍̋̅̊̀̕ḙ̡̡̙̐̓̌̉̌ŝ̢̧̝̃̉̀ ̡̮̘̤̙̤̘̋̃̂̋̊̐̀̏̋̐̐̒ą̛̞̥̦̘̌̊̋̂̂̒̆l̢̛̛̮̘̜̦̝̫̮̪̟̭̖̜̅̑̂̍̑̉ḷ̨̞̜̤̠̣̪̥̋̀̇̊̊̍̈ ̢̢̤̜̬̫̊̇̑̐̇̑̒̕Ḿ̢̭̫̘̟̟̤̮́̃̎Y̧̬̖̜̆̀̍̍̐̒̉̒ ̡̗̔̎̆̆̀́̎F̬̯̯̏Â̡̛̝̭̎̂̉̑C̡̦̄̑̓Ę̛̭̞̤̂̓̔̃̎̓̏ ̛̪̬̯̘́̐̚MÝ̛̝̫̥̖̓̏̑̀ ̘̤̄́̍F̬̯̠̩̞̊̃̓̔̕Ă̙̥̞̤̕C̪̓̆E̡̟̝̭̦̮̎̒̅́ ̭̈̋ḣ̢̛̫̗̩̩̣̭̋̎̐̃̄̈̉̓ ̦̘̖̃̉̔̂̆̃̍̅̕g̡̧̢̜̬̪̞̟̒̇̊́̃̋̚ǭ̫̣̩̙̆̏̏̌̑̀̕d̟̮̠̬̙̗̥̪̭̜̐̑̊̔̕̕ ̨̙̠̟̠̯̆̑̅̒̔ṋ̛̘̜̞̦̈̋̋̍̋̈ơ̡̧̗̟̟̩̙̔̏̀̈̀̇̇̆̎̕ ̨̛̦̎̀̕N̛̄̋Ò̢̡̙̦̓̑̒̂̆́ ̧̗̮̠̗̮̯̆̉̑̅N̛̤̤̒O̧̤̯̯̦̥̒̍̏̃̇̊̕Ő̜̩̙̂̀̎̕Ọ̝̗̆̉Ơ̢̦̫̭̪̐̚̚ ̨̢̞̊̉̑̍̎̆̒N̡̞̭̙̏̏̓̄̚ ̠̖̫̦̗̓̉́s̤̄̋t̨̞̫̣̭̏̔̀ở̜̘̝̉ṗ̧̬̗̥̫̤̗̣̄̋̒̎́̒ ̯́̃̕ṭ̮̖̟̥̗̤́̊̋̇̎ḩ̞̜̗̪̊̂̏e̢̞̬̟̟̠̗̎̌̐̏̔̒ ̥̠̞̉̌́̈́̈̏̍ä̡̨̩̩̯̦̐̂n̢̟̫̖̯̞̗̙̙̊̋̐̍̚\*̢̘́̒̉̎̚g̛̗̬̐̂́̇̉̆̀̚l̨̢̦̪̬̤̤̂̀̇̉̂̍̒̚ȩ̧̢̖̘̠̓̐́̈̌s̘̯̘̒̉̆̒̄̈̇̕ ̡̧̛̬̠̣̮̅ă̗̮̖̜̥̟̮̋̅̉̍̅̕r̢̢̢̤̩̙̩̋̑̓̍̆̍̕̚e̡̛̙̗̅̄̄̒́̚ ̡̖̫̞̖̖̟̣̭̅̐̄̑̊̃̉̎ǹ̗̟̤̄ö̪̏̎t̡̛̫̥̗̫̠̜̪̏̒ ̡̡̢̜̮̭̇̒̋̑̏̃̓̕r̡̗̬̯̪̝̮̂̊̒̏̔̉̀̚e̢̧̗̯̞̭̘̝̐̓̈̔̊̋̉å̖̣̔̋l̡̛̛̬̮̟̝̪̯̆̊ ̡̪̩̐̒Z̡̦̗̝̞̜̠̊̇̓̆AḶ̒̇̇̅̓̈̃̂Ğ̮̯̭̮̘̞̙̣̐̐̉̇Ő̡̠̞̄ ̢̟̖̪̋́́̔̚̚Į̪̗̭̖̊Ș̢̬̤̜̥̟̌̅ ̨̢̜̥̪̠̦̦̦̘̟̯̯̋̒̓̍̈̇̕T̢̉̆̌̊̎̈̕Ȍ̧̢̫̬̄̉̀̇̍̍̌̚̕Ņ̥̩̝̟̀̈̀̇̆̏̕y̛̟̫̠̭̫̗̫̮̬̥̥̭̗̓̏̑̋̍̇̐̔̋̐̅ ̝̥̘̫̪̖̫̅̂̌́̎̀̚̚̕Ṭ̌H̦̫̖̟̥̣̔̚̕Ę̢̬̮̩̣̙̇̅ ̨̧̝̭̩̟̈̂̈̃̓̓̚P̩̞̭̠̝̗̂̓̒̋̄Ợ̙̬̜̮̄̑̊̏̒N̘̤̆̏̇Y̨̫̪̜̖̯̒̎̋̌̍̈̄̊ ̧̣̠̣̜̌̄̇̋̄̊̉̏H̛̠̮̣̝̩̖̋̑̍E ̡̢̙̘̥̬̗̯̄̌̔̂̀̆̇̔̑C̪̣̮̋̇̎O̧̨̩̖̠̓̓̉̚̚̕M̛̛̙̘̟̪̙̘̩̝̖̉́̀̂̏̇Ẻ̡̛̛̘̯̜̆̀̓̓̒S
>
>
>
Uses the, ahem, 'binomial approximation' to the normal...
Text from [that bobince answer](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags).
] |
[Question]
[
I'm honestly surprised that this hasn't been done already. If you can find an existing thread, by all means mark this as a duplicate or let me know.
# Input
Your input is in the form of any positive integer greater than or equal to 1.
# Output
You must output the sum of all integers between and including 1 and the number input.
# Example
```
In: 5
1+2+3+4+5 = 15
Out: 15
```
[OEIS A000217 — Triangular numbers: a(n) = binomial(n+1,2) = n(n+1)/2 = 0 + 1 + 2 + ... + n.](http://oeis.org/A000217)
# Leaderboard
Run the code snippet below to view a leaderboard for this question's answers. (Thanks to programmer5000 and steenbergh for suggesting this, and Martin Ender for creating it.)
```
var QUESTION_ID=133109,OVERRIDE_USER=69148;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} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>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](https://github.com/isaacg1/pyth), 2 bytes
```
sS
```
[Try it online!](https://pyth.herokuapp.com/?code=sS&input=5&debug=0&input_size=4) Implicit input. `S` is 1-indexed range, and `s` is the sum.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 1 byte
```
Σ
```
[Try it online!](https://tio.run/##yygtzv7//9zi////mwIA "Husk – Try It Online")
Builtin! `Σ` in Husk is usually used to get the sum of all elements of a list, but when applied to a number it returns exactly `n*(n+1)/2`.
[Answer]
# [Piet](http://www.dangermouse.net/esoteric/piet.html), 161 bytes / 16 codels
You can interpret it with [this](http://www.majcher.com/code/piet/Piet-Interpreter.html) Piet interpreter or upload the image on [this](http://www.rapapaing.com/blog/?page_id=6) website and run it there. Not sure about the byte count, if I could encode it differently to reduce size.
Scaled up version of the source image:
[![rapapaing-image](https://i.stack.imgur.com/ZqYz3.png)](https://i.stack.imgur.com/ZqYz3.png)
### Explanation
The `highlighted` text shows the current stack (growing from left to right), assuming the user input is `5`:
[![1st transition](https://i.stack.imgur.com/QPZJW.png)](https://i.stack.imgur.com/QPZJW.png) Input a number and push it onto stack
```
5
```
[![2nd transition](https://i.stack.imgur.com/phnaY.png)](https://i.stack.imgur.com/phnaY.png) Duplicate this number on the stack
```
5 5
```
[![3rd transition](https://i.stack.imgur.com/w8sLj.png)](https://i.stack.imgur.com/w8sLj.png) Push 1 (the size of the dark red area) onto stack
```
5 5 1
```
[![4th transition](https://i.stack.imgur.com/1NnS1.png)](https://i.stack.imgur.com/1NnS1.png) Add the top two numbers
```
5 6
```
[![5th transition](https://i.stack.imgur.com/qCTak.png)](https://i.stack.imgur.com/qCTak.png) Multiply the top two numbers
```
30
```
[![6th transition](https://i.stack.imgur.com/YzxG2.png)](https://i.stack.imgur.com/YzxG2.png) The black area makes sure, that the cursor moves down right to the light green codel. That transition pushes 2 (the size of dark green) onto stack
```
30 2
```
[![7th transition](https://i.stack.imgur.com/lzDKY.png)](https://i.stack.imgur.com/lzDKY.png) Divide the second number on the stack by the first one
```
15
```
[![8th transition](https://i.stack.imgur.com/8B92k.png)](https://i.stack.imgur.com/8B92k.png) Pop and output the top number (interpreted as number)
```
[empty]
```
[![final trap](https://i.stack.imgur.com/0szWJ.png)](https://i.stack.imgur.com/0szWJ.png) By inserting a white area, the transition is a `nop`, the black traps our cursor. This ends execution of the program.
>
> Original file (far too small for here): [![Original source image](https://i.stack.imgur.com/tj5kQ.png)](https://i.stack.imgur.com/tj5kQ.png)
>
>
>
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 16 bytes
```
({({}[()])()}{})
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6Nao7o2WkMzVlNDs7a6VvP/f1MA "Brain-Flak – Try It Online")
This is one of the few things that brain-flak is *really* good at.
Since this is one of the simplest things you can do in brain-flak and it has a lot of visibility, here's a **detailed** explanation:
```
# Push the sum of all of this code. In brain-flak, every snippet also returns a
# value, and all values inside the same brackets are summed
(
# Loop and accumulate. Initially, this snippet return 0, but each time the
# loop runs, the value of the code inside the loop is added to the result.
{
# Push (and also return)...
(
# The value on top of the stack
{}
# Plus the negative of...
[
# 1
()
]
# The previous code pushes n-1 on to the stack and returns the value n-1
)
# 1
# This code has no side effect, it just returns the value 1 each loop.
# This effectively adds 1 to the accumulator
()
# The loop will end once the value on top of the stack is 0
}
# Pop the zero off, which will also add 0 to the current value
{}
# After the sum is pushed, the entire stack (which only contains the sum)
# will be implicitly printed.
)
```
[Answer]
# [Oasis](https://github.com/Adriandmen/Oasis), 3 bytes
```
n+0
```
[Try it online!](https://tio.run/##y08sziz@/z9P2@D///@mAA "Oasis – Try It Online")
## How it works
```
n+0
0 a(0)=0
n+ a(n)=n+a(n-1)
```
[Answer]
## JavaScript (ES6), 10 bytes
```
n=>n*++n/2
```
### Example
```
let f =
n=>n*++n/2
console.log(f(5))
```
[Answer]
# Mathematica, 9 bytes
```
#(#+1)/2&
```
# Mathematica, 10 bytes
```
(#^2+#)/2&
```
# Mathematica, 11 bytes
```
Tr@Range@#&
```
# Mathematica, 12 bytes
```
i~Sum~{i,#}&
```
# Mathematica, 14 bytes
(by @user71546)
```
1/2/Beta[#,2]&
```
# Mathematica, 15 bytes
```
Tr[#&~Array~#]&
```
# Mathematica, 16 bytes
```
Binomial[#+1,2]&
```
# Mathematica, 17 bytes
(by @Not a tree)
```
⌊(2#+1)^2/8⌋&
```
# Mathematica, 18 bytes
```
PolygonalNumber@#&
```
# Mathematica, 19 bytes
```
#+#2&~Fold~Range@#&
```
# Mathematica, 20 bytes
(by @Not a tree)
```
f@0=0;f@i_:=i+f[i-1]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~24~~ 16 bytes
*-8 bytes thanks to FryAmTheEggman.*
```
lambda n:n*-~n/2
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk9Lty5P3@h/QVFmXolCmoap5n8A "Python 2 – Try It Online")
[Answer]
# x86\_64 machine language (Linux), ~~9~~ 8 bytes
```
0: 8d 47 01 lea 0x1(%rdi),%eax
3: f7 ef imul %edi
5: d1 e8 shr %eax
7: c3 retq
```
To [Try it online!](https://tio.run/##FYrBCoJAFEX3fsXFEN5Li6QgQe1HmhYy4@SDGkMNBsJvn8bVuZx79OGpddiJ06@v6Zt5MTIeh1vQo5sX6KGbYO@PNlW@MspfrsqfSuVtZG@VN3H3lfL6nNZB3IJ3J474lwB2nAibErQoa0jTlqeIPAdjC4DPFH9LSDODzCiXFpACRNHSnonZMgmD61ivyZqEPw "C (gcc) – Try It Online") compile and run the following C program.
```
#include<stdio.h>
const char f[]="\x8d\x47\x01\xf7\xef\xd1\xe8\xc3";
int main(){
for( int i = 1; i<=10; i++ ) {
printf( "%d %d\n", i, ((int(*)())f)(i) );
}
}
```
Thanks to [@CodyGray](https://codegolf.stackexchange.com/questions/133109/sum-of-all-integers-from-1-to-n/133252#133252) and [@Peter](https://codegolf.stackexchange.com/users/30206/peter-cordes) for -1.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 10 bytes
```
n=>n++*n/2
```
[Try it online!](https://tio.run/##Sy7WTc4vSv2fnJNYXKyQX81VXJJYkpmsUJafmaLgm5iZp6FZzaWgEFxZXJKaq@dWmpdsk5lXogPEdgpptv/zbO3ytLW18vSN/lsjlDnn5xXn56TqhRdllqT6ZOalaqRpmGpqElBhaEBYCdiU2tr/AA "C# (.NET Core) – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 10 bytes
```
n->n++*n/2
```
[Try it online!](https://tio.run/##LYw9C8IwFEX3/oo3tpZGEJxEwdFBHIqTODz7RWr6EpKXQpD@9hiL04V7zz0jzlhp09HYvqPxLyUbaBQ6B1eUBJ8M4N86Rk4xa9nClLa8ZitpeDwB7eCKFQUYk094lkr0nhqWmsSF@E5ow810Fllb6OEYqTpRWW5ou4uH9VgHx90ktGdhkpcV5b1AY1Q4u2TI90XxA5dsiV8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
RS
```
[Try it online!](https://tio.run/##y0rNyan8/z8o@P///6YA "Jelly – Try It Online")
## Explanation
```
RS
implicit input
S sum of the...
R inclusive range [1..input]
implicit output
```
## Gauss sum, 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘×H
```
### Explanation
```
‘×H
implicit input
H half of the quantity of...
‘ input + 1...
× times input
implicit output
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~22~~ 19 bytes
*Because arithmetic operations are boring...*
```
@(n)nnz(triu(e(n)))
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzMvr0qjpCizVCMVyNHU/J@mYajJlaZhBCJMNf8DAA "Octave – Try It Online")
### Explanation
Given `n`, this creates an `n`×`n` matrix with all entries equal to the number *e*; makes entries below the diagonal zero; and outputs the number of nonzero values.
[Answer]
# [Haskell](https://www.haskell.org/), 13 bytes
This is the shortest (I ~~think~~thought):
```
f n=sum[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDfaUE8vL/Z/bmJmnoKtQm5igW@8gkZBUWZeiV6apgJI1tAg9j8A "Haskell – Try It Online")
### Direct, ~~17~~ 13 bytes
```
f n=n*(n+1)/2
```
Thanks @WheatWizard for `-4` bytes!
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz1YjT9tQUytP3@h/bmJmnoKtQm5igW@8gkZBUWZeiV6apkK0oZ6eoUHsfwA "Haskell – Try It Online")
### Pointfree direct, 15 bytes
```
(*)=<<(/2).(+1)
```
Thanks @nimi for the idea!
[Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPNfQ0vT1sZGQ99IU09D21Dzf25iZh5QIjexwDdeQaOgKDOvRC9NUyHaUE/P0CD2/7/ktJzE9OL/uhHOAQEA "Haskell – Try It Online")
### Pointfree via `sum`, 16 bytes
```
sum.enumFromTo 1
```
[Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzv7g0Vy81rzTXrSg/NyRfwfB/bmJmnoKtQm5igW@8gkZBUWZeiV6apkK0oZ6eoUHsfwA "Haskell – Try It Online")
### Recursively, ~~22~~ 18 bytes
```
f 0=0;f n=n+f(n-1)
```
Thanks @maple\_shaft for the idea & @Laikoni for golfing it!
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwNbAOk0hzzZPO00jT9dQ839uYmaegq1CbmKBb7yCRkFRZl6JXpqmQrShnp6hQex/AA "Haskell – Try It Online")
### Standard `fold`, 19 bytes
```
f n=foldr(+)0[1..n]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYtPyelSENb0yDaUE8vL/Z/bmJmnoKtQm5igW@8gkZBUWZeiV6apgJI1tAg9j8A "Haskell – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 10 bytes
```
a->a++*a/2
```
[Try it online!](https://tio.run/##XU/BTsMwDD03X2Ht1BIWGEe67YjEgQs9Ig6hS6uU1IkSZ9I09duLC90FydJ7en5@tgd91lsfDA6n79mOwUeCgTWVyTrVZWzJelQvK6mFCPnL2RZap1OCN21RXIUoVjWRJoaztycYuVc2FC32H5@gY58qUVxFUXQ@QmmRwMIBdjXDHnaPjFKy49dSNJdEZlQ@kwqcQA7LjX2GDUi2S8Z3k7KjP6U31OSxtFVV8@wkuP5ftKy72Zjiesrtr/0rkulNvIeVHKGDw6y3Ry3lnX54mpfkaChHhE7pENylxGXdJCYx/wA "Java (OpenJDK 8) – Try It Online")
Took a moment to golf down from `n->n*(n+1)/2` because I'm slow.
But this isn't a real Java answer. It's definitely not verbose enough.
```
import java.util.stream.*;
a->IntStream.range(1,a+1).sum()
```
Not bad, but we can do better.
```
import java.util.stream.*;
(Integer a)->Stream.iterate(1,(Integer b)->Math.incrementExact(b)).limit(a).reduce(0,Integer::sum)
```
I love Java.
[Answer]
# APL, 3 bytes
```
+/⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRt/Ue9m4HMQyuAtKEBAA)
`+/` - sum (reduce `+`), `⍳` - range.
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 687 bytes
```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l 2 r.[a]Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Zoom Zoom:n.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Go to The Underground:n 1 r 1 r.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[z]Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.
```
[Try it online!](https://tio.run/##rZLBTsMwDIZfxeoDRGJw6m3jwJFJbBemHbLWTS0yu0oydd3Ld20X6GCoCMQhiWLl/2z/cdBHatsngSCwFB/guSgow7SGO7Ddcv2plpS9HSrQUGnvkQ06MEJsetWqRFjoHdqCfImuURfY13Dq34mTtMcms8IYIfGWctRamHX6jd5OIeZ5ToGEYW4tNj/WvuYcnXFy4DxmfRXZD1vKMfIZOZqjflHHaMtVxqEzN6BeagpZ2b@prGZITglQASzQGQDkodYdjc2f3LsfnLM3OXSiNqfttz1eRP/1@WObU7SrAVS3I8kfrrftw@wM)
Un-golfed with comments:
```
[ n = STDIN ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left 2nd right.
[ for (i=n;i>1;i--) { T+=i } ]
[a]
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 1st right 1st right.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 3rd left 2nd left.
Switch to plan "a".
[ print(T) ]
[z]
Go to Addition Alley: north 3rd left 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
```
It's 22.6% less bytes to loop than it is to use `x*(x+1)/2`
[Answer]
# Julia, 10 bytes
```
n->n*-~n/2
```
[Try it online!](https://tio.run/##yyrNyUw0/f8/zTZP1y5PS7cuT9/of0FRZl5JTp5GmoappuZ/AA)
### 11 bytes (works also on Julia 0.4)
```
n->sum(1:n)
```
[Try it online!](https://tio.run/##yyrNyUz8/z/NNk/Xrrg0V8PQKk/zf0FRZl5JTp5GmoappuZ/AA)
[Answer]
# [Starry](https://esolangs.org/wiki/Starry), ~~27~~ 22 bytes
*5 bytes saved thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles)!*
```
, + + ** + *.
```
[**Try it online!**](https://tio.run/##Ky5JLCqq/P9fR0EbCBW0tBQgAMhW0NL7/98UAA "Starry – Try It Online")
### Explanation
```
, Read number (n) from STDIN and push it to the stack
+ Duplicate top of the stack
+ Duplicate top of the stack
* Pop two numbers and push their product (n*n)
* Pop two numbers and push their sum (n+n*n)
+ Push 2
* Pop two numbers and push their division ((n+n*n)/2)
. Pop a number and print it to STDOUT
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
LO
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fx///fxMA "05AB1E – Try It Online")
# How it works
```
#input enters stack implicitly
L #pop a, push list [1 .. a]
O #sum of the list
#implicit output
```
# Gauss sum, 4 bytes
```
>¹*;
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f7tBOLev//00B "05AB1E – Try It Online")
# How it works
```
> #input + 1
¹* #get original input & multiply
; #divide by two
```
[Answer]
# [Check](https://github.com/ScratchMan544/check-lang), 5 bytes
```
:)*$p
```
Check isn't even a golfing language, yet it beats CJam!
[Try it online!](https://tio.run/##S85ITc7@/99KU0ul4P///6YA "Check – Try It Online")
## Explanation:
The input number is placed on the stack. `:` duplicates it to give `n, n`. It is then incremented with `)`, giving `n, n+1`. `*` multiplies the two together, and then `$` divides the result by 2. `p` prints the result and the program terminates.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
:s
```
[Try it online!](https://tio.run/##y00syfn/36r4/39DAwA "MATL – Try It Online")
Not happy smiley.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 7 bytes
```
d1+*2/p
```
OR
```
d2^+2/p
```
OR
```
dd*+2/p
```
[Try it online!](https://tio.run/##S0n@b2j8P8VQW8tIv@D/fwA "dc – Try It Online")
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 16 bytes (4×4=16 codels)
```
tabR Smm Amtqa
```
[Try Piet online!](https://piet.bubbler.one/#eJw9ikEKhDAQBP_S5w7MqAjmK9HDohEEjUL0tOzfd4Li0NBV9Hwx7lOED0GoLbVhNTBoxzt1EWWJeXubsCk8EDke8HDOgViXzVjFzizmEX7-rDkSSzqus2x9stc-VU_XT6u8IPj9AV-cJX8)
![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/76de552b548076b6a315241a12cfe551adb2dd76/images/CodeGolfSE/133109.svg)
### How it works
The code simply follows the border and then stops at the 3-cell L-shaped region. Basically uses the well-known formula, because setting up a loop here costs too many cells due to the necessary `roll` command.
![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/a03514b89d038fb77dcf99655db99a21bc5215d3/images/CodeGolfSE/133109-e.svg)
```
Command Stack
inN [n]
dup 1 + [n n+1]
* 2 / [n*(n+1)/2]
outN []
```
This layout saves two black cells over the following linear, more straightforward (pun intended) layout:
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 18 bytes (2×9=18 codels)
```
tabrsaqtM a mm
```
[Try Piet online!](https://piet.bubbler.one/#eJxVisEKhDAMRP9lzlNoVAT7K9XDUisIWoXunsR_31REMITMm5kcCNsY4by3lJbSsGJdqKEGMtBLx9e215VSDkSOOxyMMSCWeVUWq6Mu5gA3fZYciTntv2_p-qSvfapurW8V-4DF-QdRViU7)
![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/76de552b548076b6a315241a12cfe551adb2dd76/images/CodeGolfSE/133109-2.svg)
[Answer]
# Brainfuck, 24 Bytes.
I/O is handled as bytes.
```
,[[->+>+<<]>[-<+>]<-]>>.
```
## Explained
```
,[[->+>+<<]>[-<+>]<-]>>.
, # Read a byte from STDIN
[ ] # Main loop, counting down all values from n to 1
[->+>+<<] # Copy the i value to *i+1 and *i+2
>[-<+>] # Move *i+1 back to i
<- # Move back to i, lower it by one. Because *i+2 is never reset, each iteration adds the value of i to it.
>>. # Output the value of *i+2
```
[Answer]
# C++ (template metaprogramming), 80 bytes (?)
I'm not very sure if it is acceptable because you need to insert input into source, which seems to be permitted for languages like `///` only.
```
template<int N>struct s{enum{v=N+s<N-1>::v};};template<>struct s<1>{enum{v=1};};
```
Example:
```
#include <iostream>
int main()
{
std::cout<<s<10>::v;
return 0;
}
```
[Answer]
# [,,,](https://github.com/totallyhuman/commata), 6 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page)
```
:1+×2÷
```
## Explanation
```
:1+×2÷
: ### duplicate
1+ ### add 1
× ### multiply
2÷ ### divide by 2
```
If I implement range any time soon...
```
rΣ
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 13 bytes
```
seq -s+ $1|bc
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEG3WFtBxbAmKfn///@mAA "Bash – Try It Online")
`seq` generates a sequence. `seq 5` generates a sequence of numbers from 1 to 5 with a default increment of 1.
`seq` with the `-s` flag uses a string parameter to separate the numbers (the default separator is `\n`).
So `seq -s+ $1` generates numbers from 1 to `$1`, the first argument, using `+` as the separator. With an argument of `5`, this generates `1+2+3+4+5`.
Now this is piped into `bc` using `|bc` to calculate the result of this mathematical expression and that value it outputted.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 13 bytes
```
.+
$*
1
$`1
1
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEslwZDL8P9/UwA "Retina – Try It Online") Explanation: The first and last stages are just unary ⇔ decimal conversion. The middle stage replaces each `1` with the number of `1`s to its left plus another `1` for the `1` itself, thus counting from `1` to `n`, summing the values implicitly.
[Answer]
# [Trilangle](https://github.com/bbrk24/Trilangle), 9 bytes
*How appropriate that the triangular language is computing triangular numbers.*
```
?2')2!*:@
```
Try it on [the online interpreter](https://bbrk24.github.io/Trilangle/?i=5#%3F2%27)2!*%3A%40)!
Unwraps to this triangular grid:
```
?
2 '
) 2 !
* : @ .
```
Instructions are executed in this order:
* `?`: Read an integer from STDIN
* `2`: Duplicate the top of the stack
* `)`: Increment the top of the stack
* `*`: Multiply the two values off the top of the stack
* `'2`: Push the number 2 to the stack
* `:`: Divide the two values off the top of the stack
* `!`: Print the top of the stack as a decimal number
* `@`: Terminate program.
Effectively identical to this C program:
```
#include <stdio.h>
int main() {
// ?
int i; while(!scanf("%i", &i)) getchar();
// 2)*
i *= i + 1;
// '2:
i /= 2;
// !
printf("%d\n", i);
// @
return 0;
}
```
] |
[Question]
[
Your task is to display the letter "A" alone, without anything else, except any form of trailing newlines if you cannot avoid them, doing so in a program and/or snippet. Code that returns (instead of printing) is allowed.
Both the lowercase and uppercase versions of the letter "A" are acceptable (that is, unicode [U+0061](http://www.fileformat.info/info/unicode/char/0061/index.htm) or unicode [U+0041](http://www.fileformat.info/info/unicode/char/0041/index.htm). Other character encodings that aren't Unicode are allowed, but either way, the resulting output of your code must be the latin letter "A", and not any lookalikes or homoglyphs)
You must *not* use any of the below characters in your code, regardless of the character encoding that you pick:
* "*A*", whether uppercase or lowercase.
* "*U*", whether lowercase or uppercase.
* *X*, whether uppercase or lowercase.
* *+*
* *&*
* *#*
* *0*
* *1*
* *4*
* *5*
* *6*
* *7*
* *9*
Cheating, loopholes, etc, are not allowed.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution, in bytes, that follows all the rules, is the winner.
---
### Validity Checker
This Stack Snippet checks to make sure your code doesn't use the restricted characters. It might not work properly for some character encodings.
```
var t = prompt("Input your code.");
if (/[AaUuXx+𣤏]/.test(t)) {
alert("Contains a disallowed character!");
} else {
alert("No disallowed characters");
}
```
*This Stack Snippet that makes sure you don't have a disallowed character is also available on [JSFiddle](https://jsfiddle.net/or1rjega/1/).*
### Leaderboard
```
var QUESTION_ID=90349,OVERRIDE_USER=58717;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]
## Python 2, 14 bytes
```
print`3<3`[~3]
```
The expression `3<3` gives the Boolean `False`, and the backticks give its string representation `'False'`. From here, it remains to extract the letter `a`. Python is 0-indexed, so the `a` is at index `1`, which is a banned character. It can be expressed as `3-2`, but there's a shorter way. Python allows indexing from the back, with index `-1` for the last entry, `-2` for the one before it, and so on. We want index `-4`, but `4` is also a banned number. But, we can express it as `~3` using the bit-complement `~`, which gives `-n-1` for `~n`.
[Answer]
# Pluso, 1 byte
```
o
```
[Pluso Esolangs Page](https://esolangs.org/wiki/Pluso).
Pluso contains a single accumulator, that starts with the value 1. It uses two commands, **p** which increments the accumulator (mod 27), and **o** which prints the current value as an uppercase ASCII character, A-Z or space (where 1-26 represents A-Z respectively, and 0 represents space).
As the accumulator starts at 1, the command **o** with no prior **p** will output **A**.
[Answer]
# Pyth, 2 bytes
```
hG
```
Test it in the [Pyth Compiler](https://pyth.herokuapp.com/?code=hG&debug=0).
### How it works
```
G Yield the lowercase alphabet.
h Extract the first character.
```
[Answer]
# PHP, ~~9~~ 6 bytes
```
<?=O^_^Q;
```
For 9 bytes: Inspired by [@Ton Hospel's answer](https://codegolf.stackexchange.com/a/90371/58556). Plus, it has the added benefit of looking a bit like a Kaomoji. :-)
The 6 bytes improved version:
```
<?=~¾;
```
wherein ¾ has the hex code of 0xBE (it is important to save the file in [Latin-1 encoding](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), *not* UTF-8!).
[Answer]
## 05AB1E, ~~3~~ 2 bytes
```
Th
```
**Explanation**
```
T # push 10
h # convert to hex
```
[Try it online](http://05ab1e.tryitonline.net/#code=VGg&input=)
Saved 1 byte thanks to Adnan
[Answer]
# JavaScript (ES6), ~~17~~ ~~16~~ 14 bytes
*Saved two bytes thanks to Neil!*
```
_=>` ${-_}`[2]
```
Returns the second character of `NaN`, which is `a`.
This is the shortest I could come up with for `A`, ~~43~~ 42 bytes:
```
_=>`${[][`constr${`${!_}`[2]}ctor`]}`[-~8]
```
Who says being an obfuscator doesn't help with code golf? Not I!
## Explanations
The first one, in depth.
```
_=>` ${-_}`[2]
```
`-_` is NaN, because `_` is undefined. To get this as a string, one would need one of the following:
```
-_+""
`${-_}`
(-_).toString()
```
The last is too long, and the first uses `+`. So we use the second one. Now, the `a` is at index `1`. This isn't any good, because `1` is forbidden. However, being a template string, we can put a space in there to make it at index `2`, thus leaving us with `` ${-_}``.
---
The second one, in depth.
```
_=>`${[][`constr${`${!_}`[2]}ctor`]}`[-~8]
```
This one was a doozy.
```
_=>` `[-~8]
```
This is the 9th character of the inside template string, `-~8` being equal to 9. In this case, this template string is just for stringification. This is the inside equation being stringified, in between `${...}`:
```
[][`constr${`${!_}`[2]}ctor`]
```
Let's expand this a bit:
```
(new Array())[`constr${`${!_}`[2]}ctor`]
```
This gets the property ``constr${`${!""}`[2]}ctor`` from an empty array. This property is, of course, a template string, but it has some text around it. It's roughly equivalent to:
```
"constr" + `${!_}`[2] + "ctor"
```
The inside is in turn equivalent to:
```
(!_).toString()[2]
```
`!_` is `true` (because `_` is `undefined`, and `!undefined === true`), and stringified is `"true"`. We get the second character of it, `u`; we have to get it this way to avoid explicitly putting `u` in our code.
So, this inside bit is equivalent to:
```
"constr" + "u" + "ctor" === "constructor"
```
So we are getting the constructor of the Array, the `Array` function. I couldn't put this down explicitly because it contains the forbidden `A`. Now, stringifying the `Array` function yields `"function Array() { [native code] }"`.
Back to the original code:
```
_=>`${[][`constr${`${!_}`[2]}ctor`]}`[-~8]
```
This is equivalent to, as we've seen:
```
_=>Array.toString()[-~8]
```
Equivalent to:
```
_=>Array.toString()[9]
```
Finally equivalent to:
```
_=>"A"
```
[Answer]
# [Hexagony](http://github.com/mbuettner/hexagony), 4 bytes
Ayyy lmao? Quite golfy for a non-golfing language haha. Code:
```
B(;@
```
[Try it online!](http://hexagony.tryitonline.net/#code=IEIgKAo7IEAgLgogLiAu&input=)
A more readable form:
```
B (
; @ .
. .
```
This puts the ASCII value of the letter `B`, which is 66, on the current memory edge. It substracts it by one using `(` and prints it with `;`. After that, the program is terminated using `@`.
Obligatory path image:
[![enter image description here](https://i.stack.imgur.com/NAlZ2.png)](https://i.stack.imgur.com/NAlZ2.png)
[Answer]
# brainfuck, 16 bytes
```
-[-[---<]>>-]<-.
```
This is based on [Esolang's brainfuck algorithm for 159](https://esolangs.org/wiki/Brainfuck_constants#159).
[Try it online!](http://brainfuck.tryitonline.net/#code=LVstWy0tLTxdPj4tXTwtLg&input=)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØWḢ
```
[Try it online!](http://jelly.tryitonline.net/#code=w5hX4bii&input=)
### How it works
```
ØWḢ Main link. No arguments.
ØW Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
Ḣ Head; extract the first character.
```
---
# Jelly, 4 bytes
```
l-ṾṂ
```
[Try it online!](http://jelly.tryitonline.net/#code=bC3hub7huYI&input=)
### How it works
```
l-ṾṂ Main link. No arguments.
l- Take the logarithm of 0 with base -1. Yields (nan+infj).
Ṿ Uneval; yield the string representation, i.e., "nanıinf".
Ṃ Take the minimum, returning 'a'.
```
[Answer]
# CJam, 3 bytes
```
'@)
```
[Try it online!](http://cjam.tryitonline.net/#code=J0Ap&input=)
### How it works
```
'@ Push the character '@' on the stack.
) Increment its code point, yielding 'A'.
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 2 bytes
```
úF
```
[Try it online!](http://actually.tryitonline.net/#code=w7pG&input=)
Explanation:
```
úF
ú lowercase English alphabet
F first element
```
[Answer]
# Ruby, ~~15~~ 12 bytes
```
$><<to_s[-3]
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 1 byte
```
"
```
or
```
B
```
Everyone seemed to forget it existed...
[Answer]
# Java, 55 bytes
```
void f(){System.err.write('c'-2);System.err.println();}
```
Since the code has to print it, one of the two built-in writers are required. `System.out` is, well, out, because it contains `u`. `System.err` works, however.
The next hurdle is Java's handling of `char` and `int`. Since it is not allowed to cast to `char` because it contains `a`, and because `'c' - 2` gets promoted to `int`, another mechanism is required. `System.err` is a `PrintWriter`, which has a `write(char)` method but not `write(int)`. Putting `'c' - 2` in there forces it to `char` without a cast.
Finally, every time I ran the program the buffer for `System.err` would not flush like it is supposed to, and the program printed nothing. So I had to flush it manually. However, `System.err.flush()` is not allowed, so I called `println()` which implicitly flushes the underlying stream.
[Answer]
## Vim, 2 Keystrokes
`vim -u NONE` then run the following (`-u NONE` turns off customization)
```
i<up>
```
When vim is run in compatible mode the arrow keys are don't get interpreted properly. `<up>` gets interpreted `<esc>OA` which leave the following in insert mode. Which would leave (with a couple of trailing newlines)
```
A
```
`i` starts insert mode.
`<up>` exits insert mode, opens a line above and enters A into the buffer
Example of people encountering this in the wild. <https://stackoverflow.com/questions/6987317/while-moving-the-cursor-across-a-vim-process-open-in-a-tmux-session-every-now-a/6988748#6988748>
[Answer]
# Perl, ~~9~~ 8 bytes
xor is still allowed, but `say` isn't. So for 9 bytes:
```
print$/^K
```
However using output to STDERR gives 8 bytes:
```
die~"\x9e\xf5"
```
Replace `\x9e` and `\xf5` by their literal versions. Or generate the executable file using:
```
perl -e 'printf q(die~"%s"),~"a\n"' > a.pl
```
[Answer]
## [><>](http://esolangs.org/wiki/Fish), 6 bytes
```
'|;o-$
```
this creates a string of characters, bounces and creates it again in reverse, flips the top 2 stack items and subtracts:
'|' (124) minus ';' (59) is 'A' (65)
[Try it online](https://fishlanguage.com/playground/caqNePn7yk34hzWpY)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~7~~ 4 bytes
Saved 3 bytes thanks to *Teal pelican*
```
"-o.
```
[Try it online!](https://tio.run/##S8sszvj/X0k3X@//fwA "><> – Try It Online")
**Explanation**
```
"-o." # pushes the string "-o."
- # subtracts the charcode of o from the charcode of . (dot), 111-46=65
o # prints as character
. # tries to pop 2 coordinates to jump to, but as nothing is left on the stack
# the program ends in an error
```
[Answer]
# MATL, 5 bytes
```
YNVH)
```
[**Try it Online**](http://matl.tryitonline.net/#code=WU5WSCk&input=)
**Explanation**
```
YN % Creates a NaN value (not a number)
V % Convert it to a string
H) % Grab the second letter ('a')
% Implicitly display the result
```
---
My original answer was the straight forward approach using the pre-defined literal `lY2` which yields `'A'...'Z'` and then selecting the first element, `'A'`.
```
lY2l)
```
[Answer]
# Javascript, ~~18 bytes~~ ~~16 bytes~~ ~~12 bytes~~ 11 bytes
```
` ${!2}`[2]
```
Based on modified [jsfuck](http://www.jsfuck.com/) basics (had to figure out how to replace `+` with `-`).
### Ungolfed?
Well, at least a version with comments (note that this version will probably not run):
```
` ${ // whitespace to make "a" the third letter
!2 // returns false
}` // convert to string "false"
[2] // index the third letter in " false" (note the whitespace)
```
Old solution:
```
`${![]}`[-(-!![])]
```
[Answer]
## JavaScript (ES6), 21 bytes
```
_=>(8^2).toString(22)
```
I originally tried converting `false` to string to do this, but it took me 23 bytes at the time. I've since come up with a shorter way, which is this for 14 bytes:
```
_=>`!${!2}`[2]
```
I don't think you can get an uppercase `A` under the rules, since you need one of `String.fromCharCode` or `.toUpperCase()`, both of which contain `a`.
[Answer]
# Vim, ~~16 13 11~~ 10 keystrokes
Thanks to H Walters for saving two keys
Thanks to DJMcMayhem for saving another!
```
:h%<cr>jvyZZp
```
```
:h%<cr> #open help for percent
jvy #move down one char (to the letter "a"), visual mode the character, yank
ZZ #exit help for percent
p #put yanked character
```
[Answer]
## R, ~~27~~ 12 bytes
**EDIT :** New version, from an excellent idea from @Jarko Dubbeldam
```
LETTERS[T*T]
```
---
Quite a funny challenge !
Basically, this takes the `26th` element of the reversed vector containing the uppercase letters (`LETTERS`, which is a **R**'s built-in vector)
*Previous version**s*** (same number of bytes) *:*
```
L=LETTERS;rev(L)[length(L)]
rev((L=LETTERS))[length(L)]
```
[Answer]
# Brainfuck, ~~192~~ 19 bytes
```
----[>---<----]>--.
```
Thanks to @NinjaBearMonkey for helping me save hella bytes
~~`-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.`~~
~~I'm not good at Brainfuck so I'm sure theres a shorter solution, but it works by decrementing below 0, rolling the byte over, and keep going until it gets down to 'A', then it prints.~~
[Answer]
## Lua, 36 bytes
This one took me a while since MANY of the standard Lua functions are taken away from the rules (all of `math`, `string.char`, `string.match`, `pairs`, even `next`)
This takes advantage of the fact that Lua has a global `_VERSION` that usually starts with "Lua" (e.g., `Lua 5.1`, or similar for other versions), so unless this is run on a non-mainstream interpreter, the third character will be an 'a'
```
print(({_VERSION:find("..(.)")})[3])
```
The `{...}[3]` is to group the results of `find` which also includes the indices where it matched, and then return the third item which is the matched character (the `a`)
[Answer]
# C, (19?) 24 bytes
Thanks to Dennis:
```
f(){printf("%c",88-23);}
```
same length:
```
f(){printf("%c",'C'-2);}
```
which enables also lowercase:
```
f(){printf("%c",'c'-2);}
```
There is a **19 bytes** solution as a function modifying its parameter, which has a flaw:
```
g(int*p){*p='C'-2;}
//Usage:
main(){
int c; //cannot be char
g(&c);
printf("%c\n",c);
}
```
If `c` was declared `char`, `g` modifies the whole `int` so it smashes the stack which causes other values to be modified or the programm to abort with an error message. The only way to circumvent is to declare `int c;` in `main` and print with `"%c"`, but that feels like a loophole.
### older solutions
```
f(){printf("%c",'B'-2/2);} //26 bytes
f(i){i='B';printf("%c",--i);} //29 bytes
f(){int*i="B";int j[]={*i-(2/2),2-2};printf("%s",j);} //53 bytes
```
Just a function, since `main` is forbidden.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 4 bytes
```
@Ztw
```
[Try it online!](http://brachylog.tryitonline.net/#code=QFp0dw&input=)
### Explanation
```
@Z The string "zyxwvutsrqponmlkjihgfedcba"
tw Write the last element to STDOUT
```
[Answer]
# Vim, 6 bytes
`grNg??`
Challenge doesn't block `N`, and Vim has a ROT-13 feature. [FDinoff's answer](https://codegolf.stackexchange.com/a/91374/60590) is probably cooler, but this is ASCII and works everywhere.
[Answer]
# Haskell, 10 bytes
As a function (or rather a statement as no input is required)
```
f=pred 'B'
```
does the trick. [Try it on Ideone.](https://ideone.com/XmWsHQ)
A full program is impossible as this would need to contain a `main`.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix/), 5 bytes
```
o'@)^
```
[**Try in the online interpreter!**](http://ethproductions.github.io/cubix/?code=bydAKV4=&input=&speed=5)
Cubix is a language where (as the name implies) everything is executed on the faces of a cube. This code maps to the following cube:
```
o
' @ ) ^
.
```
The basic idea of this answer is to get a nearby character and increment it to what we need. In Cubix, `@` is the exit command needed to terminate the program, but also conveniently right under 'A' in the ASCII table. This means we can use the character once to mean two different things, saving bytes - here's the order in which the code is run:
* `'@` pushes the character code 64 to the stack.
* `)` increments the top of stack, yielding the desired character.
* `^` sends the instruction pointer north, wrapping around to...
* `o` outputs the top of stack, `A`.
* `@` terminates the program.
] |