text
stringlengths 180
608k
|
---|
[Question]
[
In this challenge, you'll take an answer as input, and print the answer before it. If the answer passed as input is the first answer, print your own submission's source. You'll be passed any answer in the chain up to and including your own answer, but none after it in the chain.
For example, if the first submission is `xyz`, the second is `ABCD`, and you submit `pQrSt` as a third answer, you should support the following input/output pairs:
```
xyz -> pQrSt
ABCD -> xyz
pQrSt -> ABCD
```
The first answer's only possible input is its own source code, in which case it should print its own source (i.e., it can be a cat program).
## Rules
* Inputs and outputs should be treated as bytestrings. While some or most answers may be valid UTF-8, you cannot assume all programs will be representable with Unicode
* If your language doesn't support raw binary I/O, you may use lists of numbers (representing bytes) with some consistent formatting (e.g., newline separated) for I/O in place of binary data
* Answers may be in any programming language
* Answers with a negative score (more downvotes than upvotes) are invalid, and someone else may submit a different answer in their place
* Answers must follow quine rules; no reading your own source code (stringifying functions is allowed here; you just can't read your source code directly from a file or similar) or accessing the internet or other external resouces
* No duplicate answers are allowed (same or different language)
* If a user answers multiple times in a row, only their first answer counts for scoring (so that sandbagging with the first for a low score on the second doesn't work)
## Scoring
Scoring is based on percentage increase in byte count. Whatever answer has the lowest percent increase in byte count over the previous submission wins (this may be negative). You may not golf or otherwise change your answer's code after posting it.
[Answer]
# 3: [Pip](https://github.com/dloscutoff/pip), 103 bytes
```
VST Y`h:[v:"x=>x"w:"\`I?L4≠[4Nȯ,Q".vX:2\"a=b=>(t='\w',b==t?'\v':b>a?'a='+a:t)\""VST Y".RPy]h@D:h@?a`
```
[Try it online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboFS7IKlpSVpuhY308OCQxQiEzKsosuslCps7SqUyq2UYhI87X1MHnUuiDbxO7FeJ1BJryzCyihGKdE2ydZOo8RWPaZcXSfJ1rbEXj2mTN0qyS7RXj3RVl070apEM0ZJCWykkl5QQGVshoOLVYaDfWICxDqYrRXRSkj2xoAtjgHaHKMUg253DNTyGGTrkezHdABQZQzE-Bg0R8C9DQA)
This is a pretty standard Pip quine structure. We store a code string in the variable `y` then evaluate it, and then construct all the pieces of code in an array and return the one at the index before the input.
[Answer]
# 2: [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
a=b=>(t='`I?L4≠[4Nȯ,Qx=>x`I?L4≠[4Nȯ,Qx=>x',b==t?'x=>x':b>a?'a='+a:t)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/RNsnWTqPEVj3B097H5FHngmgTvxPrdQIrbO0qsAip6yTZ2pbYq4PZVkl2ifbqibbq2olWJZr/k/PzivNzUvVy8tM10jSUQEqUNDW50ISJsweLxkRbJe00oPB/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# 1: [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 32 bytes
```
`I?L4≠[4Nȯ,Qx=>x`I?L4≠[4Nȯ,Qx=>x
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJEIiwiIiwiYEk/TDTiiaBbNE7IryxReD0+eGBJP0w04omgWzROyK8sUXg9PngiLCIiLCJgST9MNOKJoFs0TsivLFF4PT54YEk/TDTiiaBbNE7IryxReD0+eCJd)
Returns the nasty ahh string when given `x=>x`.
Returns `x=>x` when given the nasty ahh string.
[Answer]
# 4: [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 149 bytes
```
`q‛:Ė+»∧⋏≬¥Cİ}ż^₀:⅛°Ṅ.V=j₈@Yʁḃk∩Ŀʁ<Kf]ȧ∪?≥]ċ@Kȯ⇩Ż.ε⅛Ṡ↓√⁽∵0}İ∆3ẋ⟇n↳p°5≬≥U≠0rb½¨hˤ¢|c¦ẋQƒ∷ε.¼₅Jǔ(;Ḃ…%ɖbU≠r.₍p∞ėwn2¢ȧH↔$[Ṙ»kQ‛ȯ≠pτn8ȯ7Ẏ(n/ṫj)ṫ/J~ḟ‹i`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJEIiwiIiwiYHHigJs6xJYrwrviiKfii4/iiazCpUPEsH3FvF7igoA64oWbwrDhuYQuVj1q4oKIQFnKgeG4g2viiKnEv8qBPEtmXcin4oiqP+KJpV3Ei0BLyK/ih6nFuy7OteKFm+G5oOKGk+KImuKBveKItTB9xLDiiIYz4bqL4p+HbuKGs3DCsDXiiaziiaVV4omgMHJiwr3CqGjElsKkwqJ8Y8Km4bqLUcaS4oi3zrUuwrzigoVKx5QoO+G4guKApiXJlmJV4omgci7igo1w4oiexJd3bjLCosinSOKGlCRb4bmYwrtrUeKAm8iv4omgcM+EbjjIrzfhuo4obi/huatqKeG5qy9KfuG4n+KAuWlgOsSWIiwiIiwieD0+eCJd)
I'm quite proud of this one, and I spent way too long compressing it. The basic idea is to use a port of [RegPack](https://siorki.github.io/regPack.html) to efficiently compress redundancies in previous answers. Also, we're out of quote types and I hate backslashes, so I used a giant compressed integer. For future answers, [here](https://vyxal.pythonanywhere.com/?v=2#WyJEIiwiIiwiw7jin4figogrSHbhuKLiiJEiLCIiLCJgceKAmzrElivCu+KIp+KLj+KJrMKlQ8SwfcW8XuKCgDrihZvCsOG5hC5WPWrigohAWcqB4biDa+KIqcS/yoE8S2ZdyKfiiKo/4omlXcSLQEvIr+KHqcW7Ls614oWb4bmg4oaT4oia4oG94oi1MH3EsOKIhjPhuovin4du4oazcMKwNeKJrOKJpVXiiaAwcmLCvcKoaMSWwqTConxjwqbhuotRxpLiiLfOtS7CvOKChUrHlCg74biC4oCmJcmWYlXiiaByLuKCjXDiiJ7El3duMsKiyKdI4oaUJFvhuZjCu2tR4oCbyK/iiaBwz4RuOMivN+G6jihuL+G5q2op4bmrL0p+4bif4oC5aWA6xJYiXQ==)'s a program to convert from the Vyxal codepage to raw bytes (output as hexadecimal)
```
`q‛:Ė+ `:Ė # Standard eval quine glue: Uneval the string and add the code to eval it
»...» # Giant compressed integer
τ # Converted to custom string base
kQ‛ȯ≠p # Printable ascii + "ȯ≠" (to deal with previous Vyxal)
n8ȯ7Ẏ # "ijklmno"
( ) # For every item of that
n/ṫj # Split on that character, and join all but the last item by the last item (regpack bit)
ṫ/ # Split on the remaining trailing semicolon, converting into list
J # Prepend the existing source code
~ḟ # Find the index of the input in the list
‹i # Decrement that, and index back into the list
```
[Answer]
# 0: [JavaScript (Node.js)](https://nodejs.org), 4 bytes
```
x=>x
```
Just a cat program, to get us started
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q7if3J@XnF@TqpeTn66RpqGEkhMSVPzPwA "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Seeing that the current language for [Learn You a Lang for Great Good](https://codegolf.meta.stackexchange.com/a/24341/96039) is Piet, and that we don't seem to have a tips page for Piet yet, I decided to make one.
[Piet](https://github.com/cincodenada/bertnase_npiet) is a stack-based esoteric programming language in which the programs are meant to resemble abstract drawings.
What are some general tips for golfing in Piet?
As usual, please keep the tips somewhat specific to Piet, and one tip per answer.
[Answer]
# Compact encoding and tools
**Use [piet.bubbler.one](https://piet.bubbler.one) for editing Piet!**
The default scoring method for code golf is in bytes. It gives Piet a significant disadvantage, since every Piet program must be a valid image file (which can be in PNG, GIF, or PPM format, but all of them costs well over 10 bytes per pixel). Also, TIO has `npiet` as the Piet interpreter ([Try it online!](https://tio.run/##K8hMLfkPAroZAA)), but it is unwieldy to use because it expects the hexdump of an image file.
In this regard, DLosc has made a tool called [ascii-piet](https://github.com/dloscutoff/ascii-piet), which gives a printable-ASCII-based roughly-1-byte-per-pixel encoding for valid Piet programs.
The color table for ascii-piet looks like this:
| | Red | Yellow | Green | Cyan | Blue | Magenta |
| --- | --- | --- | --- | --- | --- | --- |
| **Light** | t | v | r | s | q | u |
| **Medium** | l | n | j | k | i | m |
| **Dark** | d | f | b | c | a | e |
| | **Black** | (space) | **White** | ? | | |
Using only these chars gives a plain 2D-lang-like scoring, where blanks at the end of each line can be omitted and a newline counts as 1 byte. In addition, you can change the last character of each line to uppercase (`_` for white) and omit all newlines.
As an example, the program

can be written like an ordinary 2D language as
```
ttttli
auqasj
```
which can be written in one line as
```
ttttlIauqasj
```
which has the score of 12 bytes = 12 codels.
Self-contained TIO setup: [Try it online!](https://tio.run/##rVltc9u4Ef6uX4HSMxcqlmnLucu0His3TqIknnNsj51rZup6OJAISbBJkAFAv7R3/evpLkBSAKlITlN9SEhwsXj2fReeULX4OqWaHB6SZ@Ozd8/IK0LVlPOdgjMdFY@9rb/slkruTrjYLR71Ihcvej2eFbnURD2qAeH5gFA5L6hUrDeTeUbOj09IRXGc0Tnr9T78Po4/Hl3@RkZkbzIcDnuvT47e2Le9vT14@31cvQx77y/G41P7NtzrXYzf2k1A9vnD8adxw6J3cvz@w6fT8eWlyxrZvT26aHjD6@nZxcejk5ojLJiNNVd4B4p4fHbisLEbewmbESamecJiwe5TLpgKjXJiVE7/oEfgZxfMR9i8/BypIuXabuobSssqaWivrs3yLJcElwgXLjPLHX98Zr4vF/C3RT6VUhC9YAS5pgRsiC9MJCQH2HS6qLnqnHCtCIjY4sC@lPyOpkxo70NKlY6nCyqRMeDMZRIiq6ud4XV/DeVPI/IfR5Wtw45nBl9G1S3ReX5rodd781Ij7EICXDpJGZFUzNmgxUMt@EyDMGRCp7dWstYObwMqzkN4SF7s@2rsSrE9Ii9/9mhquyEJqGO6kKG3pb@S2hgxokUBFrHqOwD9kW2Pnd0qmUZbBkF0k3MRehz61g0TtsEN8TG@53rR0ADUIGg8zIBvPAypPQezssGOf4qg42gLJhnoPi/TRDwD5TNCxSNpzuGi8jwDm9wxqXguWkwmDFAwIOSKzEox1UBCaJIo3Jt5xNNcaC7KpS1bvrhUnAPeeiBx/K8txlEVKHoBoQIoRK4xaKqAMbEyZxAnBVUKxNALmZfzRYsJIF@gnyXe@grlb48MrIaMpYptQrQKDXoGoKmjuMVB5DsgrhPIYJmE0No2xLrfE9HKsFHkH64i@@C06Bc9e@aF9VY0Oew3IhDkRrSkHNjNl54hWZbfVadXTt49PJJKS16EeETl7dZJdR5zrB@Osw@sxmLF/8UG6GmTXLHROwrKreJgi3ykt@CtpbReCjmYSZp2vJWLAlIOlUu/NSqGTxUb1Ouk1vgSAfjgmpLQqzyyQrY0uElTsdIJkzIMji7fHB/v1AefI1uuggEBC7rcBiSYPGooBUF/NaP2yR2Cfq8JYUFqs2VO@myrpyvtmszzRGk/o3M0@oeYZ8mPSvT0oms8CBwuAQwjqD4PISoZKfrfqrzuxgXj8wWqYWkal2aT7LPgXOZzSTOCHosx/m8H0J9k8lgv2IP@DAad8mR@syB0dz73NtmgUP2gNvc5TTBfQwNmVWTCUxV0Cs/hJEXrV1tWaPMKH6L0plQ6dI4EZyTBN3VmWxnL9DtaG7cydXuctXkff4uSkZGb/utG0@9SUElwrPJp/f6x3TgY1iNie05AWb2bxrXbQmyRzwuIJJN9rX6THEvlNM@YlQ0g7CZU3pI7KjkVrUzehml71k4zs6QYEexyu0DA95hQXHNjynBvQIZ/2281KGmblT3tKcz2f/llEzOj1o28ANUKblxJyIcjMsnzNESN/0RgAGjTzCWDbOZRmaGhTTdJjXs4ZDho@FRyPkE4DrorA@J6ZRz6ZAbHUwgRSKtztpFSt4eAok46c4BjpqYIMmYYXLx/DXXBj0M39vvNvgjqWUI1Dd3I3iKXU@gLbMXDbaQsMOlQMqNTDW4NnQNkfygEy7r6xKz@ngmoHBrrveVskoxtaJBN4NbqtclcMpo2GdrN18/bqAxlk5K9DN2htapExUiGi2G4PGfgcurjm6JZkbKR1fzp@OhifPnJa86Bke1NClPAYO9DKMpsQAzD0V7VfsByDMtwckXQv9o/uK5VasV6RfaWSvU24FMkTeatc@5e4MGoiCyUh4ckNA0C9E9ivkSQlFmx7P45zrTm6X7BwRc4jEFYzTo73d3QEDqC8gH5q@kCD0jQkE7SHPIcxFfD54of8O3hy2uXG1rFGUXqpH@DWdFMbCZHvYRk0PeTRrN3e9RMRg6kCe4wrCbIyoC5ujm42d6/NkgdoI5MNdOqvP28119FBZuRRXUoNsaTPprvxT45BHnxn@H@S9PSkyAKVldsr3p7MFefWTfY1mSwMnzZMjyS1s1y1SgXOSaZOxZDUIWeMWEcQPdfLjdhDR9AAMcFoW0HQf5OIUuNpcwhtjNQjh3zTCabM0kg2VFoFXFWEaTllMCyguMG93Mq56qeTvGDXRmQGXjhSD2qyBKCKD3AFceCZiyOzRQaxxnlIo6rWbS@X8Lxu36OjuS8zGDkOTdf6sawpozAVWJakYTBDrbXwc5OlZkALC1TPRoOiH4s2MjV42CdPRcsLUbBWanN9CDc1Ic5dg48hJcE1zHLmKbQDoyCN2dvxyfx5fE/xsEGMR6sGBD58EDNFD0KFGRyFmtZbjjPB68wfzQuyIXSjJrhU9J7G9SbwNxZMFWh@FFA7AEGSMABwZJRez0wwWsh1KsZkdYGWlBUjTbUMutXG9DDQeCHAFqgV46CXx23OM0FewLwy7yUU2b82YS4P9bZCXM96LA68QALUkLM9Smg56K/AT0o5ofhv4W0zYVVdSPD@el7vIz7HujGf6zaYWeNPC@QsXIiVkbmP5Simc5mNV20od14kwugMO2G0dKKERogAPrAuxqquVtr19c@qCC/2viHOYY9AL36TPpr7nS@zYYcGru@Wg2vMudT8bUt54KsWD0dZYeZgQpsXgVr27YnalfLR/90kyxz6HvDll4xJc26k4N3GzGLMFBCR7qHKSv0Ovne4L2lAdbE2BqbNgWx19WducQWOanEvQe8kHXuOHjgoB3AvZXwq6rHhSuG7VTX3HnVWP1br1bgdIwC2d2F/tZEaTMHQDOC6d8mW2Jvvogq2JTPOASUTQGrXLUTp12N24RuYhXTiVEW6KoqNY5XVa0jo9j/8jx6je/HZ455sX9X9I6FS1KoOX6YLztepyEGwmjO9B12NWH/fwu6rqdWWwbk2f2zb/nrLLqXXLOwgrUxEH1Cn@j/ovd2Pf9eNcAQCRZwfAd4UnNC5TZ1EJgT/SG8Nl9HgS0brroet8HWhJrprQa22qBIFguOvMvis/rwKurgezQpZzMmm@PHZ@9600WWJ2T7ofV3z573V9E/SLTrfYcpDp92sP5EhZh/nf2aaZ3y7PbLly/wL7@55UpdanmnSsY0y3iaifRG3Cr4fcVze7uglF1ksitMevD5/Rc) (Protip: you can pass `-t` to npiet to get step-by-step information.)
If you use this setup and scoring, you should specify that ascii-piet is used for the encoding, like this:
```
# [Piet](https://github.com/cincodenada/bertnase_npiet) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 12 bytes
```
---
[MasterPiets](https://gabriellesc.github.io/piet/) has a nice color chooser interface and a step-by-step debugger (click "Debugger" on the right side to open it). It has a few drawbacks though: you lose your work when you resize the grid, and some users have reported that Export to PNG doesn't work.
[Answer]
# Basic routing and halting
Routing and halting are two of the hardest walls when starting to write nontrivial Piet programs. The pointer moves in the unit of connected areas of the same color, and it chooses the next cell using the following variables:
* DP: Direction pointer. One of right, down, left, or up. Initially right.
* CC: Codel Chooser. One of left or right. Initially left.
Given the current area, DP, and CC, the next cell to move into is chosen as follows (hopefully more intuitive than the official doc):
* Imagine you are facing in the direction of DP.
* In the area you're stepping on, choose the cell(s) that are farthest from you.
* If there are multiple, choose the rightmost or leftmost cell out of them (in your view) based on CC.
* Walk to the chosen cell and move front once.
For example, if your current area looks like `x` in the following and DP=right and CC=left,
```
h g
fxxxa
exx
xxb
cd
```
Then the next cell is `a`. The cells marked `a` to `h` are the cells you might enter next, depending on the current DP and CC.
If the next cell is black, or out of bounds, then the pointer tries the next combination of DP and CC - first swap CC, then rotate DP once clockwise, repeat. If all 8 combinations are tried and fails, it halts. (See the previous example again: the cells marked `a` to `h` are the cells that are tried in order.) Note that, by the spec, invalid commands (stack underflow and division by zero) are simply ignored and execution continues, so the *only* way to halt a program is via a trapped region.
So how to construct such a trapped region? The simplest ones I found are:
```
x
...abcx
x
```
and
```
...abcx
xx
```
Can you see why each of these works? (It is impossible to trap in a 1-row program, or using areas of size 1 or 2.) And since these are the only trapping configuration of size 3, you will likely use one of these in every halting golfed program.
The turn-right-when-blocked behavior can be used to route in interesting ways. Some examples I found are:
```
# 2-row infinite loop
abc...xyz
zyx...abc
# 3-row finite loop with tail
# use conditional DP+ on `de` to turn right to move towards exit
# also can be used for a linear program; put `Push 1` on `cd` and `DP+` on `de`
abcabc z
exyzxayz
dcbacb z
# 2-row with small loops; use conditional DP+ on `de`
abcde...bcde...az
pool pool zz
# more rows with few black cells to eventually lead to infinite loop
# note that seemingly unused cells can be used to push constants
>>>>>>>v
......v
>>>>v .v
^<<<<<<<
```
### A note on DP+ and CC+ commands (looping and if-else)
There is a command that can change the direction of movement (essentially DP). It is called "pointer" (at hue +3, darkness +1) in the official doc, but I like to call it `DP+`, as it directly adds the top value to the current DP (modulo 4). If you have a condition that evaluates to 0 or 1, you can use DP+ on that to turn right once based on a condition. This creates a branch in your program, and you can mainly use it to create a conditional loop. (If you somehow need to turn left instead, applying `*3` to the condition is the shortest method I can think of, which costs 4 more cells.)
There is CC+ ("switch" in official doc, hue +3, darkness +2) command too, which adds the top value to CC (modulo 2). This can be useful in creating if-else constructs: if you place CC+ at `ab` in the following code
```
...abcdexyz...
buvwx
```
then the pointer follows the `cde` path or the `uvw` path based on the resulting CC. Then the `x` block acts as the merging point: since CC=right path is blocked, CC is toggled and the execution continues through `xyz...` with CC=left in both cases.
[Answer]
# If-else-bounce-merge
If you need to create control flow that splits and merges quickly, you might want to use this construction:
```
..xAbcd..Z
...Afgh..Zw
```
where `xA` is CC+ and `bcd..` and `fgh..` are two if-else paths. `w` must be surrounded by three blacks (or outside of the program). It is easiest to use when there's nothing to do for `bcd..`, in which case you can just fill that row with white codels. Otherwise, you need to check what `bcd..` does when run backwards.
[An example](https://codegolf.stackexchange.com/a/249510/78410) where it prints 10 (newline) based on a condition.
The bounce part can be used without an if-else too, since it has an effect of fixing CC after it bounces back. [primo's Hello World](https://codegolf.stackexchange.com/a/67601/78410) uses it for the 3-row layout to minimize wasted codels.
[Answer]
# Detecting if the stack is empty
If you ever run into a scenario where you need to check whether or not the stack is empty, you can simply run the following instructions:
```
dup, dup, minus, not
```
If the stack is empty, all these instructions will fall through and nothing will happen. But if the stack is non-empty, this code will essentially push a `1` on top of the pre-existing stack, without changing anything else.
You can then have a DP+ or CC+ instruction afterwards to branch your code based on whether or not the stack is empty. This can be particularly helpful in things like printing out the entire stack from the top to the bottom, where you can simply construct a loop with the check shown in this tip to exit the loop if the stack is empty.
Here's an example of that [here](https://piet.bubbler.one/#eJydi8EKwkAMRP9lzrOwqbU0-yulB6krFKoWVk_ivxvBurYiSEMgM5N5N3TnfURoGs-KUvB9pH6tZ8mCyi3rHD7zlgtI9KNAqbLcTFKtuwR1DurXzvIMm11N63r6Z-kPviVSHBHgnAMx9EfT4m3MxdQhHHZDikR_Gq8X--H-ALl9V60). In this code, the stack is initialized as `6 5 4 3 5 2`. Then, it passes through the white codels (which are just there for clarity) and enter into the looping construct. Here, the check is ran (`dup, dup, minus, not`), with a `DP+` following it. If the stack is empty, then it simply passes through to the right and ends up in the halting construct (again, white codels added just for clarity). But if the stack is non-empty, there will be a `1` on the top of the stack, which will result in the DP pointing downwards after `DP+` is ran. The loop then continues with printing the value on the top of the stack, and then turning back up and to the right at the front of the loop to run the check again. This process is repeated until the stack is empty, which will then cause the IP to enter into the halting construct as stated previously. With the stack initialized as `6 5 4 3 5 2`, the code will result in `253456` being printed out (basically, the contents of the stack from the top to the bottom).
[Answer]
# A2-escape pattern
I wrote two answers today: [factorial](https://codegolf.stackexchange.com/a/258899/78410), [number to binary](https://codegolf.stackexchange.com/a/258900/78410).
Factorial:

Number to binary:

In both programs, `A1->A2` is a `DP+`. It is a no-op at start of a program (because the stack is empty), and is only meaningful after one iteration of the loop. When DP+ triggers, the IP escapes the loop through the 2nd column, which minimizes the wasted space on row C (in ascii-piet scoring). You can then do more stuff starting at C2 or D2 facing down.
This construct is useful when you can write the first part of the program in a single pure loop (no initialization before loop). The condition is easily met in Number to Binary because the only data needed is the input number, and it is OK to put `inN` in the loop (it is no-op when the input is exhausted).
It is a little harder in the case of Factorial, as you'd normally push 1 at the bottom which will be the "current product" in the loop. Fortunately with the current logic, the `DP+` is somewhat in the middle:
```
Initialize: 1 inN
Loop: dup 1 - 3 1 roll dup 1 > ! DP+ * 2 1 roll
^^^^^^^^^^^^^^
```
When the marked commands are put at the start of the program, `DP+ *` are no-ops, `2 1` push the two numbers, and `roll` is again a no-op (because there aren't two numbers to roll when 2 and 1 are removed). This leaves a 1 at the top of the stack (we can safely ignore the 2 below), which connects nicely to the logical start of the loop.
] |
[Question]
[
Left in [sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/20752#20752) for at least 3 days.
I want to verify if this inequality is true:
for \$n\geq4\$, if \$a\_1,a\_2,a\_3,\dots,a\_n\in R\_+\cup\{0\}\$ and \$\sum\_{i=1}^na\_i=1\$, then \$a\_1a\_2+a\_2a\_3+a\_3a\_4+\dots+a\_{n-1}a\_n+a\_na\_1\leq\frac{1}{4}\$.
## Challenge
Write a piece of program which takes an integer `n` as input. It does the following:
1. Generate a random array `a` which consists of `n` non-negative reals. The sum of all elements should be 1.
>
> By saying *random*, I mean, every array satisfiying the requirements in 2 should have a non-zero probability of occurrence. It don't need to be uniform. See [this related post](https://codegolf.meta.stackexchange.com/questions/17563/are-non-uniform-random-distributions-allowed).
>
>
>
2. Calculate `a[0]a[1]+a[1]a[2]+a[2]a[3]+...+a[n-2]a[n-1]+a[n-1]a[0]`.
3. Output the sum and the array `a`.
>
> For I/O forms see [this post](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
>
>
>
## Rules
(Sorry for the late edit...) All numbers should be rounded to **at least** \$10^{-4}\$.
Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) should be forbidden.
## Example
The following code is an ungolfed Python code for this challenge, using library `numpy`. (For discussion about using libraries, see [This Link](https://codegolf.meta.stackexchange.com/questions/188/using-libraries-in-solutions).)
```
import numpy as np
def inequality(n):
if n < 4:
raise Exception
a = np.random.rand(n)
sum_a = 0
for i in range(n):
sum_a += a[i]
for i in range(n):
a[i] /= sum_a
sum_prod = 0
for i in range(n):
sum_prod += a[i % n] * a[(i + 1) % n]
print(a)
return sum_prod, a
```
## Tip
You could assume that input `n` is a positive integer greater than 3.
---
Your score is the *bytes* in your code. The one with the least score wins.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 21 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(+/⊢×1∘⌽)⎕←(⊢÷+/)?⎕⍴0
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=09DWf9S16PB0w0cdMx717NV81Df1UdsEDZDYdm19TXsQv3eLAQA&f=AwA&i=S@My5eJK4zI0AAA&r=tio&l=apl-dyalog&m=tradfn&n=f)
A tradfn submission which prints the list and returns the sum.
```
⎕⍴0 ⍝ create a vector with input-many 0's
? ⍝ for each 0, get a random number between 0 and 1
⊢÷ ⍝ divide each number by
+/ ⍝ the sum of all numbers
⎕← ⍝ print the resulting vector
⊢× ⍝ multiply the vector element-wise
1∘⌽ ⍝ with the vector rotated to the left by 1
+/ ⍝ take the sum of all products
```
If appending the sum to the list is fine as output, this could be 20 bytes: [`x,+/x×1⌽x←(⊢÷+/)?⎕⍴0`](https://razetime.github.io/APLgolf/?h=AwA&c=q9DR1q84PN3wUc/eikdtEzQedS06vF1bX9P@Ud/UR71bDAA&f=AwA&i=S@My5eJK4zI0AAA&r=tio&l=apl-dyalog&m=tradfn&n=f)
[Answer]
# [R](https://www.r-project.org/), ~~49~~ 45 bytes
```
a=rexp(scan());a=a/sum(a);a;a%*%c(a[-1],a[1])
```
[Try it online!](https://tio.run/##K/r/P9G2KLWiQKM4OTFPQ1PTOtE2Ub@4NFcjEci0TlTVUk3WSIzWNYzVSYw2jNX8b/ofAA "R – Try It Online")
-4 bytes by Robin Ryder
[Answer]
# JavaScript (ES6), ~~89~~ 88 bytes
Returns `[ array, sum ]`.
```
f=(n,a=[],t=s=0)=>n?f(n-1,[...a,v=Math.random()],t+v):[a.map(k=>(s+=v/t*(v=k),v/t)),s/t]
```
[Try it online!](https://tio.run/##Vco9DoMwDEDhvSexizEgdapkeoKeIGKwgPQHcBCJcv2UtdvTp/fVrHE8PnuqLUxzKV7ASMUNlCRKi9Lbw4PVHTlmVsry1PTmQ20KG@C5VRnvTnnTHRbpIVaSm3SFLAvSWYgUmzSUMVgM68xreIGHG@LlX7oWsfwA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
a = [], // a[] = array
t = // t = sum of non-normalized values
s = 0 // s = sum of a[i] * a[(i + 1) mod n] / t
) => //
n ? // if n is not equal to 0:
f( // do a recursive call:
n - 1, // decrement n
[ ...a, // pass a new array with all previous elements of a[]
v = Math.random() ], // followed by a new random value v in [0,1)
t + v // add v to t
) // end of recursive call
: // else:
[ // build the answer array:
a.map(k => // for each value k in a[]:
( s += // add to s:
v / t // the previous normalized value v / t,
* (v = k), // multiplied by k (and update v to k)
v / t // yield the normalized value
) //
), // end of map()
s / t // also return the normalized sum
] // end of answer array
```
[Answer]
# [Julia](http://julialang.org/), 46 bytes
```
n->(a=rand(n);a/=sum(a))=>a[2:end]'*a[1:end-1]
```
[Try it online!](https://tio.run/##yyrNyUw0rPifZvs/T9dOI9G2KDEvRSNP0zpR37a4NFcjUVPT1i4x2sgqNS8lVl0rMdoQxNI1jP1fUJSZV5KTp5GmYaqp@R8A "Julia 1.0 – Try It Online")
returns `array => sum`
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
{##2,#}&@@#.#|#&[#/Tr@#&@RandomReal[1,#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v1pZ2UhHuVbNwUFZT7lGWS1aWT@kyEFZzSEoMS8lPzcoNTEn2lBHOTZW7b9LfnRAUWZeSXSmrl2aQ2asTnWmjomOWa2OoUHsfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
FN⊞υ‽φ≧∕Συυ⊞υΣEυ×ι§υ⊕κI⮌υ
```
[Try it online!](https://tio.run/##NYzBCsIwEETvfkWOG4hQwZunopceLFL9gdis7WKzLUm2@PcxFZzTMDNv@tGGfrZTzq85KGh4kdSKf2IArdVN4ghiVGfZzR4OVVVpfdpd7VLHSAN3NIwJLrSSQ6Pu4kG0UVImf3LLynyzD/IYgYyqU8MOP1vWcB/QIyd08NY/FTYQJzjbmKDDFUPEcluKnI95v05f "Charcoal – Try It Online") Like the 05AB1E answer, I generate `n` random numbers between `0` and `999`, then scale them so their sum is 1. A larger range could be obtained at the cost of one or two bytes. Also, it's unclear whether the sum has to be first; printing it last would save two bytes. Explanation:
```
FN
```
Repeat `n` times...
```
⊞υ‽φ
```
... push a random integer to the predefined empty list.
```
≧∕Συυ
```
Divide the list by its sum.
```
⊞υΣEυ×ι§υ⊕κ
```
Multiply each element by its neighbour and push the sum to the list.
```
I⮌υ
```
Print the list in reverse so that the sum is first.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 11 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
ă]_Σ/∙╫m*Σ
```
Outputs the array and sum concatenated to one another.
[Try it online.](https://tio.run/##ASUA2v9tYXRoZ29sZv//w4TGkl1fzqMv4oiZ4pWrbSrOo///NAo2CjEw)
**Explanation:**
```
Ä # Loop the (implicit) input amount of times,
# using a single character as inner code-block:
ƒ # Push a random float in the range [0,1]
] # Wrap all values on the stack into a list
_ # Duplicate this list
Σ # Take the sum of it
/ # Divide all values in the list by this sum
# (so we now have a list of random values summing to 1)
∙ # Triplicate this list
╫ # Rotate the top copy once towards the left
m* # Multiply the top two lists position-wise together
Σ # Take the sum of that list
# (after which the entire stack joined together is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](https://numpy.org/doc/stable/), 75 bytes
```
from numpy import*
def f(n):x=random.rand(n);x/=sum(x);return x,x@roll(x,1)
```
[Try it online!](https://tio.run/##FcgxCoAwDADA3Vd0TEQU0UkR/IqgRcEkJbaQvr7qdHAhx1N4KMWrkONEIbuLgmisq/3wzgPjZItuvAu1P1/M1i1PIjCc9YhJ2Vljq8p9gzU9lqAXR6g9jIjlBQ "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 30 27 25 bytes
-2 to thanks to [ovs's rotate idea](https://codegolf.stackexchange.com/a/219163/15469)
```
[:(;1#.]*1|.])@(%+/)?@$&0
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600rA2V9WK1DGv0YjUdNFS19TXtHVTUDP5rcvk56SlA5Y209GNidar1kFVwcaUmZ@QrpCmY/AcA "J – Try It Online")
* `$&0` Duplicate 0 "input" times.
* `?@` And "roll" for each (`?0` produces a random number between 0 and 1).
* `[:...(%+/)` Divide each by sum of all.
* `(;1#.]*1|.])` To that boxed list append `;` the sum of `1#.` the list `]` times `*` the list rotated once to the left `1|.]`.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~124~~ 121 bytes
Saved a byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved 3 bytes thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis)!!!
```
def f(n):l=[random()for i in[0]*n];l=[e/sum(l)for e in l];return l,sum(a*b for a,b in zip(l,l[1:]+l))
from random import*
```
[Try it online!](https://tio.run/##JczBCgIhEIDhe08xxxlbqKjTLj2JeHBZJUFHmdzD9vKmdfvhg78c9ZX53trmPHhkmuNTi@UtJySfBQIE1lej2Cxd3OW9J4w/cV0gmkVc3aXXNMiqFQbaaR38CQXjFPVtNudIdPKSE/z3EFLJUlUrErii8vggal8 "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~15~~ ~~14~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄Ý.rI£DO/ÐÀ*O‚
```
Outputs as a pair `[array, sum]`.
-2 bytes thanks to *@Neil*.
-1 byte by changing two explicit prints with enclose/overlap builtins `=Ćü*O,` to something similar as [my MathGolf answer](https://codegolf.stackexchange.com/a/219166/52210) with pair and implicit print `ÐÀ*O‚`
+2 bytes so duplicated items are possible and +1 byte to maximize the amount of floats possible
[Try it online](https://tio.run/##ASUA2v9vc2FiaWX//@KChMOdSdC4LnJJwqNETy/DkMOAKk/igJr//zEw) (but uses `[0,1000]` instead of `[0,9876543210]` to speed things up a bit).
**Explanation:**
```
žmÝ # Push a list in the range [0,9876543210]
Iи # Repeat it the input amount of times
# (so we can potentially get duplicated items)
.r # Randomly shuffle this list
I£ # Only leave the first input amount of values
D # Duplicate this list
O # Sum them together
/ # Divide all values by this sum
# (so we now have a list of random values summing to 1)
Ð # Triplicate this list
À # Rotate the top copy once towards the left
* # Multiply the top two lists position-wise together
O # Sum this list
‚ # Pair the list together with this sum
# (after which this pair is output implicitly as result)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
l&rts/ttlYS*s
```
[Try it online!](https://tio.run/##y00syfn/P0etqKRYv6QkJzJYq/j/fxMA)
**Explanation**
```
% Implicitly retrieve input (N) as an integer
l % Push the literal 1 to the stack
&r % Create an N x 1 array of random floats
t % Duplicate this array
s % Sum the elements of this array
/ % And perform element-wise division of the original array by this sum
% to get the array, A
tt % Duplicate A (twice)
lYS % Circularly shift A by 1 element
* % Perform element-wise multiplication with A
s % Compute the sum
% Implicitly display A and the sum of the products
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~83 82 72~~ 71 bytes
```
->n{k=(1..n).map{rand};p=k[~-s=0]/z=k.sum;[k.map{|x|s+=p*x/z;p=x/z},s]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOttWw1BPL09TLzexoLooMS@l1rrANju6TrfY1iBWv8o2W6@4NNc6OhssX1NRU6xtW6BVoV8FVAUka3WKY2v/FyikRZvG/gcA "Ruby – Try It Online")
-4,-1,-6 from ASCII-only!
-4, shortening it further.
-1 more byte from ASCII-only.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
No built-in for random floats, so half the code is that!
```
2ṗ⁹XHCḅ.)÷S$µṙ1ḋƊ,
```
A monadic Link accepting an integer, `n`, which yields a list containing a non-negative float (the sum of products) and the generated list of non-negative floats of length `n` which sums to `1`.
**[Try it online!](https://tio.run/##ASgA1/9qZWxsef//MuG5lzlYSEPhuIUuKcO3UyTCteG5mTHhuIvGiiz///80 "Jelly – Try It Online")** (Note that `⁹` (\$256\$) has been replaced with `9` (\$9\$) for speed - generating all \$2^{256}\$ lists of bits would take a while. Using a number as big as \$256\$ is not necessary, it's just terse.)
### How?
(Bug fixed above, will update this section later.)
Note: Uses 256 random bits to generate a random float in \$[0,1]\$.
```
2ṗ⁹XHCḅ.)µ÷Sṙ1ḋƊ, - Link: n
) - for each:
2 - 2
⁹ - 256
ṗ - (256) Cartesian product (2 implicitly -> [1,2])
X - pick one at random e.g. [1,2,2,1, ... ,1,2]
H - halve [0.5,1,1,0.5, ... ,0.5,1]
C - complement [0.5,0,0,0.5, ... ,0.5,0]
. - a half 0.5
ḅ - convert (list) from base (0.5) a float in [0,1]
µ - start a new monadic chain (call that x)
S - sum sum(x)
÷ - divide normalised(x)
Ɗ - last three links as a monad: (call that Y=[y1,y2,...,yn])
- one 1
ṙ - rotate left by (1) [y2,...,yn,y1]
ḋ - dot product (with Y) y1.y2+y2.y3+...+yn.y1
, - pair [y1.y2+y2.y3+...+yn.y1, Y]
```
] |
[Question]
[
We define \$a(n)\$ as the 1-indexed position of \$n\$ in the sequence of positive integers with the same binary weight, i.e. the same number of 1's in their binary representation. This is [A263017](https://oeis.org/A263017).
Given a positive integer \$n\$, your task is to determine how many positive integers \$k\$ satisfy:
$$k-a(k)=n$$
For instance, \$n=6\$ can be expressed as:
* \$n=7-a(7)=7-1\$ (\$7\$ being the 1st integer with 3 bits set)
* \$n=12-a(12)=12-6\$ (\$12\$ being the 6th integer with 2 bits set)
There's no other \$k\$ such that \$k-a(k)=6\$. So the expected answer is \$2\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
### Test cases
```
Input Output
1 1
6 2
7 0
25 4
43 0
62 1
103 5
1000 0
1012 6
2000 1
3705 7
4377 8
```
Or as lists:
```
Input : [1, 6, 7, 25, 43, 62, 103, 1000, 1012, 2000, 3705, 4377]
Output: [1, 2, 0, 4, 0, 1, 5, 0, 6, 1, 7, 8]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
t4*:tB!s&=Rs-=s
```
[Try it online!](https://tio.run/##y00syfn/v8REy6rESbFYzTaoWNe2@P9/E2NzcwA) Or [verify all test cases](https://tio.run/##y00syfmf8L/ERMuqxEmxWM02qFjXtvi/S8h/Qy4zLnMuI1MuE2MuMyMuQwNjIDYwABKGRlxGIJaxuQFI1twcAA).
This makes use of the following result:
## Claim
\$a(n) \le 3n/4\$ for \$n \geq 3\$.
Here is a [graphical illustration](https://matl.suever.net/?code=%3AtB%21s%26%3DRsXG1IZG3%2a4%2FXG&inputs=50&version=22.2.1). The bound is quite loose, but it is sufficient to establish that only a *finite* number of values of \$k\$ need to be tested for a given \$n\$ (more on that in “How the code works”).
**Proof**
The sequence \$a(n)\$ ([A263017](https://oeis.org/A263017)) is the amount of numbers in the set \$\{1,2,\ldots,n\}\$ that have the same binary weight as \$n\$. The binary expansion of \$n\$ has \$b \leq \log\_2 n + 1\$ digits, with a leading 1. Let \$w\$ be the binary weight of \$n\$. Clearly \$w \in \{0,\ldots,b\}\$.
The number of unique permutations of the binary expansion of \$n\$, not necessarily with a leading 1, is \${b\choose w}\$. \$a(n)\$ will be at most equal to this value. It can be less, because some of the permutations may produce a number exceeding \$n\$. Thus,
$$
a(n) \leq {b\choose w}.
$$
For \$b\$ even, the [bound](https://en.wikipedia.org/wiki/Central_binomial_coefficient)
$$
{2m \choose m} \leq \frac{4^m}{\sqrt{3m+1}} \text{ for all } m \geq 1
$$
and the fact that \${b\choose w} \leq {b\choose b/2}\$ imply that
$$
{b \choose w} \leq \frac{2^b}{\sqrt{\frac{3b+2}{2}}}.
$$
For \$b\$ not necessarily even, the bound holds with \$b\$ replaced by \$b+1\$:
$$
{b \choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}}.
$$
Since \$b \leq \log\_2 n + 1\$,
$$
a(n) \leq {b\choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}} \leq \frac{4n}{\sqrt{ 3/2 \cdot \log\_2 n + 4}}.
$$
This is less than \$3n/4\$ for \$n \geq 80478\$, because
$$
\sqrt{3/2 \cdot \log\_2 80478 + 4}\ = 5.3333348 > 16/3.
$$
For \$n = 3, \ldots, 80477 \$, direct computation of \$a(n)\$ shows that \$a(n) \leq 3n/4\$. Therefore \$a(n) \leq 3n/4\$ for \$n \geq 3\$.
## How the code works
The above result implies that
$$
k-a(k) \geq k / 4.
$$
for all \$k \geq 3\$. Thus, given \$n\$, to compute the number of positive integers \$k\$ that satisfy
$$
k-a(k)\ = n
$$
it suffices to test the latter equality for \$k = 1, \ldots, 4n\$.
Consider input `1` as an example.
```
t4* % Implicit input: n. Duplicate. Multiply by 4
% STACK: 1, 4
: % Range. Gives [1 2 ... 4*n]. This is the vector of k values
% STACK: 1, [1 2 3 4]
tB % Duplicate. Binary expansion. Gives a binary matrix, where each row
% corresponds to a value of k
% STACK: 1, [1 2 3 4], [0 0 1;
0 1 0;
0 1 1;
1 0 0]
!s % Tranpose. Sum of each column. This gives the binary weights
% STACK: 1, [1 2 3 4], [1 1 2 1]
&= % Matrix of pair-wise equality comparisons
% STACK: 1, [1 2 3 4], [1 1 0 1;
1 1 0 1;
0 0 1 0;
1 1 0 1]
R % Upper triangular part. This sets elements below the diagonal to 0
% STACK: 1, [1 2 3 4], [1 1 0 1;
0 1 0 1;
0 0 1 0;
0 0 0 1]
s % Sum of each column. For each column k, this gives the amount of
% number up to k with the same weight as k; that is, a(k). Note that
% the condition "up to k" corresponds to having taken the upper
% triangular part of the matrix
% STACK: 1, [1 2 3 4], [1 2 1 3]
- % Subtract, element-wise. This gives k-a(k)
% STACK: 1, [0 0 2 1]
= % Equality comparison, element-wise. This compares n with each
% value k-a(k)
% STACK: [0 0 0 1]
s % Sum. Implicit display
% STACK: 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~98~~ 96 bytes
Saved 2 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!!
```
lambda n:sum(n==sum(bin(i).count('1')!=bin(k).count('1')for i in range(1,k))for k in range(5*n))
```
[Try it online!](https://tio.run/##TZBBbsMgEEX3PsU0WQDVtDLGDlUkcpGEhZPaCXKCLYwXjeWzu0AWLYvP/MefkYbhx996K9ZWndZ7/Th/12D34/SgVql4nY2lhn1e@sl6Sjhhbyqi7j9qewcGjAVX22tDOXYsse6PVe@WsdUpOpHTVMjyQhBeJReEZTHtsYn5pxloBkeOsEOQCEWFUIrgCgSeiyh5HpUHoHFbJCtknnJSanx1h9fAy6TBVqkII/WWp7lfOmP7DMIZQUFLPUtmcCZs1W5mv8DHAeZxgdkdm/AZetmwlYvdLw "Python 3 – Try It Online")
Brute force and very slow.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~106~~ \$\cdots\$ ~~100~~ 96 bytes
Saved 5 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved ~~1~~ 5 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)!!!
Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
b(n){n=n?1+b(n&n-1):0;}k;i;s;p;f(n){for(p=0,k=5*n;i=k--;p+=n==s)for(s=0;--i;)s+=b(i)!=b(k);s=p;}
```
[Try it online!](https://tio.run/##TU/RbsIwDHznK7xKTAlNpLSllOFlfAjlAUILbbVQNX1AQv32zskmtEi5nH1nxzbyasw8n5nlT6vtPomJvluZ8J3CqcMGHfZYe7m@D6zXSnQ6X1lsdCcl9rG2WjvuNacVStkgd7E@s4a/EXYcne5xmr9PjWUcnovGjjAejqDhmQjYCCgEpLmAdUZRKiBRmQelPCaUSAPPChVMRTFh6FG9epCHDOuAFOaBbAKn3lvym9tpWIG5Vaajmqh8VGn5@DB0s@ilDnfn/qmX8rE1pNJmwPyHLYkK6fmEJEWI49avA3S8OpBas/HQHjmGZD9QumbR8gLyCwiXrrSRAG8RMAhfoWmL9gj7v9F2v0P4BtNimn8A "C (gcc) – Try It Online")
Port of my [Python answer](https://codegolf.stackexchange.com/a/204766/9481), ~~much~~ a bit faster.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 41 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
{1⊥⍵=i-+⌿(⊢×∘.≤⍨∘⍳∘≢)∘.=⍨+⌿2∘⊥⍣¯1⊢i←⍳4×⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUdfSR71bbTN1tR/17Nd41LXo8PRHHTP0HnUuedS7Ash61LsZRHYu0gQJ2wIFQQqNQGIgnYsPrQcasSjzUdsEoEoToOberbX/08DcvkddzY961zzq3XJovfGjtomP@qYGBzkDyRAPz@D/aYdWKBgqmCmYKxiZKpgYK5gZKRgaGAOxgQGQMDRSMAKxjM0NQLLm5gA "APL (Dyalog Unicode) – Try It Online") (Assumes ⎕IO ← 1)
This is a direct translation of [Luis Mendo's really good answer](https://codegolf.stackexchange.com/a/204774/75323) so go give that one an upvote if you haven't.
**How it works** (reading the submission from right to left):
* `i←⍳4×⍵` multiply the input ⍵ by 4, create a range from 1 to 4⍵ and save it in the variable i for later;
* `2∘⊥⍣¯1` create a matrix of binary conversions (one col per number);
* `+⌿` column-wise sum;
* `∘.=⍨` matrix of pair-wise equality comparisons;
* `(⊢×∘.≤⍨∘⍳∘≢)` from which we extract the upper triangular part;
* `+⌿` column-wise sum again;
* `i-` the original range 1 ... 4⍵ minus the new vector;
* `⍵=` compared to the input number;
* `1⊥` and summed up.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 70 bytes
```
n=>f=(i=g=i=>+i&&1+g(i&i-1))=>i>5*n?0:(i-(g[j=g(i)]=-~g[j])==n)+f(-~i)
```
[Try it online!](https://tio.run/##JYrLDoIwEEX3/QpWZMZapQiYmEzd8RM@kEBphmAxYFz66whyN@e@2vJTjtXAr7fyfW2nnCZPpiFgcsRkJIehlg44ZKURybBJN/4cnYAVuEtL84Q3Ut/Z35DIo2xAfRmnqvdj39ld1zt4CB0s0iL7MxbHPyMRpwsTkRzWnMXrT0dLkYrHbrCvrqws7O/XWgYSzhTg/um2BZkcCgREnH4 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
```
n=>[...Array(n*5)].reduce(s=>s+=++i-(g[j=g(i)]=-~g[j])==n,i=0,g=i=>i&&1+g(i&i-1))
```
[Try it online!](https://tio.run/##JU7LDoIwELz3KziR1kJpkYeXxfgdiIHwaEqwEFATL/46LrCX2ZnZ2Uxffaqlns308u3YtGsHq4UsF0Lc5rn6UnuKWSHmtnnXLV0gWzhwbnyq8x40NawA/4d7wQCsZ0B6GgxkxnUVR9s1vmJsrUe7jEMrhlHTkihnG0WSHUOS7ihJGG8Ykeh88CQ87pTchBhRyk1XUqGTkHDnipxTickUcym@upAS605DhX2Dx73hDqdXcFjw1F6HXf4 "JavaScript (Node.js) – Try It Online")
Thank Arnauld for -3 bytes
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 71 bytes
```
i,k;f(n){int C[99]={};for(i=k=0;i++/n/5<=k;)k+=i-++C[*C+=2-ffs(i)]==n;}
```
[Try it online!](https://tio.run/##TU/BboMwDL33KyykSqEJaoBSytJsBz4DOFQpWQNaOgEHJMS3MyebqkXKi@33/GKr6FOpbTOsF5rYcDF2grIqikYuq9DPgRjZSy4MpUd7zK6yF2FPpYkoLatDSWUSaT0SEzZSWrFuXzdjSQjLzvlMVQMSlpjBmUHOIMkYnFLMEgYxTx1w7jDGQuLjNOdelOer8B7tywM1KDh5xDTzwdnH6H1BvXrchgOoR6t67AnquU3quVB40@DFDs9x/Mfe6/mikMVVgbgPOyS5wOcKcSKA0s6tA3gcOyCryVR1TSh88XvAsibB/g7ROyDux9oGDJyEwcBch8QtugY@/kZ7@x3CGay7dfsB "C (gcc) – Try It Online")
WTF is happening?
# [C (gcc)](https://gcc.gnu.org/), 72 bytes mainly by dingledooper
```
i,k;f(n){int C[99]={};for(i=k=0;i++<5*n;)k+=i-++C[*C+=2-ffs(i)]==n;i=k;}
```
[Try it online!](https://tio.run/##TU/BboMwDL33KyykSoEEKUApZWm2A58BHKqUrAGNToEDEuLbmZNN1SLlxfZ7frFV/KnUvhs2CE3GcDXjDFVdlq1cN6Gflhg5SC4Mpdc8GkU4UGliSqs6qqhMY60nYsJWylGgUGz7182MJIT14IzmugUJa8LgzKBgkOYMThlmKYOEZw44d5hgIfVxVnAvKopNeI/u5YEaFJw8Ypr74Oxj9L6gXj1uNgL16NSAPUGzdGmzlApvFrxY@5ymf@y9WS4KWdwViPuwR5ILfK6QpAIo7d06gMexFllN5rpvQ@GL3xbLmgTHO8TvgHicmjFg4CQMLHMdErfoW/j4G@3tdwhnsB22/Qc "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 79 bytes
```
k;f(n){int C[99]={};for(k=0;k++<5*n;)*C+=k-++C[__builtin_popcount(k)]==n;k=*C;}
```
[Try it online!](https://tio.run/##TU9ha4MwEP3eX3EIhWhSiFprXZrtgz9DpbSprpotFmuhIP52d8lGWSAvd/fevdypzadSy6JFQ4w/tWaEvMiySk6zaPqBaMmFpvSQBEb4QU6l3lCaF8fj@dF@ja053vqb6h9mJNqvpDRCyyAX8/J9ag3xYVpZx7GoQMIUMtgxSBlECYNtjFnEIOSxBc4thliIXByn3InSdBbOo355oAYFW4eYJi7YuRi996hX19MQgLrWSmOPVz7rqHxmCm/svdihv9//sZfyuVfI4tJA7Icdklzgc4AwEkBpZ9cBPJYdkG3IWHSVL1zxNmC5Id76Apt3QFzfS@MxsBIGA7MdErfoKvj4G@3tdwhrMK/m5Qc "C (gcc) – Try It Online")
Port of my Javascript answer
] |
[Question]
[
## Task
Given two positive integers \$m,n\$, imagine a chessboard of size \$m \times n\$. A chess queen is on the upper-left corner. In how many ways can it reach the lower-right corner, by moving only right, down, or diagonally right-down (possibly moving many steps at once, because it's a queen)?
The resulting 2D sequence is [A132439](http://oeis.org/A132439).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
m n result
1 1 1
1 2 1
1 3 2
1 4 4
1 5 8
2 2 3
2 3 7
2 4 17
2 5 40
3 3 22
3 4 60
3 5 158
4 4 188
4 5 543
5 5 1712
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~94~~ ~~91~~ ~~64~~ 54 bytes
```
1!1=1;m!n=sum[m!(n-x)+(m-x)!n+(m-x)!(n-x)|x<-[1..m+n]]
```
[Try it online!](https://tio.run/##TYuxCoMwFEV/5WZLkAgZuljtXrBTxxCK0IJa31NMgg7@e2pLB5d7OAdu2/j3axiSFApFgSsH6MsByQhTmTMJrnwkS0KyXlUmaV/Bf/7atpbamjynjJ1L1HSMCtRMtwemGO5hrhk28jLOTw/r23GB7ESvsKFHqfH9npzbtTto@gA "Haskell – Try It Online")
Initially a boring port of the comment on OEIS
-27 from some tricks off dingledooper's answer
-10 from Christian Sievers
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
@xnor's idea which is 2 bytes smaller than the one below. Returns `True` for `1 1`.
```
f=lambda m,n:sum(f(m-i,n)+f(m,n-i)+f(m-i,n-i)for i in range(1,n|m))or m>0<n
```
[Try it online!](https://tio.run/##HY3NDoIwEITvfYq92cZibAsXIr6KqRGkCV0aKCEmvnsdPEzmm/1NnzzObEsZusnH58tT1NyuW5SDjFXQrM4AzVX4w1EBDvNCgQLT4vndS6P5G5VCMd6vNy77GKaeTCtwjJg6ij7JwFljfn8ETluW6rKmKWR5opNSgtKC/vETC0oVQ0YYspCDaqgRFtkiW2SL7MAO7MA1vIY31PwA "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~79~~ 77 bytes
```
f=lambda m,n:(m==n==1)+sum(f(m-i,n)+f(m,n-i)+f(m-i,n-i)for i in range(1,n+m))
```
[Try it online!](https://tio.run/##HY3NCoMwEITveYq9mWAsJNGLkGcplmpdMGvQiPTp7djDsN/sz2z@lnkVf11TXIb0eg@UrPQ6xSgxOlPvR9KTTg1bMTXASsN/uDvAad2IiYW2QT6jdlbqZMx1zryM5HqFOBKKlIasWYrF3vlkyUfR5rHnhYuuqDJGUd4wv3/hAAmOnHLkoQC1UKc8vIf38B4@gAM4gFvUFrWj7gc "Python 2 – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 36 bytes
```
{(x~1 1)+/o'x-/:{|/'~x,'-/'x}#1_+!x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxFzEsKgzAUheF5VpHSQhQr8eZRJZl0HyK1k0BpQRAHEatrb+7NoLOPw88JbiviARzKSk4i1tJtXymOeBW1FHE/w6M6xZ2x4Joq3Nnitku/HrMLPPpxevtiDM/Xx0e/+rkcdrb06WvgnANR/amRimiQhmiRXaLKrSZS2xKxhUxsTZOoKVCKiMEtrykAi2cGV+gy02oN/tpEaEGxH40JO4w=)
`!x` odometer
`+` transpose
`1_` drop the first
`{` `}#` filter
`|/'~x,'-/'x` either element or their difference is 0
`x-/:` subtract each right
`o'` recur each
`+/` sum
`(x~1 1)` does `x` match `1 1`? use as initial value for the sum
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 92 bytes
Boring port of the Haskell answer.
```
f(1,1)->1;f(M,N)->lists:sum([f(M,N-X)+f(M-X,N)+f(M-X,N-X)||X<-lists:seq(1,max(M,N)),M*N>0]).
```
[Try it online!](https://tio.run/##bYwxC8IwEEb3/oobc5oTO7jUkr2Fdi6UIkESCTRVk4oO@e/1KAoO3vR43/FMGPV0IRPPwd3mJVusyGWOpPKjFY1smUYX51jEhxf9qqjDLQN1vH6BXUpdSZ9fc@eK16@1gLLZtGo/4G7x2k3ihEAqAz53LZ7BzUb0PVhRSagRUoIaSoLf0gFhYF/981x9Aw "Erlang (escript) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
NθFNFθ⊞υ∨¬υΣΦυ∨∨⁼ι÷μθ⁼κ﹪μθ⁼⁻ικ⁻÷μθ﹪μθI⊟υ
```
[Try it online!](https://tio.run/##XY67DoMwDEV3vsKjI6UjE2MfEgMUqV@QAhUReZAQ8/tpFJBaYXnxOdeW@0n43goVY20WCi3p9@jRsar4WA/4DxmDzByDjtYJicPTY2sDEuPwIo0PqUIK7iL13ZFQK0oOtQk3uclhRM3BsZQ/3MyhsQMpe4ifaaShvDsntg@nK@fVXFXReWkCXsUasLNLei7BGEso42VTXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input the number of columns.
```
FN
```
Loop over the rows.
```
Fθ
```
Loop over each column.
```
⊞υ∨¬υ
```
The first result is always `1`...
```
ΣΦυ∨∨⁼ι÷μθ⁼κ﹪μθ⁼⁻ικ⁻÷μθ﹪μθ
```
... otherwise find the existing results that are a Queen's move away, take the total, and push that to the list of results. The list therefore simulates a matrix, requiring its index to be divided or taken modulo the number of columns as appropriate to compare with the loop variables.
```
I⊟υ
```
Output the last result calculated.
[Answer]
# [J](http://jsoftware.com/), 60 50 bytes
```
_2{(],1#.]#~(#:#)(0=*/*-/)@:-"1(#:i.@#))^:(*/@[)&1
```
[Try it online!](https://tio.run/##Vc7NCsIwDADgu08RVnDr2LqmP24UBgPBkyevoh7EoV58AMFXr3ONkAWSw0f@njFT@Qh9gBwq0BCmrBVsD/tdvJh3capQqJP4FCIIWei@bMq6kUOoM5zooQYh5TkUZTMc5RqjXN2u9xcg9DBOFWGOJRqOhtBydISOY0foOdoZzXJnS7jYiX91/JAm9Pyl9JOl@YQbTcjH0XeknmGX0KXWhN5ZQt7ZYjrlfxq/ "J – Try It Online")
] |
[Question]
[
The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one.
The challenge is to compute the average Levenshtein distance between two independent and uniformly random chosen binary strings of length `n` each. Your output must be exact but can be given in any easy to understand human readable form.
# Examples:
These are the answer for `n` up to `24`.
```
1 1/2
2 1
3 47/32
4 243/128
5 1179/512
6 2755/1024
7 12561/4096
8 56261/16384
9 124329/32768
10 2175407/524288
11 589839/131072
12 40664257/8388608
13 174219279/33554432
14 742795299/134217728
15 1576845897/268435456
16 13340661075/2147483648
17 14062798725/2147483648
18 59125997473/8589934592
19 123976260203/17179869184
20 259354089603/34359738368
21 8662782598909/1099511627776
22 72199426617073/8796093022208
23 150173613383989/17592186044416
24 1247439983177201/140737488355328
```
# Score
Your score is the highest value of ùëõ you can reach. Where humanly possible, I will run your code on my Linux machine for 10 minutes and then kill the job to get the score.
# Notes
As always this should be a competition *per* language. I will maintain a leaderboard that shows the best score for each language used in an answer. ~~I will also give a bounty of 50 points for the first answer to get to `n = 20`.~~
My CPU is an Intel(R) Xeon(R) CPU X5460.
# Leaderboard
* `n = 18` in **Python+numba** by Shamis (timing pending...).
* `n = 19` in **Java** by Bob Genom (278 seconds).
* `n = 19` in **C** by ngn (257 seconds).
* `n = 21` in **Rust** by Anders Kaseorg (297 seconds). 150 point bonus awarded.
[Answer]
# Rust, score ≈ 22
This uses a dynamic programming approach (I’ve added [an explanation here](https://cs.stackexchange.com/a/120267/34042)) whose running time seems to scale as approximately \$\tilde O(2^{1.5n})\$, rather than the \$\tilde O(2^{2n})\$ of a brute-force search. On my Ryzen 7 1800X (8 cores/16 threads), it gets through \$1 \le n \le 21\$ in 1.7 minutes, \$1 \le n \le 22\$ in 5.1 minutes.
Now using SIMD for the inner loop.
### `src/main.rs`
```
use fxhash::FxBuildHasher;
use itertools::izip;
use rayon::prelude::*;
use std::arch::x86_64::*;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::mem;
use typed_arena::Arena;
#[global_allocator]
static ALLOC: mimallocator::Mimalloc = mimallocator::Mimalloc;
type Distance = i8;
type Count = u32;
type Total = u64;
#[derive(Debug)]
struct Distances(__m128i);
impl PartialEq for Distances {
fn eq(&self, other: &Distances) -> bool {
unsafe {
let x = _mm_xor_si128(self.0, other.0);
_mm_testz_si128(x, x) != 0
}
}
}
impl Eq for Distances {}
impl Hash for Distances {
fn hash<H: Hasher>(&self, state: &mut H) {
unsafe {
_mm_extract_epi64(self.0, 0).hash(state);
_mm_extract_epi64(self.0, 1).hash(state);
}
}
}
fn main() {
let splat0 = unsafe { _mm_set1_epi8(0) };
let splat1 = unsafe { _mm_set1_epi8(1) };
let splatff = unsafe { _mm_set1_epi8(!0) };
let splat7f = unsafe { _mm_set1_epi8(0x7f) };
let seq = unsafe { _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) };
let grow0 = unsafe {
_mm_set_epi8(
-0x80, 0, 0x20, 0, 0x8, 0, 0x2, 0, 0, 0x40, 0, 0x10, 0, 0x4, 0, 0x1,
)
};
let grow1 = unsafe {
_mm_set_epi8(
0, 0x40, 0, 0x10, 0, 0x4, 0, 0x1, -0x80, 0, 0x20, 0, 0x8, 0, 0x2, 0,
)
};
for n in 1 as Distance.. {
if n > 31
|| (n as Count).leading_zeros() < n as u32
|| (n as Total).leading_zeros() < 2 * n as u32
{
break;
}
let total: Total = (0u32..1 << (n - 1))
.into_par_iter()
.map(|a| {
let mut a_sym = a.reverse_bits();
a_sym ^= (a_sym >> 31).wrapping_neg();
a_sym >>= 32 - n as usize;
if a_sym < a {
return 0;
}
let arena = Arena::<Distances>::new();
let stride = (n as usize + 16) / 16 * 16;
let idx = |i: Distance, j: Distance| i as usize + stride * j as usize;
let both = |[x, y]: [Distance; 2]| x.max(y);
let mut worst = vec![[stride as Distance; 2]; idx(0, n + 1)];
for j in 0..=n {
worst[idx(n, j)] = [n - j; 2];
}
for i in (0..n).rev() {
worst[idx(i, n)] = [n - i; 2];
let good = (a >> i & 1) as usize;
let bad = good ^ 1;
for j in (0..n).rev() {
worst[idx(i, j)][good] = both(worst[idx(i + 1, j + 1)]);
worst[idx(i, j)][bad] = 1 + worst[idx(i + 1, j)][bad]
.min(both(worst[idx(i, j + 1)]))
.min(both(worst[idx(i + 1, j + 1)]));
}
}
let worst: &[Distances] = arena.alloc_extend(
worst
.into_iter()
.map(both)
.collect::<Box<[Distance]>>()
.chunks(16)
.map(|chunk| {
Distances(unsafe {
_mm_loadu_si128(chunk as *const [i8] as *const __m128i)
})
}),
);
let mut states: HashMap<&[Distances], Count, FxBuildHasher> = HashMap::default();
let mut new_states = HashMap::default();
states.insert(
arena.alloc_extend(
(0..n + 1)
.step_by(16)
.map(|i| Distances(unsafe { _mm_add_epi8(_mm_set1_epi8(i), seq) })),
),
1,
);
let bvs: Vec<_> = [a, !a]
.iter()
.map(|b| {
arena.alloc_extend((0..n + 1).step_by(16).map(|i| unsafe {
let x = _mm_set1_epi16(((b << 1) >> i) as i16);
Distances(_mm_xor_si128(
_mm_cmpeq_epi8(
_mm_or_si128(
_mm_and_si128(x, grow0),
_mm_and_si128(_mm_alignr_epi8(x, x, 1), grow1),
),
splat0,
),
splatff,
))
}))
})
.collect();
for j in 1..=n {
new_states.reserve(2 * states.len());
let worst_slice = &worst[idx(0, j) / 16..idx(0, j + 1) / 16];
for (state, count) in states.drain() {
for bv in &bvs {
let mut x = j;
let mut y = n.into();
let mut bound = n;
let new_state: &mut [Distances] =
arena.alloc_extend(izip!(&**bv, state, worst_slice).map(
|(&Distances(bc), &Distances(yc), &Distances(wc))| unsafe {
let o = _mm_min_epi8(
_mm_add_epi8(yc, splat1),
_mm_sub_epi8(
_mm_insert_epi8(_mm_slli_si128(yc, 1), y, 0),
bc,
),
);
y = _mm_extract_epi8(yc, 15);
let o = _mm_sub_epi8(o, seq);
let o = _mm_min_epi8(o, _mm_set1_epi8(x));
let o = _mm_sub_epi8(splat7f, o);
let o = _mm_max_epu8(o, _mm_slli_si128(o, 1));
let o = _mm_max_epu8(o, _mm_slli_si128(o, 2));
let o = _mm_max_epu8(o, _mm_slli_si128(o, 4));
let o = _mm_max_epu8(o, _mm_slli_si128(o, 8));
let o = _mm_sub_epi8(splat7f, o);
x = _mm_extract_epi8(o, 15) as i8 + 16;
let o = _mm_add_epi8(o, seq);
let z = _mm_add_epi8(o, wc);
let z = _mm_min_epi8(z, _mm_srli_si128(z, 1));
let z = _mm_min_epi8(z, _mm_srli_si128(z, 2));
let z = _mm_min_epi8(z, _mm_srli_si128(z, 4));
let z = _mm_min_epi8(z, _mm_srli_si128(z, 8));
bound = bound.min(_mm_extract_epi8(z, 0) as i8);
Distances(o)
},
));
let bound = unsafe { _mm_set1_epi8(bound) };
for (i, Distances(x)) in (0..).step_by(16).zip(&mut *new_state) {
*x = unsafe {
_mm_min_epi8(
*x,
_mm_sub_epi8(
bound,
_mm_abs_epi8(_mm_add_epi8(_mm_set1_epi8(i - j), seq)),
),
)
};
}
*new_states.entry(&*new_state).or_insert(0) += count;
}
}
mem::swap(&mut states, &mut new_states);
}
let control = unsafe { _mm_insert_epi8(splatff, (n % 16).into(), 0) };
Total::from(
states
.into_iter()
.map(|(state, count)| unsafe {
count
* _mm_extract_epi8(
_mm_shuffle_epi8(state[n as usize / 16].0, control),
0,
) as Count
})
.sum::<Count>(),
) * if a_sym == a { 1 } else { 2 }
})
.sum();
let shift = total.trailing_zeros();
println!(
"{} {}/{}",
n,
total >> shift,
(1 as Total) << (2 * n as u32 - 1 - shift),
);
}
}
```
### `Cargo.toml`
```
[package]
name = "levenshtein"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
edition = "2018"
[profile.release]
lto = true
codegen-units = 1
[dependencies]
fxhash = "0.2.1"
itertools = "0.8.2"
mimallocator = "0.1.3"
rayon = "1.3.0"
typed-arena = "2.0.0"
```
### Running
```
RUSTFLAGS='-C target-cpu=native' cargo build --release
target/release/levenshtein
```
### Output
(With cumulative timing data prepended by [`ts -s %.s`](https://manpages.debian.org/buster/moreutils/ts.1.en.html).)
```
0.000008 1 1/2
0.000150 2 1/1
0.000219 3 47/32
0.000282 4 243/128
0.000344 5 1179/512
0.000413 6 2755/1024
0.000476 7 12561/4096
0.000538 8 56261/16384
0.000598 9 124329/32768
0.000660 10 2175407/524288
0.000721 11 589839/131072
0.000782 12 40664257/8388608
0.000843 13 174219279/33554432
0.006964 14 742795299/134217728
0.068070 15 1576845897/268435456
0.310136 16 13340661075/2147483648
1.062122 17 14062798725/2147483648
3.586745 18 59125997473/8589934592
11.265840 19 123976260203/17179869184
33.691822 20 259354089603/34359738368
101.514674 21 8662782598909/1099511627776
307.427106 22 72199426617073/8796093022208
956.299101 23 150173613383989/17592186044416
3077.477731 24 1247439983177201/140737488355328
10276.205241 25 5173410986415247/562949953421312
34550.754308 26 5356540527479769/562949953421312
```
[Static `core2` build for Anush](https://www.dropbox.com/s/9govtvstvq6bst0/levenshtein?dl=0)
[Answer]
# Java, score ≈ 19
My solution is a recursive approach. It is still \$\tilde O(2^{2n})\$ of a brute-force search. In other words: if n increase by 1 runtime increase by a factor of 4 (even when using multi-threading).
Which is obviously not enough to compare with Anders Kaseorg's code.
I observed and used some symmetries to squeeze out some (linear) factors.
```
import java.util.stream.IntStream;
// version 5.1
public class AvgLD51_MT {
public static void main(String[] argv) {
long t0=System.currentTimeMillis();
for (int n=1; ;n++) {
int VP = (1 << n) - 1; // 1m;
int VN = 0; // 0m;
int max=1<<(n-1);
final int N=n;
long sum=IntStream.range(0, max).mapToLong(p-> {
int rp = Integer.reverse(p)>>>(32-N);
int np = VP & ~rp;
if (p <= rp && p <= np) {
if (p == rp || p == np) {
return 2*buildX(N, p, 0, 1, VP, VN);
} else {
return 4*buildX(N, p, 0, 1, VP, VN);
}
}
return 0;
}).parallel().sum();
long gcd=gcd(sum, (1L<<(2*n)));
System.out.printf("%f %d %d %d/%d\n", (double)(System.currentTimeMillis()-t0)/(1000), n, sum, sum/gcd, (1L<<(2*n))/gcd);
sum*=2;
}
}
/**
* Myers (, Hyyrö) injected into my recursive buildX function (see version 4).
* Pattern p is fixed. Text t is generated by recursion.
*
* Myers (, Hyyrö) bit-parallel LevenshteinDistance
* taken and inferred (for gulfing e.g. m==n) from:
* https://www.win.tue.nl/~jfg/educ/bit.mat.pdf
* http://www.mi.fu-berlin.de/wiki/pub/ABI/RnaSeqP4/myers-bitvector-verification.pdf
* https://www.sciencedirect.com/science/article/pii/S157086670400053X
* https://www.researchgate.net/publication/266657812_Thread-cooperative_bit-parallel_computation_of_Levenshtein_distance_on_GPU
*/
static long buildX(int n, int p, int t, int j, int VP, int VN){
final int HMASK = 1 << (n - 1); // 10^(m-1)
final int VMASK = (1<<n)-1;
long score=0;
int Bj, D0, HP, HN, VP1, VN1, X;
// assume a 0 at Tj
Bj= ~p;
// compute diagonal delta vector
D0 = ((VP + (Bj & VP)) ^ VP) | Bj | VN;
// update horizontal delta values
HN = VP & D0;
HP = VN | ~(VP | D0);
// Scoring and output
// carry = rev(n, j)*(Integer.bitCount(HP & HMASK) - Integer.bitCount(HN & HMASK));
X = (HP << 1) | 1;
VN1 = (HN << 1) | ~(X | D0);
VP1 = X & D0;
if (j!=HMASK) {
// update vertical delta values
score = buildX(n, p, t, 2*j, VN1, VP1);
} else {
score = n + Integer.bitCount(VMASK & VN1) - Integer.bitCount(VMASK & VP1);
}
// assume a 1 at Tj
Bj= p;
// compute diagonal delta vector
D0 = ((VP + (Bj & VP)) ^ VP) | Bj | VN;
// update horizontal delta values
HN = VP & D0;
HP = VN | ~(VP | D0);
// Scoring and output
// carry += rev(n, j)*(Integer.bitCount(HP & HMASK) - Integer.bitCount(HN & HMASK));
X = (HP << 1) | 1;
VN1 = (HN << 1) | ~(X | D0);
VP1 = X & D0;
if (j!=HMASK) {
// update vertical delta values
return score + buildX(n, p, t, 2*j, VN1, VP1);
} else {
return n + score + Integer.bitCount(VMASK & VN1) - Integer.bitCount(VMASK & VP1);
}
}
static long gcd(long numerator, long denominator) {
long gcd = denominator;
while (numerator != 0) {
long tmp=numerator; numerator=gcd % numerator; gcd=tmp;
}
return gcd;
}
}
```
## Version 5.1
Like version 5 but is multi-threaded by using streams.
```
0.000000 1 2 1/2
...
0.748000 15 6307383588 1576845897/268435456
2.359000 16 26681322150 13340661075/2147483648
10.062000 17 112502389800 14062798725/2147483648
35.387000 18 473007979784 59125997473/8589934592
156.396000 19 1983620163248 123976260203/17179869184
572.525000 20 8299330867296 259354089603/34359738368
```
## Version 5
Myers code directly injected into my recursive buildX function. As a consequence no extra call of LevenshteinDistance is needed any more.
```
0.000000 1 2 1/2
...
2.134000 15 6307383588 1576845897/268435456
7.571000 16 26681322150 13340661075/2147483648
32.705000 17 112502389800 14062798725/2147483648
119.952000 18 473007979784 59125997473/8589934592
523.186000 19 1983620163248 123976260203/17179869184
```
## Version 4.1
Like version 4 but is multi-threaded by using streams.
```
0.000000 1 2 1/2
...
0.764000 13 348438558 174219279/33554432
1.525000 14 1485590598 742795299/134217728
4.417000 15 6307383588 1576845897/268435456
15.445000 16 26681322150 13340661075/2147483648
63.199000 17 112502389800 14062798725/2147483648
259.179000 18 473007979784 59125997473/8589934592
```
## Version 4
Uses Myers, Hyyrö bit-parallel LevenshteinDistance.
```
0.000000 1 2 1/2
...
8.203000 15 6307383588 1576845897/268435456
35.326000 16 26681322150 13340661075/2147483648
148.577000 17 112502389800 14062798725/2147483648
629.084000 18 473007979784 59125997473/8589934592
2615.031000 19 1983620163248 123976260203/17179869184
```
## Version 3
Copied and uses getLevenshteinDistance(..) from apache StringUtils.
BTW: Using the threshold variant made no difference for me. (Used threshold=bitCount(s^t))
```
0.000000 1 2 1/2
...
60.190000 15 6307383588 1576845897/268435456
271.020000 16 26681322150 13340661075/2147483648
1219.544000 17 112502389800 14062798725/2147483648
```
## Version 2
Found more symmetries on recursion.
```
0.000000 1 2 1/2
...
105.389000 15 6307383588 1576845897/268435456
447.617000 16 26681322150 13340661075/2147483648
2105.316000 17 112502389800 14062798725/2147483648
```
## Version 1
```
0.000000 1 2 1/2
0.068000 2 16 1/1
0.070000 3 94 47/32
0.071000 4 486 243/128
0.073000 5 2358 1179/512
0.074000 6 11020 2755/1024
0.076000 7 50244 12561/4096
0.086000 8 225044 56261/16384
0.111000 9 994632 124329/32768
0.223000 10 4350814 2175407/524288
0.640000 11 18874848 589839/131072
1.842000 12 81328514 40664257/8388608
7.387000 13 348438558 174219279/33554432
29.998000 14 1485590598 742795299/134217728
139.217000 15 6307383588 1576845897/268435456
581.465000 16 26681322150 13340661075/2147483648
```
[Answer]
# C
```
// gcc -O3 -pthread -march=native a.c && ./a.out
#define _GNU_SOURCE
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define _(a...){return({a;});}
#define $(x,a...)if(x){a;}
#define P(x,a...)if(x)_(a)
#define W(x,a...)while(x){a;}
#define F(i,n,a...)for(I i=0,n_=(n);i<n_;i++){a;}
#define S static
typedef void V;typedef int I;typedef long long L;typedef struct{I x,r;pthread_barrier_t*b;}A;
S I n,x1,msk,nt;S L f1(I,I,I,I);
S L gcd(L x,L y)_(W(x,L z=x;x=y%x;y=z)y)S I rev(I x)_(I r=0;F(i,n,r+=(x>>i&1)<<(n-1-i))r)
S L f0(I x,I j,I vp_,I vn_,I pm)_(I d0=(((pm&vp_)+vp_)^vp_)|pm|vn_,hp=vn_|~(d0|vp_),hp1=hp<<1|1,vp=(d0&vp_)<<1|~(d0|hp1),vn=d0&hp1;f1(x,j,vp,vn))
S L f1(I x,I j,I vp_,I vn_)_(P(!--j,__builtin_popcount(msk&vp_)-__builtin_popcount(msk&vn_))f0(x,j,vp_,vn_,x)+f0(x,j,vp_,vn_,~x))
S V*f2(A*a)_(I x=a->x;L s[3]={};W(x<x1,I rx=rev(x),nx=msk&~rx;$(x<=rx&&x<=nx,s[(x!=rx)+(x!=nx)]+=f1(x,n+1,msk,0))x+=nt)
a->r=s[0]+2*s[1]+4*s[2];pthread_barrier_wait(a->b);NULL)
S L f3()_(L r=(L)n<<2*n;pthread_barrier_t b;pthread_barrier_init(&b,0,nt);A a[nt];pthread_t t[nt];
F(i,nt,cpu_set_t c;CPU_ZERO(&c);CPU_SET(i,&c);pthread_attr_t h;pthread_attr_init(&h);pthread_attr_setaffinity_np(&h,sizeof(cpu_set_t),&c);
a[i].x=i;a[i].r=0;a[i].b=&b;pthread_create(t+i,0,(V*(*)(V*))f2,a+i))
F(i,nt,pthread_join(t[i],0);r+=a[i].r)pthread_barrier_destroy(&b);r)
I main()_(nt=2*sysconf(_SC_NPROCESSORS_CONF);
W(1,n++;x1=1<<(n-1);msk=(1<<n)-1;L p=f3(),q=1ll<<2*n,d=gcd(p,q);printf("%d %lld/%lld\n",n,p/d,q/d);fflush(stdout))0)
```
[Answer]
Python ~ ~~15, 17, 18~~ Requiem for a Dream.
So far for my attempt to decipher the algorithm. Just one simple symmetry as a result. Upside is that I managed to get up to 19. Downside is obviously a shattered hope XD.
To add an insult to an injury, I think that Bob Genom already has it. (Noticed after I dismantled my previous horror of a solution to something readable-ish.) It also might be that what I considered annoying edge cases might actually be a result of me overcomplicating things. Dear oh dear.
Still I think that some way of caching the Levenstein computation might be the way to go. Just not the one I tried last time.
```
7.215967655181885 16 13340661075 / 2147483648
24.544007539749146 17 14062798725 / 2147483648
93.72401142120361 18 59125997473 / 8589934592
379.6802065372467 19 123976260203 / 17179869184
```
---
Added Multiprocessing. The most expensive thing at the time are locks. And I have yet to figure a way to bypass the need for them. My manual attempts are slower than the Pool.Starmap which makes me slightly sad.
Tried a block processing approach with an attempt to gain another linear factor, however for some reason this slowed down the code by a lot. Overoptimization seems to backfire.
```
1.640207052230835 13 174219279 / 33554432
1.9370124340057373 14 742795299 / 134217728
3.1867198944091797 15 1576845897 / 268435456
9.054970979690552 16 13340661075 / 2147483648
37.539693117141724 17 14062798725 / 2147483648
158.5456690788269 18 59125997473 / 8589934592
```
Thanks to Bob Genom's answer and using his latest distance algorithm I managed to up the speed.
Also I noted that one of the attempts at a linear symmetry backfired - the code runs faster after I removed it. Probably something to do with ranges?
```
...............
0.6873703002929688 13 174219279 / 33554432
2.0464255809783936 14 742795299 / 134217728
7.808838605880737 15 1576845897 / 268435456
33.9985032081604 16 13340661075 / 2147483648
145.6884548664093 17 14062798725 / 2147483648
```
Took me quite a while and I have run into quite the Python limitations. My attempt to parallelize was ground to a halt by the GIL. Figuring out how to make processes talk to each other will take a while.
I have few more ideas to try, however my brain is starting to melt. I spent last two hours by juggling indices - my current approach is to embed symmetries directly into the loops. Recursion was much slower and Numba doesn't like to interact with Python objects. For some reason it sees nothing to parallelize in this code and I have no clue whether the parallel part does anything since the CPU is only at 20% capacity.
This approach is still bruteforcing, however with the embedded symmetries it takes the computation down a notch - many of the combinations are not even considered.
I took the liberty to start from 2nd floor. I do not consider that as a cheating since it is negligible time-wise. And it introduces a swath of very vexing edge cases.
If I have time, I will try to do these:
Rewrite the code in something faster, probably C.
Try to figure out a decent way to use parallelization, maybe in C.
And a bit of a caching. That one will be tricky, especially in combination with the embedding.
```
0.0 2 1 / 1
0.483562707901001 3 47 / 32
0.483562707901001 4 243 / 128
0.483562707901001 5 1179 / 512
0.483562707901001 6 2755 / 1024
0.483562707901001 7 12561 / 4096
0.5001938343048096 8 56261 / 16384
0.5334563255310059 9 124329 / 32768
0.6999850273132324 10 2175407 / 524288
1.3333814144134521 11 589839 / 131072
3.7170190811157227 12 40664257 / 8388608
15.165801048278809 13 174219279 / 33554432
62.91589903831482 14 742795299 / 134217728
266.3912649154663 15 1576845897 / 268435456
```
I would love to try and give a GPU a go for this task. However I failed miserably for nowXD.
```
from numba import jit, cuda, prange
import time
import multiprocessing as mp
@jit(nopython=True, fastmath=True, nogil=True)#, parallel=True)
def LevenshteinDistance(n, p, t):
np=~p
HMASK = (1 << (n - 1))
VP = (1 << n) - 1
VN = 0
score = n
for j in range(0,n):
if (t & (1<<j)) != 0:
Bj = p
else:
Bj = np
D0 = ((VP + (Bj & VP)) ^ VP) | Bj | VN
HN = VP & D0
HP = VN | ~(VP | D0)
if ((HP & HMASK) != 0):
score += 1;
elif ((HN & HMASK) != 0):
score -= 1;
X = (HP << 1) | 1
VN = X & D0
VP = (HN << 1) | ~(X | D0)
return score
@jit(nopython=True, fastmath=True)#, parallel=True)
def dispatchLev(i, level):
halfSize = 1 << (level - 1) - 1
iRange = halfSize
levelSize = 1 << (level - 1)
mask = levelSize - 1
halfSize = levelSize >> 1
rangeUpper = iRange - i
indexI = i + halfSize
baseI = indexI << 1
sum = 0
for indexJ in range(0, rangeUpper):
baseJ = indexJ << 1
if (mask ^ indexJ) == indexI:
a = LevenshteinDistance(level, baseI + 1, baseJ)
b = LevenshteinDistance(level, baseI, baseJ + 1)
sum += a + b
else:
a = LevenshteinDistance(level, baseI + 1, baseJ)
b = LevenshteinDistance(level, baseI, baseJ + 1)
sum += 2 * (a + b)
return sum
def computeSum(level):
levelSize = 1 << (level - 1)
halfSize = levelSize >> 1
curSum = 0
iRange = halfSize
test = [(x, level) for x in range(0, iRange)]
if len(test) > 1:
a = myPool.starmap(dispatchLev, test)
curSum += sum(a)
#for x, level in test:
# curSum += dispatchLev(x,level)
else:
a = dispatchLev(0, level)
curSum += a
return curSum
def gcd(num, den):
gcdRet = den
tmp = 0
while num != 0:
tmp = num
num = gcdRet % num
gcdRet = tmp
return gcdRet
if __name__ == '__main__':
t1 = time.time()
print("beginning")
prevSum = 16
bruteForceCarry = 6
levelMask = 0
target = 20
curSum = 0
bruteForce = 0
myPool = mp.Pool(mp.cpu_count())
processArray = []
resultArray = []
for level in range(3, target):
levelSize = 1 << level
halfSize = levelSize >> 1
bruteForce = computeSum(level)
diagonal = computeDiagonal(level)
bruteForceCarry = 2 * bruteForceCarry + bruteForce
curSum = prevSum + bruteForceCarry
curSum = curSum * 2
t2 = time.time()
wholeSize = levelSize * levelSize
divisor = gcd(curSum, wholeSize)
a = int(curSum / divisor)
b = int(wholeSize / divisor)
print(t2 - t1, level, a, "/", b)
prevSum = curSum
```
] |
[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/194089/edit).
Closed 4 years ago.
[Improve this question](/posts/194089/edit)
# Background
You've been given a task to take notes for a meeting. You start typing on your Google Doc, but you don't have enough time during the meeting to look at your keyboard while you type.
Fortunately for you, you can type without looking at your keyboard. After the meeting, you realize that everything you typed was one key to the left.
# The Challenge
For this challenge, you will be using the letters, numbers, and space bar of the QWERTY keyboard layout.
* Given an input of text (from any standard input method), output the resulting text, where every character is moved one to the left on the keyboard.
+ For the majority of letters, just look at the letter and translate it to the letter to the left (`c` becomes `x`, `t` becomes `r`, etc).
+ For letter `q`, translate to a literal tab character (`\t`).
+ For letter `a`, enable caps lock, so the capitalization of the rest of the string is reversed.
+ For letter `z`, capitalize the next letter in the string.
+ No translation is required for the space bar.
* Preserve capitalization while translating, and be mindful of caps lock (if caps lock is enabled, make sure the case is the opposite).
* All characters in the input string will be letters, numbers, or a space. No punctuation or other characters can be included.
# Test Cases
`\t` *is a literal tab character*
```
Hello world -> Gwkki qieks
Code Golf -> Xisw Fikd
Queried apples -> \tyweuws OOKWA
```
# Scoring
Lowest score in bytes wins. Have fun!
[Answer]
# [JavaScript (V8)](https://v8.dev/), 271 bytes
```
f=(s,k='~!@#$%^&*()_+`1234567890-=\tQWERTYUIOP{}|\tqwertyuiop[]\\ASDFGHJKL:"\n\\asdfghjkl;\'ZXCVBNM<>?zxcvbnm,./')=>s.replace(/[^ ]/g,c=>k[k.indexOf(c)-1]).replace(/\\([^\\]*)\\?/g,(m,c)=>c.replace(/[a-zA-z]/g,l=>l>'Z'?l.toUpperCase():l.toLowerCase())).replace(/[?']/,"")
```
[Try it online!](https://tio.run/##fY1ZV4JAGIbv@xVECzPGkq2mAZmVVpZZ2iKDNcJgyMgQ4BItf930ovJ0tIvv4j3Pc56vg/s4skI3iKV@ZjRyVBCJnip8Lh4sLa80V1MAPq49pTc2t7Z3djN765KK4urd8XXtoX5auXr7eEfxy4CE8WvPZYFhIpS/OTopls7Oy1ke@QjhyHbazx2P5pDQuC/cHl5e7Gt6MrT6Lb8ryooAVS2SQxJQbBGgGE3OVNqipWqe4cmub5NhxQEWlNIm/LUQAkYTITMFEdLHOuiK1rhjTXWwlOSlZNKiqkY1oSHoVI5ZPQhIWMARATA72WU2@N5w6oGhC6Yi8jwcWcyPGCUyZW3gAL5EKGXcgIXU5iHMLfzBBWYTrsioMwtWeyR0ic3hIKAk@s/IzzUS0grxTNKYS2okijns/9zEGX0B "JavaScript (V8) – Try It Online")
My first JavaScript code golf.
It could definitely be shorter, but I think this is a good start.
It basically finds each character in the `k` string and replaces it with the previous one, then swaps the case of everything between the `A` or `a`, and removes all occurences of `Z` or `z` (as shift key does nothing on its own).
This should be a normal QWERTY keyboard layout, but let me know if not.
[Answer]
# [Python 3](https://docs.python.org/3/), 211 bytes
```
d=' ~!@#$%^&*()`~1!2@3#4$5%6^7&8*9(0) qQwWeErRtTyYuUiIoOpPaAsSdDfFgGhHjJkKlLzZxXcCvVbBnNmM '
c=s=0
for i in input():k=d.find(i);print(end=d[k-2+(c*i.isalpha()^s)*(1-k%2*2)][i in'aAzZ':]);c^=i in'aA';s=i in'zZ'
```
[Try it online!](https://tio.run/##LU9rT8IwAPxMf0UJj7YzEBg@IUuYqKDiA8UXhMW6dq6urrPbBPaBvz5H8HK5XO6SSy5aJ74KO/nSF5LDqU55F8ACfMVdjBDKmYXgptyvVGtO3cDkfdMum/1OZb96UDt0jurHxglukVLpZ7J84ef6IZmu39Incanuontqx4/szLv4HPqjr6vgWo6z2erVHfw@f5yGt983ECLgWrHVAp7SUEARFozSBJNuYLGmJ0KGBelFWoQJ5iGz2DxomHvYNURTxFRGPsXEiYmB242gZhomWcy3K4ja2Qx1F6TnOtZ/gHrxzhZNvlskoPhH8hGXUsGl0pKBgWIcDpX0wCTlWnAGaRRJHgM74zpZA9o2OyDbij0ew0wxQd34Dw "Python 3 – Try It Online")
Uses a lookup string in which the normal character and its shift-modified version are grouped together. For each character in the input, it will retreive the character two places to the left. Changes capitalization by adding `1` (or `-1` if the current character is uppercase) to the lookup value when shift XOR caps lock is active. Numbers are not influenced by the caps lock modifier.
[Answer]
# [PHP](https://php.net/), 227 bytes
```
for(;''<$s=$argn[$i++];)$s!=a&&$s!=A?$s!=z&&$s!=Z?($t=$m[stripos($m='~1!2@3#4$5%6^7&8*9(0 qwertyuiopasdfghjklzxcvbnm',$s)-1])+(print$s>' '?$s<A?!$h?$s-1?$s?$s-1:9:'`':$t:($t>=A&&(($s<a)+$h+$c)%2?$t^' ':$t):$s)+$h=0:$h=1:$c=!$c;
```
[Try it online!](https://tio.run/##PZBfT4MwFMWf5VPAvKNFXDL2fzCGxER9NfFpc4sddAPtaKWdUx786GJxcQ/3d865ubc3qchEPYuE5paXOEBoBjIEUu6KJeSuuwockFZIbLuROGpYncIiwqBC2C@lKnPBJYZ9iL49q3fTvxzAsD1aj@3J1RR3L96PtFRfh5wLItPtLnt9Y9Vn8rEp9ugapNPxVo6LRZkXCuQcmUhfmcWRBZk2HU/jT/2pj16QD8rXd@dhbNsY60HiuJC5kDjtXgRqrdf1iOPrd3U/7Poang9JaEES1DTJuNl6LlrBoZBUYcidf5ecXeYE9QNljJtHXrLUuOUpNe852xqPB1rmNDWJEIzKc4xPsaKbkkhjcZInKpVJinMZcdX8guH1@oPhaDyZdg2ivVE1iBkzK57mJJE/XKicF7Lu3P0C "PHP – Try It Online")
I have created a mapping string (`~1!2@3#4$5%6^7&8*9(0 qwertyuiopasdfghjklzxcvbnm`) which for each digit has their SHIFT mode on the left and for each letter has the letter/key to their left.
I loop over input characters and for each character:
* If character is `a` or `A`, caps lock flag gets reversed (logical not).
* If character is `z` or `Z`, shift flag is set to `1`.
* When character is not in `aAzZ`:
+ Character to the left of current character in the mapping string is stored in `$t`.
+ If current character is an space, it is printed.
+ If current character is a digit, and if shift flag is `1`, `$t` is printed, else, if digit is `1`, ``` is printed, if digit is `0`, `9` is printed and otherwise, `digit-1` is printed.
+ If current character is a letter, based on status of shift flag, caps lock flag and casing of current character (lower/upper), `$t` in lower or upper case is printed. The only special case here is tab character, which is printed as is.
+ Shift flag is always set back to `0` at the end.
[Answer]
# [Red](http://www.red-lang.org), 218 bytes
```
func[t][c: z: 0 rejoin collect[foreach s t[case[find"Aa"s[c: c xor 32]find"Zz"s[z: 32]on
[keep(select/case" poiuytrewq^-lkjhgfdsamnbvcxzPOIUYTREWQ^-LKJHGFDSAMNBVCXZ0987654321~"s)xor either s <#"Z"[0][c xor z]z: 0]]]]]
```
[Try it online!](https://tio.run/##TY9LU4NAEITv/Iqp9aKHlAQSH5QXjJr4NvHNFqnC3VkhWVncXUzCwb@OkIPF3Oab6p5ujbyeIaexI4JalDmjNqYsgCoAFzQuVJYDU1Iis1QojQlLwYClLDFIRZZzEibEtAoGa6XB9@ItjaqGNibNrnKHLhGLXYOtzX4rJQCFysqN1bj6nvfkcpF@Cm6Sr/zjh62rh/vL5/en2fnrdN67ub6ajC/OHsPbu9OX0VvkHh8dHgwHvtf/JWav/YmZTVE3sU52SESo2xTYZqnitkXcTl3oLLcggExQSgUrpSUnzj8dKY4wVlJ02LREnSGHpCgkms4hrFDbTQdUnp8MvP7QcGFI/Qc "Red – Try It Online")
Currently `AaZz` don't affect digits.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 276 bytes
```
i;j;k;h;l;m;n;o;f(char*b){char*c=calloc(m=strlen(b),1),*a=" \tqwertyuiop\aasdfghjkl\nzxcvbnm\tQWERTYUIOP\aASDFGHJKL\nZXCVBNM`1234567890";for(i=k=j=n=0;j<=m;l=a[i=index(a,b[j++])-a-1])k=l^7?k:!k,o=l>64&l<91?a[i-30*k]:l<97?h=i?l^7?l?l^10?l:0:32:0:0:a[i+29*k],o?c[n++]=o:n;b=c;}
```
Thanks to ceilingcat for -33 bytes.
[Try it online!](https://tio.run/##ddBNT8JAEAbgO79i7cG00CYtIEiXtVFU8Fv8Vopxu23pttvd2hZBCb@9riReTLy8M5N5MochxoyQqqIwhgmMIIMp5FDAUCURzuuettpUgghmTBA1RUWZs4CrnqZbml7HSAFu@b4I8vJzTkXmYlz44SyKE@byryX58HjqluPHo5u75/uTq2sX798eHg9Hp2fnLn95GjwcXF68Wc1We6fT3e2ZCgxFrlKUoBhxZMK4j1LIEJ5QRLkfLFWse5O40ZhqBjasqZYg9tp1Ensr0QVie532Nuv3LEd6o2XWk6ktx64TIer8OCbTMh1mm3arKcO0JWw0exLqwiETLg8jYXPoIQLXFeUlSDHlqraqAbD5A8ACIBCqyiiQ7wALkTNf0aBcZ/OyULHY9L9oIPwADAUL/yfjeZDTwAc4y1hQ/HW1dfUN "C (gcc) – Try It Online")
] |
[Question]
[
[This 128-language quine ouroboros](https://github.com/mame/quine-relay) (a program which outputs a program in another language, which outputs a program in yet another language, (125 languages later), which outputs the original program) is pretty impressive. But unfortunately, it has a static number of iterations.
Write a program which outputs a program (not necessarily in another language, but it can be), which outputs a program, which outputs a program, etc., which after n iterations, outputs the original program **for the first time** (i.e. no intermediate program should be the same as the original, because otherwise a quine which ignores its input would work), where n is a non-negative integer provided as input. The input can't be just a number in the original source code (e.g. putting `x = <the value of n>` at the start of your program), it should be one of the following:
1. Passed as a command-line argument
2. Read from standard input
3. Passed as an argument to a function, which returns/outputs the new program.
For intermediate stages in the ouroboros, your program can either be a fully-functioning program, or a function with no arguments, which, when called, will return/output the next one.
You may not read from the source file itself, or use any quine-like builtins (I don't think there are any which would do this, but there might be)
To be clear, if `n = 0`, the program should output its own source code.
If `n = 1`, the program should output a different program, which outputs the original source code.
And so on...
Fewest bytes wins!
**Edit:**
I should have written "For intermediate stages in the ouroboros, your program can either be a fully-functioning program **with no input**, or a function with no arguments". If your program outputs the next one in the chain, *then* waits for input, that's fine, but your program shouldn't need the original value of n.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes
*-4 bytes + fix thanks to Kevin Cruijssen*
```
"34çìD«s<©di®ì"34çìD«s<©di®ì
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrS62ObQyJfPQusNrsIn9/29kAgA "05AB1E – Try It Online")
---
### Explanation
This works by appending the remaining number to print to the front of the code, which means it's added to the stack the same way an input would be. In the base case of input of "0" it will not concatenate the 0 on the front.
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 39 bytes
```
"3X4+kSql1=c*?S:1-}C'LA-}!i:0)2*?~!'´@
```
[Try it online!](https://tio.run/##KyrNy0z@/1/JOMJEOzu4MMfQNlnLPtjKULfWWd3HUbdWMdPKQNNIy75OUf3QFof//w2NAA "Runic Enchantments – Try It Online")
Would be [4 bytes shorter](https://tio.run/##KyrNy0z@/z9TyTjCRDs7uNBQN9hQ18pA01jLvk490@H/fxMA) than 05AB1E using the same tactic if inputs where less than or equal to `10`. But as we need to support arbitrarily large values, it gets more complicated.
Numerical value of `n` gets placed at the front and parsed as a continuous number literal using `´`. `"3X4+kSq` is the basic quine code. If no value is present at the front, the stack length will only be 1 (the quine) otherwise 2 letting `l1=d*?` determine how to handle things from there.
* If there is a value, `S:1-}'LA2+-}` runs: swap the value to the top, subtract 1, duplicate it, leaving a copy on the bottom of the stack, get the Log10 of that value times 100 (resulting in the value's own character length, plus 1 for the `´`), remove that many characters from the end of the string (effectively truncating itself off the end, both *where* it isn't needed *and* because it has the wrong value). `C` is one byte shorter than `2+` and results in the same value.
* If there is not a value, read one from input.
Regardless: `:0)2*?` duplicate and compare with zero.
* If non-zero push `´`.
* If zero, pop the value. We can cheat using `!` instead of `2?` and save a byte because when `´` tries to execute the first byte it sees is non-numeric and immediately drops out of number mode at the same position.
Print entire stack top to bottom.
[Answer]
# Java 10, 145 bytes
```
n->{Long N=n;var s="n->{Long N=%s;var s=%c%s%2$c;return s.format(s,N>0?N-1+%2$cL%2$c:%2$cn%2$c,34,s);}";return s.format(s,N>0?N-1+"L":"n",34,s);}
```
[Try it online](https://tio.run/##hVDBasMwDL33K4RZwKZJaLeeGtL9QObLjmUHz02L20QplhIYJd@e2V0Gu2wD8YTek@A9nc1gsvPhMtnGEMGLcXhbADjk2h@NrUHHEeCVvcMTWNl0oaEqAjsuAhAbdhY0IJQwYba7VXFDl1gMxgOV4geX0EwmNqHk8cEWvubeI1B@7HxrWFKqd6tnna2XUa4ibCNghPRpk5IqRvHHmajEVqD4Xp2i0VDX/r0JNme3Q@cO0Ias8ivX/s2oOecHcd3mXc/5NSjcoMTcypW6J/5VX/@jb9T8sXH6BA) and [see the outputs of some iterations](https://tio.run/##zZK9asMwFEb3PMVFxCBR2/inU4zTF3C1FLqUDqriFCfydZBklxL87K6UplAvLdkM4hO69xOc4RzEIKLD7jhJJYyBR9HgeQXQoK31XsgauH8CPFnd4DtI@tw1O0BWuOk4AXDAHErAaHuuOlfgZV4Vg9BgSvJrGJjrMJCBCbK1LHRte41g4n2nW2GpCfk2eeBReufXlY@ND/QR5vehYcVI/vhGKrIhSH6qHtDBZXO4bFFw6RwuXRRcModLFgI3eTx3Tv2baiQYK6y7Bm9l6@Sl36K@vAp2FffT2LqNu97GJ7exCinWHxfRKYsxjyXFXil2MfrfenZbPb2tnszq42qcvgA).
**Explanation:**
**[quine](/questions/tagged/quine "show questions tagged 'quine'") explanation:**
* The `var s` contains the unformatted source code
* `%s` is used to put this String into itself with `s.format(...)`
* `%c`, `%1$c`, and `34` are used to format the double-quotes
* `s.format(s,34,s)` puts it all together
**Challenge part:**
The first lambda function takes a `long` input as parameter.
* This is set in variable `Long N=n;` in the first iteration. Or in `Long N=%s;` for next iterations.
* The ternary check `N>0?N-1+"L":"n"` will fill this `%s` with value `N-1`, appended with `L` since it's a long and to convert it to a String for the `%s`, if `N` is larger than 1. If `N` is 0 instead (initial input was `0` or this is the last iteration of the interquine-'loop'), it will fill this `%s` with the initial `n` instead.
[Answer]
# [Haskell](https://www.haskell.org/), ~~195~~ 164 bytes
```
main=putStr(x++show x++"\na=")>>(getLine:cycle[pure$show$a-1])!!a>>=putStr
x="main=putStr(x++show x++\"\\na=\")>>(getLine:cycle[pure$show$a-1])!!a>>=putStr\nx="
a=0
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIo0Jbuzgjv1wBSCvF5CXaKmna2Wmkp5b4ZOalWiVXJuekRheUFqWqgBSpJOoaxmoqKiba2UG1c1XYKuEwLUYpBmReDGkGxuQBTeRKtDX4/98EAA "Haskell – Try It Online")
This uses a pretty simple quine technique. We modify it with a variable `a` which is set to a number. If that number is zero (which it is at the start) we take input and output our source with `a` set to the input number. If `a` is not zero we output our source with `a` set to one less. This way `a` counts down to zero before outputting the original source.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 bytes
```
“Ṫ_1xẸƲ;Ṿ⁾v,⁾¥ ”v,¥
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO1fFG1Y83LXj2Cbrhzv3PWrcV6YDJA4tVXjUMLdMB0j////f0BQA "Jelly – Try It Online")
[Try repeated calls of code](https://tio.run/##y0rNyan8//9Rw5yHO1fFG1Y83LXj2Cbrhzv3WT9q3FemAyIPLVV41DC3TAdI/zc0PdweBiQmHFoY@f8/AA "Jelly – Try It Online")
A full program that takes a single argument \$n\$. Main version outputs correctly to stdout but cannot be used as a function with a function return. The repeated calls version is 2 bytes longer but returns programmatically usable output. L
[Answer]
# [R](https://www.r-project.org/), 92 bytes
```
f=function(n=-1){gsub("\\s","",paste("f=",sub("-?\\d+",n-1,paste(deparse(f),collapse=""))))}
```
[Try it online!](https://tio.run/##LY1LCgMhEET3OcXQq26iEGeZQXIRN8ZREURFnWxCzm7Mp5aveFV1DCfdkUwPOWGSXNDTt@OOoFQDBsCKbt0iOAnsy/lNqf0MLHHx73ZbdG0WHTGTY9SlWQlAM6/hpcP1QieXK4YlpEVc13lhdEfPQCWgzT50xN9Cl55o@zhTfQM "R – Try It Online")
If `deparse` is deemed cheating, here’s an alternative:
# [R](https://www.r-project.org/), 108 bytes
```
function(n=-1){s="function(n=%d){s=%s%s%2$s;sprintf(s,n-1,intToUtf8(34),s)}";sprintf(s,n-1,intToUtf8(34),s)}
```
[Try it online!](https://tio.run/##hYxNCsIwEIX3nqIECzOQgqkuxJJb6M5NqJ0SkEnJRDfFs8dxJ27kbR7f@8mVfKUHjyUmBvadw1W8@SLt7UNaUfVbGWTJkQuBWO6cVXtOl0JH2B/QCr7Mv0Kd/fQMd1hClgmKJ@h3iLihlCE2kRt3UrCOocAMaM2VDQ4/Gw1Qn94 "R – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~60~~ ~~56~~ ~~55~~ 53 bytes
```
lambda n=-1,s='lambda n=%d,s=%r:s%%(~-n,s)':s%(~-n,s)
```
[Try it online!](https://tio.run/##fYzBCsIwEETv@YplITTB5lD0IIF8SfUQaaOBug2bIHjx12Ms4tHDwHsMM@lZbivtj4lrcIh4qou/XyYP5MzQZ9f9VE5NJdsspXoZ6rPuGn@xtulozXAWBA4OInGkogJYB/PDLwoVwg5CC@oNc2FFenPUWoSVIUIkYE/XuTVWwN@Pz6q@AQ "Python 3.8 (pre-release) – Try It Online")
*-2 bytes thanks to Jo King*
As of the 53 byte version, also works in Python 2 and Python 3.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes
```
<say '<',S{\d+}=get||0-1,'>~~.EVAL'>~~.EVAL
```
[Try it online!](https://tio.run/##K0gtyjH7/9@mOLFSQd1GXSe4OiZFu9Y2PbWkpsZA11BH3a6uTs81zNEHzuD6/98AAA "Perl 6 – Try It Online")
Takes input via standard input and returns a program where the only thing changed is the first number. Each subsequent program will then output the same program, except with that number decremented.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 112 bytes
```
void f(int n=-1){var s="void f(int n={2}){{var s={0}{1}{0};Write(s,(char)34,s,n-1);}}";Write(s,(char)34,s,n-1);}
```
Saved a lot of bytes thanks to @NickKennedy!
[Try it online!](https://tio.run/##Sy7WTS7O/P@/LD8zRSFNIzOvRCHPVtdQs7ossUih2FYJRbzaqFazGipTbVBbbVgLJK3DizJLUjWKdTSSMxKLNI1NdIp18oAmWNfWKuGW@5@WXwQ2NdPWyMA60w6IdXU1q4E2aUI0@WTmpWqAFAIA "C# (Visual C# Interactive Compiler) – Try It Online")
] |
[Question]
[
Hexcells is a game based off of [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) played on hexagons. (Full disclosure: I have nothing to do with Hexcells. In fact I don't really like the game.) Most of Hexcells rules can be pretty easily expressed in Generalized Minesweeper (Minesweeper played on an arbitrary graph). The one that is most difficult is the `{X}` and `-X-` rules.
The `{X}` rule tells us that a cell borders `X` mines and that all of these mines border each other in a continuous path. For example if we had the board:
```
? ?
? {3} ?
? ?
```
The 6 possibilities for mine placement would be
```
* . . . . . . * * * * *
* {3} . * {3} . . {3} * . {3} * . {3} * * {3} .
* . * * * * . * . . . .
```
Your goal is to implement the rule `{3}` in generalized Minesweeper.
## Specifics
Generalized Minesweeper is Minesweeper played on an arbitrary graph. The graph has two types of vertex, an "indicator" or a "value". A value can be either on or off (a mine or a dud) however its state is unknown to the player. An indicator tells the player how many adjacent vertices are on (mines) and does not count as a mine itself.
For example the following board for Generalized Minesweeper tells us that cells A and B are either both mines or neither of them are mines.
[](https://i.stack.imgur.com/N62xO.png)
*(In the diagram indicators are marked in gray while values are white)*
Unlike in normal minesweeper where you click values that are off to reveal indicators, there is no such mechanic in Generalized Minesweeper. A player simply determines for what states of the graph can satisfy its indicator.
Your goal is to build a structure in Generalized Minesweeper such that there are 6 specific cells that can only have states that fulfill as if they were connected with the Hexcells rule `{3}`. When you write your solution you should not have specific values in mind for value cells. (In answer to H.PWiz's question it is allowed that some value cells might be deducible from the state, but you can always improve your score by removing such cells)
## Scoring
You answers will be scored by the number of vertices in the final graph minus 6 (for the 6 inputs) with a lower score being better. If two answers tie in this metric the tie breaker will be the number of edges.
## Solvability
This problem is solvable, I have a solution to this problem and I will post it once this challenge is a week old.
[Answer]
# ~~7~~ 5 vertices, ~~14~~ 10 edges

(Graph made with [this online tool](http://illuminations.nctm.org/Activity.aspx?id=3550) and paint.)
`A`-`F` are our six nodes, and `J` is a helper node. The three `1`-nodes enforce that opposite nodes are different, while the `2`-node makes sure that `A`, `C` and `E` can neither be all mines, nor all empty.
*Edit: -2 vertices thanks to CalculatorFeline and H.PWiz!*
[Answer]
# 44 vertices, 66 edges
First, we start with a ring of 6 value cells all connected to a 3. These cells will be the cells with the `{3}` rule.
```
A B
\ /
F---3---C
/ \
E D
```
Then, we attach 012 sensors to the value cell pairs (AB,BC,CD,DE,EF,FA). The structure of the 012 sensor is below.
```
O ?---1---?
\ / /
2---?---1
/ \
A B
```
A and B are the inputs to the sensor and O is the output. The ? cells are generic value cells. O will be a mine if exactly one of A and B is a mine and empty otherwise. Then, we connect a 2 node to all the sensor outputs. This ensures that there are exactly 2 pairs with exactly 1 mine, and it can be proven that the only configurations that satisfy this are the ones that satisfy `{3}`. Each sensor takes 7 nodes, so 6 sensors requires 42. Add the 3 node connected to ABCDEF and the 2 node connected to the outputs and you get 44.
This solution can also be adapted for `{1}`-`{5}` by changing the 3 node to some other value.
[Answer]
# 9 Vertices, 17 Edges
Where ? is a value cell, that is not one of the `6` we care about, we need the following subgraph.
```
___________
? / ? \?
\| /|\ /
3¯¯¯¯ 1 ¯¯¯¯2
|\ | /|
| \ /¯|¯¯¯¯ |
| X | |
/ / \_|___ \
A__/ B \__C
```
My ASCII-art skill are dreadful.
With those 6 vertices set up: `ABC` can have the following states:
`111`, `110`, `011`, `000`, `100`, `001`
With the cells corresponding to the following hexagon, all we then need are 3 more indicator cells `A-1-D`, `B-1-E`, `C-1-F`
```
B C
A D
F E
```
] |
[Question]
[
# Introduction
You are a supervisor of a parking lot and your manager is preparing for shrinking the size to the extreme.
It is a simplified and adapted version of a problem in last year's [PAT](https://www.patest.cn/) top-level.
# Challenge
You are asked to calculate how many cars are in the lot at the same time, **at most**.
Standard rules apply. And this is a code-golf so shortest code wins.
First line is the quantity of entries (no more than `100,000`, **your input may not contain this line if you like, for it is only a makeshift to determine where input ends**). The following text contains one entry per line. And each entry includes three numbers:
```
<Car plate number> <Time (seconds) since open> <0(In) | 1(Out)>
```
**Modification 2:** It is OK to use an array of triples as input.
**Modification 3:** You can change the order of numbers in one entry. And you can choose which to use. (see the Remarks section)
The input is guaranteed to be valid, assuming that:
* `Car plate number` is a integer in the range of `10000` ~ `99999`
* `Time` is a integer in the range of `0` ~ `86400`
And
* Entries are **not necessarily** chronologically ordered.
* There is no car before the first second.
* There is **not necessarily** no car after the last second.
* A car would not leave before it gets in.
* `Car plate number` is unique. (but a same car may visit for more than one time)
* So it is impossible for a car to enter the lot when it is already in it.
* A same car wouldn't go in and out at the same `time`.
* A car is considered to be in the lot at the time of in / out.
# Example 1
Input
```
11
97845 36000 1
75487 16500 1
12345 16 0
75486 3300 0
12345 6500 1
97845 32800 0
12345 16400 0
97846 16501 1
97846 16500 0
75486 8800 1
75487 3300 0
```
Output
```
3
```
Explanation
At `16500`, car `12345` and `75487` were in the parking lot.
# Example 2
I made this because I found many code failed on it.
Input (with first line left out)
```
12345 16400 0
12345 16500 1
75487 16500 0
75487 16600 1
```
Output
```
2
```
Explanation
At `16500`, car `12345` and `75487` were in the parking lot.
# Remarks
Actually, not all three are required for the output. At least, you only need plate+time or in/out+time for the result. But the algorithm is slightly different under two circumstances, so the choice of being shorter stays unknown in a certain language. And of course you can use all of three numbers. So I leave them in the challenge.
[Answer]
# Mathematica, 33 bytes
```
-Min@Accumulate[2#2-1&@@@Sort@#]&
```
I had to read the problem statement better to realize that there's a much simpler algorithm that doesn't require the license plate information.
Unnamed function returning an integer; the input format is a list of ordered triples in the form `{time, 0|1, license plate}`. We start by `Sort`ing, which makes the list chronological and also breaks time-ties by sorting `0`s before `1`s; then `2#2-1&@@@` keeps the arrival/departure information and forgets the rest, and also converts `0`s to `-1`s.
`Accumulate` calculates the running totals of that list; the result is a list of the *negatives* of the numbers of cars in the parking lot after every arrival/departure. Then `Min` picks the smallest (most negative) of these and the negative sign is stripped.
# Mathematica, 56 bytes
```
Max[<|#|>~Count~0&/@FoldList[List,{},#3->#2&@@@Sort@#]]&
```
The original submission (the first several comments refer to this submission). Unnamed function returning an integer; the input format is a list of ordered triples in the form `{time, 0|1, license plate}`.
The reason we choose to put the time entry first and the in/out entry second is so that `Sort@#` sorts the list chronologically, and records arrivals before departures if they're simultaneous. After that, `#3->#2&@@@` returns a list of "rules" of the form `license plate -> 0|1`, still sorted chronologically.
Then, `FoldList[List,{},...]` creates a list of all the initial segments of that list of rules. Actually, it really messes up those initial segments; the `k`th initial segment ends up being a list with one rule at depth 2, one rule at depth 3, ..., and one rule at depth `k`+1. (`FoldList[Append,{},...]` would yield the more natural result.) However, `<|#|>` turns each of these initial segments into an "association", which has two desirable effects: first, it completely flattens the nested-list structure we just created; and second, it forces later rules to override earlier rules, which is exactly what we need here—for any car that has left the parking lot, the record of its initial entry is now completely gone (and similarly for cars that re-enter).
So all that's left to do is to `Count` how many `0`s there are in each of these associations, and take the `Max`.
[Answer]
## Haskell, ~~76 63~~ 61 bytes
2 bytes saved by a variation of @nimi's suggestion.
```
f l=maximum$scanl1(+)[(-1)^c|i<-[0..8^6],(_,b,c)<-l,i==2*b+c]
```
Expects the argument as a list of triples in the order given by the problem statement.
For each possible time (and some more), we search first for coming and then for leaving car events and turn them to a list of plus or minus ones. We take the partial sums of this list and then the maximun of these partial sums.
[Answer]
# PHP 7.1, ~~126~~ 117 bytes
```
for(;$s=file(i)[++$i];)$d[+substr($s,6)][$s[-2]]++;ksort($d);foreach($d as$a){$r=max($r,$n+=$a[0]);$n-=$a[1];}echo$r;
```
takes input from file `i`, ignores first line. Run with `-r`.
Requires a trailing newline in input. Replace `-2` with `-3` for Windows.
**breakdown**
```
# generate 2-dim array; first index=time, second index=0/1 (in/out);
# values=number of cars arriving/leaging; ignore plate number
for(;$s=file(i)[++$i];) # read file line by line (includes trailing newline)
$d[+substr($s,6)][$s[-2]]++; # substring to int=>time, last but one character=>1/0
ksort($d); # sort array by 1st index (time)
foreach($d as$a) # loop through array; ignore time
{
$r=max($r, # 2. update maximum count
$n+=$a[0] # 1. add arriving cars to `$n` (current no. of cars)
);
$n-=$a[1]; # 3. remove leaving cars from `$n`
}
echo$r; # print result
```
[Answer]
# C, 147 bytes
A complete program, reads input from `stdin`.
```
int r[86402]={},u,i,n,t;g(s,o){for(;s<86401;n<r[s]?n=r[s]:0,++s)r[s+o]+=o?-1:1;}main(){for(n=0;scanf("%d%d%d",&u,&t,&i)==3;g(t,i));printf("%d",n);}
```
[Try it on ideone](http://ideone.com/29eAjr).
[Answer]
# Octave , ~~50~~, ~~64~~ 38 bytes
```
@(A)-min(cumsum(sortrows(A)(:,2)*2-1))
```
Same as @Greg Martin 's [Mathematica answer](https://codegolf.stackexchange.com/a/106021/62451)
The function gets an array with 3 columns `[time, i/o,plateN]`
previous answer:
```
@(A){[t,O]=A{:};max(cumsum(sparse({++t(!O),t}{2},1,!O*2-1)))}{2}
```
The function only gets two inputs `t`: time and `O`: I/O from first two element of a cell array `A` that contains triple inputs!
A sparse matrix created to count for each recorded time number of existing cars . For it time of out + 1 is considered for car exit and corresponding 1 change to -1 and 0 changed to 1.
Use of sparse here is very important since multiple cars may arrive or leave at the same time.
Then cumulative sum computed representing number of current cars in the lot and max of it is found.
[Answer]
# JavaScript (ES6), ~~63~~ ~~73~~ 71 bytes
```
d=>Math.max(...d.sort((a,[b,c])=>a[s=0]-b||a[1]-c).map(e=>s+=1-e[1]*2))
```
This accepts input as an array of entries ordered `[time, inout, plate]`. Unfortunately due to the fact that identical inout times means that both cars are considered in the lot at the moment in time, the sorting algorithm must order `0` prior to `1`, which costed 11 bytes.
## Credits
* I saved 1 byte by moving the shift and multiplication inside the map function completely (thanks Neil).
* I saved another two bytes by using a destructured argument in the sort function (thanks edc65).
## Demo
```
// test the two examples
console.log([[[36000,1],[16500,1],[16,0],[3300,0],[6500,1],[32800,0],[16400,0],[16501,1],[16500,0],[8800,1],[3300,0]],[[16400,0],[16500,1],[16500,0],[16600,1]]].map(
// answer submission
d=>Math.max(...d.sort((a,[b,c])=>a[s=0]-b||a[1]-c).map(e=>s+=1-e[1]*2))
));
```
[Answer]
## JavaScript (ES6), ~~83~~ … ~~68~~ 70 bytes
*EDIT: fixed to support the 2nd example*
Takes input as an array of `[in_out, time, plate]` arrays. But the `plate` column is actually ignored.
```
a=>a.sort(([a,b],[c,d])=>b-d||a-c).map(v=>a=(n+=1-v[0]*2)<a?a:n,n=0)|a
```
### Test
```
let f =
a=>a.sort(([a,b],[c,d])=>b-d||a-c).map(v=>a=(n+=1-v[0]*2)<a?a:n,n=0)|a
console.log(f([
[1, 36000, 97845],
[1, 16500, 75487],
[0, 16, 12345],
[0, 3300, 75486],
[1, 6500, 12345],
[0, 32800, 97845],
[0, 16400, 12345],
[1, 16501, 97846],
[0, 16500, 97846],
[1, 8800, 75486],
[0, 3300, 75487]
]));
console.log(f([
[0, 16400, 12345],
[1, 16500, 12345],
[0, 16500, 75487],
[1, 16600, 75487]
]));
```
] |
[Question]
[
The goal of this challenge is to collect selected items in a list and move them to a certain location in the list.
As a visual example, take the input values (represented by black boxed integers) and a corresponding list of truthy values where true denotes the item is selected (represented by blue boxes, where `T` is truthy and `F` is falsy):
[](https://i.stack.imgur.com/MCJWf.png)
The first logical step is to separate the items marked truthy and not truthy into their corresponding lists. Note that relative order in each list must be maintained (i.e. the order of selected items must be `1,4,5`, and the order of unselected items must be `2,3,6,7`)!
[](https://i.stack.imgur.com/Q1YzH.png)
The second logical step is given an index in the remaining list of unselected items, insert all selected items before the item at the given index. Assuming indexing starts at 0, suppose you want to insert the selection at index 3. This corresponds to the spot before the `7` box, so the selected items should be inserted before the `7`.
[](https://i.stack.imgur.com/o1ios.png)
The final solution is then `2,3,6,1,4,5,7`.
Note that this logical diagram depicts one way this could be done; your program does not need to take the same logical steps as long as the output always produces the same observable result.
# Input
Your program is given 3 inputs:
1. A list of integers representing the items. This may be an empty list. This list will always consist of unique positive integers, not necessarily in sorted order (i.e. 5 will not be in the list twice).
2. A list of truthy/falsy values with the same length as the list of items, where a truthy value represents that the item at the same index has been selected.
3. An integer representing where to insert the selection. You may choose what the index of the first item of the list is as long as it is constant in every run of your program (e.g. the first item could be index 0 or index 1). Please specify which convention your program adheres to. This index should be in the range `[starting_idx, ending_idx+1]`, i.e. it will always be a valid index. For the case index is `ending_idx+1`, the selection should be inserted at the end of the list.
You may assume this integer will fit into your language's native integer type.
The input may come from any source desired (stdio, function parameter, etc.)
# Output
The output is a list representing the final sequence of items. This can be to any source desired (stdio, return value, function output parameter, etc.). You are allowed to modify any of the inputs in-place (for example, given a modify-able list as a function parameter, and having your function operate in-place on that list).
# Test cases
All of the following test cases assume 0-based indexing. I've used 0 and 1 to indicate falsy/truthy values respectively for the selection mask.
Test cases happen to have lists formatted as `[a,b,c]`, but as long as your input lists represent a finite ordered sequence that's fine.
**Input:**
```
[]
[]
0
```
**Output:**
```
[]
```
**Input:**
```
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
3
```
**Output:**
```
[2,3,6,1,4,5,7]
```
**Input:**
```
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
0
```
**Output:**
```
[1,4,5,2,3,6,7]
```
**Input:**
```
[1,2,3,4,5,6,7]
[1,0,0,1,1,0,0]
4
```
**Output:**
```
[2,3,6,7,1,4,5]
```
**Input:**
```
[1,2,3,4,5,6,7]
[1,1,1,1,1,1,1]
0
```
**Output:**
```
[1,2,3,4,5,6,7]
```
**Input:**
```
[1,2,3,4,5,6,7]
[0,0,0,0,0,0,0]
5
```
**Output:**
```
[1,2,3,4,5,6,7]
```
**Input:**
```
[1,3,2,5,4,6]
[1,0,0,1,1,0]
3
```
**Output:**
```
[3,2,6,1,5,4]
```
# Scoring
This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You are allowed to use any built-ins desired.
[Answer]
# MATL, 9 bytes
```
&)i:&)bwv
```
This solution accepts an array of `T` (true) and `F` (false) values as the second input. Also for the first test case, with empty arrays, it produces no output.
[**Try it Online!**](http://matl.tryitonline.net/#code=JilpOiYpYnd2&input=WzEsMiwzLDQsNSw2LDddCltULEYsRixULFQsRixGXQoz) and a slightly modified version for all [test cases.](http://matl.tryitonline.net/#code=YAomKWk6Jilid3YKIURUXQ&input=W10KW10KMApbMSwyLDMsNCw1LDYsN10KW1QgRiBGIFQgVCBGIEZdCjMKWzEsMiwzLDQsNSw2LDddCltULEYsRixULFQsRixGXQowClsxLDIsMyw0LDUsNiw3XQpbVCxGLEYsVCxULEYsRl0KNApbMSwyLDMsNCw1LDYsN10KW1QsVCxULFQsVCxULFRdCjAKWzEsMiwzLDQsNSw2LDddCltGLEYsRixGLEYsRixGXQo1ClsxLDMsMiw1LDQsNl0KW1QsRixGLFQsVCxGXQoz)
**Explanation**
```
% Implicitly grab the first two inputs
&) % Index into the first array using the boolean, places two items on the stack:
% 1) The values where the boolean is TRUE and 2) the values where it is FALSE.
i % Explicitly grab the third input (N)
: % Create an array from 1...N
&) % Index into the FALSE group using this array as an index. Puts two items on the stack:
% 1) The first N elements of the FALSE group and 2) other members of the FALSE group
b % Bubble the TRUE members up to the top of the stack
w % Flip the top two stack elements to get things in the right order
v % Vertically concatenate all arrays on the stack
% Implicitly display the result
```
[Answer]
# Mathematica, ~~66~~ 62 bytes
Saved 4 bytes from [@MartinEnder](http://ppcg.lol/users/8478).
```
a=#2~Extract~Position[#3,#4>0]&;##&@@@Insert[##~a~0,##~a~1,#]&
```
Anonymous function. Takes the 1-based index, the list, and the markers as input and returns the reordered list as output.
[Answer]
## Haskell, 70 bytes
```
m%n=[e|(e,b)<-zip m n,b]
(l#s)p|(h,t)<-splitAt p$l%(not<$>s)=h++l%s++t
```
Usage example: `([1,2,3,4,5,6,7]#[True,False,False,True,True,False,False]) 3` -> `[2,3,6,1,4,5,7]`.
How it works:
```
m%n=[e|(e,b)<-zip m n,b] -- helper function, that extracts the elements of m
-- with corresponding True values in n
(l#s)p -- l: list of values
s: list of booleans
p: position to insert
| (not<$>s) -- negate the booleans in s
l% -- extract elements of l
splitAt p -- split this list at index p
(h,t)<- -- bind h to the part before the split
-- t to the part after the split
= h++l%s++t -- insert elements at True positions between h and t
```
[Answer]
## JavaScript (ES6), 76 bytes
```
(a,b,c)=>(d=a.filter((_,i)=>!b[i]),d.splice(c,0,...a.filter((_,i)=>b[i])),d)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
¬+\>⁵Ḥ³oỤị
```
[Try it online!](http://jelly.tryitonline.net/#code=wqwrXD7igbXhuKTCs2_hu6Thu4s&input=&args=WzEsMCwwLDEsMSwwXQ+WzEsMywyLDUsNCw2XQ+Mw)
### How it works
```
¬+\>⁵Ḥ³oỤị Main link.
Arguments: x (list of Booleans), y (list of inputs), z (index)
¬ Logical NOT; invert all Booleans in x.
+\ Take the cumulative sum.
This replaces each entry with the number of zeroes up to that entry.
>⁵ Compare the results with z.
This yields 0 for the first z zeroes, 1 for all others. The behavior
for ones is not important.
Ḥ Unhalve; multiply the previous resulting by 2.
³o Take the element-wise logical NOT of x and the previous result.
This replaces all but the first z zeroes in x with twos.
Ụ Grade up; sort the indices of the result according to the corr. values.
ị Retrieve the items of y at those indices.
```
[Answer]
## C#, 132 bytes
```
int[]r(int[]a,bool[]b,int l){var x=a.Where((i,j)=>!b[j]);return x.Take(l).Concat(a.Where((i,j)=>b[j])).Concat(x.Skip(l)).ToArray();}
```
**ungolfed:**
```
public static int[] r(int[] a,bool[] b,int l)
{
var x = a.Where((i, j) => !b[j]);
return x.Take(l).Concat(a.Where((i, j) => b[j])).Concat(x.Skip(l)).ToArray();
}
```
improvement ideas appreciated.
[Answer]
# Python 3, 91 bytes
```
def f(a,x,i):b=[c for c,z in zip(a,x)if z<1];return b[:i]+[c for c in a if(c in b)<1]+b[i:]
```
where `a` is the elements/numbers list,`x` is the `True/False` list and `i` is the index.
Multiline version for improved readability:
```
def f(a,x,i):
b=[c for c,z in zip(a,x)if z<1]
return b[:i]+[c for c in a if(c in b)<1]+b[i:]
```
How does it work?
The call to `zip(a,x)` results in a list of tuples where each of them contains the info: `(element,0|1)`. Then a list comprehension is used to determine the elements that have a `0/False` value associated and stores them in the variable `b`.
So `[c for c,z in zip(a,x)if z<1]` creates a list that contains all the elements that have a `0`(`False`) value associated.
After that, the list of elements which have a `True|1` value associated (which is determined by checking which elements of `a` are not present in `b` : `[c for c in a if(c in b)<1]`) is inserted in the list with all the elements that have a `0`(`False`) value associated (list `b`) at the specified index `i` and the resulting list is returned.
[Answer]
## Python 3, 106 93 bytes
```
def f(x,y,z):
t,f=[],[]
for n in range(len(x)):(f,t)[y[n]].append(x[n])
f[z:z]=t
return f
```
Older version:
```
def f(x,y,z):
t,f=[],[]
for n in range(len(x)):
if y[n]:t+=[x[n]]
else:f+=[x[n]]
f[z:z]=t
return f
```
] |
[Question]
[
Given a list of integers, output the number of permutations of the integers, with indistinguishable permutations counted once. If there are `n` integers, and each group of indistinguishable numbers has length `n_i`, this is `n! / (n_1! * n_2! * ...)`
## Rules
* Input will be some form of list as arguments to a function or the program with 1 to 12 non-negative integers.
* Output will be printing or returning the number of permutations as described above.
* No standard loopholes or built-in functions (generating permutations, combinations, etc.). Factorials are allowed.
## Test Cases
**Inputs:**
```
1, 3000, 2, 2, 8
1, 1, 1
2, 4, 3, 2, 3, 4, 4, 4, 4, 4, 1, 1
```
**Outputs:**
```
60
1
83160
```
[Answer]
## Python, 48 bytes
```
f=lambda l:l==[]or len(l)*f(l[1:])/l.count(l[0])
```
A recursive implementation.
In the formula, `n! / (n_1! * n_2! * ...)`, if we remove the first element (say it's `1`), the number of permutation for the remaining `n-1` elements is
```
(n-1)! / ((n_1-1)! * n_2! * ...) ==
n! / n / (n_1! / n_1! * n_2! * ...) ==
n/n_1 * (n! / (n_1! * n_2! * ...)`)
```
So, we get the answer by multiplying by `n/n1`, the reciprocal-fraction of elements that equal the first one, by the recursive result for the rest of the list. The empty list gives the base case of 1.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ ~~13~~ 12 bytes
```
fpGu"@G=s:p/
```
[**Try it online!**](https://tio.run/##y00syfn/P63AvVTJwd222KpA////aCMdBRMdBWMdBSMwaYKKDIEoFgA)
### Explanation
The approach is very similar to that in [@Adnan's answer](https://codegolf.stackexchange.com/a/78402/36398).
```
f % Take input implicitly. Push array of indices of nonzero entries.
% This gives [1 2 ... n] where n is input length.
p % Product (compute factorial)
Gu % Push input. Array of its unique elements
" % For each of those unique values
@ % Push unique value of current iteration
G=s % Number of times (s) it's present (=) in the input (G)
:p % Range, product (compute factorial)
/ % Divide
% End for each implicitly. Display implicitly
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ ~~14~~ 13 bytes
Code:
```
D©g!rÙv®yQO!/
```
Explanation:
```
# implicit input
D© # duplicate and save a copy to register
g! # factorial of input length (total nr of permutations without duplicates)
rÙv # for each unique number in input
®yQO! # factorial of number of occurances in input
/ # divide total nr of permutations by this
# implicit output
```
Uses **CP-1252** encoding.
[Try it online!](http://05ab1e.tryitonline.net/#code=RMKpZyFyw5l2wq55UU8hLw&input=WzIsIDQsIDMsIDIsIDMsIDQsIDQsIDQsIDQsIDQsIDEsIDFd).
[Answer]
## JavaScript (ES6), ~~64~~ 61 bytes
```
a=>a.sort().map((x,i)=>r=r*++i/(x-y?(y=x,c=1):++c),y=r=-1)|-r
```
Uses the formula given, except calculating each factorial incrementally (so for example the `r=r*++i` effectively calcluates `n!`).
Edit: Originally I accepted any finite numbers but I saved 3 bytes when @user81655 pointed out that I only needed to support positive integers (although I actually accept non-negative integers).
[Answer]
# Pyth, 11 bytes
```
/.!lQ*F/V._
```
[Test suite](https://pyth.herokuapp.com/?code=%2F.%21lQ%2aF%2FV._&test_suite=1&test_suite_input=1%2C+3000%2C+2%2C+2%2C+8%0A1%2C+1%2C+1%0A2%2C+4%2C+3%2C+2%2C+3%2C+4%2C+4%2C+4%2C+4%2C+4%2C+1%2C+1&debug=0)
Uses the standard formula, `n! / (count1! * count2! * ...)`, except that the factorials of the counts are found by counting how many times each element occurs in the prefix leading up to that, then multiplying all such numbers together.
Explanation:
```
/.!lQ*F/V._
/.!lQ*F/V._QQ Implicit variable introduction.
Q = eval(input())
._Q Form all prefixes of the input.
/V Q Count how many times each element occurs in the prefix
ending with that element.
*F Fold on multiplication - take the product.
.!lQ Take the factorial of the input length
/ Divide.
```
[Answer]
# Pyth - ~~14~~ 12 bytes
```
/F.!M+lQ/LQ{
```
[Test Suite](http://pyth.herokuapp.com/?code=%2FF.%21M%2BlQ%2FLQ%7B&test_suite=1&test_suite_input=1%2C+3%2C+2%2C+2%2C+8%0A1%2C+1%2C+1%0A2%2C+4%2C+3%2C+2%2C+3%2C+4%2C+4%2C+4%2C+4%2C+4%2C+1%2C+1&debug=0).
[Answer]
# Ruby, ~~75~~ 74 bytes
Kinda wish that Ruby's `Math` module had a factorial function so I didn't have to build my own.
```
->l{f=->x{x<2?1:x*f[x-1]};l.uniq.map{|e|f[l.count e]}.inject f[l.size],:/}
```
[Answer]
## CJam, 17 bytes
```
q~_,\$e`0f=+:m!:/
```
[Test it here.](http://cjam.aditsu.net/#code=q~_%2C%5C%24e%600f%3D%2B%3Am!%3A%2F&input=%5B2%204%203%202%203%204%204%204%204%204%201%201%5D)
### Explanation
```
q~ e# Read input and evaluate.
_, e# Duplicate and get length.
\$ e# Swap with other copy and sort it.
e` e# Run-length encode. Since the list is sorted, this tallies the numbers.
0f= e# Select the tally of each number.
+ e# Prepend the length of the input.
:m! e# Compute the factorial of each number in the list.
:/ e# Fold division over it, which divides each factorial of a tally into
e# the factorial of the length.
```
[Answer]
# Jelly, 8 bytes
```
W;ĠL€!:/
```
[Try it online!](http://jelly.tryitonline.net/#code=VzvEoEzigqwhOi8&input=&args=MSwgMzAwMCwgMiwgMiwgOA)
```
W;ĠL€!:/ example input: [1, 3000, 2, 2, 8]
W wrap: [[1, 3000, 2, 2, 8]]
Ġ group index by appearance: [[1], [3, 4], [5], [2]]
; concatenate: [[1, 3000, 2, 2, 8], [1], [3, 4], [5], [2]]
L€ map by length: [5, 1, 2, 1, 1]
! [map by] factorial: [120, 1, 2, 1, 1]
:/ reduce by division: 120÷1÷2÷1÷1 = 60
```
[Answer]
# J, 13 bytes
```
#(%*/)&:!#/.~
```
## Usage
```
f =: #(%*/)&:!#/.~
f 1 3000 2 2 8
60
f 1 1 1
1
f 2 4 3 2 3 4 4 4 4 4 1 1
83160
```
## Explanation
```
#(%*/)&:!#/.~ Input: A
#/.~ Partition A by equal values and get the size of each, these are the tallies
# Get the size of A
&:! Take the factorial of both the size and the tallies
*/ Reduce using multiplication the factorial of the tallies
% Divide the factorial of the size by that product and return
```
] |
[Question]
[
Given an integer *N*, count how many ways it can be expressed as a product of *M* integers > 1.
Input is simply *N* and *M*, and output is the total count of *distinct* integer groups. Meaning you can use an integer more than once, but each group must be distinct (`3 x 2 x 2` would not count if `2 x 2 x 3` is present).
**Constraints**
1 < *N* < 231
1 < *M* < 30
**Examples**
Input `30 2` gives output `3`, since it can be expressed 3 ways:
```
2 x 15
3 x 10
5 x 6
```
Input `16 3` gives output `1`, since there's only one distinct group:
```
2 x 2 x 4
```
Input `2310 4` gives output `10`:
```
5 x 6 x 7 x 11
3 x 7 x 10 x 11
3 x 5 x 11 x 14
3 x 5 x 7 x 22
2 x 7 x 11 x 15
2 x 5 x 11 x 21
2 x 5 x 7 x 33
2 x 3 x 11 x 35
2 x 3 x 7 x 55
2 x 3 x 5 x 77
```
Input `15 4` gives output `0`, since it cannot be done.
**Rules**
Standard code golf loopholes apply, along with standard definitions for input/output. Answers may be a function or full program. Built-in functions for factorization and/or partitioning are not allowed, but others are fine. Code is counted in bytes.
[Answer]
# Python 3, 59
```
f=lambda N,M,i=2:i<=N and f(N/i,M-1,i)+f(N,M,i+1)or-~M==N<2
```
We count up potential divisors `i`. With the additional argument `i` as the lowest allowed divisor, the core recursive relation is
```
f(N,M,i)=f(N/i,M-1,i)+f(N,M,i+1)
```
For each `i`, we either choose to include it (possible as a repeat), in which case we divide the required product `N` by `i` and decrement `M`. If we don't, we increase `i` by 1, but only if `i<N`, since there's no use checking divisors greater than `N`.
When the minimum divisor `i` exceeds `N`, there's no more potential divisors. So, we check if we've succeeded by seeing if `M==0 and N==1`, or, equivalently, `M+1==N==1` or `M+1==N<2`, since when `M+1==N`, the mutual value is guaranteed to be a positive integer (thanks to FryAmTheEggman for this optimization).
This code will cause a stack overflow for `N` about 1000 on most systems, but you can run it in [Stackless Python](http://www.stackless.com/) to avoid this. Moreover, it is extremely slow because of its exponential recursive branching.
[Answer]
# [Pyth](http://pyth.herokuapp.com) - 24 23 22 21 bytes
Not a complicated solution. Will be golfing more. Just takes cartesian product of lists and filters. Same strategy as @optimizer (I'm guessing because of his comment, didn't actually decipher that CJam) Thanks to @FryAmTheEggman for 2 bytes and trick with M.
```
Ml{m`Sdfqu*GHT1G^r2GH
```
Defines a function `g` with args `G` and `H`
```
M function definition of g with args G and H
l length of
{ set (eliminates duplicates)
m map
`Sd repr of sorted factors so can run set (on bash escape ` as \`)
f filter
q G equals first arg
u*GHT1 reduce by multiplication
^ H cartesian product by repeat second arg
r2G range 2 to first arg
```
Worked on all test args except last, was too slow on that one but there is no time limit given.
[Answer]
# Ruby, 67
```
f=->n,m,s=2,r=0{m<2?1:s.upto(n**0.5){|d|n%d<1&&r+=f[n/d,m-1,d]}&&r}
```
Actually reasonably efficient for a recursive definition. For each divisor pair `[d,q]` of n, with `d` being the smaller one, we sum the result of `f[q,m-1]`. The tricky part is that in the inner calls, we limit factors to ones greater than or equal to d so that we don't end up double-counting.
```
1.9.3-p327 :002 > f[30,2]
=> 3
1.9.3-p327 :003 > f[2310,4]
=> 10
1.9.3-p327 :004 > f[15,4]
=> 0
1.9.3-p327 :005 > f[9,2]
=> 1
```
[Answer]
# CJam, 48 bytes
This can be a lot shorter but I have added certain checks to make it work for decent number of `M` on the online compiler.
```
q~\:N),2>{N\%!},a*{_,2/)<m*{(+$}%}*{1a+:*N=},_&,
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
## T-SQL ~~456~~ 373
I'm sure this'll break when the inputs are even close to being large.
Thanks to @MickyT for helping to save a lot of characters with CONCAT and SELECTing instead of multiple SETs.
```
CREATE PROC Q(@N INT,@M INT)AS
DECLARE @ INT=2,@C VARCHAR(MAX)='SELECT COUNT(*)FROM # A1',@D VARCHAR(MAX)=' WHERE A1.A',@E VARCHAR(MAX)=''CREATE TABLE #(A INT)WHILE @<@N
BEGIN
INSERT INTO # VALUES(@)SET @+=1
END
SET @=1
WHILE @<@M
BEGIN
SELECT @+=1,@C+=CONCAT(',# A',@),@D+=CONCAT('*A',@,'.A'),@E+=CONCAT(' AND A',@-1,'.A<=A',@,'.A')END
SET @C+=CONCAT(@D,'=',@N,@E)EXEC(@C)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ḍƇ`ḊœċP€ċ⁸
```
[Try it online!](https://tio.run/##y0rNyan8///hjt5j7QkPd3QdnXykO@BR05oj3Y8ad/w/vFzp//9oYwMdBUMzHQUjY0MQyzT2f7SRjoKxjoIJEMUCAA "Jelly – Try It Online")
Assumes that "Built-in functions for factorization and/or partitioning are not allowed" doesn't prohibit the `œċ` builtin, which is combinations with replacements. If this isn't allowed, we can use a Cartesian product builtin, which [is allowed](https://codegolf.stackexchange.com/questions/44983/how-many-ways-to-write-n-as-a-product-of-m-integers/210937#comment105858_44983), for 12 bytes: [`ḍƇ`ḊṗṢ€QP€ċ⁸`](https://tio.run/##y0rNyan8///hjt5j7QkPd3Q93Dn94c5Fj5rWBAYAiSPdjxp3/D@8XOn//2hjAx0FQzMgNo39H22ko2Cso2ASCwA)
## How it works
```
ḍƇ`ḊœċP€ċ⁸ - Main link. Takes n on the left and m on the right
Ƈ - Filter the integers, k, between 1 and n where the following is true:
ḍ - Does k divide...
` - ...n?
- This gives a list of divisors
Ḋ - Remove the first value, 1
œċ - Take all combinations of length m, with replacement
P€ - Take the product of each
ċ⁸ - Count occurrences of n
```
] |
[Question]
[
Your mission is to write a function/program that converts an array of bytes (i.e: an array of integers from 0 to 255), to base64.
Using built-in base64 encoders is not allowed.
The required base64 implementation is RFC 2045. (using "+", "/", and mandatory padding with "=")
Shortest code (in bytes) wins!
## Example:
Input (int array): `[99, 97, 102, 195, 169]`
Output (string): `Y2Fmw6k=`
[Answer]
# JavaScript, 177 ~~187~~ ~~198~~ characters
```
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87)))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}
```
For adding linebreaks, `\r\n`, after each 76th character, add 23 characters to the code:
```
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}
```
Demo code:
```
var encode = function(d,a,e,b,c,f){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c};
//OP test case
console.log(encode([99, 97, 102, 195, 169])); // outputs "Y2Fmw6k=".
//Quote from Hobbes' Leviathan:
console.log(
encode(
("Man is distinguished, not only by his reason, but by this singular passion from " +
"other animals, which is a lust of the mind, that by a perseverance of delight " +
"in the continued and indefatigable generation of knowledge, exceeds the short " +
"vehemence of any carnal pleasure.")
.split('').map(function(i){return i.charCodeAt(0)})
)
);
```
[Answer]
# C, 276 bytes
Quite a bump of this thread but I came up with this question myself a few days ago, then found out about code golfing, then found out about this thread.
Takes the 0-255 int array as first console arg (just a string). Uses K&R C style function parameter declaration and RFC 2045 encoding (except with no 76-character limit).
```
#define u(_)unsigned _:6;
b(i,j){putchar(j?i>61?43+i%2*4:i+65+6*(i>25)-75*(i>51):61);}i=-3;main(o,c)char**c;{char*s=c[1];for(;(i+=3)<strlen(s);){union{struct{u(a)u(b)u(c)u(d)};char s[3];}a;a.s[2]=s[i];a.s[1]=s[i+1];*a.s=s[i+2];b(a.d);b(a.c);b(a.b,a.s[1]);b(a.a,a.s[1]**a.s);}}
```
More 'readable' version of the algorithm (it was originally more clear but I started obfusc-golfing it right away so it turned out like this):
```
#include <stdio.h>
#include <string.h>
void b64_char(int i) {
putchar(i>61?43+i%2*4:i+65+6*(i>25)-75*(i>51));
}
int i=-3;
int main(int argc, char* argv[]) {
char* str = argv[1];
for (;(i+=3)<strlen(str);) {
union {
struct {unsigned a:6; unsigned b:6; unsigned c:6; unsigned d:6;};
char s[3];
} a;
a.s[2]=str[i];
a.s[1]=str[i+1];
a.s[0]=str[i+2];
b64_char(a.d);
b64_char(a.c);
a.s[1]?b64_char(a.b):putchar(61);
a.s[0]&&a.s[1]?b64_char(a.a):putchar(61);
}
return 0;
}
```
Defining the Base64 symbol table like that saved me a bunch of bytes.
Basically taking advantage of the consecutiveness of letters in ASCII.
Also, architecture dependent since it only works on little endian machines, and fails non-deterministically when the unpassed parameter for the function `b(2)` happens to be 0.
This would have been a lot shorter on a big endian machine.
Can anybody shorten this any further?
[Answer]
## 32-bit x86 assembly, 59 bytes
Byte-code:
```
66 B8 0D 0A 66 AB 6A 14 5A 4A 74 F4 AD 4E 45 0F C8 6A 04 59 C1 C0 06 24 3F 3C 3E 72 05 C0
E0 02 2C 0E 2C 04 3C 30 7D 08 04 45 3C 5A 76 02 04 06 AA 4D E0 E0 75 D3 B0 3D F3 AA C3
```
Disassembly:
```
b64_newline:
mov ax, 0a0dh
stosw
b64encode:
push (76 shr 2) + 1
pop edx
b64_outer:
dec edx
je b64_newline
lodsd
dec esi
inc ebp
bswap eax
push 4
pop ecx
b64_inner:
rol eax, 6
and al, 3fh
cmp al, 3eh
jb b64_testchar
shl al, 2 ;'+' and '/' differ by only 1 bit
sub al, ((3eh shl 2) + 'A' - '+') and 0ffh
b64_testchar:
sub al, 4
cmp al, '0'
jnl b64_store ;l not b because '/' is still < 0 here
add al, 'A' + 4
cmp al, 'Z'
jbe b64_store
add al, 'a' - 'Z' - 1
b64_store:
stosb
dec ebp
loopne b64_inner
jne b64_outer
mov al, '='
rep stosb
ret
```
Call b64encode with esi pointing to input buffer, edi pointing to output buffer.
It could be made even smaller if line-wrapping is not used.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~118~~ ~~114~~ ~~93~~ ~~82~~ ~~73~~ 61 bytes
```
C76ΣtTT'=C4§o↓_ȯa%_3L(mo!ṁ…w"AZ az 09 + /"→B64B256ΣTT0C3+R3 4
```
[Try it online!](https://tio.run/##yygtzv7/39nc7NzikpAQdVtnk0PL8x@1TY4/sT5RNd7YRyM3X/HhzsZHDcvKlRyjFBKrFAwsFbQV9JUetU1yMjNxMjIF6gwJMXA21g4yVjD5//9/tKGBhY6hgSkQGwOxiY6hoZmOsRGQsgRiQyAGChmY65iYxQIA "Husk – Try It Online")
## Examples
* []:LN "" (LN is a type hint for list of numbers)
* [0] "AA=="
* [99,97,102,195,169] "Y2Fmw6k="
* [108,105,103,104,116,32,119,111,114,107,46] "bGlnaHQgd29yay4="
## How it works
```
C76ΣtTT'=C4§o↓_ȯa%_3L(mo!ṁ…w"AZ az 09 + /"→B64B256ΣTT0C3+R3 4
§ Main fork combinator.
+R3 4 Begin first branch of the fork. Prepend 3 4s to deal with leading zeros.
ΣTT0C3 Chop into 3-byte chunks. Transpose with 0 padding, transpose back, and flatten.
B64B256 Interpret as base 256, then as base 64.
(mo!ṁ…w"AZ az 09 + /"→ Map the following: increment (Husk is 1-based) and index into the base 64 alphabet. End first branch of fork.
ȯa%_3L Second branch of the fork: padding = abs(length mod -3)
o↓_ Converge the fork on this function: Drop padding number of characters from the end of the base 64 encoded string.
ΣtTT'=C4 Chop into 4-character chunks, transpose with '=' padding, transpose back, drop the first chunk, and flatten.
C76 Chop the encoded string into 76-character chunks which will be joined with '\r\n' automatically.
```
This is my first code-golf submission and I would appreciate any help from the Husk experts here!
Thank you Leo for your help with the 61-byte version!!
[Answer]
# Excel 2016+, ~~209~~ 205 Bytes
An anonymous function that take input as a dynamic, spilled or legacy array from range `A1#` and outputs to the calling cell.
```
=LET(c,COUNT(A1#),i,CONCAT(MID(CONCAT(CHAR({64;96}+COLUMN(A:Z)),"0123456789+/"),1+BIN2DEC(MID(CONCAT(BASE(A1#,2,8))&REPT("00",MOD(c,3)),SEQUENCE(4*c/3+.7,,,6),6)),1)),j,MOD(LEN(i),4),i&REPT("=",IF(j,4-j)))
```
## Ungolfed
```
=LET( ' Begin Variable block
c,COUNT(A1#), ' Def c(ount) with count of bytes in array
i,CONCAT( ' Def i helper var holding the string concatenated from
MID( ' Repeatedly splitting
CONCAT( ' The Base64 alphabet, made by concating
CHAR({64;96}+COLUMN(A:Z)), ' uppercase and lowercase alphas
"0123456789+/"), ' numbers and symbols
1+BIN2DEC( ' at index of 1+ decimal value from binary string obtained from
MID( ' splitting
CONCAT( ' the string concatenated from
BASE(A1#,2,8), ' the binary string array representation of input
REPT("00",MOD(c,3))), ' padded with `0` to lowest even multiple of 6 bits larger than c
SEQUENCE(4*c/3+.7,,,6), ' at every sixth char, for a total of ceil(4/3*count(input)) string
6)), ' making each substring be a binary string of 6 bits
1)), ' with length 1
j,MOD(LEN(i),4), ' Def j as the helper var holding length of i mod 4
i&REPT("=",IF(j,4-j))) ' Output i and `=` padding to a string length that is a multiple 4
```
[Answer]
# perl, 126 bytes
reads stdin, outputs to stdout
```
$/=$\;print map{$l=y///c/2%3;[A..Z,a..z,0..9,"+","/"]->[oct"0b".substr$_.0 x4,0,6],$l?"="x(3-$l):""}unpack("B*",<>)=~/.{1,6}/g
```
ungolfed:
```
my @x = ('A'..'Z','a'..'z',0..9,'+','/');
my $in = join '', <>;
my $bits = unpack 'B*', $in;
my @six_bit_groups = $bits =~ /.{1,6}/g;
for my $sixbits (@six_bit_groups) {
next unless defined $sixbits;
$l=length($sixbits)/2%3;
my $zero_padded = $sixbits . ( "0" x 4 );
my $padded_bits = substr( $zero_padded, 0, 6 );
my $six_bit_int = oct "0b" . $padded_bits;
print $x[$six_bit_int];
print "=" x (3 - $l) if $l;
}
```
[Answer]
# Perl, 147 bytes
```
sub b{$f=(3-($#_+1)%3)%3;$_=unpack'B*',pack'C*',@_;@r=map{(A..Z,a..z,0..9,'+','/')[oct"0b$_"]}/.{1,6}/g;$"='';join"\r\n",("@r".'='x$f)=~/.{1,76}/g}
```
The function takes a list of integers as input and outputs the string, base64 encoded.
**Example:**
```
print b(99, 97, 102, 195, 169)
```
prints
```
Y2Fmw6kA
```
**Ungolfed:**
Version that also visualizes the intermediate steps:
```
sub b {
# input array: @_
# number of elements: $#_ + 1 ($#_ is zero-based index of last element in
$fillbytes = (3 - ($#_ + 1) % 3) % 3;
# calculate the number for the needed fill bytes
print "fillbytes: $fillbytes\n";
$byte_string = pack 'C*', @_;
# the numbers are packed as octets to a binary string
# (binary string not printed)
$bit_string = unpack 'B*', $byte_string;
# the binary string is converted to its bit representation, a string wit
print "bit string: \"$bit_string\"\n";
@six_bit_strings = $bit_string =~ /.{1,6}/g;
# group in blocks of 6 bit
print "6-bit strings: [@six_bit_strings]\n";
@index_positions = map { oct"0b$_" } @six_bit_strings;
# convert bit string to number
print "index positions: [@index_positions]\n";
@alphabet = (A..Z,a..z,0..9,'+','/');
# the alphabet for base64
@output_chars = map { $alphabet[$_] } @index_positions;
# output characters with wrong last characters that entirely derived fro
print "output chars: [@output_chars]\n";
local $" = ''; #"
$output_string = "@output_chars";
# array to string without space between elements ($")
print "output string: \"$output_string\"\n";
$result = $output_string .= '=' x $fillbytes;
# add padding with trailing '=' characters
print "result: \"$result\"\n";
$formatted_result = join "\r\n", $result =~ /.{1,76}/g;
# maximum line length is 76 and line ends are "\r\n" according to RFC 2045
print "formatted result:\n$formatted_result\n";
return $formatted_result;
}
```
**Output:**
```
fillbytes: 1
bit string: "0110001101100001011001101100001110101001"
6-bit strings: [011000 110110 000101 100110 110000 111010 1001]
index positions: [24 54 5 38 48 58 9]
output chars: [Y 2 F m w 6 J]
output string: "Y2Fmw6J"
result: "Y2Fmw6J="
formatted result:
Y2Fmw6J=
```
**Tests:**
The test strings come from the example in the question the examples in the Wikipedia article for [Base64](https://en.wikipedia.org/w/index.php?title=Base64&oldid=606643350).
```
sub b{$f=(3-($#_+1)%3)%3;$_=unpack'B*',pack'C*',@_;@r=map{(A..Z,a..z,0..9,'+','/')[oct"0b$_"]}/.{1,6}/g;$"='';join"\r\n",("@r".'='x$f)=~/.{1,76}/g}
sub test ($) {
print b(map {ord($_)} $_[0] =~ /./sg), "\n\n";
}
my $str = <<'END_STR';
Man is distinguished, not only by his reason, but by this singular passion from
other animals, which is a lust of the mind, that by a perseverance of delight
in the continued and indefatigable generation of knowledge, exceeds the short
vehemence of any carnal pleasure.
END_STR
chomp $str;
test "\143\141\146\303\251";
test $str;
test "any carnal pleasure.";
test "any carnal pleasure";
test "any carnal pleasur";
test "any carnal pleasu";
test "any carnal pleas";
test "pleasure.";
test "leasure.";
test "easure.";
test "asure.";
test "sure.";
```
Test output:
```
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbQpvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodAppbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydAp2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZSO=
YW55IGNhcm5hbCBwbGVhc3VyZSO=
YW55IGNhcm5hbCBwbGVhc3VyZB==
YW55IGNhcm5hbCBwbGVhc3Vy
YW55IGNhcm5hbCBwbGVhc3F=
YW55IGNhcm5hbCBwbGVhcD==
cGxlYXN1cmUu
bGVhc3VyZSO=
ZWFzdXJlLC==
YXN1cmUu
c3VyZSO=
```
[Answer]
## Python, 234 chars
```
def F(s):
R=range;A=R(65,91)+R(97,123)+R(48,58)+[43,47];n=len(s);s+=[0,0];r='';i=0
while i<n:
if i%57<1:r+='\r\n'
for j in R(4):r+=chr(A[s[i]*65536+s[i+1]*256+s[i+2]>>18-6*j&63])
i+=3
k=-n%3
if k:r=r[:-k]+'='*k
return r[2:]
```
[Answer]
# GolfScript, 80 (77) bytes
```
~.,~)3%:P[0]*+[4]3*\+256base 64base{'+/''A[a{:0'{,^}/=}/{;}P*'='P*]4>76/"\r
":n*
```
The above will fit exactly 76 characters in a line, except for the last line. All lines are terminated by CRLF.
Note that RFC 2045 specifies a *variable, maximum* line length of 76 characters, so at the cost of pretty output, we can save 3 additional bytes.
```
~.,~)3%:P[0]*+[4]3*\+256base 64base{'+/''A[a{:0'{,^}/=}/{;}P*'='P*]4>{13]n+}/
```
The above will print one character per line, except for the last line, which can contain 0, 1 or 2 `=` chars. GolfScript will also append a final LF, which, according to RFC 2045, must be ignored by decoding software.
### Example
```
$ echo '[99 97 102 195 169]' | golfscript base64.gs | cat -A
Y2Fmw6k=^M$
$ echo [ {0..142} ] | golfscript base64.gs | cat -A
AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4^M$
OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3Bx^M$
cnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY4=^M$
$ echo '[99 97 102 195 169]' | golfscript base64-sneaky.gs | cat -A
Y^M$
2^M$
F^M$
m^M$
w^M$
6^M$
k^M$
=^M$
$
```
### How it works
```
~ # Interpret the input string.
.,~)3%:P # Calculate the number of bytes missing to yield a multiple of 3 and save in “P”.
[0]*+ # Append that many zero bytes to the input array.
[4]3*\+ # Prepend 3 bytes to the input array to avoid issues with leading zeros.
256base # Convert the input array into an integer.
64base # Convert that integer to base 64.
{ # For each digit:
'+/' # Push '+/'.
'A[a{:0' # Push 'A[a{:0'.
{ # For each byte in 'A[a{:0':
, # Push the array of all bytes up to that byte.
^ # Take the symmetric difference with the array below it.
}/ # Result: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
= # Retrieve the character corresponding to the digit.
}/ #
{;}P*'='P* # Replace the last “P” characters with a string containing that many “=” chars.
] # Collect all bytes on the stack into an array.
4> # Remove the first four, which correspond to the 3 prepended bytes.
76/ # Collect all bytes on the stack into an array and split into 76-byte chunks.
"\r\n":n* # Join the chunks with separator CRLF and save CRLF as the new line terminator.
```
[Answer]
# [PHP](https://php.net/), 200 bytes
```
<?foreach($g=$_GET as$k=>$v)$b[$k/3^0]+=256**(2-$k%3)*$v;for(;$i<62;)$s.=chr($i%26+[65,97,48][$i++/26]);foreach($b as$k=>$v)for($i=4;$i--;$p++)$r.=("$s+/=")[count($g)*4/3<$p?64:($v/64**$i)%64];echo$r;
```
[Try it online!](https://tio.run/##RY69boMwGEX3PEUVfUj@gRCMcUqNm6FCUZd2yYYISiwaLCRsmZSxb92Zkg7tfs8513VuLvauc6vWe@sb3zrrb2a4oq@yeXs/vr6UWK6gOZRHVeV5mO/CZMvCJM/CROS1nD@sb8@6Q3BVv6uH8wi9eoYJw6WCPk5P25oqlglCEIugD1JMYJILhiSYQjCJYdwo3XkEJmCCViK7V/hjXYGhNGaixvKvcvn33xVgFF80USTBUYrBbxRaw0hjtcaVtp/DbTmGCY/TAtxe8CcEUyw4IWBwIHgtW91Z8HKevwcb6SXR/gA "PHP – Try It Online")
You could replace the string `("$s+/=")` with an array `array_merge(range(A,Z),range(a,z),range(0,9),["+","/","="])`
Only to compare which byte count can reach with an not allowed built-in
[PHP](https://php.net/), 45 bytes
```
<?=base64_encode(join(array_map(chr,$_GET)));
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lEu/uGmIbbWmpY2muY2hgpGNoaapjaGYZa81lbwfUb5uUWJxqZhKfmpecn5KqkZWfmaeRWFSUWBmfm1igkZxRpAM2QVNT0/r/fwA "PHP – Try It Online")
[Answer]
## JavaScript (ES6), 220B
```
f=a=>{for(s=a.map(e=>('0000000'+e.toString(2)).slice(-8)).join(p='');s.length%6;p+='=')s+='00';return s.match(/.{6}/g).map(e=>'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[parseInt(e,2)]).join('')+p}
```
If your browser does not support ES6, you can try with this version (262B) :
```
function f(a){for(s=a.map(function(e){return ('0000000'+e.toString(2)).slice(-8)}).join(p='');s.length%6;p+='=')s+='00';return s.match(/.{6}/g).map(function(e){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[parseInt(e,2)]}).join('')+p}
```
`f([99, 97, 102, 195, 169])` returns `"Y2Fmw6k="`.
[Answer]
# Python - ~~310~~, 333
```
def e(b):
l=len;c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";r=p="";d=l(b)%3
if d>0:d=abs(d-3);p+="="*d;b+=[0]*d
for i in range(0,l(b)-1,3):
if l(r)%76==0:r+="\r\n"
n=(b[i]<<16)+(b[i+1]<<8)+b[i+2];x=(n>>18)&63,(n>>12)&63,(n>>6)&63,n&63;r+=c[x[0]]+c[x[1]]+c[x[2]]+c[x[3]]
return r[:l(r)-l(p)]+p
```
Somewhat ungolfed:
```
def e( b ):
c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
r = p = ""
d = len( b ) % 3
if d > 0:
d = abs( d - 3 )
p = "=" * d
b + = [0] * d
for i in range( 0, len( b ) - 1, 3 ):
if len( r ) % 76 == 0:
r += "\r\n"
n = ( b[i] << 16 ) + ( b[i + 1] << 8 ) + b[i + 2]
x = ( n >> 18 ) & 63, ( n >> 12 ) & 63, ( n >> 6) & 63, n & 63
r += c[x[0]] + c[x[1]] + c[x[2]] + c[x[3]]
return r[:len( r ) - len( p )] + p
```
**Example**:
Python's built-in base64 module is only used in this example to ensure the `e` function has the correct output, the `e` function itself isn't using it.
```
from base64 import encodestring as enc
test = [ 99, 97, 102, 195, 169 ]
str = "".join( chr( x ) for x in test )
control = enc( str ).strip()
output = e( test )
print output # => Y2Fmw6k=
print control == output # => True
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
s3z0Zµḅ⁹b64‘ịØb)FṖ³LN%3¤¡s4z”=Z;€“ƽ‘Ọ
```
[Try it online!](https://tio.run/##y0rNyan8/7/YuMog6tDWhztaHzXuTDIzedQw4@Hu7sMzkjTdHu6cdmizj5@q8aElhxYWm1Q9aphrG2X9qGnNo4Y5h9sO7QUr7fn//7@lpY6luY6hgZGOoaWpjqGZJQA "Jelly – Try It Online")
As (almost) every other answer covers the RFC2045 requirement of "at most 76 chars per line with line ending `\r\n`", I followed it.
### How it works
```
s3z0Zµḅ⁹b64‘ịØb)FṖ³LN%3¤¡s4z”=Z;€“ƽ‘Ọ Monadic main link. Input: list of bytes
s3z0Z Slice into 3-item chunks, transpose with 0 padding, transpose back
Equivalent to "pad to length 3n, then slice into chunks"
µḅ⁹b64‘ịØb) Convert each chunk to base64
ḅ⁹b64 Convert base 256 to integer, then to base 64
‘ịØb Increment (Jelly is 1-based) and index into base64 digits
FṖ³LN%3¤¡s4z”=Z Add correct "=" padding
F Flatten the list of strings to single string
Ṗ ¡ Repeat "remove last" n times, where
³LN%3¤ n = (- input length) % 3
s4z”=Z Pad "=" to length 4n, then slice into 4-item chunks
;€“ƽ‘Ọ Add "\r\n" line separator
;€ Append to each line:
“ƽ‘ Codepage-encoded list [13,10]
Ọ Apply `chr` to numbers; effectively add "\r\n"
```
] |
[Question]
[
Following my entry to the [Obfuscated Hello World](https://codegolf.stackexchange.com/a/3695/2764) I thought it might be fun to share the underlying code. But why just show the code, lets make it a golf too!
**Challenge**
Write a script that scrolls a string across the terminal, from right to left, settling on the left side.
**Input**
Takes a string as an argument.
**Result**
Prints the scrolling marquee to STDOUT. Max width of ~50 chars. Starts with 0 or 1 char showing. Some space between letters while scrolling. Stops when settled (having no extra space between word chars). Slow scroll, but not too slow (< 1s per iteration).
**Example**
Running script with arg `'Hello World'`
```
H
```
later
```
H e l l o W o
```
later
```
H e l l o W o r l d
```
later
```
Hell o W o r l d
```
finally
```
Hello World
```
For a running example, try my code from the "Hello World" challenge. ~~Eventually I will post mine. It currently is 202 chars in Perl.~~ Now that there are some competitors, I have posted mine in the answers.
**Winner**
I don't want the restrictions to be absolute, that's why I left them a little vague. The shortest script which follows the spirit of my original will win.
**Notes**
This game assumes `xterm` environment. Should another environment prove useful, only similar environments will be compared and a separate winner may be declared for each.
**Addendum (April 25, 2012)**
To address some budding issues, I'm making a ruling. Your character count must include code needed to:
1. Flush STDOUT (Looking at you Ruby)
2. Implement `sleep` with time delay of <1s (Looking at you Perl)
This may be done as command line switches to an interpreter, but those characters count in the total (sans surrounding whitespace).
[Answer]
## python 2 - 146 chars
edit: made it a function instead of input through stdin. first argument is the string, and the second argument is the length you want it to be. so invocation would be `f('Hello World', 50)`. I also made it much smoother; when each character 'landed' there was an awkward pause
```
import os,time
def f(x,n):
y=' '*n+' '.join(x);z=0
while y:w=y[0]==x[z];y=y[1+w:];z+=w;os.system('cls');print((x[:z]+y)[:n]);time.sleep(0.1)
```
old, 158 chars:
```
import os,time,sys
x=' '.join(sys.argv[1:])
y=' '*50+' '.join(x)
z=0
while y:z+=y[0]==x[z];y=y[1:];os.system('cls');print((x[:z]+y)[:50]);time.sleep(0.1)
```
[Answer]
### Ruby, 93 91 89 chars
```
u="\1";s=u*50+[*$*[0].chars]*(u*3);$><<s.tr(u," ")[0,50]+" \r"while s.sub!u,""*sleep(0.1)
```
The text to be displayed must be given as command line argument, e.g.
```
ruby marquee.rb "Hello World"
```
for the example shown above. Unfortunately I cannot show the animation here, so you have to try out the code yourself.
*Previous version:*
```
s=" "*67+[*$*[0].chars]*" ";(s.size*3/4).times{|j|s[j/3]='';$><<s[16,50]+" \r";sleep 0.1}
```
[Answer]
## C, 94 83 80 173 chars
EDIT: Added lots of code, implements all the requested functionality now.
The constant `1e8` can be tweaked to control the speed. On my machine, it's quite fast as it is.
Some characters can surely be saved here. `l` can be static (saves initialization), `c` can become a pointer (replacing `b+c`).
```
char b[99],c=1;
main(a,t,w,i,l)char**t;{
for(l=0;b[l++]=*t[1]++;b[l++]=32);
for(w=80;i--||
printf("\033[F\033[K%*.*s\n",w-=l<a,a++,b,i=1e8)>l+6||
b[++c]&&memmove(b+c-1,b+c,l););
}
```
Old version (80 chars), with partial functionality:
Saved a couple of chars by replacing `char**t` with `int*t`. Works fine in 32-bit (`int**t` would support 64-bit).
```
main(i,t,w)
int*t;
{
for(w=80;i--||printf("\033[F\033[K%*s\n",w,t[1],i=1e8)*--w;);
}
```
[Answer]
## K&R C -- ~~431~~ 416 characters
Respects the standard to a high degree. Uses ncurses so it should be largely terminal independent. There is a slight stuttering when the text hits the side due to some trickery played to preserve the intended whitespace in the string.
The string to use should be passed as the first argument on the command line (and should be escaped if it contains spaces, more so if it contains a `!` as my test string (`Hello, World!`) did).
```
#include <ncurses.h>
#include <unistd.h>
#define T usleep(1e5),S(l)
#define U mvprintw(23,0,"%s",l),refresh()
char l[63],*p,*q,r;
S(char*s){r=0;if(*s==32)q=s++;else{for(;*s-32||*(s+1)-32;s++);
for(q=s;*s==32;s++);(s-q)&1?s--:usleep(1e5);}
for(r=0;*s;*q++=*s++){*s-32?r=1:0;}return r;}
main(int c,char**v){initscr();curs_set(0);for(c=0;c<62;l[c++]=32);
for(p=*++v;*p;){l[52]=*p++;U;T;U;T;U;T;}for(;T;U);getch();endwin();}
```
In a more readable and commented form:
```
#include <ncurses.h>
#include <unistd.h>
char l[63] /* take advantage of 0 initialization */,
*p,*q, r;
/* Remove the first unwanted space. Unwanted means at the begining of
* the line, all of even length blocks between non-spaces, and
* all-bu-one of odd length blocks between non-spaces.
*
* Return true if the removed space occurs before a non-space character.
*/
S/*lide marquee*/(char*s){
r=0; /* initialize the return value */
if(*s==' '){
q=s++;
} else {
/* Find the start of first block of contiguous spaces */
for(;*s-' '||*(s+1)-' ';s++);
for(q=s;*s==' ';s++); /* q holds the start, s finds it's end */
/* if this block is even length remove all, if odd, all but one */
if( (s-q)%2 )s--; else usleep(1e5);
}
/* copy from s to q all the way to the end */
for(r=0;*s;*q++=*s++){
if(*s-' ')r=1; /* note if we pass a non-space */
}
return r;
}
main(int c,char**v){
initscr();curs_set(0); /* setup ncurses with invisible cursor */
for(c=0;c<62;l[c++]=' '); /* initialize l */
for(p=*++v;*p;){ /* load the message into the marque, skipping space */
l[52]=*p++;
mvprintw(23,0,"%s",l),
refresh();
usleep(1e5),
S(l);
usleep(1e5),
S(l);
usleep(1e5),
S(l);
}
for(;usleep(1e5),S(l);mvprintw(23,0,"%s",l),refresh()); /* keeping sliding until we're done. */
getch();
endwin();
}
```
[Answer]
# Perl 5.13.2, 96
```
$_=join$;x4,$;x46,split//,pop;print substr(s/$;/ /gr,0,50)." \r"while$|=s/$;//+select'','','',.1
```
Stealing a lot from @[Kevin Reid](https://codegolf.stackexchange.com/users/3994/kevin-reid)'s answer, especially the `/r` trick available in newer Perls.
## Perl, 115
Like @[Joel Berger](https://codegolf.stackexchange.com/users/2764/joel-berger)'s answer, this would become much shorter if I could use `sleep 1` and be slow, or pass `-MTime::HiRes=sleep` on the command line to enable `sleep.1`. Otherwise the only built-in way to get short sleeps is `select'','','',.1` which is pretty long.
```
$|=@_=(($")x45,map{($")x4,$_}split//,pop);for(0..$#_){print@_," \r";splice@_,($_-=45)<0?0:$_/4,1;select'','','',.1}
```
### ~~Perl, 128~~
```
$_=$"x9 .pop;s/./ $&/g;$.=-46;$\=" \r";while($|=/./g){print substr($_,0,50);pos=++$.<0?0:$./4;s/\G.//;select'','','',.1}print
```
### ~~Perl, 133~~
```
$|=@_=split//,pop;for$i(reverse-$#_..50){for(@_){print$"x($j||$i),$_;($i+=$j=($i++>0)*4)>50&&last}print" \r";$j=select'','','',.1}
```
[Answer]
## bash 234
```
w=$1
p(){
i=$1
s=$2
p=$((50+s*3-i))
((p<s+1)) && p=$((s+1));
((p<50)) && echo -en "\e[20;"${p}H$3" ";
}
clear
for i in {0..99}
do
for s in $(seq 0 ${#w})
do
p $i $s ${w:s:1}
done
sleep .1
echo -en "\e[20;1H "
done
echo -en "\b\b$w\n"
```
Usage:
```
./marquee.sh "Hello, fine marquee world"
```
ungolfed:
```
#!/bin/bash
w=$1
p(){
#si String index
it=$1
#it=iteration
si=$2
pos=$((50+(si*3)-it))
((pos<si+1 )) && pos=$((si+1));
((pos<50)) && echo -en "\e[20;"${pos}H$3" ";
}
clear
for it in {0..99}
do
for si in $(seq 0 ${#w})
do
p $it $si ${w:si:1}
done
sleep .1
echo -en "\e[20;1H "
done
echo -en "\e[22;1H"
```
[Answer]
## JavaScript ~~180~~ 218 chars
Production Version:
```
function f(){i--&&(i>50?h=h.substr(1):h=h.replace(" ",i==16?" ":""),document.body.innerHTML="<pre>"+h.substr(0,50)+"</pre>",setTimeout(f,99))}h=(new Array(50)).join(" ")+"HelloWorld".split("").join(" "),i=80,f()
```
Ungolfed Version:
```
h=new Array(50).join(" ")+("HelloWorld".split("").join(" "));
i=80;
function f(){
if(i--){
if(i>50){
h=h.substr(1);
}else{
h=h.replace(" ",(i==16)?" ":"");
}
document.body.innerHTML="<pre>"+h.substr(0,50)+"</pre>";
setTimeout(f,99);
}
}
f();
```
Here is a [jsFiddle Demo](http://jsfiddle.net/fYvg7/3/)
**Note:** if you try to reproduce it, make sure the code is below the body
[Answer]
## Perl 5.13.2, 115 characters
```
$_=$"x9 .pop=~y/ /\0/r;s/./ $&/g;print(y/\0/ /r=~/(.{50})/,"\r"),select$.,$.,$.,.02while$|=s/ (\S)/$1 /g;print$/
```
* Warning-clean.
* Can be squeezed a bit by reducing the space between characters or the initial whitespace.
* Requires Perl 5.13.2 or newer due to use of `/r`.
* The substitution to NUL to preserve spaces is unambiguous since POSIX argv is not NUL-clean. However, the loop substitution will turn any other whitespace into nothing (eventually).
Credits:
* `$"` as a source of `" "` taken from [ephemient's answer](https://codegolf.stackexchange.com/questions/5277/scrolling-marquee/5322#5322), reduction by 1 character.
[Answer]
## R, 319 characters
Following the philosophy of @Blazer example (d is the delay in sec):
```
f=function(x,n=50,d=0.2){
s=strsplit(x,"")[[1]];i=1;l=length
while (i<(n+l(s)-1)){
if(i<=l(s))cat(rep(" ", n-i),s[1:i])
else if((i<=n)&&(i>l(s)))cat(rep(" ", n-i),s[1:l(s)])
else cat(paste(s[1:(i-n+1)],collapse=""),s[(i-n+2):l(s)])
Sys.sleep(d);system("clear");i=i+1
}
cat(paste(s[1:l(s)],collapse=""))
}
```
Usage:
```
f("Hello World",n=20,d=0.2)
```
[Answer]
**Perl**: ~~144~~ 133
```
$|=@s=(($")x50,map{$_,($")x4}@i=split//,pop);{$n=0;$s[$n]ne$_?last:$n++for@i;splice@s,$n,1;print"\r",@s[0..50];sleep.1;$n!=@i&&redo}
```
In order to get the sleep of <1s though you need to run as:
```
perl -MTime::HiRes=sleep scriptname 'string to print'
```
Since I won't declare myself winner I won't argue myself over what counts there or not (but I really can't have Ruby win this ;-) )
[Answer]
# Q,145
Doesn't exactly meet the requirements because the final line removes all the spaces that were in the original input string.
```
{c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}
```
It takes two arguments, input string and scroll speed
```
q){c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}["hello";0.05]
h
h
h
h e
h e
h e
h e l
h e l
h e l
h e l l
h e l l
h e l l
h e l l o
h e l l o
h e l l o
he l l o
he l l o
hel l o
hel l o
hell o
hell o
hello
```
[Answer]
### PowerShell, 135
Not very golfed and probably a horrible approach, but I'm sick and can't really think ...
```
for($x="`r"+' '*50;$y-ne$x){$y=$x
write-host($x=$x-replace' ([^ ])','$1 ')-n
if(!($t++%5)){$x=$x-replace'.$',"$args"[$i++]}sleep -m 99}
```
[Answer]
## J (116)
```
s(echo@((50#LF)&,)@([[i.@]&2e7)@(50&{.)@;@:(([,~#&' '@])&.>))"1([-=&0@/:@\:@:~:&0)^:(i.>:+/k)k=.50,3#~<:#s=.>2{ARGV
```
Takes the input string on the command line, i.e. `jconsole marquee.ijs 'Hello, world!'`
If it doesn't need to clear the screen, i.e. output like this:
```
H e l l o
H e l l o
He l l o
He l l o
...
```
is allowed, it would be 12 characters shorter.
Explanation:
* `s.=>2{ARGV`: get the string from the command line
* `k.=50,3#~<:#s`: the starting amount of whitespace added before each character, 50 before the first one and 3 before all the others. (gives an array, '50 3 3 3...')
* `([-=&0@/:@\:@~:&0)`: given an array, decrements the first nonzero item in the array
* `^:(i.>:+/k)`: this function applied N times, where N is 0 upto the sum of the amount of added whitespace. (gives a matrix: `50 3 3 3; 49 3 3 3; 48 3 3 3; ... 0 0 0 1; 0 0 0 0)`.
* `"1`: run following function on each row of the matrix
* `;@:(([,~#&' '@])@.>)`: add the given amount of spaces before each character in the string
* `(50&{.)`: take the first 50 characters of the string
* `([[i.@]&2e7)`: a function that generates the list from 0 to 2\*10^7, and then throws it away. This takes about a third of a second on my machine, this causes the delay.
* `((50#LF)&,)`: add 50 newlines before the string, to clear the screen
* `echo`: output the string
* `s (...)`: give the string as the left argument to the function
[Answer]
## APL (70)
```
{⎕SM∘←1,⍨1,⍨,/D{⍺,⍨⍵⍴⍕⍬}¨P←⍵-{⍵×~×⍺}\×⍵⊣⎕DL÷8⋄0∨.≠P:∇P}1↓⎕SD,1↓3⍴⍨⍴D←⍞
```
Takes input from the keyboard, the output is in the `⎕SM` window (which would be the terminal if you had a text-based APL I guess). The window size is detected automatically, if you really want it to be 50 change the `1↓⎕SD` to `50`.
Explanation:
* `1↓⎕SD,1↓3⍴⍨⍴D←⍞`: read the string and store in `D`. Generate a vector describing how much whitespace to add before each character, which is the screen width before the first character (`1↓⎕SD`), and 3 before the others (`1↓3⍴⍨⍴D`).
* `⎕DL÷8`: wait 1/8th of a second
* `P←⍵-{⍵×~×⍺}\×⍵`: in the vector in the right argument, subtract 1 from the leftmost nonzero item, and store the new vector in P.
* `,/D{⍺,⍨⍵⍴⍕⍬}¨P`: for each character in D, prefix the amount of whitespace given in P.
* `⎕SM∘←1,⍨1,⍨`: display on the screen, in the leftmost column of the top row
* `0∨.≠P:∇P`: if there is a nonzero element in P, repeat with P.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 129 bytes
```
for($x=' '*52+(($args|% t*y)-join' '*4);$x-match' '){write-host "`r$(-join($x=$x-replace'(?<! .*) ')[0..50]) "-n
sleep -m 99}
```
[Try it online!](https://tio.run/##JY69DoJAEIR7nmI1J3dgjhCjhVFjYaGlnYUxkejyYw6W7GFU0GdH0G4y881kSnog2xSNaUUMK2jamFiJ50qC9GeTsVIi4sS@R1D5L0/fKCv6ZOotxFPnUXVJJYD0mgdnFeqUbAXDMwv1I/udDmMsTXRBqdbLAUDge33jGAbBLDx1eqgLxxrEEnQO8/mn/TiO252Ru@4VwYHYXOXf2TMlHOV5ViSwv9e1QQsubOiKsCUTy/YL "PowerShell – Try It Online")
This script does not remove spaces from the arguments in contrast to [Joey's script](https://codegolf.stackexchange.com/a/5668/80745).
`TIO` does not display the output correctly. With Powershell console, you get the scrolling marqueeline.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ð¶:S3úJ46ú[D50£¶ð:D?IQ#ðõ.;“…¢('\r')“.eт.W
```
[Try it online (without the sleep).](https://tio.run/##MzBNTDJM/f//8IZD26yCjQ/v8jIxO7wr2sXU4NDiQ9sOb7BysfcMVD684fBWPetHDXMeNSw7tEhDPaZIXRPI0wNq9EjNyclXCM8vykkBAA) NOTE: I don't have 05AB1E installed locally, so I'm not 100% sure if the `\r` trick works (in theory it should work, however). In TIO the `\r` are interpret as newlines instead. Also, the TIO uses the legacy version, because `.e` is disabled in the new TIO version (program is the same in both the legacy and new version of 05AB1E, though).
**Explanation:**
```
ð¶: # Replace all spaces in the (implicit) input-string with newlines
S # Split the string to a list of characters
3ú # Pad each character with 3 leading spaces
J # Join the characters together again
46ú # And pad the entire string with an additional 46 leading spaces
[ # Now start an infinite loop:
D # Duplicate the string
50£ # And leave only the first 50 characters of this copy as substring
¶ð: # Replace the newlines back to spaces
D? # Duplicate the string, and print it without trailing newline
IQ # If the current string is equal to the input:
# # Stop the infinite loop
ðõ.; # Replace the first space with an empty string to remove it
“…¢('\r')“ # Push dictionary string "print('\r')"
.e # Evaluate it as Python code
т.W # Sleep for 100 ms
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“…¢('\r')“` is `"print('\r')"`.
[Answer]
# Python, 139 bytes
```
import os;P='\n'
def f(x,w):
v=k=P*w+P.join(x);o=str.replace
while v!=x:os.system('sleep 1;clear');k=o(k,P,'',1);v=o(k,P,' ');print v[:w]
```
Has to call `f('Hello World', 50)` to start.
] |
[Question]
[
A reflexicon is a self-descriptive word list that describes its own letter counts. Take for example the one found by Ed Miller in 1985 in English:
>
> Sixteen e’s, six f’s, one g, three h’s, nine i’s, nine n’s, five o’s, five r’s, sixteen s’s, five t’s, three u’s, four v’s, one w, four x’s
>
>
>
This reflexicon contains exactly what it says it does as per the definition. These are pretty computationally intensive but your job is to find all the possible reflexicons using roman numerals; there are way fewer letters involved (`I V X L C D M`) which is why the search space is reduced. Notice the English reflexicon containing "one g" - we can call it "dummy text" and it is allowed. Our reduced alphabet only contains letters used in numerals. A reflexicon using roman numerals would be of the form:
>
> XII I, IV V, II X
>
>
>
The counts (12 I's, 4 V's, 2 X's) are not correct - this just illustrates the format (notice no plural `'s`). A letter is completely omitted if its count is 0 (there is no `L` in this case).
Here is a list of roman numerals [1..40] for convenience (doubtful you need any more than this):
```
I II III IV V VI VII VIII IX X
XI XII XIII XIV XV XVI XVII XVIII XIX XX
XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX
XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL
```
These are all valid reflexicons (but these are not all!):
>
> IV I, II V
>
>
>
>
> V I, I L, II V, I X
>
>
>
>
> V I, II V, I X, I L
>
>
>
Standard `code-golf` rules apply - find all reflexicons using roman numerals! One per line
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 84 bytes
```
≔⪪”{⊞‴ΣAº⧴θπ⪪λpAz” θΦE×¹⁶φ⪫Φ⁺E⮌↨﹪κφχ∧λ⁺⁺§θλ §IVXμE⮌↨÷κφ²×λ⁺I §LCDMμλ, ∧κ⁼﹪κφI⭆XVI№ιλ
```
[Try it online!](https://tio.run/##ZVDNasMwDL7vKYRPMniQ7LBLT1m6gccCZR2hV9OYzsy1m9gJe3tPTppRqC3pIL4/dPxWw9Erm1IVgjk53F@sichAgsxF3QJ9STU3LQ5MAAPGBfR887AbjIv4ZmzUAzbqgl/mrAOWzwLKoigI9e6NWwE7O4YZ9aknPQSNL4pG47vRevz5p5QFp1m5Dq2AmTOPKkrX6V/sBVi@hliXTLY52Zln6p2FdHFrJtPpG5enjFzirjZMAruR/Ki3zVWTXz3FYkrRSOi1H5UN9/lrFSLuI53mlJOwQyuJWPuRTmWy0PI2KaXHyf4B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪”{⊞‴ΣAº⧴θπ⪪λpAz” θ
```
Split the compressed string `I II III IV V VI VII VIII IX` on spaces. Since there are only seven different Roman numerals, an description string can only have `22` of any one letter. However, this means that the letters `L`, `C`, `D` and `M` can only appear once, limiting the number to just `14` `I`s in the description string. I'm not convinced that you can actually get above `9` `I`s, and using base `10` makes the following loop somewhat golfier.
```
ΦE×¹⁶φ⪫Φ⁺E⮌↨﹪κφχ∧λ⁺⁺§θλ §IVXμE⮌↨÷κφ²×λ⁺I §LCDMμλ, ∧κ⁼﹪κφI⭆XVI№ιλ
```
Get the base `10` digits of the numbers up to `1000`, then use base `2` for the higher order bits, generate the description string represented by the number, count the number of times each Roman numeral appears, treat the digits as base `10`, and output those description strings where this equals the original number. Note that I don't have to count the number of occurrences of `L`, `D`, `C` and `M` since they will always appear the correct number of times and only exist to inflate the count of `I`s.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~46~~ 44 bytes
-2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
Quite inefficient version that only finds the first reflexicon in 60 seconds.
```
₂ENÝ7ãDONQÏεŽ6ˆ.XRøʒ¬Ā}©.XDS{®ø`×S{Qiðý„, ý,
```
[Try it online!](https://tio.run/##AVUAqv9vc2FiaWX//@KCgkVOw503w6NET05Rw4/OtcW9NsuGLlhSw7jKksKsxIB9wqkuWERTe8Kuw7hgw5dTe1Fpw7DDveKAniwgw70s////LS1uby1sYXp5 "05AB1E – Try It Online")
The builtin `.X` (*Convert from integer to roman numeral string*) does help quite a bit.
**Commented**:
```
₂E # for N in 1 .. 26:
NÝ # range from 0 to N
7ã # 7th cartesian power - all 7-tuples with values in [0..N]
DONQÏ # keep those that sum to N
ε # map over the tuples example: [4,2,0,0,0,0,0]
Ž6ˆ # compressed integer 1666 [4,2,0,0,0,0,0], 1666
.XR # convert to Roman numeral and reverse [4,2,0,0,0,0,0], "IVXLCDM"
ø # zip this string with the current tuple [[4,"I"],[2,"V"],[0,"X"],[0,"L"],[0,"C"],[0,"D"],[0,"M"]]
ʒ¬Ā} # keep only the pairs with a number larger than 0 [[4,"I"],[2,"V"]]
© # store the list in the register [[4,"I"],[2,"V"]]
.X # convert all numbers in the list to Roman numerals [["IV","I"],["II","V"]]
f # make a copy of the resulting list ... [["IV","I"],["II","V"]], [["IV","I"],["II","V"]]
S{ # ... and flatten and sort it [["IV","I"],["II","V"]], ["I","I","I","I","V","V"]
® # get the list with the integers still in it [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], [[4,"I"],[2,"V"]]
ø`× # and repeat Roman digit the corresponding number of times [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], ["IIII","VV"]
S{ # flatten and sort this [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], ["I","I","I","I","V","V"]
Q # are the two sorted lists of characters equal? [["IV","I"],["II","V"]], 1
i # if that is the case:
ðý # join inner pairs with spaces ["IV I","II V"]
„, ý # join by ", " "IV I, II V"
, # and print
```
---
With some optimization we can find all of them reasonably fast:
```
16EN¸2Å2«4Å1«Ý.«â€˜DONQÏεŽ6ˆ.XRøʒ¬Ā}D.X©JJ{sε`×}J{Qi®ðý„, ý,
```
[Try it online!](https://tio.run/##AWwAk/9vc2FiaWX//zE2RU7CuDLDhTLCqzTDhTHCq8OdLsKrw6LigqzLnERPTlHDj861xb02y4YuWFLDuMqSwqzEgH1ELljCqUpKe3POtWDDl31Ke1Fpwq7DsMO94oCeLCDDvSz///8tLW5vLWxhenk "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), 162 bytes
The strict output format prompted me to try a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") approach. This is based on the output of [Neil's answer](https://codegolf.stackexchange.com/a/239819/58563).
This is obviously very fast, and I think it's rather competitive (size-wise) compared to some code that would actually compute the strings.
```
_=>`IV I, II V${"XLXCLCXDLDCDXMLMCMDM".replace(/../g,a=>[i=`
V`,0,0,0].map(n=>i+" I, II V0"+a[i+='I',0]+0+a[1]).join``)}
IX I0V, II X0L0C0D0M`.split`0`.join`, I `
```
[Try it online!](https://tio.run/##NcxBCoMwFATQvacIUlDRxt8DxE2yCSRbCYj0B6sSsUZUuik9u7UtZVbDPGawD7s2i5u38@Rv7d6x/coKlCWRGZGSlKdnaJThihuhBBdGK8210CFd2nm0TRvnlOZ9ZllROYZBiRl8UtO7neOJFS4N/1cQprZyKYtkdIAUjnapEzp4NyEmr0AaIqH8WgMKOAjQSNd5dBsC/tyxEtwbP61@bOno@7iLk2R/Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# Python3, 785 bytes:
```
import itertools as i
d={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9,'X':10,'XI':11,'XII':12,'XIII':13,'XIV':14,'XV':15,'XVI':16,'XVII':17,'XVIII':18,'XIX':19,'XX':20,'XXI':21,'XXII':22,'XXIII':23,'XXIV':24,'XXV':25,'XXVI':26,'XXVII':27,'XXVIII':28,'XXIX':29,'XXX':30,'XXXI':31,'XXXII':32,'XXXIII':33,'XXXIV':34,'XXXV':35,'XXXVI':36,'XXXVII':37,'XXXVIII':38,'XXXIX':39,'XL':40}
q=lambda p,s:all(d[a]==s.count(b)for a,b in p)and all(any(m==j for _,m in p)for b,_ in p for j in b)
def g(s):
k=[1 if not(m:=max(h.count(i)for h in d))else sum([m]*len(s))for i in s]
yield from i.product(*[[j for j in d if d[j]<=a]for a in k])
f=lambda s:{n for b in range(1,len(s)+1)for m in i.combinations(s,b)for j in g(m)if q(u:=[*zip(j,m)],(n:=','.join(a+' '+b for a, b in u)))}
```
[Try it online!](https://tio.run/##RZJBj5swEIXv/ArfbCdWtECTUFSf2stK22sViaKVWSAxi20WE6npan97OmOz6sXvs8fzHmMx3ZaLs3kxzfe7NpObF6KXbl6cGz1Rnuikle/0kZapoI8gGQpoDvqLll8EhXUPK5wdUECPQQEKuHSi5VdBYU0fQNAoRUXIAiDlSGCUgt8JdY@KlUMApGMkxAKvoyU6g2Zojd5ZGgApi4SYBwTbDO3RP9sHwOIhEuJxReQi9KB3yADIQwim5GkkxGxF5Dwy@OchCJPyfSSsH1ZEPn4yborYiCGY9gTv@vCRvMlRmaZVZBK@VOPI2krVUvrdi7vahTW8dzNRoiHakokr2xK8pOyNGSkHgtVnYWIVN414DptQGRAbnrRdT87M8zIhr7JKie6JdQszpTTqD7usWToYXLCn5bwbfUf81bDK1Juxs9Ae6hrrvk7ITXdjS/rZQfpuml17fVnYpqqG/9EtJrXVUH@Tqg6D4OlrzZP@c2xfvtvQECaclT13LBUxb5uGxDCdho80jbZq0c565kV8mRBzZoZD0Bu7lrLa/NUTG4ThtWC2lFTQ3eC0ZWpLCd02JL5njLtyzj/u06xhevrbrjd7Bn/96en7j58U6vd/)
Code is able to crunch the reflexicons in about 0.4 seconds. The crux of the logic is, for every character in the "base" Roman numeral input (i.e `IV`, `IVX`, `VXMC`, etc) is first to find the maximum number of times that character can occur (e.g `I` occurs a maximum of `3` times, while `M` does not occur), take the maximum (if the letter does not occur, set maximum to `1`), and then multiply the maximum by the length of the base input, thus producing an upper bound for the range of each Roman numeral, drastically reducing the total number of Cartesian Products that have to be produced.
I am sure this solution can be golfed further - the Roman numeral lookup table takes up an incredible amount of space.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~136~~ 135 bytes
```
Pick[StringRiffle[s=Pick[{RomanNumeral@#,d=Characters@"IVXLCDM"},Sign@#,1],","," "],StringCount[""<>s,#]&/@d,#]&/@0~Range~9~Tuples~7
```
Searches \$10^7\$ possibilities, so quite slow. Does not finish in a reasonable time.
Check with better upper bounds on character occurences: [Try it online!](https://tio.run/##y00syUjNTSzJTE78X2T7PyAzOTs6uKQoMy89KDMtLSc1utgWLFYdlJ@bmOdXmptalJjjoKyTYuuckViUmFySWlTsoOQZFuHj7OKrVPu@v10nODM9D6jCMFZHCQQVlGJ1ICY655fmlUQrKdnYFesox6rpO6RAqJDSgpzU4miDuqDEvPTUumpLHSMgNITA2tj/AUDNJfoORf8B "Wolfram Language (Mathematica) – Try It Online")
Includes the empty string containing zero symbols.
Any single roman numeral contains at most one (each) `VLD`, and at most three (each) `IXCM`.
Thus there are at most 8 (each) `VLD` (7\*1+1), and at most 22 (each) `IXCM` (7\*3+1). But the maximum possible number of any symbol is only 22, so `LCDM` can only occur at most once each, as "dummy text".
From here we can just run the program and see what the maximum encountered values of `IVX` are. Their maximum counts are 9, 2, and 2, respectively.
[Answer]
# [Scala](http://www.scala-lang.org/), 149 bytes
```
"IV I,II V\nIX I,I V,II X,I L,I C,I D,I M"+{for{i<-0 to 3;j<-"DMCMCDLMLDLCXMXDXCXL"grouped 2}yield s"\nV${"I"*i} I,II V"+j.flatMap(",I "+_)}.mkString
```
By the findings of others here, we know already that there are exactly 42 (sic!) valid reflexicons. So one solution strategy is to generate these 42 lines by as small as possible code.
While doing so, I realized that my solution became very similar to [Arnauld's answer](https://codegolf.stackexchange.com/a/239850/74778). However, his trick of further saving some bytes by temporarily substituting the multiple occurences of `,I` via `0` does not seem to save additional bytes in the Scala approach taken here.
[Try it online!](https://tio.run/##fZNBS8MwFMfv@xSPIGx1rojedDtIukMgZdBJyWEgdU1HZ5bUNspk9LPXqNvcyNND4PXf95Lf7/CaZaayzjyv5dJCYjaZTmSh5LZcGt2A3Fqp8wYeqgp2PYD3TMFKallnVuZ3MLd1qVcw6QhLgV0xBulCM/FVQvr1KVzB3aHuRO7EZLgrTL0rx6NrsAZu79fjEYliGtOIxzziVMQiElRwsqrNWyVzuGk/SqlyaMhCpxc7wshl2e4fI8N1WKjMxlk1IO56MnwK2nDz8sPV7YHltnJy7qoJnHIeqgPaWULRJDpLuNfD0R56lghvSnhTAp3iLmE@NPOpmY/NfG7mgzOfnPnozGdnPjxD6DF8jB8TwAwwBcwBk8AsMA3UAxVBTVAV1AWVQW1QHdQHFfKN/t/Znlukym2UVXpw3P7gJCwL@P0RNpUq7aC/0P0gtGYuX8PG1N/7Nznu4p9NARA6S5IpfSQgVSOBTJNklpCg13af "Scala – Try It Online")
] |
[Question]
[
## Background
A [bijective base \$b\$ numeration](https://en.wikipedia.org/wiki/Bijective_numeration), where \$b\$ is a positive integer, is a bijective positional notation that makes use of \$b\$ symbols with associated values of \$1,2,\cdots,b\$.
Bijective base 2 representations of positive integers look like this:
```
1 -> 1
2 -> 2
3 -> 11
4 -> 12
5 -> 21
6 -> 22
7 -> 111
8 -> 112
9 -> 121
10 -> 122
```
Now, let's apply this to a mixed base. Bijective mixed base \$[b\_1,b\_2,\cdots,b\_n]\$ numeration uses \$1,\cdots,b\_k\$ as the symbols for each digit place, and the digit value of each digit place is \$\prod\_{i=k+1}^{n}b\_i\$, as in the usual mixed base. This system can uniquely represent the integers from 1 up to the number represented by \$b\_1b\_2\cdots b\_n\$.
Some numbers in bijective base \$[2,3,4]\$:
```
1 -> 1
2 -> 2
4 -> 4
5 -> 11
9 -> 21
16 -> 34
17 -> 111
28 -> 134
29 -> 211
40 -> 234
```
## Challenge
Given the base \$b=[b\_1,b\_2,\cdots,b\_n]\$ and a positive integer \$x\$, convert \$x\$ to bijective mixed base \$b\$ as a list of digit values. It is guaranteed that \$x\$ is representable in the system. Some digits of \$b\$ may be greater than 9. You can take the input \$b\$ and give output in either most- or least-significant-digit-first order (mixing is also OK).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
Protip: Jelly does not have this built-in.
## Test cases
Test cases are written in most-significant-digit-first order.
```
x = 1, b = [1] -> [1]
x = 3, b = [1,1,1,1] -> [1,1,1]
For b = [2, 1, 2, 3, 4]:
x = 1 -> [1]
x = 4 -> [4]
x = 10 -> [2, 2]
x = 20 -> [1, 1, 4]
x = 35 -> [2, 2, 3]
x = 56 -> [1, 2, 1, 4]
x = 84 -> [1, 1, 2, 2, 4]
x = 112 -> [2, 1, 2, 3, 4]
for b = [8, 9, 10, 11]:
x = 1 -> [1]
x = 2 -> [2]
x = 6 -> [6]
x = 24 -> [2, 2]
x = 120 -> [10, 10]
x = 720 -> [6, 5, 5]
x = 5040 -> [4, 9, 8, 2]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 40 bytes
```
x=>b=>b.flatMap(v=>x?x-(x=~-x/v|0)*v:[])
```
[Try it online!](https://tio.run/##jdDBDoIwDAbgu0@x42YGbmMgaoZP4BMQDlPBaAgQIcsOxlefjngxWUKTnpqvTfs/tNHj5Xkfpqjrr7VrlLOqOH8rblo9nfSAjSrs0UbYqndkN@bFyNrsy4q4S9@NfVvHbX/DDeYEl7wi5LD67ye@T9GvAsAPSooSisRsRMBIgOEMgAQEJSkApRkA5aDDuYAon6OPkFG0oygPPbdMMsAWuWz4nOMC2kJQymRIuQ8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
0#_=[]
a#(b:c)|q<-div(a-1)b=a-b*q:q#c
```
[Try it online!](https://tio.run/##fc/BCoJAEAbgu08xsB00VtjZXc0kn0QkdjVoySwrOvXumxiERiNz@78ZmP9o7qdD23ov2L4oq8Cw0OZ19Op3ceOeoYkxsoWJ7brPe1b7s3EdFNBcAoDrzXUPWAECgxL5MNUkVd90no/bmisuB5FT0aSgIEnSpBKSkpSkbOENlLSNdYeugm95NvuQlJS@0SThp/Ff2yxYIvQP@jc "Haskell – Try It Online")
Inputs and outputs are in least-significant-digit-first order.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
Based on [@tsh's Javascript answer](https://codegolf.stackexchange.com/a/236995/9288).
-6 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Map[x=#;Pick[x-(x=⌊--x/#⌋)#,x>=0]&]&
```
[Try it online!](https://tio.run/##dY9BCoMwEEX3nmIgIC0kVGO0lhLxAgX3IYsgLZViKcVFQLxA6ym9iDXS4qIOzGze@zDza9Ncz7VpqtKMF5DjyTyUleRYVOVNWbaxcuhfjNkdGfr3llCbyUD72h@LZ3VvVEtIByyDiyJaEa41@JDnuQdtG1Jw66brqAfQRgtZoIsJCpPjM@dfLhAeBojgmIhiRMQJIlL0eMgx47q5WtMXBwrp76l1nCBpsc7DuduK2GMiDsS/6cYP "Wolfram Language (Mathematica) – Try It Online")
Inputs and outputs are in least-significant-digit-first order.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->x,b{b.map{|y|x>0&&x-y*x= ~-x/y}-[!0]}
```
[Try it online!](https://tio.run/##jdC9CoMwFAXgvU9xuziUxCZRW0uILyIZGtCtIJaWBLWvnqaCq6eE/AxfuIczvlyIvYm88cxNLn/ch2kOs29ElnkeTt7Qh/tzWHh7FHaJngxJTS5drbSkaaC@TV/zsXt347Oz2@Pwk8Um2bp2/QoVI8konQWj0up1GhpSIiAFEgqKokKiuiBR46RSwYpqRrfUkkhb/tmQQgBGVzg67vCKSSXKPRO/ "Ruby – Try It Online")
Freely adapted from tsh's Javascript
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
f=lambda n,l:n*l and[~-n%l[0]+1]+f(~-n//l[0],l[1:])
```
[Try it online!](https://tio.run/##bVDbboQgFHzfryAkzcIuuoBorcb9EeVBdzW1oWi2PtiX/rpFwMa0jZfDzJkzZ8L4Ob0OOlqWrlD1e3OvgSYq0ycFan0vvwL9pEoqz0yeO2TQ5bJCokqWSby0c3tDsNLjo9cT6tBMmjLLAiaxK@QvVRQDrjQM34ZeIwjhDArActCYUjIJgutaDisbbSyxj@/Z48E2OAGMAPOPCBAyt057A2GBcIBRi4yaO4JTb7iaeFEU/4iMq@PiZNPxvTQVu3E3sG1ifHPZxXORUwJeDE3Nx/5J7AcdcHsT3xG/4rMt/@pFHffsuYSA2Lw@PxWOFXZ3ah3MxYePdlT1rUUwuEIC88FoIQ4/RtVP6FjpI8Z4@QY "Python 3 – Try It Online")
reversed digit order
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
\d+
$*
+`(1+),*;(\1)*(1+)
;$#2$*1,$.3
.*;,
```
[Try it online!](https://tio.run/##VY27DoMwDEV3/wYZwLFQ7CQ85F9hAIkOXTpU/f80sMTIg@85kn2/r9/7c5SynR4cgt979gOh9hsPeGVQ14lDJjdGGFEJSmFlYLpHI0jdQpFStS0n64MBsRCzgTwZWB4PWGChlTgQX@UtWz9Zn@xB7Ww0PyiHFP4 "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in the order `b₁,...,bₙ;x`. Explanation:
```
\d+
$*
```
Convert to unary.
```
+`(1+),*;(\1)*(1+)
;$#2$*1,$.3
```
Repeatedly divmod `x` by `b` in reverse order, but always ensuring that the remainder is non-zero, and convert the remainder to decimal, but keep the quotient in unary.
```
.*;,
```
Delete any unused bases.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
W∧θ⊟η«≦⊖θ←⸿I⊕﹪θι≧÷ιθ
```
[Try it online!](https://tio.run/##RcxPC4IwGMfxc76KB0/PYIFCQX9OkpcgQbqah@GWG6xN57JD9NqXEtjt4eH7@zSSucYyHcJLKi0AM8Oxp1DaDiUhBN7RqmBdNgyqNZiLxomHMF5wCj05RqvSKePxcBF3TyG@ufj/PLHB49ksCywsf2o762qS53CRr6qVc@xzNSoupuLnf0KotskmoVDtKOwppNOZpnUd1qP@Ag "Charcoal – Try It Online") Link is to verbose version of code. I/O is in left-to-right order. Explanation:
```
W∧θ⊟η«
```
While `x` is nonzero, retrieve the previous mixed base `b` from the list of mixed bases.
```
≦⊖θ
```
Decrement `x`.
```
←⸿I⊕﹪θι
```
Reduce `x` modulo `b`, then increment the result, and print it on the previous line.
```
≧÷ιθ
```
Integer divide `x` by `b`.
[Answer]
# [Red](http://www.red-lang.org), 79 bytes
```
func[n b][r: copy[]until[insert r(n: n - 1)%(t: take/last b)+ 1 1 > n: n / t]r]
```
[Try it online!](https://tio.run/##lY7NCsJADITv@xRDQVBE7K6tPwV9CK8hh/5ssVi3ZV2hPn1NC168mZDDDMOX8bYar7YiVqrOMNYvV5JDweQzlF3/Jn650LTUuKf1AX7pMjhsoFeLZcgQ8rvdtvkzoFitoWUvmBNbBPY89r4rLGrxSbP6qp2oOaynt523eXnDMJkJdAwTY5ci3eMoUhsGKcj0vnEBFA04R5KONpcIj66tBDjMXQEyAjXCT5jVL9tgDyNEwR/k0jiJ/0EfcZrKaT2hxw8 "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vD_#<y‰`>,
```
Inputs are in the order \$[b],x\$. I/O are both in least-significant-digit-first order, so reversed of the challenge description. The output is newline delimited.
[Try it online](https://tio.run/##yy9OTMpM/f@/zCVe2abyUcOGBDud//@jTXSMdYx0DHWMYrmMDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5epUJvwvc4lXtql81LAhwU7nf@2hbfb/o6MNdaINY2N1FKKNgQwdMARzgeImOsY6RkABI7CACbqAoQG6iBGGiLEpuoipGbqIBabJhkYYQkDXAZ1moGOpYwGxC13ADEOFCbqIIciBqELmmEKmBiaoYrEA).
**Explanation:**
```
v # Loop `y` over the first (implicit) input-list:
D # Duplicate the current integer
# (which is the second implicit input-integer in the first iteration,
# and the quotient of the divmod every other iteration)
_ # If this is 0:
# # Stop the loop
< # (Else) Decrease the integer by 1
y‰ # Divmod it by `y`
` # Pop and push both values separated to the stack
> # Increase the top (the remainder) by 1
, # Pop and output it with trailing newline
```
] |
[Question]
[
**This question already has answers here**:
[Tell me, how many squares are there?](/questions/120649/tell-me-how-many-squares-are-there)
(2 answers)
Closed 2 years ago.
In a 9 by 9 grid some points have been marked. The task is it to
make a program that counts all distinct squares that can be made
using four marked points. Note that squares can also be placed
diagonally (any angle).
**Input** can be one of the following:
* A character string of length 81 containing two distinct characters
for marked and unmarked points.
* A one dimensional array (length 81) containing two distinct values.
* A two dimensional array (9 by 9) with containing distinct values.
**Output**: The number of possible squares
You can write a full program or a function. This is code-golf. I am interested in the shortest code in every language. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
Examples:
```
Input: ooo......oooooo...oooooo....oo.oo....oooooo...oooooo......ooo....................
Output: 62
Looks like:
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
Input: ...ooo......ooo......ooo...ooo...oooooo.o.oooooo...ooo...ooo......ooo......ooo...
Output: 65
Input: ...........o..o..o....................o..o..o....................o..o..o.........
Output: 6
Input: ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
Output: 540
Input: ...........o..o.......................o.....o....................o...o...........
Output: 0
```
[Answer]
# JavaScript (ES6), ~~122~~ 109 bytes
*Saved 13 bytes thanks to @tsh!*
Expects a binary matrix.
```
f=(m,X,Y,t=0)=>m.map((r,y)=>r.map((v,x)=>t+=v*=1/Y?(m[X-x+Y]||0)[y-Y+X]&(m[y+X-x]||0)[x+y-Y]:~-f(m,x,y)/4))|t
```
[Try it online!](https://tio.run/##rU5NT4NAFLzzKwgHu0/gURMvarae9Oqhl5LKgcBSMcDD3bWBtPWv45amCS3WxMTJHubj7WTe43WsEpnX2q8oFV2XcVZ6Cy/0NJ8Cn5VYxjVj0muNkAex9hojtMvX1/wmCB9ZuVz4jRtG2@0Ulq0fuovoypita@yD2bjGju6//My0N6YsuAXY6k6Kj89cCjbJ1ARQijh9zgsxb6uETQE1zbXMqxUDVHWRa@a8Vg5gRvIpTt6YsvnM3li2XdrcVmabNmaAm7tdsIJ@an@xREQV9TrZawfJwbxKRfOSsQQAHkxFQpWiQmBBK1aOHLN6f7aDjoiwB/UYEsPwSEZZz/EHWMPojJyU0EntL7@sQTsd3xh/iCz6b4w34oUheHnjSfAN "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES11), 103 bytes
*Also suggested by @tsh*
We can save 6 more bytes by using [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining).
```
f=(m,X,Y,t=0)=>m.map((r,y)=>r.map((v,x)=>t+=v*=1/Y?m[X-x+Y]?.[y-Y+X]&m[y+X-x]?.[x+y-Y]:~-f(m,x,y)/4))|t
```
Optional chaining is not supported on TIO.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ŒṪÆịœc4ṗ2ạ/€QLƲ€ċ3
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7Vx1ue7i7@@jkZJOHO6cbPdy1UP9R05pAn2ObgNSRbuP///9HRxvqKECQARqK1VFASKKrIihpgCSGWxJdMzGScIRXEsMruCVjAQ "Jelly – Try It Online")
Input is a two-dimensional list of `0` and `1` (or any other falsy and truthy value).
## Explanation
The idea is that for every four distinct points, we calculate the distance between each pair and if there are exactly three distinct distances (including 0), it's a square. (There are other shapes with this property, but they don't fit on a square grid; see @aPaulT's comment.)
```
ŒṪÆịœc4ṗ2ạ/€QLƲ€ċ3 Main monadic link
ŒṪ Get the coordinates of truthy points
Æị Convert to complex numbers
œc4 Get all combinations of size 4
€ For each
Ʋ (
ṗ2 Cartesian square
ạ/ Absolute difference
€ of each pair
Q Find unique items
L Length
Ʋ )
ċ3 Count the occurences of 3
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 72 bytes
```
F⁹⊞υSυ≔±№KA1θF⁹F⌕A§υι1F⁹F⌕A§υλ1«J⁺κ⁻λι⁺ι⁻κμ¿ΣKK«J⁺μ⁻λι⁺λ⁻κμ≧⁺ΣKKθ»»⎚I÷θ⁴
```
[Try it online!](https://tio.run/##hZBBasMwEEXX9ilEViNwA4JuSlfGoeBCiml6AREr9hBZdiwpBELO7o5l7Ca00NnM5@vraUb7Wvb7VuphOLQ9gxfOCm9r8AnLTefdzvVoKuD8NS5IOfCkUmuxMvChKukUZK0nv1DqmGoNPGErseLUTpScmaG/oSnHSOpyU6rL@AbOcfZfUi/Jaxy9@6b7aqHQ3sIxYVs0JPSIo1RwcXbpuOHj@BEeGOx8EyalhQLogdT8SdK/SdFWdtMffGJVu3A7YXfsafnoFt/iTCvZw/J9mbQOcuM2eMZSwSlhzyNzGIQQ61CxCPWo1tQWNZn3iupHTZRFDU9n/Q0 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of 9 strings of `1`s and neutral characaters. Explanation:
```
F⁹⊞υSυ
```
Input the array and print it to the canvas.
```
≔±№KA1θ
```
Initialise the count to the negation of the number of `1`s on the canvas. This is because the algorithm below counts each `1` as a single `0×0` square, which we don't want.
```
F⁹F⌕A§υι1
```
Loop over all of the `1`s in the array.
```
F⁹F⌕A§υλ1«
```
Loop over all of the `1`s in the array again.
```
J⁺κ⁻λι⁺ι⁻κμ
```
Treat the two pairs of coordinates as two adjacent corners on a square, and jump to where the third corner would be.
```
¿ΣKK«
```
If there is a `1` here, then...
```
J⁺μ⁻λι⁺λ⁻κμ
```
... jump to where the fourth corner would be, and...
```
≧⁺ΣKKθ
```
... if that's also a `1` then increment the count of squares found.
```
»»⎚I÷θ⁴
```
Since squares have four pairs of adjacent corners, divide the count by 4.
[Answer]
# [Jelly (cairdcoinheringaahing's fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 17 bytes
```
ŒṪœc4ṗ2ạ/ṢɱQLƲ€ċ3
```
A modification of [my Jelly answer](https://codegolf.stackexchange.com/a/221002/98955). Instead of calculating the Euclidean distances, it simply calculates the two differences of coordinates and then sorts them to make the uniquification order-insensitive.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~121 110~~ 99 bytes
```
->m{(0..80).sum{|x|(1..8-k=x%9).sum{|w|(0..k).count{|t|[0,w+9*t,9*w-t,t*8+w*10].all?{|z|m[x+z]}}}}}
```
[Try it online!](https://tio.run/##rZDRCoIwFIbve4ogIpt6mFGhF@WDiBdLiCDXIidaOz675cjQbEHQxy7@s7PDx9kl313r/aZ2t1xZFMCnc8hyrrBEy3uU7nFTToPnXYHNk@McEpGfpEKJEXUKOyDSCUjhSkcS3y6IR2NgaRoqvCGPSvsWVw31ebyPZkII0AhNNzwStGHQ0xk@MIPkwC4ZcHZWmGCyDVkVjyfrxUj7uoNvoacQPemXKZNv9fK1iPYM@aFl8o3a7/wvBt1qSQ37gWEJMO/XaxiEtL4D "Ruby – Try It Online")
Accepts a boolean array in input.
[Answer]
# [Python 3](https://docs.python.org/3/), 133 bytes
```
lambda g,r=range:sum(g[x][y]*g[x+a][y+b]*g[x+b][y-a]*g[x+a+b][y-a+b]for a in r(1,9)for b in r(9-a)for x in r(9-a-b)for y in r(a,9-b))
```
[Try it online!](https://tio.run/##rVLbboQgEH33Kybpg7BeEnX3QRO/xPowupaaXcGgTdavt4CXarc2adITCOcww2EC0w79u@DR2EIKd2yKK0KXQFamqS1seBMSSqg5dLnV7zNa0mXxaUjUdOKcmtRBp0rkrCIxzeEFGrxVEMK1bire1YLjHVBKHCwWKLee2EII30AYbIli/kKeYob7P8CmFgsn723SN7KzE7sLfjmlvaPVe4FYxjP@ENLe5/VN/hfa@3JQt39QnH9c9y6gvMv0dZwbg7kyNf@fdB8NYdkjz4b8pFYHFXOKiReKezjvz0otuoPQdBAJ3JhqWUwy9tDIxyq9gn41HEE3Vht0bGXNe1ISFlBqrSLcimgrzltxUQaf "Python 3 – Try It Online")
Expects a two dimensional array of booleans.
Shortend by 3 bytes thanks to xigoi.
[Answer]
# [Perl 5](https://www.perl.org/), 127 bytes
```
sub{0+map{$a=$_;map{$b=$_;map{//;grep{$_[$'][$_]&$_[$'+$a][$_+$b]&$_[$'+$b][$_-$a]&$_[$'+$a+$b][$_-$a+$b]}$a..8}0..8}0..8}1..8}
```
[Try it online!](https://tio.run/##rVJha4MwFPzeX/HoQtXZRWsrdIjgfocTiS6IYI2LbjDE3@4SnU6tLQx2yOO895JLwhWUZ3ZbfkRQsRfOyVftUfdCCqhRCPQdFKY0UBZZWqmGsQcv9M1Ac6Cb8D3qPz@iEGNZ9XMQNGBifG7gAWKWf1JeQVnxNE/E5mDBW3qheZmynGRApNfGSw7gDs6qwhjDHViHKREMD@Sq13G8AkVzhIc19ZgOL8hsWzYzurOq9zguPAaw4bvGH1q9x2nxVv@L3sO@ew9847D49j1mDemBYlfmrTZ1EaIaEReFTseigRmGk3AqlNBHSuCjMNh1VEdE/ukoGoVICk9CHyd@NckaRGQgzbEcZGmdTSFiWcEOxarIoLbfvubbuWiticc18bQm2j9i@w0 "Perl 5 – Try It Online")
Expects a two dimensional array containing values 0 or 1.
[Answer]
# MATLAB, 168 Bytes
```
function o=q(I)
o=0;for i=2:9
for j=0:9-i
for k=0:9-i
a=I((1:i)+j,(1:i)+k);a(2:i-1,2:i-1)=0;o=o+floor(sum(a&rot90(a,2)&rot90(a,1)&rot90(a,3),'all')/4);end
end
end
```
A different approach. Takes a 9x9 array of 1s and 0s. Loop through every square submatrix from size 2 to 9, and rotate that submatrix three times and take the boolean combination of all 4 (original + 3 rotations). The sum of all truthy values on the edges divided by 4 rounded down is the number of squares that are in that submatrix. By looking only at the edges, you avoid capturing smaller submatrices in the middle (e.g. 2x2 in the middle of a 4x4). This method captures all squares by using the rotational symmetry of a square. It may not be the golfiest, but it was fun
] |
[Question]
[
For today's task, we have two programs, P and Q, both in the same language. Each of them receives a single-character input.
If P receives character K, P says how many times K appeared in Q. (You can use any output format for P or Q; they need not be the same, the only requirement is that your format can represent any nonnegative integer uniquely). Vice versa: If Q gets K, Q says how many times K was in P.
**Create P and Q,** which must not be identical programs. To further cement this, P and Q must be minimal (remove any amount of characters from either and it doesn't work as required).
Whoever made the combined lengths of P and Q the shortest wins (tiebreak: earlier post). Have fun!
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes
Inspired by @Wasif's awesome PowerShell answer
-6 bytes thanks to mazzy!
```
$P={$Q-replace"[^$args]"|% le*}
$Q={$P-replace"[^$args]"|% le*}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXAtlolULcotSAnMTlVKTpOJbEovThWqUZVISdVq5ZLJRAoH4BT/r@aSoCGepG6JpeaSqCGeqG65n8A "PowerShell – Try It Online")
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), Independent Functions, 109 103 93 77 bytes
This version does not require the functions to be in the same file; they are completely independent of one another.
```
$P={"Q$P"-replace"\|P|[^$args]"|% le*}
$Q={"P$Q"-replace"\|Q|[^$args]"|% le*}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXAtlopUCVASbcotSAnMTlVKaYmoCY6TiWxKL04VqlGVSEnVauWSyUQqCxAJRBZWSCGsv9qKgEa6gHqmlxgRiCYEYjEAEr9BwA "PowerShell – Try It Online")
For either answer, it costs 2 bytes to make the input character case-sensitive.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [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"))
## Mutually dependent lambdas
```
P←{≢⍸⍵=⎕CR'Q'}
Q←{≢⍸⍵=⎕CR'P'}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@BR24TqR52LHvXueNS71fZR31TnIPVA9VquQGwSAeq1QC3qtupcgSAiQB0IgEwQGQCUBDIDQaxAECtAHQA "APL (Dyalog Unicode) – Try It Online")
`P←`… establish a function with the following definition:
`{`…`}` dfn; the argument (a character) is `⍵`:
`⎕CR'`…`'` **C**haracter **R**epresentation of the function called … (as a character matrix)
`⍵=` 2D mask indicating where the character is equal to elements of that matrix
`⍸` **ɩ**ndices where true
`≢` tally them
## Mutually independent lambdas (35 bytes)
```
P←{≢⍸⍵=⎕CR'P'⋄QQ}
Q←{≢⍸⍵=⎕CR'Q'⋄PP}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@BR24TqR52LHvXueNS71fZR31TnIPUA9UfdLYGBtVyB2GQDQbIBAbVAzeq26lyBICJAHQiATBAZANQPZAaCWIEgVoA6AA "APL (Dyalog Unicode) – Try It Online")
The only difference from the above is that each function reads its own source, and that each has a dummy statement containing supplemental characters that ensure that they have identical counts of all characters. `⋄` is the statement separator, but the second statement will never be reached (it'd cause a vale error anyway) because the function terminates with the value of the first non-assigning statement.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**P**
```
“ṾċḷḤ”Ṿċḷ“”Ḥ
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/cd6X64Y/vDHUseNcyF8YASIN6OJf8Ptz9qWvP/v1JIRmaxQnFGfmlOikJ6ZlmqQqJCUmlecoZCfppCVWpRfrFCWn5OTn55aopCUqVCSXlqDlBNSTlQnLAlSgA "Jelly – Try It Online")**
**Q**
```
“ṾċḷḤ”Ṿċḷ”“Ḥ
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/cd6X64Y/vDHUseNcyF8YBMkNyOJf8Ptz9qWvP/v1JIRmaxQnFGfmlOikJ6ZlmqQqJCUmlecoZCfppCVWpRfrFCWn5OTn55aopCUqVCSXlqDlBNSTlQHI8lc0C8HUuUAA "Jelly – Try It Online")**
P and Q are very similar, they both contain two of each of the same set of six characters. The only difference is `“”` vs `”“` (empty list vs a single open quote character).
### How?
```
“ṾċḷḤ”Ṿċḷ..Ḥ - Link: character, C
“ṾċḷḤ” - list of characters = ['Ṿ', 'ċ', 'ḷ', 'Ḥ']
Ṿ - un-evaluate Jelly code = ['“', 'Ṿ', 'ċ', 'ḷ', 'Ḥ', '”']
.. - either:
- “” - empty list = []
- ”“ - character literal = '“'
ḷ - yield the left argument of this dyadic atom (C)
ċ - count occurrences (of C in the un-eval list)
Ḥ - double
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~128~~ 122 bytes
```
function P($x){cd Function:;(gc Q)-replace"[^$($x)]"|% le*}
function Q($x){(gc $psCommandPath)[0]-replace"[^$($x)]"|% le*}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P600L7kkMz9PIUBDpUKzOjlFwQ0qYmWtkZ6sEKipW5RakJOYnKoUHacCUhOrVKOqkJOqVcsF1xsI1gtSrlJQ7Jyfm5uYlxKQWJKhGW0Qi1P7/wAN9Wx1Ta5AMPUfAA "PowerShell – Try It Online")
-6 bytes Thanks to mazzy and Zaelin Goodman
Two functions work in different ways.
`P()` will read `Q()`'s source code and count occurrences of the given character.
`Q()` will read the source of the first line in the script (Which is source of function `P()`), and count occurrences of the given character.
I Couldn't be more creative than this solution to follow the rules of the question, otherwise if I made two functions identical, I could save some bytes.
[Answer]
# [R](https://www.r-project.org/), version-dependent, ~~110~~ 84 bytes
*Edit: -26 bytes with inspiration from [user81655's answer](https://codegolf.stackexchange.com/a/220148/95126)*
*Note: Function-pairs #1 and #2 below depend on the version-dependent output formatting of [R](https://www.r-project.org/) functions, and work on my locally-installed [R](https://www.r-project.org/) version 3.2.1, but unfortunately not on version 3.5.2 which is installed on TIO. A TIO-compliant (but longer) adjusted version of #1 can be tried here: [try it](https://tio.run/##PYzBCsIwEETv@YoBD9mFID2It/oR4g@UuC2Ctps0C/n72BZ0mMODYV5u2m8dbY7ltcygGFDRIzFW@5C8acoySdW8L3d5WhTSYS3SBcRBi2U5L1bUClXmgHE7P5hxw56OW/rLf25l6MHsnJKHZ5xwdYm8Hnhx7Qs).*
**1: functions that read each other's source code: 84 = 61+23 bytes**
```
p=function(c,x=q)sum(el(gregexpr(c,capture.output(x),f=T))>0)
q=function(c,x=p)p(c,x)
```
**2: functions that read their own source code, but not each other's: 142 = 2x 71 bytes**
```
p=function(c,pr=2,q=1)sum(el(gregexpr(c,capture.output(p),f=T))>pr-q-q)
q=function(c,qr=2,p=1)sum(el(gregexpr(c,capture.output(q),f=T))>qr-p-p)
```
**3: 'proper quine'-like functions that don't read their own source code: 236 = 2x 118 bytes**
```
p=function(c,q=1,p=1)2*sum(el(gregexpr(c,sQuote('function(c,p=1,q=1)2*sum(el(gregexpr(c,sQuote(),f=T))>p-q)'),f=T))>q-p)
q=function(c,p=1,q=1)2*sum(el(gregexpr(c,sQuote('function(c,q=1,p=1)2*sum(el(gregexpr(c,sQuote(),f=T))>q-p)'),f=T))>p-q)
```
---
# [R](https://www.r-project.org/), version-dependent, 150 bytes
*New function-pair to comply with the newly-added rule that functions cannot be anagrams of each other*
**4: functions that read their own source code, but not each other's, and are not anagrams of each other: 150 = 2x 75 bytes**
```
p=function(z)sum(el(gregexpr(z,chartr("yz","zy",capture.output(p)),f=T))>0)
q=function(y)sum(el(gregexpr(y,chartr("zy","yz",capture.output(q)),f=T))>0)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 51 bytes
```
p=(k,s='q='+q)=>s.split(k).length-1
q=k=>p(k,'p='+p)
```
[Try it online!](https://tio.run/##VcpBCoAgEEbhfRcZh1Jo12a8i0SUKfGb0vXNaOXy473TPS6vt0fRz1IrRIUpCyWhMbHYbDKiLyqwidu1l0PPQ5IgFu0jtAtccfurKCgCMQ@/UqfWYtc@1Rc "JavaScript (V8) – Try It Online")
Works assuming we're allowed to read the other program (grey area but not explicitly disallowed in the rules).
[Answer]
# [Zsh](https://www.zsh.org/), ~~104 96~~ 56 bytes
```
a=`<$0` b=$1;<<<${#a//[^$b]}
```
```
b=`<$0` a=$1;<<<${#b//[^$a]}
```
~~[Try it online!](https://tio.run/##qyrO@G@nkKZgY6Pu6u@m/j8tv0ghWUFDpVqj2MpKU0XDRsVAs1YzWkGlOllZxbBWIbamRkNDW7tIU9PaxsZGpbpI16D2P1AnF5edQjrMFC7cphgqqyRjN4ULbEpyRm5@ioJ2hUIaV1VxBtBh6tHqUJbRfwA "Zsh – Try It Online")
[Try it\* online!](https://tio.run/##lVCxboMwEN39Fa8GyYkQITAi062VOtEhWxMJCia2FOwIQ1uF8O2paTJUmdrT6U739N7T3Z2svKQ4nzHCQ96pvdLlAcfO7LuytSnhnPtv/uiPSVZwf11MaVD4a/gxqMPSeKLFFCy8JMu8eLn7Kz129MTRJ0I8bF5ycuyU7hFqsI0UMHd7LOwSUvUoZ6AS1uKgWjcbPYtXW/36G07ByHAlhMPN2dkqC5clWlOrRokaH6Kzyll8SlVJDFZYUFFJQ6G07UVZwzSg7iK61dkcjJBHNOCcPeXPjHgP0bvS0cl9cJbhH3@6OANSSbcKgi80hKyiBuFPZSO79vjWd@zyDQ "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##LcqxDoIwFIXhvU9xpE06GL0ye3GT1QcwGFqktgN1KAOB@OyVKMv5kpN/Tj5f4MCsr7daC7kjGyLN622qltWpha1UeWZmtUhDdH8o23zyGovOD@8n9hOcEEdyOPxWL/pvudlskgYkRh8SBjN2vk8oqEgIEcn31sRX/gI "Zsh – Try It Online")
Both programs are independent (they don't read each other's source). I found the best way to tackle the challenge was to make two self-counting programs with the same character counts. Using assignment to expand the simple `${#${$(<&0)//[^$1]}}` feels cheap, so do take a look at my older programs.
(\*My second attempt hits a fork limit on TIO, so its TIO link uses a modified version that uses the non-forking `echo` instead of `<<<`.)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~106~~ ~~100~~ 96 bytes
Saved 10 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!!
```
import inspect
f=lambda c:inspect.getsource(g).count(c)
g=lambda c:inspect.getsource(f).count(c)
```
[Try it online!](https://tio.run/##jY/BSgMxEIbveYohl2StFrSCUJge24ewIuuYpMFuEpLJQZZ99u1ai64X6e1n@D@@f9InH2JYjaPvUswMPpRkiIXFY9u9vbdA68tp6QyXWDMZ7ZolxRpYUyPcf0X7Wxxtjh0Uzj44@JbdiC3Ka0VS7FBeK5OCDoY@TEat9vXh6ZHU7Tncr1QjbMxA06fQFvL@9WiYTS6LVANxbdnHsBZQAMF@PQg8JXdOaRrP2iqrZU@DbOBuA30ZoL/Yngvi7mfEy6BmjJszPGMYcfuHGU8 "Python 3 – Try It Online")
Two mutually dependent lambdas that simply read each other's source code and return the input character count.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
I⊗№⁺´”´””yI⊗№⁺´´yS”S
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npWPuqY/apn2qHHXoS2PGuaCCSCqRJU5tAUosBkoDiT//z@0BQA "Charcoal – Try It Online")
```
I⊗№⁺”yI⊗№⁺´´yS”´”´”S
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9npWPuqY/apn2qHHXo4a5lcj8Q1sObQEKbAaKH9oCI4D8//8PbQEA "Charcoal – Try It Online")
The first program is simply my answer to [Counting characters](https://codegolf.stackexchange.com/questions/205163/) and the second is a trivial rearrangement.
[Answer]
# JavaScript, ~~85~~ 63 bytes
```
p=k=>('q='+p).split(k).length-1
q=k=>('p='+q).split(k).length-1
```
Mutually independent functions (thanks to [user81655](https://codegolf.stackexchange.com/users/46855/)). Each function reads its own source code since the character counts are the same after the concatenation.
[Try it online!](https://tio.run/##bcpBCoAgEEDRvReZGcKgXRu7i0SUKTKj4vUnwW3Lz/uv776eJXCzfVdlF92BIA4WprVyCg0jrenKd3vsZmQ6D5cfVy4hN2SECERmlox/lH4)
] |
[Question]
[
Related: [Ellipse circumference](https://codegolf.stackexchange.com/q/211763/78410)
## Introduction
An **ellipsoid** ([Wikipedia](https://en.wikipedia.org/wiki/Ellipsoid) / [MathWorld](https://mathworld.wolfram.com/Ellipsoid.html)) is a 3D object analogous to an ellipse on 2D. Its shape is defined by three principal semi-axes \$a,b,c\$:
$$ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 $$
Just like an ellipse, the volume of an ellipsoid is easy, but its surface area does not have an elementary formula. Even Ramanujan won't save you here.
The basic formula is given as the following:
$$ S = 2\pi c^2 + \frac{2\pi ab}{\sin\varphi}
\left( E(\varphi,k) \sin^2\varphi + F(\varphi,k) \cos^2\varphi \right) \\
\text{where }\cos\varphi = \frac{c}{a},\quad k^2 = \frac{a^2(b^2-c^2)}{b^2(a^2-c^2)},\quad a \ge b \ge c $$
\$F\$ and \$E\$ are incomplete [elliptic integral](https://en.wikipedia.org/wiki/Elliptic_integral) of the first kind and second kind respectively. Note that the formula does not work for a sphere.
A good approximation can be found on [this archived page](https://web.archive.org/web/20110930084035/http://www.numericana.com/answer/ellipsoid.htm), where Knud Thomsen developed a symmetrical formula of
$$ S \approx 4\pi \left(\frac{a^p b^p + b^p c^p + c^p a^p}
{3 - k\left(1-27abc/\left(a+b+c\right)^3\right)}\right)^{\frac{1}{p}} $$
with empirical values of \$p=\frac{\ln 2}{\ln (\pi/2)}\$ and \$k=3/32\$.
## Challenge
Given the three principal semi-axes \$a,b,c\$ of an ellipsoid, compute its surface area.
All three input values are guaranteed to be positive, and you can use any reasonable representation of a real number for input. Also, you may assume the three values are given in a certain order (increasing or decreasing).
The result must be within 0.1% (=10-3) relative error for the given test cases. You can go for the exact formula (if your language has the necessary built-ins) or Thomsen's approximation, or you can go for numerical integration (extra brownie points if you succeed in this way).
## Test cases
The true answer was calculated by feeding the corresponding ellipsoid equation into WolframAlpha.
```
a b c => answer
------------------
1 1 1 => 12.5664
1 1 2 => 21.4784
1 2 2 => 34.6875
1 1 10 => 99.151
1 2 3 => 48.8821
1 10 10 => 647.22
1 3 10 => 212.00
```
[Answer]
# JavaScript (ES7), ~~ 86 83 ~~ 82 bytes
*Saved 3 bytes thanks to @xnor*
*Saved 1 byte thanks to @VarunVejalla*
An approximation of Thomsen's approximation.
```
(a,b,c)=>(519*((a*b)**(p=1.535)+c**p*(b**p+a**p))/(31+27*a*b*c/(a+b+c)**3))**(1/p)
```
[Try it online!](https://tio.run/##XY7NTsMwEITvfYq9xWs7TmznF5EgJFoJAeIBEAfHdaGoaqIkQrx9cNqithxmtNLMt7tf5tsMtt92Y7hv127aVBMxvOEWq5qksqSEGNogpaSrpEh1isxS2lHSeGfGG2JEtGQqp75IbUQMa5j1hMYZk1GH0@iGESrwm6HhYDn0CFUNtt0P7c6JXftB3k7ZOzAIIKy9MSC9Gzy3@QMRxdiutj9uTRI8FmHZ923vS4e@m6@8mPFTmGY40OF8K/J2RjPk4OAWZAyUQqjhDgLy@oQB3Phhdf/4vHzAABeL@W0iOcBJUok0yxK8DhQHJUWSF5eBOkonIivy9JqQMYeyFDKV8I/QHJJCFIWS52Buz8qSXCh1SehjoPxbcQw4/QI "JavaScript (Node.js) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
Shamelessly copying from the [2D solution](https://codegolf.stackexchange.com/a/211764/87058) by @J42161217:
```
SurfaceArea[#~Ellipsoid~#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7i0KC0xOdWxKDUxWrnONScns6A4PzOlTjlW7X9AUWZeSbSyrp2fQ5oDUEDfobraUAcIa3XAtBGYNoLSQGgAFTCGCBjARIxBjNr/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), 86 83 bytes
*Saved three bytes, thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!*
```
->a{(519*a.zip(a.rotate).sum{(_1*_2)**1.535}/(31+27*eval(a*?*)/a.sum**3))**0.65147}
```
[Try it online!](https://tio.run/##fdDbagIxEIDh@z5FLpNUZzOT40IPDyJezIJCwVJxdwWrPvt2xcRW6HoT@Ml8DMyubw7D@nWYv/FReqw1w/fHVjLsvjruVgra/vN44llzkqwbpTWCt/5cSYvPFPVqz5vx412rii@jWls1DhkIHl08D9u@a4VcLxYIZibKs1yKuUACH4JTwE0rqpLiRRgwBp/@kZQlIbiYbjLnhKS/0joIKfoicz7aiSbTugb0WOS1Hq202bkEKdEN5pxaae52BheBqNBrTUh7B2m8pjG/B7pUgcMP "Ruby – Try It Online")
Expects an array of \$a,b,c\$. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves three bytes.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 325 bytes
Takes input as a descending list of semi-axis lengths; +5 bytes if this is not allowed, or +0 bytes if this is not allowed but we need only handle ascending-sorted lists as in the test cases. Spheroid handling takes up 26 bytes of this solution. This solution uses the formula for the surface area of an ellipsoid in the question, which does not hold for spheroids (a=b=c) and requires that a>=b>=c.
The integral calculated by this program is *very* rough to avoid taking too long to output; can easily improve the accuracy of results by reducing $d, and especially by calculating the area of the trapezoid between $x and $x+$d, rather than the rectangle of width $d at $x
```
$a,$b,$c=$args;$u,$p,$z={param($t,$g)for($d=1e-4;$x-lt$t){$i+=(&$g ($x+=$d))*$d}$i},($m=[Math])::PI,$c*$c;if($a-eq$c){4*$p*$z}else{$e=$c/$a;$h=$m::Acos($e);$s=$m::Sin($h);$j={$m::Sqrt(1-($a*$a*($b*$b-$z))/($b*$b*($a*$a-$z))*($v=$m::Sin($args[0]))*$v)};2*$p*$z+2*$p*$a*$b/$s*((&$u $h $j)*$s*$s+(&$u $h {1/(&$j @args)})*$e*$e)}
```
[Try it online!](https://tio.run/##bZLbjpswEIbv8xTWaraywRBMyGFBlrLqTXvRg9pKvYiiFRCTECWBxWYbhfLsqQPJ7jYEjcTM@PPv34c8@yMKuRKbzRESXh0hpBBRiDmExVIGUFLIKRx4lYdFuMWgKCxJkhUYFpwJywtgb20UKFJBanL8AZYIw97ksCDEgEUNaU0xbPnsS6hWc@L73z9rdQPiIE0whJZ4hphUngG5AYdabKSoQHCI@xAGsOKw9f3HOJMYBAlANvXPdIdhpcs1r5r6uVCYWVrN0IEhMiCy4EBIv82NdqRp6fzlTeS0xZkzPzl9IXXgti7M9q/nRH2QBtabKhGsEKw1J3WYl07F@jpdo@lJiNR6WOgg9bHugRJSfQylkIijKe5Nq3SXl6opmEMHlJFA7HMRK7Fomi5zbcchNb1GT3HFjryx7brX7IC6HdKb2JOJy27JdtiHB5sNO6h7Q3Xg2aPJeNhF2Y1t2d544nUM3ED1AQxHI42S96f3F92jqqm/lttIFJzVVQ/pDxo1ChcNDk/2ufVkX5r6dlu4ELLcqPMz9P0fWblbnG42QdNmEqEeaUlRFFmhDV3Qx0hifJ6PLPS6Hmn530WqhPUpkwrdzX5pm@id2fkM8P9LtvL9VxWDOQ4dEnKPviXJ3L8YvWu9vCmZZq8@/gM "PowerShell – Try It Online")
Ungolfed and Explanation
```
#Set a, b, and c to the elements in the input array
$a,$b,$c=$args;
#Declare a function for finding integrals of a provided function, for 0 to $to
$integralFunction={
#take parameters $to (the value to calculate the integral to, from 0)
#and $function (the function to calculate the integral of)
param($to,$function)
#set $dx to .0001 and loop until $x >= $to
for($dx=1e-4;$x-lt$to){
#increase x by dx
$x+=$dx
#calculate the area of the right-side rectangular sliver for this step (f(x)dx)
$integral+=(&$function $x)*$dx
}
#return the integral of the function
$integral
}
#pi!
$pi=[Math]::PI
#if this is a spheroid (due to the assumption a>=b>=c, a=c follows that a=b=c)
if($a-eq$c){
#return the surface area of the sphere
4*$pi*$c*$c
#if this is an ellipsoid
}else{
#cosine of Phi equals the shortest side over the longest side
$cosPhi=$c/$a;
#we need Phi for the integral, so calculate the arccos of cosPhi
$Phi=[Math]::Acos($cosPhi);
#we need the sin of Phi for the final calculation
$sinPhi=[Math]::Sin($Phi);
#set k^2 to this value, because the formula says so
#we don't need k, as the elliptical integrals use k^2
$kSquared= ($a*$a*($b*$b-$c*$c))/($b*$b*($a*$a-$c*$c))
#since both incomplete elliptical integrals have the term
#sqrt(1-k^2*sin^2(theta)), we assign this calculation it's own function
$ellipticalIntegralFunctionBase={
param($theta)
[Math]::Sqrt(1-$kSquared*($sinTheta=[Math]::Sin($theta))*$sinTheta)
};
#the first elliptical integral (F) is the integral from 0 to Phi of
#(1/sqrt(1-k^2*sin^2(theta))) with respect to theta
$FirstEllipticalIntegral = (&$integralFunction -to $Phi -function {param($theta) 1/(&$ellipticalIntegralFunctionBase -theta $theta)})
#the second elliptical integral (E) is the integral from 0 to Phi of
#sqrt(1-k^2*sin^2(theta) with respect to theta
$SecondEllipticalIntegral = (&$integralFunction -to $Phi -function $ellipticalIntegralFunctionBase)
#we have all of our intermediate calculations done, so now we plug those numbers into
#(2*pi*c^2)+((2*pi*a*b)/sin(Phi))*(E*sin^2(Phi)+F*cos^2(Phi))
#we return the result of this calculation implicitly
(2*$pi*$c*$c)+((2*$pi*$a*$b)/$sinPhi)*($SecondEllipticalIntegral*$sinPhi*$sinPhi+$FirstEllipticalIntegral*$cosPhi*$cosPhi)
}
```
[Answer]
# [BQN](https://github.com/mlochbaum/BQN), 50 bytes
```
{(519√ó(+¬¥(‚ä¢√ó1‚ä∏‚åΩ)ùï©‚ãÜp)√∑31+(27√ó√ó¬¥ùï©)√∑3‚ãÜÀú+¬¥ùï©)‚ãÜ√∑p‚Üê1.535}
```
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkHsoNTE5w5coK8K0KOKKosOXMeKKuOKMvSnwnZWp4ouGcCnDtzMxKygyN8OXw5fCtPCdlakpw7cz4ouGy5wrwrTwnZWpKeKLhsO3cOKGkDEuNTM1fQoKb3DihpBGwqjin6gx4oC/MeKAvzHii4Qx4oC/MeKAvzLii4Qx4oC/MuKAvzLii4Qx4oC/MeKAvzEw4ouEMeKAvzLigL8z4ouEMeKAvzEw4oC/MTDii4Qx4oC/M+KAvzEw4p+pCnRlc3Rz4oaQMTIuNTY2NOKAvzIxLjQ3ODTigL8zNC42ODc14oC/OTkuMTUx4oC/NDguODgyMeKAvzY0Ny4yMuKAvzIxMi4wMApkZWx0YXPihpB8KG9wKS10ZXN0cwrijYk+4p+ob3Dii4R0ZXN0c+KLhGRlbHRhc+KLhGRlbHRhc8O3dGVzdHPii4QwLjAwMeKJpWRlbHRhc8O3dGVzdHPin6k=)
An anonymous function which uses Arnauld's formula.
Input given as a single array.
[Answer]
# [Python](https://www.python.org)/[mpmath](https://mpmath.org), 70 bytes
```
lambda a,b,c:4*pi*a*b*c*elliprg(1/a/a,1/b/b,1/c/c)
from mpmath import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDLasQgFIbpNtB3OGSViGPiJYkzMF32KbrRdDITyEWspfRZugmU9p3ap6nRZFWP-MvHd1T8-Dbv7jZPy2d3fvp6dd1B_jwOatTPChTWuD0JZHqkkEYtugxDb-w1o4UqFKaFLrRf26LNk87OI4xmVO4G_Whm61A87ffuvpstOOgnyDKKfeU4JAvJtvRVboBHUO6Er5v8lICx_eQyh6HLkMvzJE1TBaABWoDzA6jp5e1ik8O_kVCAOL1FGanqWmyMBcYoEY0MjO2MC1LLptp7y5Udj4RWdNN40IQkUrLAvBO1WjSEsRXxvZP5a8vSPzj-yrLE_AM)
[DLMF 19.33.1](https://dlmf.nist.gov/19.33#i) relates one of Carlson's symmetric elliptic integrals to the ellipsoid surface area as
$$S=4\pi abcR\_G(a^{-2},b^{-2},c^{-2})$$
This is one of the examples Carlson (who wrote section 19 of the DLMF) uses to propound the superiority of his elliptic integrals over Legendre's \$F/E/\Pi\$ set. Indeed, internally mpmath uses the symmetric integrals to calculate Legendre's integrals.
] |
[Question]
[
Given a sequence of integers or to be more specific a permutation of `0..N`
transform this sequence as following:
* output[x] = reverse(input[input[x]])
* repeat
For example: `[2,1,0]` becomes `[0,1,2]` and reversed is `[2,1,0]`. `[0,2,1]` becomes `[0,1,2]` and reversed `[2,1,0]`.
**Example 1**
```
In: 0 1 2
S#1: 2 1 0
S#2: 2 1 0
Output: 1
```
**Example 2**
```
In: 2 1 0
S#1: 2 1 0
Output: 0
```
**Example 3**
```
In: 3 0 1 2
S#1: 1 0 3 2
S#2: 3 2 1 0
S#3: 3 2 1 0
Output: 2
```
**Example 4**
```
In: 3 0 2 1
S#1: 0 2 3 1
S#2: 2 1 3 0
S#3: 2 0 1 3
S#4: 3 0 2 1
Output: 3
```
Your task is to define a function (or program) that takes a permutation of
integers `0..N` and returns (or outputs) the number of steps until a permutation occurs that has already occured. If `X` transforms to `X` then the output should be zero, If `X` transforms to `Y` and `Y` to `X` (or `Y`) then the output should be 1.
```
Y -> Y: 0 steps
Y -> X -> X: 1 step
Y -> X -> Y: 1 step
A -> B -> C -> D -> C: 3 steps
A -> B -> C -> D -> A: 3 steps
A -> B -> C -> A: 2 steps
A -> B -> C -> C: 2 steps
A -> B -> C -> B: also 2 steps
```
**Testcases:**
```
4 3 0 1 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps
4 3 2 1 0 -> 4 3 2 1 0: 0 steps
4 3 1 2 0 -> 4 1 3 2 0 -> 4 3 2 1 0 -> 4 3 2 1 0: 2 steps
1 2 3 0 4 -> 4 1 0 3 2 -> 0 3 4 1 2 -> 4 3 2 1 0 -> 4 3 2 1 0: 3 steps
5 1 2 3 0 4 -> 0 5 3 2 1 4 -> 1 5 3 2 4 0 -> 1 4 3 2 0 5 ->
5 1 3 2 0 4 -> 0 5 3 2 1 4: 4 steps
```
If your language doesn't support "functions" you may assume that the sequence is given as whitespace seperated list of integers such as `0 1 2` or `3 1 0 2` on a single line.
*Fun facts:*
* the sequence 0,1,2,3,..,N will always transform to N,...,3,2,1,0
* the sequence N,..,3,2,1,0 will always transform to N,..,3,2,1,0
* the sequence 0,1,3,2,...,N+1,N will always transform to N,...,3,2,1,0
**Bonus task**:
Figure out a mathematical formula.
**Optional rules**:
* If your language's first index is 1 instead of 0 you can use permutations `1..N` (you can just add one to every integer in the example and testcases).
[Answer]
# JavaScript (ES6), 54 bytes
```
a=>~(g=a=>g[a]||~-g(g[a]=a.map(i=>a[i]).reverse()))(a)
```
[Try it online!](https://tio.run/##bc5NCoMwEAXgfU8xywxEjT9dxouIi8HGYLFGEnElXj21xiK0ruYtvveYJ83kGtuNUzSYh/Kt9CTLlWm5HV1RvSxrpNknSYpfNLJOllR1NcZWzco6xRCREfrGDM70Ku6NZi2rCg45B8Eh5ZABQI0ISbJFN6nRwe2SZzsXJxeBX@t0L4i/8V8dXPimOHV@re/f4aNw6CJo/wY "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
```
f=lambda l,*h:len(h)-1if l in h else f([l[i]for i in l][::-1],l,*h)
```
[Try it online!](https://tio.run/##FctBDoMgEEbhq/xLMGMitiuSnoSwsBHCJONILC48Pdbty/fq1cquc@/5I8v2XRcIDcVLUlPs6DhDwIqCJL@EbIIEjnk/wE@WGLwfXaRnsr0erO2PWOvZjLU9OMJMeBEmwjve "Python 2 – Try It Online")
[Answer]
# Pyth, ~~10~~ ~~9~~ 8 bytes
```
tl.u@LN_
```
Explanation:
```
t One less than
l the number of values achieved by
.u repeating the following lambda N until already seen value:
@LN_N composing permutation N with its reverse
Q starting with the input.
```
[Test suite](http://pyth.herokuapp.com/?code=tl.u%40LN_&input=%5B5%2C1%2C2%2C3%2C0%2C4%5D&test_suite=1&test_suite_input=%5B4%2C3%2C0%2C1%2C2%5D%0A%5B4%2C3%2C2%2C1%2C0%5D%0A%5B1%2C2%2C3%2C0%2C4%5D%0A%5B5%2C1%2C2%2C3%2C0%2C4%5D&debug=0).
[Answer]
## Haskell, 52 bytes
```
([]#)
a#x|elem x a= -1|n<-x:a=1+n#reverse(map(x!!)x)
```
[Try it online!](https://tio.run/##bcyxDoIwFIXhnac4BAeIbUIRF2OfBBlusCixrU0xpgPPbk0gOhDW8@X8dxofSuvYy0vMmzYrEsrCpLQyCCAJLiZ75uFEUuxt5tVb@VHlhlwe0rQIRTQ0WEhcnwng/GBf2KFHUzMcGEoGwVC1W1bNVm6amHlty7pk65Udf6c/x0/Xa7qNkXfOfQE "Haskell – Try It Online")
```
a # x -- function '#' takes a list of all permutations
-- seen so far (-> 'a') and the current p. (-> 'x')
| elem x a = -1 -- if x has been seen before, return -1
| n<-x:a = -- else let 'n' be the new list of seen p.s and return
1 + -- 1 plus
n # -- a recursive call of '#' with the 'n' and
reverse ... -- the new p.
([]#) -- start with an empty list of seen p.s
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~44~~ 35 bytes
*-9 bytes thanks to nwellnhof*
```
{($_,{.[[R,] |$_]}...{%.{$_}++})-2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlXqdaLzo6SCdWoUYlPrZWT0@vWlWvWiW@Vlu7VlPXqPZ/cWKlQpqGjYGCoYKRnaY1F5RvBOQbIPGNFdBVgESAquw0/wMA "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block
... # Create a sequence where:
$_, # The first element is the input list
{.[[R,] |$_]} # Subsequent elements are the previous element reverse indexed into itself
{ } # Until
%.{$_} # The index of the listt in an anonymous hash is non-zero
++ # Then post increment it
( )-2 # Return the length of the sequence minus 2
```
[Answer]
# J, ~~33~~ ~~27~~ 26 bytes
*-7 thanks to bubbler*
```
_1(+~:i.0:)|.@C.~^:(<@!@#)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/4w01tOusMvUMrDRr9Byc9erirDRsHBQdlDX/a3KlJmfkKxgp2CqkKZgoGAN1GSoYQQQN4IJGQEEDdJVAdTBBY7AgSABkgAlE0AQsaIoQ/g8A "J – Try It Online")
## how
original explanation. my last improvement only changes the piece which finds "the index of the first element we've seen already". it now uses the "nub sieve" to do it in fewer bytes.
```
1 <:@i.~ [: ({: e. }:)\ |.@C.~^:(<@!@#)
|.@C.~ NB. self-apply permutation and reverse
^: NB. this many times:
(<@!@#) NB. the box of the factorial of the
NB. the list len. this guarantees
NB. we terminate, and the box means
NB. we collect all the results
[: ({: e. }:)\ NB. apply this to those results:
\ NB. for each prefix
{: e. }: NB. is the last item contained in
NB. the list of previous items?
1 <:@i.~ NB. in that result find:
1 i.~ NB. the index of the first 1
<:@ NB. and subtract 1
```
Note the entire final phrase `1<:@i.~[:({:e.}:)\` is devoted to finding "the index of the first element which has already been seen." This seems awfully long for obtaining that, but I wasn't able to golf it more. Suggestions welcome.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Ṛị$ƬL’
```
[Try it online!](https://tio.run/##y0rNyan8///hzlkPd3erHFvj86hh5v///6ONdBSMdRRMdBQMdRRMYwE "Jelly – Try It Online")
1-indexed.
[Answer]
# Dyalog APL, ~~29~~ ~~28~~ 27 bytes
```
¯2∘+∘≢{⍵,⍨⊂⌽(⍋⍳⊢)⊃⍵}⍣{⍺≢∪⍺}
```
Takes boxed arrays. Will trainify and explain later.
[Try it here as a test suite](https://tryapl.org/?a=%7B2-%u2368%u2262%7B%u2375%2C%u2368%u2282%u233D%28%u2283%u2375%29%5B%u2283%u2375%5D%7D%u2363%7B%u237A%u2262%u222A%u237A%7D%u2375%7D%A8%u2282%A81+%284%203%200%201%202%29%20%284%203%202%201%200%29%20%281%202%203%200%204%29%20%285%201%202%203%200%204%29&run).
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 90 bytes
```
import StdEnv
$l=length(until(\[h:t]=any((==)h)t)(\[h:t]=[reverse(map((!!)h)h),h:t])[l])-2
```
[Try it online!](https://tio.run/##TcyxbsMgEAbg2X4KImUA6Sy5jrtEZWuHSt0yYgZk04AE2DLnVHn5UoiSKtv93393o9MqJD9Pm9PEKxuS9cu8Ijnh9BEu9d5xp8MZDd0CWkcHYY4ouQpXSjlnhiF7mFj1Ra9RU68WSne7XBoGpWLCSdZ06YQqf@ZEhYmIPbFh2XLkZN6wTMNA6M3gLoy8NQR1xCjrH6NXXVe3lF@Iuqqo6OEALbxAJ6Fj8E9dplZC@0R5p9Bjq8Ry2ks43OkVnrBn2WT6Hb@dOsfUfH6l92tQ3o7xDw "Clean – Try It Online")
] |
[Question]
[
This challenge is created in celebration of my first esoteric language, [Backhand](https://github.com/GuyJoKing/Backhand)!
Backhand is a one dimensional language with a non-linear pointer flow. The pointer moves three steps at a time, only executing every third instruction.
The program `1..1..+..O..@` will add 1+1 and output 2 before terminating. The intermediate instructions are skipped, so `1<>1()+{}O[]@` is exactly the same program.
When the pointer is about to step off the end of the tape, it instead reverses direction and steps the other way, so `[[email protected]](/cdn-cgi/l/email-protection)+.` is the same program. Note that it only counts the end instruction once. This allows us to compress most linear programs down, such as `1O+1@`
Your challenge here is to write a program or function that take a string, and output the instructions that would be executed if the program was interpreted like Backhand (you don't need to handle any actual Backhand instructions). You are to only output until the pointer lands on the last character of the string (at which point the execution would normally go backwards).
**But wait**, that's not all! When your program itself is interpreted in this fashion, the resulting code should output one of the below:
* `(Mostly) works`
* `Turing complete`
* `'Recreational'` (quotes can be either `'` or `"`, but not both)
* `Perfectly okay`
* `Only a few bugs`
For example, if your source code is `code 2 backhand`, then the program `ce cankb od2ahd` should output one of these phrases.
### Test cases:
```
"1 1 + O @" -> "11+O@"
"1O+1@" -> "11+O@"
"HoreWll dlo!" -> "Hello World!"
"abcdefghijklmnopqrstuvwxyz" -> "adgjmpsvyxurolifcbehknqtwz"
"0123456789" -> "0369" (not "0369630369")
"@" -> "@"
"io" -> "io" (Cat program in Backhand)
"!?O" -> "!?O" (Outputs random bits forever in Backhand)
"---!---!" -> "-!-----!"
```
And a [reference program](https://tio.run/##S0pMzs5IzEv5/z9Tpc7AqqY6Nj9WMdNKoTazVsHGIb5MQUXBSiHWQ7EuXtPKykqxorbGKl@z9v9/j/yi1PCcHIWUnHxFAA) written in, of course, Backhand (~~this might be a bit buggy~~ Okay, I think I've fixed it).
### Rules.
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/q/1061/76162) are forbidden
* The input of the first program will contain only printable ASCII and newlines (that is, bytes `0x20`-`0x7E` as well as 0x0A)
* You can choose whether your second program is converted from your first by bytes or by UTF-8 characters.
* Second program:
+ Case does *not* matter, so your output could be `pErFectLy OKay` if you want.
+ Any amount of trailing/leading whitespace (newline, tabs, spaces) are also okay.
+ The second program should be the same language as the first, though not necessarily the same format (program/function)
+ I'm happy to include suggestions from the comments on extra phrases (as long as they're not too short)
* As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), your aim is to get the shortest answer for your language!
* In two weeks, I'll award a 200 bounty to the shortest Backhand answer.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~163~~ ~~130~~ ~~127~~ ~~121~~ ~~115~~ ~~99~~ 96 bytes
```
i=input() ###
print(i+i[-2:0:-1]+i)[:len(i)*(len(i)%3%2or 3):3]
#'p lr+yi n'ottk(ca'eyPf'er)
```
[Try it online!](https://tio.run/##ZVBda9wwEHzXr5izOSTFGM52vyIwKbSFvt299cEcxfHJycaK5Ki69tQ/f5EvLYFWrGZZht3ZnTmGe2fr86ft5y9tlmVnasnOxyAk8jxnsycbBBXUlbXaqLLaFyQ7ZbQVJK/ES14369p5NFI1e4CxnM8wvogEWO5CmMTQcx13I9denpNIVy2T2JiavoMsfG/vtLiWikGf9IBlmTQGM@A5KML2CBO4ww7QEd5gDNCDfpXisOZfqYUtjOeRAuzggp7E2HMfd5ova17uRAvTP94eepxaztVF@XL0C/Ly7@PsdbX/qDQrIPehKDcVKSuNWNdQ@GMf32k/6iFwFMjRNK4hnbyTe1WTIJaLuaWjzGdLnSqLTpOwcu3lnnET4aY@8uRaBaQogC3wMWNZtS2qJX91Xn8zBgfjVqnsb4eDHu/u6WEyj9bNT/5HOP78dYq/E7mp6ubN23fvP1ynYmkml2B1s02Y7lgtP3sG "Python 2 – Try It Online")
Outputs:
```
int #rt+-01i:n)l(%2 :
print('Perfect' + # 33o3ie*(l)]:2i(i
#(p=iu)#pni[:-+[ei(n)%r)]
'ly okay')
```
[Answer]
# [R](https://www.r-project.org/), 187 bytes
```
# c a t ( ' P e r f e c t l y o k a y ' ) #
g=function(x,n=nchar(x),i=c(1:n,(n-1):1,2:n),j=seq(1,3*n-2,3),k=i[j][1:which(i[j]==n)[1]])cat(substring(x,k,k),sep='')
```
[Try it online!](https://tio.run/##1dK9boMwFAXgPU9xQobYjZHq0F8qqx27pVsHykAcAgZqEkOa0JenMepQ0ZDOvbIlW/7O1R1s2hYTSCACaoAAU@AFiAEDrLuD7J4KoIGtEsg733SYApNRItY7LWtVanJgWmiZRoYcKFNCEu5rRrTLqc/Z3NeUZaKKt4Qz70K7c@ZRlgsVZGHA/X2qZErsRQhNAx6GVEY1qXbLqjZKJ8fmOcspq@KNmE4p2oQ4HDiuGbAAnhyKX/UA28N50w4dWb@Y8ZNuwD@XJn4tCqyKcnwy1vPRUq7idZKqLC/edbnZmqrefewPzed3uucv@dy7ur65vbsfGKrnz85@wqvyj0DPjx8X5wM977ru2O7B0E9vA//4vzm0/QI "R – Try It Online")
The single space at the end is needed so that the `\n` never gets printed when the program is applied to itself.
## Explanation
### Part 1:
Ungolfed:
```
# c a t ( ' P e r f e c t l y o k a y ' ) #
g <- function(x) {
n <- nchar(x) # number of characters in string
i <- c(1:n, (n - 1):1, 2:n) # index: 1 to n, n-1 back to 1, 2 to n
j <- seq(1, 3 * n - 2, 3) # every third element of i
k <- i[j][1:which(i[j] == n)[1]] # the elements of i at indices j, up to the first appearance of n
cat(substring(x, k, k), sep = "") # extract from x the characters at indices k, and paste them together
}
```
### Part 2:
The function produces this when it acts on the entire program:
```
cat('Perfectly okay')#=ni(ncr)=1,-:2)=q,n,,i]:i(j=[]assi(k)e'
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~101~~ 86 bytes
*Wow, -25 bytes thanks to nwellnhof by drastically improving the first program*
```
##
{S:g/(.).?.?/$0/}o{.comb%3-1??.chop~.flip~S/.//!!$_} #
#}{ "" s( kM ro os wt l )y.
```
[Try it online!](https://tio.run/##tY/dToNAEIXv9ykOC1pIZbdYrT@kQS9MelHDRRO9bAplW@zi4lKtSOirI9vERzCZmTNnJpnMV2ZaTrqixrnAtLNt0izuN9xlHotYxJ0Rb1XDUlUkZ2M/iCKWblV5ZELm5XHBGeeW5Sxb2MRuG1CKysXuGVpBVTjsAQmvZl21qiFcZ@lBKE1oAPQxBGLggV70g3gYnJqZ0tmrlFhLZRm/StJ1Jjbb/G0ni3dVfuhq//l1@K5/zHYUXI6vric3t3fGnQ7kylQrio34vm@ZpCEhPaGTYNq/MfgfyIEXEsPpJH/Knl4e52H3Cw "Perl 6 – Try It Online")
I'm hoping more people take advantage of the rebound like this. The Backhanded program is
```
#{g.?//{o%1.o.iS/!}
{"(Mostly) works"}#_!.~l~h?-bco0?.(:
#S/).$}.m3?cpfp//$ # .
```
Which comments out to just `{"(Mostly) works"}`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ ~~40~~ ~~38~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
-2 bytes (40→38) thanks to *@Emigna*.
```
„€€Ã€„Ѐ€µ'€Ý)\[ûDN3*©è ?®IgD#<ÖNĀ*#
```
[Try it online](https://tio.run/##MzBNTDJM/f//UcO8R01rgOhwM4humHd4AoR/aKs6SHSuZkz04d0ufsZah1YeXqGgYH9onWe6i7LN4Wl@Rxq0lP//T0xKTklNS8/IzMrOyc3LLygsKi4pLSuvqKwCAA). (PS: Switch the language from **05AB1E (legacy)** to **05AB1E** for test case `0123456789`. The legacy version is faster, but it shows incorrect results for number inputs with leading zeros.)
The 'backhanded' program will become:
```
„ÃеÝ[N© I#N#
```
Which will output `perfectly okay` in full lowercase.
[Try it online.](https://tio.run/##AR4A4f8wNWFiMWX//@KAnsODw5DCtcOdW07CqSBJI04j//8)
**Explanation base program:**
```
„€€Ã€ # Push the string "the pointed"
„Ѐ€µ # Push the string "dm one"
'€Ý '# Push the string "been"
) # Wrap the entire stack in a list
\ # And remove that list from the stack again
[ # Start an infinite loop
û # Palindromize the string at the top of the stack
# i.e. "1O+1@" becomes "1O+1@1+O1" the first iteration,
# and "1O+1@1+O1O+1@1+O1" the next iteration, etc.
D # Duplicate the palindromized string
N3* # 0-indexed index of the loop multiplied by 3
© # Save it in the register (without popping)
è? # Index into the string and print the character
Ig # If the length of the input is exactly 1:
# # Stop the infinite loop
® D <Ö # If the value from the register is divisible by the length - 1
* # And
NĀ # The 0-indexed index of the loop is NOT 0:
# # Stop the infinite loop
```
**Explanation 'backhanded' program:**
```
„ÃÐµÝ # Push the string "perfectly okay"
[ # Start an infinite loop
N© # Push the index, and store it in the register (without popping)
I # Push the input (none given, so nothing happens)
# # If the top of the stack is 1, stop the infinite loop
N # Push the index again
# # If the top of the stack is 1, stop the infinite loop
```
Step by step the following happens:
1. `„ÃеÝ`: STACK becomes `["perfectly okay"]`
2. `[`: Start infinite loop
3. (first loop iteration) `N©`: STACK becomes `["perfectly okay", 0]`
4. (first loop iteration) `I`: STACK remains `["perfectly okay", 0]` because there is no input
5. (first loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop continues
6. (first loop iteration) `N`: STACK becomes `["perfectly okay", 0]`
7. (first loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop continues
8. (second loop iteration) `N©`: STACK becomes `["perfectly okay", 1]`
9. (second loop iteration) `I`: STACK remains `["perfectly okay", 1]` because there is no input
10. (second loop iteration) `#`: STACK becomes `["perfectly okay"]`, and the loop breaks because of the `1` (truthy)
11. Implicitly prints the top of the stack to STDOUT: `perfectly okay`
[See the steps here with the debugger on TIO enabled.](https://tio.run/##ASEA3v8wNWFiMWX//@KAnsODw5DCtcOdW07CqSBJI04j////LWQ)
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„€€Ã€„Ѐ€µ'€Ý` are `the pointed`, `dm one`, and `been` and `„ÃеÝ` is `perfectly okay`.
---
**Old 38-byte version:**
```
„€€Ã€„Ѐ€µ'€Ý)\ giqë¬?[ûDN>3*©è?®Ig<Ö#
```
[Try it online](https://tio.run/##MzBNTDJM/f//UcO8R01rgOhwM4humHd4AoR/aKs6SHSuZoxCembh4dWH1thHH97t4mdnrHVo5eEV9ofWeabbHJ6m/P9/YlJySmpaekZmVnZObl5@QWFRcUlpWXlFZRUA). (PS: Switch the language from **05AB1E (legacy)** to **05AB1E** for test cases `0123456789` and `@`. The legacy version is faster, but it shows incorrect results for number inputs with leading zeros or single-char inputs.)
The 'backhanded' program will become:
```
„ÃÐµÝ q?D3èIÖ<®©>û¬i\€€„€€€€')gë[N*?g#
```
(Where the `q` exits the program and makes everything else no-ops.)
[Try it online.](https://tio.run/##MzBNTDJM/f//UcO8w82HJxzaeniuQqG9i/HhFZ6Hp9kcWndopd3h3YfWZMY8aloDQg3zoAwwUtdMP7w62k/LPl35/38A)
[Answer]
# [Python 2](https://docs.python.org/2/), 130 bytes
```
p='r'#i n t ' P e r f e c t l y o k a y ' #
s=input();S=s+s[-2:0:-1]+s
print S[:len(~-len(s)%3and S or s):3]
```
[Try it online!](https://tio.run/##ZU5NT4QwFDzbXzF0Y4AQkgX8WgzRRE28YcLBw2ZjWCi7uN0WW1YXD/51bDHGgy/ttDPvTeZ1Q7@VIh7v8vuHjFI6dpmr3FkLCKAHXOAJYIACmulTTToHBtiSwA4oJ2qGZyA6a0V36D3/ush0oJdhnM7TMFoFmnSqFT2KZcqZ8L5Ci9o/TUpRo4BU0H6arEazxjKyDtIY7QWtgCrFhnkLPyUn7Mgq2HUJIVMQMvByv67LdFKnjB90w99yyZ/tX2ukEWBOAOTALSU0yoPIvo9SsWfOUXPpGFquq5o1m237uuN7Ibs3pfvD@8dx@DTNeRQnZ@cXl1cLQ6y5lQacm9ygiXHspd8 "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 130 bytes
Early attempt. Not very satisfying.
```
f =/*> " P e r f e c t l y o k a*/y=>""+/**/(g=p=>(c=y[p])?m++%3?g(p+d):y[p+1]?c+g(p+d):c:g(p-d-d,d=-d))(m=0,d=1)
```
[Try it online!](https://tio.run/##xZI9b8IwGIR3fsVhqcLGpSGlpQUpwMjUVF0YChLBdsKHiUMSPsKfp6FioKS03frKw9m655VPurm38RIRz6K0FhqpDgcfcKxqByDAK6CAGPA/hQBSQAMZjmOABeBVrczpEMKtatWigRM5HSqc7D0ase6S85tGN6ARl6ydP3F71BX8dBftXNRkTd5KpyYZo0unnkubHYQJE6PVnTYB9SmxgfxwwAV6BOfDGCwLxLa52yOlS87l9oX/T1zfxGqgNaQ2ZfIt11daGwxMrGW5gHsTIZUfTGfzhV6GJlrFSbrebHfZnpxwTwbzZZRsst06Nnrmi4maLsJVut0XltXt@8bDY/PpuUWuZKg3mq0CdiX2GVaMPTPkFyZ3XELlrkt@ho6OUilWCRz4dPz/9RqzLyEqw/BFbSHy8reHYSXvWf7XguVNJWudngxq42l6dFHGDh8 "JavaScript (Node.js) – Try It Online")
When the code is processed by itself, the following characters are isolated:
```
f =/*> " P e r f e c t l y o k a*/y=>""+/**/…
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
```
which gives:
```
f=>"Perfectly okay"//…
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JŒḄȧ`ȯ“”NNŒḄ2¡3s@”]ȧZỴḢḢ»`Qị⁸ȧ@11€
```
A full program or monadic link accepting a list of characters which prints or yields (respectively).
**[Try it online!](https://tio.run/##y0rNyan8/9/r6KSHO1pOLE84sf5Rw5xHDXP9/MAiRocWGhc7APmxJ5ZHPdy95eGORUB0aHdC4MPd3Y8ad5xY7mBo@Khpzf///9UNDI2MTUzNzC0s1QE "Jelly – Try It Online")** Or see the **[test-suite](https://tio.run/##y0rNyan8/9/r6KSHO1pOLE84sf5Rw5xHDXP9/MAiRocWGhc7APmxJ5ZHPdy95eGORUB0aHdC4MPd3Y8ad5xY7mBo@Khpzf@jew63A2n3//@jlQwVFIBIW0HBX0HBQUmHS0HJ0F/bEMLyyC9KDc/JUUjJyVcECyQmJaekpqVnZGZl5@Tm5RcUFhWXlJaVV1RWgaUNDI2MTUzNzC0swVyIIZn5YErR3h9M6@rqKoKwUiwA "Jelly – Try It Online")**.
The Backhand-parsed code is then:
```
Jȧ“N2s]Ỵ»ị@€
```
A full program or niladic link printing or yielding (respectively) **[Turing complete](https://tio.run/##AR8A4P9qZWxsef//Ssin4oCcTjJzXeG7tMK74buLQOKCrP// "Jelly – Try It Online")**.
### How?
```
JŒḄȧ`ȯ“”NNŒḄ2¡3s@”]ȧZỴḢḢ»`Qị⁸ȧ@11€ - Main Link: list of characters e.g. 'abcd'
J - range of length [1,2,3,4]
ŒḄ - bounce [1,2,3,4,3,2,1]
` - use as both arguments of:
ȧ - logical AND [x AND x = x]
“” - literal empty list of characters
ȯ - logical OR [when x is truthy: x OR y = x]
N - negate }
N - negate } together a no-op
¡ - repeat this...
2 - ... two times:
ŒḄ - bounce [1,2,3,4,3,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,3,4,3,2,1]
3 - literal three
s@ - split into (threes) [[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1,2,3],[4,3,2],[1]]
”] - literal ']' character
ȧ - logical AND [']' is truthy so a no-op]
Z - transpose [[1,4,1,4,1,4,1,4,1],[2,3,2,3,2,3,2,3],[3,2,3,2,3,2,3,2]]
Ỵ - split at new lines [no newline characters exist in this list of ints so effectively wrap in a list]
Ḣ - head [undo that wrap]
Ḣ - head [get the first of the transposed split indices]
- [1,4,1,4,1,4,1,4,1]
` - use as both arguments of:
» - maximum [max(x, x) = x]
Q - de-duplicate [1,4]
⁸ - chain's left argument (the input)
ị - index into it "ad"
11€ - literal eleven for €ach (of input)
ȧ@ - logical AND with swapped args [[11,11,...,11] is truthy]
- "ad"
- (as a full program implicit print)
```
the Backhand-parsed code is then:
```
Jȧ“N2s]Ỵ»ị@€ - Main Link: no arguments
J - range of length (of an implicit 0, treated as [0]) -> [1]
“N2s]Ỵ» - compression of "Turing complete"
ȧ - logical AND [[1] is truthy] -> "Turing complete"
€ - for each character in the list of characters:
@ - with swapped arguments (an implicit 0 is on the right, so f(0, "Turing complete"))
ị - index into
- (as a full program implicit print)
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 294 bytes
```
>; " O n l y a F e w B u g s " @
/{\!? =ka:{;!?=ka\
v R R {{R:ak=?!\:$:'@=?!;{:/
v/?!/:$:'@=?!;}:ak= ?!;}:ak=?!\}\ }
y\=ka:L }{ / }
\iuakrU y<< ! }}}L {{{L
```
[Try it online!](https://tio.run/##hY4xD4IwEIV3fsWrMXHsXkCIgxOJCYlbl4qIWEQFAbHpb8eCQWOi8Ya7d5fv7l1R5WnUdXMbE2AF5EAGtOhDDHkJxEAz6AVQAQlQoud9C3@DKk48U10pmLKJZyq3ajMIf66EUCpkQroe4WzKZr4RtmLUqqlH6GuiewSjMKzm4wVttbw3DL4baAX6RnlaCVmsn20Lx/lgiUG0DsxLKug6sYm28S7ZpweZHfPT@VKU16pubu39AQ "Runic Enchantments – Try It Online")
Uncompressed (and almost readable) version:
```
>; " O n l y a F e w B u g s " @
; / \
/y<< R R {{R:ak=?!\:$:'@=?!;{:ak=?!\{:ak=?!\{/
RiuakrR:ak=?!/:$:'@=?!;}:ak= ?!/}:ak=?!\}\ } ;
\y<< U }{ / }
\ ! L }}}L
```
[Try it Online!](https://tio.run/##KyrNy0z@/9/fSSGvtDwnPbWy2E1BQSFRgUuBMLBGYusTVB0DNlK/0sYGLhSEU3GQQnV1kFVitq29YoyVipW6A5BhXQ0VgNP6YCODMksTs4ugqvXhqmtBAgpAkVqo8toYmOm1GD4BGxQDdlsoAX/UViM8W4sUTDGEAkARwfTBbnJtrQ8oKmIQcRGjAIKJMQoA)
This...is about as close as I can get.
Compressing it further would require figuring out a way to handle the various loop swapping points without having them collide with other stuff. The first line (which is the only part needs to be passed as input to itself) is required to remain separate: the entire string can't fit on the second line without causing problems (`_` for required spaces):
```
Needed string:
>; " O n l y _ a _ F e w _ B u g s
Best fit:
>; " O n l y _ a _ F e w/{_\!? =ka:{;!?=ka\
Collision: ↑
```
That `?` can't be moved away from the `!` which itself can't be moved away from the `\` and none of the allowable messages allow any of these three characters at this position.
The alternative would be to use flow redirection, but that leads to a problem on the lower line:
```
Last usable character:
↓
>"Only a Few Bugs"@
/.../
ur }{L
↑
Earliest available free space:
```
As we have to avoid the loop switch in the main program.
Known issues:
* Extremely large inputs. Due to Runic's IP stack limits, pushing very large input strings will cause the IP to expire before completing. This can be minimized by spawning additional IPs and merging them (for example, it handles `abcdefghijklmnopqrstuvwxyz` but not the entirety of its own source). And there's a limit regardless of how many merges occur. Can handle up to 58 bytes of input as-is (additionally, increasing the number of IPs requires figuring out how to get them to merge without using more space). Can fit two more IP entries on the loop-return line (to the right of the `U` on the line starting `\y<<` in the uncompressed version, or one left on the line above the `y<<` in the compressed version) raising the input max length to 78.
* Input strings with spaces need to have the spaces escaped (e.g. `1\ \ 1\ \ +\ \ O\ \ @`). This is a limitation of the language's input parsing.
* Cannot supply inputs consisting of strings that look like integers beginning with any number of `0`s (as when turned into a number on the stack, the `0` is lost). Again, limitation of the language's input parsing.
### How it works
Entry:
1. Combine 4 instruction pointers
2. Read input, break into characters, append a newline, reverse, enter main loop.
Main loop (anything that pops the stack is preceded by a dup):
1. Print the top of the stack
2. Compare to newline. True: switch loops and rotate stack left twice.
3. Compare to `@`. True: terminate. (Terminate command executed)
4. Rotate stack right
5. Compare to newline. True: terminate. (Rightmost command executed)
6. Rotate stack right
7. Compare to newline. True: switch loops and rotate stack left thrice.
8. Rotate stack right
9. Return to top of loop
Secondary loop:
* Identical to main loop, only switch rotate right with rotate left
] |
[Question]
[
Given an integer matrix `a` and a nonnegative integer `i`, output a mapping `b` that maps the distinct values in the `i`th column of `a` to rows of `a` who have that value in the `i`th column.
You may assume that `i` is in the half-open range `[0, num_cols(a))` (or `[1, num_cols(a)]` if you choose to use 1-based indices), and that all integers are within the representable range for your language. Input and output may be done in any reasonable manner, so long as it satisfies the basic requirements of the challenge (2D array -> mapping from ints to 2D arrays of ints). So long as the mapping is clear and consistent, the keys do not need to be included in the output.
## Examples
```
[[1]], 0 -> {1: [[1]]}
[[3, 4, 5], [1, 4, 2], [5, 5, 5], [7, 7, 7], [1, 5, 9]], 1 -> {4: [[3, 4, 5], [1, 4, 2]], 5: [[5, 5, 5], [1, 5, 9]], 7: [[7, 7, 7]]}
[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [2, 3, 4, 5, 6], [8, 9, 100, 0, 2]], 4 -> {5: [[1, 2, 3, 4, 5]], 1: [[5, 4, 3, 2, 1]], 6: [[2, 3, 4, 5, 6]], 2: [[8, 9, 100, 0, 2]]}
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 24 bytes
```
@(a,i)@(n)a(a(:,i)==n,:)
```
[Try it online!](https://tio.run/##XYzNCsJADITvPsUcEwhLt@3607DQ9xAPi1ropQoVX38NQYoIcxi@Sb7H9VXe9zrlEEIdqcjMIy1cqNBgPedFBq63eX0SJjp3gl6QFNFLq0jiURzE45OR08Vmpp7Butv@o9HIFP@onQo2d/LSOYz6Mwn2iqO5jTeNwNKaMH2F9QM "Octave – Try It Online")
This creates an anonymous function that returns a matrix whose rows match the criteria. Octave indexes arrays at 1, not zero, and rows of a matrix are separated by a `;`.
Matrices are what Octave does best—so well, in fact, that this challenge can be solved using pure syntax, no built-in functions.
## Explanation
```
@(a,i) % creates an anonymous function that...
@(n) % returns another function that takes input n and
% maps it to the rows of a.
a( ,:) % Return all the columns of a, with the rows filtered by...
a(:,i) % whether the ith column of each row of a...
==n % equals n
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
->a,i{a.group_by{|x|x[i]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ7M6US@9KL@0ID6psrqmoqYiOjO2tvZ/gUJadHS0YWysjoJBLBeEZ6yjYKKjYAoUijYEM41ATFOgEFTUXEcBhKAKgKKWIP2GMP1AMSMdBSRTTMFMY7CwIUgAIa2jYAYSsACaAZQzMAA6A2QfUMwk9j8A "Ruby – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes
```
#~GroupBy~Extract@#2&
```
1-indexed. Returns an `Association` mapping.
[Try it online!](https://tio.run/##TYzLCsIwEEX3@YqBgqjMIkmND0QIgrj1F0Kx2EWrhAhKSH89zsSCwiwO5869vQu3a@9C17jcHua5Gs/@/nwc3@PpFbxrgq30LC/24uK7Idhla62NQsQYVUoIKiFzjbBCMCSiKqgZDanJbhD4pgeyO27rb5uMRvjbMAXrohWLX4ywZrGlBcqkRJC8k7gpRMof "Wolfram Language (Mathematica) – Try It Online")
This is a rare case in which a longer function (`Extract`) reduces the byte count (the shorter one being `Part` or `[[ ... ]]`) because `Extract` can curry. The result is this extremely concise two-function solution.
### Explanation
```
Extract@#2
```
Function that extracts the `<second input>`th element.
```
#~GroupBy~ ...
```
Group the `<first input>` into lists associated with distinct keys `<above function>[element]`.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 40 bytes
```
import StdEnv
```
#
```
\n l i=filter(\a=a!!n==i)l
```
[Try it online!](https://tio.run/##RY4xC8IwEIV3f8UTlxYi2FZFh2w6CG6ObYczthJIrpKmgn/eGKso3HDve3ePp0xDHGx3GUwDS5qDtrfOeZz8Zc/3cPLk/GQGco4ePSTKMhPIBQqBpcCqFihX41qMOHuDvy2wfoONwDZ6i4VAnLyuYyIP9ty4mLiMoh1Yed1xlBXDQMtWG9@4pCJJ0ylLqVMzkUh@h9/3T68UeXiq1tC1D/PDMeweTFar/gU "Clean – Try It Online")
A lambda (`:: Int [[Int]] Int -> [[Int]]`) where a partial application of just the first two arguments gives a mapping on the third argument.
[Answer]
# [J](http://jsoftware.com/), 16 bytes
-3 bytes thanks to FrownyFrog!
```
{"1(~.@[;"0</.)]
```
[Try it online!](https://tio.run/##NY3BCsIwDIbvfYqfXuYgxKRrnVYHvod4Eot48bCjuFevKWP8h3x/@ELetcwTQ5Ah9et1t/D1dvZy2XN/r73zjK5M3IHwyyizc8/H62N@ga6ohgMiEhlGBEJqIYwtlNXaCasb2xnC5icbg1UlbEscKB/NVxF7Euof "J – Try It Online")
## Explanation:
A dyadic verb, taking `i` as its left argument and `a` as its right one.
`]` is the right argument, `a`
`{"1` finds the numbers at `i`th column on each row
`</.` boxes groups from the right argument, selected by the keys, provided by the left one
`~.@[` finds the unique keys
`;"0` links the keys to the selected groups
[Answer]
# [Haskell](https://www.haskell.org/), ~~64~~ 60 bytes
```
import Data.List
i!l=[(k,[a|a<-l,a!!i==k])|k<-nub$map(!!i)l]
```
[Try it online!](https://tio.run/##TY3LCsIwEEX3fsUEXLQwlcS2PqDdudQvCEFGEAxJa2njrv8eJ6WgMIvDuTN3XjS5p/cx2m54jwEuFGh3tVPYWOFbnTnUNFNTeCQhbNs6k8@uKfrPY9vRkLHLvYkd2R5aYHO7wzDaPmwANEihtTKGGUExlwgVQm0QtFpwn7BmtdojQpp1ge15va5SE@8j/HXUC5aLVkn8YoRDEidu4ExKBJm@pTITvw "Haskell – Try It Online")
[Answer]
# jq, 100 bytes
uses an object for output, takes a command line argument `$f` plus an array on standard input
```
([.[]|.[$f]]|unique) as $c|[$c[] as $d|{($d|tostring):([.[]|[select(.[$f]==$d)]]|add)}]|add
```
deobfuscated:
```
.fieldnum as $field |
.input as $input |
([$input[] | .[$field]] | unique) as $categories |
[
$categories[] as $category |
{
($category | tostring) :
([$input[] | [select(.[$field]==$category)]] | add)
}
] | add
```
[Answer]
# [R](https://www.r-project.org/), ~~79~~ 55 bytes
```
function(a,i)for(z in unique(a[,i]))print(a[a[,i]==z,])
```
[Try it online!](https://tio.run/##XY3NCsIwEITveYoFL1lYwSTWH7BHX0D0JB6CWFjQtJYWtC9fl5UWK1nIzE7mS91HB7s5PGJT88s6koOGdeeMif4nvNpAsCTICJwKr/o762Gc2i3qJYWj4JTiBRcmOKeIEZqpCLr8i1YEG4HKfrEgkPE4RMfDaS9fKDkzpsj7ok3XhstkIzEWZW074ARt4md7s/FMfEGsak6NGLV53tEF@9mkeI9VdX/bSY3GFx1Ouqaw0RE7FZ7YqwjEAfsP "R – Try It Online")
24 bytes shaved off by @JayCe
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 29 bytes
```
a=>i=>n=>filter(r=>r[i]==n,a)
```
[Try it online!](https://tio.run/##LcoxCsAgDIXhqzgmkMVWKR3iRcTBoYJQVIL3t1qEN/x8vCa11zISj8gusyvsUn77IyDsxOfAXCjiaJJLhwTen6QMKRtIef3nsdJO2nqRWtuHqXcICBrBII4P "Proton – Try It Online")
-3 bytes thanks to Mr. Xcoder using currying and `filter` (TBH I'm kind of surprised that `filter` actually worked)
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda a,i:lambda n:[r for r in a if r[i]==n]
```
[Try it online!](https://tio.run/##LcrBCoMwEIThV5ljAnuxKqKQJ1lzSCnBBbvK4sWnT2MJzOHjZ8772g7tSw5r2dP3/UlIJEujLmzIh8EgigTJMJYYgsZymujlsmPuCQNhjATu/nw9HGtqdSI8a4da51jdeTd4X34 "Python 3 – Try It Online")
Returns the mapping represented as an anonymous lambda.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 29 bytes
```
a=>i=>n=>a.filter(e=>e[i]==n)
```
[Try it online!](https://tio.run/##jY7LCsIwEEX3fsUsE4glsa0PJPkAF7pwGbIINS2RkkhbBL8@ZkpBdwqzuJy5w5y7fdqxGfxjWod4c6mVyUrlpQpS2aL1/eQG4qRy2hspA01NDGPsXdHHjpyul3MxToMPnW9fBFqidcmgYlAbBlrMcYOxzmihOwY4SyHTgzGUCEoqCpQeV78eCKxzvPivng0YfFnVcyxnLBB81gy2CPbZKe84Z8DR36Db8i@9AQ "JavaScript (Node.js) – Try It Online")
Updated now that I realize the loose output requirements. This uses currying as a golfing technique, and it also returns a function that takes an input `n` and maps that to the proper arrays.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
ịⱮ⁹¹ƙ
```
[Try it online!](https://tio.run/##y0rNyan8///h7u5HG9c9atx5aOexmf8PLz866eHOGf//G/2PjjbWUTDRUTCN1VGINgQzjUBMU6AQVNRcRwGEoAqAopaxsQA "Jelly – Try It Online")
Omits the keys, but should be clear.
Argument 1: **i + 1**
Argument 2: **a**
[Answer]
# Java 10, ~~135~~ 64 bytes
```
m->i->n->new java.util.Stack(){{for(var a:m)if(a[i]==n)add(a);}}
```
Returns a `Function<Integer, List<int[]>>` accepting an integer-input `n`, which returns a List of arrays (matrix-rows) where the `i`'th values equal the given `n`.
[Try it online.](https://tio.run/##pVJRb5swEH7frzjxZIsLCm3pViiR@tBJlban9A3x4AVTOQWDwGSLEL89O8BJIy2ZNA0s@Xy@@@6@z7cVO7HYZu@HTSHaFr4LpftPAK0RRm1gS7deZ1Th5Z3eGFVp76s1HpU2SZqk@NegF23km2z@Oeibas1cYUUf5BDDoVys1GKlacmfZ6FrIzbvjPd9XjVsJxoQYclVzkSi0jjWXGQZEzwahkNExGjV3Y@CuFmKu0plUBJttjaN0m9JCoKPEgAY2Ro2FrNU@94fBoQlwslJHh5dCb7FOwwG7H3ab2gPMJjOn5H@Ecg/B6JY8l4F8/EGj4AB7bd09sm2Xrwn@ws@oL9c4pLKEfzdOXyAPt6TfyowzEKcKzBVtNVKHJNA4ZwL8pco60K@6LozrdVmvW@NLL2qM15NsplCM2cKCKGMHffjeZ6aRuxbL5Oyfq1miVnJXScCRXHKEv6P8YBGtl1haEJyT9R1sSd4axzRx8kYGenwEhUiM7UFExHCcRJwIntlU8epgBDYxRb43IEtqjm3uWAR3Rj@0MMctRCkxUe5U4KTnnyXpH6eeQA5icnYJWiSU7tOCI47hVnuw7XnmidhOPwG)
**Explanation:**
```
m->i-> // Method with int-matrix and int parameters and Function return-type
n-> // Return a Function with integer as parameter
new java.util.Stack(){{
// and List of integer-arrays as return-type
for(var a:m) // Loop over the arrays of the input-matrix
if(a[i]==n) // If the `i`'the value of the current array equals `n`:
add(a);}} // Add it to the return-List
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
fo=⁰!²⁴
```
[Try it online!](https://tio.run/##yygtzv6fG6zzqKnx0KZHjRuOTDdRMFUw/5@WbwvkKYLEtvz//z862ljHRMc0VifaEEgbAWlTHVMw31wHCMHipjqWsbH/jQA "Husk – Try It Online") This function is 1-indexed and, when partially applied, returns a function of type `TNum -> [[TNum]]` which implements the desired mapping.
] |
[Question]
[
### Challenge:
You'll be given an ASCII image of a pile of weights as input, and must output the combined weight of the pile.
[](https://i.stack.imgur.com/fe6XLs.jpg)
### Format:
There are 5 different weights, weighing **1, 2, 5, 10, 20** [Passerees](https://en.wikipedia.org/wiki/Passeree) (or some other arbitrary unit).
The weights looks like this, in ascending order:
```
1: __
|__|
2: ______
|______|
5: ______
| |
|______|
10: ______________
| |
|______________|
20: ____________________
| |
|____________________|
```
The weighs will be symmetrically placed (as in the example image), not necessarily in a sorted order. Weighs will share boundaries, where applicable:
### Test cases:
You may use all the single weights as test cases too.
```
__
_|__|_
|______|
| |
|______|
1 + 2 + 5 = 8
```
```
____________________
| |
|____________________|
| |
|______________|
_|__|_
|______|
| |
|______|
20 + 10 + 1 + 2 + 5 = 38
```
```
______
|______|
|______|
|______|
|______|
2 + 2 + 2 + 2 = 8
```
### Additional rules:
* You may **not** assume additional leading spaces. The largest weight will be all the way to the left.
* You may assume trailing spaces and newlines.
* You may assume there will be maximum 10 weights
* You may take the input on an optional format, but you can't substitute the characters used by something else
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes each languages wins. Explanations are encouraged as always.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟ⁶Ỵẹ€”|IFṚ’œṗ$Ḅ:3“ÇÞ‘yS
```
**[Try it online!](https://tio.run/##y0rNyan8///hjvmPGrc93L3l4a6dj5rWPGqYW@Pp9nDnrEcNM49OfrhzusrDHS1Wxo8a5hxuPzzvUcOMyuD///8rxGMBXDUKWEANVw02xTVcIDl0pSACizowiAfK1MTDuDVo0jVIRiDLAwAA "Jelly – Try It Online")**
### How?
The weights may be identified by their widths and heights. The widths may be measured by looking at the distance between the line's `|` characters. If we first remove all the spaces then those weights of height two will contribute such a line with a measured width of one.
The different weights have widths of `3, 7, 7, 15, 21` (for weights `1, 2, 5, 10, 20` respectively). Adding a trailing `1` for those of height two we find `[3],[7],[7,1],[15,1],[21,1]` converting from binary these are `3,7,15,31,43`, integer dividing by three gives us `1,2,5,10,14`, which are the weights except `14` needs replacing by `20`.
```
ḟ⁶Ỵẹ€”|IFṚ’œṗ$Ḅ:3“ÇÞ‘yS - Link: list of characters e.g. <example 2>
⁶ - literal space character
ḟ - filter discard
Ỵ - split at new lines
”| - literal pipe character
ẹ€ - get indices for €ach [[],[1,2],[1,22],[1,2],[1,16],[2,5],[1,8],[1,2],[1,8]]
I - incremental differences [[],[1],[21],[1],[15],[3],[7],[1],[7]]
F - flatten [1,21,1,15,3,7,1,7]
Ṛ - reverse [7,1,7,3,15,1,21,1]
$ - last two links as a monad:
’ - decrement [6,0,6,2,14,0,20,0]
œṗ - partition at truthy indices [[],[7,1],[7],[3],[15,1],[21,1]]
Ḅ - convert from binary [0,15,7,3,31,43]
:3 - integer divide by three [0,5,2,1,10,14]
“ÇÞ‘ - code-page-indices [14,20]
y - translate [0,5,2,1,10,20]
S - sum 38
```
---
Alternatively replace the measured widths of `21` with `30` prior to the conversion using `“ßœ‘y`:
```
ḟ⁶Ỵẹ€”|IF“ßœ‘yṚ’œṗ$Ḅ:3S
```
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
lambda x:sum(i/21*x.count('|'+i%21*' _'[i<50]+'|')for i in[23,48,69,224,440])
```
[Try it online!](https://tio.run/##dVBtC4IwEP6@X3EIoeYoWxZl@UtMhr1Ig3xBJxjsv9u20lTqYdzdnnvudrviye95RtokOLWPOD1fY2j8qk4ttiSrebO45HXGLVOYDptJwgRqhuy4cSNHcnaSl8CAZSFZY2@Ht3tMiIc9z43slt8qXgWhYRgIAChFQAWVB0mrIJAADdEzUouRLqA/0OnH6KvHEOpRMZUq80On8Zmu007SYtBimP92nw4/@OffQMojpJaoliX3qH3lFyXLuI4P7zCx1MVuXw "Python 2 – Try It Online")
`[i/21, i%21, ' _'[i<50] for i in [23,48,69,224,440]]` will generate the following triplets `[1, 2, '_'], [2, 6, '_'], [3, 6, ' '], [10, 14, ' '], [20, 20, ' ']` that represent the weight, the lenght and the character in the base of each weight, that will be used to make a unique single-line representation of each weight.
Since the 3rd weight would overlap with the 2nd, I replace it's base with it's body (`_` -> ) and reduced the value to `3` (it will count the base as `2` and the body as `3`, resulting in `5`)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
T`|`!
!__!
1
!_{6}!
11
! {6}!
3$*
!.{14}!
5$*
!.{20}!
10$*
1
```
[Try it online!](https://tio.run/##K0otycxL/P8/JKEmQZFLMT5ekcsQSFWb1QIZQJYCmGWsosWlqFdtaAJkm0LYRgYgFQZAjuH//wrxWABXjQIWUMNVg01xDRdIDl0piMCiDgzigTI18TBuDZp0DZIRyPJAJgA "Retina 0.8.2 – Try It Online") Explanation: The `|`s are replaced with `!`s for ease of matching, then the weights are converted into unary and totalled. The only interesting portion is that the `5` weight is considered to be the sum of a `2` and a `3` weight, while the `10` and `20` weights are just two lines of half the weight.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 73 bytes
```
x=>x.replace(/\|.*\|/g,s=>u+=s.length/4*(s[1]<1?s[21]?29/11:1.5:1),u=0)|u
```
[Try it online!](https://tio.run/##bYxRC4IwFEbf9yt83My2JvWQNP0hKio2tRhOnIYP97@vDCKRnYcLl3P4ntWrMvX4GKZjr@/SNsIuIl7oKAdV1RKzDKifAWsDI@L5IAxVsm@njp19bFKe33hi0pDnSXhlnEecXiJOglmcCMy21r3RSlKlW9zgEnmFAwSeA0DgigGtbp@ux9F9KT4Git8LOw2bia3/r6OSEPsG "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 76 bytes
```
lambda t:sum([1,2,3,5,5,9,11][len(x)//4+(x<'_')]for x in t.split('|')[1::2])
```
[Try it online!](https://tio.run/##dVHtboMgFP3PU9x/QEraYdekM/NJtDGuxc3EohGWuZQ@uwMUa5vuKDfAPfdwP9pf/dXI7VAm2VAX549TATpW32eSchaxLdvZ741xfkhrIUlPN5vXFenfcY7poWw66KGSoNeqrStNsME05XEcHeighdLHQgmVYIwzBAB5jiA3uf2RtQ4GGfAwtxsOK4js2kECe2QjniCE3WMWuYdxb5tHqjNPeB5TkoH74DYLiaX/po6iF1sA92ZRzXYPcz2LDvy/iabgcbl22FauO6W7qiU09DyTmcQUITeN0HQ/lDCA2GfqjqyQ6kd0Vio4rVpQwQzORe@PCac@JmcwR4ybmZ/gkTL7K6nJxJkStDk5Rts5V4kv7s1rJkXfiqMWpxguI//K4LPRcCmJY9Dr2tcz/AE "Python 3 – Try It Online")
### How?
```
sum([1,2,3,5,5,9,11][len(x)//4+(x<'_')]for x in t.split('|')[1::2])
t.split('|') - split ascii art into pieces
[1::2]) - weights are at odd indexes
for x in - iterates over the weights
len(x)//4 - map widths to 0,1,3,5,7
+(x<'_') - add 1 if the first row of 2-row weight
[1,2,3,5,5,9,11][ ] - value of each part of a weight
sum( ) - add 'em all up
```
[Answer]
I'm sure there are some improvements to be made, but this is what I have at the moment:
# Groovy, 131 bytes
`def f(s){s.split('\n').sum{n=0;[2:1,6:2,14:5,20:10].each{k,v->if(it==~".*\\|[ _]{$k}\\|.*"){n=v+(!it.contains('_')&&k==6?1:0)}};n}}`
Converts the input `String` into a `Collection<String>` and then sums the results for each line to get the total. Uses a `Map` where the key is the number of spaces or underscores in between the pipe characters and the value is the corresponding Passerees amount. The key is plugged into the regex to determine if the line matches a significant pattern. The one caveat is the ternary to add 1 in the case where the length of the substring between the pipes is 6 and is composed of spaces (as opposed to underscores). If no pattern matches, the line has a value of 0.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 57 bytes
```
{sum map {.comb+>2*(1.5,3)[.comb>16]**!/_/},m:g/\|.*?\|/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyE3sUChWi85PzdJ285IS8NQz1THWDMaLGBnaBarpaWoH69fq5Nrla4fU6OnZR9To1/7vzixUiFNQyVeUyEtv0ih0KokX9/Vz8VQXwfONkJiG@tbcykoKMTHcynE18QDEReQBIEarhoFMKhBiIDMAarDAmCKUQFcKyqoAdlYg64URGBRBwZQp8HUoknXIBmBIg/yK8y9SP7CzQAFyH8A "Perl 6 – Try It Online")
] |
[Question]
[
I have an issue with my keyboard (more likely an issue with my browser). Some times when I click on a new text field and begin typing all my text comes out backwards. After a very short amount of time (for the purpose of the challenge we will say it is 10 milliseconds) it resumes typing forwards again. It seems that at first my cursor does not move when I begin to type so all the letters get inserted at the beginning of the textfield.
For example if I were typing `python` and I typed `pyt` in the first 10 milliseconds the result would be
```
hontyp
```
# Task
Your job is to simulate this behavior in as few bytes as possible.
## Input
You may take input in any reasonable method. You may not however take the input as two separate fields. The 10 millisecond delay should start when the program begins to allow input. That is you may have preprocessing to do before input is allowed, which should not be counted towards the 10 milliseconds.
Some leniency is permitted in the timing as long as it averages 10 milliseconds and is off by more than 1 milliseconds no more than 1% of the time on a reasonably speced computer.
## Output
You may output the string in whatever method you see fit. You may either update live as the user is typing or output the result after you are finished taking input (either by a newline or end of file `^D`).
# Test cases
*Some of these were generated by [this CMC](http://chat.stackexchange.com/transcript/message/36744438#36744438) in The Nineteenth Byte*
```
First 10 | after | result
bra in-flak in-flakarb
ap ple plepa
code- golf golf-edoc
no ne neon
we st stew
ai med media
draw back backward
```
[Answer]
# VimScript, 48 47 bytes
Vim has some nice builtins for this. Requires Vim 8.
```
se ri|cal timer_start(10,{->execute("se ri&")})
```
Expects text entered in insert mode, a very reasonable input for VimScript. Explanation:
```
se ri " short for 'set revins', or 'reverse insert'
cal timer_start(10, " Start a timer that fires after 10ms
{->execute("se ri&")}) " Give it a lambda that unsets ri
```
My initial approach, `se ri|sl10m|se ri&`, doesn't work because the text is buffered until after the sleep command, and I couldn't find a way around this.
[Answer]
## HTML (JS), 96 bytes
```
<input id=i oninput=i.d=i.d||Date.now()+1e3;Date.now()<i.d&&(i.selectionEnd=i.selectionStart=0)>
```
Starts timing for 1s from the first keypress to give you a chance to see it in action.
[Answer]
## JavaScript (ES6), 88 bytes
```
p=s='',t=+new Date,document.onkeyup=k=>console.log(+new Date-t>9?(s+=k.key)+p:p=k.key+p)
```
### Demo
The way the snippet is working, you'll need to **click inside its frame** so that it gets focus *after* clicking on the *Run* button and *before* you can start typing.
There's no way to do that in less that 10ms. So, I've set the delay to 1 second in this demo -- and even so, you'd better hurry.
```
p=s='',t=+new Date,document.onkeyup=k=>console.log(+new Date-t>999?(s+=k.key)+p:p=k.key+p)
```
[Answer]
# Processing, ~~167~~ ~~165~~ 146 bytes
```
String a="",b="";long m=0;void setup(){size(9,9);}void draw(){m=m<1?millis():m;println(b+a);}void keyTyped(){if(millis()-m>9)b+=key;else a=key+a;}
```
Takes input as keystrokes and outputs to the console. It updates every frame.
### Explanation
```
String a="",b=""; // a contains the reversed (in the 10 milliseconds) string, b contains the text that is typed after the 10 milliseconds.
long m=0; // Store the start milliseconds in variable m
void setup() {
size(9,9); // set the dimensions of the window
}
void draw() { // loop forever
m=m<1?millis():m; // update m
println(b+a); // print the string b+a
}
void keyTyped() { // this function gets called whenever a key is typed
if(millis() - m) >9) // if over 9 milliseconds have elapsed then
b+=key; // add the key to the end of b
else // else (if less than 10 milliseconds have elapsed)
a=key+a; // prepend the key to a
}
```
[Answer]
# C - 169 bytes
Well C is not the best for this as it has no platform-independent way of doing this. Works under MSVC.
```
#include<time.h>
#include<conio.h>
l,k,b[9];main(a){for(a=clock();clock()-a<100;(k=_getch())?b[l++]=k:0);for(;(k=_getch())-13;k?putchar(k):0);for(;l;putchar(b[--l]));}
```
Bit of a hacky approach, if you can type more than 9 characters in 10 ms, this will crash. Updates after a newline character.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~112~~ 106
```
import msvcrt as m,time
a=b=''
T=time.time
t=T()
while 1:c=m.getch();exec'ba=+c=+cb'[T()-t>1::2];print a+b
```
If you want the output to be flush, without flooding with lines, use `print'\r'+a+b,` instead
You'll need to kill the process to stop it
] |
[Question]
[
In a steam-punk multidimensional world, our boss wants to affix printed index labels to each drawer in our conglomerate's multidimensional file cabinet.
The boss wants to typeset the entire label sheet as a single form, using a font bought only for this purpose, so we have to order the [sorts](https://en.wikipedia.org/wiki/Sort_(typesetting)) (metal symbol pieces). Since sorts are very expensive, our order must be for the exact count of each digit-symbol.
For a given (by any means) set of lengths of dimensions ≥ 0, return (by any means) our order, which is the frequency table of digits required to typeset all the Cartesian coordinates. It must be arranged by keyboard order of appearance (i.e. 0 after 9), and may not include orders of 0 sorts, so if no sorts are to be ordered at all (because a dimension has length 0); print nothing.
* Bonus of -3 sorts if your code can handle (i.e. print nothing) 0 dimensions too.
* Final newline chars are acceptable.
* Prohibition on standard loopholes apply.
* As mentioned, sorts are expensive, this is therefore [codecolf](/questions/tagged/codecolf "show questions tagged 'codecolf'").
A kind soul may edit this challenge to include automated scoring, so include a header like:
`# LanguageName, 123 sorts`
### Test cases
Given `11`, print:
```
1 4
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
0 1
```
because the needed labels are `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, and `11`.
---
Given `2 3`, print:
```
1 5
2 5
3 2
```
because the needed labels are `1 1`, `1 2`, `1 3`, `2 1`, `2 2`, and `2 3`.
---
Given `2 0`, print an empty line:
or nothing.
---
Given `1 2 3`, print:
```
1 11
2 5
3 2
```
because the needed labels are `1 1 1`, `1 1 2`, `1 1 3`, `1 2 1`, `1 2 2`, and `1 2 3`
---
Given `5 5 5 5`, print:
```
1 500
2 500
3 500
4 500
5 500
```
And no, I'm not going to list all 625 labels.
[Answer]
# Mathematica, 48 bytes - 3 = 45
```
Grid@Tally@Flatten@IntegerDigits@Tuples@Range@#&
```
[Answer]
# Dyalog APL, ~~10~~ 7
The code is 10 bytes long and qualifies for the bonus.
Thanks to user46915 for 3 bytes!
```
,∘≢⌸∊⍕¨∊⍳⎕
```
Note that `⎕` (input) doesn't work on TryAPL; you can try the function form [here](http://tryapl.org/?a=f%u2190%7B%7B%u237A%2C%u2262%u2375%7D%u2338%u220A%u2355%A8%u220A%u2373%u2375%7D%20%u22C4%20f%A8%20%2811%29%20%282%203%29%20%282%200%29%20%281%202%203%29%20%285%205%205%205%29%20%u236C&run).
```
⎕ Get input
⍳ Index vector
∊⍕¨∊ Flatten, stringify, flatten again
⌸ From the key, display the
{⍺, } elements concatenated with the
≢⍵ number of times they occur
```
I don't completely understand the `⌸` operator, but `{⍺}⌸` lists the unique values taken on, and `{⍵}⌸` lists their places in the argument.
This has the correct ordering because it is the order in which digits appear in the multidimensional array of labels.
[Answer]
# Mathematica, ~~111~~ 85 bytes
```
Grid[Thread@{Range@10~Mod~10,DigitCount@Tuples@Range@#~Total~2}~DeleteCases~{_,0}]&
```
Most of the work here is done by `DigitCount`.
[Answer]
## R, 110 bytes
*Saved 4 thanks to Alex A. (thanks!)*
```
U=unlist
X=table(U(strsplit(as.character(U(expand.grid(Map(seq_len,scan())))),"")))
z=Map(cat,names(X),X,"\n")
```
[Answer]
# Ruby, 92 bytes
```
f,*r=$*.map{|n|[*1..n.to_i]}
a=f.product(*r)*''
puts a.chars.uniq.map{|c|[c,a.count(c)]*" "}
```
Takes the lengths as command line arguments:
```
$ ruby foo.rb 1 2 3
1 11
2 5
3 2
```
[Answer]
# CJam, 31 bytes
```
Laq~{,m*}/e_:)s{_'0=A*+}$e`{(S\N}%
```
[Try it online](http://cjam.aditsu.net/#code=Laq~%7B%2Cm*%7D%2Fe_%3A)s%7B_'0%3DA*%2B%7D%24e%60%7B(S%5CN%7D%25&input=%5B1%202%203%5D)
Code is 34 bytes, and takes 3 byte bonus for working with empty input list. The input is a list in CJam format, e.g.:
```
[1 2 3]
```
Explanation:
```
La Push list containing empty list to seed Cartesian products.
q~ Get and interpret input.
{ Loop over values in input list.
, Built range from 0 to value-1.
m* Form Cartesian product with the list we already have.
}/ End loop over values in input list.
e_ Resulting list has extra nesting. Flatten it.
:) Increment all values in list, since it is 0-based, and we need 1-based.
s Convert it to string, so we can operate on digits.
{ Block to calculate source key, needed to get 0 to the end.
_ Copy the digit.
'0= Compare with '0.
A* Multiply comparison result by 10...
+ ... and add it to digit.
}$ End of sort key block.
e` RLE.
{ Start of loop over RLE entries, for generating output in specified format.
( Pop off the first value, which is the count.
S Push a space...
\ ... and swap it with the count.
N Push a newline.
}% End of loop over RLE entries.
```
[Answer]
# Pyth, 15 bytes
```
rjko%N_Ts*FSMQ8
```
[Answer]
# Haskell, 125 bytes
```
import Data.List
l=mapM_(putStrLn.(\(h:r)->h:' ':show(length r+1))).group.sort.concatMap show.concat.sequence.map(\n->[1..n])
```
] |
[Question]
[
## The scenario
I drive along a road with my car and it begins to rain. The raindrops are falling on my window randomly and now i ask myself, where is the biggest connected wet area?
## The task
To make it easier, the window is split in a matrix of 10\*10 squares.
Your job is to find the biggest connected water-drop-area on the window.
## Input
There are two possible inputs, you can use a 2-dimensional Array or a 1-dimensional one. You can choose between any inputs like stdin, etc...
Example:
```
// 2-dimensional:
[[0,1,0,0,0,0,1,0,0,0],
[0,1,1,0,0,0,0,1,1,0],
[0,1,1,0,0,0,0,1,0,0],
[0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0],
[0,0,0,1,1,0,0,0,1,0],
[0,0,0,1,1,0,0,0,1,0],
[0,0,0,0,0,1,1,0,1,0],
[0,0,0,0,0,1,1,0,1,0],
[0,0,0,0,0,0,0,0,0,0]]
// 1-dimensional
[0,1,0,0,0,0,1,0,0,0,
0,1,1,0,0,0,0,1,1,0,
0,1,1,0,0,0,0,1,0,0,
0,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,
0,0,0,1,1,0,0,0,1,0,
0,0,0,1,1,0,0,0,1,0,
0,0,0,0,0,1,1,0,1,0,
0,0,0,0,0,1,1,0,1,0,
0,0,0,0,0,0,0,0,0,0]
```
## Output
Your code has to put out the size of the biggest connected area and the x- and y-coordinates of the waterdrops which belong to this area in the format
"Size: Z Coordinates: (X1,Y1) (X2,Y2) ..."
Example for the previous input:
```
Size: 6 Coordinates: (1,0) (1,1) (2,1) (1,2) (2,2) (1,3)
```
The order of the Coordinates doesn't matter.
## Rules
* Waterdrops are connected, if they touch each other orthogonally
* Diagonal connections don't count
* There can be many areas and your code has to find the biggest one
* An empty field is represented as "0" and a wet field as "1"
* Post your solution with a short explanation and the output of the previous input
* The shortest code within the next 7 days will win
* If there are two areas with the same size, you can choose one
### Winner: Ventero with 171 - Ruby
[Answer]
# Python - 192
```
a=10;g+=[0]*a
def f(k):
if g[k]:g[k]=0;return" (%d,%d)"%(k/a,k%a)+f(k+a)+f(k-a)+f(k+(k%a<9))+f(k-(k%a>0))
return''
m=max(map(f,range(100)),key=len)
print"Size: "+`len(m)/6`+" Coordinates:"+m
```
Input (Paste before the code):
```
g=[0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0]
```
Thanks Calvin's Hobbies for suggested edits!
[Answer]
## Ruby, 171 characters
```
r=eval *$*
u=(0..99).map(&v=->p{-~p*r[p]>0?" (#{r[p]=0;u=p%c=10},#{p/c})"+v[p+c]+v[p-c]+v[u>0?p-1:p]+v[u<9?p+1:p]:""}).max_by &:size
puts"Size: #{u.size/6} Coordinates:"+u
```
Input via command line parameter as one-dimensional array.
Output for the sample input: `Size: 6 Coordinates: (1,0) (1,1) (1,2) (1,3) (2,2) (2,1)`
This answer uses a simple flood-fill approach, building a list of coordinates for each raindrop cluster. Most of the code is actually used for bounds checking and I/O.
[Answer]
# C# - 548 523 522 511 503 476
*(under 500... yey)*
I'm sure there's **lots** of room for improvement.
The way I inputted the data was to initialize an array. I didn't include that array in the score (if you think this is cheating I can change the code, but it will add relatively much code because C# isn't great at parsing arrays)
```
using o=System.Console;using l=System.Collections.Generic.List<int[]>;class P{
static int[,] a ={{0,1,0,0,0,0,1,0,0,0},{0,1,1,0,0,0,0,1,1,0},{0,1,1,0,0,0,0,1,0,0},{0,1,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,1,0},{0,0,0,1,1,0,0,0,1,0},{0,0,0,1,1,0,0,0,1,0},{0,0,0,0,0,1,1,0,1,0},{0,0,0,0,0,1,1,0,1,0},{0,0,0,0,0,0,0,0,0,0}};
static int w=10,h=w,x=0,y;static l t=new l(),m=new l();static void f(int r,int c){if(a[r,c]==1){a[r,c]=0;if(r<h)f(c,r+1);if(r>0)f(c,r-1);if(c<w)f(c+1,r);if(c>0)f(c-1,r);t.Add(new[]{c,r});}}static void Main(){for(;++x<w;)for(y=0;++y<h;){if(a[x,y]==1)f(x,y);if(t.Count>m.Count)m=t.FindAll(r=>true);t.Clear();}o.Write("Size: "+m.Count+" Coordinates: ");m.ForEach(c=>o.Write("({0},{1}) ",c[0],c[1]));}}
```
Test it at <http://ideone.com/UCVCPM>
**Note: The current version doesn't work in ideone because it doesn't like `using l=System.Collections...`, so the ideone version is slightly outdated (and longer)**
## How it works
It basically checks if there is a `1`. If it finds one, it uses the Flood Fill algorithm to replace all the adjacent `1`'s with `0` and adds the replaced coordinates to a temporary list. Afterwards it compares the top list (`m`) to the temporary list (`t`) and sets `m` to `t` if `t`contains more elements.
[Answer]
# Mathematica - 180 bytes
This function takes a 2-dimensional array.
### Golfed
```
f@x_:=(c=MorphologicalComponents[x,CornerNeighbors->False];m=Last@SortBy[ComponentMeasurements[c,"Count"],Last];Print["Size: ",Last@m," Coordinates: ",Reverse/@Position[c,m[[1]]]])
```
### Pretty
```
f@x_ := (
c = MorphologicalComponents[x, CornerNeighbors -> False];
m = Last@SortBy[ComponentMeasurements[c, "Count"], Last];
Print["Size: ", Last@m, " Coordinates: ", Reverse/@Position[c, m[[1]]]]
);
```
### Example
```
{0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0};
w=Partition[%,10];
f@w
```
>
> Size: 6 Coordinates: {{1,2},{2,2},{2,3},{3,2},{3,3},{4,2}}
>
>
>
The output is slightly anomalous. Mathematica starts indexing at 1 instead of 0, and uses `{}` to indicate position. Add 2 bytes (`-1`) if the positions need to be 0-indexed. Add a lot of bytes if they need to use `()` instead of `{}` :(
### Explanation
`f` is a function of `x`. It defines `c` as a transformation of `x`, where each (i,j) now equals an integer corresponding to which connected component it belongs to. It involves the main work:
```
MorphologicalComponents[w, CornerNeighbors -> False] // Colorize
```

Then `m` computes how many elements are in each component, sorts them by that number, and takes the last result (meaning, with the most elements). The last line prints the count, and the positions in `c` of the index contained in `m`.
[Answer]
# Haskell, 246
```
r=[0..9]
q=[(i,j)|i<-r,j<-r]
t v p@(i,j)|elem p v||notElem p q||g!!j!!i==0=v|1<2=foldr(\(k,l)v->t v(i+k,j+l))(p:v)$zip[-1,0,1,0][0,-1,0,1]
(?)=map
a=t[]?q;(b,c)=maximum$zip(length?a)a
main=putStrLn.unwords$["Size:",show b,"Coordinates:"]++show?c
```
## Input
Two dimension and paste before code as `g`, for example:
```
g = [[0, 1, 1, ......, 0], [......], ....]
```
## Ungolfed
```
field = [
[0,1,0,0,0,0,1,0,0,0],
[0,1,1,0,0,0,0,1,1,0],
[0,1,1,0,0,0,0,1,0,0],
[0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0],
[0,0,0,1,1,0,0,0,1,0],
[0,0,0,1,1,0,0,0,1,0],
[0,0,0,0,0,1,1,0,1,0],
[0,0,0,0,0,1,1,0,1,0],
[0,0,0,0,0,0,0,0,0,0]
]
range = [0..9]
positions = [(i, j) | i <- range, j <- range]
directions = zip [-1, 0, 1, 0] [0, -1, 0, 1]
traverse visited pos@(i, j)
| pos `elem` visited || pos `notElem` positions || field!!j!!i == 0 = visited
| otherwise = foldr folder (pos:visited) directions
where folder = (\(di, dj) visited -> traverse visited (i + di, j + dj))
blocks = map (traverse []) positions
(maxCount, maxBlock) = maximum $ zip (map length blocks) blocks
main = putStrLn.unwords $ ["Size:", show maxCount, "Coordinates:"] ++ map show maxBlock
```
[Answer]
### C# 374byte function
This is a heavily modified version of my answer to [Are you in the biggest room?](https://codegolf.stackexchange.com/a/34839/26981). It takes a one-dimensional array of ints, and returns a string in the style required. It works by building up disjoint sets from the input (first loop), tallying the size of each set and finding the largest set (second loop) and then appending any cells in that set to an output string (third loop) which is then returned.
```
static string F(int[]g){int s=10,e=0,d=s*s,a=0,b=d+1;int[]t=new int[b],r=new int[b];t[d]=d;System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]<d?a:d;T=v=>t[v]!=v?T(t[v]):v;for(;a<d;a++)if(g[a]>0){e=t[a]=a;if(a>s)k(a-s);if(a%s>0)k(a-1);}else t[a]=d;for(;a-->0;)e=r[e]<++r[b=T(a)]&&b<d?b:e;var p="Size: "+r[e]+" Coordinates:";for(;d-->1;)p+=T(d)==e?" ("+d%s+","+d/s+")":"";return p;}
```
Less golfed (and with test code):
```
class P
{
static int[] z = {0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0};
static string F(int[]g)
{
int s=10,e=0,d=s*s,a=0,b=d+1;
int[]t=new int[b],r=new int[b];
t[d]=d;
System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]<d?a:d;
T=v=>t[v]!=v?T(t[v]):v;
for(;a<d;a++)
if(g[a]>0)
{
e=t[a]=a;
if(a>s)k(a-s);
if(a%s>0)k(a-1);
}
else
t[a]=d;
for(;a-->0;)
e=r[e]<++r[b=T(a)]&&b<d?b:e;
var p="Size: "+r[e]+" Coordinates:";
for(;d-->1;)
p+=T(d)==e?" ("+d%s+","+d/s+")":"";
return p;
}
static void Main()
{
System.Console.WriteLine(F(z));
}
}
```
[Answer]
# JavaScript (EcmaScript 6) 183 ~~189~~
A function with array input and string return value. If real output is needed (not clear to me) add 7 bytes for 'alert()'.
```
W=(a,n=10,x=0)=>(F=p=>a[p]|0&&(a[p]=0,o+=' ('+p%n+','+(p/n|0)+')',1+F(p-n)+F(p+n)+F(p-(p%n>0))+F(p+((p+1)%n>0))),a.map((e,p)=>(t=F(p,o=''))>x&&(x=t,k=o)),'Size: '+x+' Coordinates:'+k)
```
**Test Output**
```
Size: 6 Coordinates: (1,0) (1,1) (1,2) (1,3) (2,2) (2,1)
```
**More readable**
```
W=(a,n=10,x=0)=>
(
F=p=>
a[p]|0&&(
a[p]=0,o+=' ('+p%n+','+(p/n|0)+')',
1+F(p-n)+F(p+n)+F(p-(p%n>0))+F(p+((p+1)%n>0)) // modulo takes care of not overflowing out of a row
),
a.map((e,p)=>(t=F(p,o=''))>x&&(x=t,k=o)),
'Size: '+x+' Coordinates:'+k
)
```
**Explanation**
Get a single dimension array and an optional parameter with the size of a row. The function works also with different array dimensions, even x!=y.
*Pseudo code:*
```
For each element,
try to fill.
During the fill operation build a string with the coordiinates.
Remember the longest fill and the corresponding string and
output that at the end.
```
[Answer]
## **JavaScript, 273**
Function takes array and returns string. My first attempt was ~500 characters and did not use Flood Fill. This one does. I'm learning JavaScript so any suggestions would be appreciated.
This function loops through the input array and for each 1 found it starts there and changes all connected to 1s to 0 using the Fill function. While doing so it remembers the blob with the most 1s. The Fill function changes the current position to 0 and then calls itself on the position above, to the right, below, and to the left.
```
function G(m){var B="",b=0;for(var p=0;p<m.length;p++)if(m[p]){var T="",t=0;
Z(p);if(t>b){b=t;B=T;}}return"Size: "+b+" Coordinates:"+B;function Z(p){if(m[p])
{m[p]=0;t++;T+=" ("+p%10+","+Math.floor(p/10)+")";if(p>9)Z(p-10);if(p%10)Z(p-
1);if(p<90)Z(p+10);if(p%10!=9)Z(p+1);}}}
```
Test here: <http://goo.gl/9Hz5OH>
**Readable Code**
```
var map = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
...
0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
function F(map) {
var bestBlob = "", bestLen=0;
for (var p = 0; p < map.length; p++)
if (map[p]) {
var thisBlob = "", thisLen=0;
Fill(p);
if (thisLen > bestLen){
bestLen=thisLen ; bestBlob = thisBlob;
}
}
return "Size: " + bestLen + " Coordinates:" + bestBlob;
function Fill(p) {
if (map[p]) {
map[p] = 0; thisLen++;
thisBlob += " (" + p % 10 + "," + Math.floor(p / 10) + ")";
if (p > 9) Fill(p - 10);
if (p % 10) Fill(p - 1);
if (p < 90) Fill(p + 10);
if (p % 10 != 9) Fill(p + 1);
}
}
}
```
[Answer]
# Scala, 420
Hi, my entry takes a 2d array as a `List[List[Int]]`, returns a `String`
```
val o=for{(r, y)<-w.zipWithIndex;(v,x)<-r.zipWithIndex;if(v == 1)}yield(x,y);val a=o.flatMap(c=>o.collect{case(x,y)if{(x==c._1+1||x==c._1-1)&&y==c._2^(y==c._2+1||y==c._2-1)&&x==c._1}=>c->(x,y)}).groupBy(_._1).map(n => (n._1->n._2.map(t=>t._2)));val b=a.values.flatMap(v=>v.map(c=>a(c)++v));val l=b.collect{case x if (x.length==b.map(_.length).max)=>x}.head;println(s\"Size: ${l.length} Coordinates: ${l.mkString(" ")}\")
```
## Explanation
Given a window as a `List[List[Int]]`, first we find each "1" and save the coordinates in a list. Next we turn that list into a `Map` of the coordinate of each "1" to a list the coordinates of every adjacent "1". Then use the adjacency map to transitively link the sub-blobs into blobs, and finally we return the largest blob (and ignoring duplicate blobs since order of the returned coordinates does not matter).
## More Readable
```
val w = {
List(//0,1,2,3,4,5,6,7,8,9
List(0,1,0,0,0,0,1,0,0,0), //0
List(0,1,1,0,0,0,0,1,1,0), //1
List(0,1,1,0,0,0,0,1,0,0), //2
List(0,1,0,0,0,0,0,0,0,0), //3
List(0,0,0,0,0,0,0,0,1,0), //4
List(0,0,0,1,1,0,0,0,1,0), //5
List(0,0,0,1,1,0,0,0,1,0), //6
List(0,0,0,0,0,1,1,0,1,0), //7
List(0,0,0,0,0,1,1,0,1,0), //8
List(0,0,0,0,0,0,0,0,0,0)) //9
}
case class Coord(x: Int, y: Int)
val ones: List[Coord] = for{
(row, y) <- w.zipWithIndex
(value, x) <- row.zipWithIndex
if (value == 1)
} yield Coord(x,y)
val adjacencyMap: Map[Coord, List[Coord]] = ones.flatMap(keyCoord => ones.collect{
case Coord(adjacentX, adjacentY) if {
(adjacentX == keyCoord.x + 1 || adjacentX == keyCoord.x - 1) && adjacentY == keyCoord.y ^
(adjacentY == keyCoord.y + 1 || adjacentY == keyCoord.y - 1) && adjacentX == keyCoord.x
} => keyCoord->Coord(adjacentX,adjacentY)
}).groupBy(_._1).map(n => (n._1->n._2.map(t=>t._2) ))
val blobs: Iterable[List[Coord]] = adjacencyMap.values.flatMap(v => v.map(coord => adjacencyMap(coord)++v))
val largestBlob: List[Coord] = blobs.collect{case x if (x.length == blobs.map(b=> b.length).max) => x}.head
println(s"""Size: ${largestBlob.length} Coordinates: ${largestBlob.collect{case Coord(x,y) => (x,y)}.mkString(" ")}""")
```
Criticism is very much appreciated.
] |
[Question]
[
For this challenge, you must implement Ruby's [`Abbrev`](http://www.ruby-doc.org/stdlib-2.2.0/libdoc/abbrev/rdoc/Abbrev.html) module in as little code as possible.
## Challenge
* The input will be whatever your language has as an array (array, list, sequence, etc.) of strings. You may write a function, or you may accept comma-separated words on STDIN.
* You must then calculate the set of unambiguous prefixes for those strings. This means you must return a hash (or map, object, etc.) of abbreviations to their original strings.
+ A "prefix" is a substring of the original string starting at the beginning of the string. For example, "pref" is an prefix of the word "prefix."
+ An *unambiguous* prefix is one that can only mean one word. For example, if your input is `car,cat`, then `ca` is not an unambiguous prefix because it could mean either "car" or "cat."
+ The exception to this rule is that a word is always a prefix of itself. For example, if you have input such as `car,carpet`, `car:car` must be in your output.
* You can then return the hash/map/object/etc. from your function (or do the equivalent in your language), or print it out to STDOUT in `key:value` pairs in the form of `f:foo,fo:foo,...`. (The key-value pairs may also be separated by whitespace if it makes your code shorter.)
## Test cases
```
Input code,golf,going
Output c:code,co:code,cod:code,code:code,gol:golf,golf:golf,goi:going,goin:going,going:going
Input pie
Output p:pie,pi:pie,pie:pie
Input pie,pier,pierre
Output pie:pie,pier:pier,pierr:pierre,pierre:pierre
Input a,dog
Output a:a,d:dog,do:dog,dog:dog
```
## Rules
* The input will not contain duplicate elements.
* Your output may be in any order; you don't have to sort it.
* You may not use a built-in `Abbrev` module/function/thing like Ruby's.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
[Answer]
# Python 2.7 - 146 141 bytes
```
l=raw_input().split(',')
for w in l:
for a in range(len(w)):
e=w[:a+1]
if e==w or len(filter(lambda b:b.startswith(e),l))==1:print e+':'+w
```
Note that the indentation on lines 4 and 5 is not 4 spaces, that's a side effect of SE's markdown interpreter. That's a literal tab character, so only one byte.
This is not technically up to spec, but I'll change it if Doorknob clarifies. It uses newlines instead of commas to separate the output. For example:
```
$ python2 abbreviations.py <<< code,golf,golfing
c:code
co:code
cod:code
code:code
golf:golf
golfi:golfing
golfin:golfing
golfing:golfing
```
**New:** I was able to get rid of 5 characters by assigning the string that I'm checking to a variable `e`. This means that I only have to type `e` instead of `w[:a]` three times. It also means I save characters by doing `e=w[:a+1]` and changing `...range(1,len(w)+1)` to `range(len(w))`.
---
Explanation:
```
l=raw_input().split(',') # Gets a line of input from stdin and splits it at every ',' to make a list
for w in l: # For each word in that list...
for a in range(1,len(w)+1): # For each number a from 1 to the length of that word...
if (w[:a]==w # w[:a] gets the string w up to the ath index. For example, 'aeiou'[:3] == 'aei'.
# We're testing every possible w[:a] to see if it's a unique abbreviation.
# However, a word is always its own abbreviation, so we hardcode that in by testing
# if w[:a] is the same as w.
or len(filter( # filter takes a function and an iterable as an argument, and returns a list of every
# element of that iterable where that_function(that_element) returns a True-y value
lambda b:b.startswith(w[:a]),l) # We define an anonymous function that returns True for any string
# that begins with our current w[:a]. We filter for words that return
# True.
)==1): # If exactly one word returns True for this, it's a unique abbreviation!
print w[:a]+':'+w # Print the abbreviation, a colon, and the full word.
```
[Answer]
# J - 47 char
```
(,.~~.@,~[:(#~1-1({.\e."_1]\.){."1)@;(<\,.<)&.>)
```
J sees strings as just vectors of characters, which means that when it tries to make a list of strings it actually ends up making a table of characters, so the ends get padded with spaces. J's solution to this is called the *box*, so this function takes as argument a boxed list of strings, so as to preserve length.
```
'code';'golf';'going'
+----+----+-----+
|code|golf|going|
+----+----+-----+
```
Also, J lacks a hash type, so the closest it has to that is a two-column table of items, say boxed strings, for instance. If that is unacceptable and I have to default to the key-value form, I can reformat the output to this form in **67 characters** total:
```
;@|.@,@((<&>',:'),."1,.~~.@,[:(#~1-1({.\e."_1]\.){:"1)@;(<,.<\)&.>)
```
Explanation by explosion:
```
(,.~~.@,[:(#~1-1({.\e."_1]\.){."1)@;(<\,.<)&.>) NB. unambiguous prefixes
( )&.> NB. for each string:
<\ NB. take all prefixes
,.< NB. pair each with string
[: ; NB. gather up "partial" hashes
(#~1- )@ NB. remove those rows where:
1({.\ ){."1 NB. each key
e."_1 NB. is an element of
1( ]\.){."1 NB. the rest of the keys
,.~ NB. hash each word to itself
, NB. add these rows to hash
~.@ NB. remove duplicate rows
```
Examples:
```
(,.~~.@,[:(#~1-1({.\e."_1]\.){."1)@;(<\,.<)&.>) 'pie';'pier';'pierre'
+------+------+
|pie |pie |
+------+------+
|pier |pier |
+------+------+
|pierre|pierre|
+------+------+
|pierr |pierre|
+------+------+
NB. 1-char words have to be made into lists with ,
(,.~~.@,[:(#~1-1({.\e."_1]\.){."1)@;(<\,.<)&.>) (,'a');'dog'
+---+---+
|a |a |
+---+---+
|dog|dog|
+---+---+
|d |dog|
+---+---+
|do |dog|
+---+---+
NB. "key:value," format, reversed order to save chars
;@|.@,@((<&>',:'),."1,.~~.@,[:(#~1-1({.\e."_1]\.){:"1)@;(<,.<\)&.>) 'code';'golf';'going'
goin:going,goi:going,gol:golf,cod:code,co:code,c:code,going:going,golf:golf,code:code,
```
[Answer]
# Haskell ~~96~~ 87
```
import Data.List
i=inits
f a=a>>= \x->[(y,x)|y<-i x,y/="",y`notElem`(a>>=i)\\i x||y==x]
```
Ungolfed version:
```
import Data.List
f a = concatMap (\x ->
[(y, x) |
y <- inits x,
y /= "",
y `notElem` concatMap inits a \\ inits x || y == x]
) a
```
Example:
```
> f ["pi","pier","pierre"]
[("pi","pi"),("pier","pier"),("pierr","pierre"),("pierre","pierre")]
```
I used the `inits` function, which finds all prefixes of a list/string. Does it count as cheating?
[Answer]
# Python 3 (97)
```
c=','
S=c+input()
for w in S.split(c):
e=w
while e:e<w<w*S.count(c+e)or print(e+':'+w);e=e[:-1]
```
We iterate over prefixes of each word in the input, printing the corresponding prefix/word pair if it either appears exactly once or is to whole word. We take advantage of the short-circuiting behavior of `or` (and `print` being a function) to print only if one of these conditions is met.
The `while` loop repeatedly cuts off the last character to create shorter and shorter prefixes, terminating when the empty string remains. This is the only time we index or slice into anything.
We count the occurrences of the prefix `e` in the input by searching the original comma-separated input string `S` for substrings `','+e`. We prepend a comma to the input string beaforehand. This addition causes an extra empty string element when we `split`, but this has no effect because it has no nonempty substrings.
To check for the case when the substring `e` is the whole word `w`, we compare them using the string comparison operator. This compares lexicographically, so shorter prefixes are smaller. The double comparison fails if either `e==w` or `S.count(c+e)<2`.
If printing outputs in the form `e,w` were allowed, I'd save a character by writing `e+c+w` instead.
Credit to [undergroundmonorail](https://codegolf.stackexchange.com/users/14509/undergroundmonorail) from [whose answer](https://codegolf.stackexchange.com/a/28280/20260) I based my overall code structure.
[Answer]
## APL (46)
[(Yes, the APL charset does fit in a byte, with room to spare.)](http://frankenstein.d-n-s.org.uk/~marinus/aplcharset.png)
```
{↑{∆/⍨2=⍴∆←(⊂⍵),∆/⍨⊃¨⍵∘⍷¨∆}¨∪⊃,/{↑∘⍵¨⍳⍴⍵}¨∆←⍵}
```
This is a function that takes a list of strings, and returns a 2-by-N matrix, where each row contains an unambigous prefix and the word it belongs to:
```
{↑{∆/⍨2=⍴∆←(⊂⍵),∆/⍨⊃¨⍵∘⍷¨∆}¨∪⊃,/{↑∘⍵¨⍳⍴⍵}¨∆←⍵}'code' 'golf' 'going'
c code
co code
cod code
code code
gol golf
golf golf
goi going
goin going
going going
```
Explanation:
* `∆←⍵`: store the right argument in `∆`.
* `{↑∘⍵¨⍳⍴⍵}¨∆`: for each element of `∆`, get the possible prefixes of that element:
+ `⍳⍴⍵`: get a list from `1` to the length of `⍵`
+ `↑∘⍵¨`: for each of those numbers, get that many elements from `⍵`.
* `∪⊃,/`: concatenate the lists together and take the unique values.
* `{`...`}¨`: for each of the unique prefixes:
+ `∆/⍨⊃¨⍵∘⍷¨∆`: select the words that start with that prefix
+ `(⊂⍵),`: also enclose the prefix, and concatenate
+ `∆/⍨2=⍴∆←`: only return the list if there are two elements (the prefix and one matching word)
* `↑`: turn the list of tuples into a matrix
[Answer]
## Ruby, 114
```
def f(l);h={};l.each{|w|w.size.times{|i|k=w[0..i];h[k]=h[k]&&0||w}};h.delete_if{|k,v|v==0};l.each{|w|h[w]=w};h end
```
Ungolfed:
```
def f(list)
hash = {}
list.each do |word|
word.size.times do |i|
key = word[0..i]
h[key] = (hash[key] && 0) || word
end
end
hash.delete_if{|key, value| v==0}
list.each{|word| hash[word] = word}
hash
end
```
[Answer]
## k4 (70)
not particularly golfed; i'm sure it could be shorter
pretty similar to the J impl. above, i think -- basically just collects all the (proper) prefixes, removes the words from the prefixes again (to handle the `"car"`/`"carpet"` case), groups them into equivalence classes, picks the classes with only one element, reduces them from lists to strings, and adds in the map from strings to themselves.
```
f:{(x!x),*:'{(&1=#:'x)#x}{x@=y@:&~y in x}.,/'+{1_'(c#,x;(!c:#x)#\:x)}'x}
```
some test cases
note that in `k`/`q`, a string is list of characters, so a string containing only a single character needs to be marked as such using the unary `,` function; & m.m. w.r.t a list of strings containing only a single string
these use `q`'s `show` function, which has built-in formatting for some data structures, to make the results more readable:
```
.q.show f("code";"golf";"going")
"code" | "code"
"golf" | "golf"
"going"| "going"
,"c" | "code"
"co" | "code"
"cod" | "code"
"gol" | "golf"
"goi" | "going"
"goin" | "going"
.q.show f@,"pie"
"pie"| "pie"
,"p" | "pie"
"pi" | "pie"
.q.show f("pie";"pier";"pierre")
"pie" | "pie"
"pier" | "pier"
"pierre"| "pierre"
"pierr" | "pierre"
.q.show f(,"a";"dog")
,"a" | ,"a"
"dog"| "dog"
,"d" | "dog"
"do" | "dog"
.q.show f("car";"carpet")
"car" | "car"
"carpet"| "carpet"
"carp" | "carpet"
"carpe" | "carpet"
```
[Answer]
# JavaScript - 212
```
w=prompt(o=[]).split(",");w.map(function(k,l){for(i=0;++i<k.length;){p=k.slice(0,i);if(w.filter(function(r,t){return t!=l}).every(function(r){return r.indexOf(p)}))o.push(p+":"+k)}o.push(k+":"+k)});console.log(o)
```
Initial golf.
Input:
`code,golf,going`
Output:
`["c:code", "co:code", "cod:code", "code:code", "gol:golf", "golf:golf", "goi:going", "goin:going", "going:going"]`
[Answer]
## Perl, ~~93~~ 77
With newlines and indentation for readability:
```
sub f{
(map{
$h{$x}=[($x=$`.$&,$_)x!$h{$x}]while/./g;
$_,$_
}@_),map@$_,values%h
}
```
A bit too late and too long, but I'm glad it's finally got below 100. Function returns a list which can be assigned to hash variable:
```
%h = f(qw/code golf going pie pier pierre/);
print "$_ $h{$_}\n" for sort keys %h;
```
and
```
perl prefix.pl
c code
co code
cod code
code code
goi going
goin going
going going
gol golf
golf golf
pie pie
pier pier
pierr pierre
pierre pierre
```
Actually, returned list is not filtered yet - hash construction is completed at the moment of its assignment i.e. outside function. **IF** it's not clean/fair enough, add 3 to count and put function contents into curly braces, prepending `+` - then function returns 'true' hash reference.
[Answer]
## Q: 44 Bytes
```
{x!p@'(?0,&:)'p in\:&1=#:'=,/p:`$(-1_)\'$x}
```
**NOTES**
* Q language has an inner core named internally K4 (used in this answer and another previously answer to this question)
* To test code, download interpreter (kx.com, free for non-commertial
use, support for Windows, Linux, Mac)
Interpreter admits two syntaxes:
* verbose (more readable names, distinct names for moands and diads, more libraries, ...). Load source file with q extension, or interactive interpreter
* compact (functional inner core, one letter operators, same letter for both uses monad/diad, ...). Load source file with k extension, or interactive interpreter **in k mode** (write \ at prompt). Code must be tested in this mode
The code defines a lambda (anonymous function). To give name to the function we need prefix name: (ex f:{..}), so requires 46 Bytes
**TEST**
(assumming named function: otherwise substitute f for the code)
```
f `code`golf`going
`code`golf`going!(`code`cod`co`c;`golf`gol;`going`goin`goi)
```
returns a dictionary (syntax keys!values). Keys are a list of symbols (`symb`symb..), and values a list of list of symbols. If we execute the sentente at the interactive interpreter, we have a more convenient presentation (each key and associate values at a different line)
```
code | `code`cod`co`c
golf | `golf`gol
going| `going`goin`goi
```
**EXPLANATION**
`x` is the implicit argument to the lambda
`$x` convert symbol list to string list
`(-1_)\` iterates over each elem of the symbol list
(reads as for each string calculates prefixes (at eat iteration drops last char of the string (-1\_), until empty string)
`$` transforms to a symbol list again (list of all prefixes)
`p:` and assigns to p
`,/` raze all (concatenates and creates a one-level structure)
`=` classify -> for each unique prefix, associates the corresponding words
`#:'` calculates length (number of words associated to each prefix)
`1=` true if length=1 (unambiguous), false otherwise
`&` where -> index of true elements
`p in\:` determines for all prefix if they are in unambiguous prefix
`(..)'` applies (..) to each value at right (unambiguous prefix)
`?0,&:` -> distinct 0 concatenated where (to cope words as prefix of itself)
`p@` transform indexes to symbols
`x!..` construct a dictionary with x (words) as keys, and .. as values
Read as:
* Construct and returns a dictionary with the words as keys, and values
..
* ... values of indexes at distinct positions 0 (all word) and where
unambiguous prefix
* ... unambiguous calculated as prefixes that appear only at one word
(wordlist associates to each symbols has length one)
* ... lists resulting of classifying all unique symbols with corresponding
words
* ... prefixes calculated by repeating drop last char of each word
[Answer]
**PHP 7.0, 67 bytes** (postdates the challenge)
```
for(;a&$c=$s[++$k]??($s=$argv[++$i])[$k=+$t=!1];)echo$t.=$c,":$s,";
```
takes input from command line arguments; prints a trailing comma; run with `-nr`.
for **newer PHP**, add one byte: Replace `&a` with `""<`.
for older PHP, use these 70 bytes:
# PHP, 70 bytes
```
for(;a&$s=$argv[++$i];)for($k=+$t="";a&$c=$s[$k++];)echo$t.=$c,":$s,";
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes
```
∋Xa₀Y;?↔⟨∋a₀⟩ᶜ1∧Y;X|∋gj
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpodbZzzc1Vn7cOuE/486uiMSHzU1RFoD5aY8mr8CKADiP5q/8uG2OYaPOpZHWkfUAAXTs/7/j1aIVkrOT0lV0lFKz89JA1OZeelKsTrRSgWZqXBaB0QWQakiiHgikJuSD1SrEAsA "Brachylog – Try It Online")
Takes input as a list through the input variable, and [generates](https://codegolf.meta.stackexchange.com/a/10753/85334) a list of `[key, value]` pairs through the output variable. Any input string which is not a prefix of another input string will be generated as a prefix of itself twice, although the header on TIO hides this by using `ᵘ` to obtain the full list instead of `ᶠ`.
```
X X
∋ is an element of
the input variable
Y and Y
a₀ is a prefix of
X X.
ᶜ The number of ways in which
⟨∋ ⟩ an element can be selected from
;?↔⟨ ⟩ the input variable
Y; ↔⟨ a₀⟩ such that it has Y as a prefix
1 is equal to 1.
∧Y Y is not necessarily 1,
| and the output variable
Y;X is the list [Y, X].
| If every choice from the first rule has been taken already,
the output variable is
∋ an element of
| the input variable
gj paired with itself.
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 76 bytes
```
map{say"$, $a"if($,=substr$a,0,$_)eq$a||2>grep/^$,/,@F}1..length($a=$_)for@F
```
[Try it online!](https://tio.run/##HcqxDoIwEIDhVyHkBkyOUkwYMUxsvoLmTA5sgrRc60DAV/ckDv83/YFlalRfFLZIaw6YAeVuKADb@H7EJEBoEe4nXoD2/XwZhUN1A6yw6z@1MRPPY3oWQO0xDV66XjU4zo7kj/DXh@T8HLW8NsbWVkv6AQ "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 38 bytes
thanks Erik the Outgolfer for reminding me to use a single-byte character encoding
```
{⊃,/⍵{b,¨⍨(⊂¨⍵~⊃,/a~⊂⍵)∪b←⊂⊂⍺}¨a←,\¨⍵}
```
[Try it online!](https://tio.run/##XZA9TsNAEIV7n8LdOJIjkOg4C83Gf6ywspbtBlmmCChKghxBwQWorDRUaSh9lLmIebu2yTrNzvvem539EVm6DJ9FqpJlkIqikEHPxy@pePtx21d8ePVvuDlXK79ruWk9Pmy0OL@YRKBsQAvenVbYoUkbv3XXCrD/YJrrPtZhc8Sm7ueOt584osgDrOWjLPoSaYU@3n/nkDEG3HNzoljIlACIcn5/I/VEtUOBCiNyKVFpbIpcJ@SWrkcB0IQLaDWDcE6RhZgzTRsonqH8P2PA9TUnF8PxfDyfMonB5kYZMkOQ0tbRBM4F8rHk0fAcq8uz8wmt/smJLMshAQrV@DkahG4MR1dLZetkgj8 "APL (Dyalog Classic) – Try It Online")
[Answer]
# Python (127)
So I couldn't comment @undergroundmonorail, but I thought that taking a dictionary approach would be better? I'm sure with some list/dictionary comprehension it could be cut down tremendously too, but can't get it to work with popping from the dict.
```
i=raw_input().split(",")
d = {}
for x in i:
for c in range(1,len(x)+1):
if x[:c] in d:
del d[x[:c]]
else:
d[x[:c]]=x
print d
```
The print will output the dictionary, unordered.
EDIT: Ahh I missed the car:car / car:carpet criteria. Maybe a length check?
[Answer]
## Groovy - 212 chars
Golfed:
```
c="collectEntries";f="findAll";def g={def h=[:].withDefault{[]};it.each{def w->w.size().times{ h[w[0..it]] << w}};(h."$f"{k,v->v.size()==1}."$c"{k,v->[k,v[0]]}).plus(h."$f"{k,v->v.contains(k)}."$c"{k,v->[k,k]})}
```
example output:
```
println g(["code","golf","going"])
[c:code, co:code, cod:code, code:code, gol:golf, golf:golf, goi:going, goin:going, going:going]
```
Ungolfed:
```
def g = { def list ->
def hash = [:].withDefault{[]}
list.each {
def word -> word.size().times{ hash[word[0..it]] << word }
}
def map = hash.findAll{ k,v -> v.size() == 1 }.collectEntries{ k,v -> [k,v[0]] }
map.plus(hash.findAll{ k,v -> v.contains(k) }.collectEntries{ k,v -> [k,k] }
map
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 88 bytes
```
L=>L.map(s=>[...s].map(c=>L.filter(t=>t>S&t<S+'~',S+=c)[1]&&s>S||(R[S]=s),S=''),R={})&&R
```
[Try it online!](https://tio.run/##HY2xDsIgFAD/hgcpkjjXxxd0gpEwNFiaGoSmj3Sx@uuonS53yz3GfaSwLWu95HKfWsQ2oB7Uc1w5oXZKKfKnhX@OS6rTxivqqi2rN9vBB6TtMAh39YyRtsfBjbMeSUiLAEIafL0FY6b1oWQqaVKpzDxyB@F3BAlzSfHEkmfwQvStfQE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/), 95 bytes
```
local -A m
for w;{m[$w]=$w;x=
for c (${(s::)w})x+=$c&&[ ${(M)@:#$x*} = $w ]&&m[$x]=$w
}
local m
```
[Try it online!](https://tio.run/##JYxBCsMgFAX3nuJDP6ItuYBBaA/QE4Qsgok2oLWYhdLg2Y0mizeLgXn/7VM046xYryYL3Qsc0T5A7Hc3YBwlxj7JUylguLNNCB4zTw@JitIBqnrzp7hhumeQgBFGSmuaWkoyuX5d4YRoUH5ewHirK9avqea3LhfbwonQzASzN@UA "Zsh – Try It Online")
The only way to "return" an associative array in Bash/Zsh is by declaring it without the `local` keyword and then accessing it in the parent scope. [This would save one byte.](https://tio.run/##qyrO@J@moVn9v6SyILU4tURBN91RIddWQ5MrLb9Iody6OjdapTzWVqXcusIWLJSsoKFSrVFsZaVZXqtZoW2rkqympgEUUgaK@mo6WCmrVGjV1uoaamrW1AD1VoD0ctX@r@XiSlNIzk9JVUjPz0kDEpl56VwwO3OBcgWZqeh8EC4CE0WocokKKflIuv8DAA "Zsh – Try It Online") However, I/O via variables is generally frowned upon, so we print the array definition instead.
```
local -A m # declare m as associative
# "local" is shorter than "typeset"/"declare"
for w;{ # for each word
m[$w]=$w # the word is a prefix of itself
x= # ensure x is empty
for c (${(s::)w}) # for each character in the word
x+=$c && # append to x (building a prefix
[ ${(M)@:#$x*} = $w ] && # if the only match is the word itself:
m[$x]=$w # ... then x is a prefix of w
}
local m # print m
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 84 bytes
Just noticed there's already an existing Ruby solution, oh well. This basically improves on the old solution by picking prefixes in a smarter way (eliminating the need to add each word as a "prefix" at the end) and counting prefixes to check uniqueness before adding them to the hash, instead of overwriting the value with a dummy if there is a duplicate and then erasing the entry.
```
->w{h={};w.map{|e|(1..e.size).map{|i|w.count{|d|d[0,i]==e[0,i]}<2?h[e[0,i]]=e:0}};h}
```
[Try it online!](https://tio.run/##JYlBDsIgFET3nIKFC02UVJdW6kEaYrB8y08qkNKGKHB2rO3ivZnMjPPzUyQvpyZEzWOuA3tLFxOk/ZkxYB6/cNgmTIF1djZTTCqptjqi4BzWzLfLXbdbFxyuVc61ziVoHID2MHlCqaOy3T2YdwNOgoBRpbNqee3wWoSmJw7hD10YV41AJFW2/wE "Ruby – Try It Online")
] |
[Question]
[
My robot has short circuited somehow and randomly run off somewhere from my lab!
Luckily, whenever he does this, his shut-down sequence initiates, giving him enough time to randomly turn and run in the direction its facing for five rounds before he switches off. His gyro and accelerometer functions are still relaying the data back to the lab while he is still on.
The data will always come in the form of five sets of two numbers, for example.
`12:234,-135:47,-68:230,140:324,127,87`
Your mission, golfers is to a) simulate the robot's frantic run and turn sequence by displaying five sets of numbers in the form of `a1:d1,a2:d2,a3:d3,a4:d4,a5:d5` where `a`(n) is the clockwise angle (in degrees) such that `-179<=a<=+180` that the robot will turn from its current heading (initially it is at zero heading before it runs amok and turns for the first time), and `d`(n) is the distance in feet it has run before the next heading change which is such that `0<=d<=500` feet; and b) A calculated heading from the lab (which is also facing a heading of zero), distance in feet (accuracy up to 3 decimal places is strongly encouraged, -5 bytes if you do), and the orientation heading (in degrees) of where my robot it is facing when it has switched off.
Easy example:
```
Data: 0:1,45:1,90:1,90:1,90:1
Heading: 0
Distance: 1
Orientation: -45
```
The random turns and distances are just that, random. No set values are to be hard coded, we must see the randomness in action within the code.
Restrictions to randomness: No clock or date based references, we need to see a native `random` reference within the code. Whenever you run this code, the randomness must present itself with a possibility of showing 1 of 360 possible angles of turning with each turn-run round. So the robot may turn -36 degrees at one turn and may turn +157 degrees the next, followed by another turn of +2 degrees by another turn of -116 degrees and a final turn of +42 degrees on the final turn. At least 360 distinct values must be possible (between -179 to +180 degrees inclusive) with each random angle generation.
Restrictions to distance run: Similarly set, there are 501 possible distances the robot can run, (between 0 and 500 feet inclusive), so I expect the randomness to also be available when determining the robot's running distance. The robot could theoretically run 45, 117, 364, 27 and 6 feet with each of its respective rounds...
The data fed to you will always be in integer values... the robot will turn in integer ranges of degrees, and will run in integer ranges of distance. The output values however, will be floats...
This is code-golf. Shortest code wins... Now go find my robot!
PS: In reference to my "Accuracy up to 3 decimal places", if you can provide the heading (in degrees, to a MINIMUM of 3 decimal places) and a distance in feet (also accurate also to a MINIMUM 3 decimal places) you will get a -5 byte bonus).
[Answer]
# Ruby, ~~274~~ ~~252~~ ~~249~~ ~~245~~ ~~214~~ ~~211~~ ~~207~~ ~~204~~ 202 characters (-5 = 197)
How did PHP beat Ruby in char count?! >:O Must find some way to golf more...
Edit: I beat the PHP answer, but the user who wrote it helped me do it! Go upvote him; he deserves it :-P
Another edit: Gah! He passed me again! You are a very worthy opponent, @MathieuRodic; congratulations, I have to let you win ;-)
```
P=(M=Math)::PI
puts"Data: #{([x=y=a=0]*5).map{a+=o=rand -179..e=180;x+=M.sin(b=a*P/e)*d=rand 500;y+=d*M.cos b;"#{o}:#{d}"}*?,}
Heading: #{M.atan(y/x)/P*-e+90}
Distance: #{M.hypot x,y}
Orientation: #{a}"
```
Ungolfed code (and ~~slightly~~ much older version):
```
data = Array.new(5) { [rand(-179..180), rand(0..500)] }
puts "Data: #{data.map{|x|"#{x[0]}:#{x[1]}"}.join ?,}"
x, y, a = [0] * 3
data.each do |o, d|
a += o
x += Math.sin(a * Math::PI / 180) * d
y += Math.cos(a * Math::PI / 180) * d
end
puts "Heading: #{Math.atan(y / x) / Math::PI * -180 + 90}
Distance: #{Math.sqrt(x * x + y * y)}
Orientation: #{a}"
```
Sample output:
```
c:\a\ruby>robotgolf
Data: 94:26,175:332,14:390,159:448,-45:20
Heading: 124.52305879195005
Distance: 279.5742334385328
Orientation: 397
```
[Answer]
# PHP - 238 232 221 212 203 199 characters
```
for(;$i<5;$h+=$a=rand(-179,181),$x+=cos($b=$a*$k=M_PI/180)*$l=rand(0,501),$y+=$l*sin($b),$d.=($i++?",":"")."$a:$l");echo"Data: $d
Heading: $h
Distance: ".hypot($x,$y)."
Orientation: ".atan2($y,$x)/$k
```
(test it here: <http://ideone.com/dNZnKX>)
**Non-golfed version:**
```
$k = M_PI / 180;
$h = $x = $y = 0;
$d = "";
for ($i=5; $i--;){
$h += $a = rand(-179,181);
$x += ($l = rand(0, 501)) * cos($b = $k * $a);
$y += $l * sin($b);
$d .= ($d ? "," : "") . "$a:$l";
}
echo "Data: $d\nHeading: $h\nDistance: " . sqrt($x*$x + $y*$y) ."\nOrientation: " . atan2($y, $x)/$k . "\n";
```
(test it here: <http://ideone.com/1HzWH7>)
[Answer]
# Python - 264 259 256 258 - 5 = 253 characters
```
from math import*;import random as R;r,k,d=R.randint,pi/180,[];h=x=y=0;exec"a,l=r(-179,180),r(0,500);d+=[`a`+':'+`l`];h+=a;x+=l*cos(k*a);y+=l*sin(k*a);"*5;print('Data: %s\nHeading: %d\nDistance: %.3f\nOrientation: %d'%(','.join(d),h,hypot(x,y),atan2(y,x)/k))
```
(test it at <http://ideone.com/FicW6e>)
**Ungolfed version:**
```
from math import *
from random import randrange as r
k = pi / 180
h = x = y = 0
d = []
for i in range(5):
a = r(-179,181)
l = r(501)
d += ['%d:%d' % (a, l)]
h += a
x += l * cos(k * a)
y += l * sin(k * a)
print('Data: %s\nHeading: %d\nDistance: %.3f\nOrientation: %f' % (','.join(d), h, sqrt(x*x+y*y), atan2(y,x)/k))
```
(test it at <http://ideone.com/O3PP7T>)
NB: many answers include *-5* in their title, while their program does not represent the distance with *accuracy up to 3 decimal places*...
[Answer]
# Perl 6: ~~188~~ 184 characters - 5 = 180 points
```
$_=((-179..180).pick=>(^501).pick)xx 5;my$o;$/=([+] .map:{unpolar .value,$o+=.key/($!=180/pi)}).polar;say "Data: {.fmt("%d:%d",",")}
Heading: {$1*$!}
Distance: $0
Orientation: {$o*$!}"
```
Golf with whitespace:
```
$_ = ((-179..180).pick => (^501).pick) xx 5;
my $o;
$/ = ([+] .map: {
unpolar .value, $o += .key / ($!=180/pi)
}).polar;
say "Data: {.fmt("%d:%d", ",")}
Heading: {$1*$!}
Distance: $0
Orientation: {$o*$!}"
```
Ungolfed:
```
my &postfix:<°> = */180*pi; # Deg → Rad
my &postfix:<㎭> = */pi*180; # Rad → Deg
my @data = ((-179..180).pick => (0..500).pick) xx 5;
say "Data: @data.fmt("%d:%d", ",")";
my $cum-angle = 0;
my $complex = [+] @data.map: {unpolar .value, $cum-angle += .key°}
my ($dist, $ang) = $complex.polar;
say "Heading: ", $ang.㎭;
say "Distance: ", $dist;
say "Orientation: ", $cum-angle.㎭;
```
This turns the data into complex numbers with `unpolar`, puts the sum of them into `$complex`, and then gets the polar coordinates as `$dist`, `$ang`.
The cumulative angle, `$cum-angle` is collected because the angles are relative to the robot as it moves through the lab and because we need the final angle of the robot in our output.
Sample output:
```
Data: -73:230,-144:453,-151:274,-52:232,88:322
Heading: -5.33408558001246
Distance: 378.74631610127
Orientation: -332
```
The only real trick the golf uses is that it (mis)uses all 3 of Perl 6's special variables to good effect:
* `$!` is used for radians ↔ degrees
* `$_` holds the data, and anything that looks like a lonely `.method()` actually means `$_.method()` (except inside the `map {…}` block, where `$_` actually takes on the value of the number pairs that make up the data)
* `$/` holds what is in the ungolfed version `($dist, $ang)`. `$0` and `$1` actually mean `$/[0]`, i.e., `$dist`, and `$/[1]`, i.e., `$ang`
[Answer]
# Python 301-5=296
```
from math import*
r=__import__("random").randint
o=x=y=0
s=[]
for i in[0]*5:a=r(-179,180);d=r(0,500);o+=a;o+=180*((o<-179)-(o>180));n=pi*o/180;x+=d*cos(n);y+=d*sin(n);s+=["%d:%d"%(a,d)]
print"Data: "+",".join(s)+"\nHeading: %d"%degrees(atan(y/x))+"\nDistance: %f"%sqrt(x**2+y**2)+"\nOrientation: %d"%o
```
Nothing too fancy here, rather verbose. This is one problem for which I am not happy that python's trig functions work in radians.
```
> python robot.py
Data: 17:469,110:383,-146:240,-78:493,62:1
Heading: -17
Distance: 405.435748
Orientation: -35
> python robot.py
Data: -119:363,89:217,129:321,10:159,-56:109
Heading: -79
Distance: 130.754395
Orientation: 53
```
[Answer]
## Python 2 = ~~376~~ 319 characters (-5 for distance=314)
```
import random,math
h=x=y=0
for i in range(5):
a=random.randint(-179,180)
d=random.randint(0,500)
print '%d:%d,'%(a,d),
h+=a
if h>180:
h-=360
x+=d*math.cos(h)
y+=d*math.sin(h)
t=math.sqrt(x**2+y**2)
o=math.atan2(y,x)
print
print 'Heading: %d\nDistance: %3f\nOrientation: %d' % (h,t,o)
```
sample output
```
-141:245, 56:355, 145:223, -10:80, -38:253,
Heading: 12
Distance: 559.031404
Orientation: -2
```
] |
[Question]
[
Write a program that takes a brainfuck program and compiles it to executable machine code. You can target x86, x86\_64, jvm (java bytecode) or armv6, and use one of the following executable formats: ELF, a.out, class file, exe, com. The executable should work in Linux or Windows (or Java on either).
Neither your program nor the generated executable may run any external program (such as another compiler, assembler or interpreter).
Shortest code wins.
[Answer]
## Python, 1974 chars
```
import sys
s='\x11\x75\x30\xbc\x08\x4b\x03\x3c'
k=[]
for c in sys.stdin.read():
if'>'==c:s+='\x84\x01\x01'
if'<'==c:s+='\x84\x01\xff'
if'+'==c:s+='\x2a\x1b\x5c\x33\x04\x60\x91\x54'
if'-'==c:s+='\x2a\x1b\x5c\x33\x04\x64\x91\x54'
if'['==c:k+=[len(s)];s+='\x2a\x1b\x33\x99\x00\x00'
if']'==c:a=k[-1];k=k[:-1];d=len(s)-a;s=s[:a+4]+'%c%c'%(d>>8,d&255)+s[a+6:]+'\xa7%c%c'%(-d>>8&255,-d&255)
if','==c:s+='\x2a\x1b\xb2\x00\x02\xb6\x00\x03\x91\x54'
if'.'==c:s+='\xb2\x00\x04\x59\x2a\x1b\x33\xb6\x00\x05\xb6\x00\x06'
s+='\xb1'
n=len(s)
sys.stdout.write('\xca\xfe\xba\xbe\x00\x03\x00-\x00+\n\x00\x08\x00\x13\t\x00\x14\x00\x15\n\x00\x16\x00\x17\t\x00\x14\x00\x18\n\x00\x19\x00\x1a\n\x00\x19\x00\x1b\x07\x00\x1c\x07\x00\x1d\x01\x00\x06<init>\x01\x00\x03()V\x01\x00\x04Code\x01\x00\x0fLineNumberTable\x01\x00\x04main\x01\x00\x16([Ljava/lang/String;)V\x01\x00\nExceptions\x07\x00\x1e\x01\x00\nSourceFile\x01\x00\x06B.java\x0c\x00\t\x00\n\x07\x00\x1f\x0c\x00 \x00!\x07\x00"\x0c\x00#\x00$\x0c\x00%\x00&\x07\x00\'\x0c\x00(\x00)\x0c\x00*\x00\n\x01\x00\x01B\x01\x00\x10java/lang/Object\x01\x00\x13java/io/IOException\x01\x00\x10java/lang/System\x01\x00\x02in\x01\x00\x15Ljava/io/InputStream;\x01\x00\x13java/io/InputStream\x01\x00\x04read\x01\x00\x03()I\x01\x00\x03out\x01\x00\x15Ljava/io/PrintStream;\x01\x00\x13java/io/PrintStream\x01\x00\x05write\x01\x00\x04(I)V\x01\x00\x05flush\x00!\x00\x07\x00\x08\x00\x00\x00\x00\x00\x02\x00\x01\x00\t\x00\n\x00\x01\x00\x0b\x00\x00\x00\x1d\x00\x01\x00\x01\x00\x00\x00\x05*\xb7\x00\x01\xb1\x00\x00\x00\x01\x00\x0c\x00\x00\x00\x06\x00\x01\x00\x00\x00\x03\x00\t\x00\r\x00\x0e\x00\x02\x00\x0b\x00\x00'+'%c%c'%((n+60)>>8,(n+60)&255)+'\x00\x04\x00\x03\x00\x00'+'%c%c'%(n>>8,n&255)+s+'\x00\x00\x00\x01\x00\x0c\x00\x00\x00*\x00\n\x00\x00\x00\x05\x00\x06\x00\x06\x00\x08\x00\t\x00\x0b\x00\x0b\x00\x13\x00\r\x00\x1d\x00\x0f\x00&\x00\x11\x00,\x00\x12\x002\x00\x14\x008\x00\x15\x00\x0f\x00\x00\x00\x04\x00\x01\x00\x10\x00\x01\x00\x11\x00\x00\x00\x02\x00\x12')
```
Below are the translations to java bytecode. local 0 is a byte array representing the tape, local 1 is the data pointer.
```
> iinc 1,+1
< iinc 1,-1
+ aload_0;iload_1;dup2;baload;iconst_1;iadd;i2b;bastore
- aload_0;iload_1;dup2;baload;iconst_1;isub;i2b;bastore
[ aload_0;iload_1;baload;ifeq xx xx
] goto xx xx
, aload_0;iload_1;getstatic #2;invokevirtual #3;i2b;bastore
. getstatic #4;dup;aload_0;iload_1;baload;invokevirtual #5;invokevirtual #6
```
The `xx xx` are offsets to reach the matching bracket. #2 is `System.in`, #3 is `read()`, #4 is `System.out`, #5 is `write()`, and #6 is `flush()`.
The preamble allocates a 30000 byte array and initializes the tape position to 0.
The giant wrapper at the end was generated by compiling a dummy `B.java` file with code for one of each opcode (to induce generation of the correct constant tables and other junk), then performing delicate surgery on it.
Run it like
```
python bfc.py < input.b > B.class
java B
```
Disassemble with
```
javap -c B
```
I'm sure it could be golfed some more. I'm just happy it works...
[Answer]
# C, ~~866~~ 783 bytes
Since my code outputs 32 bit ELF executable I can't promise that it will work on everyones setup. It took enough tweaking to get the executable to stop segfaulting on my computer.
For anyone trying to run this:
```
$ uname --all
Linux 4.4.0-24-generic #43-Ubuntu SMP Wed Jun 8 19:27:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
```
A Brainfuck program is read from stdin and the compiled ELF is written to stdout.
```
#define P *(t++)
#define C case
#define B break
char a[30000],b[65535],f,*t=b;*c[100];**d=c;main(g){P=188;t+=4;while((f=getchar())!=-1)switch(f){C'>':P=68;B;C'<':P=76;B;C'+':P=254;P=4;P=36;B;C'-':P=254;P=12;P=36;B;C'.':P=187;t+=4;P=137;P=225;P=186;P=1;t+=3;P=184;P=4;t+=3;P=205;P=128;B;C',':P=187;P=1;t+=3;P=137;P=225;P=186;P=1;t+=3;P=184;P=3;t+=3;P=205;P=128;B;C'[':P=138;P=4;P=36;P=133;P=192;P=15;P=132;t+=4;*d=(int*)t-1;d++;B;C']':P=138;P=4;P=36;P=133;P=192;P=15;P=133;t+=4;d--;g=((char*)(*d+1))-t;*((int*)t-1)=g;**d=-g;B;}P=184;P=1;t+=3;P=187;t+=4;P=205;P=128;*(int*)(b+1)=0x8048054+t-b;long long z[]={282579962709375,0,4295163906,223472812116,0,4297064500,4294967296,577727389698621440,36412867248128,30064779550,140720308490240};write(1,&z,84);write(1,b,t-b);write(1,a,30000);}
```
# Ungolfed
In the ungolfed version of the code, you can get a better idea of what's going on. The character array at the end of the golfed code is an encoding of the ELF and program header in the ungolfed code. This code also show how each Brainfuck instruction is translated into bytecode.
```
#include <linux/elf.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#define MAX_BIN_LEN 65535
#define MAX_JUMPS 100
unsigned int org = 0x08048000;
unsigned char move_right[] = {0x44}; /*inc esp */
unsigned char move_left[] = {0x4c}; /*dec esp */
unsigned char inc_cell[] = {0xfe,0x04,0x24}; /*inc [esp] */
unsigned char dec_cell[] = {0xfe,0x0c,0x24}; /*dec [esp] */
unsigned char read_char[] = {0xbb,0x00,0x00,0x00,0x00, /*mov ebx, 0 */
0x89,0xe1, /*mov ecx, esp */
0xba,0x01,0x00,0x00,0x00, /*mov edx, 1 */
0xb8,0x03,0x00,0x00,0x00, /*mov eax, 3 */
0xcd,0x80}; /*int 0x80 */
unsigned char print_char[] = {0xbb,0x01,0x00,0x00,0x00, /*mov ebx, 1 */
0x89,0xe1, /*mov ecx, esp */
0xba,0x01,0x00,0x00,0x00, /*mov edx, 1 */
0xb8,0x04,0x00,0x00,0x00, /*mov eax, 4 */
0xcd,0x80}; /*int 0x80 */
unsigned char loop_start[] = {0x8a,0x04,0x24, /*mov eax, [esp] */
0x85,0xc0, /*test eax, eax */
0x0f,0x84,0x00,0x00,0x00,0x00}; /*je int32_t */
unsigned char loop_end[] = {0x8a,0x04,0x24, /*mov eax, [esp] */
0x85,0xc0, /*test eax, eax */
0x0f,0x85,0x00,0x00,0x00,0x00}; /*jne int32_t */
unsigned char call_exit[] = {0xb8,0x01,0x00,0x00,0x00, /*mov eax, 1 */
0xbb,0x00,0x00,0x00,0x00, /*mov ebx, 0 */
0xcd,0x80}; /*int 0x80 */
unsigned char prelude[] = {0xbc,0x00,0x00,0x00,0x00}; /*mov esp, int32_t*/
unsigned char tape[100];
int main(){
unsigned char text[MAX_BIN_LEN];
unsigned char *txt_ptr = text;
int32_t *loop_jmps[MAX_JUMPS];
int32_t **loop_jmps_ptr = loop_jmps;
Elf32_Off entry;
entry = org + sizeof(Elf32_Ehdr) + 1 * sizeof(Elf32_Phdr);
memcpy(txt_ptr,prelude,sizeof(prelude));
txt_ptr += sizeof(prelude);
char input;
while((input = getchar()) != -1){
switch(input){
case '>':
memcpy(txt_ptr,move_right,sizeof(move_right));
txt_ptr += sizeof(move_right);
break;
case '<':
memcpy(txt_ptr,move_left,sizeof(move_left));
txt_ptr += sizeof(move_left);
break;
case '+':
memcpy(txt_ptr,inc_cell,sizeof(inc_cell));
txt_ptr += sizeof(inc_cell);
break;
case '-':
memcpy(txt_ptr,dec_cell,sizeof(dec_cell));
txt_ptr += sizeof(dec_cell);
break;
case '.':
memcpy(txt_ptr,print_char,sizeof(print_char));
txt_ptr += sizeof(print_char);
break;
case ',':
memcpy(txt_ptr,read_char,sizeof(read_char));
txt_ptr += sizeof(read_char);
break;
case '[':
memcpy(txt_ptr,loop_start,sizeof(loop_start));
txt_ptr += sizeof(loop_start);
*loop_jmps_ptr = (int32_t*) txt_ptr - 1;
loop_jmps_ptr++;
break;
case ']':
memcpy(txt_ptr,loop_end,sizeof(loop_end));
txt_ptr += sizeof(loop_end);
loop_jmps_ptr--;
int32_t offset = ((unsigned char*) (*loop_jmps_ptr + 1)) - txt_ptr;
*((int32_t*)txt_ptr - 1) = offset;
**loop_jmps_ptr = -offset;
break;
}
}
memcpy(txt_ptr,call_exit,sizeof(call_exit));
txt_ptr += sizeof(call_exit);
*(int32_t*)(text + 1) = entry + (txt_ptr - text);
Elf32_Ehdr ehdr = {
{0x7F,'E','L','F',ELFCLASS32,ELFDATA2LSB,EV_CURRENT,0,0,0,0,0,0,0,0,0},
ET_EXEC,
EM_386,
EV_CURRENT,
entry,
sizeof(Elf32_Ehdr),
0,
0,
sizeof(Elf32_Ehdr),
sizeof(Elf32_Phdr),
1,
0,
0,
SHN_UNDEF,
};
Elf32_Phdr phdr = {
PT_LOAD,
0,
org,
org,
sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
PF_R | PF_X | PF_W,
0x1000,
};
int out = open("a.out",O_CREAT|O_TRUNC|O_WRONLY,S_IRWXU);
write(out,&ehdr,sizeof(Elf32_Ehdr));
write(out,&phdr,sizeof(Elf32_Phdr));
write(out,text,txt_ptr-text);
write(out,tape,sizeof(tape));
close(out);
}
```
---
# Self Modifying BrainFuck
In order to save on bytes, the tape for my compiler isn't allocated in a `.bss` section or anything fancy like that. Instead, the tape is 30,000 null bytes written directly after the compiled byte code of the Brainfuck program. Knowing this, and being aware of what byte code is generated by my compiler means that you can generate or modify byte code at runtime. A simple illustration of this 'feature' is a Brainfuck program that sets its own exit value.
```
<<<<<<+
```
The program goes off the left edge of the tape into the byte code to the point that the exit code is normally set 0. Incrementing this byte causes the exit code to be set to 1 instead of 0 when the program eventually exits. With persistence, this could be used to do system level programming in Brainfuck.
[Answer]
## 16-bit x86 assembly code, 104 bytes
This code is from 2014, but I just found the task.
```
;compliant version, non-commands are ignored, but 104 bytes long
[bits 16]
[org 0x100]
; assume bp=091e used
; assume di=fffe
; assume si=0100
; assume dx=cs (see here)
; assume cx=00ff
; assume bx=0000
; assume ax=0000 used (ah)
; assume sp=fffe
start:
mov al, code_nothing - start
code_start:
mov ch, 0x7f ; allow bigger programs
mov bx, cx
mov di, cx
rep stosb
mov bp, find_right + start - code_start ;cache loop head for smaller compiled programs
jmp code_start_end
find_right:
pop si
dec si
dec si ;point to loop head
cmp [bx], cl
jne loop_right_end
loop_right:
lodsb
cmp al, 0xD5 ; the "bp" part of "call bp" (because 0xFF is not unique, watch for additional '[')
jne loop_left
inc cx
loop_left:
cmp al, 0xC3 ; ret (watch for ']')
jne loop_right
loop loop_right ;all brackets matched when cx==0
db 0x3c ;cmp al, xx (mask push)
loop_right_end:
push si
lodsw ; skip "call" or dummy "dec" instruction, depending on context
push si
code_sqright:
ret
code_dec:
dec byte [bx]
code_start_end:
db '$' ;end DOS string, also "and al, xx"
code_inc:
inc byte [bx]
db '$'
code_right:
inc bx ;al -> 2
code_nothing:
db '$'
code_left:
dec bx
db '$'
code_sqleft:
call bp
db '$'
; create lookup table
real_start:
inc byte [bx+'<'] ;point to code_left
dec byte [bx+'>'] ;point to code_right
mov byte [bx+'['], code_sqleft - start
mov byte [bx+']'], code_sqright - start
lea sp, [bx+45+2] ;'+' + 4 (2b='+', 2c=',', 2d='-', 2e='.')
push (code_dec - start) + (code_dot - start) * 256
push (code_inc - start) + (code_comma - start) * 256
pre_write:
mov ah, code_start >> 8
xchg dx, ax
; write
mov ah, 9
int 0x21
; read
code_comma:
mov dl, 0xff
db 0x3d ; cmp ax, xxxx (mask mov)
code_dot:
mov dl, [bx]
mov ah, 6
int 0x21
mov [bx], al
db '$'
db 0xff ; parameter for '$', doubles as test for zero
; switch
xlatb
jne pre_write
; next two lines can also be removed
; if the program ends with extra ']'
; and then we are at 100 bytes... :-)
the_end:
mov dl, 0xC3
int 0x21
int 0x20
```
] |
[Question]
[
USGS's seismometers have just detected a major earthquake! Emergency response teams need a quick estimate of the number of people affected. Write a program to compute this estimate.
Your program receives 2 inputs. The first is the details of the earthquake itself. The earthquake modeled as a line segment along which the earth ruptured, along with the critical distance from the fault within which damage could be expected. The second input is a list of the location and population of cities in the area. Your program should compute the number of people living in the affected area, that is the sum of the population of all cities within the critical distance of the fault segment.
## Input
First a line describing the earthquake, containing the x,y coordinates of the start and end points of the fault, plus the critical distance. The format is `A_x A_y B_x B_y D`. For example:
```
3.0 3.0 7.0 4.0 2.5
```
encodes the fault extending from (3.0,3.0) to (7.0,4.0) and a critical distance of 2.5.
Second, one line per city in the area, containing the x,y coordinates of the city and its population. For example:
```
1.0 1.0 2500
5.0 7.0 8000
3.0 4.0 7500
9.0 6.0 3000
4.0 2.0 1000
```

## Output
The number of people living in the affected area. For the above example only the third and fifth cities are in the danger area, so the output would be
```
8500
```
Shortest code wins.
### Example 2
```
0.0 0.0 10.0 0.0 5.0
5.0 4.0 10000
5.0 -4.0 1000
5.0 6.0 100
11.0 2.0 10
-4.0 4.0 1
```
generates
```
11010
```
[Answer]
## Ruby, 171 152 155 153
```
u,v,a,b,d=gets.split.map &:to_f
a-=u;b-=v
p eval$<.map{|l|"(x=%f-u;t=(a*x+b*y=%f-v)/(a*a+b*b);d*d<(x-a*t=t<0?0:t>1?1:t)**2+(y-t*b)**2?0:%d)"%l.split}*'+'
```
This is my first ruby submission and my first code-golf at all. Straight forward implementation of the task. Please give me some hints how to improve (there must be a shorter way to read floats...).
[Answer]
## Javascript (437)
This can probably be golfed significantly, but not enough to beat the Ruby solution.
```
p=$("#i").text().split("\n");for(i=0;i<p.length;i++){p[i]=p[i].split(" ")}
z=p[0];a=z[0];b=z[1];c=z[2];d=z[3];e=z[4];o=0;f=[a,b];g=[c,d];
function q(r,s){return Math.sqrt(Math.pow(s[0]-r[0],2)+Math.pow(s[1]-r[1],2))}
for(i=1;i<p.length;i++){w=p[i];u=((w[0]-a)*(c-a)+(w[1]-b)*(d-b))/Math.pow(q(f,g,2),2);
x=[(a*1)+u*(c-a),(b*1)+u*(d-b)];l=e;m=w[2]*1;u=w[0];w=w[1];v=[u,w];
o+=q(v,x)<l&&q(x,g)+q(x,f)==q(f,g)?m:q(v,f)<l?m:q(v,g)<l?m:0}alert(o);
```
You can see it in action [here](http://jsfiddle.net/BDZMd/4/).
[Answer]
### C# - 743 715
```
namespace System{using Linq;using m=Math;class P{public float X,Y;}class E{static void Main(){Func<string,float>p=s=>float.Parse(s);Func<P,P,double>d=(a,b)=>{return a.X*b.X+a.Y*b.Y;},c=(a,b)=>{return a.X*b.Y-a.Y*b.X;};Func<P,P,P>u=(a,b)=>{return new P{X=a.X-b.X,Y=a.Y-b.Y};};Func<P,P,P,double>g=(A,B,C)=>{return d(u(C,B),u(B,A))>0?m.Sqrt(d(u(B,C),u(B,C))):d(u(C,A),u(A,B))>0?m.Sqrt(d(u(A,C),u(A,C))):m.Abs(c(u(B,A),u(C,A))/m.Sqrt(d(u(B,A),u(B,A))));};var n=IO.File.ReadAllLines("i");var i=n[0].Split();var q=new{A=new P{X=p(i[0]),Y=p(i[1])},B=new P{X=p(i[2]),Y=p(i[3])},D=p(i[4])};Console.WriteLine((from l in n.Skip(1)let f=l.Split()let w=new P{X=p(f[0]),Y=p(f[1])}where g(q.A,q.B,w)<q.D select p(f[2])).Sum());}}}
```
Non-Golfed:
```
namespace System
{
using Linq;
using m = Math;
class Point { public float X, Y;}
class Earthquake
{
static void Main()
{
Func<string, float> parse = s => float.Parse(s);
Func<Point, Point, double> dotProduct = (a, b) => { return a.X * b.X + a.Y * b.Y; },
crossProduct = (a, b) => { return a.X * b.Y - a.Y * b.X; };
Func<Point, Point, Point> subtract = (a, b) => { return new Point { X = a.X - b.X, Y = a.Y - b.Y }; };
Func<Point, Point, Point, double> getDistance = (A, B, C) => {
return dotProduct(subtract(C, B), subtract(B, A)) > 0 ?
m.Sqrt(dotProduct(subtract(B, C), subtract(B, C))) :
dotProduct(subtract(C, A), subtract(A, B)) > 0 ?
m.Sqrt(dotProduct(subtract(A, C), subtract(A, C))) :
m.Abs(crossProduct(subtract(B, A), subtract(C, A)) / m.Sqrt(dotProduct(subtract(B, A), subtract(B, A))));
};
var inputLines = IO.File.ReadAllLines("i");
var quakeLine = inputLines[0].Split();
var quake = new {
PointA = new Point { X = parse(quakeLine[0]), Y = parse(quakeLine[1]) },
PointB = new Point { X = parse(quakeLine[2]), Y = parse(quakeLine[3]) },
Distance = parse(quakeLine[4])
};
var affectedPopulations = (from line in inputLines.Skip(1)
let fields = line.Split()
let location = new Point { X = parse(fields[0]), Y = parse(fields[1]) }
let population = parse(fields[2])
where getDistance(quake.PointA, quake.PointB, location) < quake.Distance
select population);
Console.WriteLine(affectedPopulations.Sum());
}
}
}
```
[Answer]
## c -- 471 characters
```
#include <stdio.h>
#define F float
#define G getline(&v,&l,stdin)
F a[2],b[2],c[2],d[2],e[2],r,t,y,z;char*v;size_t l,n,p;
F s(F u[2],F v[2]){y=u[0]-v[0];z=u[1]-v[1];return y*y+z*z;}
j(F g[2],F h[2],F i[2]){*i=*g-*h;i[1]=g[1]-h[1];}
int i(){j(b,a,d);j(c,a,e);t=*d**e+d[1]*e[1];
return s(a,c)<=r||s(b,c)<=r||t>0&&t/s(a,b)<=1&&s(a,c)-t*t/s(a,b)<=r;}
int main(){G;sscanf(v,"%f %f %f %f %f",a,a+1,b,b+1,&r);r*=r;
while(G!=-1)sscanf(v,"%f %f %i",c,c+1,&p),n+=p*i();printf("%d\n",n);}
```
It assumes your standard library has `getline`.
The method is clarified a bit in the comment to the ungolfed version:
```
#include <stdio.h>
float a[2],b[2],c[2],d[2],e[2],r,t,y,z;
char*v;
size_t l,n,p;
float s(float u[2],float v[2]){ /* returns the square of the distance
between two points */
y=u[0]-v[0];
z=u[1]-v[1];
return y*y+z*z;
}
j(float g[2],float h[2],float i[2]){ /* sets i=g-h */
i[0]=g[0]-h[0];
i[1]=g[1]-h[1];
}
int i/*sCLose*/(){
j(b,a,d); /* d=b-a */
j(c,a,e); /* e=c-a */
t=d[0]*e[0]+d[1]*e[1]; /* dot product */
return
(s(a,c)<=r) || /* near one end point */
(s(b,c)<=r) || /* near the other */
(
(t>0) && /* C lies more "towards" B than away */
(t/s(a,b)<=1) && /* Nearest point on AB to C lies between A and B */
(s(a,c)-t*t/s(a,b)<=r) /* length of the altitude less than R */
);
}
int main(){
getline(&v,&l,stdin);
sscanf(v,"%f %f %f %f %f",a,a+1,b,b+1,&r);
r*=r; /* r is now r squared, as that is the only way we use it */
printf("(%f, %f); (%f, %f): %f\n",a[0],a[1],b[0],b[1],r);
while (getline(&v,&l,stdin) != -1){
sscanf(v,"%f %f %i",c,c+1,&p);
printf("\t (%f, %f): %d\n",c[0],c[1],p);
n+=p*i/*sClose*/();
}
printf("%d\n",n);
}
```
[Answer]
### scala: 660 chars:
```
object E extends App{
type I=Int
type D=Double
def b(h:D,i:D,x:I,y:I,d:D)=(x-h)*(x-h)+(y-i)*(y-i)<=d*d
def a(p:java.awt.Polygon,x:I,y:I,h:I,i:I,d:D,r:Array[String])={
val w=r(0).toDouble
val j=r(1).toDouble
val n=r(2).toInt
if (p.contains(w,j)||b(j,w,x,y,d)||b(j,w,i,h,d))n
else 0}
val s=new java.util.Scanner(System.in)
val b=s.nextLine.split(" ")
val c=b.map(_.toDouble)
val e=c.map(_.toInt)
val(x,h,y,i,d)=(e(0),e(2),e(1),e(3),c(4))
val f=List(x,h)
val g=List(y,i)
val p=new java.awt.Polygon((f:::f.reverse).toArray,(g.map(_-e(4)):::g.reverse.map(_+e(4))).toArray,4)
var r=0
while(s.hasNext){
val row=s.nextLine
r+=a(p,x,y,h,i,d,row.split(" "))}
println(r)}
```
ungolfed:
```
object Earthquake extends App {
def bowContains (h: Double, i: Double, x:Int, y:Int, d: Double) : Boolean = {
(x-h)*(x-h) + (y-i)*(y-i) <= d*d
}
import java.awt._
def affected (polygon: Polygon, x:Int, y:Int, h: Int, i: Int, d: Double, row: Array[String]) : Int = {
val w = row (0).toDouble
val j = row (1).toDouble
val population = row (2).toInt
if (polygon.contains (w, j) || bowContains (j, w, x, y, d) || bowContains (j, w, i, h, d))
population
else 0
}
val sc = new java.util.Scanner (System.in)
val line = sc.nextLine.split (" ")
val li = line.map (_.toDouble)
val ll = li.map (_.toInt)
val (x, h, y, i, d) = (ll (0), ll (2), ll (1), ll (3), li(4))
val xs = List (x, h)
val ys = List (y, i)
val polygon = new Polygon ((xs ::: xs.reverse).toArray, (ys.map (_ - ll(4)) ::: ys.reverse.map (_ + ll(4))).toArray, 4)
var res = 0
while (sc.hasNext) {
val row = sc.nextLine
println ("line: " + line)
res += affected (polygon, x, y, h, i, d, row.split (" "))
}
println (res)
}
```
] |
[Question]
[
## Challenge
>
> In this task you would be given an integer N
> (less than 10^5), output the [Farey
> sequence](http://en.wikipedia.org/wiki/Farey_sequence) of order N.
>
>
>
The input N is given in a single line,the inputs are terminated by EOF.
**Input**
```
4
3
1
2
```
**Output**
```
F4 = {0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1}
F3 = {0/1, 1/3, 1/2, 2/3, 1/1}
F1 = {0/1, 1/1}
F2 = {0/1, 1/2, 1/1}
```
**Constraints**
* The number of inputs would not exceed 10^6 values
* You can use any language of your choice
* Shortest solution wins!
[Answer]
## J, 96
```
('F',],' = {0/1',', 1/1}',~('r';'/')rplc~', ',"1":"0@(3 :'}./:~~.,(%~}:\)i.1x+y')&".);._2(1!:1)3
```
( `/:~~.,(%~}:\)i.>:x:y` gives the list; the rest is I/O and formatting (with bad style))
E.g:
```
4
3
1
2
F4 = {0/1, 1/4, 1/3, 1/2, 2/3, 3/4, 1/1}
F3 = {0/1, 1/3, 1/2, 2/3, 1/1}
F1 = {0/1, 1/1}
F2 = {0/1, 1/2, 1/1}
```
### Edits
* **(114 → 106)** Clearer appending `,`
* **(106 → 105)** Cap `[:` to At `@`
* **(105 → 101)** Delete superfluous `":` conversion
* **(101 → 99)** Use infix `\` for the list
* **(99 → 96)**
[Answer]
# Common Lisp, 156
```
(do((l()()))((not(set'n(read()()))))(dotimes(j n)(dotimes(i(1+ j))(push(/(1+ i
)(1+ j))l)))(format t"~&F~D = {0/1~{, ~A~}/1}"n(sort(delete-duplicates l)'<)))
```
(newlines not necessary)
Very brutal, but languages with native rationals are an invitation to that.
**Ungolfed with comments:**
```
; at each iteration:
(do ((l()())) ; - reset l to nil
((not (set 'n (read()())))) ; - read a term (nil for eof)
; assign it to n
; stop looping if nil
(dotimes (j n) ; for j in 0..n-1
(dotimes (i (1+ j)) ; for i in 0..j
(push (/ (1+ i) (1+ j)) l))) ; prepend i+1/j+1 to l
(format t "~&F~D = {0/1~{, ~A~}/1}" ; on a new line, including 0/1,
; forcing the format for 1
n ; print sequence index, and
(sort ; sorted sequence of
(delete-duplicates l) ; unique fractions
'<))) ; (in ascending order)
```
[Answer]
# Python, 186 Chars
```
import sys
p=sys.stdout.write
while 1:
a=0;b=c=x=1;d=y=N=input();p("F%d = {%d/%d, %d/%d"%(d,a,b,c,d))
while y-1:x=(b+N)/d*c-a;y=(b+N)/d*d-b;p(", %d/%d"%(x,y));a=c;c=x;b=d;d=y
p("}\n")
```
[Answer]
# J, 156 135 117 112
```
d=:3 :0
wd;'F';(":y);' = {';(}.,(', ';2|.'/';|.)"1(<@":)"0(2)x:/:~~.,(-.@>*%)"0/~i.x:>:y),<'}'
)
d@".;._2(1!:1)3
```
j602 or similar (`wd`). Input on stdin, output on stdout.
Still puzzling over how to golf the output code, which is 100 characters or so.
Edit: (156->135) Tacit->explicit for long monadic verb chains, less braindead list generation
Edit: (135->117) Found [raze](http://www.jsoftware.com/help/dictionary/d330.htm). Took me long enough. Switched string handling around.
Edit: (117->112) Slightly less braindead way to exclude fractions above 1. Unnecessary open.
[Answer]
## Golfscript (101)
```
~:c[,{){.}c(*}%.c/zip{+}*]zip{~{.@\%.}do;1=},{~<},{~\10c?*\/}${'/'*}%', '*'F'c`+' = {0/1, '+\', 1/1}'
```
[Answer]
# Ruby, 110 108 102 97 94 92 91 89
```
#!ruby -lp
$_="F#$_ = {#{a=[];1.upto(eval$_){|d|a|=(0..d).map{|n|n.quo d}};a.sort*', '}}"
```
[Answer]
# [Haskell](https://www.haskell.org/), 145 bytes
```
f(!)(%)n|p<-product[1..n]='F':n!" = {"++unwords[i%g!"/"++p%g![",}"!!(i%p)]|i<-[0..p],g<-[gcd i p],p<=n*g]
m@main=readLn>>=putStrLn.f shows div>>m
```
[Try it online!](https://tio.run/##Dci7DoMgAEDRna8AEqNWpbWvoRHSqVO3jsbBiCKpIgGtQ@23U7Zzb1/bdzsMznURiqMgVpsuMm0mvjRzmROiKho@wptCGFL4xUmyqHUy3JYyEAjv/dAeJU5/GKFIBjquNllk5YEQXaXCSzQcSuhDF1TtRAXG@1hLRU1b86dijOplfs3mqUgHbT@tFnL5YWx0LgdHcAJncAHXPw "Haskell – Try It Online")
This reduces all of \$\left\{\frac{0}{n!}, \frac{1}{n!}, \dots, \frac{n!}{n!}\right\}\$ and selects the ones with denominator \$\leq n\$.
(The byte count went up a little again because I noticed the problem asks to handle multiple lines of input.)
The other Haskell answer is missing some imports and is missing `1/1` in the output. It also doesn't take multiple lines of input. When fixed, it comes out to 188 bytes:
```
import GHC.Real
import Data.List
f n="F"++show n++" = {"++(intercalate", ".("0/1":).map(\(i:%d)->show i++"/"++show d).sort.nub$[i%d|d<-[1..n],i<-[1..d]])++"}"
m@main=readLn>>=putStrLn.f>>m
```
[Answer]
# Haskell, 148
```
f n="F"++show n++" = {"++(intercalate", ".("0/1":).map(\(i:%d)->show i++"/"++show d).sort.nub$[i%d|d<-[1..n],i<-[1..d-1]])++"}"
main=interact$f.read
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 55 bytes
```
mλ:'F+s¹+" = "σ"1]""1/1}"σ"[0""{0/1"sOutfεmF/π2ŀ→)fImi¶
```
[Try it online!](https://tio.run/##yygtzv7/P/fcbit1N@3iQzu1lRRsFZTONysZxiopGeob1oLY0QZKStUG@oZKxf6lJWnntua66Z9vMDra8KhtkmaaZ27moW3///834TLmMuQyAgA "Husk – Try It Online")
It was interesting messing with strings in Husk.
This gives the exact required output for the given test case.
There's a strange husk-ism in the `mi¶` function that gives intermediate 0's in the output. Hence, those are filtered out. [Here's an explanation from Zgarb.](https://chat.stackexchange.com/transcript/message/55983590#55983590)
## Explanation
```
mλ:'F+s¹+" = "σ"1]""1/1}"σ"[0""{0/1"sOutfεmF/π2ŀ→)fImi¶
¶ split input on newlines
mi map to integers
fI filter out zeroes
mλ ) map each number through this function:
ŀ→ range (0..n)
π2 all possible pairs
mF/ map each to it's fraction
fε keep elements ≤ 1
t remove first value (Any)
Ou uniquify, sort ascending
s convert to string
σ"[0""{0/1" change 0 → 0/1
σ"1]""1/1}" change 1 → 1/1
+" = " add an equal sign
:'F+s¹ prepend "F{N}"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 44 bytes
```
ƓµŻœċ2g/’$Ðḟ÷/Þj€”/j⁾, ,⁸Ø<,y“F> = {<}”Ṅ
Ç1¿
```
[Try it online!](https://tio.run/##AVoApf9qZWxsef//xpPCtcW7xZPEizJnL@KAmSTDkOG4n8O3L8OeauKCrOKAnS9q4oG@LCAs4oG4w5g8LHnigJxGPiA9IHs8feKAneG5hArDhzHCv///NAozCjEKMv8 "Jelly – Try It Online")
Could probably be improved if someone told me how to read and write multiline input properly in Jelly. I couldn't find any documentation on it, so I just have a while(true) loop that errors out when it reaches EOF.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 73 bytes
```
'Fqi:T" = {"[[T1]Y,{_'\*',+\W%@_@_2$+2%Ta.+:/@f*\.-_1=T)<@W%\}g'\*\;]S*'}
```
[Try it online!](https://tio.run/##S85KzP3/X92tMNMqREnBVqFaKTo6xDA2Uqc6Xj1GS11HOyZc1SHeId5IRdtINSRRT9tK3yFNK0ZPN97QNkTTxiFcNaY2Hagyxjo2WEu99v9/CwA "CJam – Try It Online")
Uses an algorithm to generate the terms in traditional order. A lot of maps and vector functions were used here. If anyone wants a write-up then I'll make one, unless I can figure out a better algorithm.
[Answer]
# [Python 3](https://docs.python.org/3/), 89 bytes
```
lambda n:[*zip(*sorted({j/i:(j,i)for i in range(n,0,-1)for j in range(i+1)}.items()))][1]
```
[Try it online!](https://tio.run/##RcixDoMgEADQX2G8s9SW6GTSL0EHGkGP6EGQRY3fjkmXvvHFPc@Bm@I@fVnM@h2N4E5XB0WotpCyHeH0L@rAS0IXkiBBLJLhyQLLt3yq3/r/0kPhVVO26waIOGg1lJiIMzhoEcsN "Python 3 – Try It Online")
Basically generating all possible fractions and then using a dictionary comprehension to filter out the duplicates.
---
# [Python 3](https://docs.python.org/3/), 142 bytes
```
while 1:n=input();print('F%s = {'%n+', '.join([*zip(*sorted({j/i:f'{j}/{i}'for i in range(int(n),0,-1)for j in range(i+1)}.items()))][1])+'}')
```
[Try it online!](https://tio.run/##TcyxDoIwEADQna/oQq4nCFacMKz@BGEwscg1em1KjdGm317D5vyS5z5hsdzl/F7ooYXqeSB2ryDx7DxxkHApVzGICCVXUAtojCWW4@5LTu5W64O@yWha6meIJrWREszWCxLEwl/5ruW2MNaHeq9wI/NHlcLUUNDPVSLiNKoJK0iAOZ@KrlDF8Qc "Python 3 – Try It Online")
Abiding by all of the I/O requirements
[Answer]
# Mathematica ~~13~~ 78 bytes
```
Column[Row@{"F",#," = ",FareySequence[ToExpression@#]}&/@StringSplit[#,"\n"]]&
```
---
**Example**
```
Column[Row@{#," = ",FareySequence[ToExpression@#]}&/@StringSplit[#,"\n"]]&["5\n4\n3"]
```
[](https://i.stack.imgur.com/7JjSX.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 40 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|εÝ2.Æ2Å1ª.¡`/}€нΣ`/}'/ý„, ýy"Fÿ = {ÿ}",
```
[Try it online.](https://tio.run/##AVMArP9vc2FiaWX//3zOtcOdMi7DhjLDhTHCqi7CoWAvfeKCrNC9zqNgL30nL8O94oCeLCDDvXkiRsO/ID0ge8O/fSIs//80CjMKMQoy/y0tbm8tbGF6eQ)
**Explanation:**
```
| # Get all input-lines as a list
ε # Map over each input-integer:
Ý # Pop and push a list in the range [0,n]
2.Æ # Get all 2-element combinations of this list
2Å1ª # Append pair [1,1]
.¡ # Group the pairs by:
` # Pop and push both values separated to the stack
/ # Divide them
}€ # After the group-by: map over each group
н # Only leave the first pair of each group
Σ } # Then sort the pairs by:
`/ # Similar as above: dump and divide
'/ý '# Then join each inner pair with "/"-delimiter
„, ý # Join these strings with ", "-delimiter
y # Push the current map-integer
"Fÿ = {ÿ}" # Push this string, where the `ÿ` are automatically filled with
# the integer and formatted list
, # Pop and output it with trailing newline
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~18~~ 38 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Stupid old challenges and their stupid & unnecessarily strict I/O requirements costing me 20 bytes!
```
N£"F{X} = \{{Xõ c_ô+'/+ZÃü!xO mÎqSi,}}
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=TqMiRntYfSA9IFx7e1j1IGNf9CsnLytaw/wheE8gbc5xU2ksfX0&input=NAozCjEKMg)
```
N£"F{X} = \{{Xõ c_ô+'/+ZÃü!xO mÎqSi,}}
N :Array of all inputs
£ :Map each X
"F = \{ } : Build a string
{X} : Interpolate X
{ : Interpolate
Xõ : Range [1,X]
c : Flat map by
_ : Passing each Z through the following function
ô : Range [0,Z]
+'/+Z : Append "/" followed by Z to each
à : End map
ü : Group & sort by
!xO : Evaluating each as JavaScript
m : Map
Î : First element
q : Join with
S : Space
i, : Prepend comma
} : End interpolation
:Implicit output joined with new lines
```
] |
[Question]
[
Recently [I asked](https://codegolf.stackexchange.com/q/264316/56656) for tips on improving some code-golf of mine. The code was *supposed* to output every third value of the Fibonacci sequence starting with 2:
```
2,8,34,144,610,2584,10946,46368,196418,832040
```
However, I made a mistake in deriving my formula, and my code output a different sequence which is accurate for the first couple terms and then begins to diverge:
```
2,8,34,140,578,2384,9834,40564,167322,690184
```
My sequence is defined by:
$$
f(0) = 0 \\
$$
$$
f(1) = 2 \\
$$
$$
f(n) =\displaystyle 2 + 3f(n-1) + 4f(n-2) + 2\sum\_{0}^{n-3}f\\
$$
or in terms of my original Haskell code:
```
z=zipWith(+)
g=z((*2)<$>0:0:g)$z(0:g)$(*2)<$>scanl(+)1g
```
Your task is to implement a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") of integers, which has my incorrect sequence as every third value. The other values can be whatever you want them to be, it simply must have the above sequence as every third value. The required subsequence can begin at the 0th, 1st, or 2nd index, and may begin with either 0 or 2 whichever you please.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your program as measured in bytes.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes
```
{-2/z,x,y}/[;0;2;8] -3!
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6rWNdKv0qnQqazVj7Y2sDaytohV0DVW5OJKU1dQNDPgAgCjLQgP)
Given `n`, returns the `n`th term (0-indexed) of the given sequence triplicated, i.e. `0, 0, 0, 2, 2, 2, 8, 8, 8, 34, 34, 34, ...`. To start with 2 instead, change `0;2;8` to `2;8;34` or replace the space with `1+` for +1 byte.
The OP's sequence can be simplified as follows:
$$
\begin{aligned}
a\_n &= a\_{n-1} + 2a\_{n-2} + 2\sum\_{k=0}^{n-1}a\_k + 2 \\
a\_{n-1} &= a\_{n-2} + 2a\_{n-3} + 2\sum\_{k=0}^{n-2}a\_k + 2 \\
a\_n - a\_{n-1} &= a\_{n-1} + 2a\_{n-2} - a\_{n-2} - 2a\_{n-3} + 2a\_{n-1} \\
a\_n &= 4a\_{n-1} + a\_{n-2} - 2a\_{n-3}
\end{aligned}
$$
Now we want to find a sequence whose every third term satisfies the above, i.e. the original sequence satisfies
$$
a\_n = 4a\_{n-3} + a\_{n-6} - 2a\_{n-9}
$$
but it turns out that this recurrence is irreducible, at least in integers. So the code simply evaluates the "every third term" sequence at index `floor(n/3)`.
[Answer]
# [Python](https://www.python.org), 51 bytes
```
f=lambda n:n>3and 4*f(n-3)+f(n-6)-2*f(n-9)or(n>0)*2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3jdNscxJzk1ISFfKs8uyME_NSFEy00jTydI01tUGUmaauEZhvqZlfpJFnZ6CpZQTVapWWX6SQqZCZp1CUmJeeqmGoY2yqacWloFBQlJlXoqFkp6SQmaaQqWpsa2ugkJpTnKqgpKCkk6aRqakJMQHmCAA)
Test harness borrowed from @bsoelch.
### How?
Taking the difference f(n)-f(n-3) gets rid of the sum.
[Answer]
# [sclin](https://github.com/molarmanful/sclin), 39 bytes
```
[0 2 8]"dup [2_1 4] * +/ +`1dp"itr flat
```
[Try it here!](https://replit.com/@molarmanful/try-sclin) Outputs an infinite list:
$$
0,2,8,2,8,34,8,34,140,34,140,578,140,578,2384,...
$$
For testing purposes:
```
; 100tk >A
[0 2 8]"dup [2_1 4] * +/ +`1dp"itr flat
```
## Explanation
Prettified code:
```
[0 2 8] ( dup [2_ 1 4] * +/ +` 1dp ) itr flat
```
Based on a simplified variant of the original equation (first found by @loopy walt and @Bubbler):
$$
f(n)=4f(n-1)+f(n-2)−2f(n-3)
$$
* `[0 2 8] (...) itr` creates an infinite series of modifications starting from 0, 2, 8
+ `dup [2_1 4] *` vectorized-multiply each term by -2, 1, 4
+ `+/` sum
+ `+` 1dp` append as new term, discard oldest term
* `flat` flatten, which conveniently also creates a 2-term gap
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
F²⊞υι≔E²ιηFN⊞η⁻⌈⊞OυΣ…⮌υ²↨¹E✂⮌η⁵Lη³×κ§υ׳λI⌈η
```
[Try it online!](https://tio.run/##PY67DsIwDEV3vsKjI4WBIgbEBJ0q8RLwA6EYEpGmVR4Ivj44gLDkwedeX7vVyre9sjlfew9YCdinoDFJMGIxWoZgbg43asCqEAma6cfZuCHFberO5FH8trSEjXEp8MLTdKnDQncDeRV7XzKPzOpXa6nW/YAHepAPhIlzK8ElYaV4nnAMXzxa09LfpFmdSViTu0X9mabcJ9NRwLuEZWzchZ7lyJdNJVjxrcVo742LWKsQ/6/pIuRczfP4Yd8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs \$ f(n) \$ where \$ f(2)=2 \$. Explanation:
```
F²⊞υι
```
Start with the first two terms of the Fibonacci sequence (\$ 0 \$-indexed).
```
≔E²ιη
```
Start with the first two terms of the Wheat Wizard sequence (\$ 0 \$-indexed).
```
FN
```
Calculate \$ n \$ new terms.
```
⊞η⁻⌈⊞OυΣ…⮌υ²↨¹E✂⮌η⁵Lη³×κ§υ׳λ
```
Calculate \$ F(n) \$ and \$ f(n)=F(n)-\sum\_{i=0}^{\lfloor(n-5)/3\rfloor}F(3i)f(n-5-3i) \$.
```
I⌈η
```
Output the \$ n \$th additional term. This results in the following sequence:
$$ 1, 2, 3, 5, 8, 13, 21, 34, 53, 87, 140, 219, 359, 578, 903, 1481, 2384, 3725, 6109, 9834, 15365, 25199, 40564, 63379, 103943, 167322, 261431, 428753, 690184, $$
29 bytes for the boring version with all the values triplicated:
```
F³⊞υ²FN⊞υΣ×✂⮌υ²χ³⟦⁴¦¹±²⟧I§υ±³
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6Fjf70_KLFDSMNRUCSoszNEp1FIw0rbnAYp55BaUlfqW5SalFGpoI-eDSXI2QzNzUYo3gnMzkVI2g1LLUouJUjVJNoF4dBUMDHQVjIDPaBMjWUfBLTU8sSdUw0ozV1AQaHFCUmVei4ZxYXKLhWOKZl5JaATISqsgYpGRJcVJyMdRxy6OVdMtylGIXGVlCBAA "Charcoal - Attempt This Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
F³⊞υ²
```
Start with `3` `2`s.
```
FN
```
Generate `n` more terms.
```
⊞υΣ×✂⮌υ²χ³⟦⁴¦¹±²⟧
```
Calculate the next term using @loopywalt/@Bubbler's formula.
```
I§υ±³
```
Output the `n`th term.
[Answer]
# [Python](https://www.python.org), ~~96~~ ~~72~~ 66 bytes
*-6 bytes, thanks to @xnor*
```
f=lambda n:n>0and 2+3*f(n-3)+4*f(n-6)+2*sum(map(f,range(0,n-8,3)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEADvvmIJCEmbQGyslEB78CeRZjXQbEuaHnyLl170T_5GUHubwzDM4zXd822kdX0uGVXzPmM7uHjpHZClTjvqoSpNgZyUEeXxCydRVsW8RB7dxFEmR1fPtSTVSCOE-JcsjgkCBIKfcJCmFnYHMKVAmbOOQUAIe9O2Gvwwe2DAJPKwFbanDw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2λ‚āR*λ·«OÌ}€Ð
```
Outputs the infinite sequence starting with \$2\$, where all values occur three times in a row.
[Try it online.](https://tio.run/##ASMA3P9vc2FiaWX//zLOu@KAmsSBUirOu8K3wqtPw4x94oKsw5D//w)
**Explanation:**
```
λ # Start a recursive environment,
# to output the infinite sequence
2 # Starting with a(0)=2
# Where every following a(n) is calculated as:
‚ # Pair the last two implicit values together: [a(n-2),a(n-1)]
# (uses a(n-2)=0 in the first iteration: [0,2])
āR # Push pair [2,1]
* # Multiply the values at the same positions: [2*a(n-2),a(n-1)]
λ # Push a list of all terms thus far: [a(0),a(1),...,a(n-1)]
· # Double each: [2*a(0),2*a(1),...,2*a(n-1)]
« # Append the lists together: [2*a(n-2),a(n-1),2*a(0),2*a(1),...,2*a(n-1)]
O # Take its sum
Ì # And increase it by 2
} # After the recursive sequence has been generated:
€Ð # Triplicate each value in place
# (after which the infinite list is output implicitly as result)
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
L&b+2su+@G1G3*2_%3yMb
```
[Try it online!](https://tio.run/##K6gsyfj/30ctSduouFTbwd3Q3VjLKF7VuNI36X92mLFhpd9/AA "Pyth – Try It Online")
Defines a function `y`, which when given `N` returns the Nth term in the sequence
$$
0, 2, 2, 2, 8, 8, 8, 34, 34, 34, 140, 140, 140, 578, 578, 578, 2384, 2384, 2384, \dots
$$
### Explanation
```
L # define y(b)
&b # short circuiting and, if b==0: return 0
yMb # map range(b) over y
%3 # take every third element
_ # reverse the list
*2 # and double it
u 3 # reduce range(3) over lambda G,H with the list as the starting value
+@G1G # add the second element of G to the beginning of G
s # sum
+2 # add 2
```
[Answer]
# [Haskell](https://www.haskell.org/), 76 bytes
```
z=zipWith(+)
g=z((*2)<$>0:0:g)$z(0:g)$(*2)<$>scanl(+)1g
f=[x|x<-g,_<-[1..3]]
```
I don't really know Haskell that well, but I do enjoy loopholes. This is a direct ripoff of the code in the question, with each element repeated three times. [Direct link for good measure](https://codegolf.stackexchange.com/questions/264408/give-the-fools-fibonacci-sequence).
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8q2KrMgPLMkQ0NbkyvdtkpDQ8tI00bFzsDKwCpdU6VKA0xBBYuTE/NygAoN07nSbKMraipsdNN14m10ow319IxjY//nJmbmKdgqFBRl5pUoqCiUJGanKhgbKKT9BwA "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 62 bytes
```
b,c;main(a){for(a++;;)printf("0,0,%u,",a=-2*c+(c=b)+4*(b=a));}
```
[Try it online!](https://tio.run/##BcHBCoAgDADQfxGCzU2Q6Db8mDkwPGQhdYq@fb1naTdzr2xyaB@g@LZzghKJ4DX7uBuEzJmXhwNrSWs0AisVaYtQiyLK5/4D "C (gcc) – Try It Online")
New approach to a complete program, using the f(n)=4*f(n-1)+f(n-2)-2*f(n-3) formula used in other solutions.
It starts outputting the sequence at 8, not 0 or 2 as the challenge states.
I feel like this could be improved upon even further.
# [C (gcc)](https://gcc.gnu.org/), ~~74~~ ~~69~~ ~~65~~ 63 bytes
```
a,b,t;main(c){for(;t=b+(c+=b);printf("0,0,%u,",a=3*a+2*t))b=a;}
```
[Try it online!](https://tio.run/##BcHBCoAgDADQfxGCTRdIHWUfsw0MD1mInaJvX@/Zepi5CynNckrrYPjWa0CZrAkssWK5R@uzQsiUaXkokPAeJW1xIipL@dx/ "C (gcc) – Try It Online")
After many reworks, this is what I came up with from following the same algorithm to its conclusion.
This implementation
* ~~Depends on undefined behaviour (sequencing)~~
* Is a complete program, not a fragment.
* And computes the sequence explicitly, outputting zeros on all but every third number.
It may be shorter if we loop once per number output, instead of once every three numbers.
] |
[Question]
[
This is a [quine](/questions/tagged/quine "show questions tagged 'quine'") challenge related to [Write the shortest self-identifying program (a quine variant)](https://codegolf.stackexchange.com/q/11370/84844)
Write a function or a full program that compares lexicographically its source code and input, that is, output three distinct values of your choice telling if `input` / `source code` is *Bigger*, *Equal* or *Less* than `source code` / `input`.
# Specifications
>
> A [Lexicographic order](https://en.wikipedia.org/wiki/Lexicographic_order?wprov=sfla1) is a *generalization of the alphabetical order of dictionaries to sequences of elements of an ordered set [Wikipedia].*
>
>
>
In short it works just like dictionaries:
To determine if string *A* is greater than a string *B*
* we compare the order of each first character (from the left).
The string with bigger order element is greater.
* If first character of each are equal we compare the second and so on.
* If one string ends then that string is smaller.
* If *A = B* they are equal.
The ordered set is the natural character encoding of the language you choose and your submission has to work correctly with it.
For example UTF or ASCII.
# Examples
We use *Less, Eq and Greater* as output and ASCII as alphabet for clarity and simplicity.
source: "A"
input : "B"
output : Greater (input <=> source)
source: "a\_X"
input : "A\_x"
output : Greater (source <=> input)
source: "A,X"
input : "A,x"
output : Less (source <=> input)
source: "#!\*"
input : " "
output : Greater (source <=> input)
source: "x!y"
input : "x!y"
output : Eq (source <=> input)
# Rules
* Standard [quine](/questions/tagged/quine "show questions tagged 'quine'") rules apply and specifically reading your own source code is not allowed.
* 0-length answers are disallowed.
* input: a sequence of characters in any convenient format (string, list or array of characters, codepoints).
You can handle empty input but it is not required.
* output:
Three distinct values of your choice meaning less equal and greater.
You are free to choose to tell if input is <=> than source or if source is <=> than input, just be consistent and specify it.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), all usual rules apply.
[Sandbox](https://codegolf.meta.stackexchange.com/a/24665/84844)
[Answer]
# [R](https://www.r-project.org), ~~92~~ 90 bytes
```
'->T;f=\\(a,b=paste(sQuote(T),T))(a>=b)+(a>b)' ->T;f=\(a,b=paste(sQuote(T),T))(a>=b)+(a>b)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFN68y8sszizKScVI3gymK94tSSnPzkRCAvObEkNT2_qFLBVkHJxzne0cdHSUcBIgcSclbS1FxaWpKma3EzSl3XLsQ6zTYmRiNRJ8m2ILG4JFWjOLA0H0iFaOqEaGpqJNrZJmlqA6kkTXUFqGpiFENteJGmoZSYlKykyQVkkGcbUaqTchKBiObWIFkAZqorqYNFlKD-XbAAQgMA)
Outputs `2` if the input is greater than the code, `1` if they're equal and `0` otherwise.
Simple modification of [@Dominic van Essen's `R` quine](https://codegolf.stackexchange.com/a/209032/55372).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-10 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334)! (Using `M` (-8) and using a full program (-2)).
```
“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM
```
Expects the code using characters from the [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) from STDIN and prints `2` if equal to the code, `0` if less, or `1` if more.
\* without the deprecated, but supported, alternative characters of `ụ` and `ṿ`, or the newline alternative to `¶`.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZ65xccHiGV@ajjeuAyPdRw1xMQVLUAgA "Jelly – Try It Online")**
### How?
```
“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM - Main Link: no arguments
“Ṿ;,ɠØJiⱮⱮM” - "Ṿ;,ɠØJiⱮⱮM"
Ṿ - unevaluate -> "“Ṿ;$,⁸ØJiⱮⱮṢƑ+EƊ”"
; - concatenate -> the source code = "“Ṿ;,ɠØJiⱮⱮM”Ṿ;,ɠØJiⱮⱮM"
ɠ - read a line from STDIN = I
, - pair -> [source, I]
ØJ - Jelly's code-page
iⱮⱮ - index of each character in each of [source, I]
M - maximal, 1-indexed, indices:
source < I -> [2]
source = I -> [1,2]
source > I -> [1]
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~28~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"34çì·‚Ð{QsË+"34çì·‚Ð{QsË+
```
-2 bytes by switching to the legacy version of 05AB1E, where double on string works
Outputs `0` if the source code is smaller; `1` if the input is smaller; and `2` if both are equal.
[Try it online](https://tio.run/##MzBNTDJM/f9fydjk8PLDaw5tf9Qw6/CE6sDiw93a2MSIVwkA) or [verify a few example test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3lfyVjk8PLD685tP1Rw6zDE6oDiw93a2MT@69DtFIuxaTUtPyiVK7EtJLUIgA).
**Explanation:**
It's based on this base quine: [`"34çì·"34çì·`](https://tio.run/##MzBNTDJM/f9fydjk8PLDaw5thzP@/wcA).
```
"34çì·‚Ð{QsË+" # Push string "34çì·‚Ð{QsË+"
34ç # Push 34, converted to a character: '"'
ì # Prepend it to the string: '"34çì·‚Ð{QsË+'
· # Double it: '"34çì·‚Ð{QsË+"34çì·‚Ð{QsË+'
‚ # Pair it with the (implicit) input
Ð # Triplicate it
{ # (Lexicographically) sort the pair
Q # Check if the top two pairs are the same
s # Swap to get the remaining pair
Ë # Check if both values are the same
+ # Add the two checks together
# (after which the result is output implicitly)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 31 bytes
```
f=(a)->if(a<s=Str("f="f),2,s<a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboW-9NsNRI1de0y0zQSbYptg0uKNJTSbJXSNHWMdIptEjUhqm6-TiwoyKnUSFTQtVMoKMrMKwEylUAcJQWgRk1NHYVopcSkZCUdBSUQxjQ0BigWgzA2KScRiIhSSowiqBpH4gyy0cWjKBbqZVgAAQA)
Outputs `1` if the input is greater than the code, `0` if they're equal and `2` otherwise.
---
## [PARI/GP](https://pari.math.u-bordeaux.fr), cheating, 28 bytes
```
(a)->if(a<s=Str(self),2,s<a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWezQSNXXtMtM0Em2KbYNLijSKU3PSNHWMdIptEjUhSm5eSiwoyKnUSFTQtVMoKMrMKwEylUAcJQWgPk1NHYVopcSkZCUdBSUQxmdiUk4iEBFSRUAeLO1IULuNLi75WKjPFiyA0AA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 85 bytes
```
->a{z,m,w='->a{z,m,w=',',',';a<=>[z,z,m,m,m,w,w]*39.chr}';a<=>[z,z,m,m,m,w,w]*39.chr}
```
[Try it online!](https://tio.run/##KypNqvxfaGtj4@rnoldcUpRZ8F/XLrG6SidXp9xWHYmpA4bWiTa2dtFVOiBBECzXKY/VMrbUS84oqsUr@R9oPleabWpZYo5CIVeBQlo01PAc9VgwtzAWWTRPPfY/AA "Ruby – Try It Online")
### Explanation:
Not very golfy, I know.
I could take the answer to the linked question and replace '==' with '<=>' for 29 bytes, but I wanted to try something different, and opted not to use `eval`.
There is a lot of room for improvement, but I like the way it turned out.
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
compare$s++show s;s="compare$s++show s;s="
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzk/tyCxKFWlWFu7OCO/XKHYuthWCavg/9zEzDwFW4WUfC6FgqLMvBIFFYU0rEpjcIgqoWhE4SWh8FKU/ucBLbMF8lOLEpNLVECG6GlgmKoJclcu0Sr/JaflJKYX/9dNLigAAA "Haskell – Try It Online")
*compare* program Vs input.
Outputs *Ord* value :
EQ equal
GT program > input
LT otherwise
[Answer]
# JavaScript, 23 bytes
```
f=s=>s<(F='f='+f)?0:F<s
```
[Try it online!](https://tio.run/##ZYxBDsIgFET3PQW7D6lC41JL3fUcJQgVg2AK6cp4daQ2aRrcTebNm4eYRZCTecWj8zeVpHchIpkj4mhImgfehRb3HDSHWpNrc@7bkAYaJ/PE5FIxtio679UsLF7c3O9ztUy8VdT68ddRq9wY7xmVpFxDCwekVylYI9XeZ6d3Q0jxAnwz/lC3oRo@kHH6Ag "JavaScript (Node.js) – Try It Online")
Outputs `0` if input less than source, `false` for equal, and `true` for greater than.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 14 bytes
```
`I~>∇≥+`I~>∇≥+
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYEl+PuKIh+KJpStgSX4+4oiH4omlKyIsIiIsImBJfj7iiIfiiaUrYEl+PuKIh+KJpSsiXQ==)
prints `0` for smaller, `1` for equals and `2` for greater
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~74~~ 49 bytes
```
p [*$<]*''<=><<'2'*2+?2
p [*$<]*''<=><<'2'*2+?2
2
```
[Try it online!](https://tio.run/##KypNqvz/v0AhWkvFJlZLXd3G1s7GRt1IXctI296IC5e4ERlaAA "Ruby – Try It Online")
~~Note trailing newline~~
Adapted from the typical Ruby quine. Outputs `0` if input is the same as source, and `1` or `-1` if it is different. Thanks to Jo King for suggesting the use of `[*$<]*''` to capture input.
[Answer]
# [Julia](http://julialang.org/), 70 bytes
```
(q=:(show((ARGS[] > (Q = "(q=:($(q)))|>eval")) - (ARGS[] < Q))))|>eval
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/X6PQ1kqjOCO/XEPDMcg9ODpWwU5BI1DBVkEJLKOiUaipqVljl1qWmKOkqamgqwBTZqMQqAmX@k8tgwA "Julia 1.0 – Try It Online")
takes input as a single command line argument, and prints `0` for *Equal*, `1` for *Greater* and `-1` for *Less*
Based on the following quine, which is explained in this [answer by Dennis](https://codegolf.stackexchange.com/a/92455/98541) (adapted for Julia 1.0):
`(q=:(print("(q=:($(q)))|>eval")))|>eval` [Try it online!](https://tio.run/##yyrNyUw0rPj/X6PQ1kqjoCgzr0RDCcxW0SjU1NSssUstS8xRgrP@//8PAA "Julia 1.0 – Try It Online")
Sadly, all the spaces are neccessary, since the code is stored as an AST, and converting it to a string will put all the spaces back. Also, defining a function or using a macro don't work because of the lengthy comments that are automatically added in the AST
] |
[Question]
[
This challenge is inspired by the game [No More Jockeys](https://www.youtube.com/channel/UCS8aP7SiA_eTfvT_Gruxzsw).
The input is a list of tuples of natural numbers (potentially including 0), in some appropriate input format. Starting with player 0 and alternating with player 1, each player chooses some number which is contained within at least one remaining tuple, and all tuples containing that number will be removed from the list. The first player who has no possible moves loses.
Your challenge is to implement a function to calculate the minimax value of a given input. Return a truthy value if it is player 1 to win given optimal play by both players, and a falsy value if it is player 0 to win. The converse is also acceptable.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
## Test Cases
```
((), (0, 1, 3), (1,)) -> 0
() -> 1
((0,), (1, 3), (2,)) -> 0
((), (0, 1), (0, 1, 2), (0, 2), (1,)) -> 1
((0,), (0, 1, 3), (0, 3), (2,)) -> 0
((), (0, 1), (0, 2, 3), (1,), (2,), (3,)) -> 1
((0, 1), (1, 2), (2, 3), (3,)) -> 0
((0, 2), (1,), (1, 3), (3,), (4,)) -> 1
((0, 2, 3), (0, 3), (1,), (2,), (2, 3)) -> 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes
```
f=lambda a:0in(f([x for x in a if{r}-{*x}])for r in sum(a,()))
```
[Try it online!](https://tio.run/##hY8/T8MwEMXn5lOcMt2Bi/KHKahsDKyoG2JwqKNaSlLLcSCo6mcPdkywy8Ji@95797uz@jLHU1/Oc7NreVcfOPAqkz02@DpBc9IwgeyBg2zO@rI930yXN3KydvIwdsgZEtFsYAd58nmUrYC9HkWVbDiD2qodVyg@eMtshxoN0t2gWmkwhe0jpETJRmnZ23ovBpMyMPQABm4dbnWeXWNlPR7ST5MS70YcnFwH@UUMY7tkG@QBTjMiMcCMQc6gdM@cEbkVsgSXO0/Q2t7xiSIkfpsDpPh5FjEsQKJJ2f@8Iizlg/Ysr5g@us5d82WEjHaJPlEu1f01q/izWTx28Tz0Gw "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), 61 bytes
```
f=lambda a:0in(f(filter({y}.__sub__,a))for x in a for y in x)
```
[Try it online!](https://tio.run/##hY8xb4MwEIXn8itOTGfVjcB0Ikq3Dl2r7Mg0RrHkEAuOBlT1t1MbCjhdupjj3vP3nu1A52stxrE6GHkpTxJknugaK6y0IdXg1/C9K4q2K4uCS8aqawM96Bok@HHwY89GggOk0e2sjYJj06k8epAcSre9SIvqUxoOjbwVurYdIdu11mjCGJ5eIGbMmZ2TOmsUtoqwZ7DlONU2uiaIj6qlmAPtgeDR5y3Cm6fmTpLr6rW36oPUyW/Ldfuu2s5MzgpX8IjIOGDCIeWQ@THljPlqSYTTN43QybMyO8TmWC9vEPE7ihC2QYKk5H@e2ErNRndmd8zZuuQu/ixABl2CR2TT3/M9S/xpFsZO2gz9AQ "Python 2 – Try It Online")
-5 bytes thanks to Unrelated String
-6 bytes thanks to dingledooper
-1 byte if we use Python 2 thanks to dingledooper
-2 bytes thanks to xnor
Outputs `True` for player 0 winning and `False` or `()` for player 1 winning (`()` is an empty tuple in Python, which is a falsey value in the language)
[Answer]
# JavaScript (ES10), 54 bytes
Returns a Boolean value.
```
f=a=>!a.flat().some(v=>f(a.filter(b=>!b.includes(v))))
```
[Try it online!](https://tio.run/##hZFNDoMgEIX3nmK6w8QiancN7noKwwIVWxsqjVqvbxH/o7WzmEyYx@Mb5skbXiVl/q7PhUpF22aU0/DEcSZ5jWxcqZdADQ0zpI9yWYsSxbof47xI5CcVFWpsHe01sgCiiDkQEQc8B4Ku9BhsQzdcF0ivh//R6z2jJ8Z1cPfZgZ6seGYufyj9iW/jvxiA7Dx14O9Pc5s7OgVs7T9oR5DxQvDDfwZdzG3She3@z8xANiymo/XQ@zMLZ6q88eSBONAQElVUSgos1R3pdXdb/QI "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f a=any(not.f.(`filter`a).notElem)$a>>=id
```
[Try it online!](https://tio.run/##fY4xD4IwFIT/ysU4tBEJVCcT2BxMNA6OtdEmQiBCJVAj/nosFalxcODl9e67e2SyuSZF0XUpZCTVk6ib9lOfnNO80El9ltQ3yrpISjqVcRzll66UuUIEUifyslVYrbDZg3O@UVoIQWEolLLanUCO7TxGddcHXRtyiia7PdBiNsMExpn0m9VIipbSzrQIDzzwEHpY9Gso@tl/PLDvQWdWH2mXYsPKXPqd/CoN/paw8bRFzFgMNQPzufIBnc3GXDh6Ziwd8PMH7oZ1hHgB "Haskell – Try It Online")
*Was* the same length as using nested list comprehensions, until I realized `notElem` exists, and is much shorter than `(not.).elem`. Still feels very golfable...
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
(0=1#.]$:@#~1-~.@;e.&>/])`1:@.(''-:;)
```
[Try it online!](https://tio.run/##fY7BCgIhEIbv@xRDG6mQ5mgnxRCCTp26LxSxy9KlN9hXt9EN0kug/@jM//36ShvFJggOGOxBg6MtFZxv10viOmCvhq2L/YJyUdGPanc6DOKOLirOmHReJNF143N@ExdgAsY814Bghce1j6X/cLVL@2zxYGoLoTTGImByIcEWK9Gkf1iTh3Qi2DZwbpbg4rA1vj71/RStYwsWQP9y6d6lDw "J – Try It Online")
Inspired by Arnauld's answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
iÐḟⱮẎ߀0e
```
[Try it online!](https://tio.run/##y0rNyan8/z/z8ISHO@Y/2rju4a6@w/MfNa0xSP1/uB1IR/7/r6GhqaOgYaCjYKijYAxiGupoauoABTWAghA@RNwILA5XjdBlBGUaIXRDtSKZaoDXFCOE3RA1QNIYZhJEFcwimFKEtBFCpyFCEkiaIJSguQLZHrCcJgA "Jelly – Try It Online")
My first attempt repeatedly segfaulted, but now that I have a very close translation of hyper-neutrino's Python solution it seems to work fine.
I would be remiss to let this get accepted without an explanation!
```
Ɱ For each element of
Ẏ the input flattened a level,
Ðḟ yield the input without elements which
i contain the element in question.
߀ Recur on each result.
0e Is one of those results 0?
```
] |
[Question]
[
Word changer is a game where you are trying to turn one word into another via single-character edits, with each step being its own word. For this challenge, edits may be replacements, insertions, or deletions. For example, WINNER → LOSER can be done with this route (there may be others):
```
WINNER
DINNER
DINER
DINE
LINE
LONE
LOSE
LOSER
```
Phrased another way, you must be able to reach one word from the other going only through other words at a Levenshtein distance of 1 each time.
# Coding
You will be given a word list and two words and you must output a valid route from one word to the other if a route exists or a distinct constant value or consistent behavior if no route exists.
* You may assume that the input words are both in the word list
* The word list can be taken in via any convenient flat format.
+ Lists, sets, tries, space-separated strings, and line-separated files are all valid (for instance), but a pre-computed graph of Levenshtein adjacency is not.
* The output route should include both input words, but which starts and ends doesn't matter.
* If no route is found, you can output a specific constant, a falsy value, empty list, throw an exception, exit with a nonzero code, or any other behavior that happens in finite time.
* The route does not need to be optimal and there is no requirement of which route should be taken
* Computational complexity does not matter, however your program must be provably guaranteed to terminate in a finite amount of time. (even if it would run beyond the heat death of the universe)
* You may assume all words are entirely composed of letters in the same case
# Example Test Cases
* CAT → DOG; [CAT, DOG, COG, COT, FROG, GROG, BOG]
+ CAT, COT, COG, DOG
* BATH → SHOWER; [BATH, SHOWER, HATH, HAT, BAT, SAT, SAW, SOW, SHOW, HOW]
+ No Route Found
* BREAK → FIX; [BREAK, FIX, BEAK, BREAD, READ, BEAD, RED, BED, BAD, BID, FAD, FAX]
+ BREAK, BREAD, BEAD, BAD, FAD, FAX, FIX
* BUILD → DESTROY; [BUILD, DESTROY, BUILT, GUILT, GUILD, GILD, GILL, BILL, DILL, FILL, DESTRUCT, STRUCTURE, CONSTRUCT]
+ No Route Found
* CARD → BOARD; [CARD, BOARD, BARD]
+ CARD, BARD, BOARD
* DEMON → ANGEL; [DEMON, ANGEL]
+ No Route Found
* LAST → PAST; [LAST, PAST, BLAST, CAST, BLACK, GHOST, POST, BOAST]
+ LAST, PAST
* INSERT → DELETE; [This word list](https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt)
+ INSERT, INVERT, INVENT, INBENT, UNBENT, UNBEND, UNBIND, UNKIND, UNKING, INKING, IRKING, DIRKING, DARKING, DARLING, ARLING, AILING, SIRING, SERING, SERINE, NERINE, NERITE, CERITE, CERATE, DERATE, DELATE, DELETE
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~21~~ 20 bytes
Prints a list of valid routes.
Saved 2 bytes thanks to *Kevin Cruijssen*.
```
怜€`ʒü.LP}ʒ¬²Qsθ³Q*
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8LJHTWuOTgYSCacmHd6j5xNQe2rSoTWHNgUWn9txaHOg1v//0UrOjiFKOgpKLv7uIMoZRoEF3YIgXHco7QSkYrmAOriAygE "05AB1E – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~177~~ 176 bytes
Takes input as `(target)(source, list)`. Prints all possible routes. Or prints nothing if there's no solution.
```
t=>F=(s,l,p=[],d)=>s==t?print(p):l.map((S,i)=>(g=(m,n)=>m*n?1+Math.min(g(m-1,n),g(m,--n),g(--m,n)-(S[m]==s[n])):m+n)(S.length,s.length)^d||F(S,L=[...l],[...p,L.splice(i,1)],1))
```
[Try it online!](https://tio.run/##TVHLTsMwELzzFb7Fpk6k3hDIRXmnIjQoadWiKEhVKSXISSNscQG@vdhek/aQmZ3xaHftfGy/tmL32Q7S/bo5vbGTZLOEYUE5HVjd0FfCZoIxeT98tr3EA7nlXrcdMK5oq47wgeGO9qrqrvv76eRxK9@9ru3xAXfuVB1QVVDXNYXr6qiLq7prGBN13xBy2016giuP7/uDfKfCFuTl9ecnUUNyVnuexxuqaaC5Jwbe7va4pVPSqI@c5F5IxJBaGUmKOEFshr7R7tiLI997/HjAAk2Qg9yZggmS5A69YUl0nqv6Mqjk79WVboid0F86FDlRkSqqQYJyQovaSUojUqBAYUNsh8BfZrpFlRXruDRdwBodJwOdmeaBwcriWmOxtmkdUnjuXcb@g26ezDfQGQzQTgBCm5FiS8G/AmEQDuYaEx9wczFmNc8j8wxxtSyLZxgF5tkzjt46vWCdSEfKzRRDEVBilW6yCs2dTbEqY/O4C@s3BI1/pDS7BAUUtXX@DXUZRePuUfxYLHTeX6RxbvLWss6YzP3K/Osn4NoaVjuBleEoQ/24aVZACkgtUeltT38 "JavaScript (V8) – Try It Online")
### Commented
```
t => // t = target string
F = ( // F is a recursive function taking:
s, // s = source string
l, // l[] = list of words
p = [], // p[] = path
d // d = expected Levenshtein distance between s and the
) => // next word (initially undefined, so coerced to 0)
s == t ? // if s is equal to t:
print(p) // stop recursion and print the path
: // else:
l.map((S, i) => // for each word S at index i in l[]:
( g = // g = recursive function computing the Levenshtein
(m, n) => // distance between S and s
m * n ? // if both m and n are not equal to 0:
1 + Math.min( // add 1 to the result + the minimum of:
g(m - 1, n), // g(m - 1, n)
g(m, --n), // g(m, n - 1)
g(--m, n) - // g(m - 1, n - 1), minus 1 if ...
(S[m] == s[n]) // ... S[m - 1] is equal to s[n - 1]
) // end of Math.min()
: // else:
m + n // return either m or n
)(S.length, s.length) // initial call to g with m = S.length, n = s.length
^ d || // unless the distance is not equal to d,
F( // do a recursive call to F with:
S, // the new source string S
L = [...l], // a copy L[] of l[]
[...p, L.splice(i, 1)], // the updated path (removes S from L[])
1 // an expected distance of 1
) // end of recursive call
) // end of map()
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
Select[Rule@@@#~Tuples~2,EditDistance@@#<2&]~FindPath~##2&;
```
[Try it online!](https://tio.run/##ZZLBboMwDIbvfYoJpB6mnnrdKhEgQDVGqgBqp2kH1FINqUXTSE8VvDpLbGel6umzf/@xTci5Ut/1uVLNvhqPqzGvT/VefcrLqfY8zx2Ky8@p7oblgh8aFTadqtq9rrivy/nXEDXtYaPPD667nL@Mqu5Ut7rOrlcnYIWzeHJCERsEFiBGEtOY6Gv0pnw70y9ME58ViVHyRGy5NFFCSoJWH5FbbAFiaw@BVaNH77QZTZCcvcFO6x00pNTooQks/f@cUgQV14CIEXY4cNqbxpXrFDwhzwspPuCw1mD9eBqAK74xxTnIkBjZ3HQrA7wEiErJ8cIzqvQ06W46LhUwiV8hbGCIP2RaQXfI30VmRJbFPAXbg2R8Kcthnw3Rt0JwEwK4njgRZCXqcTlufNekn/WzzW/TKu/5qJ8mPLbxDw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 155 bytes
```
f=lambda a,b,W,r=[]:a==b and r+[a]or reduce(lambda q,w:q or any({a,a[:i]+a[i+1:]}&{w,w[:i]+w[i+1:]}for i in range(len(a+w)))and f(w,b,W-{a},r+[a]),W-{a},0)
```
[Try it online!](https://tio.run/##VVFNT4NAFLz7K/YkkK6JeiThwDeNWAy0oYZw2NpWSZS2pIY0hN@Ou@@9Ir3M7Ayz83aX4@X8daifh2FvfYufzVYwwTc8541VlKawrA0T9ZY1s0KUh4Y1u@3vx06n5Im35olJW9QXvRNcFGZVzkRRzZ7Msr/vWt6C05Kzl9GKVTVrRP0pW3a1LmatYRhqxF5v1eCHTvQcxhkkHo3h2FT1WSY0115qnGleEkrqUKLSXELlBCmIEMmR2Bt3Y4ljLyPVkkVJ7qdQhNboaBHqCPodwIwwV5jklFYhiTf1qW@/qP5gvsZyNFBrDgplepKJnKtCAYgf5goDG3F9O2k1jz14Dz9bpsk7TkPz3wNHnT2csEqEI8UwCMhDCkipkpULN4fFKvXhlRfk92xyHtdO4ThOgouOnKshryRpegPPf00Waou9CP0YtpBFzjQc2xn8/TfkjgzSmkPSHaWrHjqMEkwhyaNI7o3hDw "Python 2 – Try It Online")
Takes two words and a set of words as input; returns a (non-optimal) route if one exists as a list of strings, otherwise returns False.
This fragment:
```
any({a,a[:i]+a[i+1:]}&{w,w[:i]+w[i+1:]}for i in range(len(a+w)))
```
is `True` if and only if `a==w` or `a` has Levenshtein distance of `1` from `w`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 124 bytes
```
Join[#,Select[Flatten[Permutations/@Subsets@#3,1],s=#;t=#2;Union[EditDistance@@@Partition[Join[s,#,t],2,1]]=={1}&][[1]],#2]&
```
[Try it online!](https://tio.run/##NYzBCoMwEER/RQx4Wii1Rwmk1Sr0UlvbU8ghtcEGNIJZT@K3p1Hb05uZ3ZlO4kd1EnUtXUPdpdeGE6hUq2rkeSsRleGlGroR/VNv7I5V48sqtIwcYC/AUpIgJXHyNP7Mz2@NmbYoTa0YY6UcUC89vi5bIIACYl8UlE77ORKcew0kFpErB20wYLdRK2RBw6cwPT7CGYIpzK7FJpYEgtV7pH@sYX7fbPHjaSkJ574 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 163 bytes
If a route is found, it is output to stderr and the program exits with exit code 1.
If there is no route, there is no output and the program terminates with exit code 0.
```
s,e,d=input();r=[[s]]
for x in r:t=x[-1];t==e>exit(x);r+=[x+[w]for w in d-set(x)for a,b in(t,w),(w,t)for i in range(len(b)*2)if a==b[:i/2]+a[i/2:][:i%2]+b[i/2+1:]]
```
[Try it online!](https://tio.run/##XVHRrppAEH3nKzYkBqhoc31p4g1NABFNrRjUeBtCGhBuS9ICWdZIY/x2OzO7atOXOXsOZ8/ODO0f8bOpJ7djU5TMYbqu3zq7tAunqtuTMK1X7iRJl6bae8NZz6qa8alw@mT0kr4Kxyk/l30lzB58Qyfph8k5ReMZjcWoK/ETCpmdg2QK@2zZ5tkWJFYUl9U/SvNXWZu59WFiVe8sc5w8mVYfJ@kwSwCmKbABsBzZ8GWapjfoc9wJXrWmpWnV77bhgnWnvOXNsew6jbr9/oz/ZE01xloY8Gkab5oWXk30llag20wfHaHiJlKbdaIoOf/vxnITWBg0PmcwNR15VQtmBLAFuskGhcEG4OClOPEaJRuYTAMxK0zr3vnN8N2dYTNjFoUAF0klM3xVUZnHREIJHtSrZnjuboGXt4voEMR0X0oPxVhIvqBYj@pW1QPW6KDcaIKKqXHgfsHY@fJNZkpBcsOTBMUZoALvziShKj8ssc5dWd/ogf1yNaOhg@0ujr7JR6T41EjBTsN/EB3hA1aUTzCTMFcMQ/Y@zUmHfRzQKtdKvzINVh1TF14kDxel3AUYAAD6nQVfozU63XUYrMipJKWAZ@Vu6T9uJF6UoLjhKeo/qI9LDBeRdEmAhwGvfwE "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~217~~ ~~214~~ ~~212~~ 201 bytes
*-11 bytes thanx to a hint from xnor*
```
d=lambda a,b:min(d(a[1:],b[1:])+(a[0]!=b[0]),d(a[1:],b)+1,d(a,b[1:])+1)if b>""<a else len(a+b)
def g(a,b,l,p=[]):
if a==b:yield[a]+p
for c in(a!=b)*l:
if(c in p)+d(a,c)==1:yield from g(c,b,l,[a]+p)
```
[Try it online!](https://tio.run/##bVJLjptAEF2PT1Ezm6YDiYKyQyESP4MVx0RgayZCKGoMZEgwIA@z8AVygBwxF3G6uht7QrLh1Xv1eVVuD6fxse/enc@l3bJDUTJgRmEdmk4rNZaZVm4U@KU6Z2/zW7vgX2pcclQ3kUxFJm1qKD7c3b1nULVPFbRVpzG9oIuyquEbFhqtMdhZTq3FDa9ltl1Yp6Zqy4zl@rC4qfsj7IHbM@5FX7W8jNdpKMFAdfTaU9s2ZRPUx/7A5@7FXDGCntFqODbd@HVg46P0RLvBbpunUVNbUMoVrNII/P75C8ib7z23xcsHA35UJ5vvTjPLem3mwDcd5EEZ2fRw7J/HCur@uStvSc4nLV74Ec/ZEgMAiB@HIgDeJUXiCYmDYMtE0lChKwH7cvrXTNfZRjiLpFF8HyQYZpNIoiuKKRLSCe4FxBIiidGV8mlzsyRwPor9Vg@XA2YicRVF3cdgQvfCFZWgkisBS0fBwz/eu9Va5Pwg3SbxFx5m/xOFJg4MXwaiKrziWppK9BUuJ47Tdp78mUS0SwL5PBuVmW3nOYkvnsGNVSSeNpG3xVOAOOv0g0/xBpPOJgzWqnMmzlrWTir@SOSzCrBFiZNG3EnwroInHiaMYlWqkO@X4kXnPw "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
⁵ḟ,€0ị$ṭ¹-Ƥ$€e€/ẸƊƇḢ€
Wṭ@ⱮÇßƊe@⁴oṆƲ?€Ẏ
```
[Try it online!](https://tio.run/##y0rNyan8//9R49aHO@brPGpaY/Bwd7fKw51rD@3UPbZEBSiQCsT6D3ftONZ1rP3hjkVAHlc4UN7h0cZ1h9sPzz/WlerwqHFL/sOdbcc22QNlH@7q@394uTeQFfn/f3S0klOQq6O3UmzsfyU3zwil/1C@Dpino@QE4YAEXYA0lHKC8SAcMAmR8ASRbo4QMkIJAA "Jelly – Try It Online")
A full program accepting three arguments. The first is the starting word and is supplied as `[["START"]]`. The second argument is the final word, supplied as `"END"`. The third argument is the word list, supplied as quoted, comma-separated words.
The program returns a list of lists, with each list representing a valid path from the start to the end. If there is no valid route, the response is an empty list.
In the TIO link, there is footer text to display the result nicely with each word separated by spaces and each list of words separated by newlines. If a printout underlying list representation is preferred, this could be done as `ÇŒṘ`.
Unlike 05ABIE, there’s no built-in for Levenshtein distance, so this program compares outfixes with a single character missing, somewhat similar to [@ChasBrown’s solution](https://codegolf.stackexchange.com/a/184877/42248), although with a Jelly twist.
### Explanation
Helper link: monadic link that takes a list of words and returns a list of possible extended lists, or an empty list if no further extension is possible
```
⁵ḟ | Filter the word list to remove words already used
,€0ị$ | Pair each word with the last word in the current path
ƊƇ | Filter these pairs such that
e€/Ẹ | there exists any
ṭ¹-Ƥ$€ | match between the original words or any outfix with a single character removed
Ḣ€ | Take the first word of each of these pairs (i.e. the possible extensions of the route)
```
Main link
```
€ | For each of the current paths
Ʋ? | If:
e@⁴ | The path contains the end word
oṆ | Or the path is empty (i.e. could not be extended)
W | Return the path wrapped in a list (which will be stripped by the final Ẏ)
ṭ@ⱮÇ | Otherwise, look for possible extensions using the helper link, and add onto the end of the path
ßƊ | And then feed all of these paths back through this link
Ẏ | Strip back one layer of lists (needed because each recursion nests the path one list deeper)
```
[Answer]
# [Swift 4.2/Xcode 10.2.1](https://developer.apple.com/swift/), 387 bytes
```
func d(l:String,m:String)->Bool{return (0..<l.count).contains{var c=l;c.remove(at:c.index(c.startIndex,offsetBy:$0));return c==m}};func f(r:[String])->[String]{if b==r.last!{return r};return w.lazy.map{!r.contains($0)&&(d(l:r.last!,m:$0)||d(l:$0,m:r.last!)||(r.last!.count==$0.count&&zip(r.last!,$0).filter{$0 != $1}.count==1)) ? f(r:r+[$0]):[]}.first{!$0.isEmpty} ?? []};return f(r:[a])
```
[Try it online!](https://tio.run/##hVRrb9owFP3OrzARQolGA31P6TJEIDw0RqYAaieKJgOhRMpLtimlNL@dOX5AmKbCl3PvsX3PuXa4eOMvyc3eD5MYEdCO19ECEj@OCst1NAebGC2aKxi9eMj14HwFZ37gk60KjSFBfvRSmclgY0x4NNUuvstwt2dVFmogt4UioJusOA52yCNrFAG1puvfAn1O5YlGISLQj/DuFSIwN4OHuY68MH71VEiMue5HC@9NneuYQER6WVKJl0vsEWtrlGqa9iCKzk0zTNMHZmGpov8a9JdgZppIDyAmRekGpbLEhi68b/UQJrsiOvhSqUq5rGZtiZO0L8p9fGRUqUYzwVNKFSFvzjRLNR6Vy@9@Ihcr9LS@9APioV2pBoomKF2m8sSlpoE66wB9mZRqU82YTFO6G2GyK9JyPrbDhGxTUK8DuiK9s5bhVNunhcAjgHiYXALzkycFSrMxUipgRqOW06HRxgATQQpGaUpgZNvlaUegRWGqFRJ6uURlilrhoH51Rt1qjLpCfth1Hm1XOhALR1bpCqbLvVkchhIeGTiP8hDbSuHE2lXO2vU5a67d@CG8tXtPB2OCFpxiiTTjW1kg0TrkIuUgFnsM2g0BT6c@r3M@b875HPf6LfmE9nDkOr8PXsVSjmccu7JOPmC7Okfsc5McWwLbMs@qjZv84lk0dm3@hQzEykk3N7lubs9@jq5sxnJ4LL5Il1@cI4MMT2RuczJ3Z2Ra9k9nIHQag47dlzpyQbAnAnc5gfszAv3GUP6vfvGQlRe05BRLEs0j0WTfU6friK0CaefDfy72nhqi0yzztEZBO0YjSn6lzsZuX8Vs3FH9FSEJNqpVBDf6i09W69kaeygbbF5E6MAJq4vNNqh60Uvg49VF1hWuhnREeajKkj8wSFZQJ29E0cCuAOiPX8MbyWkStK0DPmNVURw7SyPvTGNnhWNWOn8@V66u44RepYq9BCJIYkTbeEbPkaJlc1ndSZ1shK6ThHYDsbdQNZBKg0eTvPpnb9UbDG33MAXtvj2y@XudWNQOdY8PIMi0kO7/Ag "Swift 4 – Try It Online")
] |
[Question]
[
# Introduction
Write a program to output the outgoing spiral of the famous pangram following given rules.
# Challenge
A [pangram](https://en.wikipedia.org/wiki/Pangram) is a sentence using every letter of a given alphabet at least once. One of the most famous pangrams is the one used extensively in Windows font viewer, namely "[The quick brown fox jumps over the lazy dog](https://en.wikipedia.org/wiki/The_quick_brown_fox_jumps_over_the_lazy_dog)". The challenge is to output a spiral based on this text.
Your task is output this exact text:
```
heeeeellllllllllllazzzzzzzzzzz
hummmmmmmmmmmmmppppppppppppppy
hubrrrrrrrrrrrrrrrrrrooooooosy
hukyddddoooooooooooooooggggwsy
hukyveeeeerrrrrrrrrrrrrrrrtwsy
hukyvxjjjjjjjjjjuuuuuuuuuttwsy
hukyvxkbbrrrrrrrrrrrrrrrmttwsy
hukyvxkogggggggttttttttomttwsy
tukyvokoellllllllllllahomttwsy
tukyvokoeovvvvvvvvvvvzhomttwsy
tukyvocoeoummmmmmmmmezhomttwsy
tukyvocoeoufooooooopezhomttwsy
tukyvocohoufroooooxpezhomttwsy
tukyvoiohoufrquuuwxpezhomttwsy
tucyvoiohoufbqttiwxpezhomttwsy
tucyvoiohoufbeehiwxprzhomttwsy
tucyvoiohoufkccciwxprzeomttwsy
tjiyvoidhounnnnnnwxprzeomttwsy
tjiyvoidhojjjjjjjjxprzeomttwsy
tjiyvoidhssssssssssprzeopttwsy
tjiyvoidttttttttttttrzeopttwsy
tjiyvoiyyyyyyyyyyyyyyzqopttwoy
tjiyvouuuuuuuuuuuuuuuuqwpttwoy
tjiyvffffnnnnnnnnnnnnnnwpttwoy
tjiyossssssssssssssssssspthwoy
tjizzzzalllllllllllleeeeehhwoy
tjuuqqqqqqqqqqqqqqqqqeeeeehnod
txxxxxoooooooooooooooffffffnod
reeeeevvvvvvvvvvvvvvvvvvvvvvod
gggggggoooooooooooooood
```
Here is how it is generated,
* There was a zealous fox who enjoyed the pangram "The quick brown fox jumps over the lazy dog". One day he was in the center of an outward spiral and decided to jump in it and paint along.
* He would like to go through the pangram from the beginning to the end, and if a letter is the n-th letter in the alphabet he would like to paint it n times.
* However, the fox was not very good at making turns on corners, so upon reaching each corner he also had to stop and switch to the next letter.
* He also decided to repeat the pangram thrice to emphasize that he is **the** quick brown fox.
* Your job is to show how the spiral would look like after the fox painted all those letters.
(Plain version without story-telling)
* The famous pangram "The quick brown fox jumps over the lazy dog" is repeated thrice, with the spaces removed and all letters in lower case, to generate
```
thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog
```
* The spiral starts from the center and begins with the letter "t", it starts by going to the right, and goes outward clockwise. If the current character is the n-th letter in the alphabet, then it switches to the next character whenever
+ the spiral reaches a corner, or
+ the current letters is printed exactly n times.
To better illustrate it, I will explain how the spiral related to the first three words "thequickbrown" is generated.
```
rooooo
rquuuw
bqttiw
beehiw
kccciw
nnnnnnw
```
The fox starts from "t", goes right, reaches the 1st corner, paints it **with the "t" and then switches** to "h" and goes down, reaches the 2nd corner, switches to "e" and goes left, reaches the 3rd corner, switches to "q" and goes up, reaches the 4th corner, switches to "u" and goes right, reaches a corner and switches to "i", goes down, reaches a corner and switches to "c", goes left, successfully **paints 3 "c"s before reaching the next corner**, switches to "k" and **goes on to the left**, reaches a corner right away, switches to "b" and goes up, **paints 2 "b"s** before reaching the next corner, switches to "r" and **goes on upwards**, reaches a corner and switches to "o", goes right, then "w", down, "n", left.
# Specs
* You can take an optional input that contains [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) of the string
```
thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog
```
* Your output must be formatted as a string, and must go to STDOUT instead of files or STDERR, with newlines placed correctly. Heading and trailing empty lines do not matter. Heading and trailing spaces in each line are allowed, but need to be be consistent. So if you add 5 spaces before one line of the given text, you'll need to add exactly 5 spaces before each line so that the spiral looks the same.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the lowest number of bytes wins.
* As usual, [default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply here.
---
Explanations are welcome, although not necessary.
Title edited to make it a pangram per comment by caird coinheringaahing.
The lazy dog is too lazy to appear in the story.
I am aiming at creating a string challenge in which the letter to output cannot be computed by simple functions of the coordinates.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~66~~ ~~40~~ 36 bytes
```
≔²ηFS«F¬η«¶↷⊞υη≔⊕÷Lυ²η¶»F⊕⌕βι¿η«≦⊖ηι
```
[Try it online!](https://tio.run/##rY47j8IwEITr8CusVGspNLRUSOgkJA6d7lqaPBx7ubDOOevwEr/dZ5GAoKfb2Z39ZkqTu9LmTQiLrkNNMMuEkfNJbZ2AFbWef9ghaZBSXCbJbb2xDGbQyVc8MqRbSuNTlNhb/kZtGAbtOwN@QCbJGLGi0qm9IlZVnHmJPVYK1oo0R7PMxEzK@8sr/zo2eCZ8IFVQZAJlrIS1iNVuzT7zdsxbqof7FYsD8xoCG/XnsfwtnD1QbY87v2872ysXD01@PlVWv8cSpn3zDw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 16 bytes by taking the text as input. Explanation:
```
≔²η
```
Start with 2 `t`s for some reason.
```
FS«
```
Loop over all the letters in the pangram.
```
F¬η«
```
Have we reached a corner yet?
```
¶
```
Move down (or whatever the next direction will be) one line.
```
↷
```
Rotate the print direction 90° clockwise.
```
⊞υη≔⊕÷Lυ²η
```
Calculate the length of the next side.
```
¶»
```
Finish fixing up the cursor position. (Charcoal would have preferred the side to end just before the corner, so that you rotated on the corner itself.)
```
F⊕⌕βι
```
Loop as many times as the current letter's position in the alphabet.
```
¿η«
```
If we haven't reached the corner,
```
≦⊖ηι
```
Decrement the count and print the current letter.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 35 34 33 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é╛îá%ⁿ┌○iê}→Ug=╩◙╘Ç⌐)QX↑L╓₧╗▌╧▬q
```
[Run and debug it online](http://stax.tomtheisen.com/#c=%C3%A9%E2%95%9B%C3%AE%C3%A1%25%E2%81%BF%E2%94%8C%E2%97%8Bi%C3%AA%7D%E2%86%92Ug%3D%E2%95%A9%E2%97%99%E2%95%98%C3%87%E2%8C%90%29QX%E2%86%91L%E2%95%93%E2%82%A7%E2%95%97%E2%96%8C%E2%95%A7%E2%96%ACq&i=thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog&a=1)
Stax is a language I've been working on for about 6 months. This is the first public golfing with it. Let's get down to business.
Stax is normally written in the printable ASCII character set. This 34 byte submission is [packed](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) into a variant of the CP437 character set. The corresponding ascii representation is
```
't],{]_96-*~cHT,+nh%^(XUs&xH{rM}MF|<mr
```
Stax is a stack based language, but it has two data stacks, "main" and "input". Most operations use the main stack, but input starts on the input stack. Stax instructions are mostly one or two character ascii sequences. Most of them are overloaded, meaning their behavior is determined by the top few values on the stack(s).
At a high level, this program builds a grid by repeatedly appending strings to the last row. When the last row fills up, it rotates the grid clockwise. At the end, it mirrors the grid horizontally. In more detail, the program works like this.
```
't],{]_96-*~cHT,+nh%^(XUs&xH{rM}MF|<mr
't] ["t"]
, Pop from input, push to main ("thequick...")
{ F For each character in input, execute block...
]_96-* Produce string using character appropriate
number of times (a=1, b=2, etc)
~ Pop from main, push to input for use later
cH Copy last row from grid.
T Right-trim whitespace
,+ Pop from input stack and append
nh% Get the width of the first row of the grid
^ Add 1
( Right-pad/truncate string to this length
X Store in the x register
Us& Overwrite last row of the grid with new value.
xH Get the last element from x.
Basically, the lower right corner.
{ }M Conditionally execute block. This will happen
when the bottom right corner isn't a space.
rM Reverse and transpose (aka rotate clockwise)
|< Left-justify grid; give all rows equal size.
m For each row, execute the rest of the program
and then print the result to output
r Reverse the row
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~217~~ ~~212~~ ~~209~~ 208 bytes
```
->s{s+=' '*8
x=0
a=[""]*30
i=14
a[i]=?t
l=->{a[i]=s[x]+a[i]}
r=->{a[i]+=s[x]}
(0..58).map{|g|c=0
(0..g/2).map{c>s[x].ord-97&&(x+=1;c=0)
c+=1
eval %w{r i+=1;r l i-=1;l}[g%4]+"[]"}
x+=1}
a[-1].slice!0
$><<a*$/}
```
[Try it online!](https://tio.run/##rY7dUsIwEEbv9yliht9mElrBEUdSHySTi1DaEg0WEwrFkmevCY5v4N235zu7s7bdXoeKDzR3vSN8iqbJGjqeguICY5ksU9A8W4ESWvK3ExhO8/4@ONFJEpMH@wfJnXqYpYw9refsoI79rb4V4V5E9eLxlxV59Fhjd/TleTKZdYRnr8GaQxESlGdl0PjSW6RjYZFBmoZgvKjHK0mwkNhDXPLhMZpJ5owuyocURvlmo5LRwg@VwKd9@dXq4mNrm8tn1XTv7eHomnNpQ2HU93XX1P@jYDn8AA "Ruby – Try It Online")
Spends a fair amount of time managing pointers, so there may be room for more golfing.
-5 bytes: Triple the pangram *before* inputting. Thanks to [Weijun Zhou](https://codegolf.stackexchange.com/users/77134/weijun-zhou).
-3 bytes: Pad the input string and trim the last leg, instead of generating the last leg from scratch.
-1 bytes: Use `&&` instead of a ternary operator with a throwaway value.
Explanation:
```
->s{
s += " " * 8 # These spaces will show on the bottom row
x = 0 # x is a pointer into s
a = [""] * 30 # a is an array of row strings
i = 14 # i is a pointer into a
a[i] = ?t # "Starts with two t's for some reason"
l = ->{ a[i] = s[x]+a[i] } # lambda to prepend char x to row i
r = ->{ a[i] += s[x] } # lambda to append char x to row i
(0..57).map{|g| # There are 58 "legs" to the spiral
c = 0 # c is the print count of s[x]
(0..g/2).map{ # Leg g has g/2+1 characters
c > s[x].ord-97 && (x+=1;c=0) # Possibly switch to next letter
c += 1
eval %w{r i+=1;r l i-=1;l}[g%4]+"[]" # Call the appropriate lambda
}
x += 1 # Definitely switch to next letter
}
a[-1].slice!0 # Remove the first char from the bottom row
$> << a*$/ # Join with newlines and print
}
```
[Answer]
# Deadfish~, 3360 bytes
```
{i}cc{{i}d}iiiicdddccccc{i}ddd{c}cc{d}dc{ii}iiiii{c}c{{d}}{d}ddc{{i}d}iiiic{i}iiic{d}ii{c}ccciii{c}cccc{i}dc{{d}}{d}dc{{i}d}iiiic{i}iiic{dd}ic{i}iiiiii{c}ccccccccdddccccccciiiiciiiiiic{{d}}{d}dc{{i}d}iiiic{i}iiic{d}c{i}iiiic{dd}dcccc{i}i{c}ccccc{d}iicccc{i}iiiiiicddddciiiiiic{{d}}{d}dc{{i}d}iiiic{i}iiic{d}c{i}iiiicdddc{dd}iiiccccc{i}iii{c}cccccciiciiicddddciiiiiic{{d}}{d}dc{{i}d}iiiic{i}iiic{d}c{i}iiiicdddciic{d}dddd{c}{i}icccccccccdcciiicddddciiiiiic{{d}}{d}dc{{i}d}iiiic{i}iiic{d}c{i}iiiicdddciic{d}dddc{d}icc{i}iiiiii{c}cccccdddddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}d}iiiic{i}iiic{d}c{i}iiiicdddciic{d}dddciiiic{d}iiccccccc{i}iiiccccccccdddddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiicddddciiiic{d}c{i}ddd{c}cc{d}dc{i}dddc{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiicddddciiiic{d}c{i}c{i}ddd{c}ciiiic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiic{d}ddc{i}iic{d}c{i}ciiiiiic{d}iiccccccccc{d}iic{ii}ic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiic{d}ddc{i}iic{d}c{i}ciiiiiic{d}dddddc{i}dcccccccic{d}dc{ii}ic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiic{d}ddc{i}iic{d}iiic{i}dddciiiiiic{d}dddddc{i}iicdddccccc{i}dc{d}iic{d}dc{ii}ic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{d}c{i}iiiicdddc{d}iiicddddddciiiiiic{d}iiic{i}dddciiiiiic{d}dddddc{i}iicdciiiiccciicic{d}iic{d}dc{ii}ic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{dd}iic{ii}iicdddc{d}iiicddddddciiiiiic{d}iiic{i}dddciiiiiic{d}dddddcddddc{i}iiiiiciiicc{d}dc{i}iiiicic{d}iic{d}dc{ii}ic{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{dd}iic{ii}iicdddc{d}iiicddddddciiiiiic{d}iiic{i}dddciiiiiic{d}dddddcddddciiicciiicic{i}iiiicic{d}iiciic{i}ddc{dd}iic{i}dddcddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiicic{dd}iic{ii}iicdddc{d}iiicddddddciiiiiic{d}iiic{i}dddciiiiiic{d}dddddciiiiic{d}iiccciiiiiic{i}iiiicic{d}iiciic{i}ddc{dd}dc{i}cddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiicddddddcdddddciiiic{i}dddciiiiiic{d}iiicccccc{i}dcic{d}iiciic{i}ddc{dd}dc{i}cddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiicddddddcdddddciiiic{i}dddcdddddcccccccc{i}iiiic{d}iiciic{i}ddc{dd}dc{i}cddc{i}dddcciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiicddddddcdddddciiiic{i}i{c}dddciic{i}ddc{dd}dc{i}ciciiiicciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiicddddddcdddddc{i}iiiiii{c}ccddc{i}ddc{dd}dc{i}ciciiiicciiicddddciiiiiic{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiicddddddc{i}iiiiii{c}ccccic{d}icddciciiiicciiic{d}iic{i}c{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}iiiciiiiii{c}ccccccddddciiiiiic{d}iiiciiiicciiic{d}iic{i}c{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiicdddc{d}ddddddcccc{i}dd{c}cccc{i}dc{d}iiiciiiicciiic{d}iic{i}c{{d}}{d}dc{{i}}iiiiiic{d}cdc{i}iiiiiic{d}ciiii{c}cccccccccdddciiiic{d}ddc{i}iiiiic{d}iic{i}c{{d}}{d}dc{{i}}iiiiiic{d}cdc{ii}dddcccc{dd}dddddc{i}i{c}cc{d}iiiccccciiicc{i}iiiiic{d}iic{i}c{{d}}{d}dc{{i}}iiiiiic{d}c{i}iccdddd{c}ccccccc{d}ddccccciiiciiiiiicic{d}dc{{d}i}c{{i}}iiiiiiciiiiccccc{d}i{c}ccccc{d}icccccc{i}ddcic{d}dc{{d}i}c{{i}}iiiic{d}dddccccc{ii}ddd{cc}cc{d}iiic{d}dc{{d}i}c{ii}iiccccccc{{i}ddd}iccccccc{i}dd{c}ccccc{d}dc{{d}i}c
```
] |
[Question]
[
[Basic rules (different from mine)](http://www.wikihow.com/Play-Chopsticks)
### Story
It is the year 4579, humans now have 2 hands with 1001 fingers each. Chopsticks has become based off of points. And @Dennis has more rep then @Martin... Hand drawn red circles are now downvoted... Jon Skeet has hit 2 trillion rep on every SE site... Yeah scary I know
Chopsticks is a hand game that has been solved. So to get around this I have created it mutated. I increased the amount of fingers.
## Rules of the game
The way this is played
Everyone starts with 2 hands. Each hand has 1001 fingers. Every hand starts with 1 (one) finger up on *each* hand. During your turn you can "hit" the other players hand. To hit you choose 1 of your hands to hit with and 1 of their hands to hit. The hand that was hit now has the amount of fingers that was their at first AND the amount of fingers that you had on the hand you hit with.
### EX
`P1: 1,1` `P2: 1,1`. `P1[0]` hits `P2[1]`. Now fingers are `P1:1,1` `P2:1,2`. Now `P2[1]` hits `p1[0]`. The fingers are now P1: `3,1` P2 `1,2`.
If one hand gets to 1001 fingers up or more then that hand is out. Then player who got a hand out (for their turn) can "split". Splitting is when you take the hand that is in and halve the amount of fingers (round up) and give those fingers to the other hand getting it back in.
### EX
P1: `1000,2` P2 `7,7`. `P2[0]` hits `P1[0]`. Score is P1: `0,2` P2 `1,1`. `P1[1]` splits for his turn and the score is P1: `1,1` and P2 `7,7`.
The game ends when one player has both hands out. Points are scored by the amount of fingers the winner has. More points = better. The loser gains no points.
There are other rules that are used but these are the ones used here.
Everybody plays everybody (round robin)
## Endgame
Total your points up from every round you win. Then average everybody's points up. Divide your total by the average points and get your final score. Most points win.
## Actual rules
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
Please do *not* try to solve the game. I actually have to be able to run it :P
Make sure the bot can run fast. With the length of rounds judging this will take a while
All libraries needed in your program must be in the default python library. Also list the ones you need imported. Imports will just be the basic import (for math I do: `import math`)
Answers must work in Python 3.x
# Handler
Your bot will be its own Python 3 file with a `play` function.
`play` will be passed two lists of two numbers each. This number indicates how many fingers are up on each hand. The first list is your own hand.
If you choose to hit the other player's hand, then return a list of two bits. The first bit is the index of the hand you are using to hit (`0` for the first, `1` for the last), and the second bit is the index of the hand you are hitting on the opponent.
If you choose to split, return any other truthy value.
Tada!
The controller can be found [here](https://gist.github.com/Cis112233/c3b5a4c11911cc7069be0e22e52cd3eb). Save each bot in its own file and list each bot's filename (without `.py`) in `botnames`.
# Final note:
You and the other bot will take turns going first. If the game does not terminate in 100,000 (one hundred thousand) rounds, the game will be terminated and neither bot wins.
The controller is not protected against moves taking forever, but unnecessary overhead will be strongly frowned upon.
[Answer]
# CodingAndAlgorithms
This answer actually uses coding and algorithms, unlike the others so far!reference: [imgur](https://i.stack.imgur.com/kWBm8.jpg)(also beats all of the answers posted before this)
```
def play(A, B):
if sum(A) == 1:
return [A.index(1), B.index(max(B))]
elif max(A) + max(B) > 1000:
return [A.index(max(A)), B.index(max(B))]
elif 0 in A:
return 1
elif 0 in B:
return [A.index(min(A)), 1-B.index(0)]
else:
return [A.index(min(A)), B.index(min(B))]
```
[Answer]
# CautionBot
```
def play(s,o):
if max(s)+max(o)>1000 and (all(s) or max(s)+min(o)<1001):
return [s.index(max(s)),o.index(max(o))]
else:
return [s.index(min(s)),o.index(min(filter(bool,o)))]if all(s) else 'split'
```
CautionBot doesn't want to cause too much trouble, so it hits the smaller of the opponent's hands with its smaller hand if it has both hands, and otherwise splits. However, CautionBot is no fool, so if it can take out an opponents' hand without immediately losing next turn, it will do so instead of its normal move.
[Answer]
# Equalizer
```
def play(s, o):
if not all(s):
return 1
else:
return [s.index(max(s)), o.index(min(filter(bool, o)))]
```
If Equalizer is missing a hand, it will split. Otherwise, it hits its opponents smallest hand with its own largest hand.
[Answer]
# Aggressor
```
def play(s, o):
return [s.index(max(s)),o.index(max(o))]if all(s)else 1
```
Another starter bot, Aggressor will hit the larger of the opponent's hands with the larger of its own hands if both of its hands are non-empty; otherwise, it splits.
[Answer]
# RandomBot
```
import random
def play(s, o):
return [random.randint(0,1)for i in' ']if all(s)else 1
```
Just to get things started, here's a bot which makes a random hit if its hands are both non-empty; otherwise, splits.
Golfed because why not :3
[Answer]
## Error
Yes, that is the name of the bot.
```
def play(s, o):
if max(s)+max(o)>1000:
return [s.index(max(s)),o.index(max(o))]
if 0 in s:return ''
return [s.index(max(s)),o.index(min(o))]
```
I arrived at at this by testing with the other bots. However it is consistently second-last in my simulations. So Ill be making another bot eventually.
Edit: I can't seem to write any bot that beats CautionBot, and my extra testing seems to indicate that this is second best, not second worst.
[Answer]
# Marathoner
I tweaked Aggressor's code provided by "HyperNeutrino" to simply hit the smaller of the opponents two hands with the smaller of it's hands. It is a very silly strategy of course but I can't turn down being at the top of a chart! (Even though that chart would be losses)
I'm not sure if this code will run without errors because I was unable to test it due to being at work. However, it should run flawlessly.
```
def play(s, o):
return [s.index(min(s)),o.index(min(o))]if all(s)else 1
```
] |
[Question]
[
In [graph-theory](/questions/tagged/graph-theory "show questions tagged 'graph-theory'") a [Prüfer code](https://en.wikipedia.org/wiki/Pr%C3%BCfer_sequence) is a unique sequence of integers that denotes a specific tree.
You can find the Prüfer code of a tree with the following algorithm taken from Wikipedia:
>
> Consider a labeled tree T with vertices `{1, 2, ..., n}`. At step *i*, remove the leaf with the smallest label and set the *i*th element of the Prüfer sequence to be the label of this leaf's neighbor.
>
>
>
(Note that since it's a leaf it will only have one neighbor).
You should stop the iteration when only two vertices remain in the graph.
# Task
Given a labeled tree as input output its Prüfer code. You may take input in any reasonable manner. Such as an adjacency matrix or your languages builtin graph representation. (*You may not take input as a Prüfer code*).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize the bytes in your source.
# Test cases
Here are some inputs in ASCII with their outputs below. You do not need to support ASCII input like this.
```
3
|
1---2---4---6
|
5
{2,2,2,4}
```
---
```
1---4---3
|
5---2---6---7
|
8
{4,4,2,6,2,5}
```
---
```
5---1---4 6
| |
2---7---3
{1,1,2,7,3}
```
[Answer]
# Mathematica, 34 bytes
```
<<Combinatorica`
LabeledTreeToCode
```
Somebody had to do it....
After loading the `Combinatorica` package, the function `LabeledTreeToCode` expects a tree input as an undirected graph with explicitly listed edges and vertices; for example, the input in the second test case could be `Graph[{{{1, 4}}, {{4, 3}}, {{4, 2}}, {{2, 5}}, {{2, 6}}, {{6, 7}}, {{5, 8}}}, {1, 2, 3, 4, 5, 6, 7, 8}]`.
[Answer]
# Python 3, ~~136~~ ~~131~~ 127 bytes
```
def f(t):
while len(t)>2:
m=min(x for x in t if len(t[x])<2);yield t[m][0];del t[m]
for x in t:m in t[x]and t[x].remove(m)
```
Takes input as an adjacency matrix. First example:
```
>>> [*f({1:[2],2:[1,3,4,5],3:[2],4:[2,6],5:[2],6:[4]})]
[2, 2, 2, 4]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
FĠLÞḢḢ
0ịµÇHĊṙ@µÇCịṪ,
WÇÐĿḢ€ṖṖḊ
```
A monadic link which takes a list of pairs of nodes (defining the edges) in any order (and each in any orientation) and returns the Prüfer Code as a list.
**[Try it online!](https://tio.run/nexus/jelly#@@92ZIHP4XkPdywCIi6Dh7u7D2093O5xpOvhzpkOIKYzUOjhzlU6XOGH2w9POLIfqOxR05qHO6eB0I6u////R0cb6pjE6kSb6BiDSSMgaQomjXTMgKSZjjlYxCI2FgA)**
### How?
```
FĠLÞḢḢ - Link 1, find leaf location: list of edges (node pairs)
F - flatten
Ġ - group indices by value (sorted smallest to largest by value)
LÞ - sort by length (stable sort, so equal lengths remain in prior order)
ḢḢ - head head (get the first of the first group. If there are leaves this yields
- the index of the smallest leaf in the flattened version of the list of edges)
0ịµÇHĊṙ@µÇCịṪ, - Link 2, separate smallest leaf: list with last item a list of edges
0ị - item at index zero - the list of edges
µ - monadic chain separation (call that g)
Ç - call last link (1) as a monad (index of smallest leaf if flattened)
H - halve
Ċ - ceiling (round up)
ṙ@ - rotate g left by that amount (places the edge to remove at the right)
µ - monadic chain separation (call that h)
Ç - call last link (1) as a monad (again)
C - complement (1-x)
Ṫ - tail h (removes and yields the edge)
ị - index into, 1-based and modular (gets the other node of the edge)
, - pair with the modified h
- (i.e. [otherNode, restOfTree], ready for the next iteration)
WÇÐĿḢ€ṖṖḊ - Main link: list of edges (node pairs)
W - wrap in a list (this is so the first iteration works)
ÐĿ - loop and collect intermediate results until no more change:
Ç - call last link (2) as a monad
Ḣ€ - head €ach (get the otherNodes, although the original tree is also collected)
ṖṖ - discard the two last results (they are excess to requirements)
Ḋ - discard the first result (the tree, leaving just the Prüfer Code)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
[Dg#ÐD˜{γé¬`U\X.å©Ï`XK`ˆ®_Ï]¯
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/tkq58eILL6TnV5zYfXnloTUJoTITe4aWHVh7uT4jwTjjddmhd/OH@2EPr//@PjjbRMY7ViTbVMQKSRjpmQNJQxwRImumYA0kTsLipjkVsLAA "05AB1E – TIO Nexus")
**Explanation**
```
[Dg# # loop until only 1 link (2 vertices) remain
ÐD # quadruple the current list of links
˜{ # flatten and sort values
γé # group by value and order by length of runs
¬`U # store the smallest leaf in X
\X # discard the sorted list and push X
.å© # check each link in the list if X is in that link
Ï` # keep only that link
XK`ˆ # add the value that isn't X to the global list
®_Ï # remove the handled link from the list of links
] # end loop
¯ # output global list
```
[Answer]
## Clojure, 111 bytes
```
#(loop[r[]G %](if-let[i(first(sort(remove(set(vals G))(keys G))))](recur(conj r(G i))(dissoc G i))(butlast r)))
```
Requires the input to be a hash-map, having "leaf-like" labels as keys and "root-like" labels as values. For example:
```
{1 2, 3 2, 5 2, 4 2, 6 4}
{1 4, 3 4, 4 2, 8 5, 5 2, 7 6, 6 2}
```
On each iteration it finds the smallest key which is not referenced by any other node, adds it to the result `r` and removes the node from the graph definition `G`. `if-let` goes to else case when `G` is empty, as `first` returns `nil`. Also the last element has to be dropped.
[Answer]
# [Python 2](https://docs.python.org/2/), 91 bytes
```
d=input()
while len(d)>2:m=min(d,key=lambda k:len(d[k]));n,=d[m];del d[m];d[n]-={m};print n
```
[Try it online!](https://tio.run/nexus/python2#JYnBCsMgEAXv/QqPEbaHGJODYn9EPCQoVNQllIRSZL/dBnMZZt5r3kTcz2Pgj@875sBywMHzl1DFlHgppPAzeS2bX1lS/bXJca4RjLfFaR8yu8Wie5paSO@fiAfD1uqoqiAQqo4wgYSZYOqLvAgLwdxrUVUS/QE "Python 2 – TIO Nexus")
Based on [L3viathan's solution](https://codegolf.stackexchange.com/a/120164/20260). Takes a dictionary of sets representing adjacency lists.
] |
[Question]
[
For a given DAG (directed acyclic graph), each of its topological sorts is a permutation of all vertices, where for every edges *(u,v)* in the DAG, *u* appears before *v* in the permutation.
Your task is to calculate the total number of topological sorts of a given DAG.
## Rules
* You can use any format to represent the graph, like adjacency matrix, adjacency list or edge list, as long as you don't do useful computations in your encoding. You can also have things like vertex count or vertex list in the input, if those are useful.
* You can assume the graph in the input is always a DAG (doesn't have any cycles).
* Your program should work in theory for any input. But it can fail if it overflows the basic integer type in your language.
* The names of vertices can be any consecutive values in any type. For example: numbers starting at 0 or 1. (And only if you are not storing code in this number, of course.)
* This is code-golf. Shortest code wins.
## Example
This is the same input in different formats. Your program don't have to accept all of them. Vertices are always integers starting at 0.
```
Adjacency list:
[ [1 2 3 5] [2 4] [] [2] [] [3] ]
Adjacency matrix:
[ [0 1 1 1 0 1] [0 0 1 0 1 0] [0 0 0 0 0 0] [0 0 1 0 0 0] [0 0 0 0 0 0] [0 0 0 1 0 0] ]
Edge list:
6 [ [0 1] [0 2] [0 3] [0 5] [1 2] [1 4] [3 2] [5 3] ]
```
It's the graph shown in this image:

The output should be:
```
9
```
The topological sorts are:
```
[0 1 4 5 3 2]
[0 1 5 4 3 2]
[0 1 5 3 4 2]
[0 1 5 3 2 4]
[0 5 1 4 3 2]
[0 5 1 3 4 2]
[0 5 1 3 2 4]
[0 5 3 1 4 2]
[0 5 3 1 2 4]
```
[Answer]
# Python, 58
```
f=lambda G,V:V<{0}or sum(f(G,V-{v})*(V-G[v]==V)for v in V)
```
The input consists of an adjacency dictionary `G` and a vertex set `V`.
```
G = {0:{1,2,3,5}, 1:{2,4}, 2:set(), 3:{2}, 4:set(), 5:{3}, 6:set()}
V = {0,1,2,3,4,5,6}
```
The code is recursive. The set `V` stores all nodes that still need visiting. For each potential next node, we check its suitability by seeing if no remaining vertices point to it, with `V-G[v]==V` checking that `V` and `G[v]` are disjoint. For all suitable such vertices, we add the number of topological sorts with it removed. As a base case, the empty set gives 1.
[Answer]
# Mathematica, ~~80~~ ~~57~~ 51 bytes
```
Count[Permutations@#,l_/;l~Subsets~{2}~SubsetQ~#2]&
```
Very straight-forward implementation of the definition. I'm just generating all permutations and count how many of them are valid. To check if a permutation is valid, I get all pairs of vertices in the permutation. Conveniently, `Subsets[l,{2}]` not only gives me all pairs, it also maintains the order they are found in in `l` - just what I need.
The above is a function that expects the vertex list and edge list, like
```
f[{1, 2, 3, 4, 5, 6}, {{1, 2}, {1, 3}, {1, 4}, {1, 6}, {2, 3}, {2, 5}, {4, 3}, {6, 4}}]
```
if you call the function `f`.
I'll try to golf this, or maybe use another approach later.
[Answer]
# CJam - 25
```
q~{_f{1$-_j@j@&!*}_!+:+}j
```
With great help from user23013 :)
[Try it online](http://cjam.aditsu.net/#code=q~%7B_f%7B1%24-_j%40j%40%26!%2A%7D_!%2B%3A%2B%7Dj&input=%5B0%201%202%203%204%205%5D%5B%5B1%202%203%205%5D%5B2%204%5D%5B%5D%5B2%5D%5B%5D%5B3%5D%5D)
**Explanation:**
The general algorithm is the same as in [xnor's Python solution](https://codegolf.stackexchange.com/a/46863/7416).
The key here is the `j` operator, which does memoized recursion. It takes a parameter, a value or array for the initial value(s) (as in f(0), f(1), etc) and a block to define the recursion. The `j` operator is used again inside the block for doing recursive (and memoized) calls to the same block. It can also be used with multiple parameters, but it's not the case here.
user23013's great innovation is to use j with different data types, making use of the adjacency list as the array of initial values.
```
q~ read and evaluate the input (vertex list followed by adjacency list)
{…}j run the block on the vertex list, doing memoized recursion
and using the adjacency list for initial values
_ copy the vertex list
f{…} for each vertex and the vertex list
1$- copy the vertex and remove it from the list
Python: "V-{v}"
_j copy the reduced list and call the j block recursively
this solves the problem for the reduced vertex list
Python: "f(G,V-{v})"
@j bring the vertex to the top of the stack and call the j block recursively
in this case, it's called with a vertex rather than a list
and the memoized value is instantly found in the list of initial values
effectively, this gets the list of vertices adjacent to the current vertex
Python: "G[v]"
@& bring the reduced list to the top of the stack and intersect
!* multiply the number of topological sorts of the reduced vertex list
with 1 if the intersection was empty and 0 if not
Python: equivalent to "*(V-G[v]==V)"
after this loop we get an array of sub-results for the reduced vertex lists
_!+ add 1 or 0 to the array if the array was empty or not
because we want to get 1 for the empty array
Python: equivalent to "V<{0}or"
:+ add the numbers in the array
Python: "sum(…)"
```
[Answer]
# Pyth, 27 bytes
```
Mlf!sm}_dHfq2lYyTfqSZUZ^UGG
```
Defines a 2 input function, `g`. First input is the number of vertices, second is the list of directed edges.
To test:
```
Code:
Mlf!sm}_dHfq2lYyTfqSZUZ^UGGghQeQ
Input:
6, [ [0, 1], [0, 2], [0, 3], [0, 5], [1, 2], [1, 4], [3, 2], [5, 3] ]
```
[Try it here.](http://pyth.herokuapp.com/)
[Answer]
# Haskell, 102 107 100 89 85 bytes
```
import Data.List
(%)=elemIndex
n#l=sum[1|p<-permutations[0..n],and[u%p<v%p|[u,v]<-l]]
```
The input is the highest vertex number (starting with 0) and an edge list, where an edge is a two element list. Usage example: `5 # [[0,1], [0,2], [0,3], [0,5], [1,2], [1,4], [3,2], [5,3]]`
How it works: count all permutations `p` of the vertices for which all edges `[u,v]` satisfy: position of `u` in `p` is less than position of `v` in `p`. That's a direct implementation of the definition.
Edit: my first version returned the topological sorts themselves and not how many there are. Fixed it.
Edit II: didn't work for graphs with not connected vertices. Fixed it.
] |
[Question]
[
## Challenge
You must create a simple model of how disease spreads around a group of people.
## Rules and Requirements
The model must be a 1000 by 1000 2D array with each element being a different person.
The user must input three variables using argv: the probability of transmission (how likely someone is going to infect someone else), chance of mutation and how many periods the simulation should run for.
In the first period (`t=0`), four people should be chosen randomly and infected with the disease.
The way the disease behaves is governed by the following rules:
* The disease can only move vertically and horizontally, moving to the person next door.
* The infection last for 3 periods in every person. You may not factor in immunodeficiencies.
* After a person has been infected three times, they are immune and cannot be infected again.
* The disease is subject to mutation making the previously immune people vulnerable to this new mutated disease. The mutated disease has exactly the same traits and follows the same rules as the original disease.
* If a mutation occurs, the whole disease does not change, just that particular 'packet' upon transmission.
* Once a person has been been infected by one virus, they cannot be infected again until the current infection passes.
* If a person is infected, they are infectious from the start of their infection period to its end.
* There are no levels of immunity - a person is either immune or not.
* To stop memory overload, there is a maximum limit of 800 mutations.
At the end of the specified number of periods, you should output the results.
The results must be a 1000 x 1000 grid showing which people are infected and which people are not. This can be output as a text file, as an image file or graphical output (where #FFFFFF is a healthy person and #40FF00 is an infected person).
Please can you include the language name and a command to run it in your answer.
## Winning
The fastest code to run on my computer wins. Its time will be measured with the following piece of Python code:
```
import time, os
start = time.time()
os.system(command)
end = time.time()
print(end-start)
```
Note that when running this script, I will use the following defaults:
```
Probability of transmission = 1
Chance of mutation = 0.01
Number of periods = 1000
```
[Answer]
I was curious what this would look like so I made this quick and dirty hack in JavaScript: <http://jsfiddle.net/andrewmaxwell/r8m54t9c/>
```
// The probability that a healthy cell will be infected by an adjacent infected cell EACH FRAME.
var infectionProbability = 0.2
// The probability that the infection will mutate on transmission EACH FRAME.
var mutationProbability = 0.00001
// The maximum number of times a cell can be infected by the same infection.
var maxInfections = 3
// The number of frames a cell in infected before it becomes healthy again.
var infectionDuration = 3
// The width and heigh of the board
var size = 400
// The number of cells infected at the beginning.
var startingNum = 4
var imageData, // the visual representation of the board
cells, // array of cells
infectionCount // counter that is incremented whenever a mutation occurs
// Just some colors. The colors are re-used as the number of mutations increases.
var colors = [[255,0,0],[255,255,0],[0,255,0],[0,255,255],[0,0,255],[255,0,255],[128,0,0],[128,128,0],[0,128,0],[0,128,128],[0,0,128],[128,0,128],[255,128,128],[255,255,128],[128,255,128],[128,255,255],[128,128,255],[255,128,255]
]
// when a cell is infected, it isn't contagious until the next frame
function infect(person, infection){
person.infect = true
person.infectionCounts[infection] = (person.infectionCounts[infection] || 0) + 1
person.currentInfection = infection
}
// when a mutation occurs, it is given a number and the counter is incremented
function mutation(){
return infectionCount++
}
function reset(){
cells = []
infectionCount = 0
imageData = T.createImageData(size, size)
// initialize the cells, store them in a grid temporarily and an array for use in each frame
var grid = []
for (var i = 0; i < size; i++){
grid[i] = []
for (var j = 0; j < size; j++){
cells.push(grid[i][j] = {
infectionTime: 0, // how many frames until they are no longer infected, so 0 is healthy
infectionCounts: [], // this stores how many times the cell has been infected by each mutation
neighbors: [] // the neighboring cells
})
}
}
// store the neighbors of each cell, I just want to minimize the work done each frame
var neighborCoords = [[0,-1],[1,0],[0,1],[-1,0]]
for (var i = 0; i < size; i++){
for (var j = 0; j < size; j++){
for (var n = 0; n < neighborCoords.length; n++){
var row = i + neighborCoords[n][0]
var col = j + neighborCoords[n][1]
if (grid[row] && grid[row][col]){
grid[i][j].neighbors.push(grid[row][col])
}
}
}
}
// infect the initial cells
for (var i = 0; i < startingNum; i++){
infect(cells[Math.floor(cells.length * Math.random())], 0)
}
}
function loop(){
requestAnimationFrame(loop)
// for each cell marked as infected, set its infectionTime
for (var i = 0; i < cells.length; i++){
var p = cells[i]
if (p.infect){
p.infect = false
p.infectionTime = infectionDuration
}
}
for (var i = 0; i < cells.length; i++){
var p = cells[i]
// for each infected cell, decrement its timer
if (p.infectionTime){
p.infectionTime--
// for each neighbor that isn't infected, if the probability is right and the neighbor isn't immune to that infection, infect it
for (var n = 0; n < p.neighbors.length; n++){
var neighbor = p.neighbors[n]
if (!neighbor.infectionTime && Math.random() < infectionProbability){
var infection = Math.random() < mutationProbability ? mutation() : p.currentInfection
if (!neighbor.infectionCounts[infection] || neighbor.infectionCounts[infection] < maxInfections){
infect(neighbor, infection)
}
}
}
// colors! yay!
var color = colors[p.currentInfection % colors.length]
imageData.data[4 * i + 0] = color[0]
imageData.data[4 * i + 1] = color[1]
imageData.data[4 * i + 2] = color[2]
} else {
imageData.data[4 * i + 0] = imageData.data[4 * i + 1] = imageData.data[4 * i + 2] = 0
}
imageData.data[4 * i + 3] = 255
}
T.putImageData(imageData, 0, 0)
}
// init canvas and go
C.width = C.height = size
T = C.getContext('2d')
reset()
loop()
```
[Answer]
# C++11, 6-8 minutes
My test run takes about 6-8 minutes in my Fedora 19, i5 machine. But due to the randomness of the mutation, it might as well be faster or take longer than that. I think the scoring criteria needs to be readdressed.
Prints the result as text at the end of completion, healthy person denoted by dot (`.`), infected person by asterisk (`*`), unless `ANIMATE` flag is set to true, in which case it will display different characters for people infected with different virus strain.
Here is a GIF for 10x10, 200 periods.

## Mutation behaviour
Each mutation will give new strain never seen before (so it is possible that one person infects the four neighboring people with 4 distinct strains), unless 800 strains have been generated, in which case no virus will go any further mutation.
The 8-minute result comes from the following number of infected people:
```
Period 0, Infected: 4
Period 100, Infected: 53743
Period 200, Infected: 134451
Period 300, Infected: 173369
Period 400, Infected: 228176
Period 500, Infected: 261473
Period 600, Infected: 276086
Period 700, Infected: 265774
Period 800, Infected: 236828
Period 900, Infected: 221275
```
while the 6-minute result comes from the following:
```
Period 0, Infected: 4
Period 100, Infected: 53627
Period 200, Infected: 129033
Period 300, Infected: 186127
Period 400, Infected: 213633
Period 500, Infected: 193702
Period 600, Infected: 173995
Period 700, Infected: 157966
Period 800, Infected: 138281
Period 900, Infected: 129381
```
## Person representation
Each person is represented in 205 bytes. Four bytes to store the virus type this person is contracting, one byte to store how long has this person been infected, and 200 bytes to store how many times he has contracted each strain of virus (2 bit each). Perhaps there are some additional byte-alignment done by C++, but the total size will be around 200MB. I have two grids to store the next step, so total it uses around 400MB.
I store the location of infected people in a queue, to cut the time required in the early periods (which is really useful up to periods < 400).
## Program technicalities
Every 100 steps this program will print the number of infected people, unless `ANIMATE` flag is set to `true`, in which case it will print the whole grid every 100ms.
This requires C++11 libraries (compile using `-std=c++11` flag, or in Mac with `clang++ -std=c++11 -stdlib=libc++ virus_spread.cpp -o virus_spread`).
Run it without arguments for the default values, or with arguments like this:
`./virus_spread 1 0.01 1000`
```
#include <cstdio>
#include <cstring>
#include <random>
#include <cstdlib>
#include <utility>
#include <iostream>
#include <deque>
#include <cmath>
#include <functional>
#include <unistd.h>
typedef std::pair<int, int> pair;
typedef std::deque<pair> queue;
const bool ANIMATE = false;
const int MY_RAND_MAX = 999999;
std::default_random_engine generator(time(0));
std::uniform_int_distribution<int> distInt(0, MY_RAND_MAX);
auto randint = std::bind(distInt, generator);
std::uniform_real_distribution<double> distReal(0, 1);
auto randreal = std::bind(distReal, generator);
const int VIRUS_TYPE_COUNT = 800;
const int SIZE = 1000;
const int VIRUS_START_COUNT = 4;
typedef struct Person{
int virusType;
char time;
uint32_t immune[VIRUS_TYPE_COUNT/16];
} Person;
Person people[SIZE][SIZE];
Person tmp[SIZE][SIZE];
queue infecteds;
double transmissionProb = 1.0;
double mutationProb = 0.01;
int periods = 1000;
char inline getTime(Person person){
return person.time;
}
char inline getTime(int row, int col){
return getTime(people[row][col]);
}
Person inline setTime(Person person, char time){
person.time = time;
return person;
}
Person inline addImmune(Person person, uint32_t type){
person.immune[type/16] += 1 << (2*(type % 16));
return person;
}
bool inline infected(Person person){
return getTime(person) > 0;
}
bool inline infected(int row, int col){
return infected(tmp[row][col]);
}
bool inline immune(Person person, uint32_t type){
return (person.immune[type/16] >> (2*(type % 16)) & 3) == 3;
}
bool inline immune(int row, int col, uint32_t type){
return immune(people[row][col], type);
}
Person inline infect(Person person, uint32_t type){
person.time = 1;
person.virusType = type;
return person;
}
bool inline infect(int row, int col, uint32_t type){
auto person = people[row][col];
auto tmpPerson = tmp[row][col];
if(infected(tmpPerson) || immune(tmpPerson, type) || infected(person) || immune(person, type)) return false;
person = infect(person, type);
infecteds.push_back(std::make_pair(row, col));
tmp[row][col] = person;
return true;
}
uint32_t inline getType(Person person){
return person.virusType;
}
uint32_t inline getType(int row, int col){
return getType(people[row][col]);
}
void print(){
for(int row=0; row < SIZE; row++){
for(int col=0; col < SIZE; col++){
printf("%c", infected(row, col) ? (ANIMATE ? getType(row, col)+48 : '*') : '.');
}
printf("\n");
}
}
void move(){
for(int row=0; row<SIZE; ++row){
for(int col=0; col<SIZE; ++col){
people[row][col] = tmp[row][col];
}
}
}
int main(const int argc, const char **argv){
if(argc > 3){
transmissionProb = std::stod(argv[1]);
mutationProb = std::stod(argv[2]);
periods = atoi(argv[3]);
}
int row, col, size;
uint32_t type, newType=0;
char time;
Person person;
memset(people, 0, sizeof(people));
for(int row=0; row<SIZE; ++row){
for(int col=0; col<SIZE; ++col){
people[row][col] = {};
}
}
for(int i=0; i<VIRUS_START_COUNT; i++){
row = randint() % SIZE;
col = randint() % SIZE;
if(!infected(row, col)){
infect(row, col, 0);
} else {
i--;
}
}
move();
if(ANIMATE){
print();
}
for(int period=0; period < periods; ++period){
size = infecteds.size();
for(int i=0; i<size; ++i){
pair it = infecteds.front();
infecteds.pop_front();
row = it.first;
col = it.second;
person = people[row][col];
time = getTime(person);
if(time == 0) continue;
type = getType(person);
if(row > 0 && randreal() < transmissionProb){
if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
newType++;
if(!infect(row-1, col, newType)) newType--;
} else {
infect(row-1, col, type);
}
}
if(row < SIZE-1 && randreal() < transmissionProb){
if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
newType++;
if(!infect(row+1, col, newType)) newType--;
} else {
infect(row+1, col, type);
}
}
if(col > 0 && randreal() < transmissionProb){
if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
newType++;
if(!infect(row, col-1, newType)) newType--;
} else {
infect(row, col-1, type);
}
}
if(col < SIZE-1 && randreal() < transmissionProb){
if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
newType++;
if(!infect(row, col+1, newType)) newType--;
} else {
infect(row, col+1, type);
}
}
time += 1;
if(time == 4) time = 0;
person = setTime(person, time);
if(time == 0){
person = addImmune(person, type);
} else {
infecteds.push_back(std::make_pair(row, col));
}
tmp[row][col] = person;
}
if(!ANIMATE && period % 100 == 0) printf("Period %d, Size: %d\n", period, size);
move();
if(ANIMATE){
printf("\n");
print();
usleep(100000);
}
}
if(!ANIMATE){
print();
}
return 0;
}
```
[Answer]
# C# 6-7 Minutes
# Edit 2
I've finally(5 hours) generated a verbose output for close to 1000 periods(only 840 frames then it crashed) at 1000x1000, every 1 period, however its close to 160MB and requires all the memory on my system to display(IrfanView), not even sure that would work in a browser, may I'll put it up later.
# EDIT
I've spent allot of time on making this more efficient per "Beta Decay"s answer stating "Choose the strain randomly" I have choosin only the random method for choosing who infects who per period, however I've changed the way that's calculated and threaded out every thing, I've updated my posts with the new details.
Coded my closest estimation to this I could, I hope it follows all the rules, it uses a ton of memory on my system(about 1.2GB). The program can output animated gifs(looks cool, really slow) or just a image matching "Beta Decay"s specs. This is a little bit of reinventing the wheel, but definitely looks cool:
---
# Results
(Note: this only differentiates between infected and non infected, ie non-verbose)
## 1000 Periods, 1% Mutation Rate, 100% Spread:

# Examples(Verbose)
Anyway using 100% "Probability of transmission" in non-verbose mode is kind of boring as you always get the same shapes and you can't see the different mutations, if you tweak the parameters around a-bit(and enable verbose mode) you get some cool looking output(animated GIFs display every 10th frame):
## Random - Grid Size: 200, ProbTransmission: 100%, ProbMutation: 1%

## Random - Grid Size: 200, ProbTransmission: 20%, ProbMutation: 1%

# Scoring
I agree with "justhalf" that the scoring criteria may not be fair as every run will differ due to the randomness of mutations and position of random start points. Maybe we could do average of several runs or something like that..., well anyway this is in C# so bounty for me :( anyway.
# Code
Make sure to include the MagickImage library(set to compile x64 bit) otherwise it won't build(<http://pastebin.com/vEmPF1PM>):
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using ImageMagick;
using System.IO;
namespace Infection
{
class Program
{
#region Infection Options
private const double ProbabilityOfTransmission = .2;
private const double ChanceOfMutation = 0.01;
private const Int16 StageSize = 1000;
private const Int16 MaxNumberOfMutations = 800;
private const byte MaxInfectionTime = 3;
private const byte NumberOfPeopleToRandomlyInfect = 4;
private static int NumberOfPeriods = 1000;
#endregion Infection Options
#region Run Options
private const bool VerbosMode = false;
private const int ImageFrequency = 10;
#endregion Run Options
#region Stage
private static Int16 MutationNumber = 1;
private class Person
{
public Person()
{
PreviousInfections = new Dictionary<Int16, byte>();
InfectionTime = 0;
CurrentInfection = 0;
PossibleNewInfections = new List<short>(4);
}
public Dictionary<Int16, byte> PreviousInfections { get; set; }
public byte InfectionTime { get; set; }
public Int16 CurrentInfection { get; set; }
public List<Int16> PossibleNewInfections { get; set; }
}
private static Person[][] Stage = new Person[StageSize][];
#endregion Stage
static void Main(string[] args)
{
DateTime start = DateTime.UtcNow;
//Initialize stage
for (Int16 i = 0; i < Stage.Length; i++)
{
var tmpList = new List<Person>();
for (Int16 j = 0; j < Stage.Length; j++)
tmpList.Add(new Person());
Stage[i] = tmpList.ToArray();
}
//Randomly infect people
RandomlyInfectPeople(NumberOfPeopleToRandomlyInfect);
//Run through the periods(NumberOfPeriods times)
List<MagickImage> output = new List<MagickImage>();
while (NumberOfPeriods > 0)
{
//Print details(verbose)
if (VerbosMode && NumberOfPeriods % ImageFrequency == 0)
{
Console.WriteLine("Current Number: " + NumberOfPeriods);
Console.WriteLine("Current Mutation: " + MutationNumber);
output.Add(BoardToImage());
}
Period();
}
//Outputs a Animated Gif(verbose)
if (VerbosMode)
{
ImagesToAnimatedGIF(output.ToArray(), Directory.GetCurrentDirectory() + "\\Output.gif");
System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "\\Output.gif");
}
//Only outputs the basic result image matching the specs
SaveBoardToSimpleImage(Directory.GetCurrentDirectory() + "\\FinalState.gif");
Console.WriteLine("Total run time in seconds: " + (DateTime.UtcNow - start).TotalSeconds);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
#region Image
private static void SaveBoardToSimpleImage(string filepath)
{
using (Bitmap img = new Bitmap(StageSize, StageSize))
{
for (int i = 0; i < img.Width; i++)
for (int j = 0; j < img.Height; j++)
img.SetPixel(i, j, Stage[i][j].CurrentInfection == 0 ? Color.FromArgb(255, 255, 255) :
Color.FromArgb(64, 255, 0));
img.Save(filepath, ImageFormat.Gif);
}
}
private static MagickImage BoardToImage()
{
using (Bitmap img = new Bitmap(StageSize, StageSize))
{
for (int i = 0; i < img.Width; i++)
for (int j = 0; j < img.Height; j++)
img.SetPixel(i, j, Stage[i][j].CurrentInfection == 0 ? Color.White :
Color.FromArgb(Stage[i][j].CurrentInfection % 255,
Math.Abs(Stage[i][j].CurrentInfection - 255) % 255,
Math.Abs(Stage[i][j].CurrentInfection - 510) % 255));
return new MagickImage(img);
}
}
private static void ImagesToAnimatedGIF(MagickImage[] images, string filepath)
{
using (MagickImageCollection collection = new MagickImageCollection())
{
foreach (var image in images)
{
collection.Add(image);
collection.Last().AnimationDelay = 20;
}
collection.Write(filepath);
}
}
#endregion Image
#region Infection
private static void Period()
{
Infect();
ChooseRandomInfections();
IncrementDiseaseProgress();
Cure();
NumberOfPeriods--;
}
private static void Cure()
{
Parallel.For(0, Stage.Length, i =>
{
for (Int16 j = 0; j < Stage.Length; j++)
if (Stage[i][j].CurrentInfection != 0 && Stage[i][j].InfectionTime == MaxInfectionTime + 1)
{
//Add disease to already infected list
if (Stage[i][j].PreviousInfections.ContainsKey(Stage[i][j].CurrentInfection))
Stage[i][j].PreviousInfections[Stage[i][j].CurrentInfection]++;
else
Stage[i][j].PreviousInfections.Add(Stage[i][j].CurrentInfection, 1);
//Cure
Stage[i][j].InfectionTime = 0;
Stage[i][j].CurrentInfection = 0;
}
});
}
private static void IncrementDiseaseProgress()
{
Parallel.For(0, Stage.Length, i =>
{
for (Int16 j = 0; j < Stage.Length; j++)
if (Stage[i][j].CurrentInfection != 0)
Stage[i][j].InfectionTime++;
});
}
private static void RandomlyInfectPeople(Int16 numberOfPeopleToInfect)
{
var randomList = new List<int>();
while (randomList.Count() < numberOfPeopleToInfect * 2)
{
randomList.Add(RandomGen2.Next(StageSize));
randomList = randomList.Distinct().ToList();
}
while (randomList.Count() > 0)
{
Stage[randomList.Last()][randomList[randomList.Count() - 2]].CurrentInfection = MutationNumber;
Stage[randomList.Last()][randomList[randomList.Count() - 2]].InfectionTime = 1;
randomList.RemoveAt(randomList.Count() - 2);
randomList.RemoveAt(randomList.Count() - 1);
}
}
private static void Infect()
{
Parallel.For(0, Stage.Length, i =>
{
for (Int16 j = 0; j < Stage.Length; j++)
InfectAllSpacesAround((short)i, j);
});
}
private static void InfectAllSpacesAround(Int16 x, Int16 y)
{
//If not infected or just infected this turn return
if (Stage[x][y].CurrentInfection == 0 || (Stage[x][y].CurrentInfection != 0 && Stage[x][y].InfectionTime == 0)) return;
//Infect all four directions(if possible)
if (x > 0)
InfectOneSpace(Stage[x][y].CurrentInfection, (short)(x - 1), y);
if (x < Stage.Length - 1)
InfectOneSpace(Stage[x][y].CurrentInfection, (short)(x + 1), y);
if (y > 0)
InfectOneSpace(Stage[x][y].CurrentInfection, x, (short)(y - 1));
if (y < Stage.Length - 1)
InfectOneSpace(Stage[x][y].CurrentInfection, x, (short)(y + 1));
}
private static void InfectOneSpace(Int16 currentInfection, Int16 x, Int16 y)
{
//If the person is infected, or If they've already been infected "MaxInfectionTime" then don't infect
if (Stage[x][y].CurrentInfection != 0 || (Stage[x][y].PreviousInfections.ContainsKey(currentInfection) &&
Stage[x][y].PreviousInfections[currentInfection] >= MaxInfectionTime)) return;
//If random is larger than change of transmission don't transmite disease
if (RandomGen2.Next(100) + 1 > ProbabilityOfTransmission * 100) return;
//Possible mutate
if (MutationNumber <= MaxNumberOfMutations && RandomGen2.Next(100) + 1 <= ChanceOfMutation * 100)
lock (Stage[x][y])
{
MutationNumber++;
Stage[x][y].PossibleNewInfections.Add(MutationNumber);
}
//Regular infection
else
lock (Stage[x][y])
Stage[x][y].PossibleNewInfections.Add(currentInfection);
}
private static void ChooseRandomInfections()
{
Parallel.For(0, Stage.Length, i =>
{
for (Int16 j = 0; j < Stage.Length; j++)
{
if (Stage[i][j].CurrentInfection != 0 || !Stage[i][j].PossibleNewInfections.Any()) continue;
Stage[i][j].CurrentInfection = Stage[i][j].PossibleNewInfections[RandomGen2.Next(Stage[i][j].PossibleNewInfections.Count)];
Stage[i][j].PossibleNewInfections.Clear();
Stage[i][j].InfectionTime = 0;
}
}
);
}
#endregion Infection
}
//Fancy Schmancy new random number generator for threaded stuff, fun times
//http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
public static class RandomGen2
{
private static Random _global = new Random();
[ThreadStatic]
private static Random _local;
public static int Next()
{
Random inst = _local;
if (inst == null)
{
int seed;
lock (_global) seed = _global.Next();
_local = inst = new Random(seed);
}
return inst.Next();
}
public static int Next(int input)
{
Random inst = _local;
if (inst == null)
{
int seed;
lock (_global) seed = _global.Next();
_local = inst = new Random(seed);
}
return inst.Next(input);
}
}
}
```
] |
[Question]
[
Presumably everybody here knows that for the legacy BIOS, the tiniest bootable disk image is 512 bytes (the lower bound is due to the 2-byte magic at offset 510), and there is a bootsector demoscene where people try to fit the entire demo into the 510 bytes of usable space.
Now that the BIOS is being superseded by UEFI, there is a question: what will be the equivalent of a "bootsector demo" in the UEFI world?
More formally, here is what I'm curious about: what's the minimum size of a whole-drive image that boots on at least one UEFI?
Rules:
1. The answer must be a disk image, or must compile to a disk image.
2. The disk image should boot on at least one UEFI with CSM/Legacy boot **disabled**.
3. By "booting" I consider that the CPU starts executing instructions that have been loaded from the disk image. It does not matter what the image actually does.
4. Exploiting bugs in specific UEFI implementations is OK, unless the bug causes the firmware to attempt a legacy boot.
5. The winner is the image that is the smallest when encoded in the raw format. If there are multiple answers with the same image size, the one where the most space can be used for x86 code wins.
[Answer]
# ~~1886~~ 1799 bytes (~3.51 sectors), OVMF
*-87 bytes by removing . and .. from cluster 2 and reorganizing the sector.*
Started off with [@набиячлэвэлиь](https://codegolf.stackexchange.com/users/46550/%d0%bd%d0%b0%d0%b1%d0%b8%d1%8f%d1%87%d0%bb%d1%8d%d0%b2%d1%8d%d0%bb%d0%b8%d1%8c)'s answer and golfed it down to the point where it's now a single NASM file building the image from scratch. Outputs "Done" and enters an infinite loop.
Hexdump:
```
00000000: 0000 0000 0000 0000 0000 0000 0201 0100 ................
00000010: 0110 0004 0000 0100 0000 0000 0000 0000 ................
00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000070: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000080: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000000f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000100: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000110: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000120: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000130: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000140: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000150: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000160: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000170: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000180: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000190: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000200: 0000 00ff 0f00 0000 0000 0000 0000 0000 ................
00000210: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000220: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000230: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000240: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000250: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000260: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000270: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000280: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000290: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000300: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000310: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000320: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000330: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000340: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000350: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000360: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000370: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000380: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000390: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000400: 4546 4920 2020 2020 2020 2010 0000 0000 EFI .....
00000410: 0000 0000 0000 0000 0000 0200 0000 0000 ................
00000420: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000430: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000440: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000450: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000460: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000470: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000480: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000490: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000004f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000500: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000510: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000520: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000530: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000540: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000550: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000560: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000570: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000580: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000590: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000005f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000600: 4d5a 0000 0000 0000 0000 0000 0000 0000 MZ..............
00000610: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000620: 424f 4f54 2020 2020 2020 2010 0000 0000 BOOT .....
00000630: 0000 0000 0000 0000 0000 0200 4000 0000 ............@...
00000640: 5045 0000 6486 0100 0000 0000 0000 0000 PE..d...........
00000650: 0000 0000 7000 2e22 0b02 0000 0000 0000 ....p.."........
00000660: 4100 0000 0000 0000 0010 0000 0010 0000 A...............
00000670: 0000 0040 0100 0000 0100 0000 0100 0000 ...@............
00000680: 4200 0000 0000 0000 0000 0000 0000 0000 B...............
00000690: 0040 0000 f000 0000 0000 0000 0a00 0000 .@..............
000006a0: 424f 4f54 5836 3420 4546 4920 0000 0000 BOOTX64 EFI ....
000006b0: 0000 0000 0000 0000 0000 0200 0002 0000 ................
000006c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000006d0: 1a00 0000 0010 0000 1a00 0000 f000 0000 ................
000006e0: 0000 0000 0000 0000 0000 0000 2000 0000 ............ ...
000006f0: 488b 4a40 488d 1505 0000 00ff 5108 ebfe [[email protected]](/cdn-cgi/l/email-protection)...
00000700: 4400 6f00 6e00 65 D.o.n.e
```
Boot:
```
$ qemu-system-x86_64 -bios OVMF.fd -nographic -drive file=disk.bin,format=raw
BdsDxe: failed to load Boot0001 "UEFI QEMU DVD-ROM QM00003 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Secondary,Master,0x0): Not Found
BdsDxe: loading Boot0002 "UEFI QEMU HARDDISK QM00001 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
BdsDxe: starting Boot0002 "UEFI QEMU HARDDISK QM00001 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
Done
```
There's way too much to explain in a single answer, so here's a [.zip](https://drive.google.com/file/d/1ZGFAVLGNguu2EXbYOiFvtdhl7Gybaqia/view?usp=sharing) of everything in my working directory, and here's the final .asm:
```
[bits 64]
; Creates a non-partitioned disk image with no MBR/GPT, just FAT12.
; (UEFI specs req. implementations to support FAT12, FAT16, and FAT32 ESP's,
; although there might be smaller partition formats for certain
; implementations).
; FAT12 appears to be optimal.
; Resources:
; https://wiki.osdev.org/FAT
; https://wiki.osdev.org/UEFI
; https://wiki.archlinux.org/title/EFI_system_partition
; https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system
; https://uefi.org/sites/default/files/resources/UEFI_Spec_2_10_Aug29.pdf
; https://archive.vn/w01DO#selection-265.0-265.44
; https://wiki.osdev.org/PE
; https://learn.microsoft.com/en-us/windows/win32/debug/pe-format
; https://johv.dk/blog/bare-metal-assembly-tutorial
; https://github.com/tianocore/edk2
; https://retrage.github.io/2019/12/05/debugging-ovmf-en.html
; https://edk2-docs.gitbook.io/edk-ii-build-specification/
; https://uefi.org/sites/default/files/resources/PI_Spec_1_6.pdf
; As long as OVMF boots this, we're good.
; Layout:
; - Reserved sectors (1 boot sector, everything else opt.)
; - FAT region (1 FAT * 1 sector per fat = 1 sector)
; - Root directory region (1 sector)
; - Data region (1 sector)
; Now, in a golfing view: whats the absolute smallest this image can be?
; - The minimum SectorSize recognized by OVMF is 512 bytes.
; - I have tried merging the FAT into the boot sector, and certain forensics
; tools can read the image just fine, but OVMF can't as it requires that
; ReservedSectors != 0.
; - OVMF requires a full, dedicated directory for the root directory, and will
; only read it right where it should be, after the FAT. This puts the total to
; 3 sectors so far.
; - It does not look like directories can point to cluster 0, meaning we need
; at least 1 sector for data-- now 4 sectors.
; A lot of the boot sector is intended for old BIOS bootloader code, but
; because we're using UEFI, we can fill most of it with zeros.
boot_sector:
times 11 db 0x00 ; Ignored by OVMF
; DOS 2.0 BPB
; OVMF requires a sector size within the range [512, 4096].
; See edk2/FatPkg/EnhancedFatDxe/Fat.h:63 for more info.
dw 512 ; Bytes per sector (512, optimal value)
; Need at least one sector per cluster (duh)
; Volume->FirstClusterLba is fixed to be directly after the root directory
; sector(s), so there's no weird bug that you could get by setting this to
; zero or -1. See edk2/FatPkg/EnhancedFatDxe/Init.c:316 for more info.
db 1 ; Sectors per cluster (1, optimal value)
; Can't merge sectors as if ReservedSectors == 0, OVMF returns
; EFI_UNSUPPORTED. This is due to a check in the code that assumes this is
; not a FAT volume if ReservedSectors is 0.
; See edk2/FatPkg/EnhancedFatDxe/Init.c:250 for more info.
dw 1 ; Reserved sectors (1, optimal value)
; Just like ReservedSectors, OVMF returns EFI_UNSUPPORTED if NumFats is
; zero. See edk2/FatPkg/EnhancedFatDxe/Init.c:250 for more info.
db 1 ; # of FATs (1, optimal value)
; OVMF returns EFI_UNSUPPORTED if RootEntries is zero and the volume is
; not FAT32. See edk2/FatPkg/EnhancedFatDxe/Init.c:285 for more info.
; Furthermore, OVMF assumes that the root directory entries will take up a
; fixed number of sectors, so any value from 1 to 16 inclusive will equal
; a single full sector. See edk2/FatPkg/EnhancedFatDxe/Init.c:312 for more
; info.
; 16 entries * 32 bytes per entry = 512 bytes, 1 sector.
dw 16 ; # of root directory entries (16, optimal value)
; If Sectors and LargeSectors (which we are not using) are both zero, OVMF
; returns EFI_UNSUPPORTED. See edk2/FatPkg/EnhancedFatDxe/Init.c:250 for
; more info.
; OVMF will, understandably, fail to properly read the volume if this is
; not just the actual value that it should be.
dw 4 ; Total logical sectors (4)
db 0 ; Ignored by OVMF
; If SectorsPerFat is zero, OVMF assumes that this volume is FAT32. FAT32
; requires a whole lot more sectors of random information, so we can't use
; it here.
; See edk2/FatPkg/EnhancedFatDxe/Init.c:239 for more info.
dw 1 ; Sectors per FAT (1, optimal value)
times 512 - ($ - boot_sector) db 0 ; Boot code + BIOS signature
; Sector 2: The File Allocation Table
; Since we're using FAT12, things get a little difficult in NASM.
; Two entries are 24 bits = 3 bytes, but each entry is stored a little
; awkwardly. See Wikipedia for more info.
; 0b111111111111000000000000
; Split
; 0b11111111 0b11110000 0b00000000
; Reverse byte order (little endian)
; 0b00000000 0b11110000 0b11111111
; Table index 0 is the FAT ID (equal to BPB_Media with high bits 1), and index
; 1 is the end-of-chain indicator (0xFFF)
; However, setting them both to zero results in no difference to OVMF.
file_allocation_table:
; FAT ID (0), EOC (0), Cluster 2 (EOC)
db 0x00, 0x00, 0x00, 0xff, 0x0f, 0x00
; Fill rest of table with zero bytes
times 512 - ($ - file_allocation_table) db 0
; Sector 3: Root directory region
; Each entry is 32 or 64 bytes, an 8.3 format chunk followed by an optional
; long file name chunk. Here we will just use 8.3.
; There is only one file in the root directory-- EFI.
; (/EFI/BOOT/BOOTX64.EFI)
root_dir_region:
db "EFI " ; 8.3 file name (11 chars, space padded)
db 0x10 ; Attributes (DIRECTORY)
times 14 db 0 ; Ignored to boot by OVMF
dw 2 ; Low 16 bits first cluster number (cluster 2)
times 4 db 0 ; Ignored to boot by OVMF
; Fill rest of region with zero bytes
times 512 - ($ - root_dir_region) db 0
; Since indices 0 and 1 of the FAT are reserved, the first cluster is really
; cluster 2. Using some tricks, we can store all of the data we need in this
; single cluster.
; This cluster is:
; - The contents of /EFI/ (a listing of directories and files,
; including BOOT)
; - The contents of /EFI/BOOT/ (a listing of directories and files,
; including BOOTX64.EFI)
; - The contents of BOOTX64.EFI (the file to be booted)
cluster_2:
; Once OVMF reads an entry with a zeroed first byte, it stops reading.
; Due to how much of a pain OVMF is, the best way to golf this is to
; squeeze in the entries where they fit in the EFI and hope for the best.
; MZ header
; Looks like it's required, even though parts of edk2 are able to handle PE
; executables that don't have an MZ header.
; EDK II Build Spec. doesn't say much other than "All EFI images must be
; formatted PE32/PE32+/COFF." The UEFI specs seem to require the MS-DOS
; stub.
; There's also extensive support for Terse Executable images (see UEFI
; PI specs section 15), but it appears that won't work here either.
mz_hdr:
db "MZ"
times 30 db 0
; ./BOOT/, but also MZ header part 2.
; Here a bit of a hack is employed to save a sector:
; If we say that BOOT occupies cluster 2, we can put BOOTX64.EFI right
; in this same sector as it refers back to this.
db "BOOT " ; 8.3 file name (11 chars, space padded)
db 0x10 ; Attributes (DIRECTORY)
times 14 db 0 ; Ignored to boot by OVMF
dw 2 ; Low 16 bits of first cluster number (cluster 2)
; edk2/BaseTools/Source/C/Common/BasePeCoff.c for some details on how
; e_lfanew is read
dd pe_hdr - cluster_2 ; e_lfanew
; PE header
pe_hdr:
dd "PE" ; mMagic (0x00004550)
dw 0x8664 ; mMachine (IMAGE_FILE_MACHINE_AMD64)
dw 1 ; mNumberOfSections (1)
dd 0 ; mTimeDateStamp (unused)
dd 0 ; mPointerToSymbolTable (unused)
dd 0 ; mNumberOfSymbols (unused)
dw popt_hdr_len ; mSizeOfOptionalHeader (required to be correct value)
dw 0x222e ; mCharacteristics (IMAGE_...)
; PE optional (required by OVMF) header
; Setting popt_hdr_len to zero results in RETURN_UNSUPPORTED, so there
; doesn't seem to be any way that the code section header can be merged
; with the optional header.
pe_opt_hdr:
dw 0x20B ; mMagic (PE32+ 64 bit)
db 0 ; mMajorLinkerVersion (unused)
db 0 ; mMinorLinkerVersion (unused)
dd 0 ; mSizeOfCode (unused)
db "A", 0, 0, 0 ; mSizeOfInitializedData (used to keep FAT entries going)
dd 0 ; mSizeOfUninitializedData (unused)
dd 0x1000 ; mAddressOfEntryPoint (0x1000)
dd 0x1000 ; mBaseOfCode (0x1000)
dq 0x140000000 ; mImageBase (OVMF ignores this, but with PIC who cares)
dd 0x1 ; mSectionAlignment (1 byte)
dd 0x1 ; mFileAlignment (1 byte)
db "B", 0 ; mMajorOperatingSystemVersion (used to keep FAT going)
dw 0 ; mMinorOperatingSystemVersion (unused)
dw 0 ; mMajorImageVersion (unused)
dw 0 ; mMinorImageVersion (unused)
dw 0 ; mMajorSubsystemVersion (unused)
dw 0 ; mMinorSubsystemVersion (unused)
dd 0 ; mWin32VersionValue (unused)
dd 0x4000 ; mSizeOfImage (must be weirdly large)
dd all_hdrs_len ; mSizeOfHeaders
dd 0 ; mCheckSum (unused)
dw 0xa ; mSubsystem (EFI)
dw 0 ; mDllCharacteristics (unused)
db "BOOTX64 " ; mSizeOfStackReserve (entry BOOTX64.EFI)
db "EFI", 0x20, 0, 0, 0, 0 ; mSizeOfStackCommit (BOOTX64 name + attr)
db 0, 0, 0, 0, 0, 0, 0, 0 ; mSizeOfHeapReserve (BOOTX64 unused)
db 0, 0, 2, 0, 0, 2, 0, 0 ; mSizeOfHeapCommit (BOOTX64 unused, clst, sze)
dd 0 ; mLoaderFlags (unused)
dd 0 ; mNumberOfRvaAndSizes (unused)
popt_hdr_len: equ $ - pe_opt_hdr
; Code section (only section)
code_sec_hdr:
times 8 db 0 ; mName (unused)
dd code_sec_len ; mVirtualSize (small as possible)
dd 0x1000 ; mVirtualAddress (0x1000)
dd code_sec_len ; mSizeOfRawData (small as possible)
dd code_sec-cluster_2 ; mPointerToRawData
dd 0 ; mPointerToRelocations (unused)
dd 0 ; mPointerToLinenumbers (unused)
dw 0 ; mNumberOfRelocations (unused)
dw 0 ; mNumberOfLinenumbers (unused)
dd 0x20 ; mCharacteristics (rx)
all_hdrs_len: equ $ - mz_hdr
; OVMF REFUSES to load sections with mPointerToRawData before mSizeOfHeaders,
; and falsifying mSizeOfHeaders results in the EFI file just not loading.
; Overall the PE loader seems pretty robust; see
; edk2/MdePkg/Library/BasePeCoff.c for more info.
code_sec:
; Output "Done" and loop forever.
; In RDX: EFI_SYSTEM_TABLE*
; Get EFI_SYSTEM_TABLE->ConOut (EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL*)
mov rcx, [rdx+64]
; Get EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL->OutputString()
; <inlined into call directive>
; OutputString(rcx this, rdx string)
; `this` is already in RCX
lea rdx, [rel str]
; 32 bytes of shadow space is supposed to be allocated, but OVMF runs
; without it.
call [rcx+8] ; Call print
; jmp $
db 0xeb, 0xfe
; "Done" + NUL in UTF-16LE
; echo -ne "Done\0" | iconv -f UTF-8 -t UTF-16LE |
; hexdump -e ' 1/1 "0x%02x, " ' -v
; The last three bytes are 0x00, and since we are at the end of file we can
; let OVMF fill in the rest.
str: db 0x44, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x65
code_sec_len: equ ($ - code_sec) + 3
; OVMF fills the rest of the sector with zero bytes, meaning the smaller
; the .efi file is, the smaller the image is.
```
At this point, I think this is pretty close to the lower bound for OVMF without using any major bugs or exploits.
[Answer]
# 16897 bytes (33+1 512-byte blocks), OVMF
Reproduce with
```
base64 -d <<\EOF | lz4 -d > a
BCJNGGRApyIJAAD0Des8kG1rZnMuZmF0AAIEAQABEABEAPgBABAAAgABAPlSgAApzas0Ek5PIE5BTUUgICAgRkFUMTIgICAOH75bfKwiwHQLVrQOuwcAzRBe6/Ay5M0WzRnr/lRoaXMgaXMgbm90IGEgYm9vdGFibGUgZGlzay4gIFBsZWFzZSBpbnNlciAA9B5mbG9wcHkgYW5kDQpwcmVzcyBhbnkga2V5IHRvIHRyeSBhZ2FpbiAuLi4gDQqjAA8CAP8l/w1Vqvj//wjw//9vAAfw/wmgAAvw/w3gAA8AAf8PUwH/JQ8CAJwwRUZJ0QMAAgCwEAAfiw2eVZ5VAAAIABEDygDzBEFOAHYAVgBhAHIADwBwcwAAAP8BAAIKAGBOVlZBUlM/AFMgAAAAkkAAAAgAAT8ADwIA/4/wGxYAAABDAHUAcwB0AG8AbQBNAG8AZABlAAAADOx2wChwmUOgcnHuXESLnxACEAHQAfMYDgAAAGMAZQByAHQAZABiAAAAbuW+2dx12Um017U0IQ9jeicAAAAEBADwCRoAAABWAGUAbgBkAG8AcgBLAGUAeQBzAFgC8wQAAODkc5DsYG5LmQNMIjwmDzwjZQDzDwEIAAAATQBUAEMAAAARQHDrAhTTEY53AKDJaXI7B1sAAI4A8BkUAAAAQQB0AHQAZQBtAHAAdAAgADEAAABFSTJZROwNTLHNnbE53wcMvgAQGZQADAIAAEUAAQIAgEF0dGVtcHQgPgAPAgB9L7wMkgB9DwIAfhDo4gEPAgD/BQXkAg8CAP8JD0kEAR8ySQQZBTALBEkEAD4ADwIAfQ9JBP//ABEuuwkBAgAPAAoCFi4hAAsgAALbAkFCT09UPgAAIAAjkIwACgAIAA9tBwEPAgD/////////hgbfBwzgBwLABw8ACAcCcA0AAAhAWDY0IEgSCgAITwUAlhfwB/////////+GDAIAQE1akADKBwDuBwDUGRO4IQATQAgADwIACfEDgAAAAA4fug4AtAnNIbgBTM0h8x2wcHJvZ3JhbSBjYW77HfMIYmUgcnVuIGluIERPUyBtb2RlLg0NCiRZAHJQRQAAZIYGDgDxABAAADsAAADwACYiCwICI4MeBOMdExAEADEAlGotAAAQABICuAAAAgARBS0AQgAAAHAdGDOPBQE7AACYGgQ8AAACAAA5AAgQAAMSACFQAGwYIgBgCxQFAgA/MAAAfRdRkC50ZXh0AAAAWHkAAKMAAE8UAJUBBwIAwSAAUGAucmRhdGEAAEABANsAACgAAz8BBAIAYkAAUEAucCgAAbwAEzAoAABVGQcCAGJAADBALngoAAEbAAD1AQBQAAI5AQUCAAEoABJlKAAAkBkjAFBQAAFdAAYCAAEoABJpKAAATxUATAEBlwEAMhoHAgBHQAAwwA8ADwIA/2vwAkiD7DhIiUwkMEiJVCQoSItEBQCQQEBIi0AISItMDQDwBUlASI0V1Q8AAP/Q6fv///9mDx9ELAQCAgAEvQECDgAGEAAPAgD/lvEGSABlAGwAbABvACwAIAB0AHIAYQBjDB4zcgAuQgUPAgD/y0AQAAAycAYA/AUPAgD/4W8BBAEABGL5Af/hBwIAQGc9rmMPACIyUCsgAC8gAAQAkChQAAAsUAAAMPAJAJwLAAgA8AIAbWFpbi5kbGwARWZpTWFpbjoADwIA////qgR4DgACAAD0AyADAbciAAoAQBh/uOQIACQAACQOAAIAAJMOEQOeJwACAEAxf4g3EgAkAACYDgACAABDDjADASILAIEAAAA8NQdcBQoABJQOAAIAAHQQIAMBQQ4ACgBCAFTox8UOcEBmZWF0LjCyDhAATgwZA2cEoQEAIAACAC5maWyiKJEAAAD+/wAAZwGUBAHEBAgCAACaAAAoDwCQAAAEACAAAF8oAAIAAA4AAAQAIAAA7gATSHUoAhIAEEEXAAkSAAH3BDAAlGqQAAIkAB1cWgAAdxAAAgAGJAAQiA8AGBASABChEgAhACDYAAJIABG7uhAIJAAR1yQAAOoABCQAEOkPAAmQABH7EAAIJAAQCy8AA0wAAloALBkBogAQPCQACZAAEFQSAAlaABlmEgBxX19kbGxfXyQABtgAE3YkAAYSABGLEgAIIAEQmhIACWwAIrABFBAA5gECogAdvKIAENo2AAMzEAIkAFnnAQAAOKIAE/UkAAA2AQIkABIBBwAQABkAAgsAEhEHAAcSACwjAkgAEzIkAAbGABBFEgAYAhIAIlgCRAIGJAAobQLGAFNfX2VuZCABBn4ALHsCUgIQiVoAJwAQ+AERohIACDYAILQC7AIIbAAdwiQAE88SAAaQAB3nEgAs+AL4ASEKA9cAB34AECZpAAkSACw+AzYAE2AkAALYAPAWcAMAAF9fX1JVTlRJTUVfUFNFVURPX1JFTE9DX0xJU1RfXwBfX/kRYV9zdGFydA8AVl9EVE9SHgBHX3Rscx4A8wdJbWFnZUJhc2UAX19ydF9wc3JlbG9jIgAATQDxA2xsX2NoYXJhY3RlcmlzdGljc1YAcHNpemVfb2ZKAIJja19jb21taW8AChkAcXJlc2VydmUzAPEIbWFqb3Jfc3Vic3lzdGVtX3ZlcnNpb24cAHBfY3J0X3hsTwAEtwABEgAfaRIAAALtAUNfX2JzpwACQgAPFQEHMUVORCMABJsASGhlYXCzAAJ9AB1wawATcFgCqV9fbWlub3Jfb3O0ABBpOwFCX2Jhc98AQHNlY3TPAIJhbGlnbm1lbg8BNUlBVEYAD6IABwBkAAG3AQTcABlDtAEA6gAEGgACrQAVY1UABBAAB/EBCj0ACdYBIGl66QEAuAULqAACnQEL4gAAvQAGWAAKSAIJTQEI5wECkQAXdE4BBvMBAOgAAYECBM4AAncAAkoBCBACsmxvYWRlcl9mbGFncAIIxgA1ZW5klAEGXAAIPwACsAEOVwAPggEHBCQCBL4AAqEAAZ8DDwIAgAAOBA8CAP8OAPoWDJIwHzNJLBkDegUGSSwAPgAPAgB9D0ks//8ADwIAGw9JBP8mHzRJBBkAAA0BAgAEkjAAPgAPAgB9D0kE////Zx81SQQZAG0PAQIABEkEAD4ADwIAfQ9JBP8gUAAAAAAAAAAAAHtyWAQ=
EOF
```
Boots as expected:
```
$ qemu-system-x86_64 -enable-kvm -bios /usr/share/ovmf/OVMF.fd -nographic -drive file=a,format=raw
BdsDxe: failed to load Boot0001 "UEFI QEMU DVD-ROM QM00003 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Secondary,Master,0x0): Not Found
BdsDxe: loading Boot0002 "UEFI QEMU HARDDISK QM00001 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
BdsDxe: starting Boot0002 "UEFI QEMU HARDDISK QM00001 " from PciRoot(0x0)/Pci(0x1,0x1)/Ata(Primary,Master,0x0)
Hello, tractor.
^AxQEMU: Terminated
```
Obtained with
```
$ for i in $(seq 100); do truncate -s $((512 * i)) a && mkfs.fat -af1 -F12 -h0 --mbr=no -r16 -S 512 -R 1 -b 0 --invariant a && break; done 2>&1 | sed 'N;s/\n/\t/' | uniq -c
6 mkfs.fat: Attempting to create a too small or a too large filesystem mkfs.fat 4.2 (2021-01-31)
61 mkfs.fat: Too few blocks for viable filesystem mkfs.fat 4.2 (2021-01-31)
1 mkfs.fat 4.2 (2021-01-31)
$ ls -l a
-rw-r--r-- 1 nabijaczleweli users 34816 Dec 30 02:35 a
# mount -o noatime a a.d
# mkdir -p a.d/EFI/BOOT/
# cp uefi-simple/main.efi a.d/EFI/BOOT/BOOTX64.EFI
# umount a.d
$ truncate -s 16897 a
```
Why 16897? The first all-zero block is 31, so I iterated on `for f in $(seq 31 68); do dd count=$f <a.bkp >b; st -e qemu-system-x86_64 -enable-kvm -bios /usr/share/ovmf/OVMF.fd b -nographic; done`, and the first one that booted to the image was 34(\*512=17408). Then I tried to trim it back even more, and having just the first byte of block 34 is sufficient, so 17408-511=16897.
I'm assuming this is due to QEMU rounding the block count up with standard semantics, and OVMF needing to "see" the entire `\EFI\BOOT\BOOTX64.EFI`.
Seeing as these are disk images, byte counts make little sense. Judge this as you wish.
The only limiting condition here is the bootable file which has huge swaths of empty space:
```
$ wc -c main.efi
6038 main.efi
$ size main.efi
text data bss dec hex filename
211 20 0 231 e7 main.efi
```
.text EfiMain is a whole of 56 bytes. (Yes, it's possible to produce a 5490-byte executable by getting rid of the print, as well as 4096/3584-byte executables by `strip --strip-all` resp., the minimum size is the same. I maintain that making a pathologically smaller PE would probably work to shrink this method, but this is not my area of expertise, so who knows.)
main.efi was obtained by building <https://github.com/utshina/uefi-simple/blob/e02a105b2d63cf8a116fa64600b6755d625ced28/main.c>:
```
#define IN
#define EFIAPI
#define EFI_SUCCESS 0
typedef unsigned short CHAR16;
typedef unsigned long long EFI_STATUS;
typedef void *EFI_HANDLE;
struct _EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL;
typedef
EFI_STATUS
(EFIAPI *EFI_TEXT_STRING) (
IN struct _EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *This,
IN CHAR16 *String
);
typedef struct _EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL {
void *a;
EFI_TEXT_STRING OutputString;
} EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL;
typedef struct {
char a[52];
EFI_HANDLE ConsoleOutHandle;
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut;
} EFI_SYSTEM_TABLE;
EFI_STATUS
EFIAPI
EfiMain (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Hello, tractor.\n");
while(1);
return EFI_SUCCESS;
}
```
with clang trunk as `cc --target=x86_64-w64-mingw32 -shared -nostdlib -mno-red-zone -fno-stack-protector -Wall -e EfiMain main.c -o main.dll; objcopy --target=efi-app-x86_64 main.dll main.efi`, likewise adapted from instructions in the linked.
] |
[Question]
[
## Task
The input consists of a JSON object, where every value is an object (eventually empty), representing a directory structure. The output must be a list of the corresponding root-to-leaf paths.
Inspired by [this](https://stackoverflow.com/questions/71479690/turn-dictionary-values-into-paths/71480973?noredirect=1#comment126341789_71480973) comment on StackOverflow.
### Input specifications
* You can assume that that the input always contains a JSON object.
* The input can be a empty JSON object (`{}`); in this case the output must be a empty list.
* You can assume that the names/keys contain only printable ASCII characters, and they do not contain `\0`, `\`, `/`, `"`, `'`, nor ```.
* You can assume each JSON object does not contain duplicate names/keys.
### Input format
The input can be:
* a string;
* a dictionary or an associative array in a language of your choice;
* a list or array of tuples, where each tuples contains the name/key and the value (which is itself a list of tuples).
### Output specifications
* There is no need to escape any character.
* You can use as directory separator either `/` or `\`, but you cannot have a mixed use of both (e.g. `a/b/c` and `a\b\c` are both valid, but `a/b\c` and `a\b/c` are not).
* Each path *can* have a leading and/or trailing directory separator (e.g. `a/b`, `/a/b`, `a/b/`, and `/a/b/` are equally valid).
* If you output a newline-separated list, the output can have a trailing newline.
* ~~The paths must be in the same order of the input.~~
## Test cases
Input 1:
```
{
"animal": {
"cat": {"Persian": {}, "British_Shorthair": {}},
"dog": {"Pug": {}, "Pitbull": {}}
},
"vehicle": {
"car": {"Mercedes": {}, "BMW": {}}
}
}
```
Output 1:
```
animal/cat/Persian
animal/cat/British_Shorthair
animal/dog/Pug
animal/dog/Pitbull
vehicle/car/Mercedes
vehicle/car/BMW
```
Input 2
```
{
"bin": {
"ls": {}
},
"home": {},
"usr": {
"bin": {
"ls": {}
},
"include": {
"sys": {}
},
"share": {}
}
}
```
Output 2:
```
/bin/ls
/home
/usr/bin/ls
/usr/include/sys
/usr/share
```
Sandbox: <https://codegolf.meta.stackexchange.com/a/24594/73593>
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~42~~ 40 bytes (+11 penalty for "-r --stream" options)
```
select(.[1]=={})[0]|join("/")
```
[Try it online!](https://tio.run/##XY07D4MwDIR3fgXyBBL0sVZi6Y6E1KEDQlUaLGIUQCShC81vT0voS/Vkn@@7a0fnNErkJtqU@yrLZhuXu@reDtRHsIXYuTkInwOsp45JOITr7TXOzCJAgUoT65fdJiEcFRnS4nISgzKCkfIPm3zBemhWcGreUEHmOkm5Wr3zBcANBXGJ/9U@FXJUHGvUn@78/BsRWJcql6baKGTdAw "jq – Try It Online")
The `--stream` option converts JSON to an alternate format where each leaf node is an element in a list. Those entries are also lists, with two fields, the first of which is a list of the keys representing the path. The second entry (for out test cases) is an empty dictionary.
So the code selects every list entry where the second entry is a an empty dictionary, them assembles the list of keys in the first entry into the output we want.
```
select(.[1]=={})[0] - pick "leaf" node entries only (1st field only)
|join("/") - join the list of string w/ a "/" separator
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 55 bytes
*Thanks to @pxeger for suggesting to use `for(k in o)`*
Expects an object. Prints the results with a leading `/`.
```
f=(o,p,q)=>{for(k in o)f(o[q=k],[p]+'/'+k);q||print(p)}
```
[Try it online!](https://tio.run/##fY/Pb8IgFIDv/SsaLkJk8bps6Q67m5js4MGYBSmVtyJQoE0W7d/eKWyu1UROvB/f9977Yh3z3IENT93zMFQFNtTShhRvx8o4XOegc0MqbDZNUW/pxm7ns8VsXpPX5nSyDnTAlvRDhY9Zfn6IaTgwhV7yFMccZ@GSQCvhPDB9@fc0R@8OAnj5@SGNC5KBi4We/oOl2Sew3f9BKwi7VqnUGjt/AdQJCVyJ29HRipbCcVEKf529XI8VWU@ydAzJsustO9BTm0r8ZKw0B5GsKW69m0K3ljvTyBZroLlqS3EP@e8HlJfMidF655OGHw "JavaScript (V8) – Try It Online")
---
# [JavaScript (V8)](https://v8.dev/), 63 bytes
Expects an object. Prints the results with a leading `/`.
```
f=(o,p)=>Object.keys(o).map(k=>f(o[k],[p]+'/'+k))+''||~print(p)
```
[Try it online!](https://tio.run/##fY89b4MwEEB3fgXygq3QdK0qkaF71EgdOkRRZcwRXzDYsg1S1NC/ThPcppBI9eT7eO/uDrzjTlg0/qF7GoYyozo1LFu95gcQflnB0VHNljU3tMpWJdXbapduzW6RPCaLirFFkpxOX8Zi46lhQ0k/o/j8CG@w5oo8xyEec4L7S4JswDrkzeXfpzF5sejRyY83qa2XHO1Y6NM/sND7ALb7X2iDPm@VCq1j5w9AOpAoFNyOHq1kDVZAAe46e/0@VUQ9i8ItLIqut@TYzG0q8LOxUtcQrCFunZ1Dt5Y708Q21rARqi3gHnLHfygnuYXJeueThm8 "JavaScript (V8) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 67 bytes
```
map/}/?/{/&&say($s)..$s=~s|[^/]+/$||:($s.=s/"//gr."/"),/{?}|".+?"/g
```
[Try it online!](https://tio.run/##fY9Ba4MwFMfvfgp5SFmp5m2HXgpF2GE3obDDDmMbqQYTiFESLRTNPvqy1nSbtrCc8v7v/X4vaZiWa@cq2qDFFHtcLAw93kVmSUhktp9meH3HtxVGw7A5pWRrEBBLTQBhGWOf2gHIKgUsneuD8HSAKlFRCZvQ12OW0/YcwI5pI6g6320cwqMWrTD845nXuuVU6LFh4z@wqEsPduUPtBPtvpPSj46TFwAOjItcsuvVoxUypnNWMPO7O3uZKgIbBJcP7IWaK6SHZrt4XTGv8nVn9By6ttyYJraxJ1Quu4LdQub4D2U41WzyvMB@1U0ramVc8gTgkuywJg/3LlHyGw "Perl 5 – Try It Online")
[Answer]
# [Python](https://www.python.org), 52 bytes
```
def f(d,s=""):[f(d[x],s+"/"+x)for x in d]or print(s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TVJS0xTSNFJ0im2VlDStooHM6IpYnWJtJX0l7QrNtPwihQqFzDyFlFggq6AoM69Eo1gTqvdkmkY1lwIQKCVl5ilZKUA4YIGcYhC_FixQqwNRlJGfmwoWhfJLi4tQNaGbgmESkmlgucy85JzSlFRMTcWVeHQVZyQWpSI5j6sW6iFYoAAA)
Takes input as a dictionary, and outputs to STDOUT.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;”/;ⱮßW⁹?}ʋ/€Ẏ
```
A monadic Link that accepts a list of lists where each is a key-value pair where the key is a list of characters and the value is a, possibly empty, list of the same type\* and yields a list of lists of characters - the paths.
\* i.e. uses the option *a list or array of tuples, where each tuples contains the name/key and the value (which is itself a list of tuples)*.
**[Try it online!](https://tio.run/##y0rNyan8/9/6UcNcfetHG9cdnh/@qHGnfe2pbv1HTWse7ur7f7g98v//6GilxLzM3MQcJR0FIDs5sQTCCEgtKs5MzANxYmOBhJJTUWZJZnFGfHBGflFJRmJmEUQKIpmSnw7VVpqO0BKQWZJUmpMDUwgRLEvNyEzOSYVZVwRh@KYWJaempBYj2ecbjtAYCwA "Jelly – Try It Online")**
### How?
```
;”/;ⱮßW⁹?}ʋ/€Ẏ - (recursive) Link: list, J
€ - for each key-value pair in J:
/ - reduce by:
ʋ - last four links as a dyad - f(Key, Value)
”/ - '/' character
; - (Key) concatenate ('/')
} - use right argument, Value with:
? - if...
⁹ - ...condition: chain's right argument, Value
ß - ...then: call this recursive Link with that (non-empty) Value
W - ...else: wrap that (empty) Value in a list -> [[]]
Ɱ - map across the recursive call result (or the [[]]) with:
; - concatenate
Ẏ - tighten
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0 -n0175`, 36 bytes
```
pop@;;push@;,/\w+/g;$,="/";/{/&&say@
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoicG9wQDs7cHVzaEA7LC9cXHcrL2c7JCw9XCIvXCI7L3svJiZzYXlAIiwiYXJncyI6Ii1NNS4xMC4wXG4tbjAxNzUiLCJpbnB1dCI6IntcbiAgICBcImFuaW1hbFwiOiB7XG4gICAgICAgIFwiY2F0XCI6IHtcIlBlcnNpYW5cIjoge30sIFwiQnJpdGlzaF9TaG9ydGhhaXJcIjoge319LFxuICAgICAgICBcImRvZ1wiOiB7XCJQdWdcIjoge30sIFwiUGl0YnVsbFwiOiB7fX1cbiAgICB9LFxuICAgIFwidmVoaWNsZVwiOiB7XG4gICAgICAgIFwiY2FyXCI6IHtcIk1lcmNlZGVzXCI6IHt9LCBcIkJNV1wiOiB7fX1cbiAgICB9XG59XG57XG4gICAgXCJiaW5cIjoge1xuICAgICAgICBcImxzXCI6IHt9XG4gICAgfSxcbiAgICBcImhvbWVcIjoge30sXG4gICAgXCJ1c3JcIjoge1xuICAgICAgICBcImJpblwiOiB7XG4gICAgICAgICAgICBcImxzXCI6IHt9XG4gICAgICAgIH0sXG4gICAgICAgIFwiaW5jbHVkZVwiOiB7XG4gICAgICAgICAgICBcInN5c1wiOiB7fVxuICAgICAgICB9LFxuICAgICAgICBcInNoYXJlXCI6IHt9XG4gICAgfVxufSJ9)
## Explanation
A different approach to the other Perl answer. This uses the `-0175` command line flag to split the input on `}`. For each closing curly brace, `@;` is `pop`ped removing any previous path keys that aren't needed. Next all the keys (`/\w+/g` - this might be too lenient?) are `push`ed onto `@;`. Finally `$,` (which is printed between records when a list - `@...` - is `print`ed) is set to `"/"` and if `{` exists in the input, `say` is used to output `@;` (with `$,` printed between each index).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 96 bytes
```
+1`"([^"]+)":{("[^"]+":{(({)|(?<-4>})|[^{}])*(?(4)^)},)*"(?!\1/)
$&$1/
M!`"[^"]+":{}
%`^.|....$
```
[Try it online!](https://tio.run/##XY1Ba8MgGIbv/ot@pEPbriXQUxkL9B4o7LBD1yw2kfqBTUDNYBh/exa122Fe/Hy/533UwmLHp2md10DPFVzWDA6OQhzDRB0bafHyvH/1bDxXzl/YihZ0zyrmN2wFtFh85DtGsqcs35FyUf9VPVnW1Xbczicj0@SAd3jnat5Aw224TkIb5F1gN3DUaNHIzzfZays56hDPedvfIjvcEndCex2Uitv5@SUkNkoka@hAKXQjWmEe2vI9oZ44uGL4DJR5uGV/FwkbTOz@B7Br1NBGu/n@DY3kWiTpDw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
+1`"([^"]+)":{("[^"]+":{(({)|(?<-4>})|[^{}])*(?(4)^)},)*"(?!\1/)
$&$1/
```
Replace each key in turn with its path.
```
M!`"[^"]+":{}
```
List the entries whose values are empty objects.
```
%`^.|....$
```
Keep just the keys.
[Answer]
# [R](https://www.r-project.org/), ~~79~~ 73 bytes
```
f=function(L)"if"(length(L),unlist(Map(paste0,names(L),"/",Map(f,L))),"")
```
[Try it online!](https://tio.run/##PY69CsMwDIT3PoYnCwztC2TpnECgQ8eiOnIscJxiy319N2l@tvt0d5xSra5xJVrhOeoWFDulA8VR/EKmxMBZdIcf/cEsdDMRJ8qrpa7KrHdnWoAFFdS2@acx8oRh0xZlEz2lzBg3AHNPLJz96@HnJB457QaYYR73RhmPdM/yLiEcGTBf8mwDHRt7u6NkaaB8jnTPswIXt3xdfw "R – Try It Online")
Takes input as a named R `list`, i.e., `list(name=value)`, and returns a `character` (string) vector of directories.
-3 bytes thanks to pajonk.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~103~~ 88 bytes
```
function f($o,$p){($x=$o.keys|%{f $o.$_ $p/$_})
if(!$x){$p}}f($args|ConvertFrom-Json -a)
```
[Try it online!](https://tio.run/##fVFNT8MwDL3nV4Qo0FXa4A7aBQQHpEmTQOI4Za3bRKRJlaT7UJffXrJkoG6TyCl@9nv2s1u9BWM5SDkrtIGBbuf9UHWqcEIrXE2ontI27yd0N6f6/hv29nDbVzj86QrT9oGufI5ENbmhu7ynrfeBwkxtDy9abcC4N6Ob2bsNWjOWDx4hRFvmuMVznPUIh0fWQpFHnIIISHuMfQT8NBVx3UBET3FnzTnpUuVKaaQWc0IVsivhmmT3/7AsZwZG4yGfPQVPjgtVj00xJRomz0csmDsCZBk2LphKdjB5NsIJy1cfXBvHmYjG/LhpqetE7Opf0lK4dSdlKj3b1Aa4KCRcto6qZAGmgBLsX@/F11giuSHL44UIuqNbnK4VMILIZzR5wpNjlDKvTev2KZH1PkNo@AE "PowerShell Core – Try It Online")
Takes a string as a parameter
Returns a list of string with a leading `/`
Thanks [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) for shaving 15 bytes off!
[Answer]
# [Kotlin 1.6.21](https://kotlinlang.org/), 118 bytes
```
{fun f(m:Map<*,*>,s:(Any?)->Any){for((k,v)in m)if((v as Map<*,*>).size==0)s(k)else f(v){s("$k/$it")}};f(it,::println)}
```
[Try it online!](https://tio.run/##jVNdT4MwFH3nVzTNHtqFqdsjCkbfF5cY46OprMANpZC2kEzCb5@FfYEytA8t7Tncc@5tb5obAXIflRJlDCShqHaQHRUTiGeF2XlozYqHJ7lzkZ0C5B@O7SGhZ2bGiqVF7PISke60HZhJyJjAyOQ/oQ4OmbmGdfiGKw1MdpxO1P3NeVZgQCcfr0muTMJAXdgDMh3@i7d5PK1dxpO6GzCfpRDX1JwRXVzxBELBJ@qhJj2tuQr5luvpgqzf/zblXObj9a1Gru8TZM8PFj3hflpJnvExS7jUV/P5Z@yOCjIU5bZfNqx3E3ydMMVHanDK2jnnHXuItK977qJ5QNEiQG8SDPL3ddsPEcm8AzoPXO0R@/wf6SKwC62jXBGSuhUF2zcUIkIqxDQ60emNhi/u@3dUk5RyobmNVtFaEzxLb2dgMG2a@4iAcT2vUCCNkLTZt76OO4JtLLT08MF1TNoWO3yfGMNdx18N@CvqNPtv)
An anonymous function of type `(Map<*, *>) -> Unit` that takes in a recursive map of `String` to `Map<String, ...>` and prints the answer without leading or trailing slashes.
**Ungolfed code:**
```
{
// Define function f that iterates a map recursively and
// outputs its keys' paths to a sink function
fun f(m: Map<*, *>, s: (Any?) -> Any) {
for ((k, v) in m)
// Note: .size==0 is 2 bytes shorter than .isEmpty()
if ((v as Map<*,*>).size == 0)
// For an empty map, call the sink with the key
s(k)
else
// Call f again on the inner map with a wrapped sink that
// that appends the current key + "/" to the input
f(v) { s("$k/$it") }
}
// Run f for the input map, using ::println as the sink
f(it, ::println)
}
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) [1.1.0-alpha](https://github.com/dloscutoff/pip/commit/f9abeb2a7055e4140017d99dbfd01bc18be303d8) `-xp`, 23 bytes
```
@_.{a@1?'/.(\fa@1)x}MFa
```
Takes a list of tuples (i.e. two-element lists) as a command-line argument. Outputs a list of strings.
Pip 1.1 (required for both `\f` and `MF`) is not on Attempt This Online at the time of writing, but you can try it on [Replit](https://replit.com/@dloscutoff/pip). The easiest way is to exit out of the Pip REPL with `;quit` and then:
```
> ./pip.py -xpe "@_.{a@1?'/.(\fa@1)x}MFa" '[["bin"; [["ls"; []]]]; ["home"; []]; ["usr"; [["bin"; [["ls"; []]]]; ["include"; [["sys"; []]]]; ["share"; []]]]]'
["bin/ls";"home";"usr/bin/ls";"usr/include/sys";"usr/share"]
```
### Explanation
A recursive full program:
```
@_.{a@1?'/.(\fa@1)x}MFa
a Program argument (a list of pairs)
MF Map this function to each and flatten the results:
@_ The first element of the pair
.{ } Concatenated (itemwise if necessary) to:
a@1? Is the second element of the pair (a list) nonempty?
'/. If so, concatenate / (itemwise) to
(\f ) a recursive call of the main function
a@1 with the second element of the pair as the argument
x If it is empty, empty string
```
[Answer]
# Bash (sed + [ShellShoccar-jpn/Parsrs parsrj.sh](https://github.com/ShellShoccar-jpn/Parsrs/blob/master/parsrj.sh)), ~~31~~ 29 bytes
Assumes parsrj.sh is on a directory specified by PATH environment variable.
Tested with parsrj.sh `Version : 2020-05-06 22:42:19 JST`.
```
parsrj.sh -rt -kd/|sed s,/$,,
```
## Example runs on my Termux
[](https://i.stack.imgur.com/gBvfd.png)
## Explained
```
parsrj.sh -rt -kd/|
# default output for {"foo":{"bar":{}},"baz":{}}:
# $.foo.bar.
# $.baz.
# -rt to replace $ with ""
# -kd/ to replace . with /
# thus output is:
# /foo/bar/
# /baz/
sed s,/$,,
# trailing slash is removed
```
] |
[Question]
[
Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details.
The story continues from [AoC2017 Day 11](https://adventofcode.com/2017/day/11).
---
Crossing the bridge, you've barely reached the other side of the stream when you are overcome with a sense of deja-vu. "Haven't I done this already?" But before you can finish that thought, someone runs up to you, and cries "My child process has gotten lost in an infinite grid! Can you help me?"
Fortunately for them, you have plenty of experience with infinite grids, even hexagonal ones.
Unfortunately for you, this isn't your typical hex grid.
This is is [an order-4 hexagonal tiling](https://en.wikipedia.org/wiki/Order-4_hexagonal_tiling). In [your typical hexagonal tiling](https://en.wikipedia.org/wiki/Hexagonal_tiling) three tiles meet at every vertex:
[](https://i.stack.imgur.com/F9Egy.png)
*Image by [wikipedia user watchduck](https://commons.wikimedia.org/wiki/User:Watchduck)*
The order-4 hexagonal tiling has *4* tiles around every vertex. In terms of geometry this means it's embedded in hyperbolic space.
[](https://i.stack.imgur.com/ohbAB.png)
*Image by Anton Sherwood*
In order to traverse this hyperbolic space and rescue the child you receive a list of instructions. Each instruction consists a number from `0-5`, with `0` move to the next tile straight ahead and each successive number meaning to take move to the next tile clockwise from the last. So as an example `3` would be the tile right behind you.
Given this path you want to figure out how far the child is from your current position.
So your task in this challenge is to take a path of instructions as input and output the number of steps in the shortest path to the same
## Strategies
There are three ways to simplify paths we can use. The first is to remove backtracks. If you ever see a `3` that's just a step back to where you were the step before. So you can remove the `3` and that step. The one hitch is that when you get back you are facing the opposite direction so you need to flip the instruction after.
So if your sequence is:
```
..., y, 3, z, ...
```
It can be rewritten as:
```
..., y+3+z mod 6, ...
```
There's one special case if your sequence ends in a `3`:
```
..., x, 3] = ...]
```
The second method you to take alternative paths around corners.
For example in the regular square grid these two paths are the same length:
```
B--D B D
| == |
A C A--C
```
Since both tilings are order 4 we can actually use a version of this rule.
```
..., x, 2, y ... = ..., x+1 mod 6, 4, y+1 mod 6, ...
```
And again there's an edge case when the `2` or `4` is the last step.
```
..., x, 2] = ..., x+1 mod 6, 4]
```
Note that these equivalences go both ways.
You can always find the shortest path by applying a combination of these two rules.
## Worked examples
### `[0,0,0,0]`
The second move can't be applied and the first one can only be applied backwards.
This is the shortest possible path to the destination, so the answer is the number of steps `4`.
### `[2,2,2,2]`
We can apply the second rule right of the bat to get `[2+1,4,2+1,2] = [3,4,3,2]`.
Now we can use the first rule with the `3` to get `[3,3]`, and the first rule again gives us `[]`.
The answer here is `0` this is a loop.
### `[2,0,2,0,2,0,2,0]`
Ok this is just the last one except we take an extra step forward after each turn.
This should just make a bigger version of the same thing right?
Nope, hyperbolic space is tricky.
We can apply rule `2` a bunch but it never really goes anywhere.
This is actually the shortest path to the destination.
The answer is `8`.
### `[2,1,2,1,2,1,2,1,2,1,2,1]`
This one forms a big hexagon.
```
[2,1,2,1,2,1,2,1,2,1,2,1]
[2,1,2,1,2,1,2,1,2,2,4,2]
[2,1,2,1,2,1,2,1,3,4,5,2]
[2,1,2,1,2,1,2,2,5,2]
[2,1,2,1,2,1,3,4,0,2]
[2,1,2,1,2,2,0,2]
[2,1,2,1,3,4,1,2]
[2,1,2,2,1,2]
[2,1,3,4,2,2]
[2,2,2,2]
[2,3,4,3]
[2,3]
[]
```
It's a loop so the answer is `0`.
### `[0,2,1,2]`
This isn't a loop but it can be reduced.
```
[0,2,1,2]
[1,4,2,2]
[1,5,4,3]
[1,5]
```
There's nothing we can apply to `[1,5]` so the answer is `2`.
## Testcases
```
[0,0,0,0] -> 4
[2,2,2,2] -> 0
[2,0,2,0,2,0,2,0] -> 8
[4,0,4,0,4,0,4,0] -> 8
[2,1,2,1,2,1,2,1,2,1] -> 2
[4,5,4,5,4,5,4,5,4,5] -> 2
[2,1,2,1,2,1,2,1,2,1,2,1] -> 0
[4,5,4,5,4,5,4,5,4,5,4,5] -> 0
[0,2,1,2] -> 2
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 82 bytes
```
s/./"bc"x($&+3)."ab"/ge;1while s/(.)\1//+s/(b|cac)a/a$1/+s/(cbcbca?)b/b$1/;$_=y;a;
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fKSlZqUJDRU3bWFNPKTFJST891dqwPCMzJ1WhWF9DTzPGUF9fG8hKqklOTNZM1E9UMQTzk5OAMNFeM0k/CShirRJvW2mdaP3/v4GRodG//IKSzPy84v@6BQA "Perl 5 – Try It Online")
### How it works
Draw right triangle \$ABC\$, where \$A\$ is the center of your initial tile, \$B\$ is the vertex of the edge behind you on your right, and \$C\$ is the center of the edge behind you. The group of symmetries of the tiling are generated by the reflections \$a, b, c\$ over the sides \$BC\$, \$CA\$, \$AB\$ of this triangle, which satisfy the equations
$$a^2 = b^2 = c^2 = (bc)^6 = (ca)^4 = (ab)^2 = ε.$$
We can translate our path to a symmetry by applying \$(bc)^{n + 3}ab\$ for each step \$n\$. Conversely, any symmetry written as an even-length string of \$a, b, c\$ can be translated to a path whose length is the number of \$a\$s.
With the [Knuth–Bendix algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Bendix_completion_algorithm), we can [transform](https://sagecell.sagemath.org/?z=eJxz07NJ1EnSSbZTsFVwK0pNdS_KLy3Q0OTlcgcJKOgrRCdqaRnpKCSByWQwqZGklayppWUGZCVrJQJZJkBWolYSkGUUy8uVDdTprleUWl6UWZKZlx5fXFlckpoLMjNbLzcxOzU-OT8vLac0Na8ELAYAPO0ijQ==&lang=sage&interacts=eJyLjgUAARUAuQ==) the above equations to a rewriting system that produces a canonical representation for any symmetry:
\begin{align\*}
aa &→ ε, \\
bb &→ ε, \\
cc &→ ε, \\
ba &→ ab, \\
caca &→ acac, \\
cbcbcb &→ bcbcbc, \\
cbcbcab &→ bcbcbca.
\end{align\*}
Since these rules never increase the number of \$a\$s, we are guaranteed that the canonical representation has the minimal number of \$a\$s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 139 bytes
```
≔⟦E⁶⊕ι⟧η⊞υ⮌ηF⁶⊞ηω≔⁰ζ≔⁰εFA«≔§§ηζ⁺ειδF¬§ηδ«≔⟦⟧κWEΦ§υ±¹№μ⌕ηω⌕ημ«F¬›⌈λ⊕⌊λ≔⮌λλ⊞λ⊖LηF⁻⁶Lλ⊞λ⊖L⊞Oηω§≔η⌕ηωλ⊞κλ»§≔§κ⁰¦¹⊖Lη⊞υκ»≔⁺³⌕§ηδζε≔δζ»I⌕Eυ№ι§ηζ¹
```
[Try it online!](https://tio.run/##fVJNi8IwED23v2KOCWTB7oKXPYmLi7C6stfiIdjRBNNU0lRlF397N0kbtR4slDAf783Hm43gZlNx1baTupY7TfIFP5Axg7neGCxRWyyIpHTNQND3dNXUgjQMfvCIpkYiqHNuKwNkTCEEBYOT8/VsIwa/Awtj/lwfGksohb806cMTO9cFnq@v8GAGK9XUBBm4LhgUDp8EgmVl7zOLjipy5a7hvc9NTkIqBOLHmkll0VxRbo4l7rhFknnqadVoS0oGM6mLbg7vjlZJ@wq38p8GuSdc8LMsm5IoOtzbQure7z/oW4u789kqtJiEzSkGH3gDf6HeWeE33OWEqo7RLcPJ00c9MzxB@9D3AQ23lYkjdXRdM3cLvE09bGsfzUv6iIqvSxk5VPZ0gHg6QZXLVfSg7ltffqCnV592FxOTi@6cLunKSKfVlNeWBKBXt4kSSgaDE/Isme@ibfP8lWXs4V@v25ej@gc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Works by mapping out the grid. The starting point is `0`, then the six adjacent hexagons are numbered `1-6`, then the 24 hexagons at a distance of `2` are numbered `7-30`, then the 90 hexagons at a distance of `3` are numbered `31-120`, and so on.
```
≔⟦E⁶⊕ι⟧η
```
The edges of the starting hexagon take you to hexagons `1-6`.
```
⊞υ⮌η
```
Save a copy as the list of hexagons at a distance of `0`.
```
F⁶⊞ηω
```
Add six placeholders for the hexagons at a distance of `1`.
```
≔⁰ζ≔⁰ε
```
Start at the origin facing direction `0`.
```
FA«
```
Loop through the input steps.
```
≔§§ηζ⁺ειδ
```
Take a step in the appropriate direction.
```
F¬§ηδ«
```
If we have hit a placeholder, then...
```
≔⟦⟧κ
```
Start collecting the hexagons at the next distance.
```
WEΦ§υ±¹№μ⌕ηω⌕ημ«
```
Until all of the placeholders at the next distance have been mapped, get the edge or edges of the next hexagon that step to a mapped hexagon.
```
F¬›⌈λ⊕⌊λ≔⮌λλ
```
Ensure that the edges are listed in clockwise order. This usually needs to be descending, except for the very last hexagon to be mapped, which steps to the first and last hexagon to be mapped in the previous pass. For example, hexagon `10` steps back to hexagons `2` and `1`, `20` steps back to hexagon `4` and `30` steps back to hexagons `1` and `6`, in that order.
```
⊞λ⊖Lη
```
The next edge from this hexagon goes to the same hexagon as the last edge from the previous hexagon.
```
F⁻⁶Lλ⊞λ⊖L⊞Oηω
```
The remaining edges go to new unmapped hexagons that are further away.
```
§≔η⌕ηωλ
```
Update the map with the edges of this hexagon.
```
⊞κλ
```
Collect this hexagon in the list of hexagons at this distance.
```
»§≔§κ⁰¦¹⊖Lη
```
Fix the second edge of the first hexagon, which needs to wrap around to the last unmapped hexagon.
```
⊞υκ
```
Collect this list of hexagons in the list of hexagons for each distance.
```
»≔⁺³⌕§ηδζε
```
Work out the direction we arrived at this hexagon from, and add 3 so that we're facing away from there.
```
≔δζ
```
Actually move to this hexagon.
```
»I⌕Eυ№ι§ηζ¹
```
Find out which list of hexagons we ended up in, which is our final distance.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 160 bytes
```
a->for(i=1,2*#p=Mod(Polrev(a)+y*x^#a,6),p=-if([[t=p%x^l+(3-s)*x^l--+(p\x^j+3)*x^j-=2|j<-[i..#p],x^(k=j-i)+1+x^k++\(x-1)==s=p%x^j\x^l=i-1]|i<-[2..#p]],t,p));#p-1
```
[Try it online!](https://tio.run/##fY/RasMwDEV/xTQU7FoqcbrtpXP/YLB31wbDlmLXLCINw4X@e@YkDLrBhrhwZd8jJPJ9wBONLdOjx0Pb9TxoBc2mIv3SvfHXLvXvn9wLed1kV3l4EkAaQ8uNGTSts0uS7/Aiym9ClJyO2UW5m/qIurnFZzRhu63IQnb8rCMGIZXM7izlkWdUQuvLPCgWMumAyt5CgZoZsjAACbGvCNXoidKVe4YHRn34GIpdTc2KtWVDAcyYGuayxTcw12JruNP09FDsnZZUOfynluQj/NIf6X@Ib6pectaK8Qs "Pari/GP – Try It Online")
Based on [my Mathematica answer](https://codegolf.stackexchange.com/a/240011/9288).
[Answer]
# TypeScript Types, 568 bytes
```
//@ts-ignore
type a<N,P=[],A=[[0,1,2,3,4,5],[1,2,3,4,5,0],[2,3,4,5,0,1],[3,4,5,0,1,2],[4,5,0,1,2,3],[5,0,1,2,3,4]],I=A[1],D=A[5]>=N extends[infer X,infer Y,infer Z,...infer R]?Y extends 3?a<[A[3][A[X][Z]],...R],P>:|a<[Y,Z,...R],[...P,X]>|(Y extends 2?a<R,[...P,I[X],4,I[Z]]>:Y extends 4?a<R,[...P,D[X],2,D[Z]]>:never):N extends[infer X,infer Y]?Y extends 3?P:Y extends 2?[...P,I[X],4]|[...P,X,Y]:Y extends 4?[...P,D[X],2]|[...P,X,Y]:[...P,X,Y]:[...P,...N];type b<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type M<C,P=0>=[C]extends[P]?b<C>["length"]:M<a<C>,C>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4A5AGgAUBeAbQF1KBBB+gBkoEZKAmSgGZKAFkoBWZvV4DhY8ZQ5TZoiYp5S5arjKnz1MoVIU7+Q0Y2YBJWi2nMAIrfqSAfLXKF0AD3DpEACaQ9LCIAGboqIQAGpShEVEAmnHhkYQAWpQAdDnxaQBKjAD8iV6+-kGEgkVk9HaCjHX00Y3pltk5hTSuAFwAPrXJmTlZXfQj1JQtrn0AFKU+foGQhHw1pPmU4zmTVs3MYnttjL0L5cuEIuub21mTDvtmD8e9iOgAbpEAlD2eixXBPJRWJAwiJYpnJaVarUHqQgGrIq3XaPESMPrIqaUcFwspQlZXTEPFr8dGY2I48nYxg9TEjciMADcuAIhAARqQACqUADStAA1ugcMgwoROe5OXiEZyioLhaLJf8Ljyipyem9PqgehxmfgiABZUgAYRotA47noRsYSqC9GoxQ5Rtc9AARAAbfzwcAACxdNMNZCdlCdmGwerFHEItEIhs46i4SlcmBAhFTAD0imHWZzuFGY6R6AIi6Skyn05mWUROXw87GBFx62YG4oTsngKnCBms1XBLWC2IuAPVIOW6X2+Xu2KRH3CzwzIYF-PW2XOxXw5zxDP9Nu1Du3G2O13K2KAGwzgSLi-z68X5fj1eTzkAdi3u7fCj3qn3K6P64AHDOza6GOh6ZkAA)
## Ungolfed / Explanation
```
// Iterate over an array, applying equivalence rules where possible
type ApplyRules<
Next,
Prev=[],
// Modulo arithmetic addition table
Add=[[0,1,2,3,4,5],[1,2,3,4,5,0],[2,3,4,5,0,1],[3,4,5,0,1,2],[4,5,0,1,2,3],[5,0,1,2,3,4]],
Inc=Add[1],
Dec=Add[5]
> =
// Get the first three elements of Next
Next extends [infer X, infer Y, infer Z, ...infer Rest]
? Y extends 3
// Apply the rule for 3
? ApplyRules<[Add[3][Add[X][Z]], ...Rest], Prev>
// Return a union of:
:
// Applying no rule and stepping forward one step
| ApplyRules<[Y, Z, ...Rest], [...Prev, X]>
// If Y is 2 or 4, applying the 2/4 rule
| (
Y extends 2
? ApplyRules<Rest, [...Prev, Inc[X], 4, Inc[Z]]>
: Y extends 4
? ApplyRules<Rest, [...Prev, Dec[X], 2, Dec[Z]]>
: never
)
// Next has fewer than 3 elements. If it has exactly 2, store them in X and Y:
: Next extends [infer X, infer Y]
? Y extends 3
// If Y is 3, remove both X and Y from the end of the array by returning Prev
? Prev
// If Y is 2 or 4, return the union of the current state and the state after applying the end-2/4 rule
: Y extends 2
? [...Prev, Inc[X], 4] | [...Prev, X, Y]
: Y extends 4
? [...Prev, Dec[X], 2] | [...Prev, X, Y]
// Otherwise, just return the full array array
: [...Prev, X, Y]
// Next has fewer than 2 elements; return the full array
: [...Prev, ...Next]
// Filter a union of tuples for those with the shortest length
type Shortest<T, K=keyof T> = T extends T ? keyof T extends K ? T : never : 0
// Continually apply rules until nothing changes, then return the shortest length in Cur
type Main<Cur, Prev=0> = [Cur] extends [Prev] ? Shortest<Cur>["length"] : Main<ApplyRules<Cur>, Cur>
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 105 bytes
-7 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Count[Table[t=b.c,#+3].a.b&/@#/.List->Dot//.{(n:a|b|c).n_:>Dot[],(n:b|c.a.c).a:>a.n,(n:c.t.t).b:>b.n},a]&
```
[Try it online!](https://tio.run/##jY1PC4JAEMXvfYoFQZLWWft3ERShjh06dJMlZhclIVeo7aR@dlsXjQqhYHjwfjPvTYn6kpWoC4ldTqJuVz2UTk8orlmqIwGSOos1BwThssRhcCju2o/3lWYM6rkKsRGN9ECdwx6mnBpmiAkYimGMoHokQYP2QISxANVS5G53vBXmk0P8mOSpwzlxCUtmdR1QMkxLZ6ReUTLMaANrP9SuNtZ@65ha2ssJHbNbez@hPxv@7HlrC17Btu2e "Wolfram Language (Mathematica) – Try It Online")
A port of [Anders Kaseorg's Perl answer](https://codegolf.stackexchange.com/a/240010/9288).
### A proof that the last rule in Anders Kaseorg's answer is not needed
As I said in the comment, the last rule is needed for minimizing the length of the word, but we only need to minimize the number of \$a\$s.
After applying the first 6 rules, there are only 6 possible cases between every two \$a\$s: \$c\$, \$bc\$, \$cbc\$, \$bcbc\$, \$cbcbc\$, \$bcbcbc\$. Since there is no \$ba\$ or \$caca\$, \$aca\$ can only appear at the beginning of the word.
Now let's apply the last rule \$cbcbcab\Rightarrow bcbcbca\$, and see what will happen before and after the \$a\$ in \$cbcbcab\$. Remember that the only way to decrease the number of \$a\$s is applying the first rule: \$aa\Rightarrow \varepsilon\$.
#### Before the \$a\$
If this is the first \$a\$ in the word, there isn't another \$a\$ for us to apply the first rule.
If it is not the first \$a\$, the only two possible cases between this \$a\$ and the previous \$a\$ are \$cbcbc\$ and \$bcbcbc\$, which will become \$bcbcbc\$ and \$cbcbc\$ respectively. So the number of \$a\$ will not decrease.
#### After the \$a\$
If this is the last \$a\$ in the word, there isn't another \$a\$ for us to apply the first rule.
If it is not the last \$a\$, there are 3 possible cases between this \$a\$ and the next \$a\$: \$bc\$, \$bcbc\$, \$bcbcbc\$, which will become \$c\$, \$cbc\$, \$cbcbc\$ respectively. In the last two cases, nothing else will change.
But the first case will produce a new \$caca\$: \$cbcbcabca\Rightarrow bcbcbcaca\$. Applying the rule \$caca\Rightarrow acac\$, this substring will become \$bcbcbacac\$, and further become \$bcbcabcac\$ (by applying \$ba\Rightarrow ab\$). Now the \$c\$ at the end of the substring might meet another \$c\$ and get eliminated. But there can't be another \$ca\$ right after the substring, so nothing else will change, and the number of \$a\$ won't decrease.
---
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 133 bytes
-10 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).
```
Length[##.E.E&@@#//.{a_ . 3 .b_/;a<6>b:>Mod[a+b+3,6],##&@@(a_ .#2.(o:#...).#2.b_/;a<6>b:>Dot@@Mod[-{-a-#,o,-b-#},6]&@@@1?2@*5?4)}]-2&
```
[Try it online!](https://tio.run/##jYxLC4JAFIX3/YoLF8Rq5mqmLnrYLGpX0F5Ext6LFGJ2w/x20yGjIig4HO7hnu9cpTofrlJddrI@wrxeH8qTOqeItKKVIwR6HmmZA8EYqMi9qZzFSTFJNtU@lcNiOGZxxhCbptu2MCC3miAR9dv7BVhWSoiW4ppLjqxivOBoGrxhxWgRiEG0CPsm44FTb2@XUqUIPIFjilkGDniip7XP4CHDeqADBg910bfxze0rtPHTO2pkm1@8YyPb/@I/F/7ceVnzn6Ax9R0 "Wolfram Language (Mathematica) – Try It Online")
First appends two dummy variable `E`'s to the list, then repeatedly replaces:
* \$a3b\Rightarrow\operatorname{mod}(a+b+3,6)\$
* \$a2\underbrace{1\cdots 1}\_{n\ge0}2b\Rightarrow\operatorname{mod}(a+1,6)\underbrace{5\cdots 5}\_{n}\operatorname{mod}(b+1,6)\$
* \$a4\underbrace{5\cdots 5}\_{n\ge0}4b\Rightarrow\operatorname{mod}(a-1,6)\underbrace{1\cdots 1}\_{n}\operatorname{mod}(b-1,6)\$
And then takes the length of the result and minus 2.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~55~~ 53 bytes
```
\d
$*____ab
_
bc
(.)\1
(b|cac)a
a$1
}`(cbcbc)b
b$1
a
```
[Try it online!](https://tio.run/##VYkxCoAwEAT7fUeEi4UkIb7BTwjmLlrYWIilvv08EEFnqp3dl2PdWBuioeg4w7WTwYIJUkGdHyNAclaunsEu4ipUxfQCscmqwUAykMIjcnhEiq/I/eun/ro9wdIN "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Another port of @AndersKaseorg's Perl answer. Edit: Saved 2 bytes using @alephalpha's observation.
```
\d
$*____ab
_
bc
```
First expand each digit into `n+3` underscores followed by `ab`, then replace each underscore with `bc`.
```
(.)\1
(b|cac)a
a$1
(cbcbc)b
b$1
```
Perform the simplifications.
```
}`
```
Repeat until no more simplifications can be made.
```
a
```
Count the remaining number of `a`s.
] |
[Question]
[
Given an array of integers, find *"the next to the middle"*.
>
> The next to the middle is the smallest integer greater than the smallest among mean, median and mode of the given numbers, that is neither the mean, median or mode and is also contained in the array.
>
>
>
For example, in the following array
```
[ 7, 5, 2, 8, 0, 2, 9, 3, 5, 1, 2 ]
Mean: 4
Median: 3
Mode: 2
```
The next to the middle is `5`, because:
* It's greater than 2 (the smallest of the three)
* It is not any of the mean, median, mode
* It's present in the input array
* It's the smallest number matching the above requirements
Another example, given this array
```
[ 2, 5, 1, 11, -1, 2, 13, 5, 1, 0, 5 ]
Mean: 4
Median: 2
Mode: 5
```
The next to the middle is `11`.
## Input
An array containing a sequence of integers.
* You don't need to handle integers larger than those that your language's data type can handle
* The mean could be a floating point number and that's just fine.
* **If the number of elements in the input array is even, you need to handle 2 medians, rather than doing the average of the two values.**
* If more than one integer occurs with the highest frequency, you need to handle multiple values for the mode.
## Output
The *next to the middle*.
If such number doesn't exist you can output either `3.14`, an empty string or any other value that cannot be mistaken for an element of the array (be consistent with that value throughout your program).
[Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, with [standard I/O conventions](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), while [default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
It would be nice if you could provide an easy way to try your program and possibly an explanation of how it works.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest wins.
## Test cases
```
[ 7, 5, 2, 8, 0, 2, 9, 3, 5, 1, 2 ]
5
[ 2, 5, 1, 11, -1, 2, 13, 5, 1, 0, 5 ]
11
[ 528, -314, 2, 999, -666, 0, 0, 78 ]
78
[ 528, -314, 2, 999, -666, 0, 0, 79 ]
79
[ 528, -314, 2, 999, -666, 5, -5, 42 ]
NaN
[ -845, 2021, 269, 5, -1707, 269, 22 ]
5
[ -843, 2021, 269, 5, -1707, 269, 22 ]
2021
[-54,-22,-933,544,813,4135,54,-194,544,-554,333,566,566,-522,-45,-45]
333
[95444,-22668,834967,51713,321564,-8365542,-962485,-253387,-761794,-3141592,-788112,533214,51713,885244,522814,-41158,-88659176,654211,74155,-8552445,-22222]
-3141592
[ 1, 2, 3, 9, 8, 7, 9, 8, 5, 4, 6, 0, 6, 7 ]
NaN
```
~~[ ] // empty array~~
~~NaN~~
You don't need to handle an empty array.
### Answers to comments
* **Is any normal floating point accuracy acceptable?**
Yes. Since you will compare the mean with integers, considering 9,87654321 as mean is the same thing of considering 9.8 as mean.
* **"If such number doesn't exist", can we error?**
Since there's a reusability rule for functions, if you are writing a function, a program needs to be able to call that function multiple times. If you are writing a program, then you can exit on error, but you have to be consistent with this output: you have to exit on error every time that there is no next to the middle.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L‘HịṢ;Æm;ÆṃµṂ³>Ƈḟȯ.Ṃ
```
A full program accepting a list of numbers which prints the *next to the middle* or `0.5` if there is none.
**[Try it online!](https://tio.run/##y0rNyan8/9/nUcMMj4e7ux/uXGR9uC0XiB/ubD609eHOpkOb7Y61P9wx/8R6PSDv////0QqmRhY6CrrGhiY6CkY6CpaWlkCemZmZjoIBGJlbKMQCAA "Jelly – Try It Online")**
Or see the [test-suite](https://tio.run/##jVIxTgQxDOx5xbZIzmntxIkjJGoKfrC6kgYdD6BDIHEFH6BDoqOBCokT3Z6E@MbykWWSHEcJq/Uqtsczjr3nZ6vV5Tyffl3dn0zvd9Pm8Wh7ewGbNjfj67S5Hp@PP9bT28PnywLePG7Gp@36cB6UOmbq@gUOyWB55@CVXpDy3lPnPAfWLDW5nIehSw1CHYr6ekClr0EUSbc8oKFEm180HFcY70Eo04ZTsabRiDKoXIyxQvrS2P9g@Q8YZB0s7LpzFva3lJhbnlOfdq784vw/cE4DORFyGRPTEMhw1cBeqSQ4hxp0Cq/MVNFRMaelBp3ACk0GqhLFaGQ@5JhIOYHLC2tEynwESRGKEgyFot5bIpciJ8jsl@WSGbMQ0oJpNBYzFQhA1RBzgVkNnBY1c4oUwYxtJTCA2bSAi0R56jTaFn3dd/lhfg5lsNS1ZeCbMJPlNw "Jelly – Try It Online") (uses a functional form which uses the register atoms, `©` and `®`, to replace the use of the program argument atom, `³`).
### How?
```
L‘HịṢ;Æm;ÆṃµṂ³>Ƈḟȯ.Ṃ - Main Link: list, A
L - length (A)
‘ - increment
H - halve
Ṣ - sort (A)
ị - index into (if A has an even number of elements we get the two in
the middle, due to Jelly's fractional indexing magic)
Æm - mean (A)
; - concatenate
Æṃ - mode (A)
; - concatenate
µ - start a new monadic chain, f(X=medians+[mean,mode])
³ - programs argument, A
Ṃ - minimum (X)
Ƈ - filter (A) keeping if:
> - greater than (minimum (X))
ḟ - filter - discard those which are in (X)
. - a half
ȯ - logical OR (replace an empty list with 0.5)
Ṃ - minimum
```
[Answer]
# [J](http://jsoftware.com/), 76 bytes
Returns an empty list `''` if there is no element.
```
(0{ ::''-./:~@#~-.><./@])({./.~#~[:(=>./)#/.~),(>.@<:@-:@#(-@[}.}.)/:~),+/%#
```
[Try it online!](https://tio.run/##hZLBSsQwEIbvPsVgkba4TTtJJpkEXQqCJ09eRXIQRbz4AMvuq69/2lX0oBZSMjP/fDPJ5O14btoXus7U0oYmyliDoZv7u9tjN@0o57YdzJgPc3MYzPbKjPNj3@3MaA7N4SF311sz9g2sftNtzXyV5yHPTTfMD3uzNz0S@83leNEc@7Pnp9d3eqFIQpYUdSwlcrCY7Bps27N1IzTkv6XMq8QuTlgFIeJVM5F8AlcVwIsddbXFKhXHvnJTohJCQNKE@EmX/tGl7/xfhEJFyNtvJ4KwqMeZJotuQ6oSjlNc9vakXIJLdWjd31rn3Ekqnoq1VBI84j0prsKzE6oBTn5xFoFVc6S2h1Wk5qAjrJVYD8GS7IpNyFrAISip8ylgJBzBdpYlIKQuAFoLB@sVICvOaaQSA0eU/eKVqMqMcTmk@hNFVSwKoAuFr3hmwT2qBkkcAwWQMdoIAsgqVVxL1O/ngOvwHd6I4s3UPy6e6qgCxeMH "J – Try It Online")
* `+/%#` mean: sum divided by length
* `>.@<:@-:@#(-@[}.}.)/:~` median(s): sort, drop first and last `floor(length % 2 - 1)` elements (can this be shorter?)
* `#/.~` mode(s): group the list by itself, get the length of each group
* `[:(=>./)` the maximum length
* `{./.~#~` take the groups' first element that have the maximum length
* `<./@]` minimum of mean, medians and modes
* `-. #~-.>` get every element that is not in (mean, medians, modes), but also larger,
* `/:~@` sort them and
* `0{ ::''` get the first element – if there is none and an error would occur, return `''` instead
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
L‘HịṢ;Æm;Æṃ
ḟÇ>ƇÇṂ$ȯ.Ṃ
```
[Try it online!](https://tio.run/##fZAxTsRADEX7PQelB8WesccjJGoKbhBtSYOWA9ChRSIFF6BDokaiJaKMhLhG9iLhO0DJRnIy42f/7/j6are7XZbLw93TxfzxOI8vZ9PDDWIe7zfz@/M0nH8O0zCP@5Ovt1N8lmk47F@Xpd/0lZSEnDq8G2XcmGRLm17WIzMlJIh/SEcaLELFKWUu0dcaJTMD7qj6Udr@o0pJqazWyQuG6gTG1gJw7ep6lj@ej3ItlEQotYyxSyHH@IWzUgBuZU0mxS1HRbgjkkYPrBEh01C1Cpk5eS7NsCyu0MrCakCeDSJhZFIcjaI5e6VUjSts4h9ZGwqqOzNWmtFaflXcVWAAV0cuFWbFWtxNG1cjgzLWX6EAZdcoDot4MN72Gw "Jelly – Try It Online")
Returns `0.5` for an invalid input.
## Explanation
```
L‘HịṢ;Æm;Æṃ Auxiliary monadic link
L Length
‘ Increment
H Half
ị Index into
Ṣ the sorted array
; Join with
Æm the mean
; Join with
Æṃ the mode(s)
ḟÇ>ƇÇṂ$ȯ.Ṃ Main monadic link
ḟ Filter out
Ç the results of the previous link
Ƈ Filter
> greater than
$ (
Ç The results of the previous link
Ṃ Maximum
$ )
ȯ Logical OR (non-vectorizing) with
. 0.5
Ṃ Minimum
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¢ZQÏIÅAI{Ås)˜WUKʒX›}ß
```
[Try it online](https://tio.run/##yy9OTMpM/f//0KKowMP9nodbHT2rD7cWa56eEx7qfWpSxKOGXbWH5///H21qZKGja2xoomOkY2lpqaNrZmamYwCE5haxAA) or [verify all test cases](https://tio.run/##fVGxSgQxEP2V4zphAjtJZjKpDmsrC1FcrlCwsLI4EA4RbM5WuVoQ7Gz2Ayx3O/2L@5H1zXqtF0jIzJt5b/Jyt7q6vr0Z79eL@Wz3vJ3NF@vhtf8c@4/L0@Gl74bNcd89DJvV0c9b363Oz06@txe7p6/H4X2ksW0LCUUyanBWSoiY4pLaON2YKSAm/gMaEkASjULi7B21UlBVIA0VOwTWf0ChIJRdMljGLE2EoFbPc2nKdI97OB2CJVOIkUJNGDZnMgydOQk5wDVPySCIkle4NHYQ74EwNlgqiiYeVSNLuSoM4gKqFFkUkCUFh@tozIa@KClZoVCUC1T8fSwVBcWMGT4mtOY9i5lECEDUkAuZWWCJmUrloqRghucFDGA28WKX8IXp/CsSvsmoTCeMI7dXqSyXvw).
**Explanation:**
```
#Mode:
¢ # Count how many times each value occurs in the (implicit) input-list
Z # Get the maximum of these counts (without popping the list)
Q # Check for each if it's equal to this maximum count
Ï # Only leave the values in the (implicit) input-list at the truthy indices
#Mean:
IÅA # Push the input; pop and push its mean
#Median:
I{ # Push the input; sort it
Ås # Pop and push the middle (one or two) values
) # Wrap all three into a list
˜ # And flatten it
W # Push the minimum of this list
U # Pop and store it in variable `X`
K # Remove all medium, mean, and mode values from the (implicit) input-list
ʒ # Filter the remaining values by:
X› # Check if it's larger than `X`
}ß # After the filter: pop and push the minimum
# (after which it is output implicitly)
```
Although 05AB1E does have builtins for all three: mean ([`ÅA`](https://tio.run/##yy9OTMpM/f//cKvj///RpjpGOsY6umZAwhDINIkFAA)); median ([`Åm`](https://tio.run/##yy9OTMpM/f//cGuuDlf14dZinf//o011jHSMdXTNgIQhkGkSCwA)); and mode ([`.M`](https://tio.run/##yy9OTMpM/f9fz1eH69CiqMDD/Tr//0eb6hjpGOvomgEJQyDTJBYA)), the median takes the average of the two values for even-length lists, and the mode only results in a single most frequent value instead of all, which is why we'll do those manually. In the legacy 05AB1E version the [`.M` mode builtin did result in all most frequent values](https://tio.run/##MzBNTDJM/f9fz/f//2hTHSMdYx1dMyBhCGSaxAIA) instead of just one, but unfortunately the legacy version doesn't have a median nor middle builtin, and doing that manually would be even longer.
[Answer]
# JavaScript (ES6), 165 bytes
Returns `undefined` if no valid answer is found.
```
a=>a.sort((a,b)=>a-b).map(c=v=>(n++,t+=v,i=c[v]=-~c[v],i<m?0:m=i,v),m=t=n=0).find(v=>v>Math.min(...A=[t/n,a[n>>1],a[n-1>>1],...a.filter(v=>c[v]==m)])&!A.includes(v))
```
[Try it online!](https://tio.run/##nVJLjtswDN33FO5mICGUa@qvonIxB@gJgiw0TtJ6EMuDxPWyV08pu9NF4S5mDFMSRb73KErPaU637tq/TCKPx9P9HO8ptqm@jdeJsQRPnDzxxOshvbAuzrFlebeDaRdn6GO3nw9R/CoT9F@Gr83nIfYwcxjiFHNseH3u85ERam6/pelHPfSZ1XX9GPfTpwxpn9sWD2UWuKwolghzmU7Xglr448AP/OHjY93n7vLzeLqxmfN7N@bbeDnVl/E7O7N95aAyUEmoPFTNsghQqWUTya0OnH/4FyNfw0gmcEHhXwyxmC3YFpORJCsU6lU5kLaw1i4k9DtfvQcV3oaisgWZ3j6s8Lo0qJHlnDas6ega98eV/4Wpt8OE0SCkBBGUAqM1eOqrRmWgBDDoZVMY8lTJoPKLicYUEBVKtkEbCLUQW@vBKx2sA4OOuJVEYynklSXSImyl9sQjjVLegXAWHcmWvqEJlOC8R5RAYUmtXFm8N5IEqAhPe0IjGk@c3pqAzoIlZnoqjhiI2ZuSXCTKt9W79UWp5SnSnbnXRbkkqNZ7ptGVDt5/Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.sort((a, b) => // sort a[] from lowest to highest
a - b // so that we can compute the median value(s)
) //
.map(c = v => // for each value v in a[]:
( n++, // increment the total number of values n
t += v, // add v to the sum t of all values
i = c[v] = -~c[v], // update the number i of occurrences of v
i < m ? 0 : m = i, // update m to max(m, i)
v // yield v so that the array is unchanged
), // and we can chain with .find()
m = t = n = 0 // start with m = t = n = 0
) // end of map()
.find(v => // find the first value v that satisfies:
v > Math.min( // 1) it's greater than the minimum of ...
...A = [ // the values stored in A[], which are:
t / n, // - the mean
a[n >> 1], // - the 1st median value
a[n - 1 >> 1], // - the 2nd median value (if any)
...a.filter(v => // - all mode values
c[v] == m // i.e. values that appear m times
) //
] // end of array
) & // end of Math.min()
!A.includes(v) // 2) it's not one of the values defined above
) // end of find()
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes
```
Min@Cases[#,a_/;a>Min@#&&#~FreeQ~a&@{Mean@#,Sort@#//._[_,a__,_]:>a,Commonest@#}]&
```
[Try it online!](https://tio.run/##jZFNawJBDIbv/oqFhT1lqpnPTEtFEHoTWjyKLEPZUg8qqDfRv27f7NYei8tmmSRP3mQn23L67rbltPkst6/X22Kzm83LsTuuairt@KVMNVI3TX19O3Tdx7U0s/OiK4jRcn84zerx@KldtYBbatfP00Lz/Xa733VH5C7r5vZ@2OxOq9pMv2b1urkuP8vueh6dE1WBKkuVUDXpD5kq1wcZ7oVGZ3v3GGa4h/gPQVFQKlgoGMd@EMmQMTHGHsCb5BEo/wuhoYH5fiojXgefWB0o5iHLaZJ@XXun3ANU8GSsJZOdo@A9Cf7PswukCc6@D5oAzymBYdRM0BqMAVOZDKoXilFInM8xUeAELWc5RKTERYhoo2i9oNAG5ySRSZET2uhfc8gAkgizJaQtLmJQEQkWDdBVEDOeOQg0JYbMKVKEMlaUoABlCQprC310vGFzrt8wbjjdD3qlVA1LwDeBBawVl9Hl9gM "Wolfram Language (Mathematica) – Try It Online")
Returns `Infinity` if such a number does not exist.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
W⁻θυF№ι⌊ι⊞υ⌊ι≔✂υ⊘⊖Lθ⊕⊘Lθ¹υ≔Eθ№θιηF⌕Aη⌈η⊞υ§θι⊞υ∕ΣθLθI⌊Φ⁻θυ›ι⌊υ
```
[Try it online!](https://tio.run/##VZBPa8MwDMXv/RQ6KuDBujG2kVNo6R9YYdBj6cEkai1wnMWxs377TM7aLfVJfu9Z@lml0b5stB2Gb8OWAHfsYoetgphlcGo84KKJLiArEIvrWCNnYn3GzmC8E/NZ0XV8dri3XFIyN9r2VOGSSk81uSD1B7lzMNhKDwVb929cs3f@PEscf313@iuR/QJJwSljxB85V@yqwlo0AqUvI5SZkhZh6yq6XB/ms5u@5J4rwr3kW@k3AZCMZxm10F3A20dXbAP56Z4UrD3pJE6WJOtLJx@GwwFeFbwoeFLwpuBxLN4VPI/iXK5wPA4Pvf0B "Charcoal – Try It Online") Link is to verbose version of code. Outputs `None` if no suitable value exists. Explanation: Not an ideal challenge for Charcoal.
```
W⁻θυ
```
While the sorted list does not contain all of the input values...
```
F№ι⌊ι⊞υ⌊ι
```
... push the next value to the sorted list according to the number of times it appears.
```
≔✂υ⊘⊖Lθ⊕⊘Lθ¹υ
```
Slice the middle element(s) from the sorted list.
```
≔Eθ№θιη
```
Tabulate how many times each element appears in the list.
```
F⌕Aη⌈η
```
Loop over the indices of maximum counts, ...
```
⊞υ§θι
```
... pushing the original value to the list of averages.
```
⊞υ∕ΣθLθ
```
Finally, push the mean to the list of averages.
```
I⌊Φ⁻θυ›ι⌊υ
```
Remove all of the averages from the input, then also filter out values lower than all of the averages, and print the minimum of the remainder (if any).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 33 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç∞♫ÑÄ‼ú╘màk■g5øg◘U½¢┴Åû)*ç╨£╨├╡óà
```
[Run and debug it](https://staxlang.xyz/#p=80ec0ea58e13a3d46d856bfe673500670855ab9bc18f96292a87d09cd0c3b5a285&i=%5B+7,+5,+2,+8,+0,+2,+9,+3,+5,+1,+2+%5D%0A%5B+2,+5,+1,+11,+-1,+2,+13,+5,+1,+0,+5+%5D%0A%5B+528,+-314,+2,+999,+-666,+0,+0,+78+%5D%0A%5B+528,+-314,+2,+999,+-666,+0,+0,+79+%5D%0A%5B+528,+-314,+2,+999,+-666,+5,+-5,+42+%5D%0A%5B+-845,+2021,+269,+5,+-1707,+269,+22+%5D%0A%5B+-843,+2021,+269,+5,+-1707,+269,+22+%5D%0A%5B-54,-22,-933,544,813,4135,54,-194,544,-554,333,566,566,-522,-45,-45%5D%0A%5B95444,-22668,834967,51713,321564,-8365542,-962485,-253387,-761794,-3141592,-788112,533214,51713,885244,522814,-41158,-88659176,654211,74155,-8552445,-22222%5D%0A%5B+1,+2,+3,+9,+8,+7,+9,+8,+5,+4,+6,+0,+6,+7+%5D&m=2)
Getting the middle two elements takes most of the space here. Reducing that would significantly improve the score.
] |
[Question]
[
# Note
This is the decryption challenge. The encryption challenge can be found [here](https://codegolf.stackexchange.com/questions/155194/lets-encrypt-it).
# Challenge
The challenge is to decrypt a given string, using the rules as specified below. The string will only contain **lowercase alphabets**, **digits**, and/or **blank spaces**. If you want to know how the input string has been encrypted, refer to [this challenge!](https://codegolf.stackexchange.com/questions/155194/lets-encrypt-it)
# Equivalent of a Character
Now, firstly you would need to know how to find the "equivalent" of each character.
If the character is a consonant, this is the way of finding it's equivalent:
```
1) List all the consonants in alphabetical order
b c d f g h j k l m n p q r s t v w x y z
2) Get the position of the consonant you are finding the equivalent of.
3) The equivalent is the consonant at that position when starting from the end.
```
eg: 'h' and 't' are equivalents of each other because 'h', 't' are in the 6th position from start and end respectively.
The same procedure is followed to find the equivalent of vowels/digits. You list all the vowels or the digits (starting from 0) in order and find the equivalent.
Given below is the list of the equivalents of all the characters:
```
b <-> z
c <-> y
d <-> x
f <-> w
g <-> v
h <-> t
j <-> s
k <-> r
l <-> q
m <-> p
n <-> n
a <-> u
e <-> o
i <-> i
0 <-> 9
1 <-> 8
2 <-> 7
3 <-> 6
4 <-> 5
```
# Rules of Decrypting
1. You start with two empty strings, let's call them `s1` and `s2`. We will be moving from left to right of the input string. At the beginning, we would be considering the first empty string, i.e, `s1`. We will be switching between the two strings whenever we encounter a vowel.
2. We take the equivalent of the current character of the input string, or a blank space if it is a blank space. Let's call this character `c`. `c` is now appended to the **right of** `s1` (if we are considering `s1` currently) or to the **left of** `s2` (if we are considering `s2` currently).
3. If that character was a vowel, switch to the other string now (`s1 <-> s2`).
4. Repeat step 2 (and 3 for vowels) for every character in the input string.
5. Concatenate `s1` and `s2` and the result is the decrypted string.
Now let me decrypt a string for you.
```
String = "htioj ixej uy "
Initially, s1 = s2 = ""
Current: s1
Moving left to right
"h" -> "t" (s1 = "t")
"t" -> "h" (s1 = "th")
"i" -> "i" (s1 = "thi")
Vowel encountered. Switching to s2 now.
"o" -> "e" (s2 = "e")
Vowel encountered. Switching to s1 now.
"j" -> "s" (s1 = "this")
" " -> " " (s1 = "this ")
"i" -> "i" (s1 = "this i")
Vowel encountered. Switching to s2 now.
"x" -> "d" (s2 = "de") [Note that when dealing with s2, we append to the left]
"e" -> "o" (s2 = "ode")
Vowel encountered. Switching to s1 now.
"j" -> "s" (s1 = "this is"
" " -> " " (s1 = "this is ")
"u" -> "a" (s1 = "this is a")
Vowel encountered. Switching to s2 now.
"y" -> "c" (s2 = "code")
" " -> " " (s2 = " code")
Now, append s1 and s2 to get:
"this is a code"
Output -> "this is a code"
```
# Examples
```
"wqcjmc" -> "flyspy"
"toek" -> "hero"
"toyike" -> "heroic"
"uo" -> "ae"
"uoz" -> "abe"
"htoo jmuy" -> "the space"
"uh68v8x " -> "a d1g13t"
"fo78i d" -> "we xi12"
"htioj ixej uy " -> "this is a code"
"jea ceeac hnx8x vni kokhj jiuth xoqqc xohmcky" -> "so you really decrypted this string d1dnt you"
```
You may also choose to use uppercase alphabets instead of lowercase.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ØḄ,ØẹØDṭ,U$F€yµe€ØẹŻœṗµ;ṚU$m2
```
A full program which prints the decoded text.
**[Try it online!](https://tio.run/##y0rNyan8///wjIc7WnSA5K6dh2e4PNy5VidUxe1R05rKQ1tTgRRY4ujuo5Mf7px@aKv1w52zQlVyjf7//5@VmqiQnJqamKyQkVdhUaFQlpepkJ2fnZGlkJVZWpKhUJFfWJgMJDNyk7MrAQ "Jelly – Try It Online")**
### How?
```
ØḄ,ØẹØDṭ,U$F€yµe€ØẹŻœṗµ;ṚU$m2 - Main Link: list, S
ØḄ - consonant characters
Øẹ - vowel characters
, - pair
ØD - digit characters
ṭ - tack -> ["bcd...","aeiou","012..."]
$ - last two links as a monad:
U - upend -> ["...dcb","uoiea","...210"]
, - pair -> [["bcd...","aeiou","012..."],["...dcb","uoiea","...210"]]
F€ - flatten each -> ["bcd...aeiou012...","...dcbuoiea...210"]
y - translate S using that map
µ - new monadic chain (i.e. f(A=that))
Øẹ - vowel characters
e€ - (for c in A) exists in (vowels)?
Ż - prepend a zero
œṗ - partition (A) before truthy elements (of that)
µ - new monadic chain (i.e. f(that))
...e.g.: f(["thi","e","s i","do","s a","c "])
$ - last two links as a monad:
Ṛ - reverse ["c ","s a","do","s i","e","thi"]
U - upend [" c","a s","od","i s","e","iht"]
; - concatenate ["thi","e","s i","do","s a","c "," c","a s","od","i s","e","iht"]
m2 - mod-2 slice ["thi", "s i", "s a", ," c", "od", "e" ]
- implicit, smashing print -> this is a code
```
[Answer]
# JavaScript (ES6), ~~112 110~~ 109 bytes
Expects an array of characters.
```
s=>s.map(c=>(C="bzcydxfwgvhtjskrlqmpnn aueoii",c=C[j=C.search(c)^1]||9-c,+s?b=c+b:a+=c,s^=j>23),a=b='')&&a+b
```
[Try it online!](https://tio.run/##ddHNbsIwDAfw@57C6gFaAUUwaWOTwg48BgIpdd0m6UdKk0KDePeu26FsUitFufgX@29F8Ss3WMvKrkodU5ewzrC9CQte@cj2/oF50R1d3Ca39CqsMlmdX4qqLAF4Q1pKb4nscFTsEBriNQofg/Pm9Hh8rHC5MF8Rw0X0yRcMl@bM1H77Giw5i9h8HsxmfBF1qEujcwpznfqJfwzD0LtdUBXonYIA1mvwktyZynkvI9JqygYnqNYTysmM/jmJo7LRg@I0Ie5PEo0bYbUGVTRukFYQmIrjRE/xtrvuWng2hniTbl7tqE70@05CPOAbQSs324kkUiuQLSloHPyJIw30hwP2fz76UlFfJOIIomz7bNdSQqYzoUDJxgpo9eWC/S0KzJ57Gg1ON1ATz3MHMWHtKksx/A40tpZl2q8Wl/aHed03 "JavaScript (Node.js) – Try It Online")
### How?
We look for the index of each character `c` in the following lookup string:
```
0 1 2
012345678901234567890123456789
"bzcydxfwgvhtjskrlqmpnn aueoii"
```
If the character is not found, it must be a digit which is replaced with `9-c`. Otherwise, we get the position of the counterpart character by inverting the least significant bit of the index.
For instance: `j` → `12` → `13` → `s`
The new character is either appended to `a` or prepended to `b`.
We switch between `a` and `b` whenever the index is greater than 23 -- i.e. `c` is a vowel.
[Answer]
# Python, ~~226, 160~~ 146 bytes
[Try it Online](https://tio.run/##NY3LboMwEEX3fMVsKiAoVSAtoaR8ieVKYEw9drF5x87PUyTCZubcqzOazk3C6Ou61rwBFbgw98AWfjlzg1g9matt8/hdxCRHNfz1baf15SvOkts1/fgE8D0Yi9iDqiC@T0@JB40ZAAE1uFwX9r1BXQcY3isy0qiwREfxOTkF@i0J6X38KfR36kE3oJ6CisQ0qsiFkjw/xzRcVeA/eiZb5ofexpPh6iCHiu88m2M/dxCTMSDb2b16kWZLZmFPjbllCPVhopGAlkuY3UuQvATGeclAaLudLRpBGSUkSJwnAdb0PdumaJnaPqz/)
I am fairly new to python and wanted to try this challenge. I know a lot of this can be improved using lambda or simplified code. I am showing my code so I can get feedback.
Thanks to @Arnauld for helping me learn new ways to code. Now at 160 bytes
More inputs and refinements. Now at 146.
```
def k(y):
x='aueoiibzcydxfwgvhtjskrlqmpnn0918273645 '
s=1
b=['']*2
for i in y:n=x.find(i);b[s]+=x[n+1-2*(n%2)];s^=n<6
print(b[1]+b[0][::-1])
```
Old Code:
```
def k(y):
x='aueoiibzcydxfwgvhtjskrlqmpnn0918273645 '
s=1
b=c=''
def a(t):
m=n+1 if n%2==0 else n-1;t+=x[m];return t
for i in y:
n=x.find(i)
if s:
b=a(b)
else:
c=a(c)
if n<=5:s=not s
b+=c[::-1]
print(b)
k('wqcjmc')
k('toek')
k('toyike')
k('uo')
k('uoz')
k('htoo jmuy')
k('uh68v8x ')
k('fo78i d')
k('htioj ixej uy ')
k('jea ceeac hnx8x vni kokhj jiuth xoqqc xohmcky')
```
Tested all the sample items and got the correct response.
```
"wqcjmc" -> "flyspy"
"toek" -> "hero"
"toyike" -> "heroic"
"uo" -> "ae"
"uoz" -> "abe"
"htoo jmuy" -> "the space"
"uh68v8x " -> "a d1g13t"
"fo78i d" -> "we xi12"
"htioj ixej uy " -> "this is a code"
"jea ceeac hnx8x vni kokhj jiuth xoqqc xohmcky" -> "so you really decrypted this string d1dnt you"
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~89~~ ~~83~~ ~~80~~ 71 bytes
```
[aeiou]|$
$&¶
+`(¶.+)¶(.*)$
$2$1
O$^r`.\G
T`¶b-df-hj-maed\oup-tv-z_`Ro
```
[Try it online!](https://tio.run/##DYpNbsIwEEb3c4pZhCqAHKldQG7AEgl111DsOoP8o2QIskMSca4cIBdLLT29xfu@JwXbqnWTn@T6o8hyvL4zyD6WGfYyX@Ziv13mvNhtU/zKPuGc/T5lUZ0AvuUy/4n6LowTjaK64vgQoRfTTV54XV@ddo2GwOSTRusJIicmMIEZXRNHiOZQ9uWAcOdjabFOk2WHdiCHcURwpFATKY2mHdKvby169sahszEYHLjrdLJptB//AQ "Retina 0.8.2 – Try It Online") Link includes test cases. This turned out to be easier than encoding, as demonstrated by the fact that I was able to code it in Retina 0.8.2 rather than requiring Retina 1. Explanation:
```
[aeiou]|$
$&¶
```
Split the input on substrings ending on vowels. An extra split is forced at the end of the string so that there are at least two lines.
```
+`(¶.+)¶(.*)$
$2$1
```
Join alternate lines together, so that the first line is the concatenation of all the odd lines and the second line is the concatenation of all the even lines.
```
r`.\G
```
Matching only the characters on the last (second) line...
```
O$^`
```
.. reverse the matches, thus reversing the second line only.
```
T`¶b-df-hj-maed\oup-tv-z_`Ro
```
Join the two lines together and decode the letters. The `Ro` causes the string to transliterate to its reverse. The middle consonant `n` and vowel `i` map to themselves so don't need to be listed. The `¶` maps to the special `_` thus deleting it. The first and last 10 consonants and the first and last two vowels then surround the digits. (The `o` is normally special so it has to be quoted here.)
[Answer]
# [R](https://www.r-project.org/), 190 bytes
```
function(i,`/`=strsplit){a=el(" 01234aeibcdfghjklmnpqrstvwxyziou98765 "/"")
names(a)=rev(a)
j=k=""
for(l in a[el(i/"")]){if(T)j=c(j,l)else k=c(l,k)
if(grepl(l,"aeiou"))T=!T}
cat(j,k,sep="")}
```
[Try it online!](https://tio.run/##NY/NbsIwEITvfgp3T14pEoX@H/wWuVVIuGYD/sFxbQdIEc@ebg89jUbzaUZTlj3ZMueml2FKtrkxKdftVjtdW6k5uoY3oykqkI/rzdOzIfdl98Ph6EM8pfxdajtfrvOPG6eP97fXFwkrABTJnKgqg7rQmUV4HTSAGMaionRJmk@udH/oFm9uUD16bZXvIlKsJAOb2AUUHB0K5cgOeHqcALHXD/1dWNOYD12lzM14//@h4MgnvHRX8nKaJeDyCw "R – Try It Online")
Note to self: learn a new, non-[R](https://www.r-project.org/), language to golf text-based challenges...
Commented:
```
decrypt=function(i,
`/`=strsplit){ # use infix '/' as alias to strsplit function
a=el(" 01234aeibcdfghjklmnpqrstvwxyziou98765 "/"")
# a=vector of characters with equivalents at reverse index
names(a)=rev(a) # name characters by equivalent
j=k="" # initialize j,k as empty strings
for(l in a[el(i/"")]){ # for each input letter (split using /), find its equivalent l
if(T)j=c(j,l)else k=c(l,k) # if T=1 (initial value) append l to j, otherwise put it at start of k
if(grepl(l,"aeiou"))T=!T} # if it was a vowel, T=not T
cat(j,k,sep="")} # finally, output j,k
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~144~~ ~~143~~ 140 bytes
-1 -3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
```
k,v,p,a;f(char*s,char*o){for(k=p=0,v=strlen(s);a=*s++;p^=1065233>>a-97&1)o[p?--v:k++]=a<33?a:a<58?105-a:"uzyxowvtisrqpnemlkjhagfdcb"[a-97];}
```
[Try it online!](https://tio.run/##TZDbbqMwEIavk6cYWWoFDUihKG02lOQBerEPkKSSaww2JzvYEGiVZ8/aNDQrWT58M/PP7yF@Rsj1WnidJz0cpQ5huHlS3ngI9zsVjVPEMl56Xax0U9LaUW6E4ye1WETyIw6WL6vnMNxusf/n9TFwxV7ufL/bFIvFMcZvYbjDG/y2Wu@C5crHG9R@Db04d5qr5iRrWpVFznCWJuQT7a3EMbpcs5sJ3fzYoL2kRNPE/Z7PRpBQIhKaWENJKx1zuNF8ltqLd4tZIBte69RBe3hQcIQDelAHBP72dpsdauSZElJJZ2rxW75DAGiD/r6PKf@pXuYV5rVjvWQOOp9IXhHkAUrLQckB2b6Ga0ELSxltxJ0NvKAT5WTirbAM0/v7awSfv4RpISCv2sFyzSgoick9n72su3UPYxEkQRaEeoql4nXNIbGhM4WeB893TS5y4D3NoR3gR5grMAuD/euUl1PzphQTYHVvunQ1h0IULIect5pBL04nYnZWkWL0pwQMooWG4rIcwAyuGaSZLIzyZpa8zozJpNY2zXa5XP8B "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žMIå0šÅ¡ι€S`R«žN‡žM‡žh‡
```
I/O as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//6D5fz8NLDY4uPNx6aOG5nY@a1gQnBB1afXSf3@GmRw0LgdJQOgNM//8frZShpKNUAsSZQJwPxFlArADlVwBxKpJYKRBXgtmxAA) or [verify all test cases](https://tio.run/##LYo9DoJAFISv8rK1hZXS0ZtoIaUxEdc1@xN4IQKyVoZED@ANKCyMxt6GYgmth@Ai60Jsvm8yM3gIt4LZXPsEuusNiK8D87BtPTfv5j5uq@Ziqu@nK1/BZmmebb1oyu5cuf1vPtjORnZFjgmVESUjkiJTg7RQzIUMB5wceYoIMsp03/CJl3sFuLjHqSdgNxwEShAFk5DpfpIsBMpYSIHHhXvnsQCFikuQIks5FJgk1JFHVGmy/gE) (with the I/O joined to pretty-print).
**Explanation:**
```
žM # Push the vowels "aeiou"
Iå # Check for each character in the input-list if it's in the vowel string
# i.e. ["h","t","i","o","j"," ","i","x","e","j"," ","u","y"," "]
# → [0,0,1,1,0,0,0,1,0]
0š # Prepend a leading 0
# → [0,0,0,1,1,0,0,0,1,0]
Å¡ # Split the (implicit) input-string on the truthy values
# → [["h","t","i"],["o"],["j"," ","i"],["x","e"],["j"," ","u"],["y"," "]]
ι # Uninterleave the list of lists
# → [[["h","t","i"],["j"," ","i"],["j"," ","u"]],[["o"],["x","e"],["y"," "]]]
€S # Convert each inner list of lists to a flattened list of characters
# → [["h","t","i","j"," ","i","j"," ","u"],["o","x","e","y"," "]]
` # Push both lists of characters separated to the stack
# → ["h","t","i","j"," ","i","j"," ","u"] and ["o","x","e","y"," "]
R # Reverse the second string
# → ["h","t","i","j"," ","i","j"," ","u"] and [" ","y","e","x","o"]
« # Merge the two lists together
# → ["h","t","i","j"," ","i","j"," ","u"," ","y","e","x","o"]
žN # Push the consonants "bcdfghjklmnpqrstvwxyz"
 # Bifurcate it; short for Duplicate & Reverse copy
‡ # Transliterate the "bcdfghjklmnpqrstvwxyz" to "zyxwvtsrqpnmlkjhgfdcb"
# → ["t","h","i","s"," ","i","s"," ","u"," ","c","e","d","o"]
žM‡ # Do the same for the vowels "aeiou"
# → ["t","h","i","s"," ","i","s"," ","a"," ","c","o","d","e"]
žh‡ # And the digits "0123456789"
# → ["t","h","i","s"," ","i","s"," ","a"," ","c","o","d","e"]
# (after which the result is output implicitly)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, 110 bytes
```
map{push@{$o[$i]},y/0-9a-z/9876543210uzyxowvtisrqpnemlkjhagfdcb/r;$i^=/[aeiou]/}@F;say@{$o[0]},reverse@{$o[1]}
```
[Try it online!](https://tio.run/##Hcy7DoIwGEDhV@nAKLaoqISYMLH5BASTWn9tubSlBeQSXt1KWE5ylk@DqULnaqpn3VmezJ7KPJEvuxETP6L@hKPr5RyejoeAdNM4qG/fCmsaLaGuyoLTz/vFntjEnnjccEZBqC7HS5LGlo6bRlbMQA/GwvZBvjhXAEUMgDLE5XAdUC8FKlXJC1SIruVoUE3D1vKaleNP6VYoaZ1/D/ckIM6XVfoH "Perl 5 – Try It Online")
] |
[Question]
[
[Lost](https://esolangs.org/wiki/Lost) is a 2-Dimensional programming language where the instruction pointer starts at a random location, moving in a random direction. A description of the language can be found at the bottom of the post for completeness' sake and a tutorial for the language can be found in the above link.
The task here is simple to describe: Write a non-empty lost program which when run will output the direction that was selected at the beginning of execution.
The four directions are:
* `N` for north
* `E` for east
* `S` for south
* `W` for west
You may output them with any capitalization you please and with an optional trailing newline.
# Description
Lost operates on a grid where each instruction is a character of the source. Lost's instruction pointer (ip) moves through the grid in one of the four cardinal directions. When it goes off one side of the grid it wraps around to the other as if the program were written on a torus.
Lost's memory is stored in a main stack and a scope. Both are stacks padded with zeros at the bottom. At the end of execution the contents of the main stack are printed and the scope discarded. Lost also stores a single value called the "safety", which begins on.
Programs can only terminate when the safety is off.
## Doors
* `[` Reflects the ip if it is moving east; becomes `]` if the ip is moving horizontally
* `]` Reflects the ip if it is moving west; becomes `[` if the ip is moving horizontally
## Jumps
* `!` Skips the next operation
* `?` Pops off the top of the stack and jumps if not zero
## Stack manipulation
* `:` Duplicates the top of the stack
* `$` Swaps the top two items of the stack
* `(` Pops from the stack and pushes to the scope
* `)` Pops from the scope and pushes to the stack
## Literals
* `0`-`9` pushes n to the top of the stack
* `"` Starts and ends a string literal. During a string literal commands are not run and instead their character values are pushed to the stack.
## Operations
* `+` Adds the top two numbers
* `*` Multiplies the top two numbers
* `-` Multiplies the top by -1
## Control
* `%` Turns the safety off
* `#` Turns the safety on
* `@` Ends execution if the safety is off (starts on)
---
The following operations are present in Lost but cannot be used for this challenge, since doing so instantly makes the challenge impossible.
* `\` Swaps the x and y directions
* `/` Swaps the x and y directions and multiplies them by -1
* `|` Multiplies the horizontal direction by -1
* `>` Tells the ip to move east
* `<` Tells the ip to move west
* `v` Tells the ip to move south
* `^` Tells the ip to move north
[Answer]
# ~~1749~~ 1533 bytes
```
%(6.99*+@+6*97(((((%#%%%%%%%#%%#%%%%%
%(((((99*6+@+*976((%%(((((((%((%(((((
%((699*+@+6*97(((((%((((((((((((((((((((
%(((((99*6+@+*976((%2(2(2(2(2(2(2(2(2(2(
%((699*+@+6*97(((((%9(9(9(9(9(9(9(9(9(9(
%(((((99*6+@+*976((%9(9(9(9(9(9(9(9(9(9(
%((699*+@+6*97(((((%*9*9*9*9*9*9*9*9*9*9
%(((((99*6+@+*976((%+9+9+9+9+9+9+9+9+9+9
#%(699*+@+6*97((((%#@*@*@*@*@*@*@*@*@*@*
%(((((99*6+@+*976((%+2+2+2+2+2+2+2+2+2+2
%((699*+@+6*97(((((%6+6+6+6+6+6+6+6+6+6+
(#%(((99*6+@+*976(%#*@*@*@*@*@*@*@*@*@*@
%((699*+@+6*97(((((%8+8+8+8+8+8+8+8+8+8+
(%((((99*6+@+*976((%9*9*9*9*9*9*9*9*9*9*
%((699*+@+6*97(((((%(8(8(8(8(8(8(8(8(8(8
(((%((99*6+@+*976((%(9(9(9(9(9(9(9(9(9(9
(((699*+@+6*97(((((%(6(6(6(6(6(6(6(6(6(6
2(((((99*6+@+*976((%((((((((((((((((
((69.9*+@+6*97(((((%((((((((%((%((
%(((%(99*6+@+*976((%%%%%%%%%#%%#
+6.*97%%#%%#%%%%%%%((((699*+@
*976((((%((%((((((((%(((((99*6+@+
((((((((((((((((((((%((699*+@+6*97(
2(2(2(2(2(2(2(2(2(2(%(((((99*6+@+*976(
9(9(9(9(9(9(9(9(9(9(%((699*+@+6*97(((
9(9(9(9(9(9(9(9(9(9(%(((((99*6+@+*976(
*9*9*9*9*9*9*9*9*9*9%((699*+@+6*97(((
+9+9+9+9+9+9+9+9+9+9%(((((99*6+@+*976(%
@*@*@*@*@*@*@*@*@*@*#%(699*+@+6*97(((%#
+2+2+2+2+2+2+2+2+2+2%(((((99*6+@+*976((%
6+6+6+6+6+6+6+6+6+6+%((699*+@+6*97(((
*@*@*@*@*@*@*@*@*@*@#%((((99*6+@+*976(%#
8+8+8+8+8+8+8+8+8+8+%((699*+@+6*97(((
9*9*9*9*9*9*9*9*9*9*%(((((99*6+@+*976((%
(8(8(8(8(8(8(8(8(8(8%((699*+@+6*97(((
(9(9(9(9(9(9(9(9(9(9%(((((99*6+@+*976
(6(6(6(6(6(6(6(6(6(6%((699*+@+6*97((
6(((((((((((((((((((%(((((99*6+@+*97
7.9(((((%((%((((((((#%(699*+@+6*
+*976%(%#((#%(9.9*6+@
```
[Try it online!](https://tio.run/##dZNBjsMgDEX3vgayhIKaRRZO2aVH6D1GmkV7f8ZANUr9f/hdRKnzQPbj5/f1bk2zrbUu5Si21D33pUnnSvp5FB1/eJ15odeZV813/jB@vnqVRVYmi@K2jKHEmjGUeFUIxKViKLFUjCSNRE3HguHEDUPPaAUjOWkgaiI7H5R4LxiZAwt9JP3hs75jZErwTSSDqb0QiYaRjfQRFOuw9cLFaeyYh0apT@pLsdVfn@7BdH6eUuYXJ///t/gghbkf@iZMexRFmMswgquqCGO@I4zJjjAV5jrcid5Nojq7EsJUx@MxzxPY6/syz0nrSFPo6ZjkiGOGA06Y3pElxi36Qsm@1hxlPA9Bxobq/Rjv@9XwT1trt8fzDw "Lost – Try It Online") [Verify it!](https://tio.run/##dZXBitswEIbPmacQa4Rku1FYt3jXgUBa6LVQeughDYtJnK4haxlbJuTp05GdLlnNRBOEsX/9mow@Me3Zvdrm86V@a23nhO2h7ezfrnwTK9EppS5S56YoknSd5knxpP2QkZxGJK@PIMcPqMtRiLocVdM7fBh/OLwqD700M1i7TNNgHQtNg3W8JySOSUGDdUwLGhDJ0FFG64QG75jRYHPMUxqgIxk4yojZec06Pqc0YDqwoI5MffizfqYBEwQfHZmDKbyQOuY0IGPqSBDzZuYOixOx43nIEOob9CHNDb6@uQcT81OWMK244f99i6slcOwHdQMOewoKcCyTI7inCs043qkZBzs1k8CxTu6EryaDOnclgEOdpsdxHhF6cV@Oc6Z0TFHY7DjIqR1HOLEDDu/QC3Keog9W8GQKHcJ4ewgwbiixHuN7fzVw6QU7wOZxOX/cYluoG6fVt7OrxM4OjVuqT@JYNfraL0zV7Oy@0qrsd3Wt4jgG2FcH0Q3Ny9H27uWq@6@PlzA71e5V2BZNlF@LhuqkYlH24oBfZwdz6mpXva@AWVe5oWuwS5l2XHZ4aMf@lYmFbd3C7zNOpj2L@defwrs@xKaryr3GfOzgfFu7l5Hp22ON//FPo1Bc9n3lO@LgNst5thWrldioXz7H33764afvaptoXwRUxYvFl/jyDw "Python 3 – Try It Online")
This works similarly to the [one posted in chat](https://chat.stackexchange.com/transcript/message/52967651#52967651), with a shorter execution part and some extra stuff trimmed off the right edge. I've golfed about a hundred bytes off the edges, but perhaps I should look for a shorter inner section before that.
[Here is a formatter](https://tio.run/##K0gtyjH7/z@3UsEhUcFWITo9tURDUwdMxlpzgYSTgMIaGmARveT83CSFqDoFBE8zokJB2yEx2iAWwrWz0ysuTSouKdJAErTmAvIUbGzq7OyA5oHVJFaCBJNggolQwf//VTU0zCwttbQdtM20LM01QECVSxVMA4XNgOJAYTOooBFMpYUlukojkEoLS5BKAA) that takes a few lines and formats them in this square, though some minor edits to the lines/columns with `@`s in them are necessary to get it actually working.
[Answer]
# ~~504~~ 503 bytes
```
+6*9+ 18((%(( 77*54*+@
6*9+-09((%(( 99*54*+@+
*9+ 18((%(( 77*54*+@+6
9+-09((%(( 99*54*+@+6*
+ 18((%(( 77*54*+@+6*9
-09((%(( 99*54*+@+6*9+
18((%(( 77*54*+@+6*9+
9((%(( 99*54*+@+6*9+-0
((%(( 77*54*+@+6*9+ 18
(%(( 99*54*+@+6*9+-09(
%(( 77*54*+@+6*9+ 18((
(( 99*54*+@+6*9+-09((%
( 77*54*+@+6*9+ 18((%(
99*54*+@+6*9+-09((%((
77*54*+@+6*9+ 18((%((
9*54*+@+6*9+-09((%(( 9
*54*+@+6*9+ 18((%(( 77
54*+@+6*9+-09((%(( 99*
4*+@+6*9+ 18((%(( 77*5
*+@+6*9+-09((%(( 99*54
+@+6*9+ 18((%(( 77*54*
@+6*9+-09((%(( 99*54*+
```
[Try it online!](https://tio.run/##bc0xCsMwEETRfk6hRjDsIrBBkrOdc4Tcw5Aiuf9Gwe20n8fM9f58M31aeNkfZCXLcdjo5if@tW1x14i7OpT1CWWnQVkLKBsOZR2Ktg2CrjMoG4SyJJRlhbKVUHaNKEsoWgKCrjMoGwZlbUDZ0aFsNyhrnpnt@foB "Lost – Try It Online")
After a `%` is reached, switching off the safety, there are enough `(`s to empty the stack. Next:
```
Going east: 99*54*+@ produces 101 (e)
77*54*+@ produces 69 (E)
Going south: 97*54*+@ produces 83 (S)
79*54*+@ produces 83 (S)
Going west: 90-+9*6+@ produces 87 (W)
81 +9*6+@ produces 87 (W)
Going north: 91-+9*6+@ produces 78 (N)
80 +9*6+@ produces 78 (N)
```
-1 by removing one `(`, allowing one more line to be one byte shorter.
] |
[Question]
[
The task here is to write a program that takes an natural number, \$n\$, and produces the \$n\$th term of an OEIS sequence. That sequence should have an identifier in the form of `A` followed by 6 digits. Now when you take your source code and reverse the order of it's bytes to produce a new program, that program should also implement an OEIS sequence. The new sequence should be identified by an `A` followed by the same 6 digits as last time but in reverse order (including leading zeros).
Now to keep things from being trivial neither the OEIS identifier number nor your program can be palindromes. That is the sequences and programs should be different. You cannot choose a sequence for which it's reverse does not exist or is empty.
For each of your sequences you may choose to either use 0 or 1 indexing. They do not have to use the same indexing. Since some OEIS sequences have a limited domain you need only output the correct numbers for the domain of the sequence. Your required behavior is undefined outside of the domain (you can output `0`, crash, order a pizza, etc.).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 4 bytes ([A000040](http://oeis.org/A000040) and [A040000](http://oeis.org/A040000))
```
Ø=>≠
```
[Try it online!](https://tio.run/##yy9OTMpM/W9o4Ob3//AMW7tHnQv@/wcA)
[!enilno ti yrT](https://tio.run/##yy9OTMpM/W9o6O73/1HnAjvbwzP@/wcA)
Explanation:
```
Ø # nth prime
= # output
>≠ # ignored
```
:noitanalpxE
```
≠ # boolean negation (0 if n == 1, 1 otherwise)
> # increment
= # output
Ø # ignored
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 55 bytes (A055642 and A246550)
```
+*.comb#}]1-_$[)4+_$^**X]_$^[)*..2,emirp-si&(perg(tros{
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplqZgq/BfW0svOT83Sbk21lA3XiVa00Q7XiVOSysiFkhFa2rp6RnppOZmFhXoFmeqaRSkFqVrlBTlF1f/t@YqTqxUyE0sUFBL01GIMzLgsv5vBAA "Perl 6 – Try It Online")
This is a anonymous Whatever lambda implementing the OEIS sequence [A055642](http://oeis.org/A055642) (length of the decimal representation of \$n\$) 0-indexed.
```
{sort(grep(&is-prime,2..*)[^$_]X**^$_+4)[$_-1]}#bmoc.*+
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplqZgq/C/uji/qEQjvSi1QEMts1i3oCgzN1XHSE9PSzM6TiU@NkJLC0hpm2hGq8TrGsbWKifl5ifraWn/t@YqTqxUyE0sUFBL01Ew1NMzMuD6bwQA "Perl 6 – Try It Online")
The reverse is the sequence [A246550](http://oeis.org/A246550) (the ordered list of \$x^e\$ where \$x\$ is prime and \$e \ge 4\$) 1-indexed.
Most of this challenge was just finding a good sequence with a not too complicated reverse.
Update: Using [torcado's answer](https://codegolf.stackexchange.com/a/188220/76162), this can be 19 bytes (A010851 and A158010)
```
{256*$_**2-$_}#{21}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9rI1ExLJV5Ly0hXJb5WudrIsPZ/cWKlQpqGkeZ/AA "Perl 6 – Try It Online")
[Answer]
# [\/\/>](https://github.com/torcado194/worm), ~~15~~ 14 bytes ([A010851](http://oeis.org/A010851) and [A158010](http://oeis.org/A158010))
```
cn;n*-1*"Ā":j
```
effectively `cn`, output 12
```
j:"Ā"*1-*n;nc
```
effectively `j:"Ā"*1-*n`, n(256n-1)
thanks to a friend for finding incredibly simple sequences!
[Answer]
# Haskell, 47 bytes ([A000010](https://oeis.org/A000010) and [A010000](https://oeis.org/A010000))
Both sequences are relatively simple.
```
p n=sum[1|x<-[1..n],gcd x n<2]--2+n*n=n p;1=0 p
```
[Try it online!](https://tio.run/##FctLCoAgFAXQrdxhP0WdlktoBSEhFSXl49EHHLR3ozM/m7/25ThyZpC9njjoN3Vi0FKSa9ZpRgJ1xglhaqrIErjVVoFz9IFgET33Iwo@A92Q4BL/1Uq5/AE "Haskell – Try It Online")
`p n` = the Euler totient function of n (A000010) (1-indexed)
Reversed:
```
p 0=1;p n=n*n+2--]2<n x dcg,]n..1[-<x|1[mus=n p
```
[Try it online!](https://tio.run/##DcpLCoAgFAXQrdxhP0WdlktoBSIhFSXl49EHGrR364zPGs5t3vecGcrqlkGWKqqNEN50hAfTuDSepNROdM@rXbpPS@CcQiRYpMD9gIKPSBckuIRTf1bK5w8 "Haskell – Try It Online")
`p n` = 1 if n = 0, otherwise n^2 + 2
It would be interesting to see an answer which doesn't use comments...
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes (A030000 and A000030)
```
f=lambda n,k=0:k if`n`in`2**k`else f(n,k+1)#]0[`n`:n adbmal
```
[Try it online!](https://tio.run/##DclBCoAgEADAryx0UetgHgVfEoEbaom6iXXp9eZcp37vdZPqPZiM5XAItCQjdYIYLNlIVgmRrM@Ph8DGzSufdrmN0wTojoK51xbphYKVhaUhnZ4pyXn/AQ "Python 2 – Try It Online")
Defines a function `f`, returning the nth term of [A030000](http://oeis.org/A030000) (smallest nonnegative number \$k\$ such that the decimal expansion of \$2^k\$ contains the string \$n\$), 0-indexed
```
lambda n:`n`[0]#)1+k,n(f esle`k**2`ni`n`fi k:0=k,n adbmal=f
```
[Try it online!](https://tio.run/##DckxDoAgDADArzRxAXVARhJeoiaUSJUAlaiLr0dvvfo@x8m6kV1axuI3BDaO3azWTk5DGlkQhDsHl/peO47/UYRklP0PcPMFs6VWr8gPFKyCxgt5D0IrKdsH "Python 2 – Try It Online")
An anonymous function returning the nth term of [A000030](http://oeis.org/A000030) (Initial digit of \$n\$), 0-indexed
---
Shorter version, which takes strings as input (for both sequences), and both still 0-indexed:
# [Python 2](https://docs.python.org/2/), 56 bytes
```
f=lambda n,k=0:`k`*(n in`2**k`)or f(n,k+1)#]0[n:n adbmal
```
[Try it online!](https://tio.run/##FcmxCoAgEADQXzlo8czBHIW@JAJPygrzEnPp662Wt7z81P1i01oYT0p@IWAVR21ddFIwHOyMlNHhVSCIr/oBu1lPbBlo8YnOlsvBFRJlEdTvXYsqxNsqjEbE9gI "Python 2 – Try It Online")
```
lambda n:n[0]#)1+k,n(f ro)`k**2`ni n(*`k`:0=k,n adbmal=f
```
[Try it online!](https://tio.run/##FckxDoAgDADArzRxociAjCa8RE2oUdQglSCLr0ddbrn0lP1iU70d60lxXgi450FPDXZtUCw85AtdkNI4PoCFdMH12n4FtMyRTutrygcXiJSEV793ySoTb6swGhHrCw "Python 2 – Try It Online")
] |
[Question]
[
There's a satirical song called [*Little Boxes*](https://en.wikipedia.org/wiki/Little_Boxes), originally by Malvina Reynolds, about suburban sprawl that has lyrics as follows:
>
> Little boxes on the hillside,
>
> Little boxes made of ticky-tacky,
>
> Little boxes on the hillside,
>
> Little boxes all the same.
>
> There's a green one and a pink one
>
> And a blue one and a yellow one,
>
> And they're all made out of ticky-tacky
>
> And they all look just the same.
>
>
>
Your job here is, given an integer input `n>1` that represents the size of the house, output the four "little boxes" using the following colors (in 0xRRGGBB notation):
```
Green -- 0x00FF00
Pink --- 0xFF00FF (technically magenta)
Blue --- 0x0000FF
Yellow - 0xFFFF00
```
*If your particular console doesn't have these exact colors, you may use the closest available (e.g., ANSI escape codes).*
The houses are constructed with `n` `_` representing the floor and roofline. They are surrounded by `n/2` (round-up) `|` characters representing the walls. The roofs are always `2` high and are two `/` on the left edge, two `\` on the right edge, and `n-2` `-` representing the roof peak. As the houses get larger, the comparative size of the roof gets smaller; this is intended.
Here's a house of size `2`:
```
/\
/__\
|__|
```
Here's size `3`:
```
/-\
/___\
| |
|___|
```
Here's size `7`:
```
/-----\
/_______\
| |
| |
| |
|_______|
```
Thus given an input of `7`, output four houses of size `7` as described above, with the first one in green, the second in pink (magenta), the third in blue, and the fourth in yellow. *Output of the colors in that order is important.*
Example picture of size `3`:
[](https://i.stack.imgur.com/tLaDB.png)
### Rules
* The houses can be horizontal or vertical so long as there is a clear separation between them.
* Leading/trailing newlines or other whitespace are optional, provided that the houses line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, etc.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# JavaScript (ES6), Chrome / Firefox, ~~156~~ ~~148~~ ~~151~~ 150 bytes
*Saved 8 bytes thanks to @Shaggy*
*Saved 1 byte thanks to @Neil*
```
n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))
```
### Demo
Make sure to open the console of your browser to get the colored output.
```
let f =
n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))
f(3)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ ~~121~~ ~~119~~ ~~111~~ ~~109~~ 108 bytes
* Saved two bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing); using the actual unprintable ASCII character instead of escaping it (`\33`)
* Could (and did) save a byte by writing an entire program using `input()` instead of defining a function
* Saved seven bytes thanks to [ElPedro](https://codegolf.stackexchange.com/users/56555/elpedro); using the fact that `str(90+n)` with `0<=n<=9` is `"9%s"%n`
* Saved ~~two~~ three bytes by using string formatting rather than string concatenation
```
N=input()
for(n)in"2543":Z="_"*N;print"[9%sm /"%n+~-~-N*"-"+"\ \n/%s\\\n"%Z+~-N/2*("|%s|\n"%" "*N)+"|%s|"%Z
```
[Try it online!](https://tio.run/##K6gsycjPM/r/3882M6@gtERDkystv0gjTzMzT8nI1MRYySrKVileScvPuqAoM69ESTraUrU4V0FfSTVPu063TtdPS0lXSVspRiEmT1@1OCYmJk9JNQoo46dvpKWhVKNaXAMSUVIAmqCpDeYD5f//NwIA "Python 2 – Try It Online")
Uses [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) for coloring the houses.
[Answer]
# Excel VBA, 243 Bytes
Anonymous VBE immediate window function that takes input from `A1` and outputs to the range `A2:A5`
```
[C1]=vbLf:For i=1To 4:Cells(i+1,1)=[" /"&Rept("-",A1-2)&"\"&C1&"/"&Rept("_",A1)&"\"&C1&Rept("|"&Rept(" ",A1)&"|"&C1,A1/2)&"|"&Rept("_",A1)&"|"]:Cells(i+1,1).Font.Color=Array(32768,&HFF00FF,rgbBlue,65535)(i-1):Next:Cells.Font.Name="Courier New"
```
### Output
[](https://i.stack.imgur.com/Xmhfx.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~79~~ ~~76~~ ~~74~~ ~~73~~ 72 bytes
```
3#²¤r1'f ò3 w £Ol"%c /{ç- ¤}\\
/{ç'_}\\
{/2-½ ç"|{ç}|
"}|{ç'_}|"Xi`¬l:#
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=MyOypHIxJ2Yg8jMgdyCjT2wiJWMgL3vnLSCkfVxcCi975ydffVxcCnsvMi29IOcifHvnfXwKIn18e+cnX318IlhpYKxsjjoj&input=Mg==) (Open your browser's console before hitting "Run").
Thanks to ETH for helping me to test this last night while I was working it up on my phone.
---
## Explanation
Implicit input of integer `U`
```
3#²¤r1'f ò3 w
```
First we build an array of 3-digit hex colours to map over. The charcode of `²` is 178 so `3#²` gives us 3178. We convert that to a base-2 string with `¤` and then replace all occurrences of `1` with `f`. `ò3` splits the string into an array of strings of length 3 and `w` reverses that array.
(I need to figure out a way to shorten that, somehow.)
```
£Ol
```
We map over the array using `£` - with `X` being the current element - and `Ol` logs to console. We'll be passing 2 strings to that, one containing the house and one containing the CSS.
```
Xi`¬l:#
```
The second string is constructed using `i` to prepend `X` with the compressed string `color:#`.
```
"%c /{ç- ¤}\\
```
The `%c` tells the console to use the second string as CSS. The top line of the house is built by repeating (`ç`) the `-` character `U` times and then slicing that from the second element (0-indexed) with `¤`. The braces act as a shortcut, of sorts, for string concatenation.
```
/{ç'_}\\
```
The second line is built in a similar way, this time repeating the `_` character `U` times.
```
{/2-½ çRi|²iUç 1}
```
The body of the house is built by first repeating the `|` character twice with `²` and then inserting a space repeated `U` times into that string at index 1. The resulting string is then prepended to a newline (`R`) and that string is repeated `U/2-0.5` times.
```
|{ç'_}|"
```
Finally, the last line is built in the same way as the second.
[Answer]
# [Python 2](https://docs.python.org/2/), 120 bytes
```
n=input()
for i in'2543':s='_'*n;print'[1;3'+i+('m /'+'-'*(n-2)+'\ \n/%s\\\n'%s+(-~n/2-1)*('|'+' '*n+'|\n')+'|%s|\n'%s)
```
[Try it online!](https://tio.run/##HcyxCsMgFEbhva/QxUV@9SIS0ywNeZIK3Urv0BuJdihIX91K5/Nx8qc@d4m9y8aS39XY02M/FCsWxOUy41o23OFkzQdLxfk2rTOIyeClAggezoiPlpBUkqBLSkmgCxn/lRD9ZJ1BG1CNCaGNOGzTpf2Z7X35AQ "Python 2 – Try It Online") (shows escape chars instead of actual colors, tested on local terminal)
[Answer]
# [Yabasic](http://www.yabasic.de), 220 bytes
An anonymous function that takes input as an integer, `n` and outputs 4 colored homes to the terminal.
The lack of a dedicated string repeating or replacement function in yabsic really hurts this response.
```
Clear Screen
Input""n
b$="__"
c$="| "
For i=1To n-2
a$=a$+"-"
b$=b$+"_"
c$=c$+" "
Next
c$=c$+"|\n"
For i=1To n-4
d$=d$+c$
Next
For i=0To 3
?Color(Mid$("gremagbluyel",1+3*i,3))" /"+a$+"\\\n/"+b$+"\\\n"+d$+"|"+b$+"|"
Next
```
This version requires graphics mode and thus does not work on TIO.
### Output
The input value for the below is `n=7`.
[](https://i.stack.imgur.com/vkd65.png)
[Answer]
# SmileBASIC, 115 bytes
```
INPUT N
H.H 6H 4H 2DEF H C
COLOR C+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END
```
Another one which is also 115 bytes:
```
INPUT N
FOR J=0TO 3COLOR!!J*8-J*2+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END
```
The colors codes I need (in 4-bit RGBI) are 5, 11, 9, 7. This is generated using `!!J*8-J*2+5` If J is not 0, this is `13-J*2` (giving 11,9,7), and if it is, the result is just 5.
] |
[Question]
[
Imagine a straight river and a road that goes across the river **n** times through bridges. The road does not loop on itself and is infinitely long. This road would be considered an open meander. An [open meander](https://www.wikiwand.com/en/Meander_(mathematics)#/Open_meander "Meander (mathematics) - Wikipedia") is an open curve, that does not intersect itself and extends infinitely at both ends, which intersects a line **n** times.
A valid meander may be described entirely by the order of the intersection points it visits.
The number of distinct patterns of intersection with **n** intersections a meander can be is the **nth meandric number**. For example, n = 4:

**The first few numbers of this sequence are:**
```
1, 1, 1, 2, 3, 8, 14, 42, 81, 262, 538, 1828, 3926, 13820, 30694, 110954...
```
This is [OEIS sequence A005316](https://oeis.org/A005316 "A061084 - OEIS").
## Challenge
Write a **program/function** that takes a positive integer **n** as input and prints the **nth meandric number**.
### Specifications
* [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") apply.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**.
* Your solution **can either be 0-indexed or 1-indexed** but please specify which.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that compute this sequence are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.
## Test cases
These are 0-indexed. Note that you need not handle numbers this big if your language cannot by default.
```
Input Output
1 1
2 1
11 1828
14 30694
21 73424650
24 1649008456
31 5969806669034
```
In a few better formats:
```
1 2 11 14 21 24 31
1, 2, 11, 14, 21, 24, 31
```
[Answer]
# [Python 3](https://docs.python.org/3/), 208 188 187 184 180 177 171 bytes
```
lambda n:sum(all(i-j&1or(x<a<y)==(x<b<y)for(i,(a,b)),(j,(x,y))in d(enumerate(map(sorted,zip((0,)+p,p+(n,)))),2))for p in d(range(n)))
from itertools import*;d=permutations
```
[Try it online!](https://tio.run/##VY0xbsMwDEXn5hScArJmgbjdkvgmXWhYbhlYFCHLRZzLu3I6ldPH/3iPvpbvZB/b2H1uk8R@ELDzvESUaUJ9ux3blPF@letKXVdDX8NYK2UU7okYb4x3XonUYMBgSwxZSsAojnPKJQz8UEc8MTXO3qAx1eN32j3g8OSy2FdAq8NhzCmClpBLStMMGr1aXi9D5yHHpUjRZPO2s8rws@P/n44Mf7aWoT1V4/nw4lmtYAvNk6HtFw "Python 3 – Try It Online")
Now **1-indexed** (was previously 0-indexed but 1-indexing saved a byte due to a lucky quirk regarding the behavior of meanders).
### Explanation
This may be the same as [the link](http://www.combinatorics.org/ojs/index.php/eljc/article/view/v19i2p43/pdf) posted by [Jenny\_mathy](https://codegolf.stackexchange.com/users/67961/jenny-mathy), but I didn't end up reading the paper, so this is just the logic behind my method.
I will be using the following illustration provided on [OEIS](https://oeis.org/A005316) in order to visualize the results.
[](https://i.stack.imgur.com/l743Z.png)
Each valid meander may be described entirely by the order of the intersection points it visits. This may be trivially observed in the image; the entry segment is always on the same side (otherwise the number would be double). We can represent the tendency of both the entry and exit segments to their respective infinities by simply adding to every order a point on either side - that is to say, the order `(2, 1, 0)` would become `(-1, 2, 1, 0, 3)`.
With this in mind, the task is to find the number of orders, or permutations of the range up to `n`, which do not intersect with themselves. Intersections are only an issue between pairs of points for which the connecting segment lies on the same side. For any two pairs of consecutive points in a permutation whose segments share a side, whether or not they intersect is equivalent to whether one, and only one, of the points of one pair is between the two elements of the other pair. As such, we can determine if an order is valid by whether there are no pairs with one point contained by another pair with a segment on the same side.
Finally, having determined the validity of each permutations, the output of the function comes down to the number of permutations found to be valid.
[Answer]
# [Haskell](https://www.haskell.org/), 199 bytes
```
1!x=x
-1!(-1:x)=1:x
n!(i:x)=i:(n-i)!x
0#([],[])=1
0#_=0
n#(a,b)=sum$((n-1)#)<$>(-1:a,-1:b):[(a,-i:b)|i:a<-[a]]++[(-j:a,b)|j:b<-[b]]++[(j!a,i!b)|i:a<-[a],j:b<-[b],i+j>=0]
f n=n#([],[-1,1])+n#([1],[1])
```
[Try it online!](https://tio.run/##TY7NasMwDMfvfgqb9GATO0Q99GDivkHZAxhTlLG0ShNTmg5y6LPPUyiDXcTv/yGhKy63r2kqBdQaVuFAaQd@NYGHyErTxuR1dmTUKtpKx2Rj4pz5HFqRK422N2H5nneaa2Aq0@2O2xW0PHrjIzccMb3IY@ciplTXUbvRb5uv0fds9m9zVGhJ/avav9hSPR5Dm8Qgc8jvPxxYSKbeFLBkLjNSlkHOeD@dpb4/KD9lIwcjIzQNHFL5@RwmvCzFfex/AQ "Haskell – Try It Online")
Based on an extension of the ideas in Iwan Jensen, [Enumerations of plane meanders](https://arxiv.org/abs/cond-mat/9910313), 1999 to the case of open meanders. This runs through *n* = 1, …, 16 in about 20 seconds on TIO.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~127~~ 115 bytes
```
⊃⊃⌽{↓⍉(⊃,/c),∘(+/)⌸(≢¨c←{1↓¨⍳¨⍨0,¨((×2↑¯1⌽⍵)/¯1 1⌽¨⊂⍵),(⊂∊#⍵#),(××/m,≠/m)/⊂1↓¯1↓(⊢-⍵×~)⍵∊m←2↑¯1⌽⍵}¨⊃⍵)/⊃⌽⍵}⍣⎕⌽1,⊂⍳2
```
[Try it online!](https://tio.run/##VU/BSsNAEL3nKxZ62IQmJLuJJfVvQiRSTKmkvUipByuxqU2piMSj1ktuPZRSKXhJ/mR@JL5NvQi7s/Nm37w3E9zG1tVdEI@urTAOxuNB2ND6bTCidONotHiKGlrO1Vn9TCl9pTzTgUw7NExavOtd26DVt07ZtipD9EwFSFVJ@V6F0jGrUtfrQlL6Uu0ERCg/GDZSpgA4ywdVMXWVLJYdgA5QXdSFPTQp@7CHho2/VnanIphbC7S6uDfwoGkI338GM6U7b53Ok6sa5V9YDECYreleNlhPo3ytuvgsUtNzk595HDdp8/zA4QjOEaUw4RHXJoqqvLPPBGlE@elSaacbPrrh9Pz4B6JgEEPjBGoya3TRhavwjElVYn0mmct8JjzmSeYD9iS7cFHwpc/cvuwx4frSYa7T63ua9Qs "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Below is a (schematic) [Digital timing diagram](https://en.wikipedia.org/wiki/Digital_timing_diagram), for the [XNOR](https://en.wikipedia.org/wiki/XNOR_gate) logic gate.
```
┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘ └─┘ └─┘ └─┘ └──
┌───┐ ┌───┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐
B ┘ └─┘ └─┘ └─┘ └───┘ └─┘ └
┌─────┐ ┌─┐ ┌─┐ ┌───┐
X ──┘ └───┘ └───┘ └───┘ └────
```
Your goal is to reproduce it exactly as depicted.
Rules:
* You can either print it or return a multiline string;
* Arbitrary number of traling and/or leading newlines are allowed;
* Trailing (but not leading !) whitespace is allowed;
* If you can not use the extended ASCII box-drawing characters,
you may substitute them for the unicode equivalents (at no byte penalty).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins.
**Binary Representation**
For your convenience, binary representation of the diagram above is as follows:
```
INP A=0101011101010110
INP B=1101101011100101
___
X=A⊕B=0111001001001100
```
**Sample Output**
[](https://i.stack.imgur.com/YlQJf.png)
**Sidenote**
While working on this question, I've implemented two different bash solutions for it, one is 122 characters/bytes long (as depicted above), and another one is exactly 100 bytes long.
I do not have plans to post them (as I don't normally post answers to my own questions), so that is just for reference.
I also believe that at least some sub-100 byte solutions are possible.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 101 bytes ~~+ 5 UTF-8 bytes = 116 Total Bytes =~~ ***106 Bytes***
(LEGACY 05AB1E VERSION, NO LONGER ON TIO)
```
•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•6B"102345"" ┌─┐└┘"‡6ävyN" A B X"èì}»
```
[Try it online!](https://tio.run/nexus/05ab1e#AacAWP//4oCiPSjDjW7Cp8OAb8OgYMWTwq9fZcOoOHkxw5zFuCzDmsKuOsK5JDosw7VLQeKAk3hbw4LDrDDDo1jDlGZ6fXnDl8OswrnDj8K9dUXDnDXDpMOAVMOrQMK6UcOI4oSiw7HDszrDsuKApkXDpOKAojZCIjEwMjM0NSIiIOKUjOKUgOKUkOKUlOKUmCLigKE2w6R2eU4iIEEgQiBYIsOow6x9wrv//w "05AB1E – TIO Nexus")
The compression:
```
•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•
# Pattern, converted to base-6 in base-6=214.
111023102310222223102310231022231112251425142511111425142514251114221022231022231023102222231110231023151114251114251425111114222514251411102222231110231110231110222311111225111114222514222514222511142222
# Actual base-6 pattern.
1110231023102222231023102310222311
1225142514251111142514251425111422
1022231022231023102222231110231023
1511142511142514251111142225142514
1110222223111023111023111022231111
1225111114222514222514222511142222
#Pattern split into chunks of 34.
┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
──┘ └─┘ └─┘ └─┘ └─┘ └─┘ └──
┌───┐ ┌───┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐
┘ └─┘ └─┘ └─┘ └───┘ └─┘ └
┌─────┐ ┌─┐ ┌─┐ ┌───┐
──┘ └───┘ └───┘ └───┘ └────
# Pattern after replacing 0,1,2,3,4,5 with appropriate blocks.
```
The conversion:
```
6B # Convert back to base-6.
"102345"" ┌─┐└┘"‡ # Replace numbers with appropriate counterparts.
6ä # Split into 6 equal parts (the rows).
vy } # For each row (chunk).
N" A B X"èì # Push label at index [i], prepend to line.
» # Print all separated by newlines.
```
Using the **CP-1252** encoding.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 76 bytes
```
00000000: 92d6 3000 5431 1505 1403 50e8 4e0a aafc ..0.T1....P.N...
00000010: 9f62 15e6 a3ff 61fa dc05 e06d 8b66 cbc7 .b....a....m.f..
00000020: e6b6 cff8 519a b85a 3eb6 b67d 95c0 0feb ....Q..Z>..}....
00000030: 35b5 521d 7f7e 68af a916 fa20 d999 564d 5.R..~h.... ..VM
00000040: 1f03 d559 59ed 265c f243 42be ...YY.&\.CB.
```
[Try it online!](https://tio.run/##Tc@7TgQxDAXQnq@4FaWVlz0TCgqoQYAQEogmTmIo2HJL@PXBI1aACyuKfI9sPap@zLfjYdvCqS5Q0xBkf4JLjogcGLGEDA5zRZmhoTXrAFGgx0hed3Tr/exHiLthkjw5BS2bQaI1jO7QDDKwqgi69sUN3fNtbweyXyO5MUV9ymwFx9qgKzfk6X8qy0DlHhBs6r4H0T3RyyXRJ/3tkd3IrAxOcWCxZULWZmg1CqylgFFrBUsZANMD0df7Hnfv6eZkFDei@e2D2UfrHEjCHZZKRkk68a88@/xM5690fUXb9g0 "Bubblegum – Try It Online")
Uses box-drawing characters from the VT100 alternate character set, which TIO can’t demonstrate. Run in a UNIX terminal for best results. My terminal converts the ACS to UTF-8 on copy-and-paste, so you can see the effect here.
```
anders@change-mode:/tmp$ bubblegum xnor.zlib
┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘ └─┘ └─┘ └─┘ └──
┌───┐ ┌───┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐
B ┘ └─┘ └─┘ └─┘ └───┘ └─┘ └
┌─────┐ ┌─┐ ┌─┐ ┌───┐
X ──┘ └───┘ └───┘ └───┘ └────
▒┼␍␊⎼⎽@␌▒┼±␊-└⎺␍␊:/├└⎻$
```
Well, the challenge didn’t say we need to take the terminal back *out* of ACS mode before returning to the shell. Good luck with that.
[Answer]
# Ruby, 113 bytes
counting printed symbols as one byte as authorised by the challenge (I was surprised to discover they are actually 3 bytes.)
```
6.times{|i|s=' A B X'[i]
'D]zunIWkF]nIRukFH'.bytes{|b|s+=' ┌─┐───┘ └'[(b*2>>i/2*2&6)-i%2*6,2]}
s[1]=' '
puts s}
```
6 lines of output lends itself to an encoding of 6 bits per each character of the magic string. But the magic string characters actually encode for each transition thus:
```
least significant bit 0 New value for A
1 Current value for A
2 New value for B
3 Current value for B
4 New value for X
5 Current value for X
most significant bit 6 Always 1 (to remain in printable range)
```
This is decoded to find the 2 characters that must be printed for each transition (the first of which is either space or a horizontal line.)
The 8-character strings for the upper and lower rows overlap: The last two characters for the upper row `11` are two horizontal lines, which matches with what is needed for the first two characters of the lower row `00`. The 8 characters for the lower row wrap around: they are last 6 and first 2 characters of the symbol string.
**Ungolfed code**
```
6.times{|i|s=' A B X'[i] #iterate through 6 lines of output. Set s to the 1st character.
'D]zunIWkF]nIRukFH'.bytes{|b| #for each byte in the magic string
s+=' ┌─┐───┘ └'[(b*2>>i/2*2&6)- #add 2 bytes to s, index 0,2,4, or 6 of the symbol string depending on relevant 2 bits of the magic string.
i%2*6,2] #if the second (odd) row of a particular graph, modify index to -6,-4,-2, or 0
} #(ruby indices wrap around. mystring[-1] is the last character of the string.)
s[1]=' ' #replace intitial ─ of the curve with space to be consistent with question
puts s #output line
}
```
[Answer]
## PowerShell, 255 characters, 265 bytes (UTF-8)
```
$a=' 012 012 0111112 012 012 01112
A 113 413 413 413 413 413 411
01112 01112 012 0111112 012 012
B 3 413 413 413 41113 413 4
0111112 012 012 01112
X 113 41113 41113 41113 41111'
0..4|%{$a=$a-replace$_,('┌─┐┘└'[$_])};$a
```
This works on my computer, but doesn't seem to parse the bytes correctly on [TIO](https://tio.run/nexus/powershell#@6@SaKuuAAQGhkZQDAJGKHwjLkcFQ0NjBRMoBgETFL6JoSGXAkQtnESYBTedy0nBGKpXAc00uPlcENcg60SQILdEgN2CrAtBQsQM1bkM9PRMalSrgb5TSdQtSi3ISUxOVYnX0VB/NKXn0ZSGR1MmPJoy49GUKerRKvGxmrXWKon//wMA "PowerShell – TIO Nexus")...
[](https://i.stack.imgur.com/rLy7T.png)
This sets `$a` to be a multi-line string filled with numbers and spaces, then loops `0..4|%{...}`. Each iteration, we `-replace` the appropriate digit `$_` with the appropriate character `'┌─┐┘└'[$_]` and store it back into `$a`. Then, we just leave `$a` on the pipeline and output is implicit.
[Answer]
## JavaScript (ES6), ~~163~~ ~~158~~ 154 bytes
NB: counting UTF-8 characters as bytes, as authorized by the challenge.
```
_=>[..." A B X"].map((c,i)=>c+" "+[...Array(33)].map((_,j)=>j%2?" ─"[p^i&1]:" ┐┌─└┘ "[p+(p=[27370,42843,12878][i>>1]>>j/2&1)*2+i%2*3]).join``,p=0).join`
`
```
### Demo
```
let f =
_=>[..." A B X"].map((c,i)=>c+" "+[...Array(33)].map((_,j)=>j%2?" ─"[p^i&1]:" ┐┌─└┘ "[p+(p=[27370,42843,12878][i>>1]>>j/2&1)*2+i%2*3]).join``,p=0).join`
`
console.log(f())
```
*Saved 4 bytes thanks to Neil*
[Answer]
## C, ~~213~~ 205 bytes
For a change, the C program size, on this challenge, isn't completely ridiculous compared to other languages.
```
#define X(a) u[i]=C[a],l[i++]=C[(a)+4]
p(n,c){char u[34],l[34],*C=" ┐┌──└┘ ",i=0;while(i<34)X(n&3),n>>=1,X((n&1)*3);printf(" %.33s\n%c %.33s\n",u,c,l);}main(){p(0xD5D4,'A');p(0x14EB6,'B');p(0x649C,'X');}
```
Ungolfed, define expanded, and commented:
```
p(n,c){
// u is the upper line of the graph, l the lower line
char u[34],l[34],*C=" ┐┌──└┘ ",i=0;
while(i<34)
u[i]=C[n&3], // using the two LSBs to set the transition char depending on the current and next state
l[i++]=C[(n&3)+4], // do for both upper and lower lines
n>>=1, // shift bits right to go to next state
u[i]=C[(n&1)*3], // using only the LSB to set the "steady" char depending on current state only
l[i++]=C[((n&1)*3)+4]; // do for both upper and lower lines
printf(" %.33s\n%c %.33s\n",u,c,l);
}
main() {
// Call p for each graph
// Constants are chosen so the display is consistent with the request.
// Each bit represents a state, but the order is reversed
// (leftmost is put on lowest significant bit, after a 0)
p(0xD5D4,'A');p(0x14EB6,'B');p(0x649C,'X');
}
```
Note: the *C* string must *not* contain unicode characters. All displayable characters must be plain old 8-bit chars (but they may be chosen in the extended range). So basically, the validity of the output depends on your code page.
[Answer]
# tcl, 221 chars, 299 bytes
```
lmap {b _ n u A V} {" " ┌─────┐ ┌───┐ └───┘ ┌─┐ └─┘} {puts "[set S \ $b][set m $A\ $A] $_ $m $n
A ──┘ [set w $V\ $V][set s \ $S]$w $V$b└──
$n $n $A $_$b$m
B ┘$b$V$b$w$s$u $V └
$S$_$b$A$b$A$b$n
X ──┘$s$u $u $u$b└────"}
```
can be run on: <http://rextester.com/live/VVQU99270>
] |
[Question]
[
# The Golfer Adventure
This is the first challenge ! There will be more challenges later that will require data from the previous challenge :)
## Chapter 1 : The Vase
Let's imagine a minute.. You are a powerful God, your powers are limitless but require one thing : Souls.
Each soul is here represented by a byte, each byte you use does sacrifice a soul.
So the goal is obviously to save the biggest amount of people while sacrificing the least amount of souls.
Your first challenge is to save a little village, the devil is willing not to destroy the entire village if you resolve his challenge.
### The Challenge :
You have a vertical vase which can contain exactly 10 things (Air included).
If you put a thing in that vase, gravity will make that thing fall to the bottom.
If the vase is already full (and it's always full if you consider it as "full of air"), the input will replace the element at the top of the vase.
Here is the set of allowed things :
* Air `0 /`
* A Rock `1 / -`
* A Leaf `2 / ~`
* A Bomb `3 / x`
If there is a rock or a leaf on top of "A Bomb", it will explode and destroy the thing on the top of it.
The input is the list of the things you'll put in the vase every turn.
**Example :** 11231 : You'll put 2 rocks, then a leaf, then a bomb and finally a last rock.
When the vase is static, you can begin to count with the following rule :
* Rock adds 1 unit to the accumulator
* Leaf multiplies the accumulator by 2
* Bomb decrement the accumulator by 1
* Air does nothing
(You need to start counting from the top of the vase)
Here is the simulation we get using "11231" as input :
```
|-| |-| |~| |x| |-| | | | | | | | | | | | |
| | |-| |-| |~| |x| |-| | | | | | | | | | |
| | | | |-| |-| |~| |x| |-| | | | | | | | |
| | | | | | |-| |-| |~| |x| |-| | | | | | |
| | | | | | | | |-| |-| |~| |x| |-| | | | |
| | | | | | | | | | |-| |-| |~| |x| |-| | |
| | | | | | | | | | | | |-| |-| |~| |x| | |
| | | | | | | | | | | | | | |-| |-| |~| |~|
| | | | | | | | | | | | | | | | |-| |-| |-|
| | | | | | | | | | | | | | | | | | |-| |-|
```
And the output will be 2 (calculated as `((0 x 2) + 1) + 1`)
No need to print all the states of the vase !
### The base program (Python3)
You can execute it to understand how it works.
```
def printVase(vase):
for i in vase:
if i == 1:
print("|-|")
elif i == 2:
print("|~|")
elif i == 3:
print("|x|")
else:
print("| |")
def updateVase(vase):
changed = False
for i in range(len(vase), -1, -1):
if i < len(vase) - 1:
if vase[i+1] == 3 and vase[i] in [1,2]:
vase[i], vase[i+1] = 0, 0
changed = True
if not vase[i+1] and vase[i] in [1, 2, 3]:
vase[i], vase[i+1] = vase[i+1], vase[i]
changed = True
return changed
userInput = input("Vase : ")
vase = [0 for i in range(0, 10)]
oldVase = vase
while updateVase(vase) or userInput != "":
if userInput != "":
vase[0] = int(userInput[0])
userInput = userInput[1::]
printVase(vase)
input()
accumulator = 0
for i in vase:
if i == 1:
accumulator += 1
if i == 2:
accumulator *= 2
if i == 3:
accumulator -= 1
print(accumulator)
```
### Golfed version (Python3, no Vase Display) : 360 bytes = 360 points
```
def u(v):
c=0
for i in range(len(v),-1,-1):
if i<len(v)-1:
if v[i+1]==3 and v[i]in[1,2]:v[i],v[i+1],c=0,0,1
if not v[i+1]and v[i]in[1,2,3]:v[i],v[i+1],c=v[i+1],v[i],1
return c
l,v=input(),[0 for i in range(0, 10)]
while u(v)or l!="":
if l!="":v[0],l=int(l[0]),l[1::]
a=0
for i in v:
if i==1:a+=1
if i==2:a*=2
if i==3:a-=1
print(a)
```
**If you want to test if your program works correctly, you can test this input : 12122111131**
**Correct answer is 43** :) (Thanks Emigna)
### Now for the points :
* (x) points where : x is the amount of bytes needed to write your program.
If you answer after the next challenge is posted, points for this challenge won't be added to your total amount of points.
The goal is to keep a minimum amount of points during the whole challenge :)
If you skip one of the part of the challenge, you'll have (wx + 1) points by default for the skipped part (where wx is the worst score for that challenge).
### Data that will be required for the next challenge :
Output when input = 10100000200310310113030200221013111213110130332101
### Current Champion : [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)
Good luck everyone !
[Answer]
# Python 2 - ~~208~~ ~~191 185 180 172 164~~ 156 bytes
```
t=filter(bool,map(int,input()))
i=a=0
n=len(t)
while 0<n-1>i<11:
if(t[i]>=3>t[i+1]):del t[i:i+2];i,n=0,n-2
i+=1
for x in t[9::-1]:a+=a+x%2*(2-x-a)
print a
```
The breakdown is it removes air and the bombs if it is on the stack then counts.
EDIT : I swapped to Python 2 to save a byte, but now the input should be put in braces like '3312123'
EDIT2 : Im also kinda proud of the accumulator count
EDIT3 : Thanks for all your suggestions I would never have thought I could get it so low
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~28~~ 36 bytes
05AB1E uses [CP-1252](http://www.cp1252.com) encoding.
```
Î0KDvT¹g‚£`sTØõ:žwõ:ì}ÁT£ÀRS"<>·"è.V
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w44wS0R2VMK5Z-KAmsKjYHNUw5jDtTrFvnfDtTrDrH3DgVTCo8OAUlMiPD7CtyLDqC5W&input=MTIxMjIxMTExMzE)
[Answer]
## [Retina](http://github.com/mbuettner/retina), ~~58~~ 56 bytes
```
1+`0|(?<=.{9}).\B|3[12]
+-1=`2
$'
+`13
*\(1`3
-
)T`d
.
```
[Try it online!](http://retina.tryitonline.net/#code=MStgMHwoPzw9Lns5fSkuXEJ8M1sxMl0KCistMT1gMgokJworYDEzCgoqXCgxYDMKLQopVGBkCi4&input=MTIxMjIxMTExMzE)
[Answer]
## Python 2, ~~150~~ 146 bytes
```
v=[]
s=0
for c in input():
v=v[:9]
if'0'==c:1
elif 3 in v[-1:]and c in'21':v=v[:-1]
else:v+=[int(c)]
for x in v[::-1]:s+=s+x%2*(2-x-s)
print s
```
Thanks to Pâris Douady for the points formula, and for saving 4 bytes.
[Answer]
## Javascript, ~~267~~ ~~264~~ 249 souls sacrificed
```
r='replace'
f=t=>{t=t[r](/0/g,'');while(/3[12]/.test(t.substring(0,10)))t=t[r](/3[12]/,'');
a=t.length-1;x=(t.substring(0,9)+(a>8?t[a]:'')).split('').reverse().join('');
c='c=0'+x[r](/1/g,'+1')[r](/2/g,';c*=2;c=c')[r](/3/g,'-1');eval(c);return c}
```
Edited version, because the previous one was incorrect for larger inputs. Golfed it a little further by making `string.prototype.replace()` into an array-accessed function call. Explanation:
```
f=t=>{ Function declaration, input t
t=t.replace(/0/g,''); Remove air
while(/3[12]/.test(t.substring(0,10))) Look for bombs; not double bombs, and only in the first 10 chars
t=t.replace(/3[12]/,''); Detonate bombs. If this makes a new bomb fall into the vase, or
a double bomb is now a single bomb, it'll detonate that bomb too.
x=(t.substring(0,9)+ Fill the vase, take the first 9 items
(t.length>9?t[t.length-1]:'')) If we have more than 9 items, then add the last one
.split('').reverse().join(''); Flip the instruction string.
c='c=0'+x.replace(/1/g,'+1') Replace each item with the proper instruction to the ACC
.replace(/2/g,';c*=2;c=c')
.replace(/3/g,'-1');
eval(c);return c} Eval to get the value of ACC and return it.
```
`f('11231');` returns `2`.
[Try it online](https://repl.it/E7ip/1)
[Answer]
# Haskell, ~~221 202 181 177~~ 166 ~~souls~~ bytes
```
g(0:r)=r++[0]
g(3:x:r)|0<x,x<3=0:0:g r|1<3=3:g(x:r)
g(x:r)=x:g r
g r=r
v%(x:r)=g(init v++[x])%r
v%[]|v==g v=foldr([id,(+)1,(*)2,(-)1]!!)0v|1<3=g v%[]
(([0..9]>>[0])%)
```
[Try it on ideone](http://ideone.com/CLMFau). Takes items as integer list.
### Usage:
```
*Prelude> (([0..9]>>[0])%) [1,2,1,2,2,1,1,1,1,3,1]
43
```
### (Edit: Old) Explanation:
```
g [] = [] -- g simulates gravity in the vase
g ('0':r) = r ++ "0" -- the first 0 from the bottom is removed
g ('3':x:r) | elem x "12" = "00"++g r -- if a 1 or 2 is on a bomb, explode
| True = '3' : g(x:r) -- else continue
g (x:r) = x : g r -- no air and no bomb, so check next item
c x = [id,(+)1,(*)2,(-)1]!!(read[x]) -- map 0, 1, 2, 3 to their score functions
f v w (x:r) = -- v is the current vase state, w the previous one
init v++[x] -- replace last vase element with input
g(init v++[x]) -- simulate one gravity step
f(g(init v++[x]))v r -- repeat, w becomes v
f v w[] | v==w = -- if the input is empty and vase reached a fixpoint
foldr c 0 v -- then compute score
| True = f (g v) v [] -- else simulate another gravity step
vase input = f "0000000000" "" input -- call f with empty vase, previous vase state and
-- the input as string of numbers
```
] |
[Question]
[
### Definition
A vector *a* containing *n* elements is said to
[majorize](https://en.wikipedia.org/wiki/Majorization) or
[dominate](https://en.wikipedia.org/wiki/Dominance_order) a vector *b* with *n*
elements iff for all values *k* such that 1 ≤ *k* ≤ *n*, the sum of the first
element of *a↓* through the *k*th element of *a↓* is
greater than or equal to the sum of the first through *k*th elements of
*b↓*, where *v↓* represents the vector *v* sorted in
descending order.
That is,
```
a_1 >= b_1
a_1 + a_2 >= b_1 + b_2
a_1 + a_2 + a_3 >= b_1 + b_2 + b_3
...
a_1 + a_2 + ... + a_n-1 >= b_1 + b_2 + ... + b_n-1
a_1 + a_2 + ... + a_n-1 + a_n >= b_1 + b_2 + ... + b_n-1 + b_n
```
where *a* and *b* are sorted in descending order.
For the purpose of this challenge, we will be using a slight generalization of
majorization: we will say a list is an *unsorted majorization* of another if
all of the above inequalities are true without sorting *a* and *b*. (This is,
of course, mathematically useless, but makes the challenge more interesting.)
### Challenge
Given an input of two distinct lists *a* and *b* of integers in the range 0
through 255 (inclusive), both lists of length *n* ≥ 1, output whether the first
list unsorted-majorizes the second (*a* > *b*), the second unsorted-majorizes
the first (*b* > *a*), or neither.
You may optionally require the length of the two lists to be provided as input.
The output must always be one of three distinct values, but the values
themselves may be whatever you want (please specify which values represent *a*
> *b*, *b* > *a*, and neither in your answer).
Test cases for *a* > *b*:
```
[255] [254]
[3,2,1] [3,1,2]
[6,1,5,2,7] [2,5,4,3,7]
```
Test cases for *b* > *a*:
```
[9,1] [10,0]
[6,5,4] [7,6,5]
[0,1,1,2,1,2] [0,1,2,1,2,1]
```
Test cases for no majorization:
```
[200,100] [150,250]
[3,1,4] [2,3,3]
[9,9,9,9,9,0] [8,8,8,8,8,9]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**2 bytes thanks to @orlp.**
**2 bytes thanks to @Dennis.**
```
_+\ṠQS
```
[Try it online!](http://jelly.tryitonline.net/#code=Xytc4bmgUVM&input=&args=WzYsMSw1LDIsN10+WzIsNSw0LDMsN10)
`1` for `a>b`, `-1` for `a<b`, `0` for no majorization.
```
_+\ṠQS
_ Difference (vectorized)
+\ Cumulative sum.
Ṡ Sign of every difference
Q Deduplicate
S Sum
```
If there were both `1` and `-1` present (some cumulative sums are bigger, some smaller), then the last step would produce `0`.
[Answer]
# ngn/apl, 11 bytes
```
{+/∪×+\⍺-⍵}
```
Based on the method in @Leaky Nun's [answer](https://codegolf.stackexchange.com/a/87591/6710).
Given two lists *A* and *B*, find the difference between each value elementwise, or let *C* = *A - B*. Then, find the cumulative sums of *C* and take the sign of each. The sum of the unique sign values will be the result. If *A* > *B*, the result is 1, if *A* < *B* the result is -1, and if there is no majority the result is 0.
[Try it online.](http://ngn.github.io/apl/web/index.html#code=6%201%205%202%207%20%7B+/%u222A%D7+%5C%u237A-%u2375%7D%202%205%204%203%207)
[Answer]
# Julia, 30 bytes
```
a^b=sum(sign(cumsum(a-b))∪0)
```
Saved 4 bytes thanks to @Dennis!
[Answer]
# Python 3.5, 85 bytes:
```
lambda*e:[all(sum(g[:k])>=sum(h[:k])for k in range(1,-~len(h)))for g,h in[e,e[::-1]]]
```
An anonymous lambda function. Returns `[True,False]` if `a>b`, `[False,True]` if `b>a`, or `[False,False]` if neither of those are true. I hope this is okay.
[Try It Online! (Ideone)](http://ideone.com/cmpNgi)
[Answer]
# [Cheddar](https://github.com/cheddar-lang/Cheddar), ~~118~~ 114 bytes
```
n->[n.map(i->i[0]-i[1]).map((j,k,l)->l.slice(0,k+1).sum).map(i->i>0?1:i<0?-1:0)].map(j->j has 1?j has-1?0:1:-1)[0]
```
Basically a port of [my Jelly answer](https://codegolf.stackexchange.com/a/87591/48934).
The fact that scope inside function is broken causing inability to define variable inside function means that I would need to do `[xxx].map(i->yyy)[0]` instead of `var a=xxx;yyy`.
Takes transposed array as input.
```
n->[n
.map(i->i[0]-i[1]) Difference (vectorized)
.map((j,k,l)->l.slice(0,k+1).sum) Cumulative sum.
.map(i->i>0?1:i<0?-1:0)] Sign of every difference
.map(j->j has 1?j has-1?0:1:-1)[0] Deduplicate and Sum
```
[Answer]
# Python 2, 73 bytes
```
a,=b,=r={0}
for x,y in zip(*input()):a+=x;b+=y;r|={cmp(a,b)}
print sum(r)
```
Test it on [Ideone](http://ideone.com/UPWw1R).
[Answer]
# Ruby, ~~72~~ 59 bytes
Returns `1` for `a>b`, `-1` for `a<b`, `0` for neither.
*-13 bytes from cribbing the sum trick off of @Dennis in their Python answer*
[Try it online!](https://repl.it/CjU4/1)
```
->a,b{x=y=0;a.zip(b).map{|i,j|(x+=i)<=>y+=j}.uniq.inject:+}
```
[Answer]
## Python 2, 59 bytes
```
t=r=0
for x,y in zip(*input()):t+=x-y;r|=cmp(t,0)%3
print r
```
Outputs:
* `1` for `a>b`
* `2` for `b>a`
* `3` for neither
Iterates through the list, tracking the running sum `t` of differences. The number `s` tracks what signs have been seen as a two-bit number `r`: positives in the right bit and negatives in the left bit. This happens via `cmp(t,0)%3`, which gives
* `t>0` → `+1` → 1
* `t==0` → `0` → 0
* `t<0` → `-1` → 2
Taking the `or` of this and the current value of `r` updates the 2 bits with `or`, with zero values having no effect.
[Answer]
# Javascript (using external library-Enumerable) (123 bytes)
```
(a,b)=>(z=(c,d)=>_.Range(1,c.length).All(x=>_.From(c).Take(x).Sum()>=_.From(d).Take(x).Sum()))(a,b)==z(b,a)?0:(z(a,b)?1:-1)
```
Link to lib: <https://github.com/mvegh1/Enumerable>
Code explanation: Pass in vector a and b, create global function z. z will begin by creating an array of integers from 1, for a count of a.length. .All will verify that the predicate is true for every member belonging to a. That predicate says to load a as an enumerable, take a count of that enumerable equivalent to the current iteration value of that range we made, and sum that up. Check if that >= the same logic from array "b". So, we call z in the order of (a,b), and compare that to the order of (b,a)...if equal we return 0 to signify there is no major. Otherwise, we return 1 if (a,b) is true, else -1
[](https://i.stack.imgur.com/3rV8A.png)
] |
[Question]
[
The [Secretary Problem](https://en.wikipedia.org/wiki/Secretary_problem) is a famous problem described as thus:
1. You need a new secretary
2. You have N applicants that you can interview one at a time
3. You are able to score each applicant after the interview. Your scoring system will never give two applicants the same score
4. After you interview an applicant, you must give an immediate "yes" or "no"
5. You want the applicant with the highest score
The solution is to interview the first `floor(N/e)` applicants, and then accept the first applicant that has a higher score than all of the previous applicants. If none of the applicants are higher, then return the last applicant. Interestingly enough, this gives the top applicant `1/e` percent of the time. `e` refers to [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant)). To get the value of `e`, you can use a builtin, `log`, or hardcode it to at least 5 decimal points.
# Input:
An non-empty array of unique non-negative integers no more than `2^31-1`.
# Output:
An integer representing the chosen candidate. To be clear the algorithm is:
1. Find the maximum element in the first `floor(N/e)` elements of the array.
2. Iterate through the remaining elements, and return the first element that is higher than the maximum found on step 1.
3. If none of the elements are higher, than return the last element.
For example, say your array was `[2,7,4,3,9,20]`, so `N = 6` and `floor(N/e) = 2`. The first 2 elements of the array is `[2,7]`. The max of `[2,7]` is `7`. The remaining elements are `[4,3,9,20]`. The first element that is greater than `7` is `9`, so we return `9`.
# Test Cases:
```
[0] => 0
[100] => 100
[100, 45] => 100
[0, 1] => 0
[45, 100] => 45
[1, 4, 5] => 4
[1, 5, 4] => 5
[5, 4, 1] => 1
[5, 1, 4] => 4
[4, 1, 5] => 5
[56, 7, 37, 73, 90, 59, 65, 61, 29, 16, 47, 77, 60, 8, 1, 76, 36, 68, 34, 17, 23, 26, 12, 82, 52, 88, 45, 89, 94, 81, 3, 24, 43, 55, 38, 33, 15, 92, 79, 87, 14, 75, 41, 98, 31, 58, 53, 72, 39, 30, 2, 0, 49, 99, 28, 50, 80, 91, 83, 27, 64, 71, 93, 95, 11, 21, 6, 66, 51, 85, 48, 62, 22, 74, 69, 63, 86, 57, 97, 32, 84, 4, 18, 46, 20, 42, 25, 35, 9, 10, 19, 40, 54, 67, 70, 5, 44, 13, 78, 96]
=> 98
[10, 68, 52, 48, 81, 39, 85, 54, 3, 21, 31, 59, 28, 64, 42, 90, 79, 12, 63, 41, 58, 57, 13, 43, 74, 76, 94, 51, 99, 67, 49, 14, 6, 96, 18, 17, 32, 73, 56, 7, 16, 60, 61, 26, 86, 72, 20, 62, 4, 83, 15, 55, 70, 29, 23, 35, 77, 98, 92, 22, 38, 5, 50, 82, 1, 84, 93, 97, 65, 37, 45, 71, 25, 11, 19, 75, 78, 44, 46, 2, 53, 36, 0, 47, 88, 24, 80, 66, 87, 40, 69, 27, 9, 8, 91, 89, 34, 33, 95, 30]
=> 30
```
Your solution must be `O(n)`, where `n` is the length of the array. If your language has a builtin that finds the maximum of an array, you can assume that the function takes `O(n)` (and hopefully it does).
Standard loopholes apply, and this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the make the shortest answer in your favorite language!
[Answer]
# Jelly, 13 bytes
```
L:Øe³ḣȯ-Ṁ<i1ị
```
Definitely an **O(n)** algorithm, hopefully an **O(n)** implementation. [Try it online!](http://jelly.tryitonline.net/#code=TDrDmGXCs-G4o8ivLeG5gDxpMeG7iw&input=&args=WzU2LCA3LCAzNywgNzMsIDkwLCA1OSwgNjUsIDYxLCAyOSwgMTYsIDQ3LCA3NywgNjAsIDgsIDEsIDc2LCAzNiwgNjgsIDM0LCAxNywgMjMsIDI2LCAxMiwgODIsIDUyLCA4OCwgNDUsIDg5LCA5NCwgODEsIDMsIDI0LCA0MywgNTUsIDM4LCAzMywgMTUsIDkyLCA3OSwgODcsIDE0LCA3NSwgNDEsIDk4LCAzMSwgNTgsIDUzLCA3MiwgMzksIDMwLCAyLCAwLCA0OSwgOTksIDI4LCA1MCwgODAsIDkxLCA4MywgMjcsIDY0LCA3MSwgOTMsIDk1LCAxMSwgMjEsIDYsIDY2LCA1MSwgODUsIDQ4LCA2MiwgMjIsIDc0LCA2OSwgNjMsIDg2LCA1NywgOTcsIDMyLCA4NCwgNCwgMTgsIDQ2LCAyMCwgNDIsIDI1LCAzNSwgOSwgMTAsIDE5LCA0MCwgNTQsIDY3LCA3MCwgNSwgNDQsIDEzLCA3OCwgOTZd)
### How it works
```
L:Øe³ḣȯ-Ṁ<i1ị Main link. Argument: A (list of scores)
L Get the length of A.
:Øe Divide the length by e, flooring the result.
³ḣ Retrieve the that many scores from the beginning of A.
ȯ- Logical OR; replace an empty list with -1.
Ṁ Compute the maximum of those scores.
< Compare each score in A with that maximum.
i1 Find the first index of 1 (0 if not found).
ị Retrieve the element of A at that index (the last one if 0).
```
[Answer]
# CJam, 20 Bytes
```
q~___,1me/i<:e>f>1#=
```
Works similarly to Dennis's suggestion.
```
q~___ Read array, duplicate three times
, Consume one to find the length
1me/i Push e then divide and take floor
< Take that many elements from the list
:e> Find maximum (Thanks to Dennis)
f> Label array elements larger than this as 1
1# Find the first one (won't be in set of elements we've looked in)
= Take that element from the final copy of the array. -1 gives us the last element as required
```
[Answer]
## Java, ~~128~~ 118 bytes
```
a->{int c=(int)(a.length/Math.E),i=0,m=-1,t=0;for(;i<a.length;i++){t=a[i];if(i<c)m=t>m?t:m;if(t>m)return t;}return t;}
```
Indented:
```
static Function<Integer[], Integer> secretary2 = a -> {
int c = (int) (a.length/Math.E), // c = floor(N/E)
i = 0, m = -1, t = 0; // declare vars early to save bytes
for (;i<a.length;i++) { // for each element of input
t = a[i]; // cache element to save bytes
if (i<c) // if before c
m = t>m ? t : m; // m = max(m, element)
if (t>m) // if element > m
return t; // return: we've found our best
} // if never found a good element
return t; // return the last element
};
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~27~~ ~~25~~ 23 bytes
```
tttn1Ze/:)-1hX>>T0(f1))
```
Uses the same approach as [A. Simmons' CJam answer](https://codegolf.stackexchange.com/a/75991/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=dHR0bjFaZS86KS0xaFg-PlQwKGYxKSk&input=WzU2LCA3LCAzNywgNzMsIDkwLCA1OSwgNjUsIDYxLCAyOSwgMTYsIDQ3LCA3NywgNjAsIDgsIDEsIDc2LCAzNiwgNjgsIDM0LCAxNywgMjMsIDI2LCAxMiwgODIsIDUyLCA4OCwgNDUsIDg5LCA5NCwgODEsIDMsIDI0LCA0MywgNTUsIDM4LCAzMywgMTUsIDkyLCA3OSwgODcsIDE0LCA3NSwgNDEsIDk4LCAzMSwgNTgsIDUzLCA3MiwgMzksIDMwLCAyLCAwLCA0OSwgOTksIDI4LCA1MCwgODAsIDkxLCA4MywgMjcsIDY0LCA3MSwgOTMsIDk1LCAxMSwgMjEsIDYsIDY2LCA1MSwgODUsIDQ4LCA2MiwgMjIsIDc0LCA2OSwgNjMsIDg2LCA1NywgOTcsIDMyLCA4NCwgNCwgMTgsIDQ2LCAyMCwgNDIsIDI1LCAzNSwgOSwgMTAsIDE5LCA0MCwgNTQsIDY3LCA3MCwgNSwgNDQsIDEzLCA3OCwgOTZdCg)
[Answer]
# JavaScript (ES6) 64
```
(a,l=a.length/Math.E,x)=>(a.every(v=>--l>0?x>v?1:x=v:(z=v)<x),z)
```
*Less golfed*
```
(
a,
l=a.length/Math.E, // limit for stage 1
x // init at undefined
)=>(
a.every(v => --l > 0 // checking for >0 no need to floor
? x>v?1:x=v // stage 1, find max in x, always return truthy
: (z=v)<x ) // stage 2, set z to current value and exit early if z>x
, z // at last z has the last seen value
)
```
**Test**
```
f=(a,l=a.length/Math.E,x)=>(a.every(v=>--l>0?x>v?1:x=v:(z=v)<x),z)
console.log=x=>O.textContent+=x+'\n'
;[
[0], [100], [0,1], [1,2,3],
[100, 45],
[45, 100],
[1, 4, 5],
[1, 5, 4],
[5, 4, 1],
[5, 1, 4],
[4, 1, 5],
[10, 68, 52, 48, 81, 39, 85, 54, 3, 21, 31, 59, 28, 64, 42, 90, 79, 12, 63, 41, 58, 57, 13, 43, 74, 76, 94, 51, 99, 67, 49, 14, 6, 96, 18, 17, 32, 73, 56, 7, 16, 60, 61, 26, 86, 72, 20, 62, 4, 83, 15, 55, 70, 29, 23, 35, 77, 98, 92, 22, 38, 5, 50, 82, 1, 84, 93, 97, 65, 37, 45, 71, 25, 11, 19, 75, 78, 44, 46, 2, 53, 36, 0, 47, 88, 24, 80, 66, 87, 40, 69, 27, 9, 8, 91, 89, 34, 33, 95, 30],
[56, 7, 37, 73, 90, 59, 65, 61, 29, 16, 47, 77, 60, 8, 1, 76, 36, 68, 34, 17, 23, 26, 12, 82, 52, 88, 45, 89, 94, 81, 3, 24, 43, 55, 38, 33, 15, 92, 79, 87, 14, 75, 41, 98, 31, 58, 53, 72, 39, 30, 2, 0, 49, 99, 28, 50, 80, 91, 83, 27, 64, 71, 93, 95, 11, 21, 6, 66, 51, 85, 48, 62, 22, 74, 69, 63, 86, 57, 97, 32, 84, 4, 18, 46, 20, 42, 25, 35, 9, 10, 19, 40, 54, 67, 70, 5, 44, 13, 78, 96]
].forEach(t=>{
var r=f(t)
console.log(r+' : '+t)
})
```
```
<pre id=O></pre>
```
[Answer]
# Ruby, 64 bytes
```
->a{m=a[0...c=a.size/Math::E].max
a[c..-1].find{|n|n>m}||a[-1]}
```
[Answer]
# [PARI/GP](http://pari.math.u-bordeaux.fr/), 70 bytes
This may have trouble on older versions of gp when given a singleton, but it works at least from revision 18487.
```
v->m=vecmax(v[1..t=#v\exp(1)]);for(i=t+1,#v,v[i]>m&&return(v[i]));v[#v]
```
[Answer]
## JavaScript (ES6), 79 bytes
```
a=>(m=Math.max(...a.splice(0,a.length/Math.E)),a.slice(a.findIndex(x=>x>m))[0])
```
Works because `findIndex` returns `-1` on failure, but `a.slice(-1)[0]` returns the last element of the array as desired.
[Answer]
# Python 2, 87 bytes
```
a=input()
t=int(len(a)/2.71828)
m=max(a[:t]+[-1])
for x in a[t:]:
if x>m:break
print x
```
The user enters the array as a list, with square brackets and commas. Python 2's `input()` command is convenient here.
Whether or not we terminate the process early, we hire the last person who got interviewed.
[Answer]
# Perl 6, 43 bytes
I think this is O(n)
```
{@^a.first(*>max @a[^floor @a/e])//@a[*-1]}
```
[Answer]
# Python 3.5; 110 bytes:
```
def Interview(h):k=max(h[0:int(len(h)/2.71828)-1]);n=max(h[int(len(h)/2.71828)-1:len(h)-1]);return max([k, n])
```
Basically, what the above does is that it firstly takes an array provided, "h" *as long as it includes **more than 5 items*** (for now...), finds the maximum value in the first (length of array (len(h))/ Euler's number (to 5 decimal places)) items of that array, and then returns that value as "k". Furthermore, "n" is the maximum value in the rest of the array. Finally, the value returned from the function is the maximum value in an array containing both "k" and "n".
**Note: The `max()` function of Python *is* O(n) complexity.**
Below is a more readable, **non-code-golf** **version** of the above code that has a random, unique 10-item array provided, to confirm that it works:
```
import random, math
def Interview():
k = max(h[0:int(len(h)/math.e)-1])
n = max(h[int(len(h)/math.e)-1:len(h)-1])
return max([k, n])
h = random.sample(range((2*31)-1), 10)
print(Interview(h))
```
] |
[Question]
[
*If you've read the book* Contact *by Carl Sagan, this challenge may seem
familiar to you.*
---
Given an input of a set of mathematical equations consisting of a number, an
unknown operator, another number, and a result, deduce which operators
represent addition, subtraction, multiplication, or division.
Each input equation will always consist of
* a non-negative integer
* one of the letters `A`, `B`, `C`, or `D`
* another non-negative integer
* the character `=`
* a final non-negative integer
concatenated together. For example, a possible input is `1A2=3`, from which you
can deduce that `A` represents addition. Each of the integers will satisfy `0 ≤ x ≤ 1,000`.
However, it's not always as simple as that. It is possible for there to be
ambiguity between:
* `5A0=5`: addition/subtraction
* `1A1=1`: multiplication/division
* `0A5=0`: multiplication/division
* `2A2=4`: addition/multiplication
* `4A2=2`: subtraction/division
* `0A0=0`: addition/subtraction/multiplication
and so on. The challenge is to use this ability to narrow down choices,
combined with process of elimination, to figure out what operator each letter
represents. (There will always be at least one input equation, and it will
always be possible to unambiguously, uniquely match each letter used in the input with a single operator.)
For example, let's say the input is the following equations:
* `0A0=0`: this narrows A down to addition, subtraction, or multiplication
(can't divide by 0).
* `10B0=10`: B has to be either addition or subtraction.
* `5C5=10`: C is obviously addition, which makes B subtraction, which makes A
multiplication.
Therefore, the output for these input equations should match `A` with `*`, `B`
with `-`, and `C` with `+`.
Input may be given as either a single whitespace-/comma-delimited string or
an array of strings, each representing one equation. Output may be either a
single string (`"A*B-C+"`), an array (`["A*", "B-", "C+"]`), or a dictionary / dict-like 2D array (`{"A": "*", ...}` or `[["A", "*"], ...]`).
You may assume that a number will never be divided by another number it isn't divisible by (so, you don't need to worry about whether division should be floating point or truncated).
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
Test cases:
```
In Out
-------------------------------
0A0=0 10B0=10 5C5=10 A*B-C+
100D100=10000 D*
4A2=2 4B2=2 0A0=0 A-B/
15A0=15 4B2=2 2C2=0 A+B/C-
1A1=1 0A0=0 A*
0A0=0 2A2=4 5B0=5 2B2=4 A*B+
2A2=4 0C0=0 5B0=5 5A0=5 A+B-C*
0A1000=0 4A2=2 A/
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 53 bytes
```
j61tthYX'+-*/'X{Y@!"t'ABCD'!XKX{@YXU?K@Y}hwxKGm1L3$).
```
Uses [current version (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0)
*EDIT (June 12, 2016): to adapt to changes in the language, replace `Y}` by `g` and `1L3$)` by `Y)`. The link below incorporates those modifications*
[**Try it online!**](http://matl.tryitonline.net/#code=ajYxdHRoWVgnKy0qLydYe1lAISJ0J0FCQ0QnIVhLWHtAWVhVP0tAZ2h3eEtHbVkpLg&input=MEEwPTAgMTBCMD0xMCA1QzU9MTA)
### Explanation
This tests all possible permutations of the four operators in a loop until one permutation makes all equations true.
To test if equations are true, a regex is applied to replace the four letters by the operators (in the order dictated by the current permutation), and the string is converted to numbers (evaluated). This gives an array with as many numbers as equations, in which equations that are true become `1` and equations that are false become `0`. If this vector only contains `1` values, we're done.
The solution found assigns operators to the four letters, but not all of them necessarily appear in the input. So a final test is done to discard not used letters (and their matching operators).
```
j % input data string
61 % '=' (ASCII)
tth % duplicate twice and concat: '==' (ASCII)
YX % regexprep to change '=' into '==' in input string
'+-*/' % push string
X{ % transform into cell array {'+','-','*','/'}
Y@! % all permutations, each in a column
" % "for" loop. Iterate columns (that is, permutations)
t % duplicate data string containing '=='
'ABCD'!XK % create column array ['A';'B';'C';'D'] and copy to clipboard K
X{ % transform into column cell array {'A';'B';'C';'D'}
@ % push column cell array with current permutation of operator symbols
YX % regexprep. Replaces 'A',...,'D' with current permutation of operators
U % convert to numbers, i.e. evaluate string
? % if all numbers are 1 (truthy result): found it! But before breaking...
K % push column array ['A';'B';'C';'D']
@Y} % push column array with current permutation of operator symbols
h % concatenate horizontally into 4x2 char array
wx % delete original input so it won't be displayed
K % push ['A';'B';'C';'D']
G % push input string
m % logical index that tells which of 'A',...,'D' were in input string
1L3$) % apply that index to select rows of the 4x2 char array
. % we can now break "for" loop
% implicitly end "if"
% implicitly end "for"
% implicitly display stack contents
```
[Answer]
# Python, 278 characters
My first answer on code golf...
It is just a function implementing a brute force algorithm, you call it passing as argument the string of equations.
```
from itertools import *
def f(s):
l=list("ABCD")
for p in permutations("+-*/"):
t=s
for v,w in zip(l+["="," "],list(p)+["=="," and "]):
t=t.replace(v, w)
try:
o=""
if eval(t):
for c,r in zip(l,p):
if c in s:
o+=c+r
return o
except:
pass
```
[Answer]
# JavaScript (ES6), ~~213~~ 208 bytes
```
f=(l,s="+-*/",p="",r)=>s?[...s].map(o=>r=f(l,s[g="replace"](o,""),p+o)||r)&&r:l.split` `.every(x=>(q=x.split`=`)[1]==eval(q[0][g](/[A-D]/g,m=>p[(a="ABCD").search(m)])))&&a[g](/./g,(c,i)=>l.match(c)?c+p[i]:"")
```
## Explanation
Input and output are strings.
Defines a function `f` which doubles as a recursive function for generating all the permutations of the operators and tests complete permutations with the input equations using `eval`.
```
f=(
l, // l = input expression string
s="+-*/", // s = remaining operators
p="", // p = current permutation of operators
r // r is here so it is defined locally
)=>
s? // if there are remaining operators
[...s].map(o=> // add each operator o
r=f(
l,
s[g="replace"](o,""), // remove it from the list of remaining operators
p+o // add it to the permutation
)
||r // r = the output of any permutation (if it has output)
)
&&r // return r
: // else if there are no remaining operators
l.split` `.every(x=> // for each expression
(q=x.split`=`) // q = [ equation, result ]
[1]==eval( // if the results is equal to the eval result
// Replace each letter with the current permutation
q[0][g](/[A-D]/g,m=>p[(a="ABCD").search(m)])
)
)
// If all results matched, add permutation symbols to present characters and return
&&a[g](/./g,(c,i)=>l.match(c)?c+p[i]:"")
```
## Test
Test does not use default arguments for browser compatibility.
```
var solution = f=(l,s,p,r)=>s==null&&(s="+-*/",p="",0)?0:s?[...s].map(o=>r=f(l,s[g="replace"](o,""),p+o)||r)&&r:l.split` `.every(x=>(q=x.split`=`)[1]==eval(q[0][g](/[A-D]/g,m=>p[(a="ABCD").search(m)])))&&a[g](/./g,(c,i)=>l.match(c)?c+p[i]:"")
```
```
<input type="text" id="input" value="2A2=4 0C0=0 5B0=5 5A0=5" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
A polynomial with coefficients in some [field](https://en.wikipedia.org/wiki/Field_(mathematics)) *F* is called [irreducible](https://en.wikipedia.org/wiki/Irreducible_polynomial) over *F* if it cannot be decomposed into the product of lower degree polynomials with coefficients in *F*.
Consider polynomials over the [Galois field](https://en.wikipedia.org/wiki/Finite_field) GF(5). This field contains 5 elements, namely the numbers 0, 1, 2, 3, and 4.
### Task
Given a positive integer *n*, compute the number of irreducible polynomials of degree *n* over GF(5). These are simply the polynomials with coefficients in 0-4 which cannot be factored into other polynomials with coefficients in 0-4.
### Input
Input will be a single integer and can come from any standard source (e.g. STDIN or function arguments). You must support input up to the largest integer such that the output does not overflow.
### Output
Print or return the number of polynomials that are irreducible over GF(5). Note that these numbers get large rather quickly.
### Examples
```
In : Out
1 : 5
2 : 10
3 : 40
4 : 150
5 : 624
6 : 2580
7 : 11160
8 : 48750
9 : 217000
10 : 976248
11 : 4438920
```
Note that these numbers form the sequence [A001692](https://oeis.org/A001692) in OEIS.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~30~~ ~~23~~ ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
ÆF>1’PḄ
ÆDµU5*×Ç€S:Ṫ
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZGPjHigJlQ4biECsOGRMK1VTUqw5fDh-KCrFM64bmq&input=&args=MTA) or [verify all test cases at once](http://jelly.tryitonline.net/#code=w4ZGPjHigJlQ4biECsOGRMK1VTUqw5fDh-KCrFM64bmqCsOH4oKs&input=&args=MSwyLDMsNCw1LDYsNyw4LDksMTAsMTE).
### Algorithm
This uses the formula
$$\text{A001692}(n) = \frac 1 n \sum\_{d|n} \mu(d)5^\frac n d$$
from the OEIS page, where \$d | n\$ indicates that we sum over all divisors \$d\$ of \$n\$, and \$\mu\$ represents the [Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function).
### Code
```
ÆF>1’PḄ Monadic helper link. Argument: d
This link computes the Möbius function of d.
ÆF Factor d into prime-exponent pairs.
>1 Compare each prime and exponent with 1. Returns 1 or 0.
’ Decrement each Boolean, resulting in 0 or -1.
P Take the product of all Booleans, for both primes and exponents.
Ḅ Convert from base 2 to integer. This is a sneaky way to map [0, b] to
b and [] to 0.
ÆDµU5*×Ç€S:Ṫ Main link. Input: n
ÆD Compute all divisors of n.
µ Begin a new, monadic chain. Argument: divisors of n
U Reverse the divisors, effectively computing n/d for each divisor d.
5* Compute 5 ** (n/d) for each n/d.
Ç€ Map the helper link over the (ascending) divisors.
× Multiply the powers by the results from Ç.
S Add the resulting products.
:Ṫ Divide the sum by the last divisor (n).
```
[Answer]
# Mathematica, ~~39~~ 38 bytes
```
DivisorSum[a=#,5^(a/#)MoebiusMu@#/a&]&
```
Uses the same formula as the Jelly answer.
[Answer]
# [Python 3](https://docs.python.org/3.8/), 59 bytes
```
f=lambda n:(5**n-sum(d*f(d)for d in range(1,n)if n%d<1))//n
```
[Try it online!](https://tio.run/##TcpBCoMwEAXQdXuK2QgzQbFBhCL1MJFxNFC/IbWLnj7FnW/90u9Yd3TPlEux8R22SQNh4N45NJ/vxuqMVWzPpBRBOWCZ2deQaIRKX16kbVHOgGvwDy/D/ZZyxMHGECl/ "Python 3.8 (pre-release) – Try It Online")
This uses the formula
$$f(n) = \frac 1 n \sum\_{d|n} \mu(d)5^\frac n d$$
but applies [Möbius inversion](https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula) to turn it into
$$5^n = \sum\_{d|n} f(d) d$$
and solves for \$f(n)\$.
**55 bytes**
```
f=lambda n,d=1:d//n*5**n/n or f(n,d+1)-d*f(d)*(n%d<1)/n
```
[Try it online!](https://tio.run/##DctBCoMwEEbhtT3FbISZqSWNIhTRw6RM0wr1NwQ3nj5m@z5eOo/fjuGVcilx@YftbYHQ2eIncw46qsKB9kyRa757eZhGNlFGa7MXhxKrglZQDvh@2Hf9U6Zbk/KKg@smUi4 "Python 3.8 (pre-release) – Try It Online")
Has float precision issues for larger inputs.
[Answer]
# [Scala](http://www.scala-lang.org/), 74 bytes
Port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/263714/110802) in Scala.
Use the formula: \$5^n = \sum\limits\_{d|n} f(d) d\$
[Try it online!](https://tio.run/##JY2xCsIwGIT3PsUtQn6hsR1cxBR0c/AhYtNIJP4JbapC6bPHiLcc3zfcTb32OofbY@gTrtoxhk8a2Ew4xYilql7awx4unFR3dvfSUMisukX8UexJxvAWTLVoMXNyHkzSOp@GURjV8cYo1ZB86vhDs7XCEMlpftKO1wzYMEIwjjVapIC2aagcoySOjpNnYcs6FbNWa/4C)
```
n=>{(BigInt(5).pow(n)-(1 until n).filter(d=>n%d==0).map(d=>d*f(d)).sum)/n}
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 17 bytes
```
n->ffnbirred(5,n)
```
[Try it online!](https://tio.run/##DcgxDoAwCADArxAnSCCxg2P7F43SsCAh/h@73HBxpsmMUujlMlT9ssznxoOdSt9Ehw6Noe0Mkebfig1kLBSdiOoH "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), without built-in, 33 bytes
```
n->sumdiv(n,d,5^d*moebius(n/d))/n
```
[Try it online!](https://tio.run/##DcgxDoAgDADArzRO1ECQwRGeYqJBTAcKAfH7leWGq2cj81RJ4IVN6CNH@hTrqPcjrrncF42u2EZEy5JKUwwenAa3aaiN@J2xgAmTpBgR5Qc "Pari/GP – Try It Online")
] |
[Question]
[
The game [BattleBlock Theater](http://en.wikipedia.org/wiki/BattleBlock_Theater) occasionally contains a puzzle which is a generalised version of [Lights Out](http://en.wikipedia.org/wiki/Lights_Out_(game)). You've got three adjacent blocks, each of which indicates a level between 1 and 4 inclusive with bars, e.g.:
```
|
||||
||
```
If you touch a block, then that block as well as any adjacent block will increment its level (wrapping back from 4 to 1). The puzzle is solved when all three blocks show the same level (it doesn't matter which level). Since, the order you touch the blocks in doesn't matter, we denote a solution by how often each block is touched. The optimal solution for the above input would be `201`:
```
| --> || --> ||| |||
|||| | || |||
|| || || --> |||
```
The game very easily generalises any number of blocks, although for some numbers, not all configurations are solvable.
## The Challenge
Given a sequence of block levels, return how often each block needs to be touched to solve the puzzle. E.g. the above example would be given as `142` and could yield `201` as a result. If there is no solution, return some *consistent* output of your choice, which is distinguishable from all potential solutions, e.g. `-1` or an empty string.
You may write a function or program, take input via STDIN, command-line argument or function argument, in any convenient list or string format, and similarly output via a return value or by printing to STDOUT.
Your code should return correct results for all test cases within a minute on a reasonable machine. (This is not a completely strict limit, so if your solution takes a minute and ten seconds, that's fine, but if it takes 3 minutes, it isn't. A good algorithm will easily solve them in seconds.)
This is code golf, so the shortest answer (in bytes) wins.
## Examples
Solutions are not unique, so you may get different results.
```
Input Output
1 0
11 00
12 No solution
142 201
434 101
222 000
4113 0230
32444 No solution
23432 10301
421232 212301
3442223221221422412334 0330130000130202221111
22231244334432131322442 No solution
111111111111111111111222 000000000000000000000030
111111111111111111111234 100100100100100100100133
412224131444114441432434 113013201011001101012133
```
As far as I know, there are exactly 4 solutions for each input where the number of blocks is 0 mod 3, or 1 mod 3, and there are 0 or 16 solutions where it is 2 mod 3.
[Answer]
# Python 2, 115 bytes
```
n=input()
for F in range(4):
t=[F];b=0;exec"x=(-n[b]-sum(t[-2:]))%4;t+=x,;b+=1;"*len(n)
if x<1:print t[:-1];break
```
This is the golfed version of the program I wrote while discussing the problem with Martin.
Input is a list via STDIN. Output is a list representing the last solution found if there is a solution, or zero if there isn't. For example:
```
>>>
[1, 4, 2]
[2, 1, 1]
>>>
[1, 2]
0
>>>
map(int,"3442223221221422412334")
[2, 3, 3, 2, 1, 3, 2, 0, 0, 2, 1, 3, 2, 2, 0, 0, 2, 2, 3, 1, 1, 3]
```
---
# Pyth, ~~32~~ 29 bytes
```
V4J]NVQaJ%_+s>J_2@QN4)I!eJPJB
```
The obligatory port. Thanks to @Jakube for the 3 byte saving.
Input method is the same as above, [try it online](https://pyth.herokuapp.com/).
---
## Explanation (long and full of logic!)
First, two basic observations:
* **Observation 1:** It doesn't matter which order you touch the blocks
* **Observation 2:** If you touch a block 4 times, it's equivalent to touching it once
In other words, if there is a solution then there is a solution where the number of touches is between 0 and 3 inclusive.
Since modulo 4 is so nice, let's do that with the blocks too. For the rest of this explanation, block level 0 is equivalent to block level 4.
Now let's denote `a[k]` to be the current level of block `k` and `x[k]` to be the number of times we touch block `k` in a solution. Also let `n` be the total number of blocks. As @Jakube has noted, a solution must satisfy:
```
a[0] + x[0] + x[1]
= a[1] + x[0] + x[1] + x[2]
= a[2] + x[1] + x[2] + x[3]
= a[3] + x[2] + x[3] + x[4]
...
= a[n-1] ... + x[n-2] + x[n-1] + x[n]
= a[n] ... + x[n-1] + x[n]
= C
```
where `C` is the final level all blocks end up on, between 0 and 3 inclusive (remember we're treating level 4 as level 0) and all equations above are really congruences modulo 4.
Now here's the fun part:
* **Observation 3**: If a solution exists, a solution exists for any final block level `0 <= C <= 3`.
There are three cases based on the number of blocks modulo 3. The explanation for each of them is the same — for any number of blocks, there exists a subset of blocks which, if you touch each of them once, increases **all** block levels by exactly 1.
```
0 mod 3 (touch every third block starting from the second):
.X. / .X. / .X.
1 mod 3 (touch every third block starting from the first):
X. / .X. / .X. / .X
2 mod 3 (touch every third block starting from either the first or second):
X. / .X. / .X. / .X.
.X. / .X. / .X. / .X
```
This explains why there are 4 solutions for `0 mod 3` and `1 mod 3`, and usually 16 solutions for `2 mod 3`. If you have a solution already, touching the blocks as above gives another solution which ends up at a higher block level (wrapping around).
So what does this mean? We can pick any final block level `C` we want! Let's pick `C = 0`, because this saves on bytes.
Now our equations become:
```
0 = a[0] + x[0] + x[1]
0 = a[1] + x[0] + x[1] + x[2]
0 = a[2] + x[1] + x[2] + x[3]
0 = a[3] + x[2] + x[3] + x[4]
...
0 = a[n-1] + x[n-2] + x[n-1] + x[n]
0 = a[n] + x[n-1] + x[n]
```
And rearrange:
```
x[1] = -a[0] - x[0]
x[2] = -a[1] - x[0] - x[1]
x[3] = -a[2] - x[1] - x[2]
x[4] = -a[3] - x[2] - x[3]
...
x[n] = a[n-1] - x[n-2] - x[n-1]
x[n] = a[n] - x[n-1]
```
So what we can see is, if we have `x[0]`, then we can use all the equations except the last to find out every other `x[k]`. The last equation is an additional condition we must check.
This gives us an algorithm:
* Try all values for `x[0]`
* Use the above equations to work out all of the other `x[k]`
* Check if the last condition is satisfied. If so, save the solution.
That gives the solution above.
So why do we sometimes get no solution for `2 mod 3`? Let's take a look at these two patterns again:
```
X. / .X. / .X. / .X.
.X. / .X. / .X. / .X
```
Now consider the equations at those positions, i.e. for the first one:
```
0 = a[0] + x[0] + x[1]
0 = a[3] + x[2] + x[3] + x[4]
0 = a[6] + x[5] + x[6] + x[7]
0 = a[9] + x[8] + x[9] + x[10]
```
Add them up:
```
0 = (a[0] + a[3] + a[6] + a[9]) + (x[0] + x[1] + ... + x[9] + x[10])
```
For the second one:
```
0 = a[1] + x[0] + x[1] + x[2]
0 = a[4] + x[3] + x[4] + x[5]
0 = a[7] + x[6] + x[7] + x[8]
0 = a[10] + x[9] + x[10]
```
Add them up again:
```
0 = (a[1] + a[4] + a[7] + a[10]) + (x[0] + x[1] + ... + x[9] + x[10])
```
So if `(a[1] + a[4] + a[7] + a[10])` and `(a[0] + a[3] + a[6] + a[9])` are not equal, then we have no solution. But if they are equal, then we get 16 solutions. This was for the `n = 11` case, but of course this generalises to any number that is `2 mod 3` — take the sum of every third element starting from the second, and compare to the sum of every third element starting from the first.
Now finally, is it possible to figure out what `x[0]` has to be instead of trying all of the possibilities? After all, since we restricted our target level `C` to be 0, there is only one `x[0]` which gives a solution in the `0 mod 3` or `1 mod 3` case (as `4 solutions / 4 final levels = 1 solution for a specific final level`).
The answer is... yes! We can do this for `0 mod 3`:
```
.X..X
.X..X.
```
Which translates to:
```
0 = a[2] + x[1] + x[2] + x[3] -> 0 = (a[2] + a[5]) + (x[1] + ... + x[5])
0 = a[5] + x[4] + x[5] /
0 = a[1] + x[0] + x[1] + x[2] -> 0 = (a[1] + a[4]) + (x[0] + x[1] + ... + x[5])
0 = a[4] + x[3] + x[4] + x[5] /
```
Subtracting gives:
```
x[1] = (a[2] + a[5]) - (a[1] + a[4])
```
Similarly for `1 mod 3` we can do this pattern:
```
.X..X.
X..X..X
```
Which gives:
```
x[0] = (a[2] + a[5]) - (a[0] + a[3] + a[6])
```
These of course generalise by extending the indices by increments of 3.
For `2 mod 3`, since we have two subsets which cover every block, we can actually pick any `x[0]`. In fact, this is true for `x[0], x[1], x[3], x[4], x[6], x[7], ...` (basically any index not congruent to `2 mod 3`, as they are not covered by either subset).
So we have a way of picking an `x[0]` instead of trying all possibilities...
... but the bad news is that this doesn't save on bytes (124 bytes):
```
def f(n):s=[];L=len(n);B=sum(n[~-L%3::3])-sum(n[-~L%3::3]);x=A=0;exec"s+=B%4,;A,B=B,-n[x]-A-B;x+=1;"*L*(L%3<2or B<1);print s
```
[Answer]
# Pyth, ~~72~~ ~~76~~ ~~73~~ ~~66~~ ~~39~~ 38 character
```
Ph+f!eTmu+G%+&H@G_3-@QH@QhH4UtQd^UT2]Y
```
**edit 4:** Realized, that the calculations `Q[N]-Q[N+1]+solution[-3]` and `Q[-2]-Q[-1]+solution[-3]` are ident. Therefore I overcalculate the solution by 1, and filter the solutions, where the last entry is 0. Then I pop the last entry. Luckily the special cases doesn't need an extra treatment with this approach. -27 character
**edit 3:** Applying some golfing tricks from FryAmTheEggman: -7 character
**edit 2:** Using filter, reduce and map: -3 character
**edit 1:**In my first version I didn't printed anything, if there was no solution. I don't think that's allowed, therefore +4 character.
Expects a list of integers as input `[1,4,2]` and outputs a valid solution `[2,0,1]` if there is one, otherwise an empty list `[]`.
## Explanation:
Let `Q` be the list of 5 levels and `Y` the list of the solution. The following equations have to hold:
```
Q0 + Y0 + Y1
= Q1 + Y0 + Y1 + Y2
= Q2 + Y1 + Y2 + Y3
= Q3 + Y2 + Y3 + Y4
= Q4 + Y3 + Y4
```
Therefore if we use any `Y0` and `Y1`, we can calculate `Y2`, `Y3` and `Y4` in the following way.
```
Y2 = (Q0 - Q1 ) mod 4
Y3 = (Q1 - Q2 + Y0) mod 4
Y4 = (Q2 - Q3 + Y1) mod 4
```
Than all levels exept the last one are equal (because we didn't used the equation `= Q4 + Y3 + Y4`. To check, if this last one is also equal to the other levels, we can simply check if `(Q3 - Q4 + Y2) mod 4 == 0`. Notice, that the left part would be the value `Y5`. If I calculate the 6th part of the solution, I can simply check, if it is zero.
In my approach I simply iterate over all possible starts (`[0,0]`, to `[3,3]`), and calculate length(input)-1 more entries and filter all solutions that end with a zero.
```
mu+G%+&H@G_3-@QH@QhH4UtQd^UT2 generates all possible solutions
```
it's basically the following:
```
G = start value //one of "^UT2", [0,0], [0,1], ..., [9,9]
//up to [3,3] would be enough but cost 1 char more
for H in range(len(Q)-1): //"UtQ"
G+=[(H and G[-3])+(Q(H)-Q(H+1))%4] //"+G%+&H@G_3-@QH@QhH4"
//H and G[-3] is 0, when H is empty, else G[-3]
```
then I filter these possible solutions for valid ones:
```
f!eT //only use solutions, which end in 0
```
to this list of solutions I append an empty list, so that it has at least one item in it
```
+....]Y
```
and take the first solution `h`, pop the last element `p` and print it
```
Ph
```
Notice, that this also works, if there is only one block. In my approach I get the starting position [0,0] and doesn't extend it. Since the last entry is 0, it prints the solution [0].
The second special case (2 blocks) isn't that special after all. Not sure, why I overcomplicated things earlier.
[Answer]
# Ruby, ~~320~~ 313 chars
```
m=gets.chop.chars.map{|x|x.to_i-1}
a=m.map{0}
t=->n{m[n]+=1
m[n-1]+=1if n>0
m[n+1]+=1if n<m.size-1
m.map!{|x|x%4}
a[n]=(a[n]+1)%4}
t[0]until m[0]==1
(2...m.size).map{|n|t[n]until m[n-1]==1}
r=0
while m.uniq.size>1&&m[-1]!=1
(0...m.size).each_with_index{|n,i|([1,3,0][i%3]).times{t[n]}}
(r+=1)>5&&exit
end
$><<a*''
```
Can definitely be golfed more. Outputs nothing for unsolvable puzzles.
Ungolfed version:
```
#!/usr/bin/ruby
nums = gets.chomp.chars.map {|x| x.to_i-1 }
touches = nums.map {0}
# our goal: make all the numbers 1
# utility function
touch = ->n {
nums[n] += 1
nums[n-1] += 1 if n > 0
nums[n+1] += 1 if n < (nums.length-1)
nums.map! {|x| x % 4 }
touches[n] = (touches[n] + 1) % 4
}
# first, start with the very first number
touch[0] until nums[0] == 1
# then, go from index 2 to the end to make the previous index right
(2...nums.length).each {|n|
touch[n] until nums[n-1] == 1
}
iters = 0
if nums.uniq.length != 1
# I have no idea why this works
while nums[-1] != 1
(0...nums.length).each_with_index {|n, i|
([1, 3, 0][i % 3]).times { touch[n] }
}
if (iters += 1) > 5
puts -1
exit
end
end
end
puts touches * ''
```
Okay, this one was fun. Here's the basic algorithm, with `{n}` representing n "touch"es on the number above the `n`, as demonstrated on one of the examples:
```
we want each number to be a 1
first make the first number a 1
3442223221221422412334
2}
1242223221221422412334
{3} now keep "touch"ing until the number to the left is a 1
1131223221221422412334
{2}
1113423221221422412334
{2}
1111243221221422412334
... (repeat this procedure)
1111111111111111111110
```
I got stumped for a bit here. How can I turn the `111...1110` into a series of same numbers? So I compared my solution and the correct solution (note: the "touch" counts all are one greater than they should be because the input is 1-indexed, while the output is 0-indexed):
```
3033233103233301320210
0330130000130202221111
```
I noticed that each number was one away from the correct one `mod 4`, so I marked them with `+`s, `-`s, and `=`s:
```
3033233103233301320210 original program output
+-=+-=+-=+-=+-=+-=+-=+ amount to modify by (+1, -1, or 0 (=))
4334534404534602621511 result (the correct answer)
0330130000130202221111 (the original solution, digits equal to result mod 4)
```
That worked for a while, until I noticed that sometimes the final result was `111...11112` or `11...1113` as well! Fortunately, repeatedly applying the magical formula that makes no sense but works also sorted these out.
So, there you have it. A program that starts out making sense, but degrades into more and more ugly hackiness as it goes. Quite typical for a code golf solution, I think. :)
[Answer]
# Python 2, ~~294,289,285,281~~ 273 bytes
```
n=input();l=len(n);s=[0]*l
for i in range(2,l):
a=(n[i-2]-n[i-1])%4;s[i]+=a;n[i-1]+=a;n[i]+=a
if i+1<l:n[i+1]+=a
n=[a%4for a in n]
if l%3>1 and n!=[n[0]]*l:print"x"
else:
for i in range(l%3,l-1,3):s[i]+=(n[l-1]-n[l-2])%4
m=min(s);s=[(a-m)%4 for a in s];print s
```
**[DEMO](http://repl.it/7Ih/4)**
I'm sure this can be golfed further..
Here are the results from the test cases:
```
[1]
-> [0]
[1,1]
-> [0, 0]
[1,2]
-> x
[1,4,2]
-> [2, 0, 1]
[4,3,4]
-> [1, 0, 1]
[2,2,2]
-> [0, 0, 0]
[4,1,1,3]
-> [0, 2, 3, 0]
[3,2,4,4,4]
-> x
[2,3,4,3,2]
-> [0, 0, 3, 3, 1]
[4,2,1,2,3,2]
-> [2, 0, 2, 3, 3, 1]
[3,4,4,2,2,2,3,2,2,1,2,2,1,4,2,2,4,1,2,3,3,4]
-> [0, 3, 3, 0, 1, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 2, 2, 2, 1, 1, 1, 1]
[2,2,2,3,1,2,4,4,3,3,4,4,3,2,1,3,1,3,2,2,4,4,2]
-> x
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2]
-> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4]
-> [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 3, 3]
[4,1,2,2,2,4,1,3,1,4,4,4,1,1,4,4,4,1,4,3,2,4,3,4]
-> [1, 0, 3, 0, 0, 3, 2, 3, 1, 0, 0, 1, 0, 3, 1, 1, 3, 1, 0, 0, 2, 1, 2, 3]
```
The algorithm first makes sure that the values of all blocks except the last block are the same (by iterating through and adding to the "touch counts" of all blocks except the first 2). Then, if the number of blocks allows for it (`(num_of_blocks - 1) % 3 != 1`), goes back and makes sure the values of the rest of the blocks match the last block. Prints `x` if there is no solution.
] |
[Question]
[
[Box blur](https://en.wikipedia.org/wiki/Box_blur) is a simple operation for blurring images. To apply box blur, simply replace each pixel with the average of its and the surrounding 8 pixels' values. Consider, for example, the following example, in which each "pixel" has a one-digit value:
\begin{array} {|r|r|}\hline 1 & 1 & 1 \\ \hline 1 & 7 & 1 \\ \hline 1 & 1 & 1 \\ \hline \end{array}
To get the blurred value of the center pixel we add its value to the 8 surrounding pixels' values and divide by 9.
$$
\frac{7+1+1+1+1+1+1+1+1}{9}=\frac{5}{3}=1.\overline{6}
$$
Repeat this operation for every pixel and you've blurred the image.
## The task
Like pixels, strings are just numbers, so we can box blur them too. Your task is to take a string, which may have multiple lines, in some convenient format and return a new string that's been "blurred" by the above process. That is to say, you'll take each character's ASCII value and treat it as that character's value, "blur" the values, and return the new values' corresponding characters.
For example, given the following input:
```
'''#
''#'
'#''
#'''
```
Your output would look like this:
```
''&%
'&&&
&&&'
%&''
```
## Edges and corners
How do you blur a "pixel" that doesn't have eight neighbors because it's on an edge or in a corner of the "canvas"? For our purposes, you'll solve this by "filling in" the missing pixels with the nearest pixel's value. In the example below the missing value northwest of 1 is filled in with 1; likewise the missing value east of 6 is filled in with 6.
\begin{array} {|r|r|}\hline \color{silver}{1} & \color{silver}{1} & \color{silver}{2} & \color{silver}{3} & \color{silver}{3} \\ \hline \color{silver}{1} & 1 & 2 & 3 & \color{silver}{3} \\ \hline \color{silver}{4} & 4 & 5 & 6 & \color{silver}{6} \\ \hline \color{silver}{7} & 7 & 8 & 9 & \color{silver}{9} \\ \hline \color{silver}{7} & \color{silver}{7} & \color{silver}{8} & \color{silver}{9} & \color{silver}{9} \\ \hline \end{array}
## Rounding
For our purposes, you'll round fractions to the nearest integer. Halves should be rounded up.
## Rules
* The input will consist of one or more lines of one or more printable ASCII characters, i.e. `0x20`–`0x7E` inclusive, plus newlines if applicable to your input format. The string will be "rectangular," i.e. every line will have the same length.
* The input format is flexible, e.g. a single string with lines separated by newlines, an array of strings with one string per line, a multi-dimensional array of characters, etc.
* The output will be in the same format as the input, and likewise flexible.
* [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) and [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/) apply and [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes wins.
## More examples
```
Input Output
111 222
171 222
111 222
XXXXX INNNI
,,X,, ;DDD;
,,X,, ,;;;,
,,X,, ;DDD;
XXXXX INNNI
'888' /020/
8'''8 00/00
8'8'8 2/)/2
8'''8 00/00
'888' /020/
103050709 111324256
!~ JU
~! UJ
Q Q
+--+ <22<
| | <22<
+--+ <22<
^ M
* ;
* ;
^ M
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
4(∩ṘǏǔ)3vl3lƛ∩ṠCvṁṙC
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI0KOKIqeG5mMePx5QpM3ZsM2zGm+KIqeG5oEN24bmB4bmZQyIsIiIsIltcIicnJyNcIiwgXCInJyMnXCIsIFwiJyMnJ1wiLCBcIiMnJydcIl1cbiJd)
A mess. Input as a list of rows, output as a char matrix.
```
4( ) # Four times...
∩Ṙ # Rotate 90°
Ǐǔ # Prepend the first item
3vl # Cut each into chunks of length 3
3l # Cut into chunks of length 3
ƛ # Over each list of lists of chunks...
∩ # Transpose into a list of 3x3 chunks
Ṡ # Stringify each chunk
C # Take the charcodes
vṁṙ # Take the mean of each and round back to integers
C # Convert back to characters
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Image Package, 50 bytes
```
@(X)char(round(imfilter(+X,~~e(3)/9,'replicate')))
```
[Try it online!](https://tio.run/##bVBNi4MwEL37K6anSWrKGkrRVhb2L@xNKG0RjTRgo8S4l7b@dTfpp@xmDjNv3nszMNMUJv8R4/hFMlocc01006uSyFMlayM0CTM2DIIs6ceaoRZtLYvcCKSUjhV8Qq66NDCiMwep2t50ljrDFjnnmALy@F5stwvgT2wxc@EMjGWM@cHd45tGTJLEZmtyxfUPnLzhi366d@BZxaNltIriaO2XZ4PbMMz86refDheL0I1dAC6u3nrfHXunzl9p/890TYOq0WDsb/lG9SdRk8nH6c1dyq4l1ZQ/myudaAhIA6HK8Rc)
[Answer]
# [J](http://jsoftware.com/), 47 45 bytes
```
(0.5<.@+9%~3+/\"#.3+/\(|.@|:@,{:)^:4)&.(3&u:)
```
[Try it online!](https://tio.run/##bY7NCsJADITveYrYotmla6xWhUaFRcGTCHoqaPUgLeLFg3pSfPW66w8iGJhJGOaDHKq0Ju28X5OUCAKmEkeChAZjFKcm42Q5m1Yq5t6QbZTW70nUWgch@6VubG9izVX0Rrq6wSppXERXGuZjxgSTDxa16qG2ZsBbF8pF1JXfaO5JOBen84hxJVjs9kdbYu6qnWfsH4mBiEJnIYETgROBBl9Gd317mR8wJjPmx1/5P2IBunoA "J – Try It Online")
*-2 thanks to ovs*
* `&.(3&u:)` Do everything that follows "under" converting to ascii code. This means it gets converted back automatically at the end.
* `({.|.@|:@,])^:4)` Standard reverse/transpose trick to fill out the sides and top.
* `3+/\"#.3+/\` Even though J has a built-in for applying a verb to "tiles" -- in this case it's 1 byte shorter to scan sum rows in groups of 3, then scan sum colums in groups of 3 to get the 3x3 tile averages.
* `9%~` Divide each by 9 for the average.
* `0.5<.@+` And round.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1ịṭṚZµ4¡O+3\Z$⁺+4:9Ọ
```
A monadic Link that accepts a list of lines and yields a list of lines.
**[Try it online!](https://tio.run/##y0rNyan8/9/w4e7uhzvXPtw5K@rQVpNDC/21jWOiVB417tI2sbJ8uLvn/8PdWw63R/7/r25hYaHOZaGurm4BJC3AJIgNFgcA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/w4e7uhzvXPtw5K@rQVpNDC/21jWOiVB417tI2sbJ8uLvn/8PdWw63R3Idnfxw5@JHjfsObTu07XD7o6Y1WVAO0AhDQy5DcyAG0lwRIMCloxOho4NCQsS51C0sLNS5LNTV1S2ApAWYBLEh4lyGBsYGpgbmBpZcXIp1XHWKXFyBXFzaurraXDUKCjUQFlcclxYQxgEA "Jelly – Try It Online").
### How?
```
1ịṭṚZµ4¡O+3\Z$⁺+4:9Ọ - Link: list of lines, T
µ4¡ - repeat four times (starting with T):
1 - one
ị - index into -> top row
Ṛ - reverse (the current lines)
ṭ - tack -> reversed current lines + top row
Z - transpose
O - convert to ordinals
⁺ - do this twice:
$ - last two links as a monad:
3\ - three-part reduce with:
+ - addition
Z - transpose
+4 - add four
:9 - integer divide by nine
Ọ - convert to characters
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 44 bytes
```
L++hbbebDONRmsM.:d3CN;jmsmC+.5ck9dOOCMMyyM.z
```
[Try it online!](https://tio.run/##K6gsyfj/30dbOyMpKTXJxd8vKLfYV88qxdjZzzortzjXWVvPNDnbMsXf39nXt7LSV6/q//8IEODS0YnQ0UEhweIA "Pyth – Try It Online")
Takes each line of the string as a separate input.
### Explanation
```
L++hbbeb define y(b) as the "filling in" for the edges
DONRmsM.:d3CN; define O(N) to transpose then blur the rows of a list by splitting into sublists of length 3 and mapping to their sum
.z put all available inputs into a list
yyM apply y to the rows and columns
CMM convert strings to lists of codepoints
OO apply the blurring, the two transpositions mean it ends as it started
m d map to
sm the joined strings of the map of
C the ascii value of the floor of
+.5ck9 0.5 + each element divided by 9
j join on newlines
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
WS⊞υι≔E⊞O⁺⟦§υ⁰⟧υ§υ±¹E⁺⁺§ι⁰ι§ι±¹℅λθEυ⭆ι℅÷⁺⁴ΣE✂θκ⁺³κ¹Σ✂νμ⁺³μ¹¦⁹
```
[Try it online!](https://tio.run/##XU89awMxDN3zKzzKoEJDu5RMoV0yJDnIEggdzJ25E/E5F5@d9t87skxJWw@y9T6k53Ywob0Yl/PXQM4q2PgpxUMM5HvQWjVpHiChIr1arOeZeg9bM0GB95MNJl4CNC7NcFrHje/sdxE/609USaP6he1sb6KFpdaMy4jikvKjouIsqx5G@mfch468ceCku3KohpNGycRLau7SsPGdv2baaAP/KX7QjTpb972yMI3iOThqLVxRnVEJ98JPnrzUVVN5j2p88KPwWhK8yb3K@VjOAvGI@KdWPD/d3B0 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:
```
WS⊞υι
```
Input the string to be blurred.
```
≔E⊞O⁺⟦§υ⁰⟧υ§υ±¹E⁺⁺§ι⁰ι§ι±¹℅λθ
```
Prepend and append a copy of the first and last rows, then for each row, prepend and append a copy of the first and last characters, and convert all of the characters to their code points to create an expanded array.
```
Eυ⭆ι℅÷⁺⁴ΣE✂θκ⁺³κ¹Σ✂νμ⁺³μ¹¦⁹
```
Map over the original list of strings, replacing each character with the average of the 3×3 tile taken from the expanded array.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4Fíø¬š}€ü3ü3εøÇÅAòç
```
I/O as character-matrices.
[Try it online](https://tio.run/##yy9OTMpM/f/fxO3w2sM7Dq05urD2UdOaw3uMgejc1sM7DrcfbnU8vOnw8v//o6OV1JV04FhZKVYnGokHomEiynB1IBFlJF1AkVgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamAMXs6/Uc3rUtCbY9r@J2@G1h3ccWnN0YS1Q4PAeYyA6t/XwjsPth1sdD286vPx/LUxzfmkJVLctF7plcDkdr0O7dbgObbP/H62krq6uHJMHJNSBpLI6kAQS6ko6CkqGhoYxeYbmIMLQECQQAQIxeTo6ETo66BRYDqRI3cLCAmiIBdAQCxBlAaHAPLAc2GgDYwNTA3MDSxBHsS4mr04RxAoEEdq6utoxeTUKCjUxeSA2SCwuJk8LjOLAuo2MY/JMTM1i8swtLJViAQ).
**Explanation:**
Step 1: Add the edges and corners as explained in the challenge description:
```
4F # Loop 4 times:
íø # Rotate once counterclockwise:
í # Reverse each inner row
ø # Zip/transpose; swapping rows/columns
¬ # Push the first row (without popping the matrix)
š # Prepend it
} # Close the map
```
[Try just this first step online.](https://tio.run/##yy9OTMpM/f/fxO3w2sM7Dq05urD2///oaCV1JR04VlaK1YlG4oFomIgyXB1IRBlJF1AkFgA)
Step 2: Create overlapping 3x3 blocks:
```
€ # After the loop: map over each inner row:
ü3 # Convert it to a list of overlapping triplets
ü3 # And then convert these lists to overlapping triplets as well
ε # Map over each list of matrices:
ø # Zip/transpose; swapping rows/columns, to create 3x3 blocks
```
[Try just the first two steps online.](https://tio.run/##yy9OTMpM/f/fxO3w2sM7Dq05urD2UdOaw3uMgejc1sM7/v@PjlZSV9KBY2WlWJ1oJB6Ihokow9WBRJSRdAFFYgE)
Step 3: Convert the characters to codepoint integers; get the rounded average of each 3x3 block; and convert these new codepoint integers back to characters (and output as result):
```
Ç # Convert each inner 3x3 block to a flattened list of codepoint integers
ÅA # Get the average of each list
ò # Round each decimal to an integer
ç # Convert this rounded integer back to a character
# (after which the resulting matrix is output implicitly)
```
] |
[Question]
[
These are the classical puzzles:
>
> You need to boil eggs for exactly 9 minutes, or else the visiting Duchess will complain, and you will lose your job as head chef.
>
>
> But you have only 2 Hourglasses, one measures 7 minutes, and the other measures 4 minutes. How can you correctly measure 9 minutes?
>
>
> (taken from [here](https://www.mathsisfun.com/puzzles/hourglasses-1-solution.html))
>
>
>
Let's write a program which will produce a solution for any such puzzle.
Input: 3 numbers a, b, x
Here a and b are the durations of the hourglasses, and x is the required time for boiling the eggs. Let's assume the following:
* 0 < a < b (without loss of generality)
* x is not divisible by a or b (to make the problem non-trivial)
* x > 0
* x is divisible by gcd(a, b) (to ensure a solution exists)
Output: a string which contains commands, such that after executing the commands, we get our eggs boiled for exactly x minutes.
The possible commands are:
* 'A' - turn hourglass A
* 'B' - turn hourglass B
* 'a' - wait until hourglass A runs out
* 'b' - wait until hourglass B runs out
* 's' - start boiling the eggs
You may use any single non-whitespace character to encode each command.
You may also use longer strings to encode commands, but then the string of commands must contain separators between each pair of commands.
You may also add a special command "stop boiling the eggs" if it makes implementation easier (naturally, you cannot restart the boiling - the "stop" command is for the case your algorithm cannot restrain itself from printing additional commands after it prints the solution).
You don't need to optimize your string of commands: it may use an inefficient algorithm or contain unnecessary commands, as long as the result is correct.
Test cases:
```
3, 5, 1 => ABaAbBsa
4, 7, 9 => ABaAbBsaAaAa
7, 11, 15 => ABaAsbBb
69, 105, 42 => ABaAbBaAaAbBaAbBaAaAbBaAsb
60, 256, 2020 => ABaAaAaAaAbBaAaAaAaAbBaAsaAaAaAbBaAaAaAaAaAbBaAaAaAaAbBaAaAaAaAbBaAaAaAaAbBaAaAaAaAaAbBaAaAaAaAbBb
```
Note: these solutions were generated by a script, so they contain completely unnecessary commands.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~157~~ ~~154~~ ~~108~~ 103 bytes
```
a,b,c=input()
t=c
while t%a:t+=b
print"".join("aA"[i%a*2:]+"bB"[i%b*2:]+"s"[i^t-c:]for i in range(t+1))
```
[Try it online!](https://tio.run/##JcfBCgIhFEDRvV8hwoCmhQnNQnBRvxETqEzNi3iKvYi@3ibaXO6pH1oKut6jSSYHwPoiqRiFzN4LPGZOQ/SkQ2K1AZIQu3sBlCIexRmGuHF@0iKdfkh/PNe/0Db76VoaBw7IW8TbLEnvlep9tIa7w7jGOsu@) or [Check all test cases!](https://tio.run/##XVPBbtswDL3rKwgFxexZKWyvyVADHtBil1yCYstORTbItuyoc6TAYtLm61NKXoKlB9M03xMfSdG7I26syU8TcPKgADcKatsoiLa20a1WDUioNEJrBxjUTkmkECqH2nQx89SSc36SohJ1uVg@/VpFMcOyZq8b3VO@G1lgUlbs6cdiuYo4v32x2kRcPvBnfSM/58U64dWj/6jGD0f@b5zWxdpLatAGBmk6FWGSxXF8IrVbh4PekQ6bwKXM3aANlbk3NWprqBGJ8LJ3GPpyoTFp3KsaAC10va1kDwc56KoPAKMHSuCcNaqFsVoXFwzOXM8BGFnOK3f6oAxNxxdjOrAtlUr@Pug7QdPC/WCCsOo6qKzuPQ/1VgUN70RO0OSCzITqQtLxYREs9KpF33/d2/pvJsZ3TlykGjDzJieTUsShHPBPODUGLsNzPjmAbr0pS/7Ai/GsnGIWINUT6KFHD/mM1RTza0h6SGAmAo4JeanYyrcopQgliq/p1Ud6fiZnlDoW6TXdEf2qA/yHO1Wc5zj1xZ5nCtP/@Yzp7c4OdNVHx3zjNGgVej862pVGGz@DsKKUWx1kH3lGHKZ@WSBtdvuPC9RY5cwnJF3ZQDvYLfxcfV8s6WBYdcrWy23VyCIK2X1G9abq8AuRP@5kgASffuOC1kfwZ57QnkTh/n3Ab0Cc8DU/fREwE5CxOwFfBdwzMhndezZj83t6pQTe5WyeCshnczJpnr4D)
**Input**: from `STDIN`, 3 positive integers `a,b,c` representing the 2 hourglass times and the time needed for the egg to boil.
**Output**: print to `STDOUT` a string of commands following the specification.
### Big idea
There exists positive integers \$x,y\$ such that:
$$ax-by=c$$
(Proof in the last section)
Thus, if we continuously flip both hourglasses, the time between when the second hourglass finishes \$y\$ flips and when the first hourglass finishes \$x\$ flips is exactly equal to the time needed to boil the egg.
### Code overview
`t` keeps track of \$by+c\$. We increment \$y\$ until \$\frac{by+c}{a}\$ is an integer.
When a valid value of `t` is found, `t` will be the time needed to flip the first hourglass \$x\$ times, and also the time when the egg should be done. `t-c` is the time when the second hourglass finishes \$y\$ flips, and also the time when the egg should start to be boiled.
The command string is created by increasing the time `i`, and insert `"aA"` or `"bB"` every time \$a\$ or \$b\$ divides the current time. `"s"` is inserted when the time is `t-c`.
### Proof of the existence of \$x\$ and \$y\$.
Since \$c\$ is a multiple of \$gcd(a,b)\$, [Bézout's identity](https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity) claims that there exists integers \$k\_1, k\_2\$ (which can be negative) such that:
$$k\_1a-k\_2b=c$$
Since \$ba - ab = 0\$, we can increase \$k\_1\$ and \$k\_2\$ by \$b\$ and \$a\$ without changing the result:
$$(k\_1+b)a-(k\_2+a)b=c$$
Thus, we can keep increasing \$k\_1\$ and \$k\_2\$ until they are both positive.
[Answer]
# JavaScript (ES6), 93 bytes
Takes input as `(a)(b)(x)`.
```
A=>(B,k=0)=>g=X=>(k+X)%A?"bB"+(h=n=>"aA".repeat(n+1))(-~~(~-k/A+1)+(k+=B)/A)+g(X):"bs"+h(X/A)
```
[Try it online!](https://tio.run/##ZYxBCoMwFET3PUag8D@pGm21WIglniLbaKO2SiIqXXr19G@LixmYN8x8zNes7fKet8j5lw2dDEpWUF9GKVBWvdSURq7xrJ6sqRmHQTpZMaNYvNjZmg0cTxEh2nfYozFRlDgtZI2JQt6DxgdrVsYH0ARC693qJxtPvocOrgg5Au1P//yGcEcoD5xgmpLyQ1OUhAWd3bJjJxCyvCATmUAMPw "JavaScript (Node.js) – Try It Online")
or [Check the results online!](https://tio.run/##pZNha8IwEIa/91cc9YtlEZJYFQU/6B8ZqaZtoE2kOWX79e7SzNWMwWAjcBz3vPdemqSXd2ydXd7vM2jMTVtQ4HEwtgFXg7GUX09onPWg7Bm0OrXQuuvQdMp7QNNrBoPG62ABWw26aaBypgv9AWZnXY/J3DPFqmKXAcwAHaruszlE6HSNNGxyFmzKJfUg7AFFCJICjy6hEx1tVw04TY27IMVYfx1VsaV2A5gwxodtAJg6hP0@P@S76K4WKEakO4IBHQMKM6sFyhSpgBgKNnJ8oYyzXr3NOVXIqEjl1Xe5fIgFWReMp3JP8uQL8JN7vXuc@ELQMRh7U505w8n1PV0RqR73AYtnh7vn5JJXR3VQh8qrQ555kVbCoqp8qn7Fp2xSLn9R/j@L@yynOXFN@U9ZUvVT9e8rz7IL/RQ4j2@ZM1gygFVR0AWIBNHLLQltRrRNkGSwYSBE7FolbMnWWyZ4dCxlwkq25kyu1iOTXPL7Bw) with @SurculoseSputum's script
### How?
The algorithm used requires to count the number of multiples of \$A\$ between \$k\$ (a multiple of \$B\$) and \$k+B\$ (included). This is done with the following formula:
$$\left\lfloor\frac{k+B}{A}\right\rfloor-\left\lceil\frac{k}{A}\right\rceil+1$$
which is translated as the following JS code:
```
(k + B) / A - ~~(~-k / A + 1) + 1
```
whose result is implicitly floored.
### Commented
\$h\$ is a helper function that repeats `"aA"` \$n+1\$ times:
```
h = n => "aA".repeat(n + 1)
```
Main function:
```
A => // A = duration of hourglass A
(B, k = 0) => // B = duration of hourglass B; k = counter
g = X => // g is a recursive function taking the boiling time X
(k + X) % A ? // if k + X is not a multiple of A:
"bB" + // append "bB"
h( // repeat "aA" as many times as there are ...
-~~(~-k / A + 1) + // ... multiples of A between k and k + B (included),
(k += B) / A // using the formula described above
) + //
g(X) // append the result of a recursive call
: // else:
"bs" + // append "bs"
h(X / A) // repeat "aA" floor(X / A) + 1 times
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞*.Δ³-²Ö}©ƒN¹Ö₃*N²Ö₂*®³-NQJ0K
```
Port of [*@SurculoseSputum*'s Python answer](https://codegolf.stackexchange.com/a/202955/52210), so make sure to upvote him!!
Takes the inputs in the same order as the challenge description: `a,b,x`.
Outputs `95261` instead of `aAbBs` respectively.
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8Lb1zUw5t1j206fC02kMrj03yO7Tz8LRHTc1afiChR01NWofWAeX9Ar0MvP//NzPgMjI14zIyMDIAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCaNj/Rx3ztPTOTYnQjTw8rfbQymOT/Cov7D087VFTs5ZfJIhu0jq0LkLXL9DLwPt/rcvRvXkX9igVJzk6JSo9alhYrHR4v4LG4f2aSjr/o6ONdUx1DGN1ok10zHUsgbS5jqGhjqEpkGVmqWNoYKpjYgRiG@gYmZrpGBkYGcTGAgA) or [verify the results with the Python script](https://tio.run/##pZNti8IwDMff71OE@cZxFdrqJhN8cfdFjqrdLGyrrFHuPr2Xrg5X8R7gNpaG/PNLMkJPn3i03fJ6nUFtLroDBQ5709VgKzAd@ec9Gts5UN0BtNof4WjPfd0o5wBNqxn0Gs99B3jUoOsadtY0nvdictDV4MwdU2yXbRKAGaBF1dxgb6HRFVKze2XB7r4kBmELKLyRZHio4km0NK7q8d41TEEZQ/x9yApIZXswvo3zYwCYypvtNs3TTaiuFnQ8fWbwOjC6IcozhWf8MLsFHd8wbzFTeoahYAOIL@Rx1qqPOacItc48o2JGPjJyJAQ1zhj3zC5mBDHR3@OT2dyNcXozbnAhKG66i2rMAfa2bWnllDXuFxbTqlfHqXJa5rLwnyjzNHHiIRRcEuRUGONTb5q8/C35/14Yd3VvFN6fvTgq/p7618w0SU5093AergxnsGQAeZbRXkQk0QVZkbQepDKSJIM1AyEClUfakhUlEzxUXMlIW7GCM5kXgya55Ncv).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
* # Multiply each by the (implicit) input `a`: [a,2a,3a,...]
.Δ # Get the first item in this list which is truthy for:
³- # Subtract the third input `x`
²Ö # And check if it's divisible by the second input `b`
}© # After we've found our value: store it in variable `®` (without popping)
ƒ # Loop `N` in the range [0, `®`]:
N¹Ö # Check if `N` is divisible by the first input `a`
₃* # Multiply this by 95 (so 95 if truthy; 0 if falsey)
N²Ö # Check if `N` is divisible by the second input `b`
₂* # Multiply this by 26 (so 26 if truthy; 0 if falsey)
®³-NQ # Check if `®` minus the third input `x` is equals to `N`
# (1 if truthy; 0 if falsey)
J # Join all values on the stack together
0K # And remove all 0s
# (after the loop, the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
NθNηNζ⭆⊗×θη⁺⎇﹪ιθω⁺aA⎇﹪⁺ιζηωs⎇﹪ιηω⁺bB⎇﹪⁻ιζθωS
```
[Try it online!](https://tio.run/##ZY1BC4IwGIbv/Yqx0zdYtyDCU9Glw0TQPzB15GBuOl2Rf359pFToLh8vz8OzqpG@ctLEeLNdGNPQlspDz5Ld/25We8KdeW1HyEc8dyE7uLpQGlVDoVs1QM9JwzjJTBigUN5K/wLh6mAcaE56RM@FUnmmnKycD0FxYnMHZTpQxjai/vI5Vl62MaHtr7Z8TXOs4UtiPJAjOcX9w7wB "Charcoal – Try It Online") Link is to verbose version of code. Uses `S` to stop boiling, so the actual boiling time is from the first `s` to the first `S` after the first `s`. Explanation:
```
NθNηN
```
Input `a`, `b` and `x`.
```
ζ⭆⊗×θη⁺
```
Loop from `0` to `2ab`.
```
⎇﹪ιθω⁺aA
```
If this is a multiple of `a` then stop and start the `a` hourglass.
```
⎇﹪⁺ιζηωs
```
In addition if this plus `x` is a multiple of `b` then start boiling.
```
⎇﹪ιηω⁺bB
```
If this is a multiple of `b` then stop and start the `b` hourglass.
```
⎇﹪⁻ιζθωS
```
In addition if this minus `x` was a multiple of `a` then stop boiling.
[Answer]
# Python 3.7, 158 bytes
I'm very new to this, so if there's some convention on explanations/proofs that should be included please helpfully point me in the right direction.
**My Solution:**
1.) Not including 's', there is only one move that can be done without returning to a previous point. Wait for a timer to run out if both are running, or if a timer is empty flip that timer. Since timer 'a' is shorter than 'b', you start both, keep flipping 'a' until 'b' runs out, keep flipping 'b' until 'a' runs out (only once), and repeat this cycle indefinitely. It will of course return eventually to a previous position, but if a solution exists it will be found first.
2.) Keeping track of the time left on 'a' when 'b' runs out, you see that it is always some number 'd' less than or equal to 'a'. If a solution exists, eventually the time to cook the egg is a multiple 'n' of 'a' plus or minus 'd'.
3.) If the time to cook is 'n' x 'a' + 'd', start the egg, continue cycling 'a' until the egg is done. If the time to cook is 'n' x 'a' - 'd', start the egg, flip 'a' so it runs *backwards* 'd' minutes, and continue cycling 'a' until the egg is done.
**My Code:**
```
a,b,c=3,5,1
d,i,j,k=a,2,'AB','Aa'
while i:
i+=1;d,j=((b-d)%a,j+k*((b-d)//a+1)) if i%2 else (a-d,j+'bB')
if c%a==d:j+='s'+'A'*(i%2)+'a'+k*(c//a);i=0;print(j)
```
[Try it online](https://tio.run/##TVDLbsIwELznK0aq0MbFFQXUS6Uc4Du4rBNDnAQnik0RX5@uiRrqg7Xencd6hkese7@fJtYwGiUK7DW@NLZZ9gaqCC4g1hajvbLzlR0R3dWi9yAm3GsrhSGMNx/Q32IiOQJ30Y6eow2gS4@bj64DLygB@OrfxLwmSaBZXEMcnb8g9mk2zPItIfCPKDPO9g7zSC7mIRsOHZcJTic68IlkPRdrgQVpdhZlzWNWaTiNRqMt5Ms7DTocKd1MWXavneDcdwY5DutCYkilkBpJJs8NPlAprMCps0aL91d3sxGvNbZKwZ2FvsIOtgsWOSfAzCBzJDXrnyVuUUJRoJot02mSLQVK2AMl/aeSSm@mP8/y6aYWlis@l3qQzGLeqGmafgE)
[Answer]
# Java 8, 115 bytes
```
(a,b,c)->{int t=c,i=0;for(;t%a>0;)t+=b;for(;i<=t;)System.out.print((i%a<1?"aA":"")+(i%b<1?89:"")+(i++==t-c?1:""));}
```
Port of [*@SurculoseSputum*'s Python answer](https://codegolf.stackexchange.com/a/202955/52210), so make sure to upvote him!!
Outputs `891` instead of `bBs` respectively.
[Try it online](https://tio.run/##bVBBbsIwELzzCssSki1vUJwSKBiD@oBy4Vj1sDGhMoWAkgWpQnl76oQcqOhlpBnvemdmj1eM9tvvxh2wqtg7@uI2YMwXlJc7dDlbt5Sx68lvmRNBZwgtZh06acJzPQhQEZJ3bM0KZhuBkIGT0fLWTpF14G1sdqdSGBriMjaSlM3ugl9YMnLzU1F@HJ0uNDqXYUkIP8SFXnF843POpQo8C/x11jOlrKXIrXTLpakb07o4X7JDcNGb6VwfQyaxofDp18cnQ3kPRHlF4gVS0F2EXhjDFGaPwhS0Bp0@SpMZ6DiFcfJHjCFJJ5DESfxUSeeim3qu727mKTwqDlxlHTrF54z3x4qR67s1/24eCtHfr5tf) or [verify the results with the Python script](https://tio.run/##pZPdioMwEIXvfYrB3lQ2hSTaX@hFn2RJ22gDaoqZlt2ndyemRdOL3cIihmG@M2fGJF6/8WLbvO9nUJm7bkGBw860FdgSTEvx7YTGtg5UewatThe42FtX1co5QNNoBp3GW9cCXjToqoKjNbWv9zA563II5o4pdsx2CcAM0KKqH8V@hVqXSM1GZ8HGWFINwh5Q@EXSwoOLr0RL46oOx65hClIM@c9BFUpK24HxbZwfA8CUftnv00O6C@5qgWJAuibo0dYj3/O4QBkj5RFDwQaOHxRx1qivOacMGWWxfPMql0@xIOuM8VguSB59AT6407vnji8EbYNp76o2ZzjZpqEjItXzPGAxdegdJ5dUHTZb/wp1SBMnXlIhJCCn4JmfRlNx/pf4/1EYtxgbhef3KM6K96XvKtMkudK/gvNwxTmDnAEss4zORUSILnRBaD2gbYQkgzUDIULVMmI5W22Z4MGxkBEr2IozuVwNTHLJ@x8).
] |
[Question]
[
## The challenge
Given two strings, each of length up to 30, consisting of printable ASCII characters (codes \$[32, 126]\$), put them onto a balance scale in the fewest bytes of code! This consists of the following steps:
1. Calculate and compare the weights of the strings
2. Choose the appropriately tilted ASCII-art scale
3. Place the two strings onto the scale
The strings may be passed as an array, two arguments, or any other reasonable method.
---
The **weight of a string** is defined as the sum of the weights of that string's characters, where:
* Spaces have a weight of 0 ()
* Lowercase letters have a weight of 2 (`abcdefghijklmnopqrstuvwxyz`)
* Uppercase letters have a weight of 4 (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`)
* All other symbols have a weight of 3 (`!"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~`)
---
The scales look like this:
```
. _
| _-*/\
|-* / \
_-*| / \
_-* | / \
/\ | *------*
/ \ |
/ \ |
/ \ |
*------* |
______|______
```
```
_ .
/\*-_ |
/ \ *-|
/ \ |*-_
/ \ | *-_
*------* | /\
| / \
| / \
| / \
| *------*
______|______
```
```
.
|
______|______
/\ | /\
/ \ | / \
/ \ | / \
/ \ | / \
*------* | *------*
|
|
______|______
```
If the first string is heavier, use the first drawing as the base of your output; if the second string is heavier, use the second drawing; if the strings have equal weight, use the third. Trailing whitespace is allowed.
---
I will be using a segment of the third drawing as the base for all of the following examples.
The first string should be placed onto the left pan, and the second string onto the right pan.
Place a string on a pan by placing its **non-space** characters within the 6x5 area immediately above the dashes, as marked by `#`s here (you may end up overwriting part of the balance scale - that is fine):
```
######_
######
######
######
/######\
*------*
```
All of these characters should be "settled" ie. either above a `-` character or another character from the string:
```
WRONG WRONG CORRECT
____ ____ ____
f /\ /\ /\
l \ / \ / \
/ \ / hov\ / s \
/oating\ /eri ng\ /ettled\
*------* *------* *------*
```
Additionally, the whole stack should be as flat as possible, meaning that of the six 1-wide columns, the height of the tallest and the height of the shortest must not differ by more than 1:
```
WRONG WRONG CORRECT CORRECT
[tallest: 5] [tallest: 4] [tallest: 5] [tallest: 2]
[shortest: 0] [shortest: 2] [shortest: 4] [shortest: 2]
5__5_ ____ 5_5__ ____
45445 & /\ 445454 /\
45445 $% &$@ 445454 / \
/45445 &%@%$& 445454 %&$@%&
/ 45445\ /&$@$&%\ /445454\ /$@$%$$\
*------* *------* *------* *------*
```
The exact order/arrangement of the characters does not matter. The following are all valid arrangements for the string "Weigh your words!":
```
____ ____ ____ ____
/\ /\ /\ /\
ds! \ / owd oe \u !Wd \
ourwor Wihuos yoiwgr eghioo
/Weighy\ /egyrr!\ /Wrhd!s\ /rrsuwy\
*------* *------* *------* *------*
```
---
## Test cases
```
INPUT: "CODE GOLF", "coding challenges"
WEIGHTS: 32, 32
EXAMPLE OUTPUT:
.
|
______|______
/\ | /\
/ \ | nge\s
/OO \ | challe
/CFGLED\ | /coding\
*------* | *------*
|
|
______|______
```
```
INPUT: "", "$"
WEIGHTS: 0, 3
EXAMPLE OUTPUT:
_ .
/\*-_ |
/ \ *-|
/ \ |*-_
/ \ | *-_
*------* | /\
| / \
| / \
| / $ \
| *------*
______|______
```
```
INPUT: "YOU KNOW WHAT THEY SAY!", "there's_always_a_relevant_xkcd"
WEIGHTS: 75, 65
EXAMPLE OUTPUT:
. tr_a_s
| _hekx_y
|-* elcdta
_-*| revanw
_-* | /e's_al\
T/\ | *------*
AUYOHY |
A!HWYK |
/OTSMEW\ |
*------* |
______|______
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 110 bytes
```
UMθ⪫⪪ι ω≔⁰ηFθ≦⁻ΣEι⁻⁺³№ακ№βκηP-×⁷_↑χ.¶¶≔³ζ¿η«≔∨›⁰η⁵ζM±⁶±²_F⁴⁺¶*-§_|_ι¿›⁰η‖»P-⁺|×⁶_J±⁴±ζFθ«←⁶↑*↗⁴↓↘⁴←↖*←⪪ι⁶J⁹⁻ζ⁶
```
[Try it online!](https://tio.run/##ZVLLbsIwEDzDV6x8spGpaEupSk8IWlQEBQE9AUJpMIlVxw55lIrHt6d2HjzaS5SZWe/OrG27VmArSyTJwPLbyvMsucIbCj3FJZ74gkeYU0CACIUtIc/lVhhyR@IaBVejtQoAbwjow5nQZ@sID7iMQwqT2MNaMA1SBo@E/txTaKtYRtii8EVIgT5TZLDpO4hFxP2Aa6FZpTDlHgvxozayRMbEKFM@fAq3tRNGN3M5l@hsUo/aacTXgF0C@3Ip54cB7gbMiliQ5aDwQLLS0kB9M/zOHC3ihibz3zsztZSPWZoRpTR6nUBGptHQXFaqiEIrepMr9qMrD0sNOUlPGxtXYwmM2VowO8JaPpaZCBn8CZ61PaBiBY18BfpAL/b8qSq81s9ed@TiYvaF66a5GQqNc450faiCrpgxd1xdVj/totlRW3lRYuD/ItP8qk827bp7xp0eVSPdSh7jqXgju1w4JslshtrDzgt0h/1XvQFkqxWXDtiuJQSTDgvRYpFUv8Uv "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two strings. Explanation:
```
UMθ⪫⪪ι ω
```
Remove the spaces from both strings.
```
≔⁰η
```
Assume the weights balance.
```
Fθ
```
Loop over both strings.
```
≦⁻ΣEι⁻⁺³№ακ№βκη
```
Subtract the running difference from the weight of the string.
```
P-×⁷_↑χ.¶¶
```
Print the base of the balance scale.
```
≔³ζ
```
Assume that both pans are 3 off the ground.
```
¿η«
```
If the weights didn't balance...
```
≔∨›⁰η⁵ζ
```
... calculate the height of the left pan...
```
M±⁶±²_F⁴⁺¶*-§_|_ι
```
... draw the balance leaning down to the right...
```
¿›⁰η‖»
```
... and reflect if the left pan was heavier.
```
P-⁺|×⁶_
```
Otherwise draw a level balance.
```
J±⁴±ζ
```
Jump to the first scale pan.
```
Fθ«
```
Loop over the inputs.
```
←⁶↑*↗⁴↓↘⁴←↖*
```
Draw the scale pan.
```
←⪪ι⁶
```
Slice the input into substrings of length 6 and print them upside-down so that they fill the pan upwards.
```
J⁹⁻ζ⁶
```
Jump to the second scale pan.
[Answer]
# [Python 2](https://docs.python.org/2/), 1101 1071 855 837 bytes
*-216 bytes with string compression*
*-18 bytes by reducing some repetition*
```
from zlib import decompress as Z
from base64 import b64decode as D
r=range(6)
j="".join
w=lambda a:0if not a else(2+2*(a[0]<'[')if a[0].isalpha()else 3)+w(a[1:])
t=Z(D('eJxT0FKIV1BQ0AWT8SAIJsAcXTCppQAGumBSSx8MYsBAC0kCAiCySAIKEJW4ZHGpxA8AejMemQ=='))
p=lambda k,l,m:j(map(j,[(t[2*l+m::6][:30-len(k)]+k)[i::6]for i in r]))
def A(a,b):
e=cmp(w(j(a.split())),w(j(b.split())))+1;return Z(D('eJxVUUGuhTAI3HOKWTdBW/U2SHoQ4O6ftvrMb0hLZJgZAYABFZB5KxD4zrZtNJOJMaHWIIoa0D6Ao+jrWRiHEI7kMcQg9VLBCo9O3dCbdanepOvZQztF9rRH2xUlwISehIZ96HltLFqu1IMF2p1QH/S+1Ge7CT5blIVOxqUWFudjqHPSwhitjPbzf7uZ1HaIaG2hShFTfU7Eca6J7MBr1K+3/YbRVLd2VlE5oilp7EG/gV7+DPQuSAsZPm7PZE9HBY2G+ctS/QzR+whSGlPAGz4mkkl5Sf18SMvkyL9iF6aLd2WLUm/KDVzvJu93k2tLZXlwetgLmFH4MzcKCaJnqX1Fz3iOf4//Pi7EwP4BHmyJpg=='))[e::3].format(*map(lambda c:[p(j(([a,b]*3)[c].split()),e,c)[i::5]for i in r],r))
```
[Try it online!](https://tio.run/##hZNbk6I4GIbv/RVZa6oMDdsKnlp2vQCVkzpoo9JCWV0BoyDh0BCPf74Xu7Z3pmtraq5CPp68@ZL3TXalQZoI7@@7PI3BjYQeCOMszSnYYj@NsxwXBUAFcCofgIcK3Gl9Il6ndae2@E4MK3k/R8keww5TOfSr1cdDGiaVc5@g2NsigMRGuANJSgECmBQYCqzwAJHb2Pxdc2tM@e/@/RgWiGQBgsydAU2GPZcML26YCu07cAhr2LgsGspYX/HyvCHZiydL0o1C8l8WgyybS@oxli3r8jRdF7I0aEQDKRxcS2Q8MuyWo6nZRXqS8GGK43m/X2OYSvbZYMQRLhYPMEYZPHAupK7wQNhYFDsbV2w2/iQ4gRGzYSPGDe/FXZqDEIQJyDelzBbvgAQR5zFiBeC@H2fwDA8QPRYZCSlkGIa7z70fc4bl/8oxPeYJ@DzYarlUj8FC0puaObYXW9muLwVLS@cts7Ojp3zqNYKJY@wdaS3JiiO3x5dh65Y79LthGlOk2bqeosawI6XsIbefQ22kd6OpP9/3VhN5kPbM5nZQHjXBmXly5jeq9PJnTbgsyVm3cKA7vY5G6ER5O/L6VBEyfq7VLZZXcXewaHtEX5mXt6WtHLeHN21mnYOQHmbebdc9OryGdKQKgRUoi92yO/JRx@hO5Zwfs8362nteTbbCiozaaUiy7kit71dddjibHy2pcGZxd@aMepq8FlTWp1Z9fntmz4Glkpmk3lpxFJG2teOfrOkpuk56odJBpZo9Wcb18XB1OxnHXjMS6MR5IWdM95NY0VrTmz8eICN5e@GVWzM0d616fRZ2R@dZS9biq5HtP8x3sSg2N4@lkzGi8OHu/L9h8EW3TAGEbuno5qHJuP7mP@c4zPkfGWj/nAEuZ5j3LA8TCiVYHZjDEVDNiVLlQLV8ImGyB36ASBmiPS6q99x9olWu@u1LYW0uwfi7aQNbkxZgoY3WwJLWf9yVaIBzXCteETmjazm85pjgE0ro6yXyt19U/r9puf5HWz@j38oWvhR@s00p9Kseyzv4Bw "Python 2 – Try It Online")
Run as `A(string_one, string_two`.
`w` calculates the weight of the string recursively.
`t` is the compressed and interlaced text of all six possible scales, which happens to compress very nicely.
`p` takes the string (with spaces removed), the weight of the string, and the side of the balance that string is on, and creates a 5x6 block of characters.
`A` takes the strings, and builds their blocks with `p`. The giant string at the bottom is three format strings interlaced and compressed.
[Answer]
# JavaScript (ES6), ~~340~~ 337 bytes
Takes input as an array of 2 arrays of characters. Draws the output character by character.
```
S=>(s=Math.sign(~(g=i=>(S[i]=S[i].filter(c=>c>' '?i+=/[a-z]/gi.test(c)?c>{}?2:4:3:0),i))(0)+g(1))+1,g=x=>y>10?'':(X=(r=x>9)?20-x:x,Y=(r?2-s:s)*2+y,S[+r][X>0&&X<7&&47-Y*6+X]||`. /\\|-_*
`[~X?x-10?y>9?X>3?6:1:[x+y*3-17,2*y-4,x+~y*3][s]/2|X<4?Y<5|Y>8?Y-9|X>7?1:X%7?5:7:~X+Y?X+Y-8?1:2^r:3^r:[7-x%3,6,5+x%3][s]:y&&4:8])+g(x<21?x+1:!++y))(y=0)
```
[Try it online!](https://tio.run/##dU9db5swFH3vr6DRGmyMCR9JSKzYVrV1q7SPPKRTQa6XIkIIHYIJUGc2lr@eOX3o0/Zw7tE9uufonqfkOWnTpvjR4areZac9PW0oAy39nHQHpy3yChxBTgutbUQh6Xk4@6LssgaklKXMNExeIDoRCf4lJ3nhdFnbgRTylP3@w30yJQFxoV1ACFyIcuBBiDw7p4qynnkuN00CIgoaqtgSct/Fiig71gL3cUtaaPmotzcCNVJEzB2Po1U4Hk9DHFtzFMlheHSMycPDgLfWxaM4RlxhHdqzJY9YwOfEI0Kh3gqwF9q@1eOprdBR71K0cuIP0WrK49VsiNmCx3g5RCzkHomuQj4jITlGKOYaeKFF/1tDAg0RYnUV2HN7hjSfc0ivPyILea6nVr7HFfLIJUK97txTF57SumrrMnPKOgd7IITjOKO363c3xof1p/cjaRsvSlrviio30kNSllmVZ@1ISggv/mV@9bz5/028/mp8/LK@N@5vr@@Mu9ub2Nhcx5ev1u6QNZnZbpPyZ9Jr2jZZmT0nVbdV39PdS@7pLw "JavaScript (Node.js) – Try It Online")
### How?
We define a first helper function that removes spaces from the input string \$S[i]\$ and returns its weight:
```
g = i => ( // i = string index
S[i] = S[i].filter(c => // for each character c in S[i]:
c > ' ' ? // if c is not a space:
i += // update i:
/[a-z]/gi.test(c) ? // if c is a letter:
c > {} ? // if c is in lower case:
2 // add 2 to i
: // else:
4 // add 4 to i
: // else (not a letter):
3 // add 3 to i
: // else (a space):
0 // remove c from S[i]
), i // end of filter(); return i
) //
```
NB: Because we re-use \$i\$ to compute the weight, it is off by one for \$S[1]\$.
We compute \$s\$, which is equal to \$0\$ if \$S[0]\$ is heavier, \$2\$ if \$S[1]\$ is heavier, or \$1\$ if both strings have the same weight:
```
s = Math.sign(~g(0) + g(1)) + 1
```
We now invoke the second helper function to draw the output:
```
g = x => // given x:
y > 10 ? // if we've reached the last row:
'' // stop recursion
: // else:
( X = (r = x > 9) ? // r = true if we're on the right side
20 - x // X = 20 - x on the right side
: // or:
x, // X = x on the left side
Y = (r ? 2 - s : s) // Y is the position of the scale tray
* 2 + y, // according to s and the current side
S[+r][ // we try to extract a character from S[0] or S[1]:
X > 0 && X < 7 && // provided that we're located above the tray
47 - Y * 6 + X // and using an index based on (X, Y)
] || // if this character doesn't exist,
`. /\\|-_*\n`[INDEX] // we need to draw the balance instead
) + // (see the next part)
g(x < 21 ? x + 1 : !++y) // append the result of a recursive call
```
Where `INDEX` is computed as follows:
```
~X ? // if this is not the last character of the current row:
x - 10 ? // if this is not the central column:
y > 9 ? // if this is the last row:
X > 3 ? 6 : 1 // draw the base ('_' or a space)
: // else:
[ x + y * 3 - 17, // attempt to draw the beam:
2 * y - 4, // using an equation depending on s
x + ~y * 3 // whose result must be -1, 0 or 1
][s] / 2 | X < 4 ? // if it's invalid or X is less than 4:
Y < 5 | Y > 8 ? // if we're not over the chains:
Y - 9 | X > 7 ? // if we're not over the pan:
1 // draw a space
: // else:
X % 7 ? 5 : 7 // draw the pan ('-' or '*')
: // else:
~X + Y ? // if this is not an interior chain:
X + Y - 8 ? // if this is not an exterior chain:
1 // draw a space
: // else:
2 ^ r // draw the exterior chain ('/' or '\')
: // else:
3 ^ r // draw the interior chain ('/' or '\')
: // else:
[ 7 - x % 3, // draw the beam, using either '_' -> '-' -> '*'
6, // or just '_'
5 + x % 3 // or '*' -> '-' -> '_'
][s] // depending on s
: // else:
y && 4 // draw the central pillar ('|' or '.')
: // else:
8 // append a line feed
```
[Answer]
# Java 10, ~~1043~~ ~~993~~ ~~988~~ ~~983~~ ~~919~~ ~~914~~ ~~900~~ 898 bytes
```
(a,b)->{var r=new char[11][21];for(var A:r)java.util.Arrays.fill(A,' ');int A=s(a=a.replace(" ","")),B=s(b=b.replace(" ","")),i=3,j,z;for(;++i<17;r[3][i]=A==B?'_':32)r[10][i]=95;for(i=11;i-->1;)r[i][10]=i>0?'|':46;if(A==B){for(r[8][0]=r[8][13]=r[8][20]=42;++i<20;)r[8][i<8|i>13?i:1]=45;for(A=B=i=8;i-->4;r[i][7-i]=r[i][20-i]=47)r[i][i]=r[i][i+13]=92;}else{for(r[i=5][z=A<B?0:13]=r[5][z+7]=r[9][13-z]=r[9][20-z]=42;i-->1;r[i][A>B?j+1:j-1]=42)r[i][j=A>B?17-i*3:3+i*3]=45;for(;++i<20;)r[i>13^A>B?9:5][i>13|i<7?i:1]=45;for(i=9;i-->1;r[i][i>4?21-z-i:4+z-i]=47)r[i][i+3+(i>4?9-z:z)]=92;r[0][A<B?i=4:16]=r[1][A>B?13:7]=r[3][A>B?7:13]=r[4][A>B?4:16]=95;A=9-i;B=5+i;}c(r,a,A,7);c(r,b,B,20);return r;};int s(String s){int r=0;for(int i:s.getBytes())r+=i>64&i<91?4:i>96&i<123?2:3;return r;}void c(char[][]r,String s,int p,int q){for(int c=0,i=p,j;i-->p-5;)for(j=q;j-->q-6&c<s.length();)r[i][j]=s.charAt(c++);}
```
-86 bytes thanks to *@ceilingcat*.
Input are two Strings, which will result in a character-matrix as result.
[Try it online.](https://tio.run/##dVRdb9s2FH3vr@CEoRKnD5iSYkeiaUPuunXYFj@kQxGomkHLSkJVVRyKThcn/u3ZJSV3Cdq9UJf365xD8bLmd9yvN5@eyoZ3HfqTi/bhFUKiVZW85GWFzvQWofKay7zIC1Q650qK9gpxbzDWmELK4RUsZ6hF7Mnh3hr7s4c7LpFkbfWlryakyENS0Msb6ehQlkpcA3ywU6IJMin5fRdciqZxMs9GNqZAAmWsczjjgay2DdBxLGR5loWxt4DAmq2/DQgWebW3NzDUdcWUTKjMoyIXBcsYW8ztlZ1GIQZCI@NMTkyuYIRQ4fszQiEmCh1mYjaa2492Go@puHR0OX7QyTI/LXKImy@JBiMETxwa0HCku4BPTE8fxYxEc5ESiPZYGVswwU4NXEwN2sQXuovQXbQZT3oWR69wNUwS0kPVdNVAQrCTIt@zbLqYj9Kehna4E20lmpm/H0zoujfseommZzZbzGuXpLWvqYU9YM20mwCfn6I0cmH9SvuZMi3pb52YpICod49iOnkhUrDkOZiYxfOQ@HtfpLG7fyHRjVxHhxN/n@6xUSnhdHOtS7A4JWMtgvSESZQaeVG/nQy6437bJ8MvzVjiC7pgJ66gh9KRHvcyb4KpNtfewgtHmMpK7WSLJD2Yu9Ydr3aHH/ReslEvBGyRdsFVpRb3quocjKULV2McvxbThACmmCVjsEkYzcM0etb37kZsYGSO0yOPM9N5uunWrLf9ldJmyUZwf7debQ5u659QrEM1u6U1OG798ety2gVN1V6pawcPF7UuWBdoiEw5petieniCWdzu1o0oUae4go8h8hmme9AIk8xxP9qgSDnWm@XPb9Gvyz9@gTEqbzaaJLRsNFTVWWbEj6mQ8eNLz8XyL/T72fID@vAue4/ev3t7gc6zix8gUV1XsrK7FW@@wHiv@EpWTXXHW7X651O5sf57Op7zNE2/fWZ6uuf3nao@Bzc7FWwhoJrWsX5rtzuVoo@W5XLX@mgh3m7Mbu3alj1Q/V7hcqdM5VHO12dOVt2uUYgh/XzpV9HBQRuU5mnrU/WP6dMRlxKlQwk2we@i6Va9GAcq8P/TGk7l8PQv)
**Explanation:**
```
// Method with two String parameters and character-matrix return-type:
(a,b)->{
// Result matrix, with 11 rows and 21 columns:
var r=new char[11][21];
// Initially fill the entire matrix with spaces:
for(var A:r)java.util.Arrays.fill(A,' ');
// Remove all spaces from the input-Strings,
// and call a separated method to calculate the scores of both input-Strings:
int A=s(a=a.replace(" ","")),B=s(b=b.replace(" ","")),
// Fill the cells for the base with '_',
// and also fill the cells for the balance-bar with '_' when the scores are equal:
i=3,j,z;for(;++i<17;r[3][i]=A==B?'_':32)r[10][i]=95;
// Fill the cells for the stand with '|':
for(i=11;i-->1;)r[i][10]=i>0?'|'
// And the top of it with '.':
:46;
// If the scores are equal:
if(A==B){
// Fill the four appropriate cells for the sides of the scales with '*':
for(r[8][0]=r[8][7]=r[8][13]=r[8][20]=42;
// Fill the appropriate cells for the scales themselves with '-':
++i<20;)r[8][i<8|i>13?i:1]=45;
// Set A and B both to 8 to use later on,
// and fill the appropriate cells of the robes with '/' and '\':
for(A=B=i=8;i-->4;r[i][7-i]=r[i][20-i]=47)r[i][i]=r[i][i+13]=92;}
// If the scores aren't equal:
else{
// Fill the four appropriate cells for the sides of the scales with '*':
for(r[i=5][z=A<B?0:13]=r[5][z+7]=r[9][13-z]=r[9][20-z]=42;
// Fill the appropriate four cells of the balance-bar with '-':
i-->1;r[i][A>B?j-1:j+1]=42)r[i][j=A>B?17-i*3:3+i*3]=45;
// Fill the appropriate cells of the scales with '-':
for(;++i<20;)r[i>13^A>B?9:5][i>13|i<7?i:1]=45;
// Fill the appropriate cells of the robes with '/' and '\':
for(i=9;i-->1;r[i][i>4?21-z-i:4+z-i]=47)r[i][i+3+(i>4?9-z:z)]=92;
// Fill the four appropriate cells of the balance-bar with '_',
// and set A and B to 9 and 5 depending on which score is higher:
r[0][A<B?i=4:16]=r[1][A>B?13:7]=r[3][A>B?7:13]=r[4][A>B?4:16]=95;A=9-i;B=5+i;}
// Call a separated method to fill the cells above the scales with the input-characters:
c(r,a,A,7);c(r,b,B,20);
// And finally return the resulting character-matrix:
return r;}
// Separated method to calculate the score of the given String:
int s(String s){
// Initially start the score-sum at 0:
int r=0;
// Loop over the characters of the given String:
for(int i:s.getBytes())
// Increase the sum by:
r+=
// 4 for uppercase letters:
i>64&i<91?4
// 2 for lowercase letters:
:i>96&i<123?2
// 3 for any other character:
:3;
// And return the resulting sum:
return r;}
// Separated method to draw the strings on top of the scales:
void c(char[][]r,String s,int p,int q){
// Keep a counter so we know when we're done drawing the given String:
for(int c=0,
// Loop over the appropriate rows bottom to top:
i=p,j;i-->p-5;)
// Inner loop over the appropriate cells of this row left to right,
for(j=q;j-->q-6
// as long as we're not done yet with the input-String:
&c<s.length();)
// And fill that appropriate cell with the next character in line of the given String:
r[i][j]=s.charAt(c++);}
```
] |
[Question]
[
OEIS sequence [A020872](https://oeis.org/A020872) counts the number of restricted forests on the [Möbius ladder](https://en.wikipedia.org/wiki/M%C3%B6bius_ladder) Mn.
## The Challenge
The challenge is to write a program that takes an integer as an input `n > 1` and returns `A020872(n)`, the number of restricted forests on the Möbius ladder Mn. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
(An ulterior motive is to perhaps extend the length of this sequence by a bit.)
## Definitions
A *restricted forest* is a partition of the graph such that each part is either a (undirected) [path](https://en.wikipedia.org/wiki/Path_(graph_theory)) or an isolated vertex.
The [*Möbius ladder*](https://en.wikipedia.org/wiki/M%C3%B6bius_ladder) Mn is a graph which can be thought of the 2n-gon with diagonals drawn between all opposite vertices.
## Example
Here are the 34 restricted forests on M2 (a square with diagonals drawn). Notice that the first graph is partitioned into four isolated vertices, the second is partitioned into one path and two isolated vertices, etc.
[](https://i.stack.imgur.com/4EEZg.png)
[Answer]
## CJam (58 56 chars)
Some characters unprintable, and one is a tab which will be mangled by the StackExchange software:
```
"¶3¬î¿Á· 7ÛÈmÈÚÚ¡"256b454b212f-{__W%.*A<1b+}qi*-4=
```
[Online demo](http://cjam.aditsu.net/#code=%22%C2%B6%023%C2%93%C2%AC%C3%AE%C2%BF%C3%81%C2%B7%06%097%C2%94%C3%9B%C3%88m%C3%88%10%15%C3%9A%C3%9A%C2%A1%22256b454b212f-%7B__W%25.*A%3C1b%2B%7Dqi*-4%3D&input=17). This will run online for n=400 in about three seconds.
Encoded by `xxd`:
```
0000000: 22b6 0233 93ac eebf c1b7 0609 3794 dbc8 "..3........7...
0000010: 6dc8 1015 dada a122 3235 3662 3435 3462 m......"256b454b
0000020: 3231 3266 2d7b 5f5f 5725 2e2a 413c 3162 212f-{__W%.*A<1b
0000030: 2b7d 7169 2a2d 343d +}qi*-4=
```
### Explanation
A Möbius ladder is basically a ladder with two extra edges. Given a restricted forest on a ladder, it can be lifted to between 1 and 4 restricted forests on the Möbius ladder. The edges can be added provided that doesn't create a vertex of degree 3 or a cycle. The degrees of the four corners and their interconnections form 116 classes of restricted forest on the ladder, although some of them are equivalent due to symmetries of the rectangle. I wrote a program to analyse the extensions of a ladder of length n to one of length n+1, and then merged the classes into 26 equivalence classes. This gives a closed form
$$\begin{bmatrix} 1 \\ 1 \\ 1 \\ 1\end{bmatrix}^T
\begin{bmatrix}
1 & 2 & 2 & 0 \\
1 & 2 & 1 & 1 \\
2 & 3 & 4 & 1 \\
0 & 0 & 1 & 0 \\
\end{bmatrix}^{n-2}
\begin{bmatrix} 0 \\ 1 \\ 0 \\ 0\end{bmatrix} + $$
$$\begin{bmatrix} 2 \\ 2 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \\ 2 \\ 2\end{bmatrix}^T
\begin{bmatrix}
2 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\
1 & 0 & 1 & 0 & 0 & 1 & 0 & 1 & 0 \\
0 & 0 & 2 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 1 \\
1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 1 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\
3 & 2 & 2 & 1 & 1 & 2 & 1 & 4 & 2 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 2 \\
\end{bmatrix}^{n-2}
\begin{bmatrix} 0 \\ 0 \\ 2 \\ 2 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0\end{bmatrix} + $$
$$\begin{bmatrix} 1 \\ 2 \\ 4 \\ 4 \\ 1 \\ 1 \\ 3 \\ 2 \\ 2 \\ 2 \\ 3 \\ 4 \\ 4\end{bmatrix}^T
\begin{bmatrix}
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 2 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 2 & 0 & 1 & 1 & 0 & 1 & 1 & 0 & 1 & 1 & 1 \\
1 & 0 & 0 & 4 & 0 & 0 & 3 & 0 & 0 & 2 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 2 & 1 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 \\
1 & 0 & 0 & 1 & 0 & 0 & 2 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 1 & 2 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 2 \\
0 & 1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 2 & 0 & 0 & 2 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 2 & 2 & 0 \\
0 & 2 & 3 & 0 & 1 & 1 & 0 & 2 & 1 & 0 & 1 & 2 & 4 \\
\end{bmatrix}^{n-2}
\begin{bmatrix} 1 \\ 0 \\ 1 \\ 1 \\ 2 \\ 0 \\ 1 \\ 0 \\ 0 \\ 0 \\ 1 \\ 2 \\ 1\end{bmatrix}$$
so values can be computed fast by taking three linear recurrences and then adding them, but this isn't looking very golfy.
However, if we take the irreducible factors of the various characteristic polynomials and multiply together one of each (ignoring multiplicity) we get a polynomial of degree 10 which gives a working single linear recurrence.
## Constructive approach (58 chars)
```
qi:Q2*,Wa*e!{Wa/{_W%e<}%$}%_&{{,1>},2few:~{:-z(Q(%}%0-!},,
```
[Online demo](http://cjam.aditsu.net/#code=qi%3AQ2*%2CWa*e!%7BWa%2F%7B_W%25e%3C%7D%25%24%7D%25_%26%7B%7B%2C1%3E%7D%2C2few%3A~%7B%3A-z(Q(%25%7D%250-!%7D%2C%2C&input=2). It will run online for `n=2` without problems and for `n=3` with a bit of patience. For `n=1` it crashes, but since OP has chosen to exclude that case from the requirements it's not a fundamental problem.
### Dissection
```
qi:Q e# Take input from stdin, parse to int, store in Q
2*,Wa*e! e# Take all permutations of (0, -1, 1, -1, 2, -1, ..., -1, 2*Q-1)
{ e# Map to canonical form...
Wa/ e# Split around the -1s
{_W%e<}% e# Reverse paths where necessary to get a canonical form
$ e# Sort paths
}%
_& e# Filter to distinct path sets
{ e# Filter to path sets with valid paths:
{,1>}, e# Ignore paths with fewer than two elements (can't be invalid; break 2ew)
2few:~ e# Break paths into their edges
{:-z(Q(%}% e# The difference between the endpoints of an edge should be +/-1 or Q (mod 2Q)
e# So their absolute values should be 1, Q, 2Q-1.
e# d => (abs(d)-1) % (Q-1) maps those differences, and no other possible ones, to 0
e# NB {:-zQ(%}% to map them all to 1 would save a byte, but wouldn't work for Q=2
0-! e# Test that all values obtained are 0
},
, e# Count the filtered distinct path sets
```
---
A more efficient version takes 98 bytes:
```
qi2*:Q{a{__0=[1Q2/Q(]f+Qf%_&1$-\f{+E}~}:E~}/]{_W%>!},:MW=0{_{M\f{__3$_@&@:e<@|^{=}{^j}?}1b}{,)}?}j
```
[Online demo](http://cjam.aditsu.net/#code=qi2*%3AQ%7Ba%7B__0%3D%5B1Q2%2FQ(%5Df%2BQf%25_%261%24-%5Cf%7B%2BE%7D~%7D%3AE~%7D%2F%5D%7B_W%25%3E!%7D%2C%3AMW%3D0%7B_%7BM%5Cf%7B__3%24_%40%26%40%3Ae%3C%40%7C%5E%7B%3D%7D%7B%5Ej%7D%3F%7D1b%7D%7B%2C)%7D%3F%7Dj&input=5)
This builds the possible paths by depth-first search, then uses a memoised function which counts the possible restricted forests for a given set of vertices. The function works recursively on the basis that any restricted forest for a given non-empty set of vertices consists of a path containing the smallest vertex and a restricted forest covering the vertices not in that path.
[Answer]
# JavaScript (ES6), ~~160 158~~ 146 bytes
```
n=>(g=(e,v,p)=>[...Array(N=2*n),N-1,1,n].reduce((s,x,i)=>(m=1<<(x=i<N?i:(p+x)%N))&v?s:s+g((i>=N)/p?[...e,1<<p|m]:e,v|m,x),g[e.sort()]^(g[e]=1)))``
```
[Try it online!](https://tio.run/##XY1BasMwEEX3PUU2DTPNREaOA8V4bHoBXSC4xDiKUYklISXGhdzdVUk3zfK///j/q5u62Afjr1vrTno582K5hoFB00QeuT4IIT5C6L5Bcf5mkdRWkiTbiqBPt14DRJrJJBNGllUFM5tKNaYEv5nxVSGupyaWcTMAmJoVZr753dSUZH8f2zI93UeakYaDFtGFK2D7CSm0LBHxeFx6Z6O7aHFxA5whwVWWrfKX/zh/4F3xxHd/eiGfiuJRyP17vvwA "JavaScript (Node.js) – Try It Online")
Notes:
* This is quite inefficient and will time-out on TIO for \$n>4\$.
* \$a(5) = 10204\$ was found in a bit less than 3 minutes on my laptop.
### Commented
```
n => ( // n = input
g = ( // g = recursive function taking:
e, // e[] = array holding visited edges
v, // v = bitmask holding visited vertices
p // p = previous vertex
) => // we iterate over an array of N + 3 entries, where N = 2n:
[ ...Array(N = 2 * n), // - 0...N-1: each vertex of the N-gon (starting points)
N - 1, // - N : previous vertex \
1, // - N+1 : next vertex }-- connected to p
n // - N+2 : opposite vertex /
].reduce((s, x, i) => // reduce() loop with s = accumulator, x = vertex, i = index:
( m = 1 << ( // m is a bitmask where only the x-th bit is set
x = i < N // and x is either:
? i // - i if i < N
: (p + x) % N // - or (p + x) mod N otherwise
)) & v ? // if this vertex was already visited:
s // leave s unchanged
: // else:
s + // add to s
g( // the result of a recursive call:
(i >= N) / p ? // if p and x are connected (i >= N and p is defined):
[ ...e, // append to e[]:
1 << p | m // the edge formed by p and x
] // and uniquely identified by 1 << p | 1 << x
: // else:
e, // leave e[] unchanged
v | m, // mark the vertex x as visited
x // previous vertex = x
), // end of recursive call
g[e.sort()] ^ // sort the edges and yield 1 if this list of edges has not
(g[e] = 1) // already been encountered; either way, save it in g
) // end of reduce()
)`` // initial call to g with e = ['']
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~61~~ 58 bytes
```
®R,³;Ø+
Ḥ©Ḷµ1ị+¢%®ḟ€;€€1¦-Ẏ;€)Ẏ$ƬẎṣ€-Ẉ’ẠƊƇU¹Ø.ị>/Ɗ?€€Ṣ€QL‘
```
[Try it online!](https://tio.run/##y0rNyan8///QuiCdQ5utD8/Q5nq4Y8mhlQ93bDu01fDh7m7tQ4tUD617uGP@o6Y11kAMRIaHluk@3NUH4mkCaZVja4Dkw52LgXygeMejhpkPdy041nWsPfTQzsMz9ICG2Okf67KHaH64cxGQDPR51DDj////xgA "Jelly – Try It Online")
This is the shorter version; it is optimised for shorter length versus algorithmic complexity and speed.
# [Jelly](https://github.com/DennisMitchell/jelly), 85 bytes
```
%®ḟ
1ị+³;Ø+¤ç,1ị+®_3¤R‘¤Ʋç;€-Ʋ“”2ị>-Ʋ?Ẏ;€
Ḥ©Ḷ;€-Ç€Ẏ$ƬẎṣ€-Ẉ=1ẸƊÐḟU¹1ị>0ị$Ʋ?€€Ṣ€QL‘+=2$
```
[Try it online!](https://tio.run/##y0rNyan8/1/10LqHO@ZzGT7c3a19aLP14Rnah5YcXq4D4a@LNz60JOhRw4xDS45tOrzc@lHTGt1jmx41zHnUMNcIqMIOyLN/uKsPJMH1cMeSQysf7tgGVnW4HUgCZVSOgciHOxeDBB/u6rA1fLhrx7GuwxOAloYe2gmyxs4ASKgADQIqAWnauQhIBvoAbdW2NVL5//@/MQA "Jelly – Try It Online")
Here’s a longer version that adds extra code to avoid trying redundant paths. The check for n=2 at the end is to cope with the specific case for n=2 which looks like a red/blue cross in the example and isn’t generated by this code. This second version completed n=4 in less than 13 seconds on TIO, but times out for higher numbers.
] |
[Question]
[
## Background
For my [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") submissions in C, I need a processing tool. Like in many other languages, whitespace is mostly irrelevant in C source (but not always!) -- still makes the code much more comprehensible for humans. A fully golfed C program that doesn't contain a single redundant whitespace often is barely readable.
Therefore, I like to write my code in C for a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") submission including whitespace and sometimes comments, so the program keeps a comprehensible structure while writing. The last step is to remove all comments and redundant whitespace. This is a tedious and mindless task which really should be done by an intern a computer program.
## Task
Write a program or function that eliminates comments and redundant whitespace from some "pre-golfed" C source according to the following rules:
* A `\` (backslash) as the very last character in a line is a *line continuation*. If you find this, you must treat the following line as part of the same *logical line* (you could for example remove the `\` and the following `\n` (newline) completely before doing anything else)
* Comments will only use the one-line format, starting with `//`. So to remove them, you ignore the rest of the logical line wherever you encounter `//` outside a *string literal* (see below).
* Whitespace characters are (space), `\t` (tab) and `\n` (newline, so here the end of a logical line).
* When you find a sequence of whitespace, examine the non-whitespace characters surrounding it. If
+ both of them are alphanumeric or underscore (range `[a-zA-Z0-9_]`) or
+ both are `+` or
+ both are `-` or
+ the preceeding one is `/` and the following one is `*`then replace the sequence with a single space () character.
Otherwise, eliminate the sequence completely.
This rule has *some exceptions*:
+ *Preprocessor directives* must appear on their own lines in your output. A preprocessor directive is a line starting with `#`.
+ Inside a *string literal* or *character literal*, you shouldn't remove any whitespace. Any `"` (double-quote) / `'` (single-quote) that isn't directly preceeded by an odd number of backslashes (`\`) starts or ends a *string literal* / *character literal*. You're guaranteed that string and character literals end on the same line they started. *string literals* and *character literals* cannot be nested, so a `'` inside a *string literal*, as well as a `"` inside a *character literal* don't have any special meaning.
### I/O specification
Input and output must be either character sequences (strings) including newline characters or arrays/lists of strings that don't contain newline characters. If you choose to use arrays/lists, each element represents a line, so the newlines are *implicit* after each element.
You may assume the input is a valid C program source code. This also means it only contains printable ASCII characters, tabs and newlines. Undefined behavior on malformed input is allowed.
**Leading and trailing whitespace / empty lines** are **not allowed**.
### Test cases
1. input
```
main() {
printf("Hello, World!"); // hi
}
```
output
```
main(){printf("Hello, World!");}
```
2. input
```
#define max(x, y) \
x > y ? x : y
#define I(x) scanf("%d", &x)
a;
b; // just a needless comment, \
because we can!
main()
{
I(a);
I(b);
printf("\" max \": %d\n", max(a, b));
}
```
output
```
#define max(x,y)x>y?x:y
#define I(x)scanf("%d",&x)
a;b;main(){I(a);I(b);printf("\" max \": %d\n",max(a,b));}
```
3. input
```
x[10];*c;i;
main()
{
int _e;
for(; scanf("%d", &x) > 0 && ++_e;);
for(c = x + _e; c --> x; i = 100 / *x, printf("%d ", i - --_e));
}
```
output
```
x[10];*c;i;main(){int _e;for(;scanf("%d",&x)>0&&++_e;);for(c=x+_e;c-->x;i=100/ *x,printf("%d ",i- --_e));}
```
4. input
```
x;
#include <stdio.h>
int main()
{
puts("hello // there");
}
```
output
```
x;
#include<stdio.h>
int main(){puts("hello // there");}
```
5. input (a real-world example)
```
// often used functions/keywords:
#define P printf(
#define A case
#define B break
// loops for copying rows upwards/downwards are similar -> macro
#define L(i, e, t, f, s) \
for (o=i; o e;){ strcpy(l[o t], l[o f]); c[o t]=c[s o]; }
// range check for rows/columns is similar -> macro
#define R(m,o) { return b<1|b>m ? m o : b; }
// checking for numerical input is needed twice (move and print command):
#define N(f) sscanf(f, "%d,%d", &i, &j) || sscanf(f, ",%d", &j)
// room for 999 rows with each 999 cols (not specified, should be enough)
// also declare "current line pointers" (*L for data, *C for line length),
// an input buffer (a) and scratch variables
r, i, j, o, z, c[999], *C, x=1, y=1;
char a[999], l[999][999], (*L)[999];
// move rows down from current cursor position
D()
{
L(r, >y, , -1, --)
r++ ? strcpy(l[o], l[o-1]+--x), c[o-1]=x, l[o-1][x]=0 : 0;
c[y++] = strlen(l[o]);
x=1;
}
// move rows up, appending uppermost to current line
U()
{
strcat(*L, l[y]);
*C = strlen(*L);
L(y+1, <r, -1, , ++)
--r;
*l[r] = c[r] = 0;
}
// normalize positions, treat 0 as max
X(b) R(c[y-1], +1)
Y(b) R(r, )
main()
{
for(;;) // forever
{
// initialize z as current line index, the current line pointers,
// i and j for default values of positioning
z = i = y;
L = l + --z;
C = c + z;
j = x;
// prompt:
!r || y/r && x > *C
? P "end> ")
: P "%d,%d> ", y, x);
// read a line of input (using scanf so we don't need an include)
scanf("%[^\n]%*c", a)
// no command arguments -> make check easier:
? a[2] *= !!a[1],
// numerical input -> have move command:
// calculate new coordinates, checking for "relative"
N(a)
? y = Y(i + (i<0 | *a=='+') * y)
, x = X(j + (j<0 || strchr(a+1, '+')) * x)
:0
// check for empty input, read single newline
// and perform <return> command:
: ( *a = D(), scanf("%*c") );
switch(*a)
{
A 'e':
y = r;
x = c[r-1] + 1;
B;
A 'b':
y = 1;
x = 1;
B;
A 'L':
for(o = y-4; ++o < y+2;)
o<0 ^ o<r && P "%c%s\n", o^z ? ' ' : '>', l[o]);
for(o = x+1; --o;)
P " ");
P "^\n");
B;
A 'l':
puts(*L);
B;
A 'p':
i = 1;
j = 0;
N(a+2);
for(o = Y(i)-1; o<Y(j); ++o)
puts(l[o]);
B;
A 'A':
y = r++;
strcpy(l[y], a+2);
x = c[y] = strlen(a+2);
++x;
++y;
B;
A 'i':
D();
--y;
x=X(0);
// Commands i and r are very similar -> fall through
// from i to r after moving rows down and setting
// position at end of line:
A 'r':
strcpy(*L+x-1, a+2);
*C = strlen(*L);
x = 1;
++y > r && ++r;
B;
A 'I':
o = strlen(a+2);
memmove(*L+x+o-1, *L+x-1, *C-x+1);
*C += o;
memcpy(*L+x-1, a+2, o);
x += o;
B;
A 'd':
**L ? **L = *C = 0, x = 1 : U();
y = y>r ? r : y;
B;
A 'j':
y<r && U();
}
}
}
```
output
```
#define P printf(
#define A case
#define B break
#define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}
#define R(m,o){return b<1|b>m?m o:b;}
#define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)
r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];D(){L(r,>y,,-1,--)r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;c[y++]=strlen(l[o]);x=1;}U(){strcat(*L,l[y]);*C=strlen(*L);L(y+1,<r,-1,,++)--r;*l[r]=c[r]=0;}X(b)R(c[y-1],+1)Y(b)R(r,)main(){for(;;){z=i=y;L=l+--z;C=c+z;j=x;!r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);scanf("%[^\n]%*c",a)?a[2]*=!!a[1],N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:(*a=D(),scanf("%*c"));switch(*a){A'e':y=r;x=c[r-1]+1;B;A'b':y=1;x=1;B;A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;A'l':puts(*L);B;A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;A'i':D();--y;x=X(0);A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;A'j':y<r&&U();}}}
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest (in bytes) valid answer wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~327~~ ~~360~~ ~~418~~ 394 bytes
```
g.(m.w.r.r=<<).lines.f
n:c:z="\n#_0123456789"++['A'..'Z']++['a'..'z']
(!)x=elem x
f('\\':'\n':a)=f a
f(a:b)=a:f b
f a=a
m('#':a)=c:a++[n]
m a=a
g(a:'#':b)=a:[n|a/=n]++c:g b
g(a:b)=a:g b
g a=a
s=span(!" \t")
r=reverse.snd.s
l n(a:b)d|a==d,n=a:w(snd$s b)|1>0=a:l(not$n&&a=='\\')b d
w('/':'/':_)=[]
w(a:b)|a!"\"'"=a:l(1>0)b a|(p,q:u)<-s b=a:[' '|p>"",a!z&&q!z||[a,q]!words"++ -- /*"]++w(q:u)
w a=a
```
[Try it online!](https://tio.run/##NVFtT8MgEP7Or6DMDHAbc76Lw8S/4dqYa0u7xZZ1Zdpl1r9uPZr4geTueeMOtuA/bFUNWxMPpRK16lSrWrNeS1XtnPWqIE5n@mxY7CbvV6vrm9u7@4fHJzabbfgrV4q/8STUEOozT4iI5MnYytb0RArB45hrHjuuQZqCAkKgU2lAFzQlCBggteCTkc80YJRLSD3iJUoDM8o3roelcXhXpku0lv85YzPqvfENOBExGh@ZJK1p7ZdtvVXe5cqTirrRk/dgTD536O0EUheeprJfvVwhUAm3P1646RQlYXSZ0px0gi9xCTzv0mwS7ENMDxGLGWejC90ohV4084P@lOsFZoahOeV988LYHKLzdHqIzn2/gfkhibp9m3t8RLpY0OUlw7U6EZykC6sMNewcNXTnjraF7Ei3w@mZTHJb4J/QYr@nKbQkiIQk3@TnNysqKP2wyJrmDw "Haskell – Try It Online")
This was a lot of fun to write! First the `f` function comes through and removes all the backslashes at the end of lines then `lines` breaks it into a list of strings at the newlines. Then we map a bunch of functions onto the lines and concatenate them all back together. Those functions: strip whitespace from the left (`t`) and from the right (`r.t.r` where `r` is `reverse`); remove whitespace from the middle, ignoring string and character literals as well as removing comments (`w`); and finally adds a newline character to the end if the line starts with a #. After all the lines are concatenated back together `g` looks for # characters and ensures they are preceded by a newline.
`w` is a little complex so I'll explain it further. First I check for "//" since in `w` I know I'm not in a string literal I know this is a comment so I drop the rest of the line. Next I check if the head is a delimiter for a string or character literal. If it is I prepend it and pass the baton to `l` which runs through the characters, tracking the "escape" state with `n` which will be true if there have been an even number of consecutive slashes. When `l` detects a delimiter and isn't in the escape state it passes the baton back to `w`, trimming to eliminate whitespace after the literal because `w` expects the first character to not be whitespace. When `w` doesn't find a delimiter it uses span to look for whitespace in the tail. If there's any it checks if the characters around it are cannot be brought into contact and inserts a space if so. Then it recurs after the whitespace is ended. If there was no whitespace no space is inserted and it moves on anyway.
EDIT: Thanks a lot to @DLosc for pointing out a bug in my program that actually led to a way for me to shorten it as well! Hooray for pattern matching!
EDIT2: I'm an idiot who didn't finish reading the spec! Thanks again DLosc for pointing that out!
EDIT3: Just noticed some annoying type reduction thing that turned `e=elem` into `Char->[Char]->Bool` for some reason, thus breaking on `e[a,q]`. I had to add a type signature to force it to be correct. Does anyone know how I could fix that? I've never had this problem in Haskell before. [TIO](https://tio.run/##rVffb6NIEn7nr6hhNwYMTuzRvYwdHM3M3cNJ0eq00upmzvHstqGJcYBmuiH@Ec@/vrmvG9txYnKbh7NkA9VUddVXVV@150zd8Sx7nIc3j25@vjyX55X@hpeX3nmWFlydJxYPecZzK3Gdmxtn6NwUzpB5YUIMIjaceSEbJjSzIAiZlbvOT2bdXHzfvilsKzdLMpT8nkvFrU3o/O4MJ07fOT93PjhT3584H/X9f5p7pu83ztRSofsH/8Omm8r2rCqMpSj/PU8zTsrKqDC7x1sWhnGnU8CNpVvRzNsOxn08ZG4hqp@LTgfr2nNvRrG1dJ0LxIDv7144mVq9Hv2fPve9f0gpJEWsVjymOZecZtw8UVo5iphSdY4VTsMhfZ4zSb0xTfTNVN99EiKDezqkLSdm39iObaJANHCdbd0y@D6svcueKllBimZYnTjkbMuxbQdCTqBFm06H03faBHzCgu/Tn5dCxsr2fUKgF117CniXrjZjLXVOHnOWFhRSWlRcsqii@ePFBYmk4gWZMJK6iKpUFOrijq@NsaH1U8wTlAb9i0oJxcQ9SD4ieqR3//iJZpKzO8uCzUyIUlGiARLlOi1uSYqlorpcMhi9iMWyMHfEgJtK8zRrAMpZJMXB4rWbBsQDqgJKAlIe3Vh7/LVpV4TpiATxkfdAqpJRuXaziaBqGpC@JlNvRJERhNFEkZiO6IdxT7LillM059GdsaSdu4hEVueFolS97tGvbh4Ijx5I8qqWBc0uB9vZOKcryuHIkGb7HYxtHbc2X6ASZBqxDMiXdaV3KDiPAXi1TCNObi7ukc4ibiAGZnmOJ@8J/F/cxCOlIlYkLqCwz@LgLLYD6gCgzsKj7fZ4dbe28JpghciNGx8@fGjSsEyrOXEWzY0IcSvS3UOq5FGapDwG2HNRZzFKmngh6tu5py2xTAmKeZTprNlRLSWHt5o4qBSmqJRNbvfa7BazigXU/WwezDsZL26ruRcYU8UOi1mdJBy5ZJ4BQEWSVXDsnsmUzTKuLBkQglwEJAIUOvIJn6facECrcBDQOhyMrEg3GNstZea6e4A7nrkdGTAM0gYEXYOUSGCzDwRXBV9LoVLdBNbfXc96MBV37cKL8TqggHrYstfzjFii066OKq@pu95g6vd6K0/7qh/C1V48WU3DPqqkPzLq0WTt@1P0IywAG2PBa5ZWOqgfLzyuy4BYWfIi1oVV407mQlVUCTrOhfXbwW/tGqsAgfZgvTeOnBz2BDqjXYhrH6FdyibEgHy/CbLXkzu1bCK1t1Fz6e8dLITMWZZu@AE5hZYFFVTUBw2ig1bWF3fmoXkQMWCA7YFnfW1E2A9lqonp4DUKxh2NPIJt3OohYsQPh@bHQlpgp2bXjd7kWTGmRcwBejXn1FqkwTNLpu4WTc3yhNVZherLag7CSA4hAfGD0kZTKL7r0UF0jceMNO9unoQa5gjCI9ECohUq8Wj/EiVYVsOD6J3U3by@kNTp0IrGSJd1PHmuwMQ2amBMtvdsYagXDDFgCX2B/vCeb4WcxJgaBgvE1jSgWytdToY9CP295GiNwqkMRTV9GmV1zJ82a4jGPpt8uymmZ90ImzHPeuaLKYs9j4Hkb8GARaUaQr3bUy9nKuVy@CI8Nnk/pW5I796xCYrl1PALNoXNOUOPmEbZbTl8qYTXozpjFUdYS7yF2ZYWeESpPqNqW3K8ld5z@5mFX8BP1sszwBWtkc6vboocu@lln7bU1acP3/GoS@tTBf1BVqD0xV1opYVW2po2nUuX6QbU2lp9dao@7J9g8TTCOIpo3SASNInWac1MvIYVXmiaacMlVHM0vZlm43b0huQiLjgNPgwOyUfaPTquL4WpEs3d7hFQD8/sfCSHO8OTqDSGcnQiXjVMA7oAUIPT9U8j66X12SvWB@3W32b0usWoJiihCaD3txF4UtAlrf33o/aEC@T4G35NP@sOjc4UTsmYZ982KCEc6YCwM3bMkNhTdNtuK38wAsGIV/aBaTDCqTrk6NO2lZZos5ZoUVHqaU78hYGyxUDaDvaiGSIvxWg1//3/gAH95vWAhLj86i48g387IMbvVzBt8fzja7Xp@6f6h5m/xjRr97cp4PXRfG9/z/dXbcL1m5xOW5xGm57q9notBlfhF7ff8jLo4XPDBGo3HqU5qGMSr4/PxgnLMkxZqQ@IbUbM6SrV5xPo41@G1Bx9@DNgDmDmzMer6ni@Hg/H3fglHCYw8/TU0mQ2PAFCtgCxS1L32l/pI007/K2HoTdQBTKE2Wya2vflm5L1zxYfxV@VR85zPdhMFL7Qcezj6X7ugRLaQ/JDEq22XgACFmoNuV2/Jaa4JaYu/gFcmd@wgbffDL0BiO63tuLUbbYeSyhJvPK2yl@0tWtDss/2@GE1vz/@jJKM3arHXlSW/wU)
EDIT4: quick fix for bug @FelixPalmen showed me. I might try to golf it down later when I have some time.
EDIT5: -24 bytes thanks to @Lynn! Thank you! I didn't know you could assign things on the global scope using pattern matching like `n:c:z=...` that's really cool! Also good idea making an operator for `elem` wish I'd thought of that.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~148~~ ~~135~~ ~~133~~ 138 bytes
```
aRM"\
"R`("|').*?(?<!\\)(\\\\)*\1`{lPBaC:++i+191}R[`//.*``#.*`{X*aJw.`(?=`}.')M[A`\w`RL2"++""--""/*"]w`¶+`'·C(192+,#l)][x_WR'¶{aRw'·}xnsl]
```
Bytes are counted in [CP-1252](https://en.wikipedia.org/wiki/Windows-1252), so `¶` and `·` are one byte each. Note that this expects the C code as a single command-line argument, which (on an actual command line) would require the use of copious escape sequences. It's much easier at [Try it online!](https://tio.run/##TY7baoNAEIbvfYrJSuOuq67mLjEH2tyE0kDwpgUVVzyQha2GJEWL9bXS@7yY3QZ6@C@GYWb@75@DOAxDGmxRpKGAY/RhEMdc4dV8FEUER0rEjDzeyd1Dup5RKqg39fog5Iw5Jue6Kt2LmT42DserBe8dg2zDex41PHiaIEoRsm2EmInihl8vlBvXzzX2phNq6ZLEYZs8B8b10qVBozZ9W51kPAzDu6/posrkW17A/HTORe3sl5qeF6WoCthBpMGPDkdRnUv8u9wA2hRS1pY6auqjzEeMIa0NPTf2zcwXvvaaigoTYAz2AmYG0bobTWEgKfxbX9ZH7P9LOWVpVWJ0lyMLxi2BJbgwHgOlykD@LBksoAX6jYEMbHsJrQ9CDT3XBQZma6nfFUVFG4okwFZHSUEUov8C "Pip – Try It Online")
## Explanation of slightly ungolfed version
The code does a bunch of replacement operations, with a couple tricks.
### Backslash continuations
We `RM` all occurrences of the literal string
```
"\
"
```
that is, backslash followed by newline.
### String and character literals
We use a regex replacement with a callback function:
```
`("|').*?(?<!\\)(\\\\)*\1`
{
lPBa
C(++i + 191)
}
```
The regex matches a single or double quote, followed by a non-greedy `.*?` that matches 0 or more characters, as few as possible. We have a negative lookbehind to ensure that the previous character was not a backslash; then we match an even number of backslashes followed by the opening delimiter again.
The callback function takes the string/character literal and pushes it to the back of the list `l`. It then returns a character starting with character code 192 (`À`) and increasing with each literal replaced. Thus, code is transformed like so:
```
printf("%c", '\'');
printf(À, Á);
```
These replacement characters are guaranteed not to occur in the source code, which means we can unambiguously back-substitute them later.
### Comments
```
`//.*`
x
```
The regex matches `//` plus everything up to the newline and replaces with `x` (preset to the empty string).
### Preprocessor directives
```
`#.*`
_WR'¶
```
Wraps runs of non-newline characters starting with a pound sign in `¶`.
### Spaces that should not be eliminated
```
{
(
X*a J w.`(?=`
) . ')
}
M
[
A`\w` RL 2
"++"
"--"
"/*"
]
{
a R w '·
}
```
There's a lot going on here. The first part generates this list of regexes to replace:
```
[
`(?a)\w\s+(?=(?a)\w)` Whitespace surrounded by [a-zA-Z_]
`\+\s+(?=\+)` Whitespace surrounded by +
`\-\s+(?=\-)` Whitespace surrounded by -
`\/\s+(?=\*)` Whitespace surrounded by / *
]
```
Note the use of lookaheads to match, for example, just the `e` in `define P printf`. That way this match doesn't consume the `P`, which means the next match can use it.
We generate this list of regexes by mapping a function to a list, where the list contains
```
[
[`(?a)\w` `(?a)\w`]
"++"
"--"
"/*"
]
```
and the function does this to each element:
```
(X*aJw.`(?=`).')
X*a Map unary X to elements/chars a: converts to regex, escaping as needed
Regexes like `\w` stay unchanged; strings like "+" become `\+`
J Join the resulting list on:
w Preset variable for `\s+`
.`(?=` plus the beginning of the lookahead syntax
( ).') Concatenate the closing paren of the lookahead
```
Once we have our regexes, we replace their occurrences with this callback function:
```
{aRw'·}
```
which replaces the run of whitespace in each match with `·`.
### Whitespace elimination and cleanup
```
[w `¶+` '·]
[x n s]
```
Three successive replacements substitute remaining runs of whitespace (`w`) for empty string (`x`), runs of `¶` for newline, and `·` for space.
### Back-substitution of string and character literals
```
C(192+,#l)
l
```
We construct a list of all the characters we used as substitutions for literals by taking `192 + range(len(l))` and converting to characters. We then can replace each of these with its associated literal in `l`.
And that's it! The resulting string is autoprinted.
[Answer]
# C, ~~497~~ ~~494~~ ~~490~~ 489 bytes
Since we're processing C, let's do it *using* C! Function `f()` takes input from char pointer `p` and outputs to pointer `q`, and assumes that the input is in ASCII:
```
#define O*q++
#define R (r=*p++)
#define V(c)(isalnum(c)||c==95)
char*p,*q,r,s,t;d(){isspace(r)?g():r==47&&*p==r?c(),g():r==92?e():(O=s=r)==34?b():r==39?O=R,a():r?a():(O=r);}a(){R;d();}b(){((O=R)==34?a:r==92?O=R,b:b)();}c(){while(R-10)p+=r==92;}e(){R-10?s=O=92,O=r,a():h();}j(){(!isspace(R)?r==47&&*p==r?c(),j:(t=r==35,d):j)();}f(){t=*p==35;j();}i(){V(s)&&V(r)||s==47&&r==42||(s==43||s==45)&&r==s&&*p==s?O=32:0;d();}h(){isspace(R)?g():i();}g(){(r==10?t?O=r,j:*p==35?s-10?s=O=r,j:0:h:h)();}
```
We assume that the file is well-formed - string and character literals are closed, and if there's a comment on the final line, there must be a newline to close it.
## Explanation
The pre-golfed version is only slightly more legible, I'm afraid:
```
#define O *q++=
#define R (r=*p++)
#define V(c)(isalnum(c)||c=='_')
char*p,*q,r,s,t;
d(){isspace(r)?g():r=='/'&&*p==r?c(),g():r=='\\'?e():(O s=r)=='"'?b():r=='\''?O R,a():r?a():(O r);}
a(){R;d();}
b(){((O R)=='"'?a:r=='\\'?O R,b:b)();}
c(){while(R!='\n')p+=r=='\\';}
e(){R!='\n'?s=O'\\',O r,a():h();}
j(){(!isspace(R)?r=='/'&&*p==r?c(),j:(t=r=='#',d):j)();}
f(){t=*p=='#';j();}
i(){V(s)&&V(r)||s=='/'&&r=='*'||(s=='+'||s=='-')&&r==s&&*p==s?O' ':0;d();}
h(){isspace(R)?g():i();}
g(){(r=='\n'?t?O r,j:*p=='#'?s!='\n'?s=O r,j:0:h:h)();}
```
It implements a state machine by tail recursion. The helper macros and variables are
* **`O`** for **o**utput
* **`R`** to **r**ead input into `r`
* **`V`** to determine **v**alid identifier characters (since `!isalnum('_')`)
* **`p`** and **`q`** - I/O pointers as described
* **`r`** - last character to be **r**ead
* **`s`** - **s**aved recent non-whitespace character
* **`t`** - **t**ag when working on a preprocessor directive
Our states are
* **`a()`** - normal C code
* **`b()`** - string literal
* **`c()`** - comment
* **`d()`** - normal C code, after reading `r`
* **`e()`** - escape sequence
* **`f()`** - initial state (main function)
* **`g()`** - in whitespace
* **`h()`** - in whitespace - dispatch to `g()` or `i()`
* **`i()`** - immediately after whitespace - do we need to insert a space character?
* **`j()`** - initial whitespace - never insert a space character
## Test program
```
#define DEMO(code) \
do { \
char in[] = code; \
char out[sizeof in]; \
p=in;q=out;f(); \
puts("vvvvvvvvvv"); \
puts(out); \
puts("^^^^^^^^^^"); \
} while (0)
#include<stdio.h>
#include<stdlib.h>
int main()
{
DEMO(
"main() {\n"
" printf(\"Hello, World!\"); // hi\n"
"}\n"
);
DEMO(
"#define max(x, y) \\\n"
" x > y ? x : y\n"
"#define I(x) scanf(\"%d\", &x)\n"
"a;\n"
"b; // just a needless comment, \\\n"
" because we can!\n"
"main()\n"
"{\n"
" I(a);\n"
" I(b);\n"
" printf(\"\\\" max \\\": %d\\n\", max(a, b));\n"
"}\n"
);
DEMO(
"x[10];*c;i;\n"
"main()\n"
"{\n"
" int _e;\n"
" for(; scanf(\"%d\", &x) > 0 && ++_e;);\n"
" for(c = x + _e; c --> x; i = 100 / *x, printf(\"%d \", i - --_e));\n"
"}\n"
);
DEMO(
"// often used functions/keywords:\n"
"#define P printf(\n"
"#define A case\n"
"#define B break\n"
"\n"
"// loops for copying rows upwards/downwards are similar -> macro\n"
"#define L(i, e, t, f, s) \\\n"
" for (o=i; o e;){ strcpy(l[o t], l[o f]); c[o t]=c[s o]; }\n"
"\n"
"// range check for rows/columns is similar -> macro\n"
"#define R(m,o) { return b<1|b>m ? m o : b; }\n"
"\n"
"// checking for numerical input is needed twice (move and print command):\n"
"#define N(f) sscanf(f, \"%d,%d\", &i, &j) || sscanf(f, \",%d\", &j)\n"
"\n"
"// room for 999 rows with each 999 cols (not specified, should be enough)\n"
"// also declare \"current line pointers\" (*L for data, *C for line length),\n"
"// an input buffer (a) and scratch variables\n"
"r, i, j, o, z, c[999], *C, x=1, y=1;\n"
"char a[999], l[999][999], (*L)[999];\n"
"\n"
"// move rows down from current cursor position\n"
"D()\n"
"{\n"
" L(r, >y, , -1, --)\n"
" r++ ? strcpy(l[o], l[o-1]+--x), c[o-1]=x, l[o-1][x]=0 : 0;\n"
" c[y++] = strlen(l[o]);\n"
" x=1;\n"
"}\n"
"\n"
"// move rows up, appending uppermost to current line\n"
"U()\n"
"{\n"
" strcat(*L, l[y]);\n"
" *C = strlen(*L);\n"
" L(y+1, <r, -1, , ++)\n"
" --r;\n"
" *l[r] = c[r] = 0;\n"
"}\n"
"\n"
"// normalize positions, treat 0 as max\n"
"X(b) R(c[y-1], +1)\n"
"Y(b) R(r, )\n"
"\n"
"main()\n"
"{\n"
" for(;;) // forever\n"
" {\n"
" // initialize z as current line index, the current line pointers,\n"
" // i and j for default values of positioning\n"
" z = i = y;\n"
" L = l + --z;\n"
" C = c + z;\n"
" j = x;\n"
"\n"
" // prompt:\n"
" !r || y/r && x > *C\n"
" ? P \"end> \")\n"
" : P \"%d,%d> \", y, x);\n"
"\n"
" // read a line of input (using scanf so we don't need an include)\n"
" scanf(\"%[^\\n]%*c\", a)\n"
"\n"
" // no command arguments -> make check easier:\n"
" ? a[2] *= !!a[1],\n"
"\n"
" // numerical input -> have move command:\n"
" // calculate new coordinates, checking for \"relative\"\n"
" N(a)\n"
" ? y = Y(i + (i<0 | *a=='+') * y)\n"
" , x = X(j + (j<0 || strchr(a+1, '+')) * x)\n"
" :0\n"
"\n"
" // check for empty input, read single newline\n"
" // and perform <return> command:\n"
" : ( *a = D(), scanf(\"%*c\") );\n"
"\n"
" switch(*a)\n"
" {\n"
" A 'e':\n"
" y = r;\n"
" x = c[r-1] + 1;\n"
" B;\n"
"\n"
" A 'b':\n"
" y = 1;\n"
" x = 1;\n"
" B;\n"
"\n"
" A 'L':\n"
" for(o = y-4; ++o < y+2;)\n"
" o<0 ^ o<r && P \"%c%s\\n\", o^z ? ' ' : '>', l[o]);\n"
" for(o = x+1; --o;)\n"
" P \" \");\n"
" P \"^\\n\");\n"
" B;\n"
"\n"
" A 'l':\n"
" puts(*L);\n"
" B;\n"
"\n"
" A 'p':\n"
" i = 1;\n"
" j = 0;\n"
" N(a+2);\n"
" for(o = Y(i)-1; o<Y(j); ++o)\n"
" puts(l[o]);\n"
" B;\n"
"\n"
" A 'A':\n"
" y = r++;\n"
" strcpy(l[y], a+2);\n"
" x = c[y] = strlen(a+2);\n"
" ++x;\n"
" ++y;\n"
" B;\n"
"\n"
" A 'i':\n"
" D();\n"
" --y;\n"
" x=X(0);\n"
" // Commands i and r are very similar -> fall through\n"
" // from i to r after moving rows down and setting\n"
" // position at end of line:\n"
"\n"
" A 'r':\n"
" strcpy(*L+x-1, a+2);\n"
" *C = strlen(*L);\n"
" x = 1;\n"
" ++y > r && ++r;\n"
" B;\n"
"\n"
" A 'I':\n"
" o = strlen(a+2);\n"
" memmove(*L+x+o-1, *L+x-1, *C-x+1);\n"
" *C += o;\n"
" memcpy(*L+x-1, a+2, o);\n"
" x += o;\n"
" B;\n"
"\n"
" A 'd':\n"
" **L ? **L = *C = 0, x = 1 : U();\n"
" y = y>r ? r : y;\n"
" B;\n"
"\n"
" A 'j':\n"
" y<r && U();\n"
" }\n"
" }\n"
"}\n";);
}
```
This produces
>
>
> ```
> main(){printf("Hello, World!");}
>
> ```
>
>
>
>
> ```
> #define max(x,y)x>y?x:y
> #define I(x)scanf("%d",&x)
> a;b;main(){I(a);I(b);printf("\" max \": %d\n",max(a,b));}
>
> ```
>
>
>
>
> ```
> x[10];*c;i;main(){int _e;for(;scanf("%d",&x)>0&&++_e;);for(c=x+_e;c-->x;i=100/ *x,printf("%d ",i- --_e));}
>
> ```
>
>
>
>
> ```
> #define P printf(
> #define A case
> #define B break
> #define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}
> #define R(m,o){return b<1|b>m?m o:b;}
> #define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)
> r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];D(){L(r,>y,,-1,--)r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;c[y++]=strlen(l[o]);x=1;}U(){strcat(*L,l[y]);*C=strlen(*L);L(y+1,<r,-1,,++)--r;*l[r]=c[r]=0;}X(b)R(c[y-1],+1)Y(b)R(r,)main(){for(;;){z=i=y;L=l+--z;C=c+z;j=x;!r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);scanf("%[^\n]%*c",a)?a[2]*=!!a[1],N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:(*a=D(),scanf("%*c"));switch(*a){A'e':y=r;x=c[r-1]+1;B;A'b':y=1;x=1;B;A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ' :'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;A'l':puts(*L);B;A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;A'i':D();--y;x=X(0);A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;A'j':y<r&&U();}}}
>
> ```
>
>
## Limitation
This breaks definitions such as
```
#define A (x)
```
by removing the space that separates the name from expansion, giving
```
#define A(x)
```
with an entirely different meaning. This case is absent from the test sets, so I'm not going to address it.
I suspect I might be able to produce a shorter version with a multi-pass in-place conversion - I might try that next week.
[Answer]
# C, ~~705~~ ~~663~~ 640 bytes
*Thanks to @Zacharý for golfing 40 bytes and thanks to @Nahuel Fouilleul for golfing 23 bytes!*
```
#define A(x)(x>47&x<58|x>64&x<91|x>96&x<123)
#define K if(*C==47&(C[1]==47|p==47)){if(p==47)--G;for(c=1;c;*C++-92||c++)*C-10||--c;if(d)p=*G++=10,--d;
#define D if(!d&*C==35){d=1;if(p&p-10)p=*G++=10;}
#define S K}if((A(p)&A(*C))|(p==*C&l==43|p==45)|p==47&*C==42|p==95&(A(*C)|*C==95)|*C==95&(A(p)|p==95))p=*G++=32;}
#define W*C<33|*C==92
#define F{for(;W;C++)
c,d,e,p,l;g(char*C,char*G)F;for(;*C;*C>32&&*C-34&&*C-39&&(p=*G++=*C),*C-34&&*C-39&&C++){l=e=0;if(*C==34)l=34;if(*C==39)l=39;if(l)for(*G++=l,p=*G++=*++C;*C++-l|e%2;e=*(C-1)-92?0:e+1)p=*G++=*C;K}D if(d){if(W)F{*C-92||++d;*C-10||--d;if(!d){p=*G++=10;goto E;}}S}else{if(W)F;S}E:D}*G=0;}
```
[Try it online!](https://tio.run/##jVdtb9pKFv7OrzjlKsTjlw2QpLvgmCqX3larRlerra7ailLJsQcwNR5rbBoI8Nu7z4yNA8HZW9pgz5k5b895GwJnGgQ/f/4W8kmUcLo1VsxYDa7@2VrdXP9ruxq8vsJbr4O33mu8dbqXrLE//IGiiWEOPQ/HjeGoM1Zv21R9M7bBXvHqOO/diZBG4HXcwDWHluX0utttYFnMHDqd9nbrOIGL4yFLPfO9ZXmdtu04oVspeqsUvQpbStflNduEkKTEt1KwPzG5u4rjI33Y4YRxa6SsdQsjGdsqc8xhK4ZRl9rKa1YYq@VeddWid90y9PGtovWu98@WllScYHuNl90DjZ/M4c3lZXG8W1HfbZTn7icXXrNGYIc2t1M7dqdGMPOlObT14z17pxECOPg/uOy2YJJzeVU8eq2WUWqEYfbxjpK7iT3utd0yGJdXLMZXteypZU8tY6aUaEGxvZdoWcMiJvGWn3Vd7pkGgsIQojftPrc6rFLtftjpQIQ6tp/Yuw1sUJG0rNCtIhm6OlZs8xSWqcgF/eHudh93PM54ye1@3P3Rf7sz38P03c/foiSIlyGnmywPI/GP2aBxSJJRMlW0KMlp4UeJwRqbBuGj8KNMBqOrdu/12H2ihTzL98Qn6v1yMuq0u1flyYdZFHMyJlOeZwb2bFKbNikbEsb0GfWBAYGfG9BjKxGsFDktKErVnpTC0nxiNM@yZrWx@3lxQWKS84SWGQ9pskyCPBJJdvGdrx@EDLN@lTD/2UuoKLcU@Bmvlr/TveT@90YDMmMh0owQVApEugZEJMVDRsv0wYfQi1A8JPqNfMkpixZRDAicARAMpKgk3hmRTdym3CYAkDH6WvmtRBvCi1wSxF220UCkayMeCcrHNqnnZMxcCjTBC0YZibFLO22e9JMpB@48@K4lKeMuAhEvF0lGUfayRf81FrZgtCHJ86VM6P6ms70fLOgNLWBIn@73GrRs5bcSnywXXEaBH1OUpMtcaUg4DwF4/hAFCPNC/ODkJ2EBMTBbLLBiT@D/aUwYZVngJxMDUDTPQvssRBxbAKg1Z7TdHu6We3NWOCvEQpvR6/WKMDxE@Yy4H8w0CX5nZCQipyzlQTSJeAiwZ2IZh3TPiSdiOZ0xJcmPM4HUCWIVtWawlJLD2lgZmAoYzmXWJMO809pCP/dtMod6oc/EPJnmM2ZrUUmJBZJ2whFLn2kAskD6OQz74cvIv4951pA2wcm5TcKmRxvxhM1jJdimldexaY2W29Al5JdbsX6WC5jD9KurwdBIaxBUDtJEApu9I3hmsDUVWaSKoPG2quU7A1YM1jbZ5ECl4xQFKC0LkX/KvCLvnM7YcpwVU7aqhbfak0ersddGlrTLbjBaW9aYPCUB2GgJrNhaKad2zyxepjb5acqTUCXWEm9yIbKc0MMOY9H4q7K77A7mnbJgvReOmFQ6gY5buri24NqNLFy0SY0FteE4smSLR1JZGxSP9t7ARMiFH0ePvEIuQ8miFeTUJj9DBa0an417huKBx4ABsjus8aUgQR/S9Khz6oHjMoJsvPIfXGrypip@bEQJNBVaH5WSo2SMkpAD9HzGqTZJ7SNJOu/mRc7yib@Mc2RfvORoGJPKJSBeMT3C@wh/a7ci3WEZkwWwHp@ICuYAxAPSHKRV2ZBL/SlSMM37FemVVNW8vpDUatGKBghXtac@b9CJm8iBATXZ0UZfbejGgC3UBeqDHatCTELyCyzgW1GAxjJT6aS7B6G@HzhKIznPdYsq6lQPu4OZoxtN82z07WsyPjMDKPNZ48gWnRb7PoYmP0UHTPKsaKjf962X@1nEZf@Ze/6oOybTo1evfNzc7FPBz7opZM581IgulFJl/zkTjgfL2M853HrAKcy2KMESqXrUqpuS41T0gzePJPyJ/nREKExdI5xfjAgxNqKbNm3J9D3v3DpnZNL6lEF9EBUwfTbmimmumLa6TGfS8FUBKm7Fvjpl77dPsHgaYRxJtC4QsYtAq7DG2l/dFZ5x6mnDJVgXKHo9zQb16PXJgF8wGv3QroKPsDM6zK8MUyWYGeYBUJsjObd0zs/7J14pDKV7Ql4VnQbtAkB1Tvd/dxvPpd@/IL1TL/3XhN7VCFUNSqgG4Fy56JOCbmhtdd36gAvE@Bu@dT2rCg3Osq8JakZ8e0QKneNfn84H53pI7Ft0nbaV1XHRYMQLeiAaHeGUHXTUad1OjbdxjbfIqOxpTvyNgLRGQFQP9rwYIs/JKDWr@39gQL0xB0iImy/GnGn86wHRdr@AaY3lty/lpmWd8lczf41pVm9vkcDrg/lef86yVnXE9S8ZHdUYjTI95XWcGoEr77PRrjmM9jAsOkFWjkepL@qYxOvDu/HEj2NMWakuiHVC9O0qUvcT8ONXhlQ9uvoxoC9g@s7H8/xwvh4Ox3L8Ei4TmHlqaqlm1j8BQtYAUQbJvLNW6kpTD3/tZegXWgUihNmsi9qy5C8F6981Noq/S48FX6jBpr2whPJj7w9@2KIl1LtkeSRqZT0DBF2o1uV6/hqfwhqfTPwCeKO/vQLedjH0Omh0f9Ulpyqz9UCCSeLIr2X@vK5ciyZ7pGPXKL53/wM)
[Answer]
# Perl 5, ~~250+3 (-00n)~~, 167+1 (-p) bytes
```
$_.=<>while s/\\
//;s,(//.*)|(("|')(\\.|.)*?\3)|/?[^"'/]+,$1|$2?$2:$&=~s@(\S?)\K\s+(?=(.?))@"$1$2"=~/\w\w|\+\+|--|\/\*/&&$"@ger,ge;$d++&&$l+/^#/&&s/^/
/,$l=/^#/m if/./
```
[Try it online](https://tio.run/##HYlBT4MwGEDv/RVN17CWQr8M40XGyt2jRz8xRupo0gGhLJhY99NF9F1eXt5oJ3@/rvxVV8fT0jlvaQBEAlCGTADoVEYhWNxLgaijlqnBOxnBPDdsDy8q44fIC8OLB55Ut1ALfDISHzEoYSqhjZQ14wdesOoGuOASUaGKeR4RMIUk4aw@2yk725K3Sm3tFTS7bQRogEDGffXXF@o@QMO6fpZk5/p3f20tPYa5dYPuTsT1M728uV5I8kXoxnidg2Cd9X6gAHTu7GQR2XbYvyQtyffPMM5u6MOaj78)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~479~~ ~~456~~ ~~445~~ ~~434~~ ~~502~~ 497 bytes
```
e=enumerate
import re
u=re.sub
def f(s):
r=()
for l in u(r'\\\n','',s).split('\n'):
s=p=w=0;L=[]
for i,c in e(l):
if(p<1)*'//'==l[i:i+2]:l=l[:i]
if c in"'\""and w%2<1:
if p in(c,0):L+=[l[s:i+1]];s=i+1
p=[0,c][p<1]
w=[0,w+1]['\\'==c]
r+=L+[l[s:]],
S=''
for l in r:s=''.join([u('. .',R,u('. .',R,u('\s+',' ',x))).strip(),x][i%2]for i,x in e(l));S+=['%s','\n%s\n'][s[:1]=='#']%s
print u('\n\n','\n',S).strip()
def R(m):g=m.group(0);f=g[::2];return[f,g][f.isalnum()or f in'++ -- /*']
```
[Try it online!](https://tio.run/##jVhdb5tIF74uv@LUVQoYnNjR3hRCqm73plK0erXVSq0wXWE8xONiBs1ADWn72/s@M9iuHZPd5sLAMOfrOec8Z0jV1StRXv/4wSJWNhsm05pZfFMJWZNkVhNJdqmahbVkOeWOcgOLZOS4FuVCUkG8pMaR9nw@L23ftn3lXqqq4LVjYwGbn6moirbRNLyL4sR6poW4n2kx5hT6PfHcqW5m7ti@urKjqIh5wL3rJChwG/DEbCAtMLLno1FaLml7cX0zg@QzvKjwwsn8qRvceVFcxArCsyQJVYQrtlRRPPWzJIYFrWqrH7fYEcNjWMuwKL3ozjOiSeJb9D6y7aPgZKCwcLkWsBM3jn1Jl7b/l39yN1ceYifbb10X4deSV47rt0nML66TPuJ2H7Ebvoej9oWCxLy8UEApiVUczJIosl/YyYWyqJK8rEkrLg2q@uf9QbHJxF/Oxg3uo83lvRRN5UzdMI/u4yC4TkLJ6kaWce7fJ3F@yVVaIK2OCzdyOGF7Hk0mdDW2kx@5I0ej0Qvo4yWjTdo6rU@dS3OL8NfSLXX0GteAOmu/653TuqSytMyd0cVy5NPL1rXS0FqEdHVF60bVlFLJ2LJgSlEmNhtW1v5Opf5bsCxtFKMtI2h5bm1SIOtaX82Gd07qhru7xe7OoAFr85F2keajgC6W8xKmtcepTwuAan1HJK5lmc2W1UfWxrNpEo6zkIenZjS8/7BePfLjhI8jQuhTevmSPA/b3J8bM4qAh6eFUZOTyS21IXEszqZTuqIx8Nu7e7Ek6OI0wbZ/2JMuhtYLXmZFs2R0o@olF5erW0v7d@Jw1dTKGa1YUQgNc71iko2eUIn3Iq8Z@lKxJeVNmdVclOrqM@u2Qi5VcMjl//bOHlbeICeKHR5/p4Vk6WfLgs5CiEqZvshE1fHynqTYKmqqbQqlV0uxLc0dpZKR4htepJIA0CbNpDhovHO4T8wnlETuk3KPCkOrdkTEQxIE0L8S6j2rOqeIBdWJT/qaJy6ANwtRFisSSUjfjXsyLe9RUSuWfTaatHNXmSiaTamIq6c9Qif5wqWv1PcNLW5m3xa3GxT@Bo4EtNhbMLp13Fq9YUqepZojkBxtQRc9AK@3PGPkbMQXRpqt@mbWjYAn9yf4fzo5GqmvO0CBevH76gNAL9cufft2/Hb3bu32wQqxMW68evWqT8OW1ytiabYyS4hbkVOKmlTFMp5ztgTYK9EUS/QfsVI09ytXa0oLJWjJskJnbZQ1UqJdqdAOVqC8mkk1Imd8Z6wt0xrtNn7bs6PeU7Dyvl65vlFV7rBYNHnOkMvUNQCoDCMFjn1JJU8XoAVLoi98WvskfHrwkU/4nGjFPrXRDBQUzUIrWyFb6e5VYa67B7jjmtvQgGGQNiDoGqRcApt9ILgq@FoJxXUTWH8cOurOgRe3nU8@TWByMnHNsgQ9vj6qvL7uJrPEm0xaV/uqH6J2vxy3STRFlUx7jsjizvMS8AE0ABujYUcfrQ7q@yOPm8qntKpYudSF1eBObgQotBZ0nAvr74Pf2rW0BgTag26vHDk52AQ64S7EzkNoN7IP0Qeb9UFOJnInVsRSe5v1l@newVLITVrwB3ZATqFlQQU1aDFVmnitDyBoNA8iBgzQPXOtj/0S7KFMT/jLkGzoau7CLfvCpFn@emh@vOAlLPVWH7SRk2Lk5ZIBdBAfDRapf6LJ1N26r1mWp01Ro/qKhoEw8kNIQPwg9IDoNY134WHpDo8F6WH58HNRw5xh8WhprUcCKvHIfoUSrOrgsPRc6m7urqQeKXqsjt8e3um/12DiEWrglkbuyYtAvzDEcKuHCaq1dU9NISdLDFyDhch3Deg0SpeTYQ9Cf2PULkVp14ai@j41E@ensf34iz/Ny@RinMFY6lonvpiy2PMYSP6@0ZNd9YT6eU@9LFWcyeBReGl8ndA4oufP0xjFcq74EZtC5ypFj5hG2ZkMHgthe9YUOK0irC12YbbxEo8o1ROqHkmGXfwLG51o@BP8dLLQu9ohnR8djhw7/GZK32ic4mDm2S6NcTQ6E9B/yAqEPjhrLbTWQt9Mm66kk@oG1NJavD0XD6ZnWPwcYQxF1PWI@H2idVoLE69hhUeSZtowCdENmt5Ms9th9AJyEBecBh/6h@Qj7S4d15fCVMlWzvgIqK8net6QzezgLCqNoQzPltueaUAXAGp2/v730HqsffGE9tmw9l9TejegVBOU0AQw@S0ETwq6oc67DocTLpDjT/g1/aw7NNPnePSM@PSAEsKXABC2b20zJPYUPWSt9WYhCEY8YQeqaTQgjnX06dCbgWiLgWjNcfIwJ/5DQTWggA@Dve6HyONltJp3/S8woN/cCZAQNx@dtWvwHwbE@P0EpgOev3mqNj3vXP4w8ztMs2F/@wLujub78D7Pa4cWu19ymg84jTY9l51MBhS20Qf9MXi2Dnp42zOB2o1HaQ7qmMTd8dk4T4sCU1bqA@KQEnO64vp8Anl8ZUjN0YePAXMAM2c@VtfH8/V4OO7GL@EwgZmnp5Yms@AMCDkAxC5J4zuv1UeaYfgHD0O/QBXIEGaz7L/75C8l692Aj@K/ymPDNnqwmSg8oePYxzN@OwElDIfkRSQGdT0CBCw0GPKw/EBMy4GYxvgCeG1@ox7eaT/0ZiC6v4eKU7dZdyshJPW/D37J8HqoXXuSPbHx3ep/zcfvj/8D "Python 2 – Try It Online")
Edit: Fixed to include `- -`,`+ +`, and `/ *`
] |
[Question]
[
### Description
A Caesar Shift is a very simple monoalphabetic cipher where each letter gets replaced by the one after it in the alphabet. Example:
```
Hello world! -> IFMMP XPSME!
```
*(`IBSLR, EGUFV!` is the output for the actual challenge, this was an example of shifting by 1.)*
As you can see, spacing and punctuation remain unattuned. However, to prevent guessing the message, all letters are capitalized. By shifting the letters back, the message was deciphered, convenient, but also really easy to decipher by other persons who are supposed not to know what the message means.
So, we'll be helping Caesar a bit by using an advanced form of his cipher: the *Self-shifting Caesar Shift*!
### Challenge
Your task is to write a program or function, that, given a string to encipher, outputs the encrypted string corresponding to the input. The advanced Caesar Shift works like this:
```
1. Compute letter differences of all adjacent letters:
1.1. Letter difference is computed like this:
Position of 2nd letter in the alphabet
-Position of 1st letter in the alphabet
=======================================
Letter difference
1.2. Example input: Hello
H - e|e - l|l - l|l - o
7 - 5|5 - 12|12 - 12|12 - 15 Letter differences: 3; -7; 0; -3
=3| =-7| =0| =-3
2. Assign the letters continously a letter difference from the list,
starting at the second letter and inverting the differences:
2.1. 2nd letter: first difference, 3rd letter: second difference, etc.
2.2. The first letter is assigned a 1.
2.3. Example input: Hello with differences 3; -7; 0; -3
Letter || Value
=======||======
H || 1
E || -3
L || 7
L || 0
O || 3
3. Shift the letters by the value x they have been assigned:
3.1. In case of a positive x, the letter is shifted x letters to the right.
3.2. In case of a negative x, the letter is shifted |x| letters to the left.
3.3. In case of x = 0, the letter is not shifted.
3.4. If the shift would surpass the limits of the alphabet, it gets wrapped around
Example: Y + Shift of 2 --> A
3.5. Example input: See the table under 2.3.
|| || Shifted
Letter || Value || Letter
=======||=======||=========
H || 1 || I
E || -3 || B Program output:
L || 7 || S IBSLR
L || 0 || L
O || 3 || R
```
Spaces and other special symbols, such as punctuation are skipped in this process. It is guaranteed that your program will be given a string containing only printable ASCII characters. The output of your function/program must only be in upper case.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply, and may the shortest answer in bytes win!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~27~~ 24 bytes
```
láÇ¥R`XIlvyaiAyk+Aèëy}u?
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/5/DCw@2HlgYlRHjmlFUmZjpWZms7Hl5xeHVlban9//8eqTk5@Qrh@UU5KYoA "05AB1E – Try It Online")
**Explanation**
```
l # convert input to lower case
á # keep only letters
Ç¥ # compute deltas of character codes
R` # reverse and push separated to stack
X # push 1
Ilv # for each char y in lower case input
yai # if y is a letter
Ayk # get the index of y in the alphabet
+ # add the next delta
Aè # index into the alphabet with this
ëy # else push y
} # end if
u? # print as upper case
```
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
b=0
for c in map(ord,input().upper()):
if 64<c<91:b,c=c,(c+c-(b or~-c)-65)%26+65
print(end=chr(c))
```
[Try it online!](https://tio.run/##BcFLCsMgEADQvaeYLgozREt/ERqSfa9RR0MEqzIYSje9un2vfttW8q13t5zVWgQYYob3q2IRr2Oue0M67bUGQaJJQVzB3meeH5fJaV5YIw9s0EGRn2EydqTj1Q52VFAl5oYh@4U3QSbq/RlSKho@RZI//AE "Python 3 – Try It Online")
`b` keeps track of the last letter’s ASCII code, or is initially zero; the formula `c+c-(b or~-x)` means a letter with ASCII code `c` gets shifted by `c-b` if `b` is non-zero, and `c-(c-1) == +1` if `b` is zero (for the very first letter).
`b` will never become zero again, as the string is guaranteed to consist of *printable* ASCII characters.
Finally, `64<c<91` checks if `c` is an uppercase ASCII letter, and `(…-65)%26+65` wraps everything back into the `A-Z` range.
ovs saved a byte. Thanks!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~30~~ 29 bytes
```
lDáÇ¥1¸ìUvyaiAX¾èAyk+sè¼ëy}Ju
```
[Try it online!](https://tio.run/##AT4Awf8wNWFiMWX//2xEw6HDh8KlMcK4w6xVdnlhaUFYwr7DqEF5aytzw6jCvMOreX1Kdf//SGVsbG8sIHdvcmxkIQ "05AB1E – Try It Online")
[Answer]
# ES6 ( Javascript ) , 138 bytes :
```
s=>((s,a,f)=>((r=i=>s[i]&&(a[i]=String.fromCharCode((2*s[f](i)-(s[f](i-1)||71)-38)%26+64),r(i+1)))(0),a))(s.toUpperCase(),[],"charCodeAt")
```
<http://jsbin.com/manurenasa/edit?console>
[Answer]
# [MATL](https://github.com/lmendo/MATL), 27 bytes
```
tXkt1Y2mXH)tlwdh+64-lY2w)H(
```
[Try it online!](https://tio.run/##y00syfn/vyQiu8Qw0ig3wkOzJKc8JUPbzEQ3J9KoXNND4/9/dY/UnJx8HYXy/KKcFEV1AA "MATL – Try It Online")
I think this is the shortest I can get, but there are lots of different varieties since there is a lot of re-use of 'variables' (there are 3 `t` (duplication), and 2 `w` (swap) operations, clipboard `H` is used, and even then there is still a duplicate `1Y2`...). Sadly, I couldn't save bytes with the automatic `M` clipboard.
Over half of the program is dedicated to making it uppercase and ignoring non-alphabetic characters - just the cipher is no more than 13 bytes ([Try it online!](https://tio.run/##y00syfn/3zDSKCczJcNd28xEV/P/f3UPVx8f/3D/IB8XdQA "MATL – Try It Online"))
[Answer]
## Perl, ~~90~~89
Though non-codegolf languages are rarely competitive, we can go below 100 ;)
```
@a=split//,<>;say uc(++$a[0]).join'',map{uc chr(2*ord($a[$_+1])-ord($a[$_])+!$_)}0..$#a-1
```
I've decided to ungolf this:
`@a = split//,<>;` Takes input from STDIN, stores character list (with newline!) in @a.
`say uc(++$a[0])` output uppercase first letter shifted by 1. Turns out you can increment a letter in perl if you use a prefix ++. This is a mutator ofc.
`2*ord($a[$_+1])-ord($a[$_])+!$_` We are asked to take character at x, and add the difference + (x-(x-1)). Well that's 2x - (x-1). However: I changed the first letter! So I've got to correct that error, hence `+!$_`, which will correct for having subtracted one too many at position 0 (only case !$\_ is not undef ). We then `uc chr` to get an uppercase letter from the calculated ASCII value.
`map{ ... } $#a-2` - `$#a` is the position to access the last array element. Since I'm adding one I want `$#a-1`, but because the newline from input needs ignoring, this is `$#a-2`.
This is concatenated with the first letter, and we are done :)
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, ~~73~~ ~~77~~ 74 bytes
```
/\w/&&($_=chr 65+(2*($n=ord uc)-65-($!||-1+ord uc))%26)&($!=$n)for@F;say@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18/plxfTU1DJd42OaNIwcxUW8NIS0Mlzza/KEWhNFlT18xUV0NFsaZG11AbKqSpamSmCdShaKuSp5mWX@TgZl2cWOng9v@/R2pOTr6OQnl@UU6K4r/8gpLM/Lzi/7q@pnoGhgb/dd0A "Perl 5 – Try It Online")
[Answer]
# PHP, ~~106~~ 98 bytes
pretty nasty that one ... if just `base_convert` wasn´t that long (or `ctype_alpha`) ...
but I got it under 100. satisfied.
```
for(;$a=ord($c=$argn[$i++]);print ctype_alpha($c)?chr(65+($p?(25-$p+2*$p=$a)%26:$p=$a)):$c)$a&=31;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/25ec0d085b1c44508279f02d7c1fc23e073d874a).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 83 87 81 bytes
```
s=>s.replace(/[a-z]/gi,(x,i)=>Buffer(x).map(x=>((i?x%32-l:1)+26+(l=x%32))%26+64))
```
[Try it online!](https://tio.run/##FcndCsIgFADgV6nB4BymjlbsItCgq94huhCnwzhN0X6kl7d1@fHd9Vtnk3x88iVMtjpZs1RZJBtJGwv9VfPvrZ89g8I8SnV@OWcTFBQPHaFIBeBPpd0PnI477IaxA5J/I7YrxgNiNWHJgaygMIOD5mKJAtt8QqJp26z/Aw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
[Röda](https://github.com/fergusq/roda/) is a stream-based scripting language created by [fergusq](https://codegolf.stackexchange.com/users/66323/fergusq).
What general tips do you have for golfing in Röda? I'm looking for ideas that can which can be applied to code-golf problems and which are also at least somewhat specific to Röda (e.g. "remove comments" is not an answer).
Please post one tip per answer.
[Answer]
# Use underscores
This is probably the most important tip. Nearly every golfed Röda program uses underscores.
The underscore syntax is syntactic sugar for `for` loops. The following lines of code are equivalent:
```
ls""|fileLength x for x|sort|pull
ls""|fileLength _|sort|pull
```
Each underscore adds a new variable to an invisible `for` loop that is around the statement. The loop pulls one value from the stream for each variable/underscore and then repeats, until no values are left.
Underscores can be used anywhere in statements:
```
a[x:y+1]=[1]*(1+y-x) /* Sets range x..y (inclusive) */
seq x,y|a[_]=1 /* 6 bytes less */
```
If you must refer to the same underscore value more than once, or use the values in reverse order, you can put a number after the underscore:
```
a|[_^_1] /* maps x to x^x */
a|[_2-_1] /* maps each pair (x,y) to y-x, eg. [1,2,4,8] -> [1, 4] */
```
[Answer]
# Some semicolons/newlines are optional
When writing Röda code, it is generally recommended to use newlines or semicolons to separate all statements. However, when golfing, it is worth to know that not all semicolons are really required.
Here's an incomplete list of places where semicolons/newlines are **optional**. Most of them do not apply when the following statement begins with an operator (`(`, `[`, `+`, etc.).
* After assignments
* After function calls, when there's at least one argument (eg. `f x`) **or** when parentheses are used (eg. `f()`)
* Everywhere, if the next line/statement would begin with `|`, `)`, `]` or `}`
If the next statement begins with an operator, the semicolon/newline is **optional** if
* The statement is a function call and parentheses are used, eg `{f(x)[y]}` is same as `{f(x);[y]}`. This works only in statement context, not when the function call is an expression.
* The statement is an assignment and parentheses are used, eg `x=(y)[z]` is same as `x=(y);[z]` (that is not same as `x=((y)[z])`).
And here are some places where the newlines are unfortunately **required**:
* After `++` and `--`.
* After `[...]`.
It is often possible to save bytes by reorganizing assignments. For example:
```
a=0;b=""c=[""]
b=""c=[b]a=0
x=f()y=i;z=a[0]
x=f()z=a[0]y=i
```
[Answer]
# Use suffix control structures
It is almost **never** optimal not to use suffix statements, as you can use `{...}` in place of `do...end`.
Some examples:
```
x|unless[not(_ in y)]do[0]else[1]done
x|[0]unless[not(_ in y)]else[1]
if[p<0]do c+=p;a-=p done
{c+=p;a-=p}if[p<0]
```
[Answer]
# Use the stream for input
In cases where the input is a list of elements, it can be beneficial to pull the values from the stream instead of getting them as an array.
In most of the cases the array elements are iterated by pushing them to the stream and then iterating it using a `for` loop (or an underscore). As the elements are iterated from the stream anyway, why not *define* that they should be there from the beginning?
For example, to calculate the sum of the squares of the numbers in input:
```
{|a|a|[_^2]|sum} /* Removing a redundant argument */
{[_^2]|sum} /* saves 5 bytes */
```
[Answer]
The parentheses are optional in the statement context. This applies even if the argument begins with an operator. For example, `[a()|sqrt-_]` is shorter than `[a()|sqrt(-_)]`. The parentheses after `a` are mandatory, as `a` is in the expression context, not in the statement context.
However, writing `[a()|sqrt(_+1)*2]` is not possible, and extra parentheses are needed to help the parser: `[a()|sqrt((_+1)*2)]`. Often it is possible to rewrite such expression so that it doesn't begin with a parenthesis: `[a()|sqrt 2*(_+1)]`
[Answer]
# Use `,` instead of `..` in `[]`/`push` statements
>
> Related: [Use `,` instead of `and`](https://codegolf.stackexchange.com/a/114401/41805)
>
>
>
The `push` function (as well as the `print` function) can take any number of arguments, and outputs each one of them with no delimiter.
So that means something like this
```
["a"..b] /*8 bytes (string "a" concatenated with variable b)*/
```
can be shortened into just
```
["a",b] /*7 bytes*/
```
saving 1 byte.
[Answer]
# `[]`/`push` > `print`
Never use `print` statements. `[]` push statements are always golfier. The difference between `print` and `push` is that the former outputs a trailing newline while the latter doesn't. However, this can be circumvented.
```
print"a" /* 8 bytes */
["a /* 6 bytes; uses a literal newline */
"]
print"a",b /* 10 bytes */
[`a$b /* 8 bytes; uses a literal newline and `` strings */
`]
```
[Answer]
# Using ```` strings
In `""` strings, you will have to escape certain characters in order to use them. For example, to print the backslash, you would have to have a string like `"\\"`. There is one added byte for escaping the backslash. However, if you use ````, you do **not** have to escape this character and can save one byte.
```
print"\\" /* 9 bytes */
print`\` /* 8 bytes */
```
---
Not just that, you can encode variables and expressions inside of ```` strings using `$variableName` or `${expression}`, a feature not present in `""` strings.
We are outputting the string `"a"` concatenated with the value of the variable `b` with a trailing newline in these examples.
```
["a",b," /* 11
"] bytes */
[`a$b /* 8
`] bytes; encodes b in the string using $b */
```
[Answer]
# Use `,` instead of `and`
Conditions in Röda are streams, and can consist of multiple values. These values are reduced to one boolean value with `and`.
This means that you can replace `and` with `,` in conditions to push multiple values to the stream:
```
x if[a and b]
x if[a,b]
```
# Empty condition is truthy
It is also possible to have a condition that contains no values, which is truthy.
```
x while true
x while[]
```
[Answer]
# Write replacement lists in form `*"...;..."/";"`
The `replace` function takes normally a list of strings as arguments. However, if the list is very long, it is beneficial to simply store the regex/replacement pairs in a string and then split the string and use the star operator:
```
replace"a","b","c","d"
replace*"a;b;c;d"/";"
```
] |
[Question]
[
You are given a bunch of ASCII test-tubes, your task is to reduce number of test-tubes used.
Each test tube looks like this:
```
| |
| |
| |
|~~|
| |
| |
| |
| |
|__|
```
Obviously, `~~` is the water level. Test-tube can be also empty, in which case there are no `~~` characters inside. Single tube can contain up to 8 water level units.
You are given finite number of test tubes with different water levels inside. You have to pour the water in least amount of test-tubes possible, and output the result.
```
| | | | | | | | |~~| | |
| | | | | | | | | | | |
| | |~~| | | | | | | | |
|~~| | | | | | | | | |~~|
| | | | | | | | ------> | | | |
| | | | | | | | | | | |
| | | | |~~| | | | | | |
| | | | | | | | | | | |
|__| |__| |__| |__| |__| |__|
05 + 06 + 02 + 00 ------> 08 + 05
```
As you can see, test-tubes are separated with single space. Empty tubes should not be shown in output.
This is code golf, so code with least number of bytes wins.
Test cases: <http://pastebin.com/BC0C0uii>
Happy golfing!
[Answer]
# Pyth, ~~48~~ ~~45~~ 44 bytes
```
jCssm+_B,*9\|_X+\_*8;ld\~*9;cUs*L/%2w\~_S8 8
```
[Try it online.](https://pyth.herokuapp.com/?code=jCssm%2B_B%2C%2a9%5C%7C_X%2B%5C_%2a8%3Bld%5C%7E%2a9%3BcUs%2aL%2F%252w%5C%7E_S8+8&input=%7C++%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C++%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C++%7C+%7C%7E%7E%7C+%7C++%7C+%7C++%7C%0A%7C%7E%7E%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C++%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C++%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C++%7C+%7C++%7C+%7C%7E%7E%7C+%7C++%7C%0A%7C++%7C+%7C++%7C+%7C++%7C+%7C++%7C%0A%7C__%7C+%7C__%7C+%7C__%7C+%7C__%7C&debug=0)
Prints a single trailing space on every line.
[Answer]
## JavaScript (ES6), ~~159~~ 148 bytes
```
s=>s.replace(/~~|\n/g,c=>1/c?i++:n+=7-i,n=i=-1)&&`012345678`.replace(/./g,i=>`|${g(+i)}| `.repeat(n>>3)+`|${g(~n&7^i)}|
`,g=i=>i?i>7?`__`:` `:`~~`)
```
Outputs a trailing linefeed. Edit: Saved 11 bytes with some help from @Arnauld.
[Answer]
## Perl, 150 bytes
149 bytes of code + `-n` flag.
```
$l+=9-$.for/~~/g}if($l){$%=($v=$l/8)+($r=$l!=8);say"|~~| "x$v.($@="| | ")x$r;say$:=$@x$%for$l%8..6;say$@x$v."|~~|"x$r;say$:for 2..$l%8;say"|__| "x$%
```
I won't explain all the code, just a few things:
`$l+=9-$.for/~~/g` counts how much water the is in the input.
The second part of the code prints the output. The idea is to put as many fully filled tubes as possible, and a last one which contains the water that is left (if any). So the algorithm is in 4 parts: prints the first line of water (the top of tubes): `say"|~~| "x$v.($@="| | ")x$r`. Then, print empty parts of tubes until we reach the level of water of the last tube: `say$:=$@x$%for$l%8..6`. Then print the level where the last tube water is: `say$@x$v."|~~|"x$r`. Then, print all the remaining "empty" levels: `say$:for 2..$l%8;`. And finally, print the bottom line: `say"|__| "x$%`.
The variable names make it hard to read (`$%`, `$@`, `$:`) but allows for keywords like `x` and `for` to be written after the variable without a space.
To run it:
```
perl -nE '$l+=9-$.for/~~/g}if($l){$%=($v=$l/8)+($r=$l!=8);say"|~~| "x$v.($@="| | ")x$r;say$:=$@x$%for$l%8..6;say$@x$v."|~~|"x$r;say$:for 2..$l%8;say"|__| "x$%' <<< "| | | | | | | |
| | | | | | | |
| | |~~| | | | |
|~~| | | | | | |
| | | | | | | |
| | | | | | | |
| | | | |~~| | |
| | | | | | | |
|__| |__| |__| |__| "
```
I'm not very satisfied with how long this answer is. I tried to make the best out of my algorithm, but a different approach could probably be shorter. I'll try to work on it soon.
[Answer]
# Befunge, ~~144~~ 138 bytes
```
9>1-00p>~$~2/2%00gv
|:g00_^#%4~$~$~+*<
$< v01!-g01+*8!!\*!\g00::-1</8+7:<p01-1<9p00+1%8-1:_@#:
_ ~>g!-1+3g:"|",,," |",,:>#^_$55+,10g:#^_@
```
[Try it online!](http://befunge.tryitonline.net/#code=OT4xLTAwcD5-JH4yLzIlMDBndgogfDpnMDBfXiMlNH4kfiR-Kyo8CiQ8IHYwMSEtZzAxKyo4ISFcKiFcZzAwOjotMTwvOCs3OjxwMDEtMTw5cDAwKzElOC0xOl9AIzoKXyB-PmchLTErM2c6InwiLCwsIiB8IiwsOj4jXl8kNTUrLDEwZzojXl9A&input=fCAgfCB8ICB8IHwgIHwKfCAgfCB8ICB8IHwgIHwKfCAgfCB8ICB8IHwgIHwKfCAgfCB8ICB8IHwgIHwKfH5-fCB8fn58IHwgIHwKfCAgfCB8ICB8IHwgIHwKfCAgfCB8ICB8IHx-fnwKfCAgfCB8ICB8IHwgIHwKfF9ffCB8X198IHxfX3w)
The first two lines process the input, basically ignoring everything except the first character in each tube that might be a level marker. We take the ASCII value of that character, divide by 2 and mod 2 (giving us 1 or 0 depending on whether we're on a level marker or not), multiply that by the row number (counting down from 8, thus giving us the level value for that tube), and add it to a running total.
The output is handled on the second two lines, essentially starting on the far right of the third line. We first calculate the number of tubes by taking the total water level plus 7 divided by 8. Then when iterating over the rows of all the tubes, we calculate the character to display inside a specific tube (*t*, counting down to 0) for a given row (*r*, counting down from 8 to 0) as follows:
```
last_level = (total_water - 1)%8 + 1
level = last_level*!t + 8*!!t
char_type = !(level - r) - !r
```
The calculated *char\_type* is -1 for the bottommost row (the base of the tube), 0 for a any other area that isn't a water level, and 1 for the water level. It can thus be used as simple table lookup for the appropriate character to output (you can see this table at the start of line 4).
[Answer]
## Haskell, 186 bytes
```
import Data.Lists
z=[8,7..0]
f x|s<-sum[i*length j-i|(i,j)<-zip z$splitOn"~~"<$>lines x],s>0=unlines$(\i->(#i)=<<(min 8<$>[s,s-8..1]))<$>z|1<2=""
l#i|i==l="|~~| "|i<1="|__| "|1<2="| | "
```
Usage example:
```
*Main> putStr $ f "| | | | | | | |\n| | | | | | | |\n| | |~~| | | | |\n|~~| | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | |~~| | |\n| | | | | | | |\n|__| |__| |__| |__|"
|~~| | |
| | | |
| | | |
| | |~~|
| | | |
| | | |
| | | |
| | | |
|__| |__|
```
Puts a trailing space on every line. How it works:
```
lines x -- split the input string at newlines
splitOn"~~"<$> -- split every line on "~~"
zip z -- pair every line with its water level, i.e.
-- first line = 8, 2nd = 7 etc.
[i*length j-i|(i,j) ] -- for each such pair take the number of "~~" found
-- times the level
s<-sum -- and let s be the sum, i.e. the total amount of water
s>0 -- if there's any water at all
[s,s-8..1] -- make a list water levels starting with s
-- down to 1 in steps of 8
min 8<$> -- and set each level to 8 if its greater than 8
-- now we have the list of water levels for the output
\i->(#i)=<<( )<$>z -- for each number i from 8,7..0 map (#i) to the
-- list of output water levels and join the results
unlines -- join output lines into a single string (with newlines)
l#i -- pick a piece of tube:
-- |__| if l==0
-- |~~| if l==i
-- | | else
|1<2="" -- if there's no water in the input, return the
-- empty string
```
The main pain was the lack of a function that counts how often a substring occurs in a string. There's `count` in `Data.Text`, but importing it leads to a bunch of name conflicts that are way too expensive to resolve.
[Answer]
# Python, 261 bytes
```
i=input().split('\n')
t=0
R=range(9)[::-1]
for n in R:t+=i[n].count('~')/2*(8-n)
m=t%8
e=t/8
o=t/8+1
T='|~~| '
b='| | '
B='|__| '
n='\n'
if m:
print T*e+b
for n in R:
if n==m:print b*e+T
else:print b*o
print B*o
elif t<1:1
else:print T*e+(n+b*e)*7+(n+B)*e
```
I feel like there is something I am missing. Also, if a bunch of newlines are accptable for the blank output, I could lose some bytes. Takes input like `'| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n|__| |__| |__|'`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 139 bytes
(138 bytes of code plus one byte for the `-n`)
```
n||=0;b=gsub(/~~/){n=n+9-$.}[0,5];END{8.times{|i|puts (b*(n/8)).tr(?_,i>0??\ :?~)+(n%8>0?b.tr(?_,(8-i==n%8)??~:?\ ):"")};puts b*((n+7)/8)}
```
[Try it online!](https://tio.run/nexus/ruby#LcxLCsIwEAbgq8SqMGPaphsxpsRsdOsFVIRAkSwcpGkEaZqr1yAu/wffciGC74V1JDp6sz7YD6tophh101r98MGCSEngSJr4vlrV06Upt7f2dD6Osh7cs/NjdPEVBs/AboCERKyHHsy9dIfGmCtTJiEHWssc7X8CWTmtc4fGJJVPqIoCp/bnZAaI7zBT0zx/AQ "Ruby – TIO Nexus")
A few explanations:
>
> This program requires the `-n` switch.
>
>
> **`n`** – water counter.
>
>
> **`b`** – Template for constructing tubes; equals `"|__| "`
>
>
> **`i`** – Current line index during tube construction.
>
>
> **`gsub(/~~/){`**…**`}`** – This abuses `gsub` to simply count the water level. `gsub` actually expands to `Kernel.gsub`, which is equivalent to `$_.gsub!`. This unnecessarily manipulates the current line (`$_`); however, it allows for a more concise assignment of `b=`…`[0,5]` instead of `b=$_[0,5]`.
>
>
> **`n=n+9-$.`** – To measure the water level, the expression uses the pre-defined variable `$.`, which carries the [current input line number](http://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/variable.html#dot). This allowed me to lose the explicit loop variable.
>
>
> **`b=gsub(/~~/){`**…**`}[0,5]`** – caches the bottom of the leftmost tube as a template. (Feels a little bit like the “Elephant in Cairo” pattern to me because the bottom line wins.)
>
> Since the bottom of the tube never shows water, the `gsub` won’t replace anything when we’re there; therefore in the end, `b` always equals `"|__| "`.
>
>
> **`END{`**…**`}`** – Gets called after the whole input stream has been processed. I use this phase to construct the target tubes.
>
>
> **`i>0??\ :?~`** – is simply short-hand for `i > 0 ? " " : "~"`.
>
>
>
**Update 1:** Added details on variables, the `gsub` trickery and the `END{`…`}` phase.
**Update 2:** **(±0 bytes overall)**
* Use `n||=0` instead of `n=n||0` **(-1 byte)**
* Took malus for `-n` **(+1 byte)**
[Answer]
# Python 3, 404 bytes
This program creates the full intended output with the water levels both in ASCII and number formats.
```
w,x,y=[],[],[];a,b,s=" ------> ","~","";y=input().split("\n")
for i in [i for i in zip(*y) if "_" in i][::2]:w+=[8-i.index(b)] if b in i else [0]
u=sum(w)
while u:x+=[[8],[u]][u<8];u-=x[-1]
for i,k in enumerate(y):
s+=k+"%s"%[a," "*9][i!=4]
for j,l in enumerate(x):
c=[" ","__"][i==8];s+="|%s| "%(c,b*2)[l==8-i]
s+="\n"
s+="\n"
for i in w:s+=" %02d "%i
s+="\b"+a
for i in x:s+=" %02d "%i
print(s)
```
] |
[Question]
[
## Eh!
You know, the problem with us Canadians is that sometimes, after a long day of moose hunting and dam repairing, we forget our way back to our cabins! Wouldn't it be great if our handy laptop (which, is always at our side), had some way to point us home? Well, it's been long told that, if you display a compass on your computer, it will be the brightest when pointed North. I'd like to test this out, but I need a compact program to take with me on my next trip, because my hard drive is already filled with maple syrup recipes (and those CANNOT go). So, your task is to design me a program which, when run, saves or displays an image of the following compass rose:

The letters may be in a different font. Remember, least is best, so lowest byte count wins!
## Specifications
**Colors**
* Light purple: #9999FF
* Gray: #E5E5E5
**Lengths and Angles**

* Angle `a` = 45°
* Angle `b` = 90°
* Length `c` = 250 units
* Length `d` = 200 units
* Length `e` = 40 units
* Length `f` = 45 units
**Clarifications**
* The text may be in any ***appropriate*** font, where appropriate denotes that it is readable to the average, educated human being.
* The text must be 3 units away from the spikes at its closest point, must not touch the rose, and must be upright
* If a line is drawn from the center of the rose, through the end point of the spike and beyond, it should cross through the center of the text with a precision of +/- 2 units (the text must be centered along an axis `a`, where `a` extends from the middle of the page, through the end of the spike, and beyond)
* Each character must be at least 15 units by 15 units, and have an x/y or y/x ratio of no more than 2:1 (no stretching – readability)
* The dim circle passing through the longer spikes and text closest to the middle on the reference image is not to be drawn.
* The image must be square, and at least 400px by 400px
* A compressed image within the source is disallowed
* A unit must be at least 1 pixel
[Answer]
## HTML + CSS, 487 + 189 = 676
The compass rose is constructed from CSS borders using the [triangle technique](http://css-tricks.com/snippets/css/css-triangle/) and some basic transformations. The letters are just given fixed positions, so that turned out quite long :/
The snippet below is scaled down so that it all fits. You can check out the [JSFiddle here](http://jsfiddle.net/grc4/8nbbhmx3/1/). Also, I'm not sure how well the letters will line up on different browsers (with different fonts, default styles, etc.).
```
html{transform:scale(0.2)}body{margin:5em}hr{margin:0;float:left;border:250px solid transparent;border-right:58px solid #E5E5E5;border-bottom:58px solid #9999FF}a{position:fixed;width:616px;font-size:4em}#a{transform:rotate(90deg)}#b{transform:rotate(270deg)}#c{transform:rotate(180deg)}#d{transform:rotate(45deg)scale(.8)}#n{top:20px;left:365px}#e{top:356px;left:700px}#s{top:700px;left:370px}#w{top:356px;left:10px}#N{top:150px;left:550px}#E{top:560px;left:550px}#S{top:560px;left:140px}#W{top:150px;left:140px}
```
```
<a id=n>N</a><a id=e>E</a><a id=s>S</a><a id=w>W</a><a id=N>NE</a><a id=E>SE</a><a id=S>SW</a><a id=W>NW</a><a id=d><hr><hr id=a><hr id=b><hr id=c></a><a><hr><hr id=a><hr id=b><hr id=c></a>
```
[Answer]
# Processing 2 - 636
A quick solution that just draws all the triangles using the processing triangle method and then places the letters at their tips.
```
int s,h,m,b,n,t;void setup(){s=400;h=s/2;b=125;t=71;n=32;m=28;size(s,s);noStroke();fill(229);t(h-t,h-t,h-m,h);t(h-t,h+t,h,h+m);t(h+t,h-t,h,h-m);t(h+t,h+t,h+m,h);fill(#9999FF);t(h-t,h-t,h,h-m);t(h-t,h+t,h-m,h);t(h+t,h-t,h+m,h);t(h+t,h+t,h,h+m);t(h-b,h,h-n,h-n);t(h+b,h,h+n,h+n);t(h,h-b,h+n,h-n);t(h,h+b,h-n,h+n);fill(229);t(h-b,h,h-n,h+n);t(h+b,h,h+n,h-n);t(h,h-b,h-n,h-n);t(h,h+b,h+n,h+n);fill(color(0));text("NW",h-t-14,h-t-2);text("NE",h+t+2,h-t-2);text("SW",h-t-14,h+t+10);text("SE",h+t,h+t+10);text("N",h-5,h-b-5);text("S",h-5,h+b+12);text("E",h+b+2,h+5);text("W",h-b-14,h+5);}void t(int a,int b,int c,int d){triangle(h,h,a,b,c,d);}
```

you can get processing [here](https://www.processing.org/download/)
[Answer]
# PHP, 628 bytes
added a few linebreaks for convenience.
```
$c=$z.create;$h=$c($w=250,$w);$i=$c(530,533);$a=$z.colorallocate;$a($h,$f=255,$f,$f);$a($i,$f,$f,$f);$a($h,229,229,229);$a($h,153,153,$f);
$p=$z.filledpolygon;$p($h,$o=[0,64,0,0,141,141,],3,2);$p($h,[64,0]+$o,3,1);$p($h,$o=[0,$w,0,0,57,57],3,1);$p($h,[$w,0]+$o,3,2);
$c=$z.copy;$r=$z.rotate;$c($i,$h,263,267,0,0,$w,$w);$c($i,$r($h,90,0),263,17,0,0,$w,$w);$c($i,$r($h,180,0),13,17,0,0,$w,$w);$c($i,$r($h,270,0),13,267,0,0,$w,$w);
$s=$z.string;$s($i,5,259,0,N,3);$s($i,5,259,518,S,3);$s($i,5,0,259,W,3);$s($i,5,518,259,E,3);$s($i,5,106,108,NW,3);$s($i,5,406,108,NE,3);$s($i,5,406,410,SE,3);$s($i,5,106,410,SW,3);
imagepng($i,"n.png");
```
Run with `-r`. Creates a file `n.png` with the image; unit is 2 pixels.
I must admit I found the coords for the winds by trial & error, and they are probably a bit off. Will do the calculations soon; but I promise: they won´t change the byte count.
Had my fun for now excavating my trignonometry and struggling with `imagecopy` ... what a sissy!
on golfing: not many tricks; but these few saved a lot:
* Assigning function names and two of the values to variables probably had the largest impact.
I didn´t even count before I replaced the function names.
* The magic with the array `+` operator gave 42 bytes.
* Writing a file instead of sending the image to the browser saved 27 bytes.
* Moving assignments to the first usage of the variables gave a few more.
[](https://i.stack.imgur.com/uA9h8.png)
**breakdown**
```
// create images and allocate colors
$c=imagecreate;
$h=$c($w=250,$w); // helper image - just as large as needed or imagecopy will screw up
$i=$c(530,533); // main image
$a=imagecolorallocate;
$a($h,$f=255,$f,$f); // white is 0
$a($i,$f,$f,$f); // must be assigned to both images
$a($h,229,229,229); // grey is 1
$a($h,153,153,$f); // purple is 2
// draw the south-east quadrant
$p=imagefilledpolygon;
// small triangle purple first
$p($h,$o=[
// point 3: 0.8*e *2
0,64,
// point 1: center
0,0,
// point 2: a=45 degrees, d=200 units
141,141,// d/sqrt(2)=141.421356
],3,2);
// small triangle grey
$p($h,[64,0]+$o,3,1);
// large triangles
$p($h,$o=[
0,$w,
0,0,
57,57 // e*sqrt(2)=56.5685424949
],3,1);
$p($h,[$w,0]+$o,3,2);
// create rose
$c=imagecopy;
$r=imagerotate;
$c($i,$h,263,267,0,0,$w,$w); // copy quadrant to main image (SE)
$c($i,$r($h,90,0),263,17,0,0,$w,$w); // rotate quadrant and copy again (NE)
$c($i,$r($h,180,0),13,17,0,0,$w,$w); // rotate and copy again (NW)
$c($i,$r($h,270,0),13,267,0,0,$w,$w);// rotate and copy a last time (SW)
// add circle
#imageellipse($i,263,267,500,500,2); // grey is now 2: imagecopy shuffled colors
// add names
$s=imagestring;
$s($i,5,259, 0,N,3); // 5 is actually the largest internal font PHP provides
$s($i,5,259,518,S,3); // unassigned colors are black
$s($i,5, 0,259,W,3);
$s($i,5,518,259,E,3);
$s($i,5,106,108,NW,3);
$s($i,5,406,108,NE,3);
$s($i,5,406,410,SE,3);
$s($i,5,106,410,SW,3);
// output
#header("Content-Type:image/png");
#imagepng($i);
imagepng($i,"n.png");
```
[Answer]
# Java 8, 756 bytes
```
import java.awt.*;v->new Frame(){void t(Graphics g,String s,int x,int y){g.drawString(s,x,y);}public void paint(Graphics g){g.setFont(new Font("Hei",0,30));t(g,"N",289,80);t(g,"E",553,341);t(g,"S",290,605);t(g,"W",20,341);t(g,"NE",434,186);t(g,"SE",437,496);t(g,"SW",120,498);t(g,"NW",121,186);g.setColor(new Color(229,229,229));g.fillPolygon(new int[]{300,346,442,390,550,390,442,346,300,254,158,210,50,210,158,254},new int[]{80,240,188,284,330,376,472,420,580,420,472,376,330,284,188,240},16);g.setColor(new Color(153,153,255));g.fillPolygon(new int[]{300,158,254,244,50,300,158,210,244,300,300,442,346,356,550,300,442,390,356,300},new int[]{330,188,240,274,330,330,472,376,386,580,330,472,420,386,330,330,188,284,274,80},20);}{setSize(600,630);show();}}
```
Output:
[](https://i.stack.imgur.com/DfYg2.png)
## Explanation:
**Code explanation:**
```
import java.awt.*; // Required import for Frame, Graphics, Font, and Color
v-> // Method with empty unused parameter and Frame return-type
new Frame(){ // Create a new Frame
void t(Graphics g,String s,int x,int y){
// Create a temp method to reduce bytes:
g.drawString(s,x,y);} // To draw the given text at the given coordinate
public void paint(Graphics g){
// Overwrite the Frame's default paint method:
g.setFont(new Font("Hei",0,30));
// Set the Font to size 30
// (I've used Font "Hei" here, but "Kai" could be used as
// well for the same byte-count)
t(g,"N",289,80); // Draw the text "N"
t(g,"E",553,341); // Draw the "E"
t(g,"S",290,605); // Draw the "S"
t(g,"W",20,341); // Draw the "W"
t(g,"NE",434,186); // Draw the "NE"
t(g,"SE",437,496); // Draw the "SE"
t(g,"SW",120,498); // Draw the "SW"
t(g,"NW",121,186); // Draw the "NW"
g.setColor(new Color(229,229,229));
// Change the color to grey
// (the default color was black, which is why we started
// with the texts)
g.fillPolygon(new int[]{300,346,442,390,550,390,442,346,300,254,158,210,50,210,158,254},new int[]{80,240,188,284,330,376,472,420,580,420,472,376,330,284,188,240},16);
// Draw the 8-pointed star
g.setColor(new Color(153,153,255));
// Change the color to light purple
g.fillPolygon(new int[]{300,158,254,244,50,300,158,210,244,300,300,442,346,356,550,300,442,390,356,300},new int[]{330,188,240,274,330,330,472,376,386,580,330,472,420,386,330,330,188,284,274,80},20);}
// Draw a single shape as explained below
{ // In an inner code block:
setSize(600,630); // Set the size of the Frame
show();}} // And show the Frame
```
**Calculations:**
Although Java has ways to draw based on rotations, it would increase the byte-count substantial in comparison to this straight-forward approach. There is however one main disadvantage about using this shorter approach: I have to calculate all \$x,y\$-coordinates manually..
So, here's how I did that:
I first used the units as is, since that was easier to calculate with. I've put the center at position \$150,150\$ and started calculating from there.
*1) Calculate the coordinates of the tips of the star at N/E/S/W:*
This is not too hard. With the center at \$150,150\$ and \$\frac{\color{red}{c}}{2} = 125\$, we'll have the following points:
\$N=150,25\$
\$E=275,150\$
\$S=150,275\$
\$W=25,100\$
*2) Calculate the coordinates of the tips of the star at NE/SE/SW/NW:*
Again, we know the center is at \$150,150\$ and we also know \$\frac{\color{blue}{d}}{2}=100\$. We can make a triangle calculation with the angles being 90, 45, and 45 like this:
[](https://i.stack.imgur.com/oLMiw.png)
\$n=\frac{100}{2}\sqrt{2}=70.710\dots\$
(where \$m\$ are the sides \$b\$ and \$c\$ in the triangle above)
Knowing the \$n\$, we have the following points:
\$NE=150+m,150-m=220.710\dots,79.289\dots\$
\$SE=150+m,150+m=220.710\dots,220.710\dots\$
\$SW=150-m,150+m=79.289\dots,220.710\dots\$
\$NW=150-m,150-m=79.289\dots,79.289\dots\$
*3) Calculate the coordinates of the points between the center and the NE/SE/SW/NW tips:*
We again know the center \$150,150\$ and also \$\color{violet}{e}=40\$, so we can make a similar calculation as in step 2:
\$n=\frac{40}{2}\sqrt{2}=28.284\dots\$
And use that to calculate the points:
\$NE\_{center}=150+n,150-n=178.284\dots,121.715\dots\$
\$SE\_{center}=150+n,150+n=178.284\dots,178.284\dots\$
\$SW\_{center}=150-n,150+n=121.715\dots,178.284\dots\$
\$NW\_{center}=150-n,150-n=121.715\dots,121.715\dots\$
*4) Calculate the coordinates of the remaining points:*
Now all that's left are the points at the concaved intersection of the edges of the star, which are circled in red here:
[](https://i.stack.imgur.com/ewnyks.png)
Since we know the center \$150\$ and \$\color{lightblue}{f}=45\$, a portion of these coordinates aren't hard to calculate. The other part of the coordinates requires some calculations, though..
[](https://i.stack.imgur.com/wNaRi.png)
In the picture above, we know the following things beforehand:
* Red line: \$\frac{\color{red}{c}}{2}=125\$
* Both orange lines: \$n=\frac{40}{2}\sqrt{2}=28.284\dots\$
And what we want to calculate is the thick vertical blue line of the small purple triangle.
We start with the horizontal line of the larger green triangle:
\$o=125-n=96.715\dots\$
Using what we know now, we can calculate the black angle of the large green triangle as follows:
\$t=\sqrt{n^2+o^2-2no\times\cos(90)}=100.765\dots\$
\$A=\arccos(\frac{t^2+o^2-n^2}{2to})=16.301\dots\$
Then we can calculate the light blue angle of the small purple triangle:
\$B=90-16.301\dots=73.699\dots\$
As well as the horizontal line of the small purple triangle:
\$p=45-n=16.716\dots\$
Which we can then both use to calculate the height of the thick blue line of the small purple triangle:
\$q=p\frac{\sin(A)}{\sin(B)}=4.888\dots\$
After which we can finally calculate the final coordinates of these red dots, using the center and the points we've calculated in step 2:
[](https://i.stack.imgur.com/ewnyks.png)
\$NE\_N=178.284\dots-q,150-\color{lightblue}{f}=173.395\dots,105\$
\$NE\_E=150+\color{lightblue}{f},121.715\dots+q=195,126.604\dots\$
\$SE\_E=150+\color{lightblue}{f},178.284\dots-q=195,173.395\dots\$
\$SE\_S=178.284\dots-q,150+\color{lightblue}{f}=173.395\dots,195\$
\$SW\_S=121.715\dots+q,150+\color{lightblue}{f}=126.604\dots,195\$
\$SW\_W=150-\color{lightblue}{f},178.284\dots-q=105,173.395\dots\$
\$NW\_W=150-\color{lightblue}{f},121.715\dots+q=105,126.604\dots\$
\$NW\_N=121.715\dots+q,150-\color{lightblue}{f}=126.604\dots,105\$
---
We now have all the coordinates of the points we need, so we can draw the shape on the screen. We do this with the `Graphics#fillPolygon(int[],int[],int)`-method, which takes two integer-arrays for all \$x\$- and \$y\$-coordinates respectively, as well as an integer being the amount of points. The grey star is therefore drawn using the following \$x,y\$-coordinates:
\$[[150,25],[173,105],[221,79],[195,127],\$
\$[275,150],[195,173],[221,221],[173,195],\$
\$[150,275],[127,195],[79,221],[105,173],\$
\$[25,150],[105,127],[79,79],[127,105]]\$:
[](https://i.stack.imgur.com/vLeBEm.png)
We then draw a single shape for the light purple parts, and the following \$x,y\$-coordinates:
\$[[150,150],[79,79],[127,105],[122,122],[25,150],\$
\$[150,150],[79,221],[105,173],[122,178],[150,275],\$
\$[150,150],[221,221],[173,195],[178,178],[275,150],\$
\$[150,150],[221,79],[195,127],[178,122],[150,25]]\$:
A quarter of this shape goes from the center to point \$NW\$; then to point \$NW\_N\$; then \$NW\_{center}\$; then \$W\$; and then back to the center again:
[](https://i.stack.imgur.com/qKtqz.png)
And the entire shape is drawn by continuing in a similar fashion.
---
After that I've doubled everything, because the challenge description states the square should be at least 400 by 400 pixels, and in addition all \$y\$-coordinates are increased by \$30\$, because we draw directly on the frame and we still have the Window-bar at the top to consider (outside codegolf you would add a Panel to the Frame, and draw on that, but drawing directly on the Frame is also possible and -in this case- 1 byte shorter ¯\\_(ツ)\_/¯).
And finally we add the text, for which no calculations are used. In the used Font the letters aren't monospace (W is for example larger than S), and in Java everything is drawn from the top-left \$x,y\$-coordinate, so we can't really make any smart calculations here tbh. I've just added some temporary red lines going beyond the points and manually adjusted the text positions a bit:
[](https://i.stack.imgur.com/PPRU5.png)
If you think they aren't correct, they can be moved slightly by adjusting the coordinates, without changing the byte-count.
For those curious, here are the adjustments made to the coordinates of the tips to position the texts:
\$N=300-11, 80\$
\$E=550+3,330+11\$
\$S=275+15,580+25\$
\$W=50-30,330+11\$
\$NE=441-7,188-2\$
\$SE=441-4,471+25\$
\$SW=158-38,471+27\$
\$NW=158-37,188-2\$
And well, that's it. Thank you for listening to my TED talk about drawing a compass in Java. :)
[Answer]
## R, ~~877~~ ~~850~~ 813
Lot's of room to golf this I suspect, but I wanted to get something up to see if I managed to comply with the rules.
Edit: Lost a few cleaning up around the polygon creation, gained a few removing outlines
```
a=45;b=90;c=125;e=40;h=c(0,0,b,a,a,0,a,b)*pi/180;i=c(0,c,c,100,e,a,(2*a^2)^.5,a);x=i*sin(h);y=i*cos(h);q=x[6:7];r=x[7:8];s=x[2:3];t=x[c(5,5)];u=y[6:7];v=y[7:8];w=y[2:3];z=y[c(5,5)];m=(s-t);n=(w-z);o=(q-r);p=(u-v);i=((q*v-u*r)*m-o*(s*z-w*t))/(o*n-p*m);x=c(x,i)[c(1,2,5,1,3,5,5,4,10,5,4,9)];y=c(y,rev(i))[c(1,2,5,1,3,5,5,4,10,5,4,9)];png("1.png",400,400);par(mar=rep(0,4));a=c(-200:200);plot(a,a,type="n");for(b in 0:3){for(i in(0:3)*3+1){a=c(1,1,1,-1,-1,-1,-1,1);polygon(x[(i):(i+3)]*a[b*2+1],y[(i):(i+3)]*a[b*2+2],border=NA,col=c("#9999FF","#E5E5E5")[(i%%6%/%4+b%%2)%%2+1]);}};for(i in 1:4){a=c("N","NE","E","SE","S","SW","W","NW");b=a[i*2-1];c=a[i*2];o=c(1,1,-1,-1,1);n=o[i+1];m=o[i];e=c(5,2)[i%%2+1];text((x[e]+(11*abs(i%%2-1)))*m,(y[e]+(12*i%%2))*n,b,cex=1.8);text((x[8]+10)*m,(y[8]+12)*n,c,cex=1.8)};dev.off()
```
This produces the following png image

A bit of an explanation of what I'm doing
```
a=45;
b=90;
c=125;
e=40;
h=c(0,0,b,a,a,0,a,b)*pi/180; # angles to known vertices in one quadrant
i=c(0,c,c,100,e,a,(2*a^2)^.5,a); # distances to known vertices
x=i*sin(h); # calculate x ordinates
y=i*cos(h); # calculate y ordinates
q=x[6:7]; #-----------------------
r=x[7:8]; #
s=x[2:3]; # Get the lines required
t=x[c(5,5)]; # to determine the vertex
u=y[6:7]; # for the minor pointers
v=y[7:8]; #
w=y[2:3]; #
z=y[c(5,5)]; #------------------------
m=(s-t); # Intersect them
n=(w-z); # to give coordinate.
o=(q-r); # Just calculate the x's
p=(u-v); # as they can be reversed
i=((q*v-u*r)*m-o*(s*z-w*t))/(o*n-p*m); #------------------------
x=c(x,i)[c(1,2,5,1,3,5,5,4,10,5,4,9)]; # X Triangle groups
y=c(y,rev(i))[c(1,2,5,1,3,5,5,4,10,5,4,9)]; # Y Triangle groups
png("1.png",400,400); # Set output to png
par(mar=rep(0,4)); # Make margins 0
a=c(-200:200);
plot(a,a,type="n"); # Start plot
for(b in 0:3){for(i in(0:3)*3+1){ # draw polygons, alternating colors and drawing all quadrants
a=c(1,1,1,-1,-1,-1,-1,1);
polygon(x[(i):(i+3)]*a[b*2+1],y[(i):(i+3)]*a[b*2+2],border=NA,col=c("#9999FF","#E5E5E5")[(i%%6%/%4+b%%2)%%2+1]);
}};
for(i in 1:4){ # Add text to compass points for each quadrant
a=c("N","NE","E","SE","S","SW","W","NW");b=a[i*2-1];c=a[i*2];
o=c(1,1,-1,-1,1);n=o[i+1];m=o[i];
e=c(5,2)[i%%2+1];
text((x[e]+(11*abs(i%%2-1)))*m,(y[e]+(12*i%%2))*n,b,cex=1.8);
text((x[8]+10)*m,(y[8]+12)*n,c,cex=1.8)
};
dev.off() # Close PNG
```
[Answer]
# Mathematica, 347 bytes
```
p=q={{0,0},{0,125},40{1/Sqrt[2],1/Sqrt[2]}};q[[3,1]]*=-1;m=5p[[3]]/2;s=u={{0,0},m,{32,0}};u[[3]]={0,32};r={{0,1},{-1,0}};t=Polygon[#]&;z=MatrixPower[r,#]&;a[v_]:=Table[t[z[n].#&/@v],{n,4}];i=Table[Text[#[[j]],z[j].#2],{j,4}]&;G=RGBColor["#E5E5E5"];Graphics[{i[{E,S,W,N},{0,130}],i[{NE,SE,SW,NW},1.06m],G,a[u],RGBColor["#9999FF"],a[s],a[p],G,a[q]}]
```
Pregolfed:
```
p = q = {{0, 0}, {0, 125}, 40 {1/Sqrt[2], 1/Sqrt[2]}}; (*defining points*)
q[[3, 1]] *= -1; (*for triangles*)
m = 5 p[[3]]/2;
s = u = {{0, 0}, m, {32, 0}};
u[[3]] = {0, 32};
r = {{0, 1}, {-1, 0}}; (*-pi/2 rotation matrix*)
t = Polygon[#] &;
z = MatrixPower[r, #] &;
a[v_] := Table[t[z[n].# & /@ v], {n, 4}]; (*rotate the sets of points*)
(*four times*)
i = Table[Text[#[[j]], z[j].#2], {j, 4}] &;
G = RGBColor["#E5E5E5"]; (*need to use this twice*)
(*so triangles overlap*)
(*properly so define a variable*)
Graphics[{i[{E, S, W, N}, {0, 130}],
i[{NE, SE, SW, NW}, 1.06 m], G, a[u], RGBColor["#9999FF"], a[s],
a[p], G, a[q]}]
```
`N` and `E` (base of the natural log) are both built-ins in Mathematica but as text E gets stylized into a lowercase font you see in the image but the problem doesn't *quite* say we can only use one font for all the text. If that is a requirement then replace `E` with `"E"` and I gain two bytes.
`Sqrt[2]` in Mathematica can be stylized into two characters, so if we count each `Sqrt[2]` as two characters then my new byte count is 339 instead of 349.
The image below is produced.
[](https://i.stack.imgur.com/RAjhY.png)
] |
[Question]
[
Your job is write a program that prints all times (in the format HH:MM, 24 hours) that follow any of the following patterns:
* Hours equal to minutes, e.g. 22:22,01:01
* Hours equal to reverse minutes, e.g. 10:01, 01:10, 22:22
* Sequences, that match H:MM, or HH:MM, always printed with HH:MM. E.g. 00:12, 01:23, 23:45, 03:45, etc (always a single step between digits)
Rules:
* You may choose any language you like
* You cannot print repeated times
* One time per line, following the order of the day
* The winner will be chosen in February 5.
PS: this is my first question, it might have some inconsistencies. Feel free to edit.
PS2: Here is the expected 44 solutions (already presented by Josh and primo, Thanks!)
```
00:00
00:12
01:01
01:10
01:23
02:02
02:20
02:34
03:03
03:30
03:45
04:04
04:40
04:56
05:05
05:50
06:06
07:07
08:08
09:09
10:01
10:10
11:11
12:12
12:21
12:34
13:13
13:31
14:14
14:41
15:15
15:51
16:16
17:17
18:18
19:19
20:02
20:20
21:12
21:21
22:22
23:23
23:32
23:45
```
[Answer]
**Golfscript (~~82~~ 72)**
Still very much a beginner, but there was no GS answer, so... :)
```
24,{'0'\+-2>..+\.-1%+}%5,{'0'7,{+}/>4<.(;0\+}%|{2=54<},$);{2/~':'\++}%n*
```
[Answer]
## PHP - 93 bytes
```
<?for(;24>$h;)@ereg(+$h=&date(i,$i).$m=date(s,$i++),"0123456$h$h".strrev($h))&&print"$h:$m
";
```
This will find patterns like `02:34`, but will not find patterns like `00:23` or `00:02`. If i understand the OP's clarifications in the comments, this is correct.
Prints a total of 44 results:
```
00:00
00:12
01:01
01:10
01:23
02:02
02:20
02:34
03:03
03:30
03:45
04:04
04:40
04:56
05:05
05:50
06:06
07:07
08:08
09:09
10:01
10:10
11:11
12:12
12:21
12:34
13:13
13:31
14:14
14:41
15:15
15:51
16:16
17:17
18:18
19:19
20:02
20:20
21:12
21:21
22:22
23:23
23:32
23:45
```
[Answer]
## C, 118 (initially 136)
```
h,m;main(){h<24&&main(m>57?m=0,h++:h==m|h==m%10*10+m/10|m-12==h*11|h==m-22&!(~-m++%11)&&printf("%02d:%02d\n",h,m-1));}
```
An iterative version with 119 characters:
```
h;main(m){for(;h<24;h++)for(m=0;m<57;m++)h==m|h==m%10*10+m/10|m-12==h*11|h==m-22&!(~-m%11)&&printf("%02d:%02d\n",h,m);}
```
A big thanks to @squeamish ossifrage !
[Answer]
**Python (178)**
```
s=sorted
for i in[x for x in['%04d'%i for i in range(2400)if i/10%10<6]if s(x[:2])==s(x[2:])or len({i-ord(y)for i,y in enumerate(x.lstrip('0'))})==1]:print'%2s:%2s'%(i[:2],i[2:])
```
Stripping all leading zeroes before sequences gives 57 results in total.
[Answer]
## APL (90)
```
F←{,'ZI2'⎕FMT⍵}⋄↑⊃¨{(F⍺),':',F⍵}/¨Z/⍨{(⍺=⍵)∨(≡/0 1⌽∘F¨⍺⍵)∨∧/¯1=2-/⍎¨(⍕⍺),F⍵}/¨Z←,1-⍨⍳24 60
```
[Answer]
# Javascript - 171 chars (5/2/14) !
```
for(h='00';+h<24;h=(++h<10?'0':'')+h)for(m='00';+m<60;m=(++m<10?'0':'')+m)if(h[1]+h[0]==m||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)
```
I seriously am getting the hang of golfing. If I look back from now, I have cut down almost 30 chars ! [JSBin](http://jsbin.com/EkEbodI/10/edit).
## Ungolfed (and commented) :
```
// Note: +'string' is same as 'parseInt(string, 10)'
// Also, this code is not the shortest one, I have purposely made this code longer for
// understanding purposes
for(h = '0'; +h < 24; h = +h + 1 + '') //initialize h(our), loop while it's less than 24
{ // increase it by 1 and cast back to string
for(m = '0'; +m < 60; m= +m + 1 + '') // intialize m(inute), loop while < 60
{ // increase it by 1 and cast back to string
if(h.length < 2) h = 0 + h; // if it is '9', convert to '09'
if(m.length < 2) m = 0 + m; // if it is '9', convert to '09'
// Tests for printing
if(h[0] === m[1] && m[0] === h[1] ||
h === m ||
+m[1] - +m[0] === 1 && +m[0] - +h[1] === 1 && (+h[0] === 0 || +h[1] -+ h[0] === 1))
console.log(h + ':' + m); // print
} // inner loop end
} // outer loop end
```
### 187 chars (Old) (4/2/14)
```
for(h='00';+h<24;h=(+h<9?'0':'')+(+h+1))for(m='00';+m<60;m=(+m<9?'0':'')+(+m+1))if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)
```
Little bit of experimenting, and lot improvement (9 chars) :) [JSBin](http://jsbin.com/EkEbodI/9/edit?js,console)
### 196 chars (Old) (3/2/14)
```
for(h='00';+h<24;h=(+h<9?'0':'')+(+h+1))for(m='00';+m<60;m=(+m<9?'0':'')+(+m+1))if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-m[0]==1&&+m[0]-h[1]==1&&(!+h[0]||+h[1]-h[0]==1))console.log(h+':'+m)
```
Sat down with a fresh mind and improved it a lot, a one liner :) [JSBin](http://jsbin.com/EkEbodI/4/edit).
### 208 chars (Old) (2/2/14)
```
for(h='0';+h<24;h=+h+1+''){for(m='0';+m<60;m=+m+1+''){if(h.length<2)h=0+h
if(m.length<2)m=0+m
if(h[0]==m[1]&&m[0]==h[1]||h==m||+m[1]-+m[0]==1&&+m[0]-+h[1]==1&&(+h[0]==0||+h[1]-+h[0]==1))console.log(h+':'+m)}}
```
---
Gives exactly the 44 required times (each in new line)
Will keep improving my code.
I would highly appreciate any feedback. Thank you.
[Answer]
# Python 3, 248 characters
Guess I'm a little late and not very good as well, but finally, got my first codegolf thing to share:
I decided to only support real sequences like 01:23 and 23:45, not 00:12. Anyway, I bet theres plenty to do better, so please go ahead and share a comment with me.
```
import itertools as t
s=sorted
r=range
i=int
d='%02d'
e=d+':'+d
print([e%(i(a[0]),i(a[1])) for a in t.product([d% x for x in r(0,24)], [d% x for x in r(0,60)]) if s(a[0])==s(a[1]) or list(a[0]+a[1])==[str(x) for x in r(i(a[0][0]),i(a[1][-1])+1)]])
```
Got the very descriptive version along with it on my [pastebin](http://pastebin.com/embed_iframe.php?i=eBBrnPCF)
[Answer]
# Delphi
Still working on it but this is what i have so far.
It works, but im sure its possible to get it shorter.
**Edit:** Prints 48 times.
## Without indent 422 characters
```
uses System.SysUtils,DateUtils;var t:TTime;a,b,c,d:integer;s:string;begin t:=StrToTime('00:01');while t<StrToTime('23:59')do begin s:=FormatDateTime('hhnn',t);a:=StrToInt(s[1]);b:=StrToInt(s[2]);c:=StrToInt(s[3]);d:=StrToInt(s[4]);if((a+1=b)and(b+1=c)and(c+1=d))or((a=0)and(b+1=c)and(c+1=d))or((a=0)and(b=0)and(c+1=d))or((a=d)and(b=c))or((a=c)and(b=d))then WriteLn(FormatDateTime('hh:nn',t));t:=IncMinute(t)end;ReadLn;end.
```
## With indent 557characters
```
uses
System.SysUtils, DateUtils;
var
t:TTime;
a,b,c,d:integer;
s:string;
begin
t:=StrToTime('00:01');
while t<StrToTime('23:59')do
begin
s:=FormatDateTime('hhnn',t);
a:=StrToInt(s[1]);
b:=StrToInt(s[2]);
c:=StrToInt(s[3]);
d:=StrToInt(s[4]);
if((a+1=b) and (b+1=c) and (c+1=d)) or
((a=0) and (b+1=c) and (c+1=d)) or
((a=0) and (b=0) and (c+1=d)) or
((a=d) and (b=c)) or ((a=c) and (b=d)) then
WriteLn(FormatDateTime('hh:nn',t));
t:=IncMinute(t)
end;
ReadLn;
end.
```
[Answer]
# q (116)
```
distinct{t:string 00:00+x;$[(t[0 1]in(t[3 4];t[4 3]))|all 1=1_deltas{"I"$x}each t[0 1 3 4];t;"00:00"]}each til 1440
```
Increments 00:00 to 23:59, casts to string, then check (test 1 or 2) or 3
Output:
```
("00:00";"01:01";"01:10";"01:23";"02:02";"02:20";"03:03";"03:30";"04:04";"04:40";"05:05";"05:50";"06:06";"07:07";"08:08";"09:09";"10:01";"10:10";"11:11";"12:12";"12:21";"12:34";"13:13";"13:31";"14:14";"14:41";"15:15";"15:51";"16:16";"17:17";"18:18";"19:19";"20:02";"20:20";"21:12";"21:21";"22:22";"23:23";"23:32";"23:45")
```
[Answer]
# PHP - 56 39 31 bytes
```
<? http_redirect("goo.gl/W2M5mo")?>
```
It doesn't bend the rules in any way. You need the pecl\_http module installed and short\_open\_tag set to "1" in php.ini.
] |
[Question]
[
What general tips do you have for golfing in AWK? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to AWK. Please post one tip per answer.
[Answer]
These are not in any particular order, and some of them might even apply to other languages too, but not to a lot of them I think.
* You can sometimes use awk's simple string concatenation to assemble numbers
`z=x*10+y` and `a=b*10`
become
`z=x y` and `a=b 0`
* You can use the ~ operator (match pattern on the right side) to compare numbers or strings if you know that the two parts meet certain conditions
for instance if you know that `a` will always be smaller than or equal to `b`, you can replace
`a==b`
with
`a~b`
or if you want to check for an empty string `s` (which means that s isn't allowed to be `"0"` either), and you haven's changed the variable `X` before, so that it is still undefined, you could use
`X~s`
instead of
`s==""`
if you want to check if i is an integer you can use
`i!~/\./` (`i` doesn't contain a dot)
instead of
`i==int(i)`
* You can swap two numbers in a single command
`t=a;a=b;b=t`
becomes
`a+=b-(b=a)`
saving one character
* If you don't need them as input anymore, you can use the input variables $1, $2, $3, ... as an array. So instead of writing a[n] you can just write $n. Sometimes even while reading the input from these you can use the already handled ones as a stack for something.
* You can make good use of the built-in separators FS (space, if not changed by you) and RS (newline) when concatenating strings
`a=$1" "$2`
becomes
`a=$1FS$2`
or even better
`a=$1"\n"$2`
becomes
`a=$1RS$2`
* If there is no input and you use the BEGIN block, you can try to use the END block instead. Depending on the judge it works. If you test it, you have to press `Ctrl-D` (end of input) to access the `END` block.
* If you want to skip the first line, you can use
`C++`
instead of
`NR>1`
if you won't be using `C` anywhere in your program.
[Answer]
## Techniques
* Thanks to [Peter Taylor](https://codegolf.stackexchange.com/questions/13014/tips-for-golfing-in-awk/24410#24410) for pointing out the [language-generic version of this question](https://codegolf.stackexchange.com/questions/5285/tips-for-golfing-in-all-languages/) for which I did not bother to search. I'll try to limit this answer to things that are not available in other C-like languages.
* The frequently accessed builtin variables are 2 characters long. Find the break-even point for assigning to a temp variable. `a=$1;` is five characters, so it breaks even after five uses of `$1`;
* Remember that the default action for a matching pattern is `print $0`, so if you get what you want printed into `$0`, just use
```
1
```
* Getting creative with operator ordering can save you some parentheses or extra statements
```
for(i=1;i<=NF;i++)print$i;
```
vs
```
for(;i<NF;)print$++i;
```
## Examples
* A solution to [Do We Sink or Swim?](https://codegolf.stackexchange.com/questions/23259/do-we-sink-or-swim) in 70 characters:
```
n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}
```
* A solution to [The Floating Horde](https://codegolf.stackexchange.com/questions/23631/the-floating-horde) in 44 characters:
```
{for(i=NF;i>1;){n=int($i/2);$i%=2;$--i+=n}}1
```
## Summary
awk will probably never outgolf APL, Golfscript, J, or K, but you can quite consistently beat other high level languages.
[Answer]
To read and process a number on each line:
```
{
n=$1;
print(n*n);
// OR printf("%d\n",n*n);
}
```
Compressed form (Length = 14):
```
{print($1*$1)} // thanks due to @manatwork
```
Shorter Code (Length = 7)
```
1,$0^=2 // thanks due to @llhuii
```
When compiled and run in `gawk` with inputs:
```
1
2
3
```
Output:
```
1
4
9
```
[Answer]
# Truthy and falsey values
Boolean evaluation is somehow flexible in AWK, and this is awesome. Remember: AWK's basis is `pattern{action}`; when `pattern` is true, it executes `action`.
Besides doing their business, some built-in functions return values, e.g., `split()`, `gsub()`. They are also useful as a `pattern` when manipulating the input.
## Examples of truthy and falsey variables
I tried to come up with valuable examples of how to exploit truthy/falsey variables. This is non-exhaustive. Anyone is encouraged to share more examples, and I would add them to this list.
[Try it online!](https://tio.run/##ZZLPjpwwDMbveQqLvbQadhZm227/qFIPVaU@Q9VDAANRIaGJmWFazbNPnQAzQUUKB8ef8/Nny9Ov6zVxZJVuHEiLQHak9pz8HThEkF8AHpbYJ4jzZHeSZ7dcpYBTiQNBbSxQi6DHrlvShXjMpm/PmGdLzcMlKqnHvkDroFJ1jRb5uramhz9oTYQjxCp@DkC17Byy2qfhzBNCHyFL4ZHPjk82@R9/@/2e@QYsZ74kS1I4tapsQbF2xcygWN54s2lam9PSkieFzItKo0tJqPlUQEwaNwyvJBylVbLokEOKL7QhkM6pRmP1OuVyY6hxREteoMgXYS6RrMa/vURtxm6ukO82RhSeKqTFj2@eFUJ@/vI0PS36l3gKFdZKe5LghtFNdwY6D9ycxQYnz@pIatrD1@2cJHBFGCQRWi3u1d9v6HxO5QflgXpJ7Lx3VOlhJCHKHwmho@Tnov3A2kg86kDHLIqwB1PzuK3klfPt3sW73bqyWWzdzQv2B4@yG8PICuRF8AClxZ6b@Y8hz2eIaAlSuCUB/h65PuSr7nAXHjady45aMzZzv@VMHjYKJ@XIpSG@lADsAszNquv1u3foHw "AWK – Try It Online")
```
"strings are truthy"{print 1} # truthy; strings are always truthy, except for the null string
-0xF3e10{print 2} # truthy; numbers different from zero are truthy
0{print 3} # falsey; zeroes are false: 0, -0, +0, 0x0, 0000... expect for "0", which is a string
0 b{print 4} # truthy; now the number 0 is concatenated to a null string (a variable still not assigned), thus converting it to "0"
""{print 5} # falsey; null string
b{print 6} # falsey; b is null (a variable not assigned)
a=@/x/{print 7} # truthy; defining a strongly typed regex constant. Different from a /x/ pattern
/x/{print 8} # falsey; /x/ does not match the input
c["test"]{print 9} # falsey; undefined item of array, null
c["test"]++{print 10} # falsey; variable is evaluated before increment
c["test"]{print 11} # truthy; now, c["test"] equals 1
c["test2"]{print 12} # falsey; although the c array now exists, the "test2" element does not
```
Result:
```
1
2
4
7
11
```
[Answer]
one of the great things about `awk`'s sigils `$` is that string concat can be even more condensed than having to use the built-ins as buffer zones - say, u wanna prepend a zero to the full row:
>
>
> ```
> _=0
> $_=_$_
>
> ```
>
>
```
jot -c 8 75 | gawk '$_=+_$_'
0K
0L
0M
0N
0O
0P
0Q
0R
```
and you wanna make patterns out of it ?
```
jot -c 8 75 | gawk '$_=_++$_' # integers
0K
L 1
M 2
N 3
O 4
P 5
Q 6
R 7
jot -c 8 75 | gawk '$_=_++$++_' # even numbers
K 0
L 2
M 4
N 6
O 8
P 10
Q 12
R 14
jot -c 8 75 | gawk '$_=++_$++_' # odd numbers
K 1
L 3
M 5
N 7
O 9
P 11
Q 13
R 15
```
And honestly, what language can repeat stings THIS easily :
```
jot 20 | mawk 'NF=OFS=$_'
1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111
121212121212121212121212
13131313131313131313131313
1414141414141414141414141414
151515151515151515151515151515
16161616161616161616161616161616
1717171717171717171717171717171717
181818181818181818181818181818181818
19191919191919191919191919191919191919
2020202020202020202020202020202020202020
```
or can decode arbitrary precision hex with this few keystrokes :
```
echo 0xEDCFAB12EDCFAB127659438976594389EDCFAB |
```
>
>
> ```
> gawk -nM '$_=+$_'
>
> ```
>
>
```
5303367068685265828195859270035065456131166123
```
] |
[Question]
[
## Background
[Page 219 of *A New Kind of Science*](https://www.wolframscience.com/nks/p219--systems-based-on-constraints/) (a book by Stephen Wolfram, the creator of Mathematica) shows an interesting 2D pattern generated by constraints. The relevant section in the book starts at [page 210](https://www.wolframscience.com/nks/p210--systems-based-on-constraints/); you can browse other pages for more context.

In short, the large binary image is the result generated by 12 **constraints** at the bottom, along with an extra condition that two black cells stacked vertically must appear somewhere on the grid. The constraints describe that, for every cell in the (infinite) pattern, the cell itself combined with its four neighbors must match one of the constraints given. The book describes this pattern as "the simplest system based on constraints that is forced to exhibit a non-repetitive pattern". An interesting fact is that the sequence of antidiagonals describes the binary pattern of all integers (including positive and negative).
## Task
The task is to replicate a finite region at the center of this infinite pattern. For this task, the **center** of this pattern is defined to be the endpoint of the semi-infinite antidiagonal of black cells (which does not include the part of the upper-right stripes).
The input is a positive odd number \$n\$. You may choose to take the value of \$\left\lfloor \frac{n}{2}\right\rfloor\$ (0-based integers) or \$\left\lceil \frac{n}{2}\right\rceil\$ (1-based) instead.
The output is the square region of \$n \times n\$ cells centered at the center cell defined above. See test cases below for exact output. The output format is flexible; you may choose any two distinct values (numbers or chars) for black and white cells respectively, and any structure that exhibits the 2D grid is acceptable (e.g. nested arrays or strings delimited by newlines).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
Uses `X` for black and `.` for white cells. Note that your program should (at least theoretically) give the correct pattern for arbitrarily large \$n\$.
```
n = 1
X
n = 3
.XX
.X.
X..
n = 7
.XXXXXX
.X.....
...XXXX
.X.X...
..X..XX
.X...X.
X......
n = 15
.XXXXXXXXXXXXXX
.X.............
...XXXXXXXXXXXX
.X.X...........
..X..XXXXXXXXXX
.X...X.........
.......XXXXXXXX
.X...X.X.......
..X...X..XXXXXX
...X.X...X.....
X...X......XXXX
.X.X.....X.X...
..X.......X..XX
.X.......X...X.
X..............
n = 25
X........................
..XXXXXXXXXXXXXXXXXXXXXXX
..X......................
....XXXXXXXXXXXXXXXXXXXXX
..X.X....................
...X..XXXXXXXXXXXXXXXXXXX
X.X...X..................
.X......XXXXXXXXXXXXXXXXX
X.....X.X................
.......X..XXXXXXXXXXXXXXX
X.....X...X..............
.X..........XXXXXXXXXXXXX
..X...X...X.X............
...X...X...X..XXXXXXXXXXX
X...X...X.X...X..........
.X...X...X......XXXXXXXXX
..X...X.X.....X.X........
...X...X.......X..XXXXXXX
X...X.X.......X...X......
.X...X..............XXXXX
..X.X.........X...X.X....
...X...........X...X..XXX
X.X.............X.X...X..
.X...............X......X
X...............X.....X.X
```
[Answer]
# Python 3 with numpy, ~~90~~ ~~87~~ ~~86~~ 84 bytes
```
from numpy import*
lambda n:2*((4<<(a:=(y:=c_[1-n:n])-y.T)//4)+a%4-2&a-2*y)-1<<a<y%2
```
Takes \$\left\lceil \frac{n}{2}\right\rceil\$.
-3 by removing `x`. -1 with a shorter expression for \$-x - y\$. -2 with a shorter combining method.
## How it works
Broadcasting is used in several places to produce the table.
### The bottom-left section
Change coordinates to \$a = -x + y\$ and \$b = -x - y\$, as shown here (\$a\$ blue, \$b\$ yellow):
[](https://i.stack.imgur.com/3m1zG.png)
This part is handled by the subexpression `(4<<(a:=(y:=c_[1-n:n])-y.T)//4)+a%4-2&a-2*y`. (`y.T` produces \$x\$.)
Looking at the lines of constant nonnegative even \$a\$, their squares are black when certain bits of \$b\$ are zero, specifically (1x, 10x, 11x, 100x, 111x, 1000x, 1111x, ...) -- the low bit does not matter as it is always 0 in \$b\$ here. These values are produced by taking a power of 2 and adding 0 or -2; then bitwise-ANDing with \$b\$ yields 0 for black squares and nonzero values for white squares.
The lines of constant nonnegative odd \$a\$ are all white. To get this to work, since the low bit of \$b\$ is 1 here, we just need to make sure the low bit of the value ANDed with \$b\$ is 1.
### The top-right section
Here, a square is black iff \$y\$ is odd, thus black iff `y%2` is 1.
### Combining the sections
Doubling the first part and subtracting 1 from it makes it negative for black squares and positive for white squares in the bottom-left section. In numpy arrays, shifting by a negative number produces zero, so `<<a` makes it zero in the top-right section while preserving its sign in the bottom-left section. Finally, it is less than `y%2` iff it is negative (for a black square in the bottom-left section) or it is 0 and `y%2` is 1 (for a black square in the top-right section).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
NθG↖→→↓↓θ¶XFθ«P↖⭆…⊕⁻ιθ⁻θι§ X¬&κ⁻X²⊕÷鲬﹪ι²←←
```
[Try it online!](https://tio.run/##ZY9Ba8JAEIXP9VcsOU1gPWhv8WTxEmhElIKHXtLsGIeuM3HdTVpKf/t202IrdC6PN8z7eNMca9dIbWMsuQt@HU4v6OCcLyYbse@tMBRP3SMevFbFltrjra5k4F85a5U98z5LyYM4lRDqY3JXBeupc8T@j7PzybdV3cG25hah5MbhCdmjgYo4XIASLs@1@nGJTKNb@pINvkGm9plWa/HwQH6gCy7ZwOv1eiNDemCu1S22ZL@ingyO6Hk@0sZ8JSZYue6@Z5E6S49QjF3/uc8YZ/dx2tsv "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the 1-indexed distance from the centre. Explanation: Diagonal bit-twiddling shamelessly stolen from @m90's answer, because I can't work out what @Bubbler means regarding the antidiagonals.
```
Nθ
```
Input `⌈n/2⌉`.
```
G↖→→↓↓θ¶X
```
Draw alternate rows of `X`s in the upper right triangle, leaving the cursor at the bottom right of the final diagram.
```
Fθ«
```
Loop through each diagonal of the lower right triangle.
```
P↖⭆…⊕⁻ιθ⁻θι§ X¬&κ⁻X²⊕÷鲬﹪ι²
```
Output `X`s where the distance from the centre antidiagonal does not have the given bits.
```
←←
```
Move to the next diagonal.
] |
[Question]
[
My phone number (which I will not be sharing here) has a neat property where there is a two digit number, which when iteratively removed from my phone number will eventually remove all the digits. For example if my phone number were
```
abaababbab
```
Then by repeatedly removing `ab` we would eventually get nothing (I encluse the string I am removing in brackets to make it clear)
```
abaababb[ab]
abaab[ab]b
aba[ab]b
ab[ab]
[ab]
```
Now to generalize this property lets have any string. A "minimal eraser" of that string will be the smallest substring such that if iteratively removed it will eventually make the string empty.
Some examples at the bottom.
# Task and Scoring
*Warning: This challenge is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Do not assume it is without reading the scoring*
Your challenge will be to take a string as input and output a minimal eraser of that string.
Your answers will be scored by taking them as a string of bytes and calculating that string's minimal eraser. The length in bytes of that eraser is your score, with lower being better.
Your answer must support strings containing all printable ascii plus any characters that appear in your program.
# Test cases
```
abaababbab -> ab
baababbab -> baababbab
baababab -> baababab
echoecho -> echo
ototoo -> oto
ibiibibii -> ibi
aabaabaa -> abaa / aaba
```
[Answer]
# [Python 3](https://docs.python.org/3/), score ~~... 48~~ ~~29~~ 20
```
+1,eval(bytes([57]))
```
A completely different approach from the last 2 versions (and also result in manageable generated program). Check out the revision history for some (possibly) interesting ideas.
---
Given an arbitrary Python program:
```
print(1)
```
it can be transformed, without changing the behavior:
```
exec("print(1)")
```
```
eval(rb'exec("print(1)")')
```
```
eval(bytes([101, 120, 101, 99, 40, 34, 112, 114, 105, 110, 116, 40, 49, 41]))
```
The number list is getting long, so I'll use a shorter list for demonstration. Note that only printable ASCII characters can appear in the string representation and the first character is `e`, so the first number is 101 and all numbers are at least 32.
```
eval(bytes([101, 32, 32]))
```
Rewrite the first number to `57+1+1+1+...+1+1+1`, the rest into `9+1+1+...+1`; then add some `,9` at the end of the list. This is always possible because of the conditions mentioned before, and the program's behavior is unchanged because **the byte `9` is `\t`, a whitespace character**.
```
eval(bytes([57+1+1+...+1, 9+1+1+...+1+1, 9+1+1+...+1, 9, 9,..., 9]))
```
The number of `,9` added must satisfy that **the total number of `9`s is equal to the number of `+1`**.
Then replace all the `9` with `eval(bytes([57])`, and prepend `+1,`.
```
+1,eval(bytes([57+1+1+...+1,eval(bytes([57])+1+1+...+1+1,eval(bytes([57])+1+1+...+1,eval(bytes([57]),eval(bytes([57]),...,eval(bytes([57])]))
```
Done! It's easy to see that this string has the eraser string `+1,eval(bytes([57])`.
---
It's trivial to see that there exists a Python snippet that solves the given problem.
```
g=lambda s, e: not s or any(
s[i:].startswith(e) and g(s[:i]+s[i+len(e):], e)
for i in range(len(s)-len(e)+1))
f=lambda s: min((s[i:j] for j in range(len(s)+1) for i in range(j) if g(s, s[i:j])), key=len)
print(f(input()))
```
[Try it online!](https://tio.run/##XVHBboMwDD3XX2FxaSxop2k3pO5HEIewhmIGASWpNr6e2WWttgoHy89@ec8wL6mb/Nu6Xk6DHZuzxVigK9FPCSNOAa1fDOxixWV9jMmGFL84dcaRdM54MbEquc6lnw/OC1zWwifYtcJlZI/B@osz2ox02GbyVyJoH4IljuyNUY2@RiX2z0Rh4NONPSG3aqDAjUlU4KdbTsIg2O/3MAf2ybSG/XxNhkSTx3kKstgSQc7RfbPgOruC3h7TtW0LDC5eh6RK1cDeHeM8yFyGh3fMNhsKaz/LMrCNlWgkdMA28K9@FL/wX1RA99FNehTUDFOS51ZKBm5YQl4KSAa7qdlNSvILag1iRP5O4NnQZlcdRkN1Cbv7Z7htR/f1CGD9AQ "Python 3 – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes, score 23
Rather boring, as it doesn't have a non-trivial eraser.
```
{|~c₃↺↔At.l>0∧Akc↰}ᶠlᵒh
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7qmLvlRU/Ojtl2P2qY4lujl2Bk86ljumJ38qG1D7cNtC3Iebp2U8f@/UmJiEhgp/Y8CAA "Brachylog – Try It Online") or [verify the other test cases](https://tio.run/##SypKTM6ozMlPN/r/v7q6pi75UVPzo7Zdj9qmOJbo5dgZPOpY7pid/KhtQ@3DbQtyHm6dlFH7cOuE/6oK0UqZSZlABCSUYv9HKyUmJQJREhAp6ShhssHM1OSMfBAGMvNLgDAfqDMKAA "Brachylog – Try It Online") (split in two, so TIO doesn't time out.)
### How it works
```
{|~c₃↺↔At.l>0∧Akc↰}ᶠlᵒh
{ }ᶠ Find all outputs for the implicit input, that …
| either is itself or …
~c₃ split into three groups in every possible way
[,,AAABBB],[,AA,AABB],[AAA,B,BB],[AA,AB,BB] etc. …
↺↔ with the middle moved to the back [AA,BB,AB] …
A assign to A
t. the tail AB is the output of this predicate
l>0 and its length is greater than 0.
∧Ak Also, [AA,BB] …
c concatenated AABB …
↰ used in a recursive call
has the same output as this predicate: AB.
lᵒh Order all possible erasers by length, take first
```
[Answer]
# Javascript, 228 bytes, score 228
Naive solution I guess:
```
(r,d)=>{w=0;l=r.length;for(var i=0;i!=-1&&i<l;){i=r.indexOf(d,i);w=w||((i<0)?0:t(r.substr(0,i)+r.substr((i++)+d.length,l),d))}return !r?1:w}
f=a=>{n=a.length;for(p=1;p<=n;p++)for(i=0;i<=n-p;i++)if(t(a,b=a.substr(i,p)))return b}
```
[Try it online!](https://tio.run/##bY/dcoMgEIXv8xQmFxkYf6K3QZJH6DOAYrKNBQZJbCfx2e3aaibaDgsze/g4e3gXN9EUDqyPGwulch9GX9RX73lPXFRSfri3PGU1d0mt9MmfWWUcuQkXAMqw5nG23UJeM3oHZECX6vOtImUElLW8fTwIgTylx3TviUuaq2y8Iynehs@OQBjSsBz9o5riWNo55a9OB2t3zPZtt6q4wCiai9cYlmfM5lwziw6D8JMJhdiywRQq4omIJL4aZ0FkKaWjt@xWfWF0Y2qV1OZEKrIRUmBJrA2lQbDbBfEhEHK1wObUiD3F/@kJntF/YVWczbBn8CAsQeNxTdgEorTkQAIWHq9ZsV9y4vfvYjZ4EPpv)
] |
[Question]
[
[The Onion](https://www.theonion.com/) (warning: many articles are NSFW) is a satirical news organization that parodies traditional news media. In 2014, The Onion launched [ClickHole](https://www.clickhole.com) (warning: also frequently NSFW), a satirical news website that parodies "clickbait" sites like BuzzFeed. Thanks to [Poe's Law](https://en.wikipedia.org/wiki/Poe%27s_law), it's fairly common for people to read the headlines of articles from The Onion or ClickHole and believe them to be true, not knowing that they are intended to be satire. The converse also happens with ridiculous-sounding real news stories - people often think that they are satire when they are not.
This confusion naturally lends itself to a game - given a news headline, try to guess whether or not it is satire. This challenge is about doing exactly that with a program.
Given a news headline (a string consisting of only printable ASCII characters and spaces), output `1` if the headline is satire, or `0` if it is not. Your score will be the number of correct outputs divided by the total number of headlines.
As per usual, [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/45941) (especially [optimizing for the test cases](https://codegolf.meta.stackexchange.com/a/2507/45941)) are not allowed. To enforce this, I will run your programs on a set of 200 hidden test cases (100 from The Onion, 100 from Not The Onion). Your solution must score no more than 20 percentage points less than your score on the public test cases in order to be valid.
## Test Cases
To come up with test cases for this challenge, I picked 25 headlines from [The Onion subreddit](https://reddit.com/r/theonion) (where articles from The Onion and its child sites, like ClickHole, are posted), and 25 headlines from [the Not The Onion subreddit](https://reddit.com/r/nottheonion) (where real news articles that sound like satire are posted). The only changes I made to the headlines were replacing "fancy" quotes with regular ASCII quotes and standardizing capitalization - everything else is left unchanged from the original article's headline. Each headline is on its own line.
**The Onion headlines**
```
Trump Warns Removing Confederate Statues Could Be Slippery Slope To Eliminating Racism Entirely
'No Way To Prevent This,' Says Only Nation Where This Regularly Happens
My Doctor Told Me I Should Vaccinate My Children, But Then Someone Much Louder Than My Doctor Told Me I Shouldn't
Man At Park Who Set Up Table Full Of Water Cups Has No Idea How Passing Marathon Runners Got Impression They Can Take Them
This Child Would Have Turned 6 Today If His Mother Hadn't Given Birth To Him In October
Incredible Realism: The Campaign In The Next 'Call Of Duty' Will Begin At Your Avatar's High School Cafeteria When He's Being Tricked Into Joining The Military By A Recruiter
'Sometimes Things Have To Get Worse Before They Get Better,' Says Man Who Accidentally Turned Shower Knob Wrong Way
Report: Uttering Phrase 'Easy Does It' Prevents 78% Of Drywall Damage While Moving Furniture
Barbara Bush Passes Away Surrounded By Loved Ones, Jeb
Family Has Way Too Many Daughters For Them Not To Have Been Trying For Son
News: Privacy Win! Facebook Is Adding A 'Protect My Data' Button That Does Nothing But Feels Good To Press
Dalai Lama Announces Next Life To Be His Last Before Retirement
Researchers Find Decline In Facebook Use Could Be Directly Linked To Desire To Be Happy, Fully Functioning Person
Manager Of Combination Taco Bell/KFC Secretly Considers It Mostly A Taco Bell
Trump: 'It's My Honor To Deliver The First-Ever State Of The Union'
Daring To Dream: Jeff Bezos Is Standing Outside A Guitar Center Gazing Longingly At A $200 Billion Guitar
Area Dad Looking To Get Average Phone Call With Adult Son Down To 47.5 Seconds
Experts Warn Beef Could Act As Gateway Meat To Human Flesh
Jeff Bezos Named Amazon Employee Of The Month
Dad Suggests Arriving At Airport 14 Hours Early
Report: Only 3% Of Conversations Actually Need To Happen
Delta Pilot Refuses To Land Until Gun Control Legislation Passed
Family Wishes Dad Could Find Healthier Way To Express Emotions Than Bursting Into Full-Blown Musical Number
New Honda Commercial Openly Says Your Kids Will Die In A Car Crash If You Buy A Different Brand
Teacher Frustrated No One In Beginner Yoga Class Can Focus Chakras Into Energy Blast
```
**Not The Onion headlines**
```
Man Rescued From Taliban Didn't Believe Donald Trump Was President
Nat Geo Hires Jeff Goldblum To Walk Around, Being Professionally Fascinated By Things
Mike Pence Once Ratted Out His Fraternity Brothers For Having A Keg
Reddit CEO Tells User, "We Are Not The Thought Police," Then Suspends That User
Trump Dedicates Golf Trophy To Hurricane Victims
Uber's Search For A Female CEO Has Been Narrowed Down To 3 Men
ICE Director: ICE Can't Be Compared To Nazis Since We're Just Following Orders
Passenger Turned Away From Two Flights After Wearing 10 Layers Of Clothing To Avoid Luggage Fee
Somali Militant Group Al-Shabaab Announces Ban On Single-Use Plastic Bags
UPS Loses Family's $846k Inheritance, Offers To Refund $32 Shipping Fee
Teen Suspended From High School After Her Anti-Bullying Video Hurts Principal's Feelings
Alabama Lawmaker: We Shouldn't Arm Teachers Because Most Are Women
Cat Named After Notorious B.I.G. Shot Multiple Times - And Survives
EPA Head Says He Needs To Fly First Class Because People Are Mean To Him In Coach
Apology After Japanese Train Departs 20 Seconds Early
Justin Bieber Banned From China In Order To 'Purify' Nation
Alcohol Level In Air At Fraternity Party Registers On Breathalyzer
NPR Tweets The Declaration Of Independence, And People Freak Out About A 'Revolution'
Man Who Mowed Lawn With Tornado Behind Him Says He 'Was Keeping An Eye On It.'
After Eating Chipotle For 500 Days, An Ohio Man Says He's Ready For Something New
'El Chapo' Promises Not To Kill Any Jurors From Upcoming Federal Trial
After 4th DWI, Man Argues Legal Limit Discriminates Against Alcoholics
Palestinian Judge Bans Divorce During Ramadan Because 'People Make Hasty Decisions When They're Hungry'
Argentinian Officers Fired After Claiming Mice Ate Half A Ton Of Missing Marijuana
'Nobody Kill Anybody': Murder-Free Weekend Urged In Baltimore
```
[Answer]
# JavaScript (ES7), 39 / 50 (78%)
63.5% (127/200) on hidden test cases
A simple heuristic based on the length of the title, number of spaces and use of the `-ly` suffix.
```
isOnion = str =>
str.length ** 0.25 +
str.split(' ').length ** 1.25 * 2 +
str.split(/ly\b/).length ** 1.75 * 7
> 76
```
[Try it online!](https://tio.run/##hVhdcxo7En3Pr@h15dbEie0437ecSrYGAzY2GMrgUFubfRAzgtG1RqIkDb7kz2dP94Dju1W7@xACM5L66/Q5Lf@hNioWwazTsfOl/vnTxLEz3tEXiinQl6/PiL@cWO1WqaKXL@n05O0HerV7HNfWpBcZZYdPVrzhFS/p7X@sem233xev/7rwEy/8hGVf6dPHn2NY/efBLDT1muYquEi3uvYb41Z07t1SlzqopGmaVGp0xLPGltTBA2vWax22@OLXmmaeetbUxqnEW29VYWJNPZdM0HZ7cHSQ3Xicv@WFk6A32iWaVSYeZTRV20hjZ7d0g81Iw7zSQctb@LJqrAp4d6lgzkWcNNpS1xfJB5wFX0aaBjStxK9vqijYBU1YdF4ZWwbtjqjTsDHtaOpr7R3eNkVFQ98gOLxQjv77mS5LbBNr8kQTFe7hnqepTnS3pplaWE39xloaLxFewnnnzTrC20gIeFBqRZf@ARtj5LyMFLJZIcbbxjkdIl34RIN6HTTe4zG8hOMwNlP3nAJdw7hkQqKhuYR5qTZ42QSnS/oIj0vkdbCkSywb@YTsYQU7ThcGiaaOCag9En9paho4GiPQhQ44eeCKoEvDQdxqZVGyMzYKD@q1MivHq/n3jf4zUXau2ji7TdpmNDf41dErI5n5h28C5RuVVMgQvllVNC0q7y3OWmrkxSiuq6NLjfcdzcmYBVPcI4SBS56uvHHyEOZGBthVwFZnSzk8K0JjkjiccQWTqYFEZMWt4i4Xni5QkbkPUePwpRf8IJX8tKMTNu@BxpXkCuZASgkUIqbtPpeo@AOSd@38gubBwxsgFlZv9dqHdEZ3fBA7OamCgqWspyIDB94MUrbHdaRPv/8meQrbB05ZV9VqpWHVIM@jtrf6sGhSEzSO76iwAC4A01gJUnBe/oCaTpsQfONKuIZMDP0GX8ZOxyO60gts7KvaSGvEXWt5Dg8eqWZVJYZXnxENFAGMSRDA2epo1GEWtuIHFky9w2E3@iGeIQazUcUW1XV/o74q9ML7exrAobLk9Tllk@CTLpL0DOqdcXslwa5KbTJgjIsjfdfX2jLMfblr/cg93FVWGRoiMZQ7hxgL3sYoG5ql1BMUw3geqpj2Fb3VzCY1Uiw1iVqFopIojSupqwtr0NuA7KPfdyjSI2N1sblIyNfQOIYdjHR1NOHRHBhmeyTdvMWnK5iMpNqwISlCclHIwLU99/VCyI4DVwUfYO3r6/45qAE9xWZAnxEQCwwOlD3ys/zXYm5sZt0zygCeyOm89E4YCH5ZdK6UDsGFmI57/JNJWLN1fn7HkpFJLgWTvC1ohQ6@0sslTPzwkQuHTU5KN24S@wMfLhpuLzpHJnHqhfrBr4fAO/5nJxPWPH97egrmsJYjbDfAVg4LqHqJ1f5@Z5V7LId7jPFJxfQqRDE3IJ28bGxigAEYD45Xv/908oFz5F3JQOj9CRFJUaSHgbnc1SsHwHLgBgFzJ4y0avHb1OjfvtWxwuYngd6oGiXNa/UDtnr12vqtfkzVyLtUSabQ481qpSMs5gFQF0jDkgnc4fTmPWrQoGI91pwnnS/y9O63tvIOwUYpfWQ/G6GQG91CqtUpNqZtUjQxFp13q5cNdzXeD1EN1C4Zi6w6Pi0FsOQQRBptiyehgPJXf89NrLCZvW@TI3i/BGGjzVDAnawildxdiN63vomydRCOSLKwLIP7uGO5FqMmmkJZumnqVgxAAIzAUjG4ax0Kg7djBAMXhDqF469NGVvu7xppthzlBpZAiBWLEBbBJiO9a5ZLCDmEvhMQNONdK25Y6ocGIwpKW7JIjtumFSmBJuKEFVywSIIoYd8XDcufuoeJNooelq2gDliTDv71@dmzm3aKYW4HLxQNDu4HX6PZrFngYdeIHKLtDCgaWHQKadwPPVFoSdSA0wCkXWgWSzxse@kCM8HCNjVnea7sPbDDtHy00zEQ4rLVb0FCH8OdDCHC2q1MMXkYKPpEg@kQMT5uVeIl6Eohuj7ngzUBcQUR8Za9wdgt717rlQASPJzovDemGUgkMsWFI/p@MEdjg8qE5ytWP88aQBNvTaGPvh/sBqAmoqBlbMma9@5pCJxTAg9JM1lb9E3w62rb9hw6pVCo0jcDTqw5mDtABpw1FQoWP3Mwfa0gcOwaK5KozI2Cgj0gzH37v0Mrc3cMzns7QvbhjPgXai0lYvStVWi76QbcBDOGEzbXGQK8AnRg0ALDQmqBGRYHStM4ZuedmIuCtih4APAtRhLu@iVT3ly3nPnmFP245VRzY9udbMFuvvEGJAeuYFaDhsECRg/AaTecANUXAMGacns8rdRCqcUTJesAc2PHfq@sPmYVmjBWTYE3Aoa7yRQUypTQ9jhy@fz39x@htA6V5/NRNDi1ZN/gDxMIev75u7cYUjB4i3SLVzP9q6x72D8dv9qAL/EvB@kcd1jdePc34F1qmxj@SLBZKws3WK93iM0t4oJCD9VDjXEUdQLIHqdiwA2pbTuaq10oUJzonABxjkGNC30OnO3IWTwBQH0wHi3dORmcXJzwgZBHyIRZAz0zme2O4SxTddhABkUmJjkTXtkS0aUWupXM9LnjWCJ3lLF3ZKI9n8euQDzck/H33MNnDm/trQeNtH5dqTUgjo2zoDDSdjUwiNS8Pd2L1aMmMAINT9UaTcCldvu8Y0Z3SibsIDcLj2GpCWaJabm92khSC18J4W@0Ff40gSXoSf/jloHPW1YEGeKApA50N1XKbn@0VD25Baq1TlGanUcfvliweADIAyBB4CAg4kzuktHHKffCOPnC8ydlt3rjbZN2o8R@OB5Jz6LurpXxmQ9OlTy3VCI9SOS@EBnz57XWAskc2rtlfsPIc8IHtrnttZdCpGftE/sBvviA8aKLM9hBGldGRtf9qRnf/FS53Y2nGPmlMaFQfAfoWZaDteeJ29cmthMnp/uadSnHBHzVBM8EylW5WxdYJQ3Dl1nL9w5lH517j/i688GR2M/Dim@5UGOsG@I@i4nW8F1dbrY8l6@ADoZ4W0ZTtNyDgQQhGpxw1ZRgDKACgm02PoC4uk1o78S1KlmRdwjNdlUZ8VUPjImao5AminbLXYmvMMx5l41bha3kM6ygUq0lsAOoXcbf8NheaAIjwY7wDrjik8HmmDtbbIzM40XU/NFgnm2v5guPZO@zxz@yM/Qko/gYoGHu1feaBxfYL0WtMXyYGlO56C9G7S90@vnZ@ASDeg/t9SLSl6@0@7vGi3hIfyd//@oVnRF6KXqrT9B6L7J@Phj2urRkDcjoFcXDw88Q8/9xyv/ZDgNsB6c8@8vKaQFX20Xw9RW@vJYfL8b7P428opv998PDn/8G "JavaScript (Node.js) – Try It Online")
[Answer]
## Python 3, 84%
Untested on hidden test cases.
This uses Keras LSTM RNN trained on various headlines. To run it you need Keras the following and the model which I've made available on GitHub: [repo link](https://github.com/vihanb/OnionNotOnion). You will need the model `.h5` and the word/vector mappings are in `.pkl`. The latest
The dependencies are:
```
import numpy as np
from pickle import load
from keras.preprocessing import sequence, text
from keras.models import Sequential
from keras.layers import Dense, Embedding, SpatialDropout1D, LSTM, Dropout
from keras.regularizers import l2
import re
```
The settings are:
```
max_headline_length = 70
word_count = 20740
```
The model is:
```
model = Sequential()
model.add(Embedding(word_count, 32, input_length=max_headline_length))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(64, kernel_regularizer=l2(0.005), dropout=0.3, recurrent_dropout=0.3))
model.add(Dropout(0.5))
model.add(Dense(32, kernel_regularizer=l2(0.005)))
model.add(Dropout(0.5))
model.add(Dense(2, kernel_regularizer=l2(0.001), activation='softmax'))
```
Now to load the model and the word embeddings:
```
model.load_weights('model.h5')
word_to_index = load(open('words.pkl', 'rb'))
```
And the code to test if a string is from 'NotTheOnion' or 'TheOnion' I've written a quick helper function which converts the string to the respective word embeddings:
```
def get_words(string):
words = []
for word in re.finditer("[a-z]+|[\"'.;/!?]", string.lower()):
words.append(word.group(0))
return words
def words_to_indexes(words):
return [word_to_index.get(word, 0) for word in words]
def format_input(word_indexes):
return sequence.pad_sequences([word_indexes], maxlen=max_headline_length)[0]
def get_type(string):
words = words_to_indexes(get_words(string))
result = model.predict(np.array([format_input(words)]))[0]
if result[0] > result[1]:
site = 'NotTheOnion'
else:
site = 'TheOnion'
return site
```
### Explanation
This code runs a model which analyzes the relationships between words by representing the words as a 'vector'. You can learn more about word embedding [here](https://en.wikipedia.org/wiki/Word_embedding).
This is trained on headlines but the test cases *are excluded*.
This processes is automated after a quite a bit of processing. I've distributed the final processed word list as a `.pkl` but what happens in word embedding is first we analyze the sentence and isolate the words.
After we now have the words the next step is to be able to understand the differences and similarities between certain words e.g. `king` and `queen` versus `duke` and `duchess`. These embeddings don't happen between the actual words but between numbers representing the words which is what is stored in the `.pkl` file. Words that the machine doesn't understand are mapped to a special word `<UNK>` which allows us to understand that there is a word there but that it is not known exactly what the meaning is.
Now that the words are able to be understood, the sequence of words (headline) needs to be able to be analyzed. This is what 'LSTM' does, an LTSM is a type of 'RNN' cell which avoids the vanishing gradient effect. More simply, it takes in a sequence of words and it allows us to find relationships between them.
Now the final layer is `Dense` which basically means it's kind of like an array meaning the output is like: `[probability_is_not_onion, probability_is_onion]`. By finding which one is larger we can choose which one is the most confident result for the given headline.
[Answer]
# Python 3 + Keras, 41/50 = 82%
83% (166/200) on hidden test cases
```
import json
import keras
import numpy
import re
from keras import backend as K
STRIP_PUNCTUATION = re.compile(r"[^a-z0-9 ]+")
class AttentionWeightedAverage(keras.engine.Layer):
def __init__(self, return_attention=False, **kwargs):
self.init = keras.initializers.get("uniform")
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self).__init__(**kwargs)
def build(self, input_shape):
self.input_spec = [keras.engine.InputSpec(ndim=3)]
assert len(input_shape) == 3
self.W = self.add_weight(shape=(input_shape[2], 1),
name="{}_W".format(self.name),
initializer=self.init)
self.trainable_weights = [self.W]
super(AttentionWeightedAverage, self).build(input_shape)
def call(self, x, mask=None):
logits = K.dot(x, self.W)
x_shape = K.shape(x)
logits = K.reshape(logits, (x_shape[0], x_shape[1]))
ai = K.exp(logits - K.max(logits, axis=-1, keepdims=True))
if mask is not None:
mask = K.cast(mask, K.floatx())
ai = ai * mask
att_weights = ai / (K.sum(ai, axis=1, keepdims=True) + K.epsilon())
weighted_input = x * K.expand_dims(att_weights)
result = K.sum(weighted_input, axis=1)
if self.return_attention:
return [result, att_weights]
return result
def get_output_shape_for(self, input_shape):
return self.compute_output_shape(input_shape)
def compute_output_shape(self, input_shape):
output_len = input_shape[2]
if self.return_attention:
return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
return (input_shape[0], output_len)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
if __name__ == "__main__":
model = keras.models.load_model("combined.h5", custom_objects={"AttentionWeightedAverage": AttentionWeightedAverage})
with open("vocabulary.json", "r") as fh:
vocab = json.load(fh)
while True:
try:
headline = input()
except EOFError:
break
tokens = STRIP_PUNCTUATION.sub("", headline.lower()).split()
inp = numpy.zeros((1, 45))
for i, token in enumerate(tokens):
try:
inp[0,i] = vocab[token]
except KeyError:
inp[0,i] = 1
print(model.predict(inp)[0][0] > 0.3)
```
`combined.h5` and `vocabulary.json` can be retrieved from [here (very large)](https://drive.google.com/open?id=1uyV2EhCgWJnoXonag_3ofxCSQBWTDVzW) and [here](https://drive.google.com/open?id=1ySWiRi4unGfw5tdkOGLYZmoNWL2wY7yh).
Fully-connected classifier connected to a pre-trained sentiment analysis model DeepMoji, which consists of stacked bi-directional LSTMs and an attentional mechanism. I froze the DeepMoji layers and took out the final softmax layer, trained just the fully connected layers, then unfroze the DeepMoji layers and trained them together for finetuning. The attentional mechanism is taken from <https://github.com/bfelbo/DeepMoji/blob/master/deepmoji/attlayer.py> (I didn't want to have to use all their code as a dependency for one class, especially since it's Python 2 and rather unwieldy to use as a module...)
This performs surprisingly poorly on Mego's test set, considering that on my own larger validation set it gets >90%. So I'm not done with this yet.
[Answer]
# JavaScript ([Node.js](https://nodejs.org/)), 98% (49/50)
96% (192/200) on hidden test cases
```
const words = require('./words');
const bags = require('./bags');
let W = s => s.replace(/[^A-Za-z0-9 ]/g, '').toLowerCase().split(' ').filter(w => w.length > 3);
let M = b => {
for (let i = 0; i < bags.length; i++) {
let f = true;
for (let j = 0; j < bags[i].length; j++) if (!b.includes(bags[i][j])) {
f = false;
break;
}
if (f) return true;
}
return false;
};
let O = s => {
let b = [];
W(s).forEach(w => {
let p = words.indexOf(w);
if (p >= 0) b.push(p);
});
return (b.length > 0 && M(b));
};
```
This requires two large JSON files which I can't put them here or on "TiO". Please download them from the following links and save them with the `words.json` and `bags.json` names, in the same folder as JS file. There is also a link for a JS file with test cases and result/percent printing. You can put your hidden test cases in `onions` and `nonOnions` variables.
* [words.json](https://ghostbin.com/paste/4bzan/download)
* [bags.json](https://ghostbin.com/paste/pjcsq/download)
* [onion.js](https://ghostbin.com/paste/bbeng/download) (this includes default test cases)
After saving all 3 files in same directory, run `node onion.js`.
The `O` function will return `true` if it is onion and `false` if it isn't. Uses a big list of word bags (without order) to detect if the input string is onion. Kind of hard coded, but works very well on a variety of random test cases.
[Answer]
Working off Arnauld's solution
**JavaScript (ES6), 41 / 50**
64% (128/200) on hidden test cases
```
str.includes("Dad") || str.length ** .25 +
str.split(' ').length ** 1.25 * 2 +
str.split(/ly\b/).length ** 1.75 * 7
> 76
```
**JavaScript (ES6), 42 / 50**
62.5% (125/200) on hidden test cases (invalid)
```
isOnion = str =>
str.includes("Dad") || str.length ** .25 +
str.split(' ').length ** 1.25 * 2 +
str.split(' ').filter(w => w.length > 3 && w.split(/ly/).length > 1).length * 23.54 +
/\d/.test(str) * 8
> 76
```
The length+word count+"ly " concept works pretty well, I was able to squeeze a few more points out by checking for the word "Dad" (when do real articles talk about people's dads in the third person in the title?) and an additional point by changing the "ly " search heuristic and checking for the presence of numbers in the title (which might be less valid in the general case outside the test, so I left both solutions)
] |
[Question]
[
# Definition
An "integer triangle" is one with integer coordinates. For example the following triangle is an integer triangle:
```
(0, 0), (0, 1), (1, 2) with perimeter 1 + sqrt(2) + sqrt(5) ≈ 4.650.
```
# Task
The goal of this challenge is to count all integer triangles (up to congruence) with perimeter less than n.
# Input and Output
The argument will be given as an integer, and the output should be the number of triangles with perimeter strictly less than the argument.
# Examples
The smallest integer triangle by perimeter is congruent to
```
(0, 0), (0, 1), (1, 0) which has perimeter 2 + sqrt(2) ≈ 3.414
```
The next smallest are:
```
(0, 0), (0, 1), (1, 2) with perimeter 1 + sqrt(2) + sqrt(5) ≈ 4.650,
(0, 0), (0, 2), (1, 1) with perimeter 2 + 2sqrt(2) ≈ 4.828,
(0, 0), (0, 2), (1, 0) with perimeter 3 + sqrt(5) ≈ 5.236, and
(0, 0), (1, 2), (2, 1) with perimeter sqrt(2) + 2sqrt(5) ≈ 5.886
```
Test cases:
```
a(1) = 0
a(2) = 0
a(3) = 0
a(4) = 1
a(5) = 3
a(6) = 5
a(7) = 11
a(8) = 18
a(9) = 29
a(10) = 44
a(12) = 94
a(20) = 738
a(30) = 3756
a(40) = 11875
```
I have coordinates for each of the triangles in [this Gist](https://gist.github.com/peterkagey/5bac5bf4a7fd2c70ad668854e6a847b8).
# Warnings
Notice that two non-congruent triangles can have the same perimeter:
```
(0, 0), (0, 3), (3, 0) and (0, 0), (0, 1), (3, 4) both have perimeter 6 + 3sqrt(2).
```
Also keep in mind that the inequality is *strict*; the 3-4-5 pythagorean triangle should be counted by a(13), not a(12).
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")—the shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ ~~27~~ ~~25~~ 23 bytes
```
pḶŒcÆḊÐfḅı;I$€AṢ€QS€<¹S
```
[Try it online!](https://tio.run/##y0rNyan8/7/g4Y5tRyclH257uKPr8IS0hztaj2y09lR51LTG8eHORUAqMBhI2BzaGfzf0CDI2tDo0Najew63A8Xc/wMA "Jelly – Try It Online")
### How it works
```
pḶŒcÆḊÐfḅı;I$€AṢ€QS€<¹S Main link. Argument: n
Ḷ Unlength; yield [0,...,n-1].
p Take the Cartesian product of [1,...,n] and [0,...,n-1].
Œc Take all combinations of the resulting pairs.
The result are of the form [[a, b], [c, d]].
ÆḊÐf Filter by determinant; keep only pairs of pairs for which
the determinant (ad - bc) is non-zero, i.e., those such
that [0, 0], [a, b], and [c, d] are not collinear.
ḅı Convert each pair [a, b] from base i (imaginary unit) to
integer, mapping it to ai + b.
€ For each pair of complex numbers [p, q]:
;I$ append their forward differences, yielding [p, q, p-q].
A Take the absolute value of each resulting complex number.
Ṣ€ Sort each resulting array of side lengths.
Q Unique; remove duplicates.
S€ Take the sum of each array, computing the perimeters.
<¹ Compare them with n.
S Take the sum of the resulting Booleans.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (invert `SP¬+÷/E$` by using `SẠ>÷/E$` and use `ÇÐf` rather than `ÇÐḟ`)
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (no need to flatten prior to the sort)
-2 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (`S<¥Ðf³L` -> `S€<³S`)
-1 stealing a trick from an earlier revision of [Dennis's answer](https://codegolf.stackexchange.com/a/153152/53748) (`ṗ2’Œc` -> `p`⁺’` - more redundant cases but golfier!)
```
SẠ>÷/E$
p`⁺’ÇÐfµ_/ṭ⁸²S€Ṣµ€Q½S€<³S
```
A full program taking an integer and printing the result.
**[Try it online!](https://tio.run/##y0rNyan8/z/44a4Fdoe367uqcBUkPGrc9ahh5uH2wxPSDm2N13@4c@2jxh2HNgU/alrzcOeiQ1uBdOChvSCuzaHNwf///zc0AgA "Jelly – Try It Online")** (too slow to complete test cases 20+ in under 60s)
### How?
```
SẠ>÷/E$ - Link 1, straightLineFromOrigin?: coordinates i.e. [[a,b],[c,d]]
S - sum [a+c,b+d]
Ạ - all? (0 if either of a+c or b+d are 0 otherwise 1) all([a+c,b+d])
$ - last two links as a monad:
÷/ - reduce by division [a÷c,b÷d]
E - all equal? (i.e. 1 if on a non-axial straight line) a÷c==b÷d
> - greater than? (i.e. 1 if not on any line, 0 otherwise) all([a+c,b+d])>(a÷c==b÷d)
p`⁺’ÇÐḟµ_/ṭ⁸²S€Ṣµ€Q½S€<³S - Main link: integer, n
p` - Cartesian product of implicit range(n) with itself
⁺ - repeat (Cartesian product of that result with itself)
’ - decrement (vectorises)
- - i.e. all non-negative lattice point pairs up to x,y=n-1
Ðf - filter keep only if:
Ç - call last link (1) as a monad
µ µ€ - monadic chain for €ach:
_/ - reduce with subtraction i.e. [a-c,b-d]
⁸ - chain's left argument, [[a,b],[c,d]]
ṭ - tack [[a,b],[c,d],[c-a,d-b]]
² - square (vectorises) [[a²,b²],[c²,d²],[(c-a)²,(d-b)²]]
S€ - sum €ach [[a²+b²],[c²+d²],[(c-a)²+(d-b)²]]
- - i.e. the squares of the triangle's edge lengths
Ṣ - sort
Q - de-duplicate (get one of each congruent set of triangles)
½ - square root (vectorises) - get sides from squares of sides
S€ - sum €ach
³ - program's 3rd argument, n
< - less than?
S - sum (number of such triangles)
- implicit print
```
[Answer]
# JavaScript (ES7), 157 bytes
```
f=(n,i=n**4,o={})=>i--&&([p,P,q,Q]=[0,1,2,3].map(k=>i/n**k%n|0),!o[k=[a=(H=Math.hypot)(p,P),b=H(p-q,P-Q),c=H(q,Q)].sort()]&a+b+c<n&&(o[k]=P*q!=p*Q))+f(n,i,o)
```
### Test cases
Only small values can be computed with the default stack size of most JS engines.
```
f=(n,i=n**4,o={})=>i--&&([p,P,q,Q]=[0,1,2,3].map(k=>i/n**k%n|0),!o[k=[a=(H=Math.hypot)(p,P),b=H(p-q,P-Q),c=H(q,Q)].sort()]&a+b+c<n&&(o[k]=P*q!=p*Q))+f(n,i,o)
;[
1, // 0
2, // 0
3, // 0
4, // 1
5, // 3
6, // 5
7, // 11
8, // 18
9 // 29
]
.forEach(n => console.log('a(' + n + ') = ' + f(n)))
```
---
# Non-recursive version, 165 bytes
```
n=>[...Array(n**4)].reduce((x,_,i,o)=>x+=!o[[p,P,q,Q]=[0,1,2,3].map(k=>i/n**k%n|0),k=[a=(H=Math.hypot)(p,P),b=H(p-q,P-Q),c=H(q,Q)].sort()]&(o[k]=P*q!=p*Q)&a+b+c<n,0)
```
### Test cases
This version also works for **a(30)** and **a(40)**, but that would take too much time for the snippet.
```
let f =
n=>[...Array(n**4)].reduce((x,_,i,o)=>x+=!o[[p,P,q,Q]=[0,1,2,3].map(k=>i/n**k%n|0),k=[a=(H=Math.hypot)(p,P),b=H(p-q,P-Q),c=H(q,Q)].sort()]&(o[k]=P*q!=p*Q)&a+b+c<n,0)
;[
1, // 0
2, // 0
3, // 0
4, // 1
5, // 3
6, // 5
7, // 11
8, // 18
9, // 29
10, // 44
12, // 94
20 // 738
]
.forEach(n => console.log('a(' + n + ') = ' + f(n)))
```
[Answer]
# [Julia 0.6](http://julialang.org/), 135 bytes
Iterate over possible non-origin points to make up the triangle, represent them as complex numbers, sort the square lengths and keep them in a set to check for congruence. Avoids colinear points by checking that the angle between their complex numbers is nonzero. Then it returns the length of the set. It's shorter to use the lengths directly, but you get the wrong answer for `a(40)`. The solution is too slow to reach run `a(40)` because of a deprecation warning, so I have a link to a faster version as well.
```
n->(q=Set();for x=0:n,y=1:n,a=1:n,b=0:n
r=x+y*im
t=a+b*im
g=sort(abs2.([r,t,r-t]))
sum(√g)<n&&angle(r/t)>0&&push!(q,g)
end;length(q))
```
[Try it online!](https://tio.run/##HY4xEoIwEEX7nAIbZleCgoWFGC5hyVAkQww4sEASZuAGnsHjeREEmzf/v@q9praR11UKpU1DK8U5jOKhPWD27G0wi@RGfBHpRvmn2g2zYo6WY9MxL2Sk9mGE660HqdzlBIXlntvYl4jMTR183x@DdwpDSabVYM8e8yQMh8nVBxi5QaapylpNxtcwIq7bZVXjhlYuUJDIJRAGexBtEemlxPUH "Julia 0.6 – Try It Online")
[Faster, longer version with deprecation avoided. Try it online!](https://tio.run/##LYy9bsMwDIR3PgWzGFSjuE4QdAiiPIOBjoYHqf6JCoeWZRlInt6V3Aw8kB/v7ncZrP5a127hn2BHRk0sYFLfbSABjapq6EaPT1VcWL7UMare1CQC6NVz//qwD8Cg9N5sW68qL4P0h1ADOjUvD9JmzqkXArBU8@hDAqc3sR26K2OWoeZ@aMl/BnErAHFHJVrGSWSZW@b7jhpJFJuFdLJMSfzHU7wAW24gTapP1iEo0tKIw01Xp/pqoojN4LzlMDANLffhnpPO6Xg5FyI2vl@RUQLr@gc "Julia 0.6 – Try It Online") Uses `sqrt.(g)` in place of deprecated `√g` for elementwise square root.
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~227~~ ... 143 bytes
```
import StdEnv
@n#l=[0.0..n]
=sum[1\\p<-removeDup[sort(map(sqrt o\[u,v]=u*u+v*v)[[a-i,b-j],[a,b],[i,j]])\\a<-l,b<-l,i<-l,j<-l|a*j<>i*b]|sum p<n]
```
[Try it online!](https://tio.run/##JY67DsIgGIV3n4LEpVZoqK6t6VAHEzdHYPipVWmAoi0kJn12EePyJSc5t073YKMZr173yICyURk3vmZ0ma9HG1aNXeua0YIWhRWrevKGlZy7irx6M4a@9Y5NyZ4ZcNn0TLmRM4@DqH3utyEPG8aAKCzJIDADLBMVHoTYcA4V0Vj@oH4YEhbIh@qgcimWtIRcZUW8zJBqa9SgclfQ@OluGu5TJKdzbN8WjOr@Ih0@KxnJI@4pNV8 "Clean – Try It Online")
Detects congruent triangles via comparing the three values which sum to make the perimeter, and colinear points by verifying that the two smallest such values do not sum to the third.
Here's a version that uses a faster, more memory-heavy, approach: [Try it online!](https://tio.run/##Jc@xasMwEAbgPU9hKAQbS45aAoEihwzpUMiWUVLL2UkTGUl2I8vEJs/eq0yW7@4fDv6rzRkc2vYUzDmxoB1q27W3Pjn2pw83kDgOulrs3IspBStYUTi1KH2w4lVKIe5kJJN6/1acXm5t6FIfb8VMaqFLpQhkUKX/jTl8vRUsH2azTAigmlS0UUQAqaKaNEplUgKnhlQzeqaJPGBV8a1eNSp73PMxn7hbLuPCt5PCYw@xbZnsknWsh3/1j4GLR/p5wP3owOr6GZ6PIL3ihjGL1OOa2X8 "Clean – Try It Online")
] |
[Question]
[
Today, we'll be computing the most efficient binary function. More specifically, we'll be computing the function which, when an expression is created from applying the function to the constant input 0 or its own output, can represent all positive integers with the shortest possible expressions, placing higher priority on the smaller integers.
This function is built as follows:
For each integer, starting at 1 and going upwards, choose the shortest expression which we have not yet assigned an output to, and make that integer the output of that expression. Ties in expression length will be broken by smaller left argument, and then by smaller right argument. Here's how it works:
* Initially, 1 is unassigned. The shortest unassigned expression is `f(0, 0)`, so we'll set that to 1.
* Now, 2 is unassigned. The shortest unassigned expressions are `f(f(0, 0), 0)` = `f(1, 0)` and `f(0, f(0, 0))` = `f(0, 1)`. Ties are broken towards smaller left argument, so `f(0, 1) = 2`.
* The shortest unassigned expression remaining is `f(f(0, 0), 0)` = `f(1, 0)`, so `f(1, 0) = 3`.
* Now, we're out of expressions with only 2`f`s and 3`0`s, so we'll have to add one more of each. Breaking ties by left argument, then right argument, we get `f(0, 2) = 4`, since `f(0, f(0, f(0, 0))) = f(0, f(0, 1)) = f(0, 2)`.
* Continuing, we have `f(0, 3) = 5`, `f(1, 1) = 6`, `f(2, 0) = 7`, `f(3, 0) = 8`, `f(0, 4) = 9`, ...
Here's a table I filled out for the first few values:
```
0 1 2 3 4 5 6 7 8
/---------------------------
0| 1 2 4 5 9 10 11 12 13
1| 3 6 14 15 37 38 39 40 41
2| 7 16 42 43
3| 8 17 44 45
4| 18 46
5| 19 47
6| 20 48
7| 21 49
8| 22 50
```
Another way to look at it is that each output has a size, equal to the sum of the sizes of its inputs plus one. The table is filled out in order of increasing size of output, ties broken by minimizing left input then right input.
Your challenge is, given two non-negative integers as input, compute and output the value of this function. This is code golf. Shortest solution, in bytes, wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/20080) are banned.
[Answer]
# Haskell, 110 bytes
```
f q=head[i|let c=[(-1,0)]:[[(f a,f b)|n<-[0..k],a<-c!!n,b<-c!!(k-n)]|k<-[0..]],(p,i)<-zip(concat c)[0..],p==q]
```
The argument here is taken to be the tuple `(x,y)`. Pretty similar to the answer above, but the lookup list holds just the pairs of left and right indices instead of the trees.
[Answer]
Wow! I actually managed to make an efficient computation algorithm. I did not expect this at first. The solution is quite elegant. It repeatedly deduces more and more, then recurses all the way down to the base case of 0. In this answer the C(n) function denotes the [Catalan numbers](https://en.wikipedia.org/wiki/Catalan_number).
The crucial first step is acknowledging that there are C(0) = 1 values of length zero (namely 0 itself), C(1) = 1 values of length one (namely f(0, 0)), C(2) = 2 values of length two (f(0, f(0, 0)) and f(f(0, 0), 0)).
This means that if we're looking for the nth expression, and we find the biggest k such that C(0) + C(1) + ... + C(k) <= n then we know that n has length k.
But now we can continue! Because the expression we look for is the n - C(0) - C(1) - ... - C(k) th expression in its length class.
Now we can use a similar trick to find the length of the left segment, and then the rank within that subsection. And then recurse on those ranks we found!
It found that f(5030, 3749) = 1542317211 in the blink of an eye.
# Python, noncompeting
```
def C(n):
r = 1
for i in range(n):
r *= 2*n - i
r //= i + 1
return r//(n+1)
def unrank(n):
if n == 0: return 0
l = 0
while C(l) <= n:
n -= C(l)
l += 1
right_l = l - 1
while right_l and n >= C(l - 1 - right_l) * C(right_l):
n -= C(l - 1 - right_l) * C(right_l)
right_l -= 1
right_num = C(right_l)
r_rank = n % right_num
l_rank = n // right_num
for sz in range(l - 1 - right_l): l_rank += C(sz)
for sz in range(right_l): r_rank += C(sz)
return (unrank(l_rank), unrank(r_rank))
def rank(e):
if e == 0: return 0
left, right = e
l = str(e).count("(")
left_l = str(left).count("(")
right_l = str(right).count("(")
right_num = C(right_l)
n = sum(C(sz) for sz in range(l))
n += sum(C(sz)*C(l - 1 - sz) for sz in range(left_l))
n += (rank(left) - sum(C(sz) for sz in range(left_l))) * C(right_l)
n += rank(right) - sum(C(sz) for sz in range(right_l))
return n
def f(x, y):
return rank((unrank(x), unrank(y)))
```
I'm fairly certain I'm doing a bunch of unnecessary computation and a lot of middle steps could be removed.
[Answer]
# Python 3, 154 bytes
```
b=lambda n:[(l,r)for k in range(1,n)for l in b(k)for r in b(n-k)]+[0]*(n<2)
def f(x,y):r=sum((b(n)for n in range(1,x+y+3)),[]);return r.index((r[x],r[y]))
```
It's not very fast nor very golfy, but it's a start.
] |
[Question]
[
In [this challenge](https://codegolf.stackexchange.com/questions/18541/period-of-the-decimal-representation) 2 years ago, we found the **period** of a unit fraction (`1/n where n is a natural number`).
Now, your task is to write a program/function to find the **repetend** of a unit fraction.
The **repetend** is the part of the decimal expansion which repeats infinitely, like:
* The decimal representation of `1/6` is `0.16666...`, then the **repetend** is `6`.
* The decimal representation of `1/11` is `0.090909...`, then the repetend is `09`.
* The decimal representation of `1/28` is `0.0357142857142857142857...`, then the repetend is `571428`.
## Specs
* Input in any reasonable format.
* Output the repetend in decimal, **string or list**.
* For `1/7` (`0.142857142857...`), you must output `142857` instead of `428571`.
* For `1/13` (`0.076923076923076923...`), you must output `076923` instead of `76923`.
* No brute force, please.
## Testcases
```
Input Output
1 0
2 0
3 3
7 142857
13 076923
17 0588235294117647
28 571428
70 142857
98 102040816326530612244897959183673469387755
9899 000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes win.
No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.
## Leaderboard
```
var QUESTION_ID=78850,OVERRIDE_USER=42854;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Java, 150 bytes:
```
String p(int n){int a=1,p;String r="";for(;n%10<1;n/=10);for(;n%2<1;n/=2)a*=5;for(;n%5<1;n/=5)a*=2;for(p=a%=n;;){p*=10;r+=p/n;if(a==(p%=n))return r;}}
```
### Added whitespace:
```
String p(int n){
int a=1,p;
String r="";
for(;n%10<1;n/=10);
for(;n%2<1;n/=2)
a*=5;
for(;n%5<1;n/=5)
a*=2;
for(p=a%=n;;){
p*=10;
r+=p/n;
if(a==(p%=n))
return r;
}
}
```
### Ungolfed, full program:
```
import java.util.Scanner;
public class A036275 {
public static String period(int a,int n){
if(n%10==0) return period(a,n/10);
if(n%2==0) return period(a*5,n/2);
if(n%5==0) return period(a*2,n/5);
a %= n;
int pow = a;
String period = "";
while(true){
pow *= 10;
period += pow/n;
pow %= n;
if(pow == a){
return period;
}
}
}
public static String period(int n){
return period(1,n);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.close();
System.out.println(period(n));
}
}
```
[Answer]
# CJam, 26
```
riL{_XW$%A*:X|X@-}g_X#>\f/
```
[Try it online](http://cjam.aditsu.net/#code=riL%7B_XW%24%25A*%3AX%7CX%40-%7Dg_X%23%3E%5Cf%2F&input=17)
**Explanation:**
The program builds a series of dividends involved in the calculation of the decimal expansion, until it finds a dividend it has seen before. Then it takes all the dividends starting with that one, and divides them by n to get the digits of the repetend.
```
ri read the input and convert to integer (n)
L push an empty array (will add the dividends to it)
{…}g do … while
_ copy the current array of dividends
X push the latest dividend (initially 1 by default)
W$ copy n from the bottom of the stack
%A* calculate X mod n and multiply by 10
:X store in X (this is the next dividend)
| perform set union with the array of dividends
X@ push X and bring the old array to the top
- set difference; it is empty iff the old array already contained X
this becomes the do-while loop condition
_X# duplicate the array of dividends and find the position of X
> take all dividends from that position
\f/ swap the array with n and divide all dividends by n
```
[Answer]
# Python 3.5, ~~79~~ ~~74~~ ~~73~~ 70 bytes
```
f=lambda n,t=1,q=[],*d:q[(*d,t).index(t):]or f(n,t%n*10,q+[t//n],*d,t)
```
*Saved 3 bytes by keeping track of dividends, an idea I took from [@aditsu's CJam answer](https://codegolf.stackexchange.com/a/78871).*
Test it on [repl.it](https://repl.it/CLdV/5).
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~12~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
%³×⁵
1ÇÐḶ:
```
*Saved 2 bytes by keeping track of dividends, an idea I took from [@aditsu's CJam answer](https://codegolf.stackexchange.com/a/78871).*
[Try it online!](http://jelly.tryitonline.net/#code=JcKzw5figbUKMcOHw5DhuLY6&input=&args=OTg5OQ)
### How it works
```
%³×⁵ Helper link. Argument: d (dividend)
%³ Yield the remainder of the division of d by n.
×⁵ Multiply by 10.
1ÇÐḶ: Main link. Argument: n
1 Yield 1 (initial dividend).
ÇÐḶ Apply the helper link until its results are no longer unique.
Yield the loop, i.e., everything from the first repeated result
up to and including the last unique one.
: Divide each dividend by n.
```
[Answer]
# [Perl 6](http://perl6.org), 37 bytes
```
{(1.FatRat/$_).base-repeating[1]||~0}
~0 max (1.FatRat/*).base-repeating[1]
```
If you don't care that it will only work with denominators that fit into a 64 bit integer you can remove the method call to `.FatRat`.
### Explanation:
```
# return 「"0"」 if 「.base-repeating」 would return 「""」
~0
# 「&infix<max>」 returns the numerically largest value
# or it's first value if they are numerically equal
max
(
# turn 1 into a FatRat so it will work
# with denominators of arbitrary size
1.FatRat
# divided by
/
# the input
*
# get the second value from calling the
# method 「.base-repeating」
).base-repeating[1]
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my &code = ~0 max (1.FatRat/*).base-repeating[1];
# stupid highlighter */
# Perl has never had // or /* */ comments
my @tests = (
1 => '0',
2 => '0',
3 => '3',
6 => '6',
7 => '142857',
11 => '09',
13 => '076923',
17 => '0588235294117647',
28 => '571428',
70 => '142857',
98 => '102040816326530612244897959183673469387755',
9899 => '000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901',
);
plan +@tests;
for @tests -> $_ ( :key($input), :value($expected) ) {
is code($input), $expected, "1/$input";
}
```
```
1..12
ok 1 - 1/1
ok 2 - 1/2
ok 3 - 1/3
ok 4 - 1/6
ok 5 - 1/7
ok 6 - 1/11
ok 7 - 1/13
ok 8 - 1/17
ok 9 - 1/28
ok 10 - 1/70
ok 11 - 1/98
ok 12 - 1/9899
```
[Answer]
# GameMaker Language, 152 bytes
*Based on Kenny's answer*
```
n=argument0;a=1r=0while(n mod 2<1){a*=5n/=2}while(n mod 5<1){a*=2n/=5}a=a mod n;p=a;while(1){p*=10r=r*10+p/n;r=r mod $5f5e107;p=p mod n;if(a=p)return r}
```
[Answer]
# Java, 122
```
String f(int n){String r="";int x=1,a[]=new
int[n*10];while(a[x]++<1)x=x%n*10;do{r+=x/n;x=x%n*10;}while(a[x]<2);return r;}
```
Similar to my CJam solution.
[Answer]
# Pyth, 63 bytes
```
W!%QT=/QT;J*F+1-PQ,2 5K%*F+1-L7@,2 5PQJ=NKW1=+k/=*NTJIqK=%NJB;k
```
[Try it online!](http://pyth.herokuapp.com/?code=W!%25QT%3D%2FQT%3BJ*F%2B1-PQ%2C2+5K%25*F%2B1-L7%40%2C2+5PQJ%3DNKW1%3D%2Bk%2F%3D*NTJIqK%3D%25NJB%3Bk&input=70&debug=0)
Direct translation of the [answer in Java](https://codegolf.stackexchange.com/a/78851/48934).
[Answer]
# PHP, 169 Bytes
```
$d=$argv[2];$a[]=$n=$argv[1];while($n%$d&&!$t){$n*=10;$r[]=$n/$d^0;$t=in_array($n%=$d,$a);$a[]=$n;}if($t)echo join(array_slice($r,array_search(end($a),$a),count($a)-1));
```
] |
[Question]
[
Given 5 distinct points on a two-dimensional plane, determine the type of conic section formed by the points. The output shall be one of `circle`, `hyperbola`, `ellipse`, or `parabola`.
### Rules
* The points will be in general linear position, meaning that no three points are collinear, and thus the conic passing through them will be unique.
* The coordinates of the 5 points will be decimal numbers between -10 and 10, inclusive.
* The precision for the decimal/float values should be the precision of your language's native float/decimal type. If your language/data type is arbitrary-precision, you may use 12 digits after the decimal point as the maximum required precision, rounding toward zero (e.g. `1.0000000000005 == 1.000000000000`).
* Capitalization of the output does not matter.
* Outputting `ellipse` when the conic section is actually a circle is not allowed. All circles are ellipses, but you must output the most specific one.
On floating point inaccuracies and precision:
>
> I'm trying to make this as simple as possible, so that issues with floating point inaccuracies don't get in the way. The goal is, if the data type was "magical infinite precision value" instead of float/double, then everything would work perfectly. But, since "magical infinite precision value" doesn't exist, you write code that assumes that your values are infinite precision, and any issues that crop up as a result of floating point inaccuracies are features, not bugs.
>
>
>
### Test Cases
```
(0, 0), (1, 5), (2, 3), (4, 8), (9, 2) => hyperbola
(1.2, 5.3), (4.1, 5.6), (9.1, 2.5), (0, 1), (4.2, 0) => ellipse
(5, 0), (4, 3), (3, 4), (0, 5), (0, -5) => circle
(1, 0), (0, 1), (2, 1), (3, 4), (4, 9) => parabola
```
[Answer]
# JavaScript (ES6), 316 ~~323 347~~
```
p=>[1,2,4].some(x=>(d=D(Q=[[x&1,x&2,x&4,0,0,0],...p.map(([x,y])=>[x*x,x*y,y*y,x,y,1])]))?[a,b,c]=Q.map((v,i)=>D(Q.map((r,j)=>(r=[...r],r[i]=x*!j,r)))/d):0,D=m=>m[1]?m[0].reduce((r,v,i)=>r+(i&1?-v:v)*D(m.slice(1).map(r=>r.filter((a,j)=>j-i))),0):m)&&(d=b*b-4*a*c)?d<0?!b&c==a?'Circle':'Ellipse':'Hyperbola':'Parabola'
```
Any language better suited for handling matrix and determinant should score better (APL, J, CJAM, Jelly)
References: [General form of a conic](https://en.wikipedia.org/wiki/Conic_section), [Five points determine a conic](https://en.wikipedia.org/wiki/Five_points_determine_a_conic), [System of linear equations](https://en.wikipedia.org/wiki/System_of_linear_equations), [Determinant](https://en.wikipedia.org/wiki/Determinant)
In the cartesian plane, the general equation of a conic is
```
A*x*x + B*x*y + C*y*y + D*x + E*y + F = 0
```
having A or B or C not equal to 0 (otherwise it's a straight line)
A ... F are six unknowns to be found. With five pairs of (x,y) we can build a linear system with five equations, and scaling remove one dimension. That is, we can set one of A,B or C to 1 if it's not 0 (and we know that at least one is not 0).
I build and try to solve 3 systems: first trying A=1. If not solvable then B=1, then C. (There could be a better way, but that's my best at the time)
Having the values of A,B,C we can classify the conic looking at the discriminant `d=B*B-4*A*C`
* d == 0 -> parabola
* d > 0 -> hyperbola
* d < 0 -> ellipse, particularly (A == C and B == 0) -> circle
**Less golfed**
```
F=p=>(
// Recursive function to find determinant of a square matrix
D=m=>m[1]
?m[0].reduce((r,v,i)=>r+(i&1?-v:v)*D(m.slice(1).map(r=>r.filter((a,j)=>j-i))),0)
:m,
// Try 3 linear systems, coefficients in Q
// Five equation made from the paramaters in p
// And a first equation with coefficient like k,0,0,0,0,0,1 (example for A)
[1,2,4].some(
x => (
// matrix to calc the determinant, last coefficient is missing at this stage
Q = [
[x&1, x&2, x&4, 0,0,0] // first one is different
// all other equations built from the params
,...p.map( ([x,y]) => [x*x, x*y, y*y, x, y, 1] )
],
d = D(Q), // here d is the determinant
d && ( // if solvable then d != 0
// add missing last coefficient to Q
// must be != 0 for the first row, must be 0 for the other
Q.map( r=> (r.push(x), x=0) ),
// solve the system (Cramer's rule), I get all values for A...F but I just care of a,b,c
[a,b,c] = Q.map((v,i)=>D(Q.map(r=>(r=[...r],r[i]=r.pop(),r))) / d),
d = b*b - 4*a*c, // now reuse d for discriminant
d = d<0 ? !b&c==a ? 'Circle' : 'Ellipse' // now reuse d for end result
: d ? 'Hyperbola' : 'Parabola'
) // exit .some if not 0
), d // .some exit with true, the result is in d
)
)
```
**Test**
```
F=p=>[1,2,4].some(x=>(d=D(Q=[[x&1,x&2,x&4,0,0,0],...p.map(([x,y])=>[x*x,x*y,y*y,x,y,1])]))?[a,b,c]=Q.map((v,i)=>D(Q.map((r,j)=>(r=[...r],r[i]=x*!j,r)))/d):0,D=m=>m[1]?m[0].reduce((r,v,i)=>r+(i&1?-v:v)*D(m.slice(1).map(r=>r.filter((a,j)=>j-i))),0):m)&&(d=b*b-4*a*c)?d<0?!b&c==a?'Circle':'Ellipse':'Hyperbola':'Parabola'
console.log=(...x)=>O.textContent+=x+'\n'
;[
[[0, 0], [1, 5], [2, 3], [4, 8], [9, 2]]
,[[1.2, 5.3],[4.1, 5.6], [9.1, 2.5], [0, 1], [4.2, 0]]
,[[5, 0], [4, 3], [3, 4], [0, 5], [0, -5]]
,[[1, 0], [0, 1], [2, 1], [3, 4], [4, 9]]
].forEach(t=>console.log(t.join`|`+' => '+F(t)))
```
```
<pre id=O></pre>
```
[Answer]
# Matlab, 154 bytes
```
p=input();c=null([p.^2 prod(p,2) p 1+p(:,1)*0]),s={'circle' 'ellipse' 'parabola' 'hyperbola'};s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}
```
Saved some bytes thanks to Suever's suggestions.
Takes input as `[x1 y1;x2 y2;x3 y3; etc]`. This used a Vandermonde matrix, and finds the basis of its null space, which will always be a single vector. Then it calculates the discriminant and uses it to make an index between 1 and 4 which is used to get the string.
Ungolfed:
```
p=input();
c=null([p.^2 prod(p')' p ones(length(p),1)]);
s={'circle' 'ellipse' 'parabola' 'hyperbola'};
s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}
```
The `sign(...)` part calculates the discriminant, giving 1 if it's positive (hyperbola), -1 if it's negative (ellipse), and 0 if it's 0 (parabola). The `max(...)` subtracts 1 away if it is a circle. Matlab arrays are one-indexed, so add 3 to give values 1, 2, 3, 4, and use that to index the array of conic section names.
[Answer]
# Python - 234 bytes
```
import numpy as n
x=input()
d=[n.linalg.det(n.delete(n.array([[i*i,i*j,j*j,i,j,1]for i,j in x]),k,1))for k in range(6)]
t=d[1]**2-4*d[0]*d[2]
print"hyperbola"if t>0else"parabola"if t==0else"circle"if d[1]==0and d[0]==d[2]else"ellipse"
```
I never print `circle` or `parabola` because `t` and `d[1]` never hit exactly `0`, but OP said that was okay.
[Answer]
# C, 500
My JavaScript answer ported to C. Just to see if it can be done.
Usage: read 10 values from standard input
>
> echo 1 0 0 1 2 1 3 4 4 9 | conic
>
>
>
Output:
>
> Parabola
>
>
>
[Test (ideone)](http://ideone.com/ECm7fm)
```
double D(m,k)double*m;{double t=0;for(int s=1,b=1,x=0;x<6;x++,b+=b)k&b||(t+=s*m[x]*(k+b>62?1:D(m+6,k+b)),s=-s);return t;}i,u,h;double m[36],*t=m+6,w[6],s[3],b,d;main(){for(;i++<5;*t++=d*d,*t++=d*b,*t++=b*b,*t++=d,*t++=b,*t++=1)scanf("%lf%lf",&d,&b);for(u=4;u;u/=2)for(m[0]=u&1,m[1]=u&2,m[2]=u&4,d=D(m,0),h=0;d&&h<3;h++){for(i=0;i<6;i++)w[i]=m[i*6+h],m[i*6+h]=i?0:u;s[h]=D(m,0)/d;for(;i--;)m[i*6+h]=w[i];}b=s[1];d=b*b-4*s[0]*s[2];puts(d?d<0?!b&(s[2]==s[0])?"Circle":"Ellipse":"Hyperbola":"Parabola");}
```
**Less golfed**
```
// Calc determinant of a matrix of side d
// In the golfed code, d is fix to 6
double D(m, d, k)
double*m;
{
int s = 1, b = 1, x = 0;
double t = 0;
for (; x < d; x++, b += b)
k&b || (
t += s*m[x] *(k+b+1==1<<d? 1: D( m + d, d, k + b)), s = -s
);
return t;
}
double m[36],d, *t = m + 6, w[6], s[3], a, b, c;
i,u,h;
main()
{
for (; i++ < 5; )
{
scanf("%lf%lf", &a, &b);
*t++ = a*a, *t++ = a*b, *t++ = b*b, *t++ = a, *t++ = b, *t++ = 1;
}
for (u = 4; u; u /= 2)
{
m[0] = u & 1, m[1] = u & 2, m[2] = u & 4;
d = D(m, 6, 0);
if (d)
for (h = 0; h < 3; h++)
{
for (i = 0; i < 6; i++)
w[i] = m[i * 6 + h],
m[i * 6 + h] = i ? 0 : u;
s[h] = D(m, 6, 0)/d;
for (; i--; )
m[i * 6 + h] = w[i];
}
}
a = s[0], b = s[1], c = s[2];
d = b*b - 4 * a * c;
puts(d ? d < 0 ? !b&(c == a) ? "Circle" : "Ellipse" : "Hyperbola" : "Parabola");
}
```
[Answer]
## Sage, 247 bytes
```
def f(p):
for i in[1,2,4]:
z=[i&1,i&2,i&4,0,0,0]
M=matrix([z]+[[x*x,x*y,y*y,x,y,1]for x,y in p])
try:A,B,C=(M\vector(z))[:3]
except:continue
d=B*B-4*A*C
return['parabola','hyperbola','circle','ellipse'][[d==0,d>0,d<0and B==0and A==C,d<0].index(1)]
```
[Try it online](http://sagecell.sagemath.org/?z=eJxFUs1ugzAMvlfqO_jUBOYioHRa0VKp9NwnyDgwSLVIjKKQVtCnX5zSDmTZsf19_kkadYYz74N8uYDzxYAG3ckEU8xKcsFdSL1KUK9SJxnG9JcUOInfyho9cnkv36QcwxHHcMLJyYgTJiWxOcvxQV8GBLFmyg9Y4FHw09dN1fZi-D0IZL7xjGqsVW_z-tJZ3V0VuRpRhMU6Cw_hkY5G2avpJOsrU31f2ooh-5l6ZWa71qZulTNU2-p-UKyUshEixmbv5DOuugYKdyZ9EOJIvjLSXaNGngSuh-XCqsEOIIAxxmOEOEDgCcKWdIqwIZ0hfJDeIaQBiD28elgueBK5tG30SIwIGr37ZLLTyBM54uQRT6kEUcwdO4LtXDWbq20Qshn0BK-3HvMYl2rOkCdvOusn1FHtPOK1N8ZoWLqhuhoUXZEfPBr6VttWd2rg_kW4jwLoNk9boeRHDmfEx4L_HKFuVcvJmp290Z11b8u7PMMfioGfWw==&lang=sage)
This function takes an iterable of `(x,y)` pairs as input, tries computing the discriminant of each of the 3 possible linear systems (`A=1`, `B=1`, and `C=1`), and outputs the type of conic section based on the values of the discriminant, `A`, `B`, and `C`.
There's probably some more golfing to be done, but I'm rusty with Sage and sleepy right now, so I'll work on it more in the morning.
] |
[Question]
[
Sliding doors have varying prices based on the width of the doors. The different prices are as follows:
* 60 - 80 cm: ¤150
* 81 - 100 cm: ¤200
* 101 - 120 cm: ¤220
When buying a closet you would obviously want to minimize the cost, so your task is to find the width of the doors that minimizes the total cost based on the total width of the closet.
**Rules:**
* The total width will be taken as input
* All doors will have the same width
* Choose the smallest doors if two type of doors cost the same
* The widths are in centimeters, integers not decimals
+ Round up decimals
* The price shall be returned as an integer (no need for the currency sign)
* The input and output formats are optional, but the order of the output must be: `Number of doors, Width, Price`.
* Input will be in the range `[120 1000)`.
This is code golf. Shortest code in bytes win.
**Examples:**
```
Input: 156
Output: 2, 78, 300
Input: 331
Output: 3, 111, 660
Input: 420
Output: 4, 105, 880
```
[Answer]
## JavaScript (ES6), 101 bytes
```
t=>[[80,150],[100,200],[120,220]].map(([w,p])=>[n=-~(~-t/w),-~(~-t/n),n*p]).sort((a,b)=>a[2]-b[2])[0]
```
`-~(~-a/b)` is the same as Math.ceil(a/b) in 31-bit integers.
[Answer]
# Perl, ~~190~~ ~~180~~ ~~154~~ ~~133~~ ~~128~~ 117 bytes
*includes +1 for `-p`*
```
use POSIX;$m=1E4;for$q(80,100,120){($m,@z)=($p,$n,ceil$_/$n)if$m>($p=(150,200,220)[$x++]*($n=ceil$_/$q))}$_="@z $m"
```
Commented:
```
use POSIX; # for ceil()
$m = 1E4; # init min price to 10k
for $q (80,100,120) { # iterate widths
($m,@z) = ($p,$n, ceil $_/$n) # update min, output
if $m > ( #
$p = (150,200,220)[$x++] # grab price
* ( $n = ceil $_/$q ) # times nr of doors needed
)
}
$_="@z $m"
```
---
* Save 11 bytes by inlining and splitting hash to two arrays
* Save 5 bytes by using `-p` (thanks to @dev-null)
* Save 18 bytes by using POSIX::ceil and 3 more by using list syntax for hash (thanks to @msh210)
[Answer]
## PowerShell, ~~137~~ 135 bytes
```
param($a)$j=9e9;60..120|%{if((($c=[math]::ceiling($a/$_))*($p=(220,(200,150)[$_-le80])[$_-le100]))-lt$j){$j=($k=$c)*$p;$i=$_}}
$k;$i;$j
```
Output is newline-separated.
We take input `$a`, set our cost `$j` to `9000000000` (a large number that's way more than we would ever need). Next, we loop from `60..120` with `|%{...}`. Each iteration we calculate the `$p` price of the current item with a [pseudo-ternary statement](https://codegolf.stackexchange.com/a/73519/42963), then calculate the `$c` ceiling of `$a/$_`. If the current total is smaller than the smallest total we've seen (`$j`), save all these variables: `$j` (the total), `$k` (the number of doors required), and `$i` (the door width), and continue the loop. Once the loop is finished, just output the best values.
Edit -- Saved two bytes by moving the `$c` and `$p` assignments into the `if` conditional
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 47 bytes
Code:
```
D120/ó>DU=/ó>=D101›iX220*=q}D80›iX200*=q}X150*=
```
Not the best submission, but at least something :)
[Try it online!](http://05ab1e.tryitonline.net/#code=RDEyMC_Dsz5EVT0vw7M-PUQxMDHigLppWDIyMCo9cX1EODDigLppWDIwMCo9cX1YMTUwKj0&input=MjAx)
[Answer]
# Pyth, 65 bytes
```
ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17
```
[Try it here!](http://pyth.herokuapp.com/?code=ho%2BeNcehNTm%5Bd*hd%3F%3E81ed150%3F%3C101ed220+200%29f%7DeTr60+121m%5Bd.EcQd%29r2+17&input=420&test_suite=1&test_suite_input=156%0A331%0A420&debug=0)
### Explanation
First this generates a list of all possible door count/door width combinations and calculates the price for every of those combinations. Then we only have to order it by price and door width and take the first element of the resulting list.
~~Code explanation follows after I golfed this down~~ Please help me golf this, this is way too long.
```
ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17 # Q=input
m r2 17 # map range(2,17) to
[d ) # list with door count first
.EcQd # and width second
f # Filter map result with T
} r60 121 # in range(60,121)
eT # door width
m # map filter result with d
[d ) # to a list with door count and width first
*hd # mult door count with
?>81ed150?<101ed220 200 # price per door, simple lookup with ternaries
o # order map result with N
+eNcehNT # order key=price+width/10
h # first element is the best
```
[Answer]
# JavaScript (ES6) 96
```
n=>[80,100,120].map((d,i)=>[d=-~(~-n/d),-~(~-n/d),d*[150,200,220][i]]).sort((a,b)=>a[2]-b[2])[0]
```
As noted by @Neil, `=-~(~-n/d)` is equivalent to division with rounding up for integeres of 32 bit or less.
[Answer]
# [R](https://www.r-project.org/), ~~135~~ 104 bytes
```
"!"=utf8ToInt;cbind(n<-16:1,w<-ceiling(scan()/n),p<-n*approx(!"<Qex",!"–ÈÜÜ",w,"c")$y)[order(p)[1],]
```
[Try it online!](https://tio.run/##K/r/X0lRyba0JM0iJN8zr8Q6OSkzL0Ujz0bX0MzKUKfcRjc5NTMnMy9dozg5MU9DUz9PU6fARjdPK7GgoCi/QkNRySYwtUJJR1Hp0LTDHYfnHJ6jpFOuo5SspKlSqRmdX5SSWqRRoBltGKsT@9/Y2PA/AA "R – Try It Online")
Saved 31 bytes by
* decompressing numbers
* using `utf8ToInt`
* using "!" to shorten function call
* using vectorized functions
* not defining total length
* using `cbind` directly rather than after defining variables
### How it works:
1. `approx` returns the price of a
single door based on its length. It returns `NA` outside of the
range `[60,120]`.
2. Based on the spec, the total numbers of doors can't be more than 16
(total length 1000). All number of doors from 16 to 1 are tested,
and the triplet `(number of doors, door width, total price)` is
returned.
3. The `order` function is used to locate the minimum price; the
correct triplet is extracted based on that. In case of ties, `order`
will return the entry that comes first, and since we looped from 16
to 1 the greatest numbers of doors (smallest door width) will be
returned.
] |
[Question]
[
This one is inspired by Calvin's Hobbies recent [multiplication table challenge](https://codegolf.stackexchange.com/questions/65051/sort-the-unique-numbers-in-a-multiplication-table).
Write a function or program that takes an integer `N` as input and prints or returns a N-by-N unique multiplication spiral. The code must (in theory) work for N between 0 and 1000 (outputting this can be hard though). The output should be equivalent to the table produced by the following procedure:
1. Fill out an N-by-N multiplication table. E.g. for N = 3:
```
1 2 3
2 4 6
3 6 9
```
2. Follow a spiral clockwise from the upper left corner, noting the numbers that you visit. When you visit a number which you have already visited, replace it with 0.
A few examples might make it more clear:
```
n = 0:
0
n = 1:
1
n = 2: // Spiral order:
1 2 // 1 2
0 4 // 4 3
n = 3:
1 2 3 // 1 2 3
0 4 6 // 8 9 4
0 0 9 // 7 6 5
n = 4:
1 2 3 4 // 1 2 3 4
0 0 6 8 // 12 13 14 5
0 0 9 12 // 11 16 15 6
0 0 0 16 // 10 9 8 7
n = 5:
1 2 3 4 5
0 0 6 8 10
0 0 9 12 15
0 0 0 16 20
0 0 0 0 25
n = 10:
1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 12 14 16 18 20
0 0 0 0 15 0 21 24 27 30
0 0 0 0 0 0 28 32 36 40
0 0 0 0 25 0 35 0 45 50
0 0 0 0 0 0 42 48 54 60
0 0 0 0 0 0 49 56 63 70
0 0 0 0 0 0 0 64 72 80
0 0 0 0 0 0 0 0 81 90
0 0 0 0 0 0 0 0 0 100
```
The numbers are found like this:
[](https://i.stack.imgur.com/2LFcq.png)
Any reasonable output format is accepted, but it must be an N-by-N matrix, it cannot be just a list. Formats such the ones below are accepted, as there are N easily distinguishable 1-by-N columns, or N-by-1 rows:
```
[[1 2 3][0 4 6][0 0 9]] <-- OK
[[1 0 0][2 4 0][3 6 9]] <-- OK
ans = <-- OK
1 2 3
0 4 6
0 0 9
```
**Shortest code in bytes win.**
[Answer]
# Mathematica ~~123 122 117 98 92~~ 73 bytes
With 24 bytes saved thanks to LegionMammal978 and another 19 by alephalpha !
---
Surprisingly, in this table, multiple instances of any whole number `n` will have the same relative ordering in the spiral as they do in the table itself!
The first appearance of a number `n` lies at the very cell where that number appears first in the table (when one fills in the table row by row). This means that the approach can disregard the spiral constraint altogether, for it has no bearing on the outcome. (See explanation below.)
```
ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&
```
---
## Example
```
ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&[10]
```
>
> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {0, 0, 0, 0, 0, 12, 14, 16, 18,
> 20}, {0, 0, 0, 0, 15, 0, 21, 24, 27, 30}, {0, 0, 0, 0, 0, 0, 28, 32,
> 36, 40}, {0, 0, 0, 0, 25, 0, 35, 0, 45, 50}, {0, 0, 0, 0, 0, 0, 42,
> 48, 54, 60}, {0, 0, 0, 0, 0, 0, 49, 56, 63, 70}, {0, 0, 0, 0, 0, 0,
> 0, 64, 72, 80}, {0, 0, 0, 0, 0, 0, 0, 0, 81, 90}, {0, 0, 0, 0, 0,
> 0, 0, 0, 0, 100}}
>
>
>
---
```
Grid[%]
```
[](https://i.stack.imgur.com/iCYhs.png)
---
## Explanation
We exploit the fact that the spiral-order of the positions of any digit, n, is the same as the the order of row-col positions returned by the function, `Positions`!
The location of the first occurrence of each number (whether one orders by the spiral or by the table position) will be the first element returned by `Position`. That first-occurrence cell will be left as it is. The remaining instances of the number are replaced by 0.
Let's look at how this works, examining for the case of `n==18`. The idea is to start with the multiplication table:
```
(t = Table[k Range@#, {k, #}] &[10]) // Grid
```
and locate the row-col positions of each number. For example, 18 is located at
Row 2, Col 9 (the first instance); Row 3, Col 6; Row 6, Col 3; and Row 9, Col 2.
These have the respective spiral-order positions {44, 58, 68, 82}.
```
Position[t, 18]
```
>
> {{2, 9}, {3, 6}, {6, 3}, {9, 2}}
>
>
>
as the following table shows.
[](https://i.stack.imgur.com/mmNWU.png)
The final 3 instances of 18 need to be replaced by 0. (We'll use a large bold blue zeros so they can be easily spotted.)
```
ReplacePart[%, {{3, 6}, {6, 3}, {9, 2}} -> Style[0, {Blue, Bold, 16}]]// Grid
```
[](https://i.stack.imgur.com/fQ5jJ.png)
[Answer]
# J, 22 bytes
```
,~$[:(*~:)[:,1*/~@:+i.
```
It output a 0-by-0 matrix for `n=0`.
[Answer]
# Python, ~~99 95 90 89 87~~ 81 bytes
Golfed code:
```
n=range(1,input()+1);m=[]
for x in n:l=[(x*y,0)[x*y in m]for y in n];m+=l;print l
```
Ungolfed:
```
n=range(1,input()+1);
m=[]
for x in n:
l=[(x*y,0)[x*y in m]for y in n];
m+=l;
print l
```
Output:
```
10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 0, 0, 0, 0, 12, 14, 16, 18, 20]
[0, 0, 0, 0, 15, 0, 21, 24, 27, 30]
[0, 0, 0, 0, 0, 0, 28, 32, 36, 40]
[0, 0, 0, 0, 25, 0, 35, 0, 45, 50]
[0, 0, 0, 0, 0, 0, 42, 48, 54, 60]
[0, 0, 0, 0, 0, 0, 49, 56, 63, 70]
[0, 0, 0, 0, 0, 0, 0, 64, 72, 80]
[0, 0, 0, 0, 0, 0, 0, 0, 81, 90]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 100]
```
[Answer]
# MATLAB, ~~96 88 87 86~~ 79 bytes
This is the 79 byte code, which follows the example outputs (for n=0 specifically)
```
n=input('');m=+(n>0);for i=1:n;a=i*(1:i);for j=a;m(m==j)=0;end;m(1:i,i)=a;end;m
```
This one is 75 bytes, has the same behaviour except for n=0 which will produce an empty array as per the implication of the question (N by N array = 0 by 0 = empty array).
```
n=input('');m=[];for i=1:n;a=i*(1:i);for j=a;m(m==j)=0;end;m(1:i,i)=a;end;m
```
This also works with **Octave**. You can try it online [here](http://octave-online.net/?s=QHPazBNGkfyhbhbdFrYAnJeGZmDvKMKYapOgHyikJRbmUTQP). The code is already added as a file named 'multspiral.m'. So at the Octave prompt, type `multspiral` and press enter. You should then enter the size of the table (e.g. 4). The output will then be printed.
---
### How does it work?
First this takes an input number as required (e.g. 6, 4, etc.)
```
n=input('');
```
Then we handle cases for `n=0` and `n=1` - these are given special treatment as they are two that don't follow the rule I am using for generating the arrays - in fact this could be 5 bytes shorter if not for the obscure `n=0` case.
```
m=+(n>0);
```
Then for all values of `n>2`, we do some looping until the matrix is grown to the correct size.
```
for i=2:n;
```
There are actually only three simple differences between `n` and `n+1` for all `n>=2`. These are:
1. A new column is added rightmost in the array which contains the numbers `n(1:n)`. This is easily calculated with:
```
a=i*(1:i);
```
2. Any elements which will be added in that new column must be removed from the existing matrix (set to zero) as they will always come later in the spiral than the new column. This is removed using a nestled for loop to set all elements in the current matrix which are in the new column to be zero.
```
for j=a;
m(m==j)=0;
end;
```
3. There is a new row bottom most for which every element except that which is in the new column will be zero. When the new column added, because of the out of bounds indices that has been intentionally created are padded automatically with 0. One of MATLAB's strong features is that it can grow arrays without any special handling, so we can add the new row and column simply with:
```
m(1:i,i)=a;
```
Finally we have the end of the for loop - which once reached, the matrix `m` contains our output. As you are flexible with your output format, the matrix is shown by simply having `m` as a new line without a semicolon
```
end;
m
```
As an example, if we run the program, enter the number 10, we get the following output:
```
m =
1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 12 14 16 18 20
0 0 0 0 15 0 21 24 27 30
0 0 0 0 0 0 28 32 36 40
0 0 0 0 25 0 35 0 45 50
0 0 0 0 0 0 42 48 54 60
0 0 0 0 0 0 49 56 63 70
0 0 0 0 0 0 0 64 72 80
0 0 0 0 0 0 0 0 81 90
0 0 0 0 0 0 0 0 0 100
```
[Answer]
## Haskell, ~~103~~ 99 bytes
```
import Data.Lists
f 0=[[0]]
f n=chunksOf n$foldr(\c d->c:replace[c][0]d)[][a*b|a<-[1..n],b<-[1..n]]
```
Usage example: `f 4`-> `[[1,2,3,4],[0,0,6,8],[0,0,9,12],[0,0,0,16]]`.
I've just discovered the `Data.Lists` module which has nice functions on lists (such as `replace`) and re-exports `Data.List`, `Data.List.Split` and `Data.List.Extras`.
[Answer]
# Ruby, ~~67~~ ~~63~~ 61 bytes
```
->n{s,x=1..n,{};s.map{|c|s.map{|r|x[v=c*r]==1?0:(x[v]=1;v)}}}
```
**63 bytes**
```
->n{s,x=1..n,{};s.map{|c|s.map{|r|e=x[v=c*r]==1?0:v;x[v]=1;e}}}
```
**67 bytes**
```
->n{s,x=1..n,[];s.map{|c|s.map{|r|e=x.include?(v=c*r)?0:v;x<<v;e}}}
```
**Usage:**
```
->n{s,x=1..n,{};s.map{|c|s.map{|r|x[v=c*r]==1?0:(x[v]=1;v)}}}[10]
=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 0, 0, 0, 0, 12, 14, 16, 18, 20], [0, 0, 0, 0, 15, 0, 21, 24, 27, 30], [0, 0, 0, 0, 0, 0, 28, 32, 36, 40], [0, 0, 0, 0, 25, 0, 35, 0, 45, 50], [0, 0, 0, 0, 0, 0, 42, 48, 54, 60], [0, 0, 0, 0, 0, 0, 49, 56, 63, 70], [0, 0, 0, 0, 0, 0, 0, 64, 72, 80], [0, 0, 0, 0, 0, 0, 0, 0, 81, 90], [0, 0, 0, 0, 0, 0, 0, 0, 0, 100]]
```
] |
[Question]
[
INPUT: Any string consisting exclusively of lowercase letters via function argument, command line argument, STDIN, or similar.
OUTPUT: Print or return a number that will represent the sum of the distances of the letters according to the following metric:
You take the first and second letter and count the distance between them. The distance is defined by the QWERTY keyboard layout, where every adjacent letter in the same row has distance 1 and every adjacent letter in the same column has distance 2. To measure the distance between letters that aren't adjacent, you take the shortest path between the two.
Examples:
```
q->w is 1 distance apart
q->e is 2 distance
q->a is 2 distance
q->s is 3 distance (q->a->s or q->w->s)
q->m is 10 distance
```
Then you take the second and third letter, then the third and fourth, etc., until you reach the end of the input. The output is the sum of all those distances.
Example input and output:
```
INPUT: qwer
OUTPUT: 3
INPUT: qsx
OUTPUT: 5
INPUT: qmq
OUTPUT: 20
INPUT: tttt
OUTPUT: 0
```
Here is an image showing which letters are in the same column:

This is code golf, so the shortest code in bytes wins!
[Answer]
# Python 2, ~~220~~ ... ~~124~~ 119 Bytes
*Huge thanks to Sp3000 for saving a **lot** of bytes.*
```
f='qwertyuiopasdfghjkl zxcvbnm'.find
g=lambda i:sum(abs(f(x)%10-f(y)%10)+2*abs(f(x)/10-f(y)/10)for x,y in zip(i,i[1:]))
```
Usage:
```
g("tttt") -> 0
```
[Check it out here.](http://ideone.com/5i7yCy)
Slightly ungolfed + explanation:
```
f='qwertyuiopasdfghjkl zxcvbnm'.find # Defining keyboard rows and aliasing find
g=lambda i: # Defining a function g which takes variable i
sum( # Sum of
abs(f(x)%10-f(y)%10) # horizontal distance, and
+ 2*abs(f(x)/10-f(y)/10) # vertical distance,
for x,y in zip(i,i[1:])) # for each pair in the zipped list
# Example of zipping for those unaware:
# Let i = asksis, therefore i[1:] = sksis, and zip would make
# the list of pairs [(a,s),(s,k),(k,s),(s,i),(i,s)].
```
[Answer]
# Java, 266 bytes
```
int c(String q){String[]r={"qwertyuiop","asdfghjkl","zxcvbnm"};int v=0,l=q.length();int[][]p=new int[l][2];for(int i=0;i<l;i++){while(p[i][0]<1)p[i][0]=r[p[i][1]++].indexOf(q.charAt(i))+1;v+=i<1?0:Math.abs(p[i][0]-p[i-1][0])+2*Math.abs(p[i][1]-p[i-1][1]);}return v;}
```
Ungolfed version:
```
int c(String q) {
String[] r = {
"qwertyuiop",
"asdfghjkl",
"zxcvbnm"
};
int v = 0, l = q.length(); // v=return value, l = a shorter way to refer to input length
int[][] p = new int[l][2]; // an array containing two values for each
// letter in the input: first its position
// within the row, then its row number (both
// 1 indexed for golfy reasons)
for(int i = 0; i<l; i++) { // loops through each letter of the input
while (p[i][0] < 1) // this loop populates both values of p[i]
p[i][0] = r[p[i][1]++].indexOf(q.charAt(i))+1;
v += (i<1) ? 0 : Math.abs(p[i][0]-p[i-1][0])+2*Math.abs(p[i][1]-p[i-1][1]); // adds onto return value
}
return v;
}
```
[Answer]
# SWI-prolog, 162 bytes
```
a(A):-a(A,0).
a([A,B|C],T):-Z=`qwertyuiopasdfghjkl0zxcvbnm`,nth0(X,Z,A),nth0(Y,Z,B),R is T+(2*abs(Y//10-X//10)+abs(Y mod 10-X mod 10)),(C=[],print(R);a([B|C],R)).
```
Example: `a(`qmq`)` outputs `20` (And `true` after it but there's nothing I can do about that).
**Edit:** had to use 3 more bytes. My original program passed the test cases given but was actually incorrect (absolute values were misplaced/missing)
Note: if you want to use it on say [Ideone](https://ideone.com/), you have to replace all backquotes ``` to double quotes `"`. Backquotes in my case (which is the current standard in SWI-Prolog) represent codes list for strings, and double-quotes character strings, but this is different in older versions of SWI-Prolog.
[Answer]
# CJam, 50 bytes
```
r{i",ÙZ°^ªýx´|"257b27b=A+Ab}%2ew::.-::z2fb:+
```
Note that the code contains unprintable characters.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%7Bi%22%06%C2%99%2C%08%C3%99Z%C2%B0%C2%9C%5E%18%C2%AA%C3%BD%C2%93x%C2%B4%7C%22257b27b%3DA%2BAb%7D%252ew%3A%3A.-%3A%3Az2fb%3A%2B&input=qsx). If the permalink doesn't work, copy the code from this [paste](http://pastebin.com/HSpWaL2T).
### Background
We start assigning positions **0** to **9** to the letters on the top row, **10** to **18** to the letters on the home row and **20** to **26** to the letters on the bottom row.
The positions of all 26 letters, in alphabetical order, are
```
[10 24 22 12 2 13 14 15 7 16 17 18 26 25 8 9 0 3 11 4 6 23 1 21 5 20]
```
This is an array of length 26. Since arrays wrap around in CJam, and the code point of the letter **h** is **104 = 4 × 26**, we rotate the array 7 units to the left, so that each letter's position can be accessed by its code point.
```
[15 7 16 17 18 26 25 8 9 0 3 11 4 6 23 1 21 5 20 10 24 22 12 2 13 14]
```
Now we encode this array by considering its elements digits of a base 27 number and convert the resulting integer to base 257.
```
[6 153 44 8 217 90 176 156 94 24 170 253 147 120 180 124]
```
By replacing each integers by the corresponding Unicode character, we obtain the string from the source code.
### How it works
```
r e# Read a whitespace separated token from STDIN.
{ e# For each character:
i e# Push its code point.
",ÙZ°^ªýx´|" e# Push that string.
257b27b e# Convert from base 257 to base 27.
A+Ab e# Add 10 and convert to base 10.
e# Examples: 7 -> [1 7], 24 -> [3 4]
}% e#
2ew e# Push all overlapping slices of length 2.
::.- e# Subtract the corresponding components of the pairs in each slice.
::z e# Apply absolute value to the results.
2fb e# Convert each to integer (base 2).
e# Example: [2 5] -> 2 × 2 + 5 = 9
:+ e# Add the distances.
```
] |
[Question]
[
Write a program that takes a birth date (month and day-of-month) as input and outputs the corresponding sign, element and quality of the [western zodiac](https://en.wikipedia.org/w/index.php?title=Western_astrology&oldid=608954699#The_twelve_signs). For the purposes of this challenge, these are defined exactly as in the table in the linked wikipedia page:
```
Sign Date Range Element Quality
Aries March 21 to April 19 Fire Cardinal
Taurus April 20 to May 20 Earth Fixed
Gemini May 21 to June 21 Air Mutable
Cancer June 22 to July 22 Water Cardinal
Leo July 23 to August 22 Fire Fixed
Virgo August 23 to September 22 Earth Mutable
Libra September 23 to October 23 Air Cardinal
Scorpio October 24 to November 20 Water Fixed
Sagittarius November 21 to December 22 Fire Mutable
Capricorn December 23 to January 20 Earth Cardinal
Aquarius January 21 to February 21 Air Fixed
Pisces February 22 to March 20 Water Mutable
```
### Rules
* The sign, element and quality will be calculated from the input date exactly according to the wikipedia table.
* I am giving some freedom over input date format (see **Input** section below). You must clearly state in your answer what format you are using.
* If an invalid date is provided (unparsable date, or month or day-of-month out of range), the program will exit with the message `Invalid date`.
* The program must correctly handle leap years. i.e. if Feb 29th is the input, then output must correctly be `Pisces, Water, Mutable`.
* Your language's Date libraries/APIs are allowed, but any APIs that specifically calculate signs of the zodiac are banned.
* [Standard “loopholes” which are no longer funny](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
### Input
* The program may read the input date from STDIN, command-line, environment variables or whatever method is convenient for your language of choice.
* This is not primarily an exercise in datestring-parsing, so the input string may be provided in whatever format you choose, as long as it consists of only month and day-of-month components and not other values (such as year or time). E.g. `Jul 24` or `24th of July` or `7/24` or `24/07` or whatever format is convenient. If input not matching your choice of input format is entered, then the `Invalid date` error must be thrown.
### Output
* The program will output to STDOUT, dialog box or whatever display method is convenient for your language of choice.
* The output format will be the sign, element and quality separated by a comma and a space: `Sign, Element, Quality`
### Examples
```
Input Output
1/1 Capricorn, Earth, Cardinal
2/29 Pisces, Water, Mutable
7/24 Leo, Fire, Fixed
13/1 Invalid date
2/31 Invalid date
-1/-1 Invalid date
1st of Golfember Invalid date
```
[Answer]
# JavaScript, 285 bytes
(My first answer here after lurking here for a while)
```
d=prompt(m=prompt(e='MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAriesTaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g)));alert(m>0&m<13&d>0&d<29-~'202121221212'[--m]?e[n=7+m%12+(d>18-~'121012333413'[m])]+', '+e[n%4+3]+', '+e[n%3]:'Invalid date')
```
The first `prompt()` is the month in numerical form, and the second `prompt()` is the day of the month (Ignore the text of the prompt). Leading zeroes are optional for both. The output is displayed with `alert()`. (Thanks to bitpwner, Snack, edc65, and core1024 for helping shorten the code.)
Try it above using Stack Snippets or at <http://jsfiddle.net/8vq89/5/>.
Code with whitespace and comments to explain the confusing parts added:
```
var m = prompt(), d = prompt(),
e = 'MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAries\
TaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g);
alert(m > 0 && m < 13 && d > 0
& d < 29 - ~'202121221212'[--m] /* ~ is bitwise NOT, which yields -(x + 1). It also
converts a string to a number. Subtracting that
number from 29 gives the number of days in the
month given. */
? e[n = 7 + // 7 is added to skip over the 7 qualities and elements in array e.
m % 12 // The modulus allows dates near the end of December to wrap around to January.
+ (d > 18 - ~'121012333413'[m])] + ', ' +
e[n % 4 + 3] + /* Qualities and elements follow a pattern, so the modulus determines
which one it is. 3 is added to skip over the 3 qualities. */
', ' + e[n % 3] : 'Invalid date')
```
[Answer]
# C 353 ~~352~~
**Edit** Fixed bug and typo, 1 char more
Before you ask: yes, even without #include is valid and working C standard.
Input format: two numbers, first month, then day.
```
char*s[]={"Air","Water","Fire","Earth","Fixed","Mutable","Cardinal","Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn"};
main(m,d){
scanf("%d%d",&m,&d);
m>0&m<13&d>0&d<(32-(4460832>>m>>m&3))
?m+=10+(" 121012333413"[m]-29<d),printf("%s, %s, %s\n",s[m%12+7],s[m%4],s[m%3+4])
:puts("Invalid date");
}
```
**Test**
```
char*s[]={"Air","Water","Fire","Earth","Fixed","Mutable","Cardinal","Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn"};
char *test(char *o, int m, int d)
{
char *result=o;
m>0&m<13&d>0&d<(32-(4460832>>m>>m&3))
?m+=10+(" 121012333413"[m]-29<d),sprintf(o, "%s, %s, %s\n",s[m%12+7],s[m%4],s[m%3+4])
:(result = 0);
return result;
}
int main()
{
char buf[100];
int m,d;
for (m=0;m<14;m++)
for(d=0;d<40;d++)
if (test(buf, m,d)) printf("%d %d %s", m, d, buf);
return 0;
}
```
[Answer]
# Perl 287 (286 + 1 for the `-p` flag)
```
/\//;$_=32-(26830452>>$`*2&3)<$'|$'<1|$`<1|$`>12?'Invalid date
':qw(Aquarius01 Pisces23 Aries45 Taurus61 Gemini03 Cancer25 Leo41
Virgo63 Libra05 Scorpio21 Sagittarius43
Capricorn65)[$`-1-($'<20+(219503166088>>$`*3&7))].$/;s/\d/', '.qw(Air
Fixed Water Mutable Fire Cardinal Earth)[$&]/eg
```
The input is from STDIN and the output goes to STDOUT. Here are the tests from OP:
```
1/1
Capricorn, Earth, Cardinal
2/29
Pisces, Water, Mutable
7/24
Leo, Fire, Fixed
13/1
Invalid date
2/31
Invalid date
-1/-1
Invalid date
1st of Golfember
Invalid date
```
[Answer]
# Python, ~~447~~ 387 characters
```
import sys
try:S=sys.argv[1];a,b=int(S[:2])-1,int(S[3:])
except:a=b=0
print['Invalid date',', '.join((s.split()*5)[a+(b>[20,21,20,19,20,21,22,22,22,23,20,22][a%12])]for s in"Capricorn Aquarius Pisces Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Capricorn|Earth Air Water Fire|Cardinal Fixed Mutable".split("|"))][-1<a<12and 0<b<[32,30,32,31,32,31,32,32,31,32,31,32][a]]
```
Takes input as MM/DD, must always be two digits.
```
$ python zods.py 01/01
Capricorn, Earth, Cardinal
$ python zods.py 02/29
Pisces, Water, Mutable
$ python zods.py 07/24
Leo, Fire, Fixed
$ python zods.py 13/01
Invalid date
$ python zods.py 02/31
Invalid date
$ python zods.py -1/-1
Invalid date
$ python zods.py First of golfember
Invalid date
$ python zods.py
Invalid date
```
[Answer]
# Javascript, ~~403~~ 396 bytes
```
M=prompt(),D=+prompt(),i=[52,85,117,147,180,213,246,278,310,343,372,406,415];if([0,0,-2,0,1,0,1,0,0,1,0,1,0][M]<D-31||M<1||D<1||M>12)alert("Invalid date");else for(x in i)if(M*32+D<=i[x]){alert("Capricorn0Aquarius0Pisces0Aries0Taurus0Gemini0Cancer0Leo0Virgo0Libra0Scorpio0Sagittarius0Capricorn".split(0)[x]+", "+["Earth","Air","Water","Fire"][x%4]+", "+["Cardinal","Fixed","Mutable"][x%3]);break}
```
Another approach. I think I can golf down more, but later.
Input month on first prompt, date on second prompt.
[Answer]
# PHP - 294 bytes (w/o php tags\*)
**\*As the other php entry did**
Input:`Month Day` as integers, leading zero not required.
Ex:`php starsign.php <<< "2 29"` for February 29th.
Golfed (do not copy this directly, see below):
```
<?@eval(gzinflate('=Œ1
Â0…ÿŠC!Ë
¦q+JQ—
BEq¸¶¡Ô¤^ðç{¤"ï>/Ãò®`³GOBqú7
v¥±MP#äpúµ;$:Å€Ý$“g¦Þ³ƒê‘).p¦¥·
TL’Œ,ÝѾȑ¬]oëáJ<zh¨c„V3yhq¤VË_ü(²®TZË¥ØêܳÓF_'));die(fscanf(STDIN,'%u%u',$m,$d)/2&$m<13&&$m*$d&&$d<33-$b[$m]?$a[7+$m-=$d<20+$b[$m+9]].$a[$m%4].$a[$m%3+4]:'Invalid date');
```
Hexdump of php file:
```
3f3c 6540 6176 286c 7a67 6e69 6c66 7461
2865 3d27 318c c20b 1030 ff85 438a cb21
a60d 2b71 4a1d 9751 420a 0745 b871 a1b6
d41e 5ea4 f013 7be7 22a4 ef07 1e3e 2f8f
f2c3 60ae 47b3 4f0e 4205 7115 37fa 760c
03a5 4db1 2350 e40f fa70 1fb5 243b c53a
dd80 9324 671a dea6 83b3 1dea 2991 702e
a5a6 0bb7 4c54 1792 2c8c d1dd c8be ac91
6f5d 1a19 e1eb 3c4a 687a 63a8 5684 3304
6879 a471 5610 5fcb 28fc aeb2 5a54 9d1b
a5cb ead8 18dc d3b3 1546 275f 2929 643b
6569 6628 6373 6e61 2866 5453 4944 2c4e
2527 2575 2775 242c 2c6d 6424 2f29 2632
6d24 313c 2633 2426 2a6d 6424 2626 6424
333c 2d33 6224 245b 5d6d 243f 5b61 2b37
6d24 3d2d 6424 323c 2b30 6224 245b 2b6d
5d39 2e5d 6124 245b 256d 5d34 242e 5b61
6d24 3325 342b 3a5d 4927 766e 6c61 6469
6420 7461 2765 3b29
```
To generate golfed file, run the following php script (generates to `starsign.php`):
```
<?php
$a=<<<'NOW'
$a=[', Earth',', Air',', Water',', Fire',', Cardinal',', Fixed',', Mutable',Capricorn,Aquarius,Pisces,Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn];$b='1131212112121012333413';
NOW;
$p = '<?@eval(gzinflate(\'';
$s = <<<'NOW'
'));die(fscanf(STDIN,'%u%u',$m,$d)/2&$m<13&&$m*$d&&$d<33-$b[$m]?$a[7+$m-=$d<20+$b[$m+9]].$a[$m%4].$a[$m%3+4]:'Invalid date');
NOW;
file_put_contents('starsign.php',$p . gzdeflate($a) . $s);
```
Completely ungolfed version:
```
<?php
$a=[', Earth',', Air',', Water',', Fire',', Cardinal',', Fixed',', Mutable',Capricorn,Aquarius,Pisces,Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn];$b='1131212112121012333413';
if(fscanf(STDIN, '%u%u', $m, $d) == 2
and $m < 13
and $m
and $d
and $d < 33-$b[$m]){
if($d < 20 + $b[$m+9])
--$m;
die($a[7+$m] . $a[$m%4] . $a[$m%3+4]);
}else die('Invalid date');
```
[Answer]
# Python 3 - 332 bytes
```
s="Capricorn Aquarius Pisces Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Earth Air Water Fire Cardinal Fixed Mutable".split()
import sys
try:m,d=map(int,sys.argv[1:]);13>m>0<d<b" 313232332323"[m]-19or E
except:x="Invalid date"
else:i=m-1+(d>b" 121012333413"[m]-29);x=s[i%12]+", "+s[-7+i%4]+", "+s[-3+i%3]
print(x)
```
* Takes input as separate arguments (i.e. `1 1`)
* One split for all strings
* Indexing bytes in py3 gives the ord
* `or E` is a cheap way to generate an exception (`NameError`)
* Is there a cheaper way to concatenate the strings? `+` and literals turned out to be smaller than `join`.
* There's no good reason for one bytes lookup to start with 1 and the other with 0, I just forgot the 29-day February and changed 0->1 instead of redoing the whole thing.
[Answer]
# PHP ~~548~~ ~~524~~ ~~502~~ 419 (w/o php tags)
Requires PHP >= 5.4.0
Input: `Day Month` (numerical value starting at 1)
e.g. `2 3` for March 2nd.
```
<?
$x='Invalid date';
@list($d,$m)=split(' ',fgets(STDIN));
if(@$m<1||$m>12||@$d<1)die($x);
$z=['Aquarius','Pisces','Aries','Taurus','Gemini','Cancer','Leo','Virgo','Libra','Scorpio','Sagittarius','Capricorn','Air','Water','Fire','Earth','Fixed','Mutable','Cardinal','121012333413202121221212'];
$m=$m+0;$d<$z[19][--$m]+20&&$m--;$m<0&&$m=11;$d>$z[19][$m+12]+29&&die($x);
echo$z[$m+0],", {$z[$m%4+12]}, {$z[$m%3+16]}";
```
**EDIT:** The `A non well formed numeric value` notice is caused by performing a pre-increment on the string `$m`. Regardless of the notice, the following output should still be correct. This notice varies per version of `PHP`. To fix this, a simple string to integer conversion should be placed before the second last line. I've updated the code with the conversions.
Sample Input/Output (on Windows):
```
// March 2nd
Input > echo 2 3 | php star.php
Output > Pisces, Water, Mutable
// Feb. 30th
Input > echo 30 2 | php star.php
Output > Invalid date
// June 30th
Input > echo 30 6 | php star.php
Output > Cancer, Water, Cardinal
```
] |
[Question]
[
(Adapted from [Problem C of the first qualifier of the ACM Programming Contest of 2012/2013](http://www.cs.sfu.ca/SeminarsAndEvents/ACM/120922/probC.pdf))
You have several arrays, named \$A\_1, A\_2, ... , A\_n\$, each sorted in ascending order. Every item in the array will be a 32-bit integer.
A **sandwich** is a set of indices \$j\_1, j\_2, ... , j\_n\$ such that \$A\_1[j\_1] ≤ A\_2[j\_2] ≤ ... ≤ A\_n[j\_n]\$. \$A\_i[0]\$ is the first element of \$A\_i\$.
Given some arrays, output every possible sandwich that you can have from those arrays, separated by a newline.
If there is somehow a built-in function which does this in your language, don't use it.
Input can be given in any way, output must be separated with whitespace, but can given in any order.
Test Case:
```
[[1, 5, 7, 10], [2, 6, 6, 8, 12], [4, 5, 9]]
```
Output:
```
0 0 0
0 0 1
0 0 2
0 1 2
0 2 2
0 3 2
1 1 2
1 2 2
1 3 2
2 3 2
```
Test Case:
```
[[10, 20, 30], [1, 2, 3]]
```
Output:
Shortest code wins.
[Answer]
## APL (33)
```
↑1-⍨B/⍨{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B←,⍳⊃∘⍴¨A←⎕
```
Input is read from the keyboad, but it must be given as an APL list, i.e.
```
(1 5 7 10) (2 6 6 8 12) (4 5 9)
```
Explanation:
* `B←,⍳⊃∘⍴¨A←⎕`: A is evaluated input, B is all possible sets of indices in the lists given in A.
* `{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B`: for each set of indices, get the values from the lists (`⍵⌷¨A`) and see if they are sorted (`(⍳⍴A)∘=⍋`)
* `B/⍨`: select from B all sets of indices where the previous expression was true (i.e. all the sandwiches)
* `1-⍨`: subtract one from all indices, because this question assumed 0-based arrays and APL-arrays are 1-based by default.
* `↑`: arrange the list of sets of indices as a matrix (so each set is on its own line)
[Answer]
## GolfScript, 51 chars
```
~:A{,}%{*}*,{A{,.@.@/\@%}%\;}%{:k,,{.A=\k==}%.$=},`
```
Example input (on stdin):
```
[[1 5 7 10] [2 6 6 8 12] [4 5 9]]
```
Example output (to stdout):
```
[[0 0 0] [0 0 1] [0 0 2] [0 1 2] [1 1 2] [0 2 2] [1 2 2] [0 3 2] [1 3 2] [2 3 2]]
```
(Note that input *must* be given without commas, otherwise the program will most likely crash.)
---
I guess I should add some explanation about how this code works:
* `~:A` just evaluates the input as GolfScript code and assigns the result (an array of arrays) to `A`. It also leaves a copy of `A` on the stack for the next step.
* `{,}%` replaces each sub-array with its length, and `{*}*` multiplies those lengths together, giving the total number of possible sandwich candidates. This number is then converted by `,` to an array of that many successive integers starting from 0.
* `{A{,.@.@/\@%}%\;}%` converts each number into a the corresponding sandwich candidate (i.e. an array of valid indices into each sub-array in `A`). For example, given the input above, `0` would map to `[0 0 0]`, `1` to `[1 0 0]`, `2` to `[2 0 0]`, `3` to `[3 0 0]`, `4` to `[0 1 0]` and so on. (Figuring out exactly how the code accomplishes that is left as an exercise for the interested reader.)
* `{:k,,{.A=\k==}%.$=},` filters the sandwich candidates by mapping each of them to the corresponding elements of the sub-arrays of `A` (so that e.g. `[0 0 0]` would yield `[1 2 4]`, `[1 0 0]` would yield `[5 2 4]`, and so on, for the input above), sorting the resulting array and comparing it with an unsorted copy. If they are equal, the array was already sorted, and thus the candidate is indeed a sandwich.
* Finally, ``` just turns the filtered array of sandwiches into a string for output.
[Answer]
# Mathematica, 120 130 bytes
## Edit
This version works with arrays of varying sizes.
---
```
l = List;
g = Grid@Cases[Outer[l, Sequence @@ MapIndexed[l, #, {2}], 1]~Flatten~(Length[#] - 1),
x_ /; LessEqual @@ x[[All, 1]] == True :> x[[All, 2, 2]] - 1] &
```
## Usage
```
g@{{10, 20, 30}, {1, 22, 3}}
g@{{1, 5, 7, 10}, {2, 6, 6, 8, 12}, {4, 5, 9}}
g@{{10, 20, 30}, {1, 2, 3}}
g@{{1, -2, 3}, {-12, -7, 8, 9, 6}, {3, 99, 9}, {100, 10, -23}, {90, 10}}
```

---
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
J€Œpị"ṢƑ¥Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/9/rUdOao5MKHu7uVnq4c9GxiYeWHmv/f7j9UcNMd82sR437Dm07tO3//@hoQx0FUx0Fcx0FQ4NYHYVoIx0FMzCyAIoYgURMwAosY0HsaEMDHQUjIDYGKwbqBao3jo0FAA "Jelly – Try It Online")
This uses 1-indexing which is the default for Jelly. [+2 bytes](https://tio.run/##y0rNyan8/9/rUdOao5MKHu7uVnq4c9GxiYeWHms/tPVRw8z/h9vdNbMeNe47tO3Qtv//o6MNdRRMdRTMdRQMDWJ1FKKNdBTMwMgCKGIEEjEBK7CMBbGjDQ10FIyA2BisGKgXqN44NhYA) to use 0-indexing.
## How it works
```
J€Œpị"ṢƑ¥Ƈ - Main link. Takes a 2d array A on the left
€ - Over each subarray:
J - Replace the subarray with its indices
Œp - Take the Cartesian product of these indices
¥Ƈ - Keep the indices for which the following is true:
ị" - Index into each subarray of A
ṢƑ - The resulting elements are in ascending order?
```
[Answer]
## R - 89 chars
```
i=do.call(expand.grid,lapply(x,seq_along))
i[apply(diff(t(mapply(`[`,x,i)))>=0,2,all),]-1
```
where
```
x = list(c(1, 5, 7, 10), c(2, 6, 6, 8, 12), c(4, 5, 9))
```
or
```
x = list(c(10, 20, 30), c(1, 2, 3))
```
[Answer]
# Python, ~~149~~ ~~141~~ 140
```
import itertools as I;x=input();r=range;print[p for p in I.product(*map(r,map(len,x)))if all(x[i][p[i]]<=x[i+1][p[i+1]]for i in r(len(x)-1))]
```
Python has a useful itertools library that can generate permutations. This just iterates over all possible permutations of valid indices and checks whether they satisfy the criteria.
I think I can make this shorter, still working on it.
Edit: Now all one line for your reading (in)convenience!
[Answer]
# Python 120
```
f=lambda p,k=0:['%i '%j+m for j,v in enumerate(p[0])if v>=k for m in f(p[1:],v)]if p else['']
print'\n'.join(f(input()))
```
... still think, "enumerate" is a very long word.
[Answer]
## GolfScript (44 chars)
```
~{.,,]zip}%{{`{+}+1$\/}%\;}*{2%.$=},{(;2%}%`
```
Same input and output format as Ilmari's entry.
[Demo](http://golfscript.apphb.com/?c=OydbWzEgNSA3IDEwXSBbMiA2IDYgOCAxMl0gWzQgNSA5XV0nCgp%2Bey4sLF16aXB9JXt7YHsrfSsxJFwvfSVcO30qezIlLiQ9fSx7KDsyJX0lYA%3D%3D)
Rough breakdown:
Map each input row into an array of pairs `[value index]`
```
{.,,]zip}%
```
Fold a Cartesian product over the rows
```
{{`{+}+1$\/}%\;}*
```
Filter to those whose 0th, 2nd, 4th, etc. entries are non-decreasing.
```
{2%.$=},
```
Map each one down to its 1st, 3rd, 5th, etc. entries.
```
{(;2%}%
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εεN].«â€˜ʒεINèsè}¥dP
```
Indexing into matrices is not 05AB1E's strong suit.. :/
[Try it online.](https://tio.run/##yy9OTMpM/f//3NZzW/1i9Q6tPrzoUdOa03NOTTq31dPv8IriwytqDy1NCfj/PzraUMdUx1zH0CBWJ9pIxwwILXQMjYAcE6C4ZWwsAA)
**Explanation:**
```
εεN] #Transform the input to a list of lists of indices:
ε # Map over each list of the (implicit) input-list:
ε # Map over each inner value in this list:
N # Push the map-index
] # Close both maps
.«â€˜ #Create all combinations of the indices in each list:
.« # Left-reduce the list of lists by:
â # Taking the cartesian product
€ # Then map over each inner list of nested lists:
˜ # And flatten the values to a single list
ʒεINèsè}¥dP #Filter to keep just the indices that are in ascending order
ʒ # Filter the list of lists of indices by:
ε # Map over each index:
INè # Use the map-index itself to index into the input list of lists
sè # Then use the index we're mapping over to index into this list
}¥ # After the map: get all the deltas / forward differences
d # Check for each that they're non-negative (>=0)
P # And check if this is truthy for all of them
# (after the filter, the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
vẏΠ'?¨£iÞṠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24bqPzqAnP8KowqNpw57huaAiLCI74oGLIiwiW1sxLCA1LCA3LCAxMF0sIFsyLCA2LCA2LCA4LCAxMl0sIFs0LCA1LCA5XV0iXQ==)
Port of Jelly.
[Answer]
# Q, 43
```
{f(&)m~'(asc')m:x@'/:f:(cross/)(!:')(#:')x}
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
#<=##&~Outer~##~Position~True&
```
[Try it online!](https://tio.run/##LYu9CsMgFEb3PMUFIdOFqukvNODSuYH2BUQMcYiCNdNFX91KWviW83HOqtNiV52c0XUeK7uPjPXluSUbC2NlCh@XXPDlHTfb1yk6nw5qVuphlqCa@TLaF@qIQCCcEC4oeMYOCCTCed8Vhfxdx1255UZEgqPkOPztVrdgyLnL9Qs "Wolfram Language (Mathematica) – Try It Online")
Returns 1-indexed. For 0-indexing, add `-1` (+2 bytes).
[Answer]
## JavaScript, 138 bytes
```
x=a=>(f=(a,p)=>a[0].flatMap((v,i)=>v<p?null:a[1]?(r=f(a.slice(1),v))&&r.map(j=>j&&[i,...j]):[[i]]))(a).map(i=>i?i.join(' ')+'\n':'').join('')
```
or more readable:
```
x = a => (f = (a, p) => a[0].flatMap(
(v, i) => v<p
? null
: a[1]
? (r = f(a.slice(1), v)) && r.map(j => j && [i, ...j])
: [[i]]
)
)(a).map(
i => i
? i.join(' ') + '\n'
: ''
).join('')
```
[Answer]
# [J](http://jsoftware.com/), 22 bytes
```
#&>#:[:I.(-:/:~)@>@,@{
```
[Try it online!](https://tio.run/##LYvLCsIwFET3/YqhF9IE2mtTfN5iCAqCIF24ra7Eom78gEJ@PYYgw4HhMPOJJVcT9oIKNVpIomEcr5dTJOVIRjmzbmQhwXjnaz9HUwwHxhyUGyWbN3tS7LKmW2qawv9SWqN0Hpl78Xy8vphgscIGtu3RYZ2yhe16LJPdxR8 "J – Try It Online")
Takes input as boxed lists, as J does not allow heterogeneous arrays.
* `>@,@{` The open `>` of the flatten `,` of the Cartesian product `{`. This is just one big matrix whose rows are the elements of the Cartesian product.
* `(-:/:~)@` Which of those matches itself sorted? Returns a single 0-1 boolean list.
* `[:I.` Indices of the ones.
* `#&>#:` Convert to a mixed base number, where the bases are the lengths of the original input lists.
] |
[Question]
[
Here's an advanced version of the [Count the Liberties](https://codegolf.stackexchange.com/questions/243956/count-the-liberties) challenge.
The definitions of the terms *liberty* and *group* are the same as the previous challenge, so have a look at the previous one for details, but briefly put,
* A *group* is a group of stones that are connected horizontally or vertically.
* *Liberty* is the number of empty spaces connected horizontally or vertically to a group.
For example,
```
. . O .
. X X .
. X . .
. O O .
```
black's group (`X`) has 5 liberties, the upper group of white (`O`) has 2 liberties, and the lower group of white has 3 liberties.
For input, you will be given an 2D array of arbitrary size, in which each cell has one of `black`, `white`, or `empty`. You may map any value of any data type for `black`, `white`, and `empty`; but 1 value can be mapped to each.
All groups in the input will always have 1 or more liberties.
For output, the cells that had `empty` will be `0`, and the cells that had `black` or `white` will be filled with the number of liberties of its group.
### Examples
```
. . O . 0 0 2 0
. X X . -> 0 5 5 0
. X . . 0 5 0 0
. O O . 0 3 3 0
. X . O -> 0 2 0 1
X 1
X 1
. -> 0
. 0
O 2
. 0
. X X . 0 3 3 0
X . X O -> 2 0 3 2
X X O . 2 2 1 0
```
---
If you have participated in the previous challenge, having to count the liberties of multiple groups may require a quite different strategy.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~85~~ 81 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
2FINi(}Θ©˜ƶIgäΔ2Fø0δ.ø}2Fø€ü3}®*εεÅsyøÅs«à]+ÐU˜ê¦©vyX®y†AS:¾1:'a0:4FJTx:€Søí}S2¢:
```
"*If you have participated in the previous challenge, having to count the liberties of multiple groups may require a quite different strategy.*" That's an understatement, haha. This answer is almost 8 times as large as [my 05AB1E answer for the related challenge](https://codegolf.stackexchange.com/a/243999/52210). Although this is primarily because flood-filling is so expensive in 05AB1E; and the conversion I use is currently pretty verbose as well..
Uses `-1`/`1` for `O`/`X` and `0` for empty spaces.
[Try it online](https://tio.run/##yy9OTMpM/f/fyM3TL1Oj9tyMQytPzzm2zTP98JJzU4zcDu8wOLdF7/COWhDzUdOaw3uMaw@t0zq39dzWw63FlYd3AMlDqw8viNU@PCH09JzDqw4tO7SyrDLi0LrKRw0LHIOtDu0ztFJPNLAycfMKqbACmhAM1LO2Ntjo0CKr//@jow10DHR0DXUMYnWATEMdBMsAygJKguVjAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JhcUpqYo5CZV1BaYqWgZF/pEqbDpRRQlFpSUqlbUJSZV5KaApfVqTy03OjclqxDu3WU/hu5RfplatSem3Fo5ek5x7ZFph9ecm6KkdvhHQbntugd3lELYj5qWnN4j3HtoXVa57ae23q4tbjy8A4geWj14QWx2ocnhJ6ec3jVoWWHVpZVRhxaV/moYYFjsNWhfYZW6okGViZuXiEVVkATgoF61tYGGx1aZPVfSS8M5uT80hKom20xHAyX0zm0PCod4uJD2@z/R0dHG@gY6Oga6hjE6gCZhjoIlgGUBZQEy8fqKERDJXQNITxDoAIQNoBiXQgHrhJiGEgHyAwwE2ZYLAA).
**Explanation:**
Step 1: Flood-fill the individual islands. I've done this before in 05AB1E [for this challenge](https://codegolf.stackexchange.com/a/242094/52210) (which actually contained a bug that I discovered thanks to the final test case here):
```
2F # Loop 2 times (for each 1/-1 type of piece individually):
I # Push the input-matrix
Ni } # If the 0-based loop-index is 1:
( # Negate all values
Θ # Check which values are equal to 1 (maps 1→1; 0→0; -1→0)
© # Store this in variable `®` (without popping)
˜ # Flatten it to a list
ƶ # Multiply each value by its 1-based index
ä # Convert it back to the matrix,
Ig # using the input-length amount of rows
Δ # Loop until it no longer changes to flood-fill:
2Fø0δ.ø} # Add a border of 0s around the matrix:
2F } # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
δ # Map over each row:
0 .ø # Add a leading/trailing 0
2Fø€ü3} # Convert it into overlapping 3x3 blocks:
2F } # Loop 2 times again:
ø # Zip/transpose; swapping rows/columns
€ # Map over each inner list:
ü3 # Convert it to a list of overlapping triplets
®* # Multiply each 3x3 block by the value in matrix `®`
# (so the 0s remain 0s)
εεÅsyøÅs«à # Get the largest value from the horizontal/vertical cross of
# each 3x3 block:
εε # Nested map over each 3x3 block:
Ås # Pop and push its middle row
y # Push the 3x3 block again
ø # Zip/transpose; swapping rows/columns
Ås # Pop and push its middle rows as well (the middle column)
« # Merge the middle row and column together to a single list
à # Pop and push its maximum
] # Close the nested maps, flood-fill loop, and outer loop
+ # Add the values in the two matrices together
```
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f/fyM3TL1Oj9tyMQytPzzm2zTP98JJzU4zcDu8wOLdF7/COWhDzUdOaw3uMaw@t0zq39dzWw63FlYd3AMlDqw8viNX@/z862kDHQEfXUMcgVgfINNRBsAygLKAkWD4WAA)
Step 2: Loop over the individual islands, and convert all `0`s to `1`s; the current island to `0`s; and all other islands to lowercase letters, as preparation for the next step:
```
Ð # Triplicate the resulting matrix
U # Pop one, and save it in variable `X`
˜ # Flatten another one
ê # Sort and uniquify the values
¦ # Remove the leading 0
© # Store these island-values in variable `®` (without popping)
v # Loop over each island-value `y`:
X # Push matrix `X`
® # Push list `®`
y† # Filter the current island to the front
AS # Push the lowercase alphabet as list
: # Replace the island-values with letters
¾1: # Replace all 0s with 1s
'a0: # Replace all "a" (the current island) with 0s
```
[Try the first 2 steps online (with some added debug-lines).](https://tio.run/##yy9OTMpM/f/fyM3TL1Oj9tyMQytPzzm2zTP98JJzU4zcDu8wOLdF7/COWhDzUdOaw3uMaw@t0zq39dzWw63FlYd3AMlDqw8viNXmUvIvykzPzEvMUchNLCnKrLBSUNJxObQ8Kv3clqxDu3UObbPnOjwh9PScw6sOLTu0soxLQcmzOCcxL0W3LDGnNBWo2r5SByjonJ9XllpUkpqCZEzEoXWVjxoWOAZbHdpnaKWeaGAFMhhu7v//0dEGOgY6uoY6BrE6QKahDoJlAGUBJcHysQA)
Step 3: Use the same method as [in the linked challenge](https://codegolf.stackexchange.com/a/243999/52210) to get the liberty-counts of each island:
```
4F # Loop 4 times:
J # Join the inner rows together to strings
T # Push 10
x # Double it (without popping): 20
: # Replace all "10" with "20"
€S # Convert each row back to a list again
øí # Rotate the matrix 90 degrees clockwise:
ø # Zip/transpose; swapping rows/columns
í # Reverse each inner row
} # Close the loop
S # Convert the matrix to a flattened list of characters
2¢ # Count how many 2s are in this list
```
[Try the first 3 steps online (again with added debug-lines).](https://tio.run/##yy9OTMpM/f/fyM3TL1Oj9tyMQytPzzm2zTP98JJzU4zcDu8wOLdF7/COWhDzUdOaw3uMaw@t0zq39dzWw63FlYd3AMlDqw8viNXmUvIvykzPzEvMUchNLCnKrLBSUNJxObQ8Kv3clqxDu3UObbPnOjwh9PScw6sOLTu0soxLQcmzOCcxL0W3LDGnNBWo2r5SByjonJ9XllpUkpqCZEzEoXWVjxoWOAZbHdpnaKWeaGAFMhhiLlCLT2YSUEelbnJ@aV6JQn6aQklGZrFCJth0BY3EXJiwYbFCcn5eXmoyyPSM/KLMqvy8ksScnEp9kI2ZySCmQkm@gkGxJsg5Jm5eIRVWQE8HA725tjbY6NAikC/@/4@ONtAx0NE11DGI1QEyDXUQLAMoCygJlo8FAA)
Step 4: Convert the current island to this count in the matrix:
```
# The matrix from the triplicate of step 2 is still on the stack
y # Push island-value `y` from the still open loop of step 2
: # Replace all of these islands with its count from step 3
# (after which the resulting matrix is output implicitly)
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 43 bytes [SBCS](https://github.com/abrudz/SBCS)
Takes an integer matrix with 0 for blanks and any positive integer for a color (Supports any number of colors)
```
⍴⍴,+.<∘.(2>+⍥|.-)⍨⍤,⍤⍳⍤⍴∨.∧⍨⍣≡⍤∧,∘.(=≠0=⊣),
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S75VHvFh1tPZtHHTP0NIzstB/1Lq3R09V81LviUe8SHSB@1LsZTG551LFC71HHcrDM4kedC0GiHct1wBptH3UuMLB91LVYUwcA&f=e9Q31dNf4VHbBAUDrnQwXa1xaL3ho7bJj3qXAKmJOvpGQPLQike9WzUVdB71Ln3U1aSQpgDkPurd/Kh3hbqef4R6LRdQs4mCyaPeLep6ehF6ev7@QKwHZEboqQOlDKFSEXr@IK6ZgiGIGwFSCJY3hslHAJVE@EdEAIUB&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
The general strategy is to build an adjacency matrix for positions on the board, find the transitive closure, and, for each position with a color, count how many blank squares are connected to it. Some step-by-step results can be seen [on APLgolf](https://razetime.github.io/APLgolf/?h=AwA&c=e9S1CAA&f=tVDNSgMxEL73KebWXRrX7c@pWEEFQfBYwWu6HdvobrIk2VLBkwdpCwsevQhKK/ZunyhPYjbd1lMVQQkzE2bm@0kGkvXBPDxC0x6TryCEuo2Gy0UNKyZ/hu6QKZCYSlTItXK9sJwFcOnqBY9EktgxXAkJMZUDBBzTJI2x7RYGG60WtKxUye8U12p14jX3Q580nG71jKeZdqh2tWJm98WtUj2NqdbIsWwCWbeP@tc0Qh7dQo8q7IPgMKJxhuWWR8zkKfA6ZvoSdsxs7hMfdgJToZhmgpdYh2wc1kz@dhfs@SZfmnxBbJj8w@VVSXUikh6zzoBuOROqJRtvTPzMZCbvO512JeWFsRFCFAuVSfwN7zKw3G4yN9PXovuN1DnrodQMFUQi43r72R6pBQd/rnZMoxtgHNSQpl9vsjT56h/0PgE&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f#).
`,` Flatten the board matrix. To work with 2d adjacency matrices, we must represent the board in 1d. In the end `⍴⍴` will put the result into the correct shape.
`,∘.(...),` Create a matrix by applying the inner function between each pair of values:
`=` are the values equal (of same color)?
`≠` XOR
`0=⊣` is the right one a zero.
This connects places of equal colors, and colored pieces to blank squares in one direction.
`(2>+⍥|.-)⍨⍤,⍤⍳⍤⍴` adjacency matrix for horizontal and vertical neighbourhood on the grid.
`,⍤⍳⍤⍴` Indices of the grid, flattened
`(...)⍨⍤` Table for all pairs of these values
`2>+⍥|.-` Is the absolute distance less than 2?
The final adjancency table is generated by `∧` of the two matrices, then `∨.∧⍨⍣≡` finds the transitive closure (The matrix that has 1's where there is a valid path between two nodes)
`,+.<` Magic inner product, counting for each node on the grid, to how many blank spaces it is connected.
`⍴⍴` Reshape the resulting flat vector into a matrix of the same shape of the input.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 37 bytes
Port of my APL answer. Really not the right language for the job but still slightly beats it.
```
˜©DδÊ®Ā^IāsнgLâDδαO2‹*ΔDøδ*OĀ}®›øOIgä
```
[Try it online!](https://tio.run/##yy9OTMpM/f//9JxDK13ObTncdWjdkYY4zyONxRf2pvscXgQUO7fR3@hRw06tc1NcDu84t0XL/0hD7aF1jxp2Hd7h75l@eMn/Q7v/R0cb6CgAkRGQjNVRAPEMwQiJZ4DgGUFVxv7X1c3L181JrKoEAA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES7), ~~153 135 133~~ 130 bytes
Expects a matrix of integers with \$0\$ for empty, \$1\$ for white, \$2\$ for black.
```
f=(m,V,X,Y,n=0,M=m.map((r,y)=>r.map((v,x)=>V?n+=V[k=[x,y]]|(x-X)**2+(y-Y)**2-1?0:(V[k]=1,v-V)?!v:f(m,V,x,y):f(m,[v],x,y))))=>V?n:M
```
[Try it online!](https://tio.run/##VY8xb4MwEIV3/4orC3ZirKRjIidTu0UMkRBRwoCISZ2CnRqKQG1/O7Udoqq@4e59fn46X/Mubwojb22k9FmMY8lxTROa0gNVfEF3vGZ1fsPY0IHwjbmLjvZWJFs158nxnR97OmTZN@6jlMxmz3M8RAc3RMvtYoWtI@NL2kUJ2T51q9Ln2xfEj8cu88Ien7jajUZ8fEojcFg2IWFG5OdXWYn9oAq8IKzV@9ZIdcGENbdKtjg4qZMKCCu1ecmLN9wA38AXAqhECzVwaP6M1uY@YJzFPDBMtHA0YHEaMKnOoo9LXNi11jaq0KrRlWCVvmC79b@Uq5YKhxASMo0nFRKYg@9r9ENGBgxiYIhBauveme@x5xOIEUptWY5iNFFnd3epvXXK2n8B "JavaScript (Node.js) – Try It Online")
### How?
When defined, the parameter \$V\$ is a singleton array whose value is the reference color that triggered the recursion and whose underlying object is used to store the positions of the connected squares that were already visited.
On the initial call, we walk through the matrix and simply trigger a recursive call for each square \$v\$ at position \$(x,y)\$:
```
f(m, [v], x, y)
```
On subsequent calls, we receive \$V\$ along with the reference position \$(X,Y)\$. We walk through the matrix again, this time applying the following logic:
```
n += // update the liberty counter n:
V[k = [x, y]] | // if this square was already visited
(x - X) ** 2 + // or the squared Euclidean distance between
(y - Y) ** 2 - 1 ? // (x, y) and (X, Y) is not equal to 1:
0 // do nothing
: // else:
( //
V[k] = 1, // mark this square as visited
v - V // NB: V is coerced to an integer
) ? // if v is not equal to V:
!v // increment n if v = 0
: // else:
f(m, V, x, y) // do another recursive call
```
**NB**: We do not prevent the recursion from starting when the reference square is empty. This is harmless because we simply flood-fill the empty space without updating \$n\$.
[Answer]
# Python3, 510 bytes:
```
E=enumerate
def S(b,x,y):
for X,Y in[(0,1),(0,-1),(1,0),(-1,0)]:
try:
if(A:=x+X)>=0 and(B:=y+Y)>=0:yield(A,B,b[A][B])
except:1
def f(b):
a,s=[],[]
while(o:=[(x,y,c)for x,t in E(b)for y,c in E(t)if c in['X','O']and(x,y,c)not in s]):
q,A=[o[0]],[]
while q:x,y,c=q.pop(0);A+=[(x,y,c)];q+=[i for i in S(b,x,y)if i[-1]==c and i not in A]
a+=[A];s+=A
for i in a:
for x,y,_ in i:b[x][y]=str(len({k for X,Y,_ in i for k in S(b,X,Y)if k[-1]=='.'}))
return '\n'.join(map(' '.join,b)).replace('.','0')
```
[Try it online!](https://tio.run/##dZLBjpswEIbP9VNMc7HdOAiSPVRErkSkvTaHXlh5rRUkRuuGBQJeNajqs6djnGSrtiskhvH8/3zjEd3onttm9bnrz@d7aZrXF9MXzpC9qeAbK8VJjDwlULU95OIBbKNYLBIu8L3wIRExvhc@aNSB60cfwFYsS@VpnvMvMoai2bNNKsf5g0/T0Zp6zzKxEaXKtNpojhZz2pnOpcmErljpsYUYpNJCaQI/nm1tWJtKxXAmseN@pJNwOBLco9qneBxSx20F/lvRnAq6pdpPEHxNO3kG7QFwFJlUrYp1oAQMHNNJK49R13Ys5utsfuPq9RETO63E@k7XNSHSqkWipdz5C2Pxgsp84wJNmV4Pc5mRN2/hZwg3GcWTP7FpqU5ajVoOrme1adjPw3X9F8WUHq5oPPfoQ0DTiP7iuM7euNe@AfrY0Oh7axv2UnSMQkhEyXnUm64udoahQ9CY8rPfu2ufyrbo92zA7Xy4NFGqnJBloCOshI8SsJu@XaSytTM9@9o2RsAQDV1tHfN0zjUhZQLyrfdsNosggi1EJIIcnxCjKW79OSo4KZf/mILYS3PYEp/dxKv/iLFbKN79VcxJThBGtiS4u942juFPl/BrQhf00zL@o7R6v3T3fmnJ@fk3)
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 157 bytes
```
function E=f(B)
A=([W,k]=(l=@bwlabel)(B==1,4))+([R,n]=l(B>1,4))+k.*~~R;
E=0*B;
for x=1:n+k
E=E+(X=A==x)*nnz(conv2(X,[0 1 0;1 0 1;0 1 0],'same').*~B);
end
end
```
[Try it online!](https://tio.run/##JU5BCoMwELznFbl1o6Ek0lPDlhrwA14qiAe1CsU0gdZa6cGvp1EZhlmGmWFdO9ZT533/se34cJZm2INmJEUob3yoEAxem6@pm84w0IiSnxiLocy5rdCAvuzGcIyWJVckQxFpRXr3ojPKs42HYGUxFJgiziyy9gets1MCBS8FlVSoQCrVdlf88K6f3YGFNc0U6ex9pdcYsnta0CRgV7Gp3Jpkfdv/AQ "Octave – Try It Online")
I suspect there are further improvements that can be made.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 157 bytes
```
m->matrix(#m~,#m,i,j,p=0*m;a=p[i,j]=m[i,j];while(s=0;p!=q=matrix(#m~,#m,k,l,matrix(#m~,#m,u,v,normlp([u-k,l-v],1)<2&&p[u,v])&&!if(a-b=m[k,l],b||s++)),p=q);s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VU5bSgMxFN1K2sKQ2BtI8iVc0x10BSFICo5GJzWdR6tQdCEiDIi4JnfjTad-lHycnBf3fPzk0Mbb-zx-1cx-D30tr38_k1yl0LfxhS_SGywSRHiEbNVVwmCzI-ZtOgEeHmJzxzurMM_szl7WnqCBS2WAPWyf29Rk7gZJvtx70OLGVFV2ZHpRVbNY8yA3dIF8D5vjsVsuhaABO4GdOI98Dzk3rzwxuWK5jduevvNC5qzmieLMOQUKDChUoOlNqE5oiu6BrUPP3SQbXzoaNVIADRbb_TdLQIPBwkrTn2eM44R_)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 88 bytes
```
WS⊞υι≔Eυ⟦⟧θFLυFL§υι«≔§§υικη≔⁰ζF№αη«Eυ⭆μ⎇⁼ξηψξJκι¤*FLυFL§υι«Jνμ≧⁺∧№KV*⁼KK.ζ»⎚»⊞§θιζ»Eθ⪫ιω
```
[Try it online!](https://tio.run/##lVHLTsMwEDw7X7HqaYNMxJ1TVYHUCmgEFaqEOFitSaw4mzaxaQvqt4d1HjyOHLzS7I7HM@tNrupNpWzbHnJjNeCcdt49udpQhnEMqW9y9BJMfB1Nm8ZkhPdqFzovr7GEPbffqhrwTlPmmMlXfuOpm9NWH3sFnn1GYlAZJ38YEgo@OYuOtCsJHwF2orPKk0MVGJ2USNmmGw31pgMoJax0Tao@4c3eK9vgMdyRcJJwZBtBUCx8uVtVWPTZhLg11uLkYtKBf2b6ViMJZScg2Ecf4dFkucPU@kbClLZDiFTr4rmiB@1LRYTsLTwtYfAbxl0zmcTxsAJx5jOzWtUYIKPuc0Y7@36BgXqOfhbD7UVlCI2EQ0jetkmyTKJkvQ4l4bJk2F6@2y8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings of letters (indicating a group) and `.` and outputs a list of strings of digits. Explanation:
```
WS⊞υι≔
```
Read the input array.
```
Eυ⟦⟧θ
```
Create an empty output array of the same height.
```
FLυFL§υι«
```
Loop over all of the cells in the array.
```
≔§§υικη
```
Get the current cell.
```
≔⁰ζ
```
Assume this cell is empty.
```
F№αη«
```
If this cell is a letter, then:
```
Eυ⭆μ⎇⁼ξηψξ
```
Write the array to the canvas, but replacing that letter with the null character.
```
Jκι¤*
```
Fill the canvas with `*` starting at the current cell.
```
FLυFL§υι«
```
Loop over all of the cells again.
```
Jνμ≧⁺∧№KV*⁼KK.ζ
```
Keep a running total of any liberties found.
```
»⎚
```
Clear the canvas after counting the liberties ready for the next iteration or the output.
```
»⊞§θιζ
```
Save the result to the output array.
```
»Eθ⪫ιω
```
Output the final array of liberties. Note that this format smashes digits together so is only suitable for values up to `9` but the `ω` can be replaced with a separator character such as a space or comma.
] |
[Question]
[
Inspired by certain puzzles on *Flow Free: Warps*.
## Background
We all know that L-triominos can't tile the 3x3 board, and P-pentominos can't tile the 5x5 board. But the situation changes if we allow the board to wrap around in both dimensions:
### L-triominos can tile 3x3 toroidal grid
The 3rd tile wraps around through all four edges.
```
┌ ┌─┐ ┐
│ │3
┌─┤ └─┐
│ │2 │
│ └─┬─┘
│1 │
└───┘ ┘
```
### P-pentominos can tile the 5x5 toroidal grid
The 5th tile wraps around through all four edges.
```
┌ ┌───┬─┐ ┐
│ │ │
┌─┘ │ └─┐
│ 1 │2 │
├─────┤ │
│ 3 │ │
│ ┌─┴─┬─┤
│ │ │ │
└─┬─┘ │ ╵
│ 4 │5
└ └─────┘ ┘
```
Note that, in both cases, wrapping around in only one dimension doesn't allow such tiling.
In case the Unicode version is hard to read, here is the ASCII version:
```
3 2 3
1 2 2
1 1 3
5 1 1 2 5
1 1 1 2 2
3 3 3 2 2
3 3 4 4 5
5 4 4 4 5
```
## Challenge
Given a polyomino and the size (width and height) of the toroidal grid, determine if the polyomino can tile the toroidal grid. The polyomino can be flipped and/or rotated.
A polyomino can be given in a variety of ways:
* A list of coordinates representing each cell of polyomino
* A 2D grid with on/off values of your choice (in this case, you *cannot* assume that the size of the grid defining the polyomino matches that of the toroidal grid)
The output (true or false) can be given using the truthy/falsy values in your language of choice, or two distinct values to indicate true/false respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
The polyomino is given as the collection of `#` symbols.
### Truthy
```
# (singleton, a.k.a. monomino)
5x7 (or any size)
--------
## (domino)
4x3 (or any even size)
--------
#
## (L-triomino)
3x3 (as shown above)
--------
##
### (P-pentomino)
5x5 (as shown above)
--------
##
## (Z-tetromino)
4x4 (left as an exercise to the reader)
--------
###
#
# (V-pentomino)
5x5
--------
####
#
### (a polyomino larger than the grid is possible)
4x4
--------
###
###
### (single polyomino can cover the entire grid, and can wrap multiple times)
3x3
```
### Falsy
```
## (domino)
3x5 (or any odd sizes)
--------
###
#
1x8
--------
# #
### (U-pentomino)
5x5
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~300~~ ~~265~~ 163 bytes
*-35 bytes after suggestions from @xnor, @ovs, and largely @user202729 (removing evenly divisible check allowed for a one-liner + lambda)*
*-102 bytes following encouragement + general suggestions by @user202729*
```
lambda l,w,h:all(w*h-len({((e-(p&4)*e//2)*1j**p+p/8+p/8/w*1j)%w%(1j*h)for e in l for p in c})for c in combinations(range(8*w*h),w*h/len(l)))
from itertools import*
```
Takes input as a list of complex coordinates of each cell of the polyomino. Outputs False for Truthy and True for Falsey (quirky de Morgan optimization).
[Try it online](https://tio.run/##XVLtbusgDP3PU1hU2yBji/ox3apS7ot0@8Ey2nBHgAtEaTTt2TsgS5cuErZzfOzjxNghNEavzsfq@ax4@/rGQbGeNTuuFOmL5kEJTT4IEQ/E3m5oIcpyRYvlv6Kw97bcplP28Z3e9Dckwg09GAcCpAYFKbQprD8zXOfYtK9S8yCN9sRxfRRkW0QlyqIpk5yilKKDMy3IIFwwRnmQrTUuFOeae@Ghgj1aQHBdaIYYEIxxdIvo2BP7Q9kMy@CGrSM4QmiE1hma8bL5bvF0YS/QpcXmmp8LflR/BFIKAEYzL57SKOMpPeWnYQ5ceTH8nn49nydKJmzJtrnCN67T7xAMiJOouyDgfyfrdzWgqQW6fNWKoheU9uDThvMu0t/c5Ul85R@9VTIQ/Kwx3S93LxlX1X4MUuHAlNR5uUJ3rXA8COLp2GDinFjdcHfNSVUzWnrkARKvqvACX2ey6iO3Vug3crof0u3KBOukDnF4uGN3DPpv3zDA1V/M4EjyzaXnLw "Python 2 – Try It Online") with many testcases. Since this brute-forces, I have commented out a few cases to run fast enough for TIO.
Thoroughly commented:
```
lambda l,w,h:
all( # we want any configuration to work, but De Morgan gives any(L==len) <==> not all(L!=len) <==> not all(L-len)
w*h-len( # if two polyominos in a configuration overlap, then there are duplicate cells
# so the length of the set is less
{ # create a set consisting of each possible position+orientation of L/len(l) polyominos:
( # here, e is a single cell of the given polyomino
( # reflect e across the imaginary axis if p >= 4 (mod 8)
e- # e-e.real*2 = e-e//.5 reflects across the Im axis
p&4 # Only reflect if the 2^2 bit is nonzero: gives 4* or 0* following
*e//2 # floor(z) = z.real when z is complex, so
) # e//2 (floor division) gives z.real/2 (complex floor division only works in Python 2)
*1j**p # rotate depending on the 2^0 and 2^1 bits. i**x is cyclic every 4
+p/8 # translate horizontally (real component) by p>>3 (mod this later)
+p/8/w*1j # translate vertically (im component) by p>>3 / w
)%w%(1j*h) # mod to within grid (complex mods only work in Python 2)
for e in l # find where each cell e of the given polyomino goes
for p in c # do this for each c (each set of position+orientation integers)
}
)
for c in combinations( # iterate c over all sets of w*h/len(l) distinct integers from 0 to 8*L-1
range(8*w*h) # each of these 8*L integers corresponds to a single position/orientation of a polyomino
# Bits 2^0 and 2^1 give the rotation, and 2^2 gives the reflection
# The higher bits give the position from 0 to L=w*h-1 ==> (0,0) to (w-1,h-1)
,w*h/len(l) # w*h/len(l) is the number of polyominos needed since len(l) is the number of cells per polyomino
# can't switch to *[range(8*w*h)]*(w*h/len(l)) because Python 3 does not allow short complex operations as above
)
)
from itertools import*
```
A new 169-byte solution that replaces `combinations` with recursion:
```
g=lambda l,w,h,k=[]:all(g(l,w,h,k+[((e-(p&4)*e//2)*1j**p+p/8+p/8/w*1j)%w%(1j*h)for e in l])for p in range(8*w*h))if w*h>len(k)else len(set(k))-w*h
from itertools import*
```
This has the advantage of removing `combinations` (12 characters on its own) and one for loop, but the self-invocation takes many bytes. Currying would not save length.
[Answer]
# JavaScript (ES7), 233 bytes
Takes input as `(w)(h)(p)`, where \$p\$ is a binary matrix describing the polyomino. Returns \$0\$ or \$1\$.
Similar to my original answer, but uses a more complex expression to update the cells of the matrix instead of explicitly rotating the polyomino.
```
w=>h=>g=(p,m=Array(w*h).fill(o=1))=>+m.join``?(R=i=>i--?m.map((F,X)=>(F=k=>p.map((r,y)=>r.map((v,x)=>k|=v?m[Z=i&2?p[0].length+~x:x,~~(X/w+(i&1?Z:W))%h*w+(X+(i&1?W:Z))%w]^=1:0,W=i&4?p.length+~y:y))&&k)(F()||g(p,m)))|!o||R(i):0)(8):o=0
```
[Try it online!](https://tio.run/##hZDRboJAEEXf/Qr7UJzRlbKtTZpNBtIXPsA00UhpJFZhFViCViQh/jouIba0MWkyDzt3zt47u9vgGOxXucwO41R9rusN1QXZEdkhQcYSes3zoIRiGKG5kXEMijgi2aPE3CqZLpcOTEmSLcdjJzGTIANw2VwD4NKO7KyVclZqKW@bIzvpZlfR0Um8BUnj0ck8yzfjdRoeotH5JE7sfIb5QzECaXBnIWaI99FQt/NWmYmFVgr/g7iw2ExbTJzs@34pSkTD2CG4gFUVNs9AxOpOVdUUJAoL4QWFIqteqXSv4rUZqxAG3lv@dYhKf4C9rr6BJ2zK6/X7Hvd7Pv6dP2NT7ZxxZvnseryJTzp2t4luYMeuRX@xg/fUc4N4/8/Wt2N48w8/e/NrkKUzG7y@AA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), ~~311 ... 252~~ 250 bytes
Takes input as `(w)(h)(p)`, where \$p\$ is a binary matrix describing the polyomino. Returns a Boolean value.
Not quite as desperately long as I was expecting. :p
```
w=>h=>g=(p,m=Array(w*h).fill(o=1),P)=>+m.join``?[...13**7+''].some(i=>(p.sort(_=>i-7).map((r,y)=>r.map((v,x)=>(P[x]=P[x]||[])[y]=v),P=[]),m.map((F,X)=>(F=k=>P.map((r,y)=>r.map((v,x)=>k|=v?m[~~(X/w+y)%h*w+(X+x)%w]^=1:0))&&k)(F()||g(p,m))),p=P,!o)):o=0
```
[Try it online!](https://tio.run/##hY9Ba4NAEIXv@RXpIXFGN1uXtKQExtCLZw89BLbbRtIkmqgrmmoE6V@3igRsSSkMy5udb9@bPfqFn2@zMD3PEv2xa/bUlOQE5BwIUhbTc5b5FZRmgHwfRhFoEsg8JMeK@VGHyWazkpxzMTfNhWUYiuc63kFIDqStzM7wTk44WyCP/RQgY1X7NOubgl3aBjx5UdQddS0VykpR0SZQq1ncgy5bd6BLJ3K8P41ONRWrWH59wfq@tCqcBGZpwdq64KRUbySWNuJ0ekJwAev60P0OEVlKHrvTiEtNdrPVSa6jHY/0AQz5kn2eg0oZOBre72GOXcnReCyFGin8PX/Ervo5E8xW7Cpv4g8Du9vEMHBg16M/WOM1ka4f5f9sfTtGIDwN9hbXILvN7PDmGw "JavaScript (Node.js) – Try It Online")
### How?
The following code builds all possible transformations \$P\$ of the polyomino \$p\$:
```
[...13 ** 7 + ''] // this expands to ['6','2','7','4','8','5','1','7']
.some(i => // for each value i in the above list:
( p.sort(_ => i - 7) // reverse the rows of p[], except when i = '8'
.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
( P[x] = // transpose p[y][x]
P[x] || [] ) // to P[x][y]
[y] = v //
), // end of inner map()
P = [] // start with an empty array
) // end of outer map()
(...) // more fun things happen here!
p = P, // get ready for the next transformation
!o // success if o is cleared
) //
) // end of some()
```
We use a flat array of \$w\times h\$ entries to describe the matrix. All of them are initially set to \$1\$.
The function \$F\$ inserts the polyomino in the matrix at the position \$(X,Y)\$ by XOR'ing the cells. It returns \$0\$ if the operation was done without setting any cell back to \$1\$.
```
F = k => // expects k undefined for the first call
P.map((r, y) => // for each row r[] at position y in P[]:
r.map((v, x) => // for each value v at position x in r[]:
k |= // update k:
v ? // if v is set:
m[~~(X / w + y) // toggle the value at (X + x, Y + Y),
% h * w + // taking the wrapping around into account
(X + x) % w //
] ^= 1 // k is set if the result is not 0
: // else:
0 // leave k unchanged
) // end of inner map()
) && k // end of outer map(); return k
```
For each position \$(X,Y)\$ in the matrix:
* We do a first call to \$F\$. If successful, it is followed by a recursive call to the main function \$g\$.
* We just need to call \$F\$ a second time to remove the polyomino -- or to clear the mess if it was inserted at an invalid position.
Hence the code:
```
F(F() || g(p, m))
```
The recursion stops when there's no more \$1\$'s in the matrix (success) or there's no more valid position for the polyomino (failure).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~120~~ 115 bytes
```
NθNηWS⊞υ⌕Aι#≔⟦⟧ζFθFηF²«≔EθEη⁰εFLυF§υμ¿λ§≔§ε⁺κν﹪⁺ιμη¹§≔§ε⁺ιμ﹪⁺κνη¹F²F²⊞ζ↨⭆⎇μ⮌εε⪫⎇ν⮌ξξω²»≔…ζ¹υFυFζF¬&ικ⊞υ|ικ⁼⊟υ⊖X²×θη
```
[Try it online!](https://tio.run/##hVJLb8IwDD7TX2HBJZEyaVTcOAHbJKbB0MZt2qGjhkSkKSQNBab99s4p5aFdFilx7M/@/EgWMrGLPNFVNTYbX0x99oWWbXk/utUl6aVUGoHV5vfCKrNinMPMO8m8gCdl0oHWTAlod9qc/AfOqZVhH58CjqQucwvEC7WUjYw5fEetxnOSbNhWQBBSwD3nApACW7XnC5pVQZl4EzkoxibFfUidkU0tgWkOJ6YzdpYoYKa9Y2sBJrBO8tTrnNU2FeIFSNpd3gfUDv9hqSP@sNTMF5am5PjaZD2lo4Bh4pCdhhfanKM1iT2wTMAb7tASiHXXAp5zZS64ueJ7wsIuQwlxmPPPedKjw0LjSOabkKlLsD@P3TeVHBs5zQs2VEWpHA5MGjpa85u3bKBX2yD9aEYVF@xx6xPt2IwyeKJ/wIXFDE2BKdlK@iaxgLnK0IVnlDysflX1ol7UoRUBwOmge3W3078 "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order width, height, newline-terminated polyomino and outputs a Charcoal boolean i.e. `-` only if the polyomino tiles the torus. Explanation:
```
NθNη
```
Input the size of the grid.
```
WS⊞υ⌕Aι#
```
Input the polyomino and convert it to a list of horizontal indices.
```
≔⟦⟧ζ
```
Start building up a list of polyomino placements.
```
FθFηF²«
```
Loop through each vertical and horizontal offset and direction.
```
≔EθEη⁰ε
```
Start with an empty grid.
```
FLυF§υμ
```
Loop over each cell of the polyomino...
```
¿λ§≔§ε⁺κν﹪⁺ιμη¹§≔§ε⁺ιμ﹪⁺κνη¹
```
... place the optionally transposed cell in the grid, but offset by the outer indices.
```
F²F²⊞ζ↨⭆⎇μ⮌εε⪫⎇ν⮌ξξω²
```
For each of four reflections of the grid, push the grid to the list of placements, represented as a base 2 integer (e.g. a grid with just the bottom right square filled would be 1 etc.)
```
»≔…ζ¹υFυ
```
Start a breadth first search using the first placement.
```
Fζ
```
Loop over each placement.
```
F¬&ικ
```
If this placement does not overlap the grid so far...
```
⊞υ|ικ
```
... then push the merged grid to the list of grids.
```
⁼⊟υ⊖X²×θη
```
Check whether we pushed a completed grid. (This must be the last entry because any incomplete grid must by definition have fewer polyominoes and would therefore have been discovered earlier.)
] |
[Question]
[
>
> Yes, It's basically [You're a Romanizer, Baby](https://codegolf.stackexchange.com/questions/65272/), but *harder*. like, *way* harder.
>
>
>
Learning Korean is HARD. at least for a person outside Asia. But they at least have the chance to learn, right?
# What you must do
You will be given a Korean Statement. For example, `안녕하세요`. You must convert the input to its Roman pronunciation. For the given example, the output can be `annyeonghaseyo`.
# Now it gets technical
A Korean character has three parts, Starting consonant, Vowel, and Ending consonant. The Ending consonant may not exist in the character.
For example, `아` is `ㅇ`(Starting consonant) and `ㅏ`(Vowel), and `손` is `ㅅ`(Starting consonant), `ㅗ`(Vowel), and `ㄴ`(Ending consonant).
Evert consonant and vowel has its pronunciation. The pronunciation for each consonant is as following.
```
Korean ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ
Romanization Starting g kk n d tt r m b pp s ss – j jj ch k t p h
Ending k k n t – l m p – t t ng t – t k t p h
```
( - means no pronunciation or not used. you do not have to handle them.)
and Pronunciation for each vowels is as following.
```
Hangul ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ
Romanization a ae ya yae eo e yeo ye o wa wae oe yo u wo we wi yu eu ui i
```
# Now its the real hard part
The consonant's pronunciation changes by the Ending consonant in before. The pronunciation for every Starting/Ending consonant is as the following image.[](https://i.stack.imgur.com/mGfVJ.png)
(You do not have to do the hyphen between pronunciations. Its unnecessary. If a cell has two or more pronunciations, choose one. If there's no ending consonant, use the original pronunciation.)
# Examples
```
Korean => English
안녕하세요 => annyeonghaseyo
나랏말싸미 듕귁에달아 => naranmalssami dyunggwigedara //See how the ㅅ in 랏 changes from 't' to 'n'
```
Example suggestion welcomed. You can get answers for your own inputs [here](http://roman.cs.pusan.ac.kr/input_eng.aspx). (The one in "General text", Revised is what I'm asking for)
[Answer]
# Python 3.6, ~~400~~ 394 bytes
**Edit:** Thanks to [RootTwo](https://codegolf.stackexchange.com/users/53587/roottwo) for -6 bytes.
This is my first submission on CodeGolf, so I'm pretty sure there are better ways to golf it, but I thought I'd still post it, as nobody has mentioned the key idea yet, and this is still significantly shorter than other solutions.
```
import re,unicodedata as u
t='-'.join(u.name(i)[16:]for i in input()).lower()
for i in range(19):t=re.sub('h-[gdb]|(?<!n)([gdbsjc]+)(?!\\1)(?!-?[aeiouyw]) gg dd bb -- - h(?=[nmrcktp])|hh hj l(?=[aeiouyw]) l[nr] [nt][nr] tm pm [pm][nr] km kn|kr|ngr c yi weo'.split()[i],([lambda m:'ktpttt'['gdbsjc'.index(m[0][-1])]]+'kk,tt,pp, ,,t,c,r,ll,nn,nm,mm,mn,ngm,ngn,ch,ui,wo'.split(","))[i],t)
print(t)
```
## How it works
The solution attempts to exploit the fact (which I learned from the original Japanese romanization challenge) that romanized character names are accessible through Python's unicodedata module. For Korean language, they take the form of `HANGUL SYLLABLE <NAME>`. Unfortunately, processing these names to meet the provided specification and to cover all the syllable combination scenarios still requires quite a bit of effort (and bytes).
The obtained character names list all consonants in their voiced form anywhere in the syllable, e.g. `GGAGG` for `깎`, `R/L` are transcribed as intended (starting `R`, ending `L`), and `CH` is given as `C` (this actually saves us a bit of headache).
First of all, we strip off the `HANGUL SYLLABLE` part (first 16 chars), mark the syllable boundaries with `-`, and then apply a series of RegEx'es to do the conversions.
The first RegEx looks particularly nasty. What it basically does, is conversion of starting consonants into their ending equivalents (also removing the extra letter in case of double consonants), when they are not followed by a vowel, or for some letters - when they are preceded by `h`. The `(?<!n)` lookbehind prevents matching `g` which is part of `ng`, and `(?!\\1)` lookahead ensures that we don't convert, e.g., `ssa` to `tsa`.
The next few RegEx'es convert starting double consonants into their unvoiced equivalents. Here's where `-` separators also come in handy as they help discerning boundary collisions (`g-g`) from double consonants (`gg`). Now they can also be removed.
Next, we handle the remaining `h+consonant` combinations, `l->r` before vowels, and other special cases.
Finally, we restore `c` to `ch`, and resolve some other pecularities of our incoming char names, such as `yi` instead of `ui` and `weo` instead of `wo`.
I'm not an expert in Korean and can't comment much more, but this seems to pass all the tests posted in the task and on Github.
Obviously, a few more bytes could be shaved off, if the output is acceptable in uppercase, as this is what we get from the name function.
[Answer]
# JavaScript (ES6), 480 bytes (WIP)
This is an early attempt based on the current specs to get the ball rolling. It may require some fixing when the questions in the comments are addressed.
```
s=>[...s].map(c=>c<'!'?c:(u=c.charCodeAt()-44032,y='1478ghjlmnpr'.search((p=t).toString(36)),t=u%28,u=u/28|0,v=u%21,x=[2,5,6,11,18].indexOf(u=u/21|0),~x&~y&&(z=parseInt(V[y+68][x],36))>10?V[z+69]:V[p+40]+V[u+21])+V[v],t=0,V='8a6y8ye6e46ye4y64w8wa6o6y4u/w4w6wi/yu/eu/ui/i/g/k21d/t7r/3b/p0s/ss95j5ch/270h922/197l999930/77ng/77270h/bbcd6afaa8gghi5ffak8alaa8llmn4gghp8abaa8gghq5gghr5ggha5gghs8ng1ng3g/2ll/n1n3d/7r/m1m3b/0s/5ch/h'.replace(/\d/g,n=>'pnkmojeta/'[n]+'/').split`/`).join``
```
### Test cases
```
let f =
s=>[...s].map(c=>c<'!'?c:(u=c.charCodeAt()-44032,y='1478ghjlmnpr'.search((p=t).toString(36)),t=u%28,u=u/28|0,v=u%21,x=[2,5,6,11,18].indexOf(u=u/21|0),~x&~y&&(z=parseInt(V[y+68][x],36))>10?V[z+69]:V[p+40]+V[u+21])+V[v],t=0,V='8a6y8ye6e46ye4y64w8wa6o6y4u/w4w6wi/yu/eu/ui/i/g/k21d/t7r/3b/p0s/ss95j5ch/270h922/197l999930/77ng/77270h/bbcd6afaa8gghi5ffak8alaa8llmn4gghp8abaa8gghq5gghr5ggha5gghs8ng1ng3g/2ll/n1n3d/7r/m1m3b/0s/5ch/h'.replace(/\d/g,n=>'pnkmojeta/'[n]+'/').split`/`).join``
console.log(f("안녕하세요"))
console.log(f("나랏말싸미 듕귁에달아"))
```
### How?
Once decompressed, the array **V** contains the following data:
```
00-20 vowels
a/ae/ya/yee/eo/e/yeo/ye/o/wa/wae/oe/yo/u/wo/we/wi/yu/eu/ui/i
21-39 starting consonants
g/kk/n/d/tt/r/m/b/pp/s/ss//j/jj/ch/k/t/p/h
40-67 ending consonants
/k/k//n///t/l////////m/p//t/t/ng/t/t/k/t/p/h
68-79 indices of substitution patterns for consecutive consonants
('a' = no substitution, 'b' = pattern #0, 'c' = pattern #1, etc.)
bbcde/afaaa/gghij/ffaka/alaaa/llmno/gghpa/abaaa/gghqj/gghrj/gghaj/gghsa
80-97 substitution patterns
ngn/ngm/g/k/ll/nn/nm/d/t/r/mn/mm/b/p/s/j/ch/h
```
We split each Hangul character into starting consonant, vowel and ending consonant. We append to the result:
* `V[80 + substitution] + V[vowel]` if there's a substitution
* `V[40 + previousEndingConsonant] + V[21 + startingConsonant] + V[vowel]` otherwise
[Answer]
# Tcl, 529 bytes
```
fconfigure stdin -en utf-8
foreach c [split [read stdin] {}] {scan $c %c n
if {$n < 256} {append s $c} {incr n -44032
append s [string index gKndTrmbPsS-jJCktph [expr $n/588]][lindex {a ae ya yae eo e yeo ye o wa wae oe yo u wo we wi yu eu ui i} [expr $n%588/28]][string index -Ak-n--tl-------mp-BGQDEkFph [expr $n%28]]}}
puts [string map {nr nn
A- g An ngn Ar ngn Am ngm A kk
t- d p- b B- s D- j
nr ll l- r ln ll lr ll
A k B t G t D t E t F t
K kk T tt P pp S ss J jj C ch Q ng
- ""} [regsub -all -- {[tpBDEFh]([nrm])} $s n\\1]]
```
### Algorithm
1. Decomposition into lead, vowel, and tail indices
2. First lookup to intermediate alphabetic representation
3. Apply an initial pass for all the xn→nn/xm→nm transforms
4. Apply a final pass for the remaining transforms
This algorithm is crunched for purposes of the challenge; the trade-off being that the input is assumed to *not* contain any Latin alphabetic characters, nor to use characters outside the U+AC00 Hangul block as described in the challenge. Were this real code, I'd keep all the transforms in Jamo until the final pass.
I suppose I could throw some more brainpower at crunching those vowels and some of the repetitions in the lookup table, but this is as good as it gets from me today.
### Testing
Make sure you can supply UTF-8 input to the Tcl interpreter. This is most easily accomplished with a simple UTF-8 text file. Alas, Tcl still does not default to UTF-8 by default; this cost me 33 bytes.
Here’s my (currently pathetic) test file:
```
한
안녕하세요
나랏말싸미 듕귁에달아
```
### Notes
I know nothing about Korean language (except what little I have learned here). This is a first attempt, pending potential revision due to updates in the question specification.
And, about that, some additional information is useful. In particular, there is not a 1:1 correspondence between lead and tail consonants as seems to be suggested in the challenge. The following two sites helped immensely figuring that out:
• [Wikipedia: Korean language, Hangul](https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode)
• [Wikipedia: Hangul Jamo (Unicode block)](https://en.wikipedia.org/wiki/Hangul_Jamo_(Unicode_block))
] |
[Question]
[
Given two numbers n and m, evaluate the infinite power tower:
>
> n^(n+1)^(n+2)^(n+3)^(n+4)^... mod m
>
>
>
Keep in mind that ^ is right-associative. So 2^3^4 = 2^(3^4). Now how can you possibly assign a value to an infinite sequence of right-associative operators?
Define f(n,m,i) as the power tower containing the first i terms of the infinite power tower. Then there is some constant C such that for every i > C, f(n,m,i) = f(n,m,C). So you could say the infinite power tower converges on a certain value. We're interested in that value.
---
Your program must be able to compute n = 2017, m = 10^10 in under 10 seconds on a reasonable modern PC. That is, you should implement an actual algorithm, no bruteforcing.
You may assume that *n < 230* and *m* < 250 for the numerical limits in your programming language, but your algorithm must theoretically work for any size *n*, *m*. However your program **must** be correct for inputs within these size limits, intermediate value overflows are **not** excused if the inputs are within these limits.
Examples:
```
2, 10^15
566088170340352
4, 3^20
4
32, 524287
16
```
[Answer]
# Pyth, 23 bytes
```
M&tG.^HsgBu-G/GH{PGGhHG
```
Defines a function `g`, taking *m* and *n* in that order.
[Try it online](https://pyth.herokuapp.com/?code=M%26tG.%5EHsgBu-G%2FGH%7BPGGhHGgF&input=32%2C524287&test_suite=1&test_suite_input=1000000000000000%2C2%0A3486784401%2C4%0A524287%2C32%0A10000000000%2C2017&debug=0)
### How it works
```
M&tG.^HsgBu-G/GH{PGGhHG
M def g(G, H):
&tG 0 if G == 1, else …
PG prime factors of G
{ deduplicate that
u-G/GH G reduce that on lambda G,H:G-G/H, starting at G
(this gives the Euler totient φ(G))
gB hH bifurcate: two-element list [that, g(that, H + 1)]
s sum
.^H G H^that mod G
```
# Python 2, ~~109~~ 76 bytes
```
import sympy
def g(n,m):j=sympy.totient(m);return m-1and pow(n,j+g(n+1,j),m)
```
[Try it online!](https://tio.run/##RczRCsIgFMbx@z2Fl9OdQs82FkUPE8xKwaO4E@HTmxSx2x//70uFn5GwVhdSzCy2ElLpVnsXj54gyLO/funIkZ0l7oO8ZMuvTCIczI1WkeK7lX5o/WDAyzaqKTvi9oBgtFJmlt1fJhiVQr3DiDDjhKdlJ9Rm@Q21rB8 "Python 2 – Try It Online")
# Why it works
We use the following generalization of [Euler’s theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem).
**Lemma.** *n*2φ(*m*) ≡ *n*φ(*m*) (mod *m*) for all *n* (whether or not *n* is coprime to *m*).
*Proof:* For all prime powers *p**k* dividing *m*,
* If *p* divides *n*, then because *φ*(*m*) ≥ *φ*(*p**k*) = *p**k* − 1(*p* − 1) ≥ 2*k* − 1 ≥ *k*, we have *n*2φ(*m*) ≡ 0 ≡ *n*φ(*m*) (mod *p**k*).
* Otherwise, because *φ*(*p**k*) divides *φ*(*m*), Euler’s theorem gives *n*2φ(*m*) ≡ 1 ≡ *n*φ(*m*) (mod *p**k*).
Therefore, *n*2φ(*m*) ≡ *n*φ(*m*) (mod *m*).
**Corollary.** If *k* ≥ φ(*m*), then *n**k* ≡ *n*φ(*m*) + (*k* mod φ(*m*)) (mod *m*).
*Proof:* If *k* ≥ 2φ(*m*), the lemma gives *n**k* = *n*2φ(*m*)*n**k* - 2φ(*m*) ≡ *n*φ(*m*)*n**k* - 2φ(*m*) = *n**k* - φ(*m*) (mod *m*) and we repeat until the exponent is less than 2φ(*m*).
[Answer]
# [Haskell](https://www.haskell.org/), 156 bytes
`(?)` takes two `Integer`s and returns an `Integer`, use as `(10^10)?2017` (reversed order compared to OP.)
```
1?n=0
m?n=n&m$m#2+m#2?(n+1)
1#_=1
n#p|m<-until((<2).gcd p)(`div`p)n=m#(p+1)*1`max`div(n*p-n)(p*m)
(_&_)0=1
(x&m)y|(a,b)<-divMod y 2=mod(x^b*(mod(x*x)m&m)a)m
```
[Try it online!](https://tio.run/##XZDBbsIwDIbveYqITshuy9QEEDs06guM044MSlnRqFa7ES2jSH33Lu2EmBYpyh9/v23Zp6z@OpZlT1nBhjK7TqW9NG/N@ZWFdGczeWcehDRyEgT1qbpKDoKRScfoH6M/rKmux/ODASWMI@yAQ8J41hzrpt4KMb7SDGwDOpQq2qklhqMXFqGc73R0/84dX@qFflndIzpSq9@cCLe9SthEwrUyPKUn8nTgbgIcKBTKS40S7NmO4tmFm6IEiDU@f37k0iLs8@J7b9HtwQPr/L7aU9YOUWDfzhjB@oQC0mmKkSsE7ZTw1kEWHtwwzraucnmT2lCVQ7s7@DAKv0Vyxgyp738A "Haskell – Try It Online") (I put the cases to test in the header this time, since they use exponentiation notation.)
Curiously the slowest test case isn't the one with a speed limit (that's almost instant), but the `524287 ? 32` one, because `524287` is a much larger prime than appears in the factors of the other test cases.
# How it works
* `(x&m)y` is `x^y `mod` m`, or power mod, using exponentiation by squaring.
* `n#p` is the Euler totient function of `n`, assuming `n` has no smaller prime factors than `p`.
+ `m` is `n` with all `p` factors divided out.
+ If there are `k` such factors, the totient should itself get a corresponding factor `(p-1)*p^(k-1)`, which is calculated as `div(n*p-n)(p*m)`.
+ `1`max`...` handles the case where `n` wasn't actually divisible by `p`, which makes the other argument of `max` equal to `0`.
* The main function `m?n` uses that when `y` is large enough, `n^y `mod` m` is the same as `n^(t+(y`mod`t)) `mod` m`, when `t` is the totient of `m`. (The `t+` is needed for those prime factors `n` and `m` have in common, which all get maximized.)
* The algorithm stops because iterated totient functions eventually hit 1.
[Answer]
# Mathematica, 55 bytes
```
n_~f~1=0;n_~f~m_:=PowerMod[n,(t=EulerPhi@m)+f[n+1,t],m]
```
Examples:
```
In[1]:= n_~f~1=0;n_~f~m_:=PowerMod[n,(t=EulerPhi@m)+f[n+1,t],m]
In[2]:= f[2, 10^15]
Out[2]= 566088170340352
In[3]:= f[4, 3^20]
Out[3]= 4
In[4]:= f[32, 524287]
Out[4]= 16
In[5]:= f[2017, 10^10]
Out[5]= 7395978241
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 56 bytes
```
f(n,m)=if(m-1,lift(Mod(n,m)^((t=eulerphi(m))+f(n+1,t))))
```
[Try it online!](https://tio.run/##TctBCoMwEIXhfU/hcgZHyIyK3XiEXiEgaOyAsSHE86dBEXzLj/@FKWqzhpwd7ORxVAe@YdrUJfj85hMtQBqXY1ti@Cp4xLrENVPCshyi7gkcCFVsLPeIr5s6qlor5iFtqXrp5D08UAwP17mk@Q8 "Pari/GP – Try It Online")
] |
[Question]
[
## Introduction: Combinatory Logic
Combinatory logic (CL) is based off of things called *combinators*, which are basically functions. There are two basic "built-in" combinators, `S` and `K`, which will be explained later.
### Left-associativity
CL is *left-associative*, which means brackets (containing stuff) which are at the far-left of anther pair of brackets containing it can be removed, with its stuff released. For example, something like this:
```
((a b) c)
```
Can be reduced to
```
(a b c)
```
Where the `(a b)` is on the far-left of the bigger bracket `((a b) c)`, so it can be removed.
A much bigger example of left-association (square brackets are explanations):
```
((a b) c ((d e) f (((g h) i) j)))
= (a b c ((d e) f (((g h) i) j))) [((a b) c...) = (a b c...)]
= (a b c (d e f (((g h) i) j))) [((d e) f...) = (d e f...)]
= (a b c (d e f ((g h i) j))) [((g h) i) = (g h i)]
= (a b c (d e f (g h i j))) [((g h i) j) = (g h i j)]
```
Brackets can also be reduced when more than one pair wrap around the same objects. Examples:
```
((((a)))) -> a
a ((((b)))) -> a b
a (((b c))) -> a (b c) [(b c) is still a group, and therefore need brackets.
Note that this doesn't reduce to `a b c`, because
`(b c)` is not on the left.]
```
### Builtins
CL has two "built-in" combinators, `S` and `K`, which can switch objects (single combinators, or a group of combinators / groups wrapped around brackets) around like so:
```
K x y = x
S x y z = x z (y z)
```
Where `x`, `y` and `z` can be stand-ins for anything.
An example of `S` and `K` are as follows:
```
(S K K) x [x is a stand-in for anything]
= S K K x [left-associativity]
= K x (K x) [S combinator]
= x [K combinator]
```
Another example:
```
S a b c d
= a c (b c) d [combinators only work on the n objects to the right of it,
where n is the number of "arguments" n is defined to have -
S takes 3 arguments, so it only works on 3 terms]
```
The above are examples of normal CL statements, where the statement cannot be evaluated further and achieves an end result in a finite amount of time. There are non-normal statements (which are CL statements that do not terminate and will keep being evaluated forever), but they aren't within the scopes of the challenge and won't need to be covered.
If you want to learn more about CL, read [this Wikipedia page](https://en.wikipedia.org/wiki/Combinatory_logic).
## Task:
Your task is to make extra combinators, given the number of arguments, and what it evaluates to as input, which is given like so:
```
{amount_of_args} = {evaluated}
```
Where `{amount_of_args}` is a positive integer equal to the number of args, and `{evaluated}` consists of:
* arguments up to the amount of args, with `1` being the first argument, `2` being the second, etcetera.
+ You are guaranteed that argument numbers above the amount of args (so a `4` when `{amount_of_args}` is only `3`) won't appear in `{evaluated}`.
* brackets `()`
So examples of inputs are:
```
3 = 2 3 1
4 = 1 (2 (3 4))
```
The first input is asking for a combinator (say, `R`) with three arguments (`R 1 2 3`), which then evaluates into:
```
R 1 2 3 -> 2 3 1
```
The second input asks for this (with a combinator name `A`):
```
A 1 2 3 4 -> 1 (2 (3 4))
```
Given the input in this format, you must return a string of `S`, `K` and `()`, which when substituted with a combinator name and run with arguments, returns the same evaluated statement as the `{evaluated}` block when the command block is substituted back for that combinator name.
The output combinator statement may have its whitespace removed and the outer brackets removed, so something like `(S K K (S S))` can be turned into `SKK(SS)`.
If you want to test your program's outputs, @aditsu has made a combinatory logic parser (which includes `S`, `K`, `I` and even other ones like `B` and `C`) [here](http://ski.aditsu.net).
## Score:
Since this is a [metagolf](/questions/tagged/metagolf "show questions tagged 'metagolf'"), the aim of this challenge is to achieve the smallest amount of bytes in the output possible, given [these 50 test-cases](https://gist.github.com/Qwerp-Derp/53de04a0d0048d74c77a9240db279e59). Please put your results for the 50 test-cases in the answer, or make a pastebin (or something similar) and post a link to that pastebin.
In the event of a tie, the earliest solution wins.
## Rules:
* Your answer must return CORRECT output - so given an input, it must return the correct output as per the definition in the task.
* Your answer must output within an hour on a modern laptop for each test case.
* Any hard-coding of solutions is disallowed. However, you are allowed to hard-code up to 10 combinators.
* Your program must return the same solution every time for the same input.
* Your program must return a valid result for any input given, not just test-cases.
[Answer]
# [Haskell](https://www.haskell.org/), score 5017
This combines the dumbest possible algorithm for abstraction elimination ((λ*x*. *x*) = I; (λ*x*. *y*) = K*y*; (λ*x*. *M* *N*) = S(λ*x*. *M*)(λ*x*. *N*)) with a peephole optimizer used after every application. The most important optimization rule is S(K*x*)(K*y*) ↦ K(*xy*), which stops the algorithm from always blowing up exponentially.
The set of rules is configured as a list of string pairs so it’s easy to play around with new rules. As a special bonus of reusing the input parser for this purpose, S, K, and I are also accepted within the input combinators.
Rules are not applied unconditionally; rather, both the old and new versions are kept, and suboptimal versions are pruned only when their length exceeds that of the best version by more than some constant (currently 3 bytes).
The score is slightly improved by treating I as a fundamental combinator until the output stage rewrites it to SKK. That way KI = K(SKK) can be shortened by 4 bytes to SK on output without confusing the rest of the optimizations.
```
{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntMap as I
import qualified Data.List.NonEmpty as N
import System.IO
data Term
= V Int
| S
| K
| I
| A (N.NonEmpty (Int, Term, Term))
deriving (Show, Eq, Ord)
parse :: String -> (Term, String)
parse = parseApp . parse1
parseApp :: (Term, String) -> (Term, String)
parseApp (t, ' ':s) = parseApp (t, s)
parseApp (t, "") = (t, "")
parseApp (t, ')':s) = (t, ')' : s)
parseApp (t1, parse1 -> (t2, s)) =
parseApp (A (pure (appLen (t1, t2), t1, t2)), s)
parse1 :: String -> (Term, String)
parse1 (' ':s) = parse1 s
parse1 ('(':(parse -> (t, ')':s))) = (t, s)
parse1 ('S':s) = (S, s)
parse1 ('K':s) = (K, s)
parse1 ('I':s) = (I, s)
parse1 (lex -> [(i, s)]) = (V (read i), s)
ruleStrings :: [(String, String)]
ruleStrings =
[ ("1 3(2 3)", "S1 2 3")
, ("S(K(S(K1)))(S(K(S(K2)))3)", "S(K(S(K(S(K1)2))))3")
, ("S(K(S(K1)))(S(K2))", "S(K(S(K1)2))")
, ("S(K1)(K2)", "K(1 2)")
, ("S(K1)I", "1")
, ("S(S(K1)2)(K3)", "S(K(S1(K3)))2")
, ("S(SI1)I", "S(SSK)1")
]
rules :: [(Term, Term)]
rules = [(a, b) | (parse -> (a, ""), parse -> (b, "")) <- ruleStrings]
len :: Term -> Int
len (V _) = 1
len S = 1
len K = 1
len I = 3
len (A ((l, _, _) N.:| _)) = l
appLen :: (Term, Term) -> Int
appLen (t1, S) = len t1 + 1
appLen (t1, K) = len t1 + 1
appLen (K, I) = 2
appLen (t1, t2) = len t1 + len t2 + 2
notA :: Term -> Bool
notA (A _) = False
notA _ = True
alt :: N.NonEmpty Term -> Term
alt ts =
head $
N.filter notA ts ++
[A (N.nub (a N.:| filter (\(l, _, _) -> l <= minLen + 3) aa))]
where
a@(minLen, _, _) N.:| aa =
N.sort $ do
A b <- ts
b
match :: Term -> Term -> I.IntMap Term -> [I.IntMap Term]
match (V i) t m =
case I.lookup i m of
Just ((/= t) -> True) -> []
_ -> [I.insert i t m]
match S S m = [m]
match K K m = [m]
match I I m = [m]
match (A a) (A a') m = do
(_, t1, t2) <- N.toList a
(_, t1', t2') <- N.toList a'
m1 <- match t1 t1' m
match t2 t2' m1
match _ _ _ = []
sub :: I.IntMap Term -> Term -> Term
sub _ S = S
sub _ K = K
sub _ I = I
sub m (V i) = m I.! i
sub m (A a) =
alt $ do
(_, t1, t2) <- a
pure (sub m t1 & sub m t2)
optimize :: Term -> Term
optimize t = alt $ t N.:| [sub m b | (a, b) <- rules, m <- match a t I.empty]
infixl 5 &
(&) :: Term -> Term -> Term
t1 & t2 = optimize (A (pure (appLen (t1, t2), t1, t2)))
elim :: Int -> Term -> Term
elim n (V ((== n) -> True)) = I
elim n (A a) =
alt $ do
(_, t1, t2) <- a
pure (S & elim n t1 & elim n t2)
elim _ t = K & t
paren :: String -> Bool -> String
paren s True = "(" ++ s ++ ")"
paren s False = s
output :: Term -> Bool -> String
output S = const "S"
output K = const "K"
output I = paren "SKK"
output (V i) = \_ -> show i ++ " "
output (A ((_, K, I) N.:| _)) = paren "SK"
output (A ((_, t1, t2) N.:| _)) = paren (output t1 False ++ output t2 True)
convert :: Int -> Term -> Term
convert 0 t = t
convert n t = convert (n - 1) (elim n t)
process :: String -> String
process (lex -> [(n, lex -> [((`elem` ["=", "->"]) -> True, parse -> (t, ""))])]) =
output (convert (read n) t) False
main :: IO ()
main = do
line <- getLine
putStrLn (process line)
hFlush stdout
main
```
[Try it online!](https://tio.run/##lVdtc9s2DP6uX4G5vYa8OF7l2M7L1b1lt7anKXN3p65fUp@rxEqtmyy7Ft2Xrfvt2QOQlGRnuW1xIoMPHoIACILKIq1@z4ri7u7Po0d0eTF59dvFqxf0Ns8@/5oak23Kih4d/RUE@XK92hj6uE2L/DbP5vRTatJeVJpf0jWlFUUPMC7zyvQmq/LFcm2@MnHiicnXymTLXvQ6COZg0ptsswyIxvSWYBbSN0rkGcszkucFqUljToHYlYn2qTVI82yTf8rLD6SSxepzl1587NLrzVwHwTrdVBmdn1NiNkw4ek7KTraAdowxyffFek09K4ZuMkOYvzvrITtMVvDvgA7OK922ymi1x@p0mOKkPQPaGXADOt@bHXadm@KK6bN18JGMhoTMrbebjFS6Xl9mpZ1l@hoPK2jxKXCG/jVLIandwEKqGo06OFc2meKRj0H7KKqWlcRHl@ziscfjXTzyeLSDF9kXXuxK5QxPhfGW1CZL55S74DbbIrNRVBzhlbKDOrTpDoMTeEWqE9Kx6tOx7mBvkpAgdrjQulAlKlb4CxGZcjIyqR3XApbAsH5wIrStGcJuU0PNFGbECg7s6SJWhC3MmVBxy4@QR1r327TIzYWYxNpamNosufy0ztbU4WPAaZeuNY5ja49TKVxXiIJcC6Lp2RG1sgr7BcoP1tkqE/m0M4TdmvGuhTJKaimupQjSseWinFXRpVmX50x659/wzZOLIHAF3pxTcd@v1C7/RGZgZEI6xBptXfyADsUYsaof7B2kNl2EPoR@EJQrc9EO98fVqrAggpCAX6ZFlVlohuGbzTZDFIXhWa1u5w1Io2S1sSW64Ap/DGHSu80L9GwSU9AeHnIFS88st9fYI5spx1LvmgzCbEHPxrTMS47pENVOaaqx6USfF9kmwzdR@oOyhJ3Ep6m4wT@TXsWt/THNVw4htOxrLgFT1ch1ECxTc7NoZ6UuBn@neOBqB5m6maiVXJOhpSx9k6Lkol6xWv2@XVMOdHUrq/28rQwK5fsxGYmRUyvC1VT0M7dCXlYZ/M7Zol8iwWfJ1V4jMT67SITPLoI9TbU8D7SoJBNqVrdZzsWkZ1Z8MVJa6w5YebCnPYB6GTJmjaO2wCS@Jh3Q51nguNVn8hlzeEGFHUeC7yV0p4yYNJOzljiZT1vsZD5vkchLl3FUCCx@R7lHJVzeAy7Iet/34k0FtNePnYdInpAT@2jMq7XJl/kf2X5JNAqDte0axpbdlZ1@zW3I9iPXaKou4DpnKfhRL@MThKTk5W3@paAhPQkC9UT/UwXKsuIfsjum2oH/cIMikKzIl5L20twzKjrpc0qNx1Q2Jakl0V7/v3OawFk3WRz3MjIr4kyyF3NIcsHb7tjc79yS@NsijlGJa5jXUR10EuJ2Qh3dqdXStqCvsH1bs96a/S7XMukIXGg3qxK13Uk6HowbMK7ByL5WYKFOEjewr8J3cnIrvODh0LJf1FD4akCubKNuXQ21uXtUn9Z7ZOWIyKqNFkt5qG@3Lgjg@yfuHg/sulc/lU0w9biUsR@pko4oROfwe8evYpvVTVZVu3vl98jpmtceNOVaVu@zIlu@p6vOmO/3o@edaV1s7Svavm3iZWlqC87npfZK3p5QqGif9pZCo8mleqLXpLQduSZX5GXGlfkhM5cQ@e1za@DuJfLo3WUOv2UsXhbbakGVmWNJaWd5GdzdHbNXeJfjt63ADY5xiYoIEPewiBA8GrIoumNH85S@Z8Mgj3ClwXBfe2u1Hqpg4FcYAB1YAwNZRQYiNrQQgBuIt7A/wOl3gBvv6tUAEPuAOgu9qjY4qMkD/g29sYGLo7Y8CIaNp0Noht7XoXg7bDLI6w09EEKvhjYRwPkbde6sDet1auPDYGTXH9LIxT7y@@F0MEQjjw4kzCEHONIt6i6LLbuBGjHduSIBn9SWTsjZgjEPY3/pxA7EPz84gX@N/6d1@LB8aod4Y@bI@7wk3DvRotNWebpn4IzBEZ3xnx3w0k48u0cPnwrlKaAzgKfsJBQjVsl/YyGnHnosz7POsD5YcMTpXSzgBWHfTVBnnAK7W/wPgvYqNuxW/hs "Haskell – Try It Online")
### Output
1. S(KS)K
2. S(K(SS(KK)))(S(KK)S)
3. S(K(SS))(S(KK)K)
4. S(K(SS(KK)))(S(KK)(S(KS)(S(K(S(SKK)))K)))
5. S(K(S(K(SS(SK)))))(S(K(SS(SK)))(S(SKK)(SKK)))
6. KK
7. S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)
8. S(K(SS(K(S(KK)(S(SKK)(SKK))))))(S(SSK(KS))(S(S(KS)(S(KK)(S(KS)K)))(K(S(K(S(SSK)))K))))
9. S(K(S(KK)))(S(K(S(S(SKK)(SKK))))K)
10. SK
11. S(KS)(S(KK)(S(K(SS))(S(KK)K)))
12. S(K(SS(K(S(KK)K))))(S(KK)(S(KS)(S(SSK(KS))(S(K(SS))(S(KK)K)))))
13. S(K(S(K(S(K(SS(KK)))(S(KK)S)))))(S(K(SS(KK)))(S(KK)(S(KS)(S(K(S(SKK)))K))))
14. S(K(S(K(S(K(SS(KK)))(S(KK)S)))))(S(K(S(SKK)))K)
15. S(K(S(K(S(KS)K))))(S(KS)K)
16. S(K(S(KS)K))
17. S(K(S(K(S(K(SS(K(S(S(KS)(S(KK)(SSK)))(K(S(SKK)(SKK)))))))(S(KK)(S(KS)K))))))(S(K(SS(K(SSK))))(S(KK)(S(KS)(S(KK)(SSK)))))
18. SSS(KK)
19. KK
20. S(KK)(S(KK)(S(S(KS)K)(S(K(S(SKK)))(S(K(S(SKK)))K))))
21. S(S(KS)(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))
22. S(KK)
23. S(KS)(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K)))))
24. S(K(S(K(S(KS)K))))(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(S(KK)(S(K(SS))(S(KK)K))))
25. S(KS)(S(KK)(S(KS)K))
26. S(S(KS)(S(KK)(S(KS)(S(KK)(S(K(S(K(SS(KK)))))(S(KS)(S(KK)(S(SSK(KS))(S(KS)(S(SKK)(SKK)))))))))))(K(S(S(KS)(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(SKK)))K))))))))(S(K(S(SKK)))K)))(S(K(S(K(S(KK)K))))(S(K(S(SKK)))K))))
27. S(K(S(K(S(K(SS(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))(S(KK)(S(KS)K))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))
28. K(S(KK))
29. S(K(S(K(S(K(S(K(S(KS)K))))(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))K)))))(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(S(KK)(S(K(SS))(S(KK)K))))
30. S(KK)(S(K(SSS(KK))))
31. K(SSS(KK))
32. S(K(SS(K(S(S(KS)(S(KK)(S(KS)K)))(K(S(K(S(SKK)))K))))))(S(KK)(S(KS)(SS(S(S(KS)(S(KK)(S(KS)(S(K(S(KS)(S(KK)(S(KS)K)))))))))(KK))))
33. S(K(S(K(S(K(S(K(SS(KK)))(S(KK)S)))))))(S(K(SS(K(S(KK)K))))(S(KK)(SSS(KS))))
34. S(K(S(K(S(KK)K))))
35. S(K(S(K(S(K(S(K(SS(K(S(K(S(SKK)))K))))(S(KK)(S(KS)(S(KK)(S(K(SS(K(S(K(S(SKK)))K))))(S(KK)(S(K(SS))(S(KK)K)))))))))))))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))
36. S(K(SS(K(S(K(SS(K(S(K(S(SKK)))K))))(S(KK)(S(KS)(SS(S(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K)))))(KK))))))))(S(KK)(S(KS)(S(KK)(S(K(S(K(S(K(S(K(S(K(SS(KK)))(S(KK)S)))))))))(S(K(SS(KK)))(S(KK)(S(KS)(S(K(S(KS)(S(KK)(S(KS)K))))))))))))
37. S(KK)(S(K(S(K(S(KK)(S(KK)K)))))(SS(SK)))
38. K(S(K(SSS(KK))))
39. S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))(S(KK)(S(KS)K))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))
40. S(K(S(KK)))(S(KS)(S(KK)(S(K(S(KK)(S(KK)K))))))
41. S(K(SS(K(S(S(KS)(S(KK)(S(KS)K)))(K(S(K(S(SKK)))K))))))(S(KK)(S(KS)(S(KK)(S(K(S(K(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K))))))(S(K(SS(K(S(KK)(S(K(SS))K)))))(S(KK)(S(K(SS))(S(KK)(S(K(S(K(S(KK)(S(KS)K)))))(S(KS)K))))))))))
42. S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))(S(KK)(S(KS)K))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))
43. K(K(K(K(K(S(KK)(S(KK)(S(K(SS(SK)))(SSK))))))))
44. S(KK)(S(K(S(KK)(S(KK)(S(KK)(S(KK)K))))))
45. S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))(S(KK)(S(KS)K))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))
46. S(K(S(K(S(K(S(K(S(K(SS(K(S(K(SS(K(S(K(SS(KK)))(S(KK)(S(KS)(S(K(S(SKK)))K)))))))(S(KK)(S(KS)(S(KK)(S(SSK(KS))(S(K(SS))(S(KK)K))))))))))(S(KK)(S(KS)(S(KK)(S(K(SS(K(S(KK)(S(KS)(S(KK)(S(K(SS(K(S(KK)(S(KS)K)))))(S(KK)(S(K(SS))(S(KK)(S(K(SS(K(S(KK)K))))(S(KK)S))))))))))))(S(KK)(S(K(SS))K))))))))))(S(K(SS(K(S(KK)(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(S(KK)(S(K(SS))(S(KK)K))))))))(S(KK)S))))))(S(K(SS(K(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(S(KK)(S(K(SS))(S(KK)K)))))))(S(KK)(S(KS)(S(KK)(S(K(S(K(S(KS)(S(KK)(S(KS)K))))))(S(KS)(S(KK)(S(K(SS))(S(KK)K)))))))))
47. S(K(SS(K(SS(S(S(KS)(S(KK)S)))(KK)))))(S(KK)(S(KS)(S(K(S(K(S(KS)(S(KK)(S(KS)(S(KK)(S(K(S(K(S(K(SS(K(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)K))))))(S(KK)(S(K(SS))(S(KK)K)))))))(S(KK)(S(KS)K))))))))))))))(S(K(S(S(KS)(S(KK)(S(K(SS))(S(KK)(S(K(S(K(S(KS)K))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(SS))(S(KK)K)))))))))))))(S(KK)(S(K(S(K(S(KK)(S(KS)(S(KK)(S(K(SS(K(S(KK)(S(KS)K)))))(S(KK)(S(K(SS))K)))))))))(S(KS)(S(KK)(S(K(SS(K(S(KK)K))))(S(KK)(S(KS)(S(SSK(KS))(S(K(SS(KK)))(S(KK)(S(KS)(S(K(S(SKK)))K))))))))))))))))
48. K(S(K(S(KK)(S(K(S(KK)(S(K(S(KK)(S(KK)K))))))))))
49. S(KK)(S(K(S(K(S(KK)(S(K(S(K(S(KK)(S(K(S(K(S(KK)(S(K(S(K(S(KK)(S(K(S(KK)))(S(K(S(SKK)))K))))))(S(K(S(SKK)))K))))))(S(K(S(SKK)))K))))))(S(K(S(SKK)))K))))))(S(K(S(SKK)))K))
50. S(K(S(K(S(K(S(K(S(K(S(KK)))(S(K(SS(K(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)K)))))))(S(K(SS(K(S(K(SS))(S(KK)K)))))(S(KK)(S(KS)(S(KK)(S(K(S(K(S(KK)(S(KK)(S(KK)(S(KK)K)))))))(S(K(SS))(S(KK)K)))))))
[Answer]
## Sum of solution lengths: ~~12945 8508~~ 5872
Haskell code that takes input lines from stdin and doesn't care if the separator is `=` or `->`:
```
data E=S|K|V Int|A E E deriving Eq
instance Show E where
showsPrec _ S = showChar 'S'
showsPrec _ K = showChar 'K'
showsPrec _ (V i) = shows i
showsPrec p (A e f) = showParen (p>0) $ showsPrec 0 e . showsPrec 1 f
type SRead a = String -> (a,String) -- a simpler variation of ReadS
parse :: String -> E
parse s = let (e,"")=parseList (s++")") in e
parseList :: SRead E
parseList s = let (l,s')=parseL s in (foldl1 A l,s')
parseL :: SRead [E]
parseL (c:s) | c==' ' = parseL s
| c==')' = ([],s)
parseL s = let (p,s')=parseExp s; (l,s'')=parseL s' in (p:l,s'')
parseExp :: SRead E
parseExp ('(':s) = parseList s
parseExp s = let [(n,s')]=reads s in (V n,s')
k e = A K e
s e f = A (A S e) f
i = s K K
s3 e f g = A (s e f) g
sk = A S K
ssk e f = A (s3 S K e) f
n `invars` (A e f) = n `invars` e || n `invars` f
n `invars` (V m) = n==m
_ `invars` _ = False
comb (A e f) = comb e && comb f
comb (V _) = False
comb _ = True
abstract _ (A (A S K) _) = sk
abstract n e | not (n `invars` e) = k e
abstract n (A e (V _)) | not (n `invars` e) = e
abstract n (A (A (V i) e) (V j)) | n==i && n==j =
abstract n (ssk (V i) e)
abstract n (A e (A f g)) | comb e && comb f =
abstract n (s3 (abstract n e) f g)
abstract n (A (A e f) g) | comb e && comb g =
abstract n (s3 e (abstract n g) f)
abstract n (A (A e f) (A g h)) | comb e && comb g && f==h =
abstract n (s3 e g f)
abstract n (A e f) = s (abstract n e) (abstract n f)
abstract n _ = i
abstractAll 0 e = e
abstractAll n e = abstractAll (n-1) $ abstract n e
parseLine :: String -> (Int,E)
parseLine s = let [(n,s')] = reads s
s''=dropWhile(`elem` " =->") s'
in (n, parse s'')
solveLine :: String -> E
solveLine s = let (n,e) = parseLine s in abstractAll n e
main = interact $ unlines . map (show . solveLine) . lines
```
It implements the improved bracket abstraction from section 3.2 of John Tromp: *Binary Lambda Calculus and Combinatory Logic* which is linked to from the Wikipedia article on combinatory logic. The most useful special cases only use the `S` combinator to suffle subterms around in order to avoid deep nesting of variables. The case that checks for equality of some subterms is not needed for any of the test cases. While there is no special case for handling the `W` combinator (see Peter's answer), the rules work together to find the shorter `SS(SK)` expression. (I first made a mistake by trying to optimize away the inner calls to `abstract`, then this `W` optimization did not happen and the overall result was 16 bytes longer.)
And here are the results from the test cases:
```
S(KS)K
S(K(S(K(SS(KK)))K))S
S(K(S(K(SS))K))K
S(K(S(K(S(K(S(K(SS(KK)))K))S))(S(SKK))))K
S(K(S(K(SS(SK)))))(S(K(SS(SK)))(S(SKK)(SKK)))
KK
S(K(S(K(S(S(K(S(KS)(S(SKK))))K)))K))K
S(K(S(K(SS(K(S(KK)(S(SKK)(SKK))))))(S(KS))))(S(K(S(K(S(K(SS(K(S(K(S(SSK)))K))))K))S))K)
S(K(S(K(S(KK)))(S(S(SKK)(SKK)))))K
SK
S(K(S(K(S(K(S(S(KS)(S(KS)))))K))K))K
S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(KK)K))))K))S))(S(KS))))(SS)))K))K
S(K(S(K(S(K(S(K(SS(KK)))K))S))))(S(K(S(K(S(K(S(K(SS(KK)))K))S))(S(SKK))))K)
S(K(S(K(S(K(S(K(S(K(SS(KK)))K))S))))(S(SKK))))K
S(K(S(K(S(K(S(K(S(K(SS(K(S(KS)K))))K))S))K))S))K
S(K(S(KS)K))
S(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(K(S(K(S(K(S(K(S(K(SS(K(S(S(K(S(KS)(S(KS))))(S(K(S(K(S(K(SS(K(S(S(KS)(S(K(SS(K(S(SKK)(SKK)))))K))K))))K))S))K))(S(KK)K)))))K))S))K))S))K))(S(K(S(KK)K))K)
S(KK)(S(KK))
KK
S(K(S(KK)K))(S(S(KS)K)(S(K(S(K(S(SKK)))(S(SKK))))K))
S(K(S(K(S(K(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K)))K))K))K
S(KK)
S(K(S(K(S(K(S(K(S(S(KS)(S(K(S(KS)(S(KS))))))))K))K))K))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))(S(S(KS)(S(KS))))))K))K))K
S(K(S(K(S(KS)K))S))K
S(K(S(K(S(K(S(K(SS(KK)))(S(KS))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(K(S(KS)(S(SKK))))K))))))))(S(SKK))))K)(S(K(S(K(S(K(S(KK)K))))(S(SKK))))K)))))K))S))K))S))K))S))(S(SKK)(SKK)))
S(K(S(K(S(K(S(K(S(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K))))K))K))K)))K))K))K))K
K(S(KK))
S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))(S(S(KS)(S(KS))))))K))K))K)
S(KK)(S(K(S(KK)(S(KK)))))
K(S(KK)(S(KK)))
S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)))(S(K(S(K(S(K(SS(K(S(K(S(SKK)))K))))K))S))K)))))K))S))K))S))(S(K(S(K(S(K(S(KS)K))S))K)))
S(K(S(K(S(K(S(K(S(K(SS(KK)))K))S))))))(S(K(S(K(S(K(SS(K(S(KK)K))))K))S))(S(KS)))
S(K(S(K(S(KK)K))))
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(S(K(S(K(S(KS)(S(K(S(K(S(KS)(S(SKK))))K)))))(S(SKK))))K)))K))K))K))))))(S(S(K(S(KS)(S(SKK))))K))))K))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(KK)))K))S))))))))))(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)))(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(KK)))(S(SKK))))K))))K))S))K))S))(S(SKK))))K)))))K))S))K))S))(S(K(S(K(S(K(S(KS)K))S))K))))
S(K(S(KK)(S(K(S(K(S(KK)K))K)))))(SS(SK))
K(S(K(S(KK)(S(KK)))))
S(K(S(K(S(K(S(K(S(K(S(K(S(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))(S(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K))))K))K))K))))K))K))K))K))))K))K))K))K))K)))K))K))K))K))K))K
S(K(S(K(S(K(S(KK)(S(K(S(K(S(KK)K))K)))))))S))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(KS)K))S))K))))K))))(S(K(S(K(S(K(SS(K(S(K(S(SKK)))K))))K))S))K)))))K))S))K))S))K))S))K))S))K))S))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))(S(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K))))K))K))K))))K))K))K))K))))K))K))K))K))K))))K))K))K))K))K))K)))K))K))K))K))K))K))K
K(K(K(K(K(S(K(S(KK)K))(S(K(SS(SK)))(SSK)))))))
S(KK)(S(K(S(K(S(K(S(K(S(KK)K))K))K))K)))
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))(S(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K))))K))K))K))))K))K))K))K))))K))K))K))K))K))))K))K))K))K))K))K))))K))K))K))K))K))K))K)))K))K))K))K))K))K))K))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))))))))(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(KK)K))K))K))))K))S))(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))(S(K(S(K(S(K(S(K(SS(K(S(KK)K))))K))S))(S(KS)))))))(S(S(K(S(KS)(S(KS))))(S(K(S(K(S(K(S(K(SS(KK)))K))S))(S(SKK))))K)))))K))K))K))))K))K))K))K))K))))K))K))K))K))K))K))K)))K))K))K))K))K))K))K))K))K
S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KK)K))K))K))K))K))K))K))))K))S))(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))))))))(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(K(S(KK)K))K))K))K))))K))S))(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS)))))))))))))(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))))))))(S(K(S(K(S(K(S(K(SS(K(S(K(S(KK)K))K))))K))S))(S(K(S(KS)(S(KS)))))))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(SS(K(S(K(S(K(S(K(S(K(S(KK)K))))))))(S(K(S(K(SS(KK)))K))S)))))K))S))K))S))K))S))K))S))(S(KS))))(S(K(S(K(S(K(S(K(SS(KK)))K))S))(S(SKK))))K))
K(S(K(S(KK)(S(K(S(KK)(S(K(S(K(S(KK)K))K)))))))))
S(K(S(K(S(KK)(S(K(S(K(S(K(S(KK)(S(K(S(K(S(K(S(KK)(S(K(S(K(S(K(S(KK)(S(K(S(K(S(K(S(KK)(S(KK))))(S(SKK))))K)))))(S(SKK))))K)))))(S(SKK))))K)))))(S(SKK))))K)))))(S(SKK))))K
S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KK)(S(K(S(K(S(K(S(K(S(KK)K))K))K))K)))))))))))(S(S(K(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(K(S(KS)(S(KS))))))))))(S(S(K(S(K(S(K(S(K(S(KS)(S(K(S(KS)(S(KS)))))))(S(S(K(S(K(S(K(S(KS)(S(KS))))(S(S(K(S(KS)(S(SKK))))K))))K))K))))K))K))K))))K))K))K))K))))K))K))K))K))K
```
[Answer]
## 8486 using S, K, I, W
### Explanation
The standard algorithm (as described e.g. in chapter 18 of *To Mock a Mockingbird*) uses four cases, corresponding to the combinators `S`, `K`, `I = SKK`, and simple left-association. I think this is what Christian's answer implements. This is sufficient, but not necessarily optimal, and since we're allowed to hard-code up to 10 combinators it leaves 7 options.
Other well-known combinatorial combinators are
```
B x y z = x (y z)
C x y z = x z y
W x y = x y y
```
which, together with `K`, [make a complete basis](https://en.wikipedia.org/wiki/B,_C,_K,_W_system). In SK these are
```
B = S (K S) K
C = S (S (K (S (K S) K)) S) (K K)
W = S S (S K)
```
and the `SKI` rules derive those same expressions for `B` and `C`, but for `W` they derive `S S (K (S K K))`. I therefore chose to implement `W` as a special case.
### Program (CJam)
```
e# A tests whether argument is an array
{W=!!}:A;
e# F "flattens" an expression by removing unnecessary parentheses, although if the expression is a primitive
e# it actually wraps it in an array
{
e# A primitive is already flat, so we only need to process arrays
_A{
ee{
~
e# Stack: ... index elt
e# First recurse to see how far that simplifies the element
F
e# If it's an array...
_A{
e# ... we can drop a level of nesting if either it's the first one (since combinator application
e# is left-associative) or if it's a one-element array
_,1=@!|{
e# The tricky bit is that it might be a string, so we can't just use ~
{}/
}*
}{
\;
}?
}%
}{a}?
}:F;
qN%{
e# Parse line of input
"->=()"" [[[]"er']+~
e# Eliminate the appropriate variables in reverse order. E eliminates the variable currently stored in V.
\,:)W%{
e# Flatten current expression
F
e# Identify cases; X holds the eXpression and is guaranteed to be non-primitive
:X
[
XVa= e# [V]
Xe_V&! e# case V-free expression
X)_A0{V=}?\e_V&!* e# case array with exactly one V, which is the last element
X_e_Ve=~)>[VV]=X,2>* e# case array with exactly two Vs, which are the last two elements
]
1#
e# Corresponding combinators
[
{;"SKK"} e# I
{['K\]} e# K
{);} e# X (less that final V)
{););['S 'S "SK"]\a+} e# W special-cased as SS(SK) because the general-case algorithm derives SS(K(SKK))
{['S\)E\E\]} e# S (catch-all case)
]=~
}:EfV
e# Format for output
F
{
_A{
'(\{P}%')
}*
}:P%
oNo}/
```
[Online test suite](https://tio.run/nexus/cjam#fVVtTyJJEP4@v6Jk48Hsiusg4Ftwz1w0MSQbEy5IAsS00EDfDjNcd6NLvPGve0/19DB4bs6gdNfLU1VPVbVv8hNdkZXGGnpeSLuQmoSer5cysaQMiQRXLTbBy31nby87v7oIArjcUGUWC2tlYipsI3@utDRGpQk9bkjLZfqkkjmtk0ROIBd6QyuhgbmQRpoDErFdpOv5gtSMINv156C00mqprHqSHExZEhO7FnG8oWctVoYlKtnJLSBydWzdHEqspZhuiBM9IJPSs6Q0AUYi5ZRsCuuUk8tBDDAerhgJWDL/Jnr130DvWTH5cU6Hh4eIPZU/Sca21N4obSwKn6y1kQxupKRF@kwzoVGhsGTUchWrmZImrziWzLFHuCmRbmcor1oyj4BeWaTnDTkTlDSB4VSnK7AWyycZUzpDhcYy/2BXKtdTB8lxZy7RNJFUMyqZwD9dPqpE2BSNXyHDibBow24gcBnLma0LY9KJEsxvSDBXRaYMV/cF@ZYU7g8HUef3vX/KxB3in0jEajX5saFH5ebMUYTjUs0Xlh4lQA0sknnROZRZtfTXGsmvwfDrDuBL9nV7yz77Y1aGHF0Usm/ukO0HrBe4Zuc3GOjg7@/7L26u7wS3L1agBzSqZLW2QaV@2amFlQoNh8NxRerq@Msr217HGDYQJx2v4A5N0IrvTwLfjzE6jSnVaAqDpnoq9SFdo/PeL29IYUwYHd4QDKhBMzCicO4fBqOD8/B@34/4Tb50he3O3gQ8RLnR7RQqNduAMyzbBQ0wiPHUj91gu2gimTLz87XQIrF@J8B8kib1cv@Izgf4M3TMDfqiQx9@EHLYH@cG8qH/294vDDgV6tdnWsr3ScMnfLg6eul3sm8j5/35nY8bJ3rGFMMPzwDo4eHtH@C5UpNFPjtomcBg7O7U4AFgsvMaXg77/XFncNC4/Py/qPY5pb4pYPFYlbis8tj8THCp0aec6z9SNMKs0mTK@1buktly9nJR6XW7lewDJbe5eljtjsbZR8a6uTq8yH7J@IBqMT9ebnFmCBpTPyxcwothtUf4IHRlPBJfMna5J7OSWOC4zhxMSRjq9Wq9boiuTwRvFVc8l4nU3gZv6DzVYGlJGF6Mg/PowqcbhkX6vVF4Pbp@VwM/l1TDSzJZ1PFsO87Zftx5xcpdz/r5P5FULzl5PCXp2vKq3binvHjnqrXRy122X2VP7HV2frcfBOn3NPv69nZM9UuKqNag4zDwl2Nq5EcIKcqPOBTSiI9Od@zNCpNGYQ1Avh2HDNwIC7StHqqgWURoQtrMAZouiru4Y2kWQeAvLlvgN0GdF/j7e32tCRHn0AiLCFEJ2NwaN/kTFWBNX8cWuRm0ykxb0LSKXFsu21bJIMdrFYII@lorJwJy/g7DAq21jbMFbwXtPH6L2r72dtEPrwMQtQtp05XZ4gLb4Y7peytG9pdam819Kq7gky3SCXksgBVi9JdO8ovLr7icIL8y/9Nt@UA@za@1yFXe4JBI7yR0ujBXnv4H4IyFbTrj3/zCof3x7IN5dORMjiA6g/CUk4SizarIqZh66BGevc4QH1ZIxOt9LbALooZ3qJ0xBXm3QAyo8SoG9pH/BQ)
### Generated outputs:
```
S(KS)K
S(S(KS)(S(KK)S))(KK)
S(K(SS))(S(KK)K)
S(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K))))(KK)
S(K(S(K(SS(SK)))))(S(K(SS(SK)))(S(SKK)(SKK)))
KK
S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)
S(S(KS)(S(K(S(KS)))(S(S(KS)(S(KK)(S(KS)K)))(K(S(S(KS)(S(K(S(SKK)))K))(K(SKK)))))))(K(S(KK)(S(SKK)(SKK))))
S(K(S(KK)))(S(K(S(S(SKK)(SKK))))K)
K(SKK)
S(K(S(S(KS)(S(KS)))))(S(KK)(S(KK)K))
S(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(K(SS))(S(KK)K))))))(K(S(KK)K))
S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K))))(KK))))))(K(KK))
S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(K(S(SKK)))K)))))(K(KK))
S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)K)))))(K(S(KS)K))
S(K(S(KS)))(S(KK))
S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)K)))))(K(S(S(KS)(S(K(S(KS)))(S(S(KS)(S(KK)(S(KS)K)))(K(S(S(KS)(S(S(KS)K)(K(S(SKK)(SKK)))))K)))))(S(KK)K)))))))(S(KK)(S(KK)K))
S(KK)(S(KK))
KK
S(KK)(S(KK)(S(S(KS)K)(S(K(S(SKK)))(S(K(S(SKK)))K))))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))
S(KK)
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(KS))))))))(S(KK)(S(KK)(S(KK)K)))
S(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(KS)))))(S(KK)(S(KK)K))))))))(K(S(KK)(S(KK)K)))
S(KS)(S(KK)(S(KS)K))
S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(SKK)(SKK)))))))))(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(SKK)))))))(S(K(S(K(S(KK)))))(S(K(S(SKK)))K))))))(S(K(S(KK)))(S(K(S(KK)))(S(K(S(SKK)))K))))))))))(K(K(KK)))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))))))))(S(KK)(S(KK)(S(KK)K)))
K(S(KK))
S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(KS)))))(S(KK)(S(KK)K))))))))(K(S(KK)(S(KK)K))))))))))(K(K(S(KK)(S(KK)K))))
S(KK)(S(K(S(KK)))(S(K(S(KK)))))
K(S(KK)(S(KK)))
S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(KK))))))))))(K(S(K(S(KK)))(S(S(KS)(S(KK)(S(KS)K)))(K(S(K(S(SKK)))K)))))
S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(KK)))))(S(K(S(K(S(KS)))))(S(S(KS)(S(KK)(S(KS)(S(KS)))))(K(S(KK)K))))))))(K(K(KK)))
S(K(S(K(S(KK)))))(S(K(S(KK))))
S(K(S(K(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(SKK)))))(S(K(S(KK)))(S(K(S(SKK)))K)))))))))))(S(K(S(K(S(KK)))))(S(K(S(K(S(KK)))))(S(K(S(K(S(KK)))))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K)))))
S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(KK))))))))))(K(S(K(S(KK)))(S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K))))))(K(S(K(S(KK)))(S(K(S(SKK)))K))))))))))))))(K(K(K(K(KK)))))
S(KK)(S(K(S(KK)))(S(K(S(KK)))(S(K(S(KK)))(SS(SK)))))
K(S(K(S(KK)))(S(K(S(KK)))))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))))))))(S(KK)(S(KK)(S(KK)K))))))))))(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K)))))
S(K(S(KK)))(S(K(S(K(S(KK)))))(S(K(S(K(S(KK)))))(S(K(S(K(S(KK)))))(S(KS)K))))
S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)K)))))))))))(K(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(S(KS)(S(KK)(S(KS)K)))))))(S(K(S(KK)))(S(S(KS)(S(KK)(S(KS)K)))(K(S(K(S(SKK)))K)))))))))))(K(K(S(KK)(S(KK)K))))))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))))))))(S(KK)(S(KK)(S(KK)K))))))))))(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))
K(K(K(K(K(S(KK)(S(KK)(S(S(KS)(SSK))(K(SKK)))))))))
S(KK)(S(K(S(KK)))(S(K(S(KK)))(S(K(S(KK)))(S(K(S(KK)))(S(KK))))))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))))))))(S(KK)(S(KK)(S(KK)K))))))))))(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K)))))))
S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))))(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(KK)))))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K))))(KK))))))(S(KK)(S(KK)K))))))))(K(K(S(KK)K))))))))))(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))(K(K(K(S(KK)(S(KK)K))))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))))))(K(K(K(K(S(KK)(S(KK)(S(KK)K))))))))))))))))))(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K))))))))
S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))))))(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))))(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(K(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))))(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(K(S(K(S(K(S(KS)))))))))(S(K(S(K(S(K(S(K(S(K(S(KS)))))))))))(S(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(KK)(S(KS)(S(K(S(KS)))(S(S(KS)(S(KK)(S(KS)(S(K(S(SKK)))K))))(KK))))))))))))(K(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(KK)))))))(S(S(KS)(S(KK)S))(KK))))))))))))))(K(K(K(K(S(KK)(S(KK)K))))))))))))))))(K(K(K(K(K(S(KK)(S(KK)K))))))))))))))))))(K(K(K(K(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))))))))))))(K(K(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)(S(KK)K)))))))))
K(S(K(S(KK)))(S(K(S(K(S(KK)))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(KK))))))))))
S(KK)(S(K(S(KK)))(S(K(S(K(S(KK)))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(K(S(KK)))))))))))(S(K(S(K(S(K(S(K(S(K(S(SKK)))))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(SKK)))))))))(S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(SKK)))))))(S(K(S(K(S(KK)))))(S(K(S(K(S(SKK)))))(S(K(S(KK)))(S(K(S(SKK)))K))))))))))))))
S(K(S(K(S(K(S(KK)))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(K(S(K(S(K(S(KK)))))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(K(S(KS)))))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(S(KS)(S(K(S(SKK)))K))))(S(KK)K))))))(S(KK)(S(KK)K))))))))(S(KK)(S(KK)(S(KK)K))))))))))(S(KK)(S(KK)(S(KK)(S(KK)K))))))))))
```
] |
[Question]
[
# Balancing Act
A see-saw (supposedly from the French 'ci-ça', meaning 'this-that') forms a third of the holy trinity of playground equipment, along with the similarly ubiquitous slide and swing. A see-saw is in perfect balance if, and only if, the sum of the moments on each side are equivalent. A see-saw can therefore be balanced by adding a specific quantity of weight to the side with the lower moment sum; achieving this is your goal for this challenge.
# Challenge
Your challenge is to take a depiction of a see-saw as input and output it again, with weight added to one end of the see-saw to balance it.
**Input**
Your program must take, in any reasonable format, an ASCII see-saw such as the following:
```
100 100
-------------------
^
```
The first line contains two numbers, each representing weights on the see-saw. Exactly one weight is present on each side, each acting on the very end of its side of the plank. Weights are guaranteed to be integers, and always align with their corresponding end of the plank. These numbers will never overlap the fulcrum (`^`).
The second line represents the 'plank' of the see-saw. Each dash (`-`) represents an equal length to each other dash, with the sole exception of the dash directly over the fulcrum (`^`), which has no length.
The third line represents the fulcrum of the see-saw. This fulcrum is marked by the only character that is not a space on this line, a circumflex ('^'). The fulcrum can be positioned anywhere along the length of the plank in a valid input so long as enough space is left so that the numbers representing weights do not overlap the fulcrum in either the input or the output.
The input is guaranteed to have three lines, and have no white-space prior to or after the characters that constitute the see-saw (excepting, of course, the third line, which requires it).
**Output**
For output, the same see-saw depiction should be printed to stdout, but with one (and only one) of the weights replaced with a larger weight, so as to balance the see-saw. Inputs are guaranteed to make this possible using integers alone. Therefore, weights must be shown without decimal points or any other similar notations. If your language does not use stdout you should go by community / meta consensus on output. Trailing newlines are fine but any other changes to the depiction format are probably not OK.
# Exemplification
**Test Inputs and Corresponding Outputs**
Input 1
```
12 22
--------------------
^
```
Output 1
```
12 26
--------------------
^
```
---
Input 2
```
42 42
-----------
^
```
Output 2
```
42 42
-----------
^
```
---
Input 3
```
3 16
----------------
^
```
Output 3
```
14 16
----------------
^
```
---
Input 4
```
1 56
-------------------
^
```
Output 4
```
196 56
-------------------
^
```
**Reference Implementation - Python 3**
```
# Takes a list of strings as input
def balance_seesaw(lines):
weights = [int(w.strip()) for w in lines[0].split()]
length = len(lines[1])
pivot = lines[2].find("^")
left_length = pivot
right_length = length - 1 - pivot
left_torque = weights[0] * left_length
right_torque = weights[1] * right_length
if left_torque > right_torque:
weights[1] = left_torque // right_length
elif right_torque > left_torque:
weights[0] = right_torque // left_length
weights = [str(w) for w in weights]
string_gap = " " * (length - sum(len(w) for w in weights))
lines[0] = weights[0] + string_gap + weights[1]
print("\n".join(lines))
balance_seesaw(["1 56",
"-------------------",
" ^ "])
```
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins counted in bytes. Check meta if counting bytes is awkward in your language.
* Standard rules/loopholes apply.
* Input must be taken in a reasonable format. A non-exhaustive list of appropriate formats are given as follows:
+ A single string with lines separated by newline characters
+ A list of strings, each string represented a line
+ A 2D Array or Matrix of characters
# Related Challenges
* [Balance a set of weights on a see-saw](https://codegolf.stackexchange.com/questions/54311) - Proposed Aug 2015 by samgak
---
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~60~~ ~~51~~ ~~50~~ ~~49~~ ~~47~~ 45 bytes
Saved 10 bytes thanks to Emigna and 1 byte thanks to Adnan.
All input lines must have the same amount of characters.
```
#õKD³'^¡€gDŠ*¬-Os÷1®‚*D0›*+¬?DJg²gs-ð×?¤,²,³,
# Split the first input line on spaces
õKD Push [first weight, second weight] twice
³'^¡€gD Push both lengths from either side of the pivot '^' as an array [left, right] twice
Š* Multiply by weights to get torque
¬-O Evaluate rightTorque-leftTorque
s÷ Divide by each side's length to get the weights to add: [deltaLeft, deltaRight], keep integer values
1®‚ Push [1,-1]
*D Yield [deltaLeft, -deltaRight]
0›* Replace the negative value by 0
+ Add weights: old + deltaWeight
¬? Print left weight
DJg Take the size of total decimal representation
²gs-ð×? Print a string composed of filler spaces between both new weights
¤, Print right weight and newline
²,³, Print the last two lines from input (unchanged)
```
[Try it online!](http://05ab1e.tryitonline.net/#code=I8O1S0TCsydewqHigqxnRMWgKsKsLU9zw7cxwq7igJoqRDDigLoqK8KsP0RKZ8KyZ3Mtw7DDlz_CpCzCsizCsyw&input=MSAgICAgICAgICAgICAgICA1NgotLS0tLS0tLS0tLS0tLS0tLS0tCiAgICBeICAgICAgICAgICAgICA)
There should be a rule of thumb, like "if your 05AB1E code is longer than 40 bytes, you're probably doing it wrong".
It seems so golfable, any idea is welcome!
[Answer]
# JavaScript (ES6), 136
~~Probably not working in Chrome,as it uses destructured assignment and default parameters.~~
Note that the standard JS output method `alert` is particularly unsuited for the task, because of the proportional font used.
```
(m,n,o,[p,q]=m.split(/ +/),l=n.length,h=o.indexOf`^`,g=l-h-1,c=p*h<q*g?q*g:p*h)=>alert((c/h+o).slice(0,h)+(o+c/g).slice(h-l)+`
${n}
`+o)
```
*Less golfed*
```
( m,n,o, // input parameters, 3 strings
// default parameters used as local variables
[p,q] = m.split(/ +/), // left and right weight
l = n.length, // bar length
h = o.indexOf`^`, // left length
g = l-h-1, // right length
// p*h left torque
// q*g right torque
c = p*h<q*g ? q*g : p*h // max torque
) => alert( (c/h+o).slice(0,h)+(o+c/g).slice(h-l) // o has enough spaces to pad left and right
+`\n${n}\n`+o )
```
**Test**
```
F=
(m,n,o,[p,q]=m.split(/ +/),l=n.length,h=o.indexOf`^`,g=l-h-1,c=p*h<q*g?q*g:p*h)=>alert((c/h+o).slice(0,h)+(o+c/g).slice(h-l)+`
${n}
`+o)
function go()
{
var [a,b,c]=I.value.split('\n')
if(a.length!=b.length || a.length < c.length)
alert('The strings are not of the same length')
else
{
if (a.length > c.length)
c = c+' '.repeat(a.length-c-length)
F(a,b,c)
}
}
```
```
<textarea id=I>3 16
----------------
^ </textarea>
<button onclick='go()'>go</button>
```
[Answer]
# Perl, 149+2=151 characters
Requires command line options `-p0` (this gives me a 2 byte penalty on top of the 149 bytes in the program itself).
```
($_,$b,$c,$d)=map length,/(\d+) +(.+)
(-+)
( +)/;$r=$d/($c-$d-1);($x,$y)=$1*$r>$2?($1,$1*$r):($2/$r,$2);$_="$x$,$y",$,.=$"while$c>length;$\="
$3
$4^"
```
Explanation:
* The `-p0` switch reads the entire input up to the first NUL byte or EOF. This problem doesn't allow NULs, so we'll get the entire input in the variable `$_` that's used for regexes, etc., by default.
* We start with a regex that parses the input (between the first and second slash). There are several ways we could parse the first weight (e.g. `.+?`), but I can't get it below 3 characters so I may as well use the obvious `\d+`. The second number is at the end of the line so it can be parsed as `.+` (2 characters). The central line is used to determine how wide the scales are; it's parsed as `-+` (many other representations would work). The spaces before the caret on the last line are `+`. Once the caret (or indeed any nonspace) appears, we ignore the rest of the input.
* Perl automatically captures the four groups of the regex (first weight, second weight, row of hyphens, spaces before the caret) into `$1`, `$2`, `$3`, `$4`. Giving a regex as an argument to `map` additionally uses an array of those groups as the array to map over. We therefore take their lengths; this is a convenient way to store the lengths of `$3` and `$4` without having to write `length` twice. We also overwrite `$_` with the length of `$1`; we don't really care about the value of this (the number of digit in the left input is kind-of useless), but the fact that it's short (`$_`'s length is now the number of digits in the number of digits in the first weight, which is necessarily very small compared to the width of the scales).
* We measure the ratio `$r` in which the scales are divided.
* `$1*$r>$2` checks to see which side is heavier. We store the new weights in `$x` and `$y`; these have very simple calculations once the ratio of weights is known.
* We concatenate `$x`, `$,`, and `$y` into `$_` to produce the top row, then keep adding spaces (`$"` contains a single space by default, and is shorter than a literal space `' '` would be) onto `$,` until it's the same length as the middle row (i.e. has length `$c`). (I chose the variable `$,` as it's a built-in variable that can safely be changed in this context and starts empty by default.) As `length` operates on `$_` by default, we don't need to give it an argument explicitly. I used a Yoda conditional because it needs considerably less disambiguating syntax to parse correctly.
* Finally, I redefine Perl's idea of the output line ending convention (`$\`) to contain the rest of the set of scales (which is the same as in the input, so I can simply use `$3` and `$4` directly to produce the bulk of it). Note that this means that there's no trailing whitespace on the third line; adding it would make the program slightly longer and doesn't seem to serve any purpose, so I left it out.
* At the end of the program, the `-p` switch triggers again; this time, it outputs `$_` followed by a "newline" (`$\`). Because I redefined the output newline, these two implicit prints generate the new set of scales between them (although as a side effect, there's no newline on the output).
* The `-p` switch now tries to read input again, but we already slurped the entire file, so it reads EOF and ends the program.
[Answer]
# PHP, ~~212~~ ~~209~~ 205 bytes
probably golfable
```
preg_match("#(\d+)( +)(\d+)\s*(-+)[\r\n]+( +)\^#",$s=$argv[1],$m);echo preg_replace("#\d+( +)\d+#",(($r=$m[3])>($q=$m[1]*($p=strlen($m[5]))/(-$p-1+$e=strlen($m[4])))?$r*$e/($p+1)-$q=$r:$m[1]).$m[2].$q,$s);
```
Takes input from command line argument; escape newlines. Run with `-r`.
---
Replacing with a placeholder did not work as expected; so I had to add more parens to the first regex.
[Answer]
# Befunge, ~~223~~ 217 bytes
```
&:00p&10p~$0>~#<2#+%#1_:20p0~>8#~%#+!#1_:3v
v\g01/g03*g01_v#!\g04`*g01g04:*g03p04-1-p0<
>#g>#0>#0>#/>#<:.2\5>5>#\+/#1:#\_$50p:50g\5>5>#\+/#1:#\_$20g\-v>
1#,>#*-#4:#8_$.55+,20g>:#,1#*-#9\#5_55+,30g>:#,1#*-#8\#4_"^",@>>
```
[Try it online!](http://befunge.tryitonline.net/#code=JjowMHAmMTBwfiQwPn4jPDIjKyUjMV86MjBwMH4-OCN-JSMrISMxXzozdgp2XGcwMS9nMDMqZzAxX3YjIVxnMDRgKmcwMWcwNDoqZzAzcDA0LTEtcDA8Cj4jZz4jMD4jMD4jLz4jPDouMlw1PjU-I1wrLyMxOiNcXyQ1MHA6NTBnXDU-NT4jXCsvIzE6I1xfJDIwZ1wtdj4KMSMsPiMqLSM0OiM4XyQuNTUrLDIwZz46IywxIyotIzlcIzVfNTUrLDMwZz46IywxIyotIzhcIzRfIl4iLEA-Pg&input=MSAgICAgICAgICAgICAgICA1NgotLS0tLS0tLS0tLS0tLS0tLS0tCiAgICBe)
[Answer]
# Python 2, ~~184~~ 183 bytes
Definitely golfable
```
i=raw_input
j=int
w=map(j,i().split())
W=len(i())
I=i().find('^')
R=W-I-1
a=[w[1]*R/I,w[0]*I/R]
h=a[1]>w[1]
w[h]=j(a[h])
k='\n'
print(' '*(W-len(str(w))+4)).join(map(str,w))+k+'-'*W+k+' '*I+'^'
```
Pretty straightforward. Just take the adjusted weights for adjusting both sides, see which one's larger than the original, and change that one, and output.
EDIT Switched multiplication and division because integer division is evile (thanks to @JonathanAllan for noticing this)
EDIT *-1 byte* Changed `i().index('^')` to `i().find('^')` (thanks to @JonathanAllan [again!])
[Answer]
### C++ 14, 482 bytes
```
include<iostream>#include<string>#include<math.h>usingnamespacestd;intmain(){stringa,b,c,d;intj=0;inte[2];getline(cin,a);getline(cin,b);getline(cin,c);for(inti=0;i<a.size();i){if(isdigit(a.at(i))){while(i<a.size()&&isdigit(a.at(i))){d=a.at(i);i;}e[j]=stoi(d);d="";}}strings(b.size()-(int)log10(e[0])-(int)log10(e[1])-2,'');intl1=(c.size()-1);intl2=(b.size()-c.size());intl=e[0]*l1;intr=e[1]*l2;if(l>r)e[1]=l/l2;elsee[0]=r/l1;cout<<e[0]<<s<<e[1]<<endl;cout<<b<<endl;cout<<c;return0;}
```
more readable version:
```
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
string a,b,c,d;
int j=0;
int e[2];
// input
getline(cin,a);// 1st line
getline(cin,b);// 2nd line
getline(cin,c);// 3rd line
for (int i=0;i<a.size();i++) {
if(isdigit(a.at(i))){
while(i<a.size() && isdigit(a.at(i))){
d+=a.at(i);
i++;
}
e[j++]=stoi(d);
d="";
}
}
// amount of white space in between 2 numbers
string s(b.size()-(int)log10(e[0])-(int)log10(e[1])-2,' ');
int l1 = (c.size()-1);
int l2 = (b.size()-c.size());
int l = e[0]*l1;
int r = e[1]*l2;
// change the side with smaller torque
if (l>r)
e[1]=l/l2;
else
e[0]=r/l1;
// output
cout<<e[0]<<s<<e[1]<<endl;// 1st line
cout<<b<<endl;// 2nd line
cout<<c;// 3rd line
return 0;
}
```
[Answer]
# Python 3, 235 230 bytes (minimized reference)
I just minimized the reference, since I'm very new to code-golfing.
```
def s(l):
w,i,t=[int(z.strip())for z in l[0].split()],len(l[1]),l[2].find("^");k,o=i-1-t,w[0]*t;p=w[1]*k
if o>p:w[1]=o//k
else:w[0]=p//t
w=[str(z)for z in w];s=" "*(i-sum(len(z)for z in w));l[0]=w[0]+s+w[1];print("\n".join(l))
```
You use it exactly the same as the example, but the function is `s` instead of `balance_seesaw`.
] |
[Question]
[
## Introduction
I defined the class of antsy permutations in [an earlier challenge](https://codegolf.stackexchange.com/questions/97217/antsy-permutations).
As a reminder, a permutation **p** of the numbers from **0** to **r-1** is antsy, if for every entry **p[i]** except the first, there is some earlier entry **p[i-k]** such that **p[i] == p[i-k] ± 1**.
As a fun fact, I also stated that for **r ≥ 1**, there are exactly **2r-1** antsy permutations of length **r**.
This means that there is a one-to-one correspondence between the antsy permutations of length **r** and the binary vectors of length **r-1**.
In this challenge, your task is to implement such a correspondence.
## The task
Your task is to write a program or function that takes in a binary vector of length **1 ≤ n ≤ 99**, and outputs an antsy permutation of length **n + 1**.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.
The lowest byte count wins.
## Example
The (0-based) antsy permutations of length 4 are
```
0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0
2 1 0 3
2 1 3 0
2 3 1 0
3 2 1 0
```
and your program should return one of them for each of the eight bit vectors of length 3:
```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḟẋLṭ+
0;ç/
```
[Try it online!](http://jelly.tryitonline.net/#code=4bif4bqLTOG5rSsKMDvDpy8&input=&args=MSwgMSwgMCwgMCwgMSwgMCwgMQ) or [generate all permutations of length 4](http://jelly.tryitonline.net/#code=4bif4bqLTOG5rSsKMDvDpy8KMuG4tuG5lzPDh-KCrEc&input=).
### How it works
```
0;ç/ Main link. Argument: B (bit array)
0; Prepend a 0 to B.
ç/ Reduce [0] + B by the helper link.
ḟẋLṭ+ Helper link. Left argument: A (array or 0). Right argument: b (bit)
ẋ Repeat A b times, yielding A or [].
ḟ Filter false; remove the elements of A or [] from A.
L Get the length of the resulting array.
This yield len(A) if b = 0 and 0 if b = 1.
+ Add b to all elements of A.
ṭ Tack; append the result to the left to the result to the right.
```
[Answer]
# Python 2, ~~62~~ 60 bytes
```
x=0,
for n in input():x=[t-n+1for t in x]+[n*len(x)]
print x
```
*Thanks to @xnor for golfing off 2 bytes!*
Test it on [Ideone](http://ideone.com/YHMXhV).
[Answer]
## Python, 54 bytes
```
lambda l:[i-i*x+sum(l[i:])for i,x in enumerate([1]+l)]
```
Uses the following procedure:
1. Prepend a 1 to the list.
2. For each 0 entry, write its position in the 0-indexed list.
3. For each entry, write the number of 1's to its right, not counting itself.
4. Add the results of steps 2 and 3 entrywise.
For example, `l=[1,0,1,0]` gives `f(l) == [2,1,3,0,4]`
```
List with prepended 1 1 1 0 1 0
0-indexed position for 0's 2 4
Number of 1's to right 2 1 1 0 0
Sum of above two 2 1 3 0 4
```
Prepending a 0 would also give the same result. The `enumerate` is clunky, I'll see if it can done better recursively.
[Answer]
## JavaScript (ES6), ~~48~~ ~~47~~ 45 bytes
```
a=>[h=l=0,...a.map(c=>c?--l:++h)].map(e=>e-l)
```
This turned out to be similar to @ETHproductions' method, except I had started by directly calculating the first element and then using the binary vector to determine whether each digit is a new high or a new low. Edit: Saved 1 byte thanks to @ETHproductions. Saved 2 bytes by starting with zero and adjusting afterwards. My previous method turned out to be similar to @Dennis's method, but took 54 bytes:
```
a=>a.reduce((r,b)=>[...r.map(e=>b+e),r.length*!b],[0])
```
[Answer]
# Perl, 33 bytes
Includes +1 for `-p`
Give vector as string without spaces on STDIN:
```
antsy.pl <<< 110
```
`antsy.pl`:
```
#!/usr/bin/perl -p
s%^|.%y/0//+($&?++$a:$b--).$"%eg
```
[Answer]
# JavaScript (ES6), 52 bytes
```
v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
```
Test it out:
```
f=v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
g=v=>console.log(f((v.match(/[01]/g)||[]).map(x=>+x)))
```
```
<input oninput="g(this.value)" value="010">
```
### Explanation
This takes advantage of the fact that when an antsy permutation is reversed, each item is either 1 more than the maximum of the previous low entries, or 1 less than the minimum of the previous high entries. By denoting a higher item as a `0` and a lower item as a `1`, we can create an exact one-to-one correspondance between the antsy permutations of length **n** and the binary vectors of length **n - 1**.
The best I could do with Dennis' technique is ~~57~~ 51 bytes:
```
v=>v.reduce((x,n)=>[...x.map(i=>i+n),!n*++j],[j=0])
v=>v.map(n=>x=[...x.map(i=>i+n),!n*++j],x=[j=0])&&x
```
xnor's solution is 56 (saved 1 byte thanks to @Neil):
```
l=>[1,...l].map((x,i)=>i*!x+eval(l.slice(i).join`+`||0))
```
[Answer]
## Haskell, 40 bytes
```
foldl(\r a->map(+0^a)r++[a*length r])[0]
```
[Dennis's Python solution](https://codegolf.stackexchange.com/a/98231/20260) golfs wonderfully in Haskell with `map` and `fold`. It's shorter than my attempts to port my [direct entrywise construction:](https://codegolf.stackexchange.com/a/98246/20260)
```
f l=[i*0^x+sum(drop i l)|(i,x)<-zip[0..]$0:l]
f l=[a+c-b*c|(a,c,b)<-zip3(scanr(+)0l)[0..]$0:l]
```
[Answer]
## Batch, 127 bytes
```
@set s=%*
@set/an=h=l=%s: =+%
@for %%b in (%*)do @call:%%b
:0
@echo %n%
@set/an=h+=1
@exit/b
:1
@echo %n%
@set/an=l-=1
```
Takes input as command-line parameters, output is line-separated. (It's possible to input as space-separated on STDIN for no extra cost.)
] |
[Question]
[
[Related](https://codegolf.stackexchange.com/questions/78615/calculate-the-kronecker-sum-of-two-matrices), but very different.
---
In the examples below, \$A\$ and \$B\$ will be \$2\times2\$ matrices, and the matrices are one-indexed.
A [Kronecker *product*](http://mathworld.wolfram.com/KroneckerProduct.html) has the following properties:
```
A⊗B = A(1,1)*B A(1,2)*B
A(2,1)*B A(2,2)*B
= A(1,1)*B(1,1) A(1,1)*B(1,2) A(1,2)*B(1,1) A(1,2)*B(1,2)
A(1,1)*B(2,1) A(1,1)*B(2,2) A(1,2)*B(2,1) A(1,2)*B(2,2)
A(2,1)*B(1,1) A(2,1)*B(1,2) A(2,2)*B(1,1) A(2,2)*B(1,2)
A(2,2)*B(2,1) A(2,2)*B(1,2) A(2,2)*B(2,1) A(2,2)*B(2,2)
```
**Challenge: Given two matrices, \$A\$ and \$B\$, return \$A\otimes B\$.**
* The size of the matrices will be at least \$1\times1\$. The maximum size will be whatever your computer / language can handle by default, but minimum \$5\times5\$ input.
* All input values will be non-negative integers
* Builtin functions that calculate Kronecker products or [Tensor](https://en.wikipedia.org/wiki/Tensor_product)/[Outer](https://en.wikipedia.org/wiki/Outer_product) products are not allowed
* In general: Standard rules regarding I/O format, program & functions, loopholes etc.
**Test cases:**
```
A =
1 2
3 4
B =
5 6
7 8
A⊗B =
5 6 10 12
7 8 14 16
15 18 20 24
21 24 28 32
B⊗A =
5 10 6 12
15 20 18 24
7 14 8 16
21 28 24 32
------------------------
A =
1
2
B =
1 2
A⊗B =
1 2
2 4
------------------------
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
B =
1 1
0 1
A⊗B =
16 16 2 2 3 3 13 13
0 16 0 2 0 3 0 13
5 5 11 11 10 10 8 8
0 5 0 11 0 10 0 8
9 9 7 7 6 6 12 12
0 9 0 7 0 6 0 12
4 4 14 14 15 15 1 1
0 4 0 14 0 15 0 1
B⊗A =
16 2 3 13 16 2 3 13
5 11 10 8 5 11 10 8
9 7 6 12 9 7 6 12
4 14 15 1 4 14 15 1
0 0 0 0 16 2 3 13
0 0 0 0 5 11 10 8
0 0 0 0 9 7 6 12
0 0 0 0 4 14 15 1
------------------------
A = 2
B = 5
A⊗B = 10
```
[Answer]
## CJam, 13 bytes
```
{ffff*::.+:~}
```
This is an unnamed block that expects two matrices on top of the stack and leaves their Kronecker product in their place.
[Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~ffff*%3A%3A.%2B%3A~%0A%0A%7Bs4Se%5B%7Df%25Sf*N*oNoNo%7D%2F&input=%5B%5B1%202%5D%20%5B3%204%5D%5D%20%5B%5B5%206%5D%20%5B7%208%5D%5D%0A%5B%5B5%206%5D%20%5B7%208%5D%5D%20%5B%5B1%202%5D%20%5B3%204%5D%5D%0A%5B%5B1%5D%20%5B2%5D%5D%20%5B%5B1%202%5D%5D%0A%5B%5B1%202%5D%5D%20%5B%5B1%5D%20%5B2%5D%5D%0A%5B%5B16%202%203%2013%5D%20%5B5%2011%2010%208%5D%20%5B9%207%206%2012%5D%20%5B4%2014%2015%201%5D%5D%20%5B%5B1%201%5D%20%5B0%201%5D%5D%0A%5B%5B1%201%5D%20%5B0%201%5D%5D%20%5B%5B16%202%203%2013%5D%20%5B5%2011%2010%208%5D%20%5B9%207%206%2012%5D%20%5B4%2014%2015%201%5D%5D)
### Explanation
This is just the Kronecker product part [from the previous answer](https://codegolf.stackexchange.com/a/78621/8478), therefore I'm here just reproducing the relevant parts of the previous explanation:
Here is a quick overview of CJam's infix operators for list manipulation:
* `f` expects a list and something else on the stack and maps the following *binary* operator over the list, passing in the other element as the second argument. E.g. `[1 2 3] 2 f*` and `2 [1 2 3] f*` both give `[2 4 6]`. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.
* `:` has two uses: if the operator following it is unary, this is a simple map. E.g. `[1 0 -1 4 -3] :z` is `[1 0 1 4 3]`, where `z` gets the modulus of a number. If the operator following it is binary, this will *fold* the operator instead. E.g. `[1 2 3 4] :+` is `10`.
* `.` vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. `[1 2 3] [5 7 11] .*` gives `[5 14 33]`.
```
ffff* e# This is the important step for the Kronecker product (but
e# not the whole story). It's an operator which takes two matrices
e# and replaces each cell of the first matrix with the second matrix
e# multiplied by that cell (so yeah, we'll end up with a 4D list of
e# matrices nested inside a matrix).
e# Now the ffff* is essentially a 4D version of the standard ff* idiom
e# for outer products. For an explanation of ff*, see the answer to
e# to the Kronecker sum challenge.
e# The first ff maps over the cells of the first matrix, passing in the
e# second matrix as an additional argument. The second ff then maps over
e# the second matrix, passing in the cell from the outer map. We
e# multiply them with *.
e# Just to recap, we've essentially got the Kronecker product on the
e# stack now, but it's still a 4D list not a 2D list.
e# The four dimensions are:
e# 1. Columns of the outer matrix.
e# 2. Rows of the outer matrix.
e# 3. Columns of the submatrices.
e# 4. Rows of the submatrices.
e# We need to unravel that into a plain 2D matrix.
::.+ e# This joins the rows of submatrices across columns of the outer matrix.
e# It might be easiest to read this from the right:
e# + Takes two rows and concatenates them.
e# .+ Takes two matrices and concatenates corresponding rows.
e# :.+ Takes a list of matrices and folds .+ over them, thereby
e# concatenating the corresponding rows of all matrices.
e# ::.+ Maps this fold operation over the rows of the outer matrix.
e# We're almost done now, we just need to flatten the outer-most level
e# in order to get rid of the distinction of rows of the outer matrix.
:~ e# We do this by mapping ~ over those rows, which simply unwraps them.
```
[Answer]
# MATLAB / Octave, ~~83~~ 42 Bytes
Saved **41** bytes, thanks to FryAmTheEggman!
```
@(A,B)cell2mat(arrayfun(@(n)n*B,A,'un',0))
```
[Test it here!](https://ideone.com/SASqUt)
**Breakdown**
`arrayfun` is a disguised for-loop that multiplies `n*B`, for a variable `n` defined by the second argument. This works because looping through a 2D matrix is the same as looping through a vector. I.e. `for x = A` is the same as `for x = A(:)`.
`'un',0` is equivalent to the more verbose `'UniformOutput', False`, and specifies that the output contains cells instead of scalars.
`cell2mat` is used to convert the cells back to a numeric matrix, which is then outputted.
[Answer]
# Jelly, ~~10~~ 9 bytes
```
×€€;"/€;/
```
Uses [Büttner's Algorithm](https://codegolf.stackexchange.com/a/78798/48934) (`ü` pronounced when trying to make an `ee` sound [as in meet] in the mouth-shape of an `oo` sound [as in boot]).
The `;"/€;/` is inspired by [Dennis Mitchell](https://codegolf.stackexchange.com/a/78668/48934). It was originally `Z€F€€;/` (which costs one more byte).
* [Test case 1](http://jelly.tryitonline.net/#code=w5figqzigqw7Ii_igqw7Lw&input=&args=W1sxLDJdLFszLDRdXQ+W1s1LDZdLFs3LDhdXQ)
* [Test case 2](http://jelly.tryitonline.net/#code=w5figqzigqw7Ii_igqw7Lw&input=&args=W1sxXSxbMl1d+W1sxLDJdXQ)
* [Test case 3](http://jelly.tryitonline.net/#code=w5figqzigqw7Ii_igqw7Lw&input=&args=W1sxNiwyLDMsMTNdLFs1LDExLDEwLDhdLFs5LDcsNiwxMl0sWzQsMTQsMTUsMV1d+W1sxLDFdLFswLDFdXQ)
* [Test case 4](http://jelly.tryitonline.net/#code=w5figqzigqw7Ii_igqw7Lw&input=&args=W1syXV0+W1s1XV0)
[Answer]
# Pyth, ~~14~~ ~~12~~ 11 bytes
```
JEsMs*RRRRJ
```
Translation of [Jelly answer](https://codegolf.stackexchange.com/a/78799/48934), which is based on [Büttner's Algorithm](https://codegolf.stackexchange.com/a/78798/48934) (`ü` pronounced when trying to make an `ee` sound [as in meet] in the mouth-shape of an `oo` sound [as in boot]).
[Try it online (test case 1)!](http://pyth.herokuapp.com/?code=JEsMs*RRRRJ&input=%5B%5B1%2C2%5D%2C%5B3%2C4%5D%5D%0A%5B%5B5%2C6%5D%2C%5B7%2C8%5D%5D&debug=0)
### Bonus: calculate `B⊗A` in the same number of bytes
```
JEsMs*LRLRJ
```
[Try it online (test case 1)!](http://pyth.herokuapp.com/?code=JEsMs*LRLRJ&input=%5B%5B1%2C2%5D%2C%5B3%2C4%5D%5D%0A%5B%5B5%2C6%5D%2C%5B7%2C8%5D%5D&debug=0)
[Answer]
# Julia, ~~40~~ ~~39~~ 37 bytes
```
A%B=hvcat(sum(A^0),map(a->a*B,A')...)
```
[Try it online!](http://julia.tryitonline.net/#code=QSVCPWh2Y2F0KHN1bShBXjApLG1hcChhLT5hKkIsQScpLi4uKQoKUChBLEIpID0gQSVCCgpkaXNwbGF5KFAoWzEgMgogICAgICAgICAgIDMgNF0sCgogICAgICAgICAgWzUgNgogICAgICAgICAgIDcgOF0pKQoKcHJpbnQoIlxuXG4iKQoKZGlzcGxheShQKFs1IDYKICAgICAgICAgICA3IDhdLAoKICAgICAgICAgIFsxIDIKICAgICAgICAgICAzIDRdKSkKCnByaW50KCJcblxuIikKCmRpc3BsYXkoUChbMTYgICAgIDIgICAgIDMgICAgMTMKICAgICAgICAgICAgNSAgICAxMSAgICAxMCAgICAgOAogICAgICAgICAgICA5ICAgICA3ICAgICA2ICAgIDEyCiAgICAgICAgICAgIDQgICAgMTQgICAgMTUgICAgIDFdLAoKICAgICAgICAgIFsxIDEKICAgICAgICAgICAwIDFdKSkKCnByaW50KCJcblxuIikKCmRpc3BsYXkoUChbMSAxCiAgICAgICAgICAgMCAxXSwKCiAgICAgICAgICBbMTYgICAgIDIgICAgIDMgICAgMTMKICAgICAgICAgICAgNSAgICAxMSAgICAxMCAgICAgOAogICAgICAgICAgICA5ICAgICA3ICAgICA2ICAgIDEyCiAgICAgICAgICAgIDQgICAgMTQgICAgMTUgICAgIDFdKSk&input=)
### How it works
* For matrices **A** and **B**, `map(a->a*B,A')` computes the Kronecker product **A⊗B**.
The result is a vector of matrix blocks with the dimensions of **B**.
We have to transpose **A** (with `'`) since matrices are stored in column-major order.
* `sum(A^0)` computes the sum of all entries of the identity matrix of **A**'s dimensions. For an **n×n** matrix **A**, this yields **n**.
* With first argument **n**, `hvcat` concatenates **n** matrix blocks horizontally, and the resulting (larger) blocks vertically.
[Answer]
# [R](https://www.r-project.org/), ~~98~~ 86 bytes
```
function(x,y,`+`=array)aperm(apply(x,1:2,`*`,y)+c(w<-dim(y),v<-dim(x)),c(1,3,2,4))+v*w
```
[Try it online!](https://tio.run/##TY/dCoMwDEbvfYreCM2MsKj7RS8U9gJju2/nNhCmk@LUPr1LJwMLh4Svh6Q1k/LlCL4SaSim56cpu@rdyBEtqkBl2hhtQbcPU0vdti/LN3SMUK0UWghKOaThvaqlBeznbgTAUhLGGGECEPSrYcrd8Fp3phqlV0pBWxQiYmKGYvQEnw0KImbNmdjP2YH7HeN8iuYsYcexcR4BNuY9ZAnerKuX8/UEXrHY595CuMa/yWuXav77feEVv5pPXw "R – Try It Online")
Reimplementation of `.kronecker` and `outer` for matrices. ~~I do think there's a golfier approach out there, maybe using `apply`?~~ 6 bytes golfed using `apply` and `array` thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!
The builtins are `%x%` for `kronecker(A,B,"*")` and `%o%` for `outer(A,B,"*")`.
# [R](https://www.r-project.org/), 120 bytes
```
function(A,B){l=list()
a=dim(A)
for(i in 1:a[2]-1)l[[i+1]]<-do.call(rbind,lapply(A,"*",B)[1:a+a[2]*i])
do.call(cbind,l)}
```
[Try it online!](https://tio.run/##TY3disIwEEbv8xSDV4lOxam6P2IvWvAFZPeq9CKmFAZiKtkuu7Lss9eJRTBwyPBxZr44lrDP4GyHyL9aOQ30ggC5sBZojQrkbRGIhJVk8DZl7zK/CsmnfMo24iS2ySODIfY/xQZP1/R/HD8PRlVPfU4TEq7wYUrts9oldey@gxu4D7rEyvz5wvPXoI2yRctnXYrVR83AAWhn67zJyPi65gU1zT5r@6Wz3ut44tCit5eLv8qd2Xwmt2pZWKSVOTdGPVQ3qeZ/7O6NqtMVlma8AQ "R – Try It Online")
Naive approach: calculate the subarrays \$a\_{ij}B\$ and bind them together in the appropriate order. There are probably golfs here too, but I don't think it'll be shorter than the one above.
[Answer]
# J, 10 bytes
This is one possible implementation.
```
[:,./^:2*/
```
# J, 13 bytes
This is a similar implementation, but instead uses J's ability to define ranks. It applies `*` between each element on the LHS with the entire RHS.
```
[:,./^:2*"0 _
```
## Usage
```
f =: <either definition>
(2 2 $ 1 2 3 4) f (2 2 $ 5 6 7 8)
5 6 10 12
7 8 14 16
15 18 20 24
21 24 28 32
(2 1 $ 1 2) f (1 2 $ 1 2)
1 2
2 4
2 f 5
10
```
[Answer]
# JavaScript (ES6), 79
Straightforward implementation with nested looping
```
(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t
```
**Test**
```
f=(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t
console.log=x=>O.textContent+=x+'\n'
function show(label, mat)
{
console.log(label)
console.log(mat.join`\n`)
}
;[
{a:[[1,2],[3,4]],b:[[5,6],[7,8]] },
{a:[[1],[2]],b:[[1,2]]},
{a:[[16,2,3,13],[5,11,10,8],[9,7,6,12],[4,14,15,1]],b:[[1,1],[0,1]]},
{a:[[2]],b:[[5]]}
].forEach(t=>{
show('A',t.a)
show('B',t.b)
show('A⊗B',f(t.a,t.b))
show('B⊗A',f(t.b,t.a))
console.log('-----------------')
})
```
```
<pre id=O></pre>
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
```
{⍪/,/⍺×⊂⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR7yp9Hf1HvbsOT3/U1fSod2vt/7RHbRMe9fY96mp@1LvmUe@WQ@uNH7VNfNQ3NTjIGUiGeHgG/3cEqWmbqGGoYKSpYaxgosnlBBUxVTDT1DBXsNDkclRIU3ACAA "APL (Dyalog Unicode) – Try It Online")
### How it Works
```
{ ... } ⍝ dfn that takes ⍺=A and ⍵=B
⍺×⊂⍵ ⍝ Product of each element of A with all of matrix B
⍝ Gives a nested array: an matrix of matrices
./ ⍝ Join rows
⍪/ ⍝ Join columns
```
] |
[Question]
[
# Introduction
Imagine you are on a two dimensional cartesian plane and want to determine your position on it. You know 3 points on that plane and your distance to each of them. While it is always possible to calculate your position from that, doing that in your head is pretty hard. So you decide to write a program for that.
# The Challenge
Given 3 points and your distance to them, output the cordinates of your position.
* Input and output may be in any convenient format, including using complex instead of real numbers. Please clarify in your answer which format you use.
* You will always get exactly 3 distinct points with their distance to you.
* The coordinates and distances will be floats with arbitrary precision. Your output has to be correct to 3 decimal places. Rounding is up to you. Please clarify in your answer.
* You may assume that the three points are not collinear, so there will be always an unique solution.
* You are not allowed to bruteforce the solution.
* You may not use any builtins that trivialize this particular problem. Builtins for vector norms, etc. are allowed though.
**Hint to get started:**
>
> Think about a circle around each of those 3 points with their distance to you as radius.
>
>
>
# Rules
* Function or full program allowed.
* [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission.
# Test cases
Input format for one point here is `[[x,y],d]` with `x` and `y` being the coordinates and `d` being the distance to this point. The 3 of those points are arranged in a list. Output will be `x` and then `y` in a list.
```
[[[1, 2], 1.414], [[1, 1], 2.236], [[2, 2], 1.0]] -> [2, 3]
[[[24.234, -13.902], 31.46], [[12.3242, 234.12], 229.953], [[23.983, 0.321], 25.572]] -> [-1.234, 4.567]
[[[973.23, -123.221], 1398.016], [[-12.123, -98.001], 990.537], [[-176.92, 0], 912.087]] -> [12.345, 892.234]
```
You can generate additional test cases with [this Pyth program](http://pyth.herokuapp.com/?code=%2B%2B%60m%2Cd.R.a%2CQd3.Q%22+-%3E+%22%60Q&input=%5B12.345%2C892.234%5D%0A%5B973.23%2C-123.221%5D%0A%5B-12.123%2C-98.001%5D%0A%5B-176.92%2C0%5D&debug=0). Location goes on the first line of the input and the 3 points are on the following 3 lines.
**Happy Coding!**
[Answer]
# Desmos, 122 bytes
[Online use](https://www.desmos.com/calculator). Copy+paste each equation into an equation box, click "add all" for each box, then click on the point of intersection, then enter in each value as appropriate. each of `A`, `B`, and `C` are the distances for the points `(a,b)`, `(c,d)`, and `(E,f)`, respectively. To get a square root in the value, type `sqrt` then the value in the box.
```
\left(x-a\right)^2+\left(y-b\right)^2=AA
\left(x-c\right)^2+\left(y-d\right)^2=BB
\left(x-E\right)^2+\left(y-f\right)^2=CC
```
[Verify the first test case](https://www.desmos.com/calculator/9hjpo9py6d).
Or you can take a look here:
[](https://i.stack.imgur.com/Fcl9M.png)
[Answer]
## C, ~~362~~ ~~348~~ 345 bytes
Input is given as a sequence of space-separated floats on stdin: `x1 y1 d1 x2 y2 d2 x3 y3 d3`. Output is similar on stdout: `x y`.
```
#define F"%f "
#define G float
#define T(x)(b.x*b.x-a.x*a.x)
typedef struct{G a;G b;G c;}C;G f(C a,C b,G*c){G x=b.b-a.b;*c=(T(a)+T(b)-T(c))/x/2;return(a.a-b.a)/x;}main(){C a,b,c;G x,y,z,t,m;scanf(F F F F F F F F F,&a.a,&a.b,&a.c,&b.a,&b.b,&b.c,&c.a,&c.b,&c.c);x=f(a,a.b==b.b?c:b,&y);z=f(b.b==c.b?a:b,c,&t);m=t-y;m/=x-z;printf(F F"\n",m,x*m+y);}
```
`C` is a structure type whose members are an x-coordinate `a`, a y-coordinate `b`, and a distance (radius) `c`. The function `f` takes two `C` structures and a pointer to a float, and determines the line at which the `C` (circles) intersect. The y-intercept of this line is placed into the pointed-to float, and the slope is returned.
The program calls `f` on two pairs of circles, then determines the intersection of the produced lines.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) 18.0, 23 [bytes](https://github.com/abrudz/SBCS)
```
-∘(+/)⍥(×⍨)⌹⍥(2-⌿⊢)¯2×⊢
```
[Try it online!](https://tio.run/##jY69TsMwFIX3PIVHmyqufZ2femaBlfIClZIipAoqtQOIMiFVEJqKDqjMoEpsmTrAgtS@yX2RcJ1IBCGoWK7tc853rnvDgZ9c9gbnJ356MU7PkjQprzj4bczfeWu79MUE87XA2dumgO0S8zvLtMbbJ4nL@yq2vvZcvg6TMXFhOilaIT/y2bPXRF0yXxGOsw9yxO9YxWD24mvMVlWMGPeXV7GjwFE@vXmLvH8jZY20dwBf0T5OHzCfY3azKQxOFzh/7B7t0zw@OOyWw/HI@dMF1wwEDS040M1LTkeVxWFPhoKHbupaZX1GmOc1LAQSTMA2hTbSKtcD0kBARSaQmt5AescwRapuuo2WQcQArLShYRDKMIa/VtjY0A63grqAWri7UrnTbEcqVUtxJC0w1SzRxrk6YtYqGZqYWcJUJ/6@6BM "APL (Dyalog Extended) – Try It Online")
A tacit infix function that can be called like `dists f pts`, where `pts` contains three centers' coordinates as a 3-row 2-column matrix, and `dists` contains three distances to the respective centers.
Uses 18.0 feature `⍥`. TIO's Dyalog Unicode is not updated yet from 17.1, so TIO link uses Dyalog Extended for demonstration purposes.
### How it works
Uses the same method as [R.T.'s Python answer](https://codegolf.stackexchange.com/a/75911/78410), i.e. constructing a linear system of equations and solving it.
The distance equations are necessarily quadratic. Then how did we get linear ones?
Let's consider just two circles, and denote the point we want to find as \$P\$, two circles' centers as \$C, D\$, and their radii as \$r\_C, r\_D\$. Also, let's use \$A\_x, A\_y\$ for the \$x\$- and \$y\$-coordinates of a point \$A\$. Then the following equations hold:
$$
(P\_x-C\_x)^2+(P\_y-C\_y)^2 =r\_C^2 \\
(P\_x-D\_x)^2+(P\_y-D\_y)^2 =r\_D^2 \\
$$
Then we expand them and subtract the second from the first:
$$
P\_x^2-2P\_xC\_x+C\_x^2+P\_y^2-2P\_yC\_y+C\_y^2=r\_C^2\\
P\_x^2-2P\_xD\_x+D\_x^2+P\_y^2-2P\_yD\_y+D\_y^2=r\_D^2\\
-2P\_x(C\_x-D\_x)+(C\_x^2-D\_x^2)-2P\_y(C\_y-D\_y)+(C\_y^2-D\_y^2)=r\_C^2-r\_D^2\\
-2P\_x(C\_x-D\_x)-2P\_y(C\_y-D\_y)=(r\_C^2-C\_x^2-C\_y^2)-(r\_D^2-D\_x^2-D\_y^2)
$$
We've just got one linear equation on \$P\_x\$ and \$P\_y\$. Since we have three circles given, we can take any two pairs and construct two equations, which then solving the system of equations gives the coordinates we want.
```
-∘(+/)⍥(×⍨)⌹⍥(2-⌿⊢)¯2×⊢ ⍝ Left: dists, Right: pts
-∘(+/)⍥(×⍨) ⍥(2-⌿⊢) ⍝ Constants part
⍥(×⍨) ⍝ Square each number in both dists and pts
∘(+/) ⍝ Row sums of squared pts
- ⍝ Subtract above from squared dists
⍥(2-⌿⊢) ⍝ Take pairwise difference
⍥(2-⌿⊢)¯2×⊢ ⍝ Coefficients part
¯2×⊢ ⍝ -2 times pts
⍥(2-⌿⊢) ⍝ Take pairwise difference between rows
⌹ ⍝ Solve linear equations
```
[Answer]
# Python - 172
Takes input as a list of tuples of form (x,y,d). Let me know if you see a way to golf this further, I feel like there must be but I can't figure it out!
```
import numpy as N
def L(P):
Z=[p[2]**2-p[0]**2-p[1]**2 for p in P];return N.linalg.solve([[P[i][0]-P[0][0],P[i][1]-P[0][1]]for i in[1,2]],[(Z[0]-Z[i])*0.5 for i in [1,2]])
```
] |
[Question]
[
The Scream™ Winter Sale is on and you just nabbed yourself an intense minimalist action game, [Super Square](http://superhexagon.com/). Upon playing it, you come to the realisation that either the game's just ridiculously hard or you're just *really* bad at it. In particular, there's this ["rain" pattern](http://cloud-4.steampowered.com/ugc/576727052452751097/9598AADF9E784D0992320A8C9FF8DB8BFBBCB58A/) that seems to get you every time...

Frustrated, you decide to give yourself a different challenge: Draw the rain pattern in ASCII art!
# Input
Input is a single positive integer indicating the size of the pattern `n`, given via STDIN or function argument.
# Output
Output is the rain pattern at the specified size, returned as a string or printed via STDOUT. Leading or trailing whitespace before or after the entire image is okay. Additionally, the image need not be flush to the left of the screen, but must be clearly discernible.
Here's `n = 10`:
```
...................
| ----------------- |
| ............... |
| | ------------- | |
| | ........... | |
| | | --------- | | |
| | | ....... | | |
| | | | ----- | | | |
| | | | ... | | | |
| | | | | - | | | | |
| | | | | | | | | |
| | | | | - | | | | |
| | | | ... | | | |
| | | | ----- | | | |
| | | ....... | | |
| | | --------- | | |
| | ........... | |
| | ------------- | |
| ............... |
| ----------------- |
...................
```
Here's `n = 5`:
```
---------
.......
| ----- |
| ... |
| | - | |
| | | |
| | - | |
| ... |
| ----- |
.......
---------
```
And finally, here's `n = 1` (just the innermost two walls):
```
-
-
```
# Construction (for extra clarity)
The playing area is divided into two pairs of quadrants like so:
```
AAAAAAAAA
B AAAAAAA B
BB AAAAA BB
BBB AAA BBB
BBBB A BBBB
BBBBB BBBBB
BBBB A BBBB
BBB AAA BBB
BB AAAAA BB
B AAAAAAA B
AAAAAAAAA
```
The upper/lower quadrants should alternate between horizontal walls represented by hyphens `-`, and gaps shaded with dots `.`. The left/right quadrants should alternate between spaces and vertical walls represented by pipes `|`. The main diagonals are empty, and should always be filled with spaces.
The rain pattern of size `n` has `2n` walls, with walls from the upper/lower quadrants closest to the centre and walls alternating between quadrants as we move away from the centre.
# Scoring
This is code-golf, so the code in the fewest bytes wins.
[Answer]
# Haskell 150 bytes
I realize it's not going to win, just wanted to post my first codegolf :D
```
q n=putStr$unlines$iterate(\l->let[a,b]=if l!!0!!1=='-'then"|."else" -";c=[a:s++[a]|s<-l];t=' ':[b|x<-l!!0]++" "in t:c++[t])[" - "," "," - "]!!(n-1)
```
Use by loading into GHCi and calling `q n` where `n` is the size.
Some examples:
```
*Main> q 1
-
-
*Main> q 2
...
| - |
| |
| - |
...
*Main> q 5
---------
.......
| ----- |
| ... |
| | - | |
| | | |
| | - | |
| ... |
| ----- |
.......
---------
*Main> q 10
...................
| ----------------- |
| ............... |
| | ------------- | |
| | ........... | |
| | | --------- | | |
| | | ....... | | |
| | | | ----- | | | |
| | | | ... | | | |
| | | | | - | | | | |
| | | | | | | | | |
| | | | | - | | | | |
| | | | ... | | | |
| | | | ----- | | | |
| | | ....... | | |
| | | --------- | | |
| | ........... | |
| | ------------- | |
| ............... |
| ----------------- |
...................
```
Someone can probably do better, I'm fairly new to Haskell.
[Answer]
# CJam, ~~93 87 78 61~~ 59 bytes
```
ri:K_+){K" |"*KKI-z:I-I2%:L+<SL>\+_W%L'-'.?I2*Ig-*@I0=>N}fI
```
Takes value `n` via STDIN
Few examples:
```
1
-
-
2
...
| - |
| |
| - |
...
5
---------
.......
| ----- |
| ... |
| | - | |
| | | |
| | - | |
| ... |
| ----- |
.......
---------
10
...................
| ----------------- |
| ............... |
| | ------------- | |
| | ........... | |
| | | --------- | | |
| | | ....... | | |
| | | | ----- | | | |
| | | | ... | | | |
| | | | | - | | | | |
| | | | | | | | | |
| | | | | - | | | | |
| | | | ... | | | |
| | | | ----- | | | |
| | | ....... | | |
| | | --------- | | |
| | ........... | |
| | ------------- | |
| ............... |
| ----------------- |
...................
```
This can be golfed a lot, which I will do first thing tomorrow.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Python, ~~204~~,~~198~~,191 bytes
```
r=lambda a,b,d=' ':d.join((a,b,a[::-1]))
def f(s,i,n):d=[r(s[:i],'.-'[(n-i)%2]*((n-i)*2-1))];return i==n and[r(s,' '*(2*(i%2)+1),'')]or d+f(s,i+1,n)+d
g=lambda n:'\n'.join(f('| '*(n/2),0,n))
```
"r" is a utility function that writes "b" surrounded by reflected "a", with an optional delimiter, (yes lambda parameters can have defaults).
"f" is recursive, generating sides and middle parts for each level
"g" is the rain function, which can be called with an integer to return the text requested.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 43 bytes
```
ʀ›ƛ?∷-½⌊‛| ?∷ßṘ*ð?∷ßðn?+∷*⁰n-›:‛.-$i*Ṡøm;øm
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%CA%80%E2%80%BA%C6%9B%3F%E2%88%B7-%C2%BD%E2%8C%8A%E2%80%9B%7C%20%3F%E2%88%B7%C3%9F%E1%B9%98*%C3%B0%3F%E2%88%B7%C3%9F%C3%B0n%3F%2B%E2%88%B7*%E2%81%B0n-%E2%80%BA%3A%E2%80%9B.-%24i*%E1%B9%A0%C3%B8m%3B%C3%B8m&inputs=1&header=&footer=)
A bit of a mess, but it works!
[Answer]
# Perl 5: 74 bytes (73 code + `-p`)
```
#!perl -p
s/.*/ /;$a=qw(- .)[$|--]x
s/.+/$"$&$"/g,s/^|\z/ $a
/g,$"^="\\"for($_)x$&
```
Takes parameter on the input (end of line character required for proper function):
```
$ perl rain.pl <<<"3"
-----
...
| - |
| |
| - |
...
-----
```
Ungolfed:
```
# Read the input line into $_ (-p)
s/.*/ /; # Replace the input with a space (plus the original eol), saves the parameter in $&
for(($_)x$&) { # Iterate $& times without affecting $_
$c=s/.+/$"$&$"/g; # Add $" (initially space) at the start and the end of each line, stores number of lines in $c
$a=("-",".")[$|--]x$c; # Set $a to $c times minus or dot using magic $| (which iterates over 1 and 0 on decrement)
s/^|\z/ $a \n/g; # Equivalent to $_=" $a \n$_ $a \n"
$"^="\\"; # Alternate $" between space and bar using the string xor
}
# Print $_ (-p)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
This ended up being longer than I expected, especially once I'd realised I'd gotten the pattern completely wrong! So I may be able to get it down smaller with a different method, but this'll do for now.
```
ôÈçXg-i.¹²Åû3wXÑÄÃûSi|)Ôê
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9MjnWGctaS65ssX7M3dY0cTD%2b1NpfCnU6g&input=MTA)
```
ôÈçXg-i.¹²Åû3wXÑÄÃûSi|)Ôê :Implicit input of integer
ô :Range [0,input]
È :Map each X
ç : X times repeat
Xg : Index X into
-i. : "-" prepended with "."
¹ : End repeat
² : Repeat twice
Å : Slice off the first character
û : Centre pad with spaces to length
3w : Maximum of 3 and
XÑ : X*2
Ä : Plus 1
à :End map
û :Centre pad each to the length of the longest with
S : Space
i| : Prepended with "|"
) :End padding
Ô :Reverse
ê :Palindromise
:Implicit output joined with newlines
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 120 bytes
```
def f(s):W=[(~s%2+i)//2*"| "+(~s-i)%2*" "+(s-i)*"'-"[i+s&1]for i in range(s+1)];[print(i+i[-2::-1])for i in W+W[-2::-1]]
```
[Try it online!](https://tio.run/##PYrBCsIwEETvfkUIVHe7hJoWQSJ@Rw4hB8FG95KGpBdB/PXYHHQOw7zHpNf6XOJ0TrnW@xxEgILGXh18SjcS4zCMvXwLSZtQjN1GDdru5UFJx1T22oclCxYcRb7FxwyFNPqLS5njCkzs1GiM0h7/P0v2J30NoHEX4NRKH7G2fAE "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
This challenge is partly an algorithms challenge, involves some math and is partly simply a fastest code challenge.
For some positive integer `n`, consider a uniformly random string of `1`s and `0`s of length `n` and call it `A`. Now also consider a second uniformly chosen random string of length `n` whose values are `-1`, `0,` or `1` and call it `B_pre`. Now let `B` be `B_pre`+`B_pre`. That is `B_pre` concatenated to itself.
Now consider the inner product of `A` and `B[j,...,j+n-1]` and call it `Z_j` and index from `1`.
**Task**
The output should be a list of `n+1` fractions. The `i`th term in the output should be the *exact* probability that *all* of the first `i` terms `Z_j` with `j <= i` equal `0`.
**Score**
The largest `n` for which your code gives the correct output in under 10 minutes on my machine.
**Tie Breaker**
If two answers have the same score, the one submitted first wins.
In the (very very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted.
**Hint**
Do not try to solve this problem mathematically, it's too hard. The best way in my view is to go back to basic definitions of probability from high school and find smart ways to get the code to do an exhaustive enumeration of the possibilities.
**Languages and libraries**
You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.
**My machine**
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.
---
Some test outputs. Consider just the first output for each `n`. That is when `i=1`. For `n` from 1 to 13 they should be.
```
1: 4/6
2: 18/36
3: 88/216
4: 454/1296
5: 2424/7776
6: 13236/46656
7: 73392/279936
8: 411462/1679616
9: 2325976/10077696
10: 13233628/60466176
11: 75682512/362797056
12: 434662684/2176782336
13: 2505229744/13060694016
```
You can also find a general formula for `i=1` at <http://oeis.org/A081671> .
**Leaderboard (split by language)**
* n = 15. **Python + parallel python + pypy** in 1min49s by Jakube
* n = 17. **C++** in 3min37s by Keith Randall
* n = 16. **C++** in 2min38s by kuroi neko
[Answer]
# Python 2 using pypy and pp: n = 15 in 3 minutes
Also just a simple brute force. Interesting to see, that I nearly get the same same speed as kuroi neko with C++. My code can reach `n = 12` in about 5 minutes. And I only run it on one virtual core.
## edit: Reduce search space by a factor of `n`
I noticed, that a cycled vector `A*` of `A` produces the same numbers as probabilities (same numbers) as the original vector `A` when I iterate over `B`.
E.g. The vector `(1, 1, 0, 1, 0, 0)` has the same probabilities as each of the vectors `(1, 0, 1, 0, 0, 1)`, `(0, 1, 0, 0, 1, 1)`, `(1, 0, 0, 1, 1, 0)`, `(0, 0, 1, 1, 0, 1)` and `(0, 1, 1, 0, 1, 0)` when choosing a random `B`. Therefore I don't have to iterate over each of these 6 vectors, but only about 1 and replace `count[i] += 1` with `count[i] += cycle_number`.
This reduces the complexity from `Theta(n) = 6^n` to `Theta(n) = 6^n / n`. Therefore for `n = 13` it's about 13 times as fast as my previous version. It calculates `n = 13` in about 2 minutes 20 seconds. For `n = 14` it is still a little bit too slow. It takes about 13 minutes.
## edit 2: Multi-core-programming
Not really happy with the next improvement. I decided to also try to execute my program on multiple cores. On my 2 + 2 cores I now can calculate `n = 14` in about 7 minutes. Only a factor of 2 improvement.
The code is available in this github repo: [Link](https://github.com/jakobkogler/you-do-the-math/blob/master/you-do-the-math.py). The multi-core programming makes is a little bit ugly.
## edit 3: Reducing search space for `A` vectors and `B` vectors
I noticed the same mirror-symmetry for the vectors `A` as kuroi neko did. Still not sure, why this works (and if it works for each `n`).
The reducing of the search space for `B` vectors is a bit cleverer. I replaced the generation of the vectors (`itertools.product`), with an own function. Basically, I start with an empty list and put it on a stack. Until the stack is empty, I remove a list, if it has not the same lenght as `n`, I generate 3 other lists (by appending -1, 0, 1) and pushing them onto the stack. I a list has the same length as `n`, I can evaluate the sums.
Now that I generate the vectors myself, I can filter them depending on if I can reach the sum = 0 or not. E.g. if my vector `A` is `(1, 1, 1, 0, 0)`, and my vector `B` looks `(1, 1, ?, ?, ?)`, I know, that I cannot fill the `?` with values, so that `A*B = 0`. So I don't have to iterate over all those 6 vectors `B` of the form `(1, 1, ?, ?, ?)`.
We can improve on this, if we ignore the values for 1. As noted in the question, for the values for `i = 1` are the sequence [A081671](https://oeis.org/A081671). There are many ways to calculate those. I choose the simple recurrence: `a(n) = (4*(2*n-1)*a(n-1) - 12*(n-1)*a(n-2)) / n`. Since we can calculate `i = 1` in basically no time, we can filter more vectors for `B`. E.g. `A = (0, 1, 0, 1, 1)` and `B = (1, -1, ?, ?, ?)`. We can ignore vectors, where the first `? = 1`, because the `A * cycled(B) > 0`, for all these vectors. I hope you can follow. It's probably not the best example.
With this I can calculate `n = 15` in 6 minutes.
## edit 4:
Quickly implemented kuroi neko's great idea, which says, that `B` and `-B` produces the same results. Speedup x2. Implementation is only a quick hack, though. `n = 15` in 3 minutes.
## Code:
For the complete code visit [Github](https://github.com/jakobkogler/you-do-the-math/blob/master/you-do-the-math.py). The following code is only a representation of the main features. I left out imports, multicore programming, printing the results, ...
```
count = [0] * n
count[0] = oeis_A081671(n)
#generating all important vector A
visited = set(); todo = dict()
for A in product((0, 1), repeat=n):
if A not in visited:
# generate all vectors, which have the same probability
# mirrored and cycled vectors
same_probability_set = set()
for i in range(n):
tmp = [A[(i+j) % n] for j in range(n)]
same_probability_set.add(tuple(tmp))
same_probability_set.add(tuple(tmp[::-1]))
visited.update(same_probability_set)
todo[A] = len(same_probability_set)
# for each vector A, create all possible vectors B
stack = []
for A, cycled_count in dict_A.iteritems():
ones = [sum(A[i:]) for i in range(n)] + [0]
# + [0], so that later ones[n] doesn't throw a exception
stack.append(([0] * n, 0, 0, 0, False))
while stack:
B, index, sum1, sum2, used_negative = stack.pop()
if index < n:
# fill vector B[index] in all possible ways,
# so that it's still possible to reach 0.
if used_negative:
for v in (-1, 0, 1):
sum1_new = sum1 + v * A[index]
sum2_new = sum2 + v * A[index - 1 if index else n - 1]
if abs(sum1_new) <= ones[index+1]:
if abs(sum2_new) <= ones[index] - A[n-1]:
C = B[:]
C[index] = v
stack.append((C, index + 1, sum1_new, sum2_new, True))
else:
for v in (0, 1):
sum1_new = sum1 + v * A[index]
sum2_new = sum2 + v * A[index - 1 if index else n - 1]
if abs(sum1_new) <= ones[index+1]:
if abs(sum2_new) <= ones[index] - A[n-1]:
C = B[:]
C[index] = v
stack.append((C, index + 1, sum1_new, sum2_new, v == 1))
else:
# B is complete, calculate the sums
count[1] += cycled_count # we know that the sum = 0 for i = 1
for i in range(2, n):
sum_prod = 0
for j in range(n-i):
sum_prod += A[j] * B[i+j]
for j in range(i):
sum_prod += A[n-i+j] * B[j]
if sum_prod:
break
else:
if used_negative:
count[i] += 2*cycled_count
else:
count[i] += cycled_count
```
## Usage:
You have to install pypy (for Python 2!!!). The parallel python module isn't ported for Python 3. Then you have to install the parallel python module [pp-1.6.4.zip](http://www.parallelpython.com/downloads/pp/pp-1.6.4.zip). Extract it, `cd` into the folder and call `pypy setup.py install`.
Then you can call my program with
`pypy you-do-the-math.py 15`
It will automatically determine the number of cpu's. There may be some error messages after finishing the program, just ignore them. `n = 16` should be possible on your machine.
## Output:
```
Calculation for n = 15 took 2:50 minutes
1 83940771168 / 470184984576 17.85%
2 17379109692 / 470184984576 3.70%
3 3805906050 / 470184984576 0.81%
4 887959110 / 470184984576 0.19%
5 223260870 / 470184984576 0.05%
6 67664580 / 470184984576 0.01%
7 30019950 / 470184984576 0.01%
8 20720730 / 470184984576 0.00%
9 18352740 / 470184984576 0.00%
10 17730480 / 470184984576 0.00%
11 17566920 / 470184984576 0.00%
12 17521470 / 470184984576 0.00%
13 17510280 / 470184984576 0.00%
14 17507100 / 470184984576 0.00%
15 17506680 / 470184984576 0.00%
```
## Notes and ideas:
* I have a i7-4600m processor with 2 cores and 4 threads. It doesn't
matter If I use 2 or 4 threads. The cpu-usage is 50% with 2 threads and 100% with 4 threads, but it still takes the same amount of time. I don't know why. I checked, that each thread only has to the the half amout of data, when there are 4 threads, checked the results, ...
* I use a lot of lists. Python isn't quite efficient in storing, I have to copy lots of lists, ... So I thought of using an integer instead. I could use the bits 00 (for 0) and 11 (for 1) in the vector A, and the bits 10 (for -1), 00 (for 0) and 01 (for 1) in the vector B. For the product of A and B, I would only have to calculate `A & B` and count the 01 and 10 blocks. Cycling can be done with shifting the vector and using masks, ... I actually implemented all this, you can find it in some of my older commits on Github. But it turned out, to be slower than with lists. I guess, pypy really optimizes list operations.
[Answer]
## C++, n=18 in 9 min on 8 threads
(Let me know if it makes it under 10 minutes on your machine.)
I take advantage of several forms of symmetry in the B array. Those are cyclic (shift by one position), reversal (reverse the order of the elements), and sign (take the negative of each element). First I compute the list of Bs we need to try and their weight. Then each B is run through a fast routine (using bitcount instructions) for all 2^n values of A.
Here's the result for n==18:
```
> time ./a.out 18
1: 16547996212044 / 101559956668416
2: 3120508430672 / 101559956668416
3: 620923097438 / 101559956668416
4: 129930911672 / 101559956668416
5: 28197139994 / 101559956668416
6: 6609438092 / 101559956668416
7: 1873841888 / 101559956668416
8: 813806426 / 101559956668416
9: 569051084 / 101559956668416
10: 510821156 / 101559956668416
11: 496652384 / 101559956668416
12: 493092812 / 101559956668416
13: 492186008 / 101559956668416
14: 491947940 / 101559956668416
15: 491889008 / 101559956668416
16: 449710584 / 101559956668416
17: 418254922 / 101559956668416
18: 409373626 / 101559956668416
real 8m55.854s
user 67m58.336s
sys 0m5.607s
```
Compile the program below with `g++ --std=c++11 -O3 -mpopcnt dot.cc`
```
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
typedef long long word;
word n;
void inner(word bpos, word bneg, word w, word *cnt) {
word maxi = n-1;
for(word a = (1<<n)-1; a >= 0; a--) {
word m = a;
for(word i = maxi; i >= 0; i--, m <<= 1) {
if(__builtin_popcount(m&bpos) != __builtin_popcount(m&bneg))
break;
cnt[i]+=w;
}
}
}
word pow(word n, word e) {
word r = 1;
for(word i = 0; i < e; i++) r *= n;
return r;
}
typedef struct {
word b;
word weight;
} Bentry;
mutex block;
Bentry *bqueue;
word bhead;
word btail;
word done = -1;
word maxb;
// compute -1*b
word bneg(word b) {
word w = 1;
for(word i = 0; i < n; i++, w *= 3) {
word d = b / w % 3;
if(d == 1)
b += w;
if(d == 2)
b -= w;
}
return b;
}
// rotate b one position
word brot(word b) {
b *= 3;
b += b / maxb;
b %= maxb;
return b;
}
// reverse b
word brev(word b) {
word r = 0;
for(word i = 0; i < n; i++) {
r *= 3;
r += b % 3;
b /= 3;
}
return r;
}
// individual thread's work routine
void work(word *cnt) {
while(true) {
// get a queue entry to work on
block.lock();
if(btail == done) {
block.unlock();
return;
}
if(bhead == btail) {
block.unlock();
this_thread::sleep_for(chrono::microseconds(10));
continue;
}
word i = btail++;
block.unlock();
// thread now owns bqueue[i], work on it
word b = bqueue[i].b;
word w = 1;
word bpos = 0;
word bneg = 0;
for(word j = 0; j < n; j++, b /= 3) {
word d = b % 3;
if(d == 1)
bpos |= 1 << j;
if(d == 2)
bneg |= 1 << j;
}
bpos |= bpos << n;
bneg |= bneg << n;
inner(bpos, bneg, bqueue[i].weight, cnt);
}
}
int main(int argc, char *argv[]) {
n = atoi(argv[1]);
// allocate work queue
maxb = pow(3, n);
bqueue = (Bentry*)(malloc(maxb*sizeof(Bentry)));
// start worker threads
word procs = thread::hardware_concurrency();
vector<thread> threads;
vector<word*> counts;
for(word p = 0; p < procs; p++) {
word *cnt = (word*)calloc(64+n*sizeof(word), 1);
threads.push_back(thread(work, cnt));
counts.push_back(cnt);
}
// figure out which Bs we actually want to test, and with which weights
bool *bmark = (bool*)calloc(maxb, 1);
for(word i = 0; i < maxb; i++) {
if(bmark[i]) continue;
word b = i;
word w = 0;
for(word j = 0; j < 2; j++) {
for(word k = 0; k < 2; k++) {
for(word l = 0; l < n; l++) {
if(!bmark[b]) {
bmark[b] = true;
w++;
}
b = brot(b);
}
b = bneg(b);
}
b = brev(b);
}
bqueue[bhead].b = i;
bqueue[bhead].weight = w;
block.lock();
bhead++;
block.unlock();
}
block.lock();
done = bhead;
block.unlock();
// add up results from threads
word *cnt = (word*)calloc(n,sizeof(word));
for(word p = 0; p < procs; p++) {
threads[p].join();
for(int i = 0; i < n; i++) cnt[i] += counts[p][i];
}
for(word i = 0; i < n; i++)
printf("%2lld: %14lld / %14lld\n", i+1, cnt[n-1-i], maxb<<n);
return 0;
}
```
[Answer]
# woolly bully - C++ - way too slow
Well since a better programmer took on the C++ implementation, I'm calling quits for this one.
```
#include <cstdlib>
#include <cmath>
#include <vector>
#include <bitset>
#include <future>
#include <iostream>
#include <iomanip>
using namespace std;
/*
6^^n events will be generated, so the absolute max
that can be counted by a b bits integer is
E(b*log(2)/log(6)), i.e. n=24 for a 64 bits counter
To enumerate 3 possible values of a size n vector we need
E(n*log(3)/log(2))+1 bits, i.e. 39 bits
*/
typedef unsigned long long Counter; // counts up to 6^^24
typedef unsigned long long Benumerator; // 39 bits
typedef unsigned long Aenumerator; // 24 bits
#define log2_over_log6 0.3869
#define A_LENGTH ((size_t)(8*sizeof(Counter)*log2_over_log6))
#define B_LENGTH (2*A_LENGTH)
typedef bitset<B_LENGTH> vectorB;
typedef vector<Counter> OccurenceCounters;
// -----------------------------------------------------------------
// multithreading junk for CPUs detection and allocation
// -----------------------------------------------------------------
int number_of_CPUs(void)
{
int res = thread::hardware_concurrency();
return res == 0 ? 8 : res;
}
#ifdef __linux__
#include <sched.h>
void lock_on_CPU(int cpu)
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
}
#elif defined (_WIN32)
#include <Windows.h>
#define lock_on_CPU(cpu) SetThreadAffinityMask(GetCurrentThread(), 1 << cpu)
#else
// #warning is not really standard, so this might still cause compiler errors on some platforms. Sorry about that.
#warning "Thread processor affinity settings not supported. Performances might be improved by providing a suitable alternative for your platform"
#define lock_on_CPU(cpu)
#endif
// -----------------------------------------------------------------
// B values generator
// -----------------------------------------------------------------
struct Bvalue {
vectorB p1;
vectorB m1;
};
struct Bgenerator {
int n; // A length
Aenumerator stop; // computation limit
Aenumerator zeroes; // current zeroes pattern
Aenumerator plusminus; // current +1/-1 pattern
Aenumerator pm_limit; // upper bound of +1/-1 pattern
Bgenerator(int n, Aenumerator start=0, Aenumerator stop=0) : n(n), stop(stop)
{
// initialize generator so that first call to next() will generate first value
zeroes = start - 1;
plusminus = -1;
pm_limit = 0;
}
// compute current B value
Bvalue value(void)
{
Bvalue res;
Aenumerator pm = plusminus;
Aenumerator position = 1;
int i_pm = 0;
for (int i = 0; i != n; i++)
{
if (zeroes & position)
{
if (i_pm == 0) res.p1 |= position; // first non-zero value fixed to +1
else
{
if (pm & 1) res.m1 |= position; // next non-zero values
else res.p1 |= position;
pm >>= 1;
}
i_pm++;
}
position <<= 1;
}
res.p1 |= (res.p1 << n); // concatenate 2 Bpre instances
res.m1 |= (res.m1 << n);
return res;
}
// next value
bool next(void)
{
if (++plusminus == pm_limit)
{
if (++zeroes == stop) return false;
plusminus = 0;
pm_limit = (1 << vectorB(zeroes).count()) >> 1;
}
return true;
}
// calibration: produces ranges that will yield the approximate same number of B values
vector<Aenumerator> calibrate(int segments)
{
// setup generator for the whole B range
zeroes = 0;
stop = 1 << n;
plusminus = -1;
pm_limit = 0;
// divide range into (nearly) equal chunks
Aenumerator chunk_size = ((Aenumerator)pow (3,n)-1) / 2 / segments;
// generate bounds for zeroes values
vector<Aenumerator> res(segments + 1);
int bound = 0;
res[bound] = 1;
Aenumerator count = 0;
while (next()) if (++count % chunk_size == 0) res[++bound] = zeroes;
res[bound] = stop;
return res;
}
};
// -----------------------------------------------------------------
// equiprobable A values merging
// -----------------------------------------------------------------
static char A_weight[1 << A_LENGTH];
struct Agroup {
vectorB value;
int count;
Agroup(Aenumerator a = 0, int length = 0) : value(a), count(length) {}
};
static vector<Agroup> A_groups;
Aenumerator reverse(Aenumerator n) // this works on N-1 bits for a N bits word
{
Aenumerator res = 0;
if (n != 0) // must have at least one bit set for the rest to work
{
// construct left-padded reverse value
for (int i = 0; i != 8 * sizeof(n)-1; i++)
{
res |= (n & 1);
res <<= 1;
n >>= 1;
}
// shift right to elimitate trailing zeroes
while (!(res & 1)) res >>= 1;
}
return res;
}
void generate_A_groups(int n)
{
static bitset<1 << A_LENGTH> lookup(0);
Aenumerator limit_A = (Aenumerator)pow(2, n);
Aenumerator overflow = 1 << n;
for (char & w : A_weight) w = 0;
// gather rotation cycles
for (Aenumerator a = 0; a != limit_A; a++)
{
Aenumerator rotated = a;
int cycle_length = 0;
for (int i = 0; i != n; i++)
{
// check for new cycles
if (!lookup[rotated])
{
cycle_length++;
lookup[rotated] = 1;
}
// rotate current value
rotated <<= 1;
if (rotated & overflow) rotated |= 1;
rotated &= (overflow - 1);
}
// store new cycle
if (cycle_length > 0) A_weight[a] = cycle_length;
}
// merge symetric groups
for (Aenumerator a = 0; a != limit_A; a++)
{
// skip already grouped values
if (A_weight[a] == 0) continue;
// regroup a symetric pair
Aenumerator r = reverse(a);
if (r != a)
{
A_weight[a] += A_weight[r];
A_weight[r] = 0;
}
}
// generate groups
for (Aenumerator a = 0; a != limit_A; a++)
{
if (A_weight[a] != 0) A_groups.push_back(Agroup(a, A_weight[a]));
}
}
// -----------------------------------------------------------------
// worker thread
// -----------------------------------------------------------------
OccurenceCounters solve(int n, int index, Aenumerator Bstart, Aenumerator Bstop)
{
OccurenceCounters consecutive_zero_Z(n, 0); // counts occurences of the first i terms of Z being 0
// lock on assigned CPU
lock_on_CPU(index);
// enumerate B vectors
Bgenerator Bgen(n, Bstart, Bstop);
while (Bgen.next())
{
// get next B value
Bvalue B = Bgen.value();
// enumerate A vector groups
for (const auto & group : A_groups)
{
// count consecutive occurences of inner product equal to zero
vectorB sliding_A(group.value);
for (int i = 0; i != n; i++)
{
if ((sliding_A & B.p1).count() != (sliding_A & B.m1).count()) break;
consecutive_zero_Z[i] += group.count;
sliding_A <<= 1;
}
}
}
return consecutive_zero_Z;
}
// -----------------------------------------------------------------
// main
// -----------------------------------------------------------------
#define die(msg) { cout << msg << endl; exit (-1); }
int main(int argc, char * argv[])
{
int n = argc == 2 ? atoi(argv[1]) : 16; // arbitray value for debugging
if (n < 1 || n > 24) die("vectors of lenght between 1 and 24 is all I can (try to) compute, guv");
auto begin = time(NULL);
// one worker thread per CPU
int num_workers = number_of_CPUs();
// regroup equiprobable A values
generate_A_groups(n);
// compute B generation ranges for proper load balancing
vector<Aenumerator> ranges = Bgenerator(n).calibrate(num_workers);
// set workers to work
vector<future<OccurenceCounters>> workers(num_workers);
for (int i = 0; i != num_workers; i++)
{
workers[i] = async(
launch::async, // without this parameter, C++ will decide whether execution shall be sequential or asynchronous (isn't C++ fun?).
solve, n, i, ranges[i], ranges[i+1]);
}
// collect results
OccurenceCounters result(n + 1, 0);
for (auto& worker : workers)
{
OccurenceCounters partial = worker.get();
for (size_t i = 0; i != partial.size(); i++) result[i] += partial[i]*2; // each result counts for a symetric B pair
}
for (Counter & res : result) res += (Counter)1 << n; // add null B vector contribution
result[n] = result[n - 1]; // the last two probabilities are equal by construction
auto duration = time(NULL) - begin;
// output
cout << "done in " << duration / 60 << ":" << setw(2) << setfill('0') << duration % 60 << setfill(' ')
<< " by " << num_workers << " worker thread" << ((num_workers > 1) ? "s" : "") << endl;
Counter events = (Counter)pow(6, n);
int width = (int)log10(events) + 2;
cout.precision(5);
for (int i = 0; i <= n; i++) cout << setw(2) << i << setw(width) << result[i] << " / " << events << " " << fixed << (float)result[i] / events << endl;
return 0;
}
```
## Building the executable
It's a standalone C++11 source that compiles without warnings and runs smoothly on:
* Win7 & MSVC2013
* Win7 & MinGW - g++4.7
* Ubuntu & g++4.8 (in a VirtualBox VM with 2 CPUs allocated)
If you compile with g++, use : **g++ -O3 -pthread -std=c++11**
forgetting about `-pthread` will produce a nice and friendly core dump.
## Optimizations
1. The last Z term is equal to the first (Bpre x A in both cases), so the last two results are always equal, which dispenses of computing the last Z value.
The gain is neglectible, but coding it costs nothing so you might as well use it.
2. As Jakube discovered, all cyclic values of a given A vector produce the same probabilities.
You can compute these with a single instance of A and multiply the result by the number of its possible rotations. Rotation groups can easily be pre-computed in a neglectible amount of time, so this is a huge net speed gain.
Since the number of permutations of an n length vector is n-1, the complexity drops from o(6n) to o(6n/(n-1)), basically going a step further for the same computation time.
3. It appears pairs of symetric patterns also generate the same probabilities. For instance, 100101 and 101001.
I have no mathematical proof of that, but intuitively when presented with all possible B patterns, each symetric A value will be convoluted with the corresponding symetric B value for the same global outcome.
This allows to regroup some more A vectors, for an approximative 30% reduction of A groups number.
4. **WRONG** For some semi-mysterious reason, all patterns with only one or two bits set produce the same result. This does not represent that many distinct groups, but still they can be merged at virtually no cost.
5. The vectors B and -B (B with all components multiplied by -1) produce the same probabilities.
(for instance [ 1, 0,-1, 1] and [-1, 0, 1,-1]).
Except for the null vector (all components equal to 0), B and -B form a pair of *distinct* vectors.
This allows to cut the number of B values in half by considering only one of each pair and multiplying its contribution by 2, adding the known global contribution of null B to each probability only once.
## How it works
The number of B values is huge (3n), so pre-computing them would require indecent amounts of memory, which would slow down computation and eventually exhaust available RAM.
Unfortunately, I could not find a simple way of enumerating the half set of optimized B values, so I resorted to coding a dedicated generator.
The mighty B generator was a lot of fun to code, though languages that support yield mechanisms would have allowed to program it in a much more elegant way.
What it does in a nutshell is consider the "skeleton" of a Bpre vector as a binary vector where 1s represent actual -1 or +1 values.
Among all these +1/-1 potential values, the first one is fixed to +1 (thus selecting one of the possible B/-B vector), and all remaining possible +1/-1 combinations are enumerated.
Lastly, a simple calibration system ensures each worker thread will process a range of values of approximately the same size.
A values are heavily filtered for regrouping in equiprobable chunks.
This is done in a pre-computing phase that brute-force examines all possible values.
This part has a neglectible O(2n) execution time and does not need to be optimized (the code being already unreadable enough as it is!).
To evaluate the inner product (which needs only be tested against zero), the -1 and 1 components of B are regrouped into binary vectors.
The inner product is null if (and only if) there is an equal number of +1s and -1s among the B values corresponding to non-zero A values.
This can be computed with simple masking and bit count operations, helped by `std::bitset` that will produce reasonably efficient bit count code without having to resort to ugly intrinsic instructions.
The work is equally divided among cores, with forced CPU affinity (every little bit helps, or so they say).
## Example result
```
C:\Dev\PHP\_StackOverflow\C++\VectorCrunch>release\VectorCrunch.exe 16
done in 8:19 by 4 worker threads
0 487610895942 / 2821109907456 0.17284
1 97652126058 / 2821109907456 0.03461
2 20659337010 / 2821109907456 0.00732
3 4631534490 / 2821109907456 0.00164
4 1099762394 / 2821109907456 0.00039
5 302001914 / 2821109907456 0.00011
6 115084858 / 2821109907456 0.00004
7 70235786 / 2821109907456 0.00002
8 59121706 / 2821109907456 0.00002
9 56384426 / 2821109907456 0.00002
10 55686922 / 2821109907456 0.00002
11 55508202 / 2821109907456 0.00002
12 55461994 / 2821109907456 0.00002
13 55451146 / 2821109907456 0.00002
14 55449098 / 2821109907456 0.00002
15 55449002 / 2821109907456 0.00002
16 55449002 / 2821109907456 0.00002
```
## Performances
Multithreading should work perfectly on this, though only "true" cores will fully contribute to computation speed. My CPU has only 2 cores for 4 CPUs, and the gain over a single-threaded version is "only" about 3.5.
## Compilers
An initial problem with multithreading led me to believe the GNU compilers were performing worse than Microsoft.
After more thorough testing, it appears g++ wins the day yet again, producing approximatively 30% faster code (the same ratio I noticed on two other computation-heavy projects).
Notably, the `std::bitset` library is implemented with dedicated bit count instructions by g++ 4.8, while MSVC 2013 uses only loops of conventional bit shifts.
As one could have expected, compiling in 32 or 64 bits makes no difference.
## Further refinements
I noticed a few A groups producing the same probabilities after all the reduction operations, but I could not identify a pattern that would allow to regroup them.
Here are the pairs I noticed for n=11:
```
10001011 and 10001101
100101011 and 100110101
100101111 and 100111101
100110111 and 100111011
101001011 and 101001101
101011011 and 101101011
101100111 and 110100111
1010110111 and 1010111011
1011011111 and 1011111011
1011101111 and 1011110111
```
] |
[Question]
[
This is the second of two challenges about "pulling functions taut". [Here is the slightly simpler Part I](https://codegolf.stackexchange.com/q/38313/8478).
Let's drive *m* nails into a board at positions *(x1, y1)* to *(xm, ym)*. Tie a rubber band to the first and last of those and stretch around the other nails, such that the band traverses all nails in order. Note that the rubber band now describes a piecewise linear parameterised function *(x(t), y(t))* in 2D space.
Now drive another *n* nails into the board, at positions *(x1, y1)* to *(xn, yn)*. If we now remove all of the original *m* nails *except* the first and last one (which the ends of the rubber is tied to), the rubber band will shorten until it's lying taut around the new nails, yielding another piecewise linear function.
As an example, take *m = 12* initial nails at positions *(0, 0), (2, -1), (3/2, 4/3), (7/2, 1/3), (11/2, 16/3), (1, 16/3), (0, 1), (7, -2), (3, 4), (8, 1), (3, -1), (11, 0)*, and *n = 10* further nails at positions *(1, 1), (3, 1), (4, 4), (1, 3), (2, 2), (5, -1), (5, 0), (6, 2), (7, 1), (6, 0)*. The following three plots show the process described above:

For larger version: Right-click --> Open in new tab
And here is an animation of the rubber band tightening if you have some difficulty visualising it:

## The Challenge
Given two lists of "nails", plot the taut rubber band around the second list if it starts from the shape traversing all the nails in the first list.
You may write a program or function and take input via STDIN, ARGV or function argument. You can either display the result on the screen or save an image to a file.
If the result is rasterised, it needs to be at least 300 pixels on each side. The final rubber band and nails must cover at least 75% of the horizontal and vertical extent of the image. The length scales of *x* and *y* have to be the same. You need to show the nails in the second set (using at least 3x3 pixels) and the string (at least 1 pixel wide). You may or may not include the axes.
Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the nails and the string (those may have different colours though).
You may assume that all nails in the second list are at least 10-5 units away from initial shape of the rubber band (so that you don't need to worry about floating-point inaccuracy).
This is code golf, so the shortest answer (in bytes) wins.
## More Examples
Here are two more examples:
```
{{1, 1}, {3, 3}, {2, 4}, {1, 3}, {4, 0}, {3, -1}, {2, 0}, {4, 2}}
{{2, 1}, {3, 2}, {1, 2}, {4, 1}}
```

```
{{1, 1}, {3, 1}, {3, 3}, {1, 3}, {1, 5}, {3, 5}, {-1, 3}, {-1, 0}, {3, 4}, {5, 1}, {5, -1}, {7, -1}, {3, 7}, {7, 5}}
{{0, 0}, {0, 2}, {0, 4}, {0, 6}, {2, 0}, {2, 2}, {2, 4}, {2, 6}, {4, 0}, {4, 2}, {4, 4}, {4, 6}, {6, 0}, {6, 2}, {6, 4}, {6, 6}}
```

And here is one example that shows the significance of two of the initial nails remaining. The result should be *b* and **not** *a*:
```
{{0, 0}, {0, 1}, {-1, 1}, {-1, -1}, {1, -1}, {1, 0}}
{{-0.5, 0.5}}
```

Thanks to Ell for providing this example.
[Answer]
## Python + matplotlib, 688
```
from pylab import*
C=cross
P,M=eval("map(array,input()),"*2)
P,N=[[P[0]]+L+[P[-1]]for L in P,M]
W=[.5]*len(P)
def T(a,c,b):
I=[(H[0]**2,id(n),n)for n in N for H in[(C(n-a,b-a),C(n-b,c-b),C(n-c,a-c))]if(min(H)*max(H)>=0)*H[1]*H[2]]
if I:d=max(I)[2];A=T(a,c,d);B=T(d,c,b);return[A[0]+[d]+B[0],A[1]+[sign(C(c-a,b-c))]+B[1]]
return[[]]*2
try:
while 1:
i=[w%1*2or w==0for w in W[2:-2]].index(1);u,a,c,b,v=P[i:i+5];P[i+2:i+3],W[i+2:i+3]=t,_=T(a,c,b);t=[a]+t+[b]
for p,q,j,k in(u,a,1,i+1),(v,b,-2,i+len(t)):x=C(q-p,c-q);y=C(q-p,t[j]-q);z=C(c-q,t[j]-q);d=sign(j*z);W[k]+=(x*y<=0)*(x*z<0 or y*z>0)*(x!=0 or d*W[k]<=0)*(y!=0 or d*W[k]>=0)*d
except:plot(*zip(*P))
if M:scatter(*zip(*M))
show()
```
Reads two lists of points from STDIN.
**Example**
```
[(0, 0), (2, -1), (3.0/2, 4.0/3), (7.0/2, 1.0/3), (11.0/2, 16.0/3), (1, 16.0/3), (0, 1), (7, -2), (3, 4), (8, 1), (3, -1), (11, 0)]
[(1, 1), (3, 1), (4, 4), (1, 3), (2, 2), (5, -1), (5, 0), (6, 2), (7, 1), (6, 0)]
```

**How it works**
The key to the solution is to work in small, incremental steps.
Instead of trying to figure out what happens when we remove all the nails at once, we concentrate on the direct effects of removing just a single nail.
We can then remove the nails one by one in an arbitrary order.
Working incrementally means that we must keep track of the intermediate state of the rubber band.
Here's the tricky part: merely keeping track of which nails the band runs through is not enough.
During the process of removing nails the band can get wound and later unwound around a nail.
Therefore, when the band interacts with a nail we must keep track of how many times and in what direction it wraps around it.
We do it by assigning a value to each nail along the band like so:

Note that:
* We start counting as soon as the band is tangent to the nail, even though the nail doesn't strictly affect its shape.
Recall that, unlike the illustration, our nails are dimensionless.
Therefore, if the band becomes tangent to a nail we can't tell which side of the band the nail is on by its position alone---we must keep track of where it *used* to be relative to the band.
* We keep around nails with a value of zero, that is, nails that used to, but no longer hold the band, instead of removing them right away.
If we did, it could trigger an unwelcomed chain reaction, while we're trying to keep the effects of each step localized.
Instead, nails with a value of zero are considered eligible for removal as part of the bigger process.
Now we can describe what happens at each step:
* We select a nail to remove from the band's current path.
A nail is eligible for removal if it's part of the first set of nails (save for the endpoints) or if its value is zero.
* Pretending that the two neighboring nails are fixed, we figure out which nails from the second set or the pair of endpoints the band is going to run through once the selected nail is removed (we don't bother with the rest of the nails from the first set, since they'll eventually all be removed.)
We do it in a similar fashion to [the solution to Part I](https://codegolf.stackexchange.com/a/38339/31403).
All these nails are on the same side of the band, hence we assign to all of them a value of *1* or *-1*, depending on the side.
* We update the value of the two neighboring nails to reflect the changes to the band's path (easily the trickiest part!)
This process is repeated until there are no more nails to remove:

And here's a more complicated example illustrating the band wrapping around a nail several times:

[Answer]
## Java - 1262 bytes
I know this is probably not golfed as much as it could be.
However, no one else seems to be stepping up to the plate and answering this question, so I will.
First, class "T" - which is a point class - 57 bytes
```
class T{double x,y;public T(double a,double b){x=a;y=b;}}
```
And the main class - 1205 bytes
```
import java.awt.Color;import java.awt.Graphics;import java.util.*;import javax.swing.*;class Q extends JPanel{void d(List<T>a,T[]z){JFrame t=new JFrame();int m=0;int g=0;for(T v:a){if(v.x>m)m=(int)v.x;if(v.y>g)g=(int)v.y;}for(T v:z){if(v.x>m)m=(int)v.x;if(v.y>g)g=(int)v.y;}t.setSize(m+20,g+20);t.setVisible(true);t.getContentPane().add(this);double r=9;while(r>1){r=0;for(int i=0;i<a.size()-1;i+=2){T p1=a.get(i),p2=new T((p1.x+a.get(i+1).x)/2,(p1.y+a.get(i+1).y)/2);a.add(i+1,p2);if(y(p1,p2)>r){r=y(p1,p2);}}}double w=15;List<T>q=new ArrayList<T>();while(w>3.7){w=0;q.clear();for(int e=0;e<a.size()-2;e++){T p1=a.get(e),u=a.get(e+1),p3=a.get(e+2),p2=new T((p1.x+p3.x)/2,(p1.y+p3.y)/2);w+=y(u,p2);int k=0;if(y(p1,a.get(e+1))<.5){a.remove(e);}for(T n:z){if(y(n,p2)<1){k=1;q.add(n);}}if(k==0){a.set(e+1,p2);}}}q.add(a.get(a.size()-1));q.add(1,a.get(0));p=z;o=q.toArray(new T[q.size()]);repaint();}T[]p;T[]o;double y(T a,T b){return Math.sqrt(Math.pow(b.x-a.x,2)+Math.pow(b.y-a.y,2));}public void paintComponent(Graphics g){if(o!=null){for(int i=0;i<o.length-1;i++){g.drawLine((int)o[i].x,(int)o[i].y,(int)o[i+1].x,(int)o[i+1].y);}g.setColor(Color.blue);for(T i:p){g.fillOval((int)i.x-3,(int)i.y-3,6,6);}}}}
```
Example:

To run, call the "d" function with a List of points and an array of nails (yeah, I know, weird).
What it does:
* creates a list of points that represent the lines - that is, all the points in between the lines.
* repeats an algorithm repeatedly to these points so that the each point is the average of the two points around it.
* When the points don't seem to be moving much anymore, I draw between any nails that they are touching.
I am not sure if axes in pixels is ok. It will always take up more than 75% of the space, it might just be really, really small.
Here is a nice animation to demonstrate what I'm doing here:

Eventually, it becomes this, in which the points are barely moving. This is when I see what nails it is touching:

Here is the ungolfed, animation code:
```
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Q extends JPanel{
List<Point>points=new ArrayList<Point>();
List<Point>n=new ArrayList<Point>();
public Q() throws InterruptedException{
double[][]rawPoints={{0, 0}, {2, -1}, {3/2, 4/3}, {7/2, 1/3}, {11/2, 16/3}, {1, 16/3}, {0, 1}, {7, -2}, {3, 4}, {8, 1}, {3, -1}, {11, 0}};
double[][]rawNails={{1, 1}, {3, 1}, {4, 4}, {1, 3}, {2, 2}, {5, -1}, {5, 0}, {6, 2}, {7, 1}, {6, 0}};
List<Point>p=new ArrayList<Point>(),nails = new ArrayList<Point>();
double factor = 50;
for(double[]rawP:rawPoints){p.add(new Point(rawP[0]*factor+100,rawP[1]*factor+100));}
for(double[]rawN:rawNails){nails.add(new Point(rawN[0]*factor+100,rawN[1]*factor+100));}
n=nails;
JFrame frame=new JFrame();
frame.setSize(700,500);
frame.setVisible(true);
frame.getContentPane().add(this);
d(p,nails);
}
public static void main(String[]a) throws InterruptedException{
new Q();
}
void d(List<Point>a,List<Point>nails) throws InterruptedException{
//add midpoint every iteration until length of 1 is achieved
//begin algorithm
//stop points that are within a small amount of a nail
double distance=20;
while(distance>1){
distance=0;
for (int i=0;i<a.size()-1;i+=2){
double fir=a.get(i).x;
double sec=a.get(i).y;
double c=(fir+a.get(i+1).x)/2;
double d=(sec+a.get(i+1).y)/2;
a.add(i+1,new Point(c,d));
double dist=distBP(new Point(fir,sec),new Point(c,d));
if(dist>distance){distance=dist;}
}
}
for(Point p:a){a.set(a.indexOf(p), new Point(p.x,p.y));}
//algorithm starts here:
setEqual(a);
repaint();
invalidate();
System.out.println(a);
int count=0;
while(true){
count++;
for(int index=0;index<a.size()-2;index++){
double x2=(a.get(index).x+a.get(index+2).x)/2;
double y2=(a.get(index).y+a.get(index+2).y)/2;
int pointStable=0;
if(distBP(a.get(index),a.get(index+1))<.5){a.remove(index);}
for(Point n:nails){
if(distBP(n,new Point(x2,y2))<1){pointStable=1;}
}
if(pointStable==0){a.set(index+1, new Point(x2,y2));}
}
if(count%10==0){
setEqual(a);
invalidate();
repaint();
Thread.sleep(5);
}
}
//System.out.println(a);
}
void setEqual(List<Point>a){
points = new ArrayList<Point>();
for(Point p:a){points.add(p);}
}
double distBP(Point a,Point b){
return Math.sqrt(Math.pow(b.x-a.x, 2)+Math.pow(b.y-a.y, 2));
}
@Override
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(Color.black);
for(Point p:points){
g.drawRect((int)p.x, (int)p.y, 1, 1);
}
for(Point nail:n){
g.drawOval((int)nail.x-2, (int)nail.y-2, 4, 4);
}
}
}
```
] |
[Question]
[
## Background
Most people on here should be familiar with several base systems: decimal, binary, hexadecimal, octal. E.g. in the hexadecimal system, the number *1234516* would represent
```
1*16^4 + 2*16^3 + 3*16^2 + 4*16^1 + 5*16^0
```
Note that we're usually not expecting the base (here, `16`) to change from digit to digit.
A generalisation of these usual positional systems allows you to use a different numerical base for each digit. E.g. if we were alternating between decimal and binary system (starting with base 10 in the least significant digit), the number *190315[2,10]* would represent
```
1*10*2*10*2*10 + 9*2*10*2*10 + 0*10*2*10 + 3*2*10 + 1*10 + 5 = 7675
```
We denote this base as `[2,10]`. The right-most base corresponds to the *least* significant digit. Then you go through the bases (to the left) as you go through the digits (to the left), wrapping around if there are more digits than bases.
For further reading, [see Wikipedia](http://en.wikipedia.org/wiki/Mixed_radix).
## The Challenge
Write a program or function which, given a list of digits `D` an input base `I` and an output base `O`, converts the integer represented by `D` from base `I` to base `O`. You may take input via STDIN, ARGV or function argument and either return the result or print it to STDOUT.
You may assume:
* that the numbers in `I` and `O` are all greater than `1`.
* the `I` and `O` are non-empty.
* that the input number is valid in the given base (i.e., no digit larger than its base).
`D` could be empty (representing `0`) or could have leading zeroes. Your output should not contain leading zeroes. In particular, a result representing `0` should be returned as an empty list.
You must not use any built-in or 3rd-party base conversion functions.
This is code golf, the shortest answer (in bytes) wins.
## Examples
```
D I O Result
[1,0,0] [10] [2] [1,1,0,0,1,0,0]
[1,0,0] [2] [10] [4]
[1,9,0,3,1,5] [2,10] [10] [7,6,7,5]
[1,9,0,3,1,5] [2,10] [4,3,2] [2,0,1,1,0,1,3,0,1]
[52,0,0,0,0] [100,7,24,60,60] [10] [3,1,4,4,9,6,0,0]
[0,2,10] [2,4,8,16] [42] [1,0]
[] [123,456] [13] []
[0,0] [123,456] [13] []
```
[Answer]
# CJam, 45
```
q~_,@m>0@{@(:T+@T*@+}/\;La{\)_@+@@md@@j@+}jp;
```
Finally I found a good use of `j`.
### How it works
`Long ArrayList Block j` executes the block which takes an integer as the parameter, and `Long j` will call this block recursively in the block. It will also store the values returned by the block in an internal array, which is initialized by the array parameter. It will not execute the block if the input is already in the array, and the value in the array is returned instead.
So if I initialize it with an array of an empty array, the empty array will be returned for input 0, and the block will be executed for any other input.
```
q~_,@m>0@{@(:T+@T*@+}/\; " See below. Stack: O decoded-D ";
La " Initialized the value with input 0 as empty list. ";
{
\)_@+@@md@@ " See below. Stack: remainder O quotient ";
j " Call this block recursively except when the same quotient has
appeared before, which is impossible except the 0.
Stack: remainder O returned_list ";
@+ " Append the remainder to the list. ";
}j
p; " Format and output, and discard O. ";
```
# CJam, 49 48
```
q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`
```
Input should be `O I D`.
Examples:
```
$ while read; do <<<$REPLY ./cjam-0.6.2.jar <(echo 'q~_,@m>0@{@(:T+@T*@+}/\;{\)_@+@@md@@}h;;_{}?]W%`');echo; done
[2] [10] [1 0 0]
[10] [2] [1 0 0]
[10] [2 10] [1 9 0 3 1 5]
[4 3 2] [2 10] [1 9 0 3 1 5]
[10] [100 7 24 60 60] [52 0 0 0 0]
[42] [2 4 8 16] [0 2 10]
[13] [123 456] []
[13] [123 456] [0 0]
[1 1 0 0 1 0 0]
[4]
[7 6 7 5]
[2 0 1 1 0 1 3 0 1]
[3 1 4 4 9 6 0 0]
[1 0]
""
""
```
### How it works
```
q~ “ Read the input and evaluate. ";
_,@m> " Rotate I to the right by the length of D. ";
0@{ " For each item in D, with the result initialized to 0: ";
@(:T+ " Rotate I to the left, and set the original first item to T. ";
@T*@+ " Calculate result * T + current. ";
}/
\; " Discard I. ";
{ " Do: ";
\)_@+ " Rotate O to the right, and get a copy of the original last item. ";
@@md " Calculate divmod. ";
@@ " Move O and the quotient to the top of the stack. ";
}h " ...while the quotient is not 0. ";
;; " Discard O and the last 0. ";
_{}? " If the last item is still 0, discard it. ";
]W% " Collect into an array and reverse. ";
` " Turn the array into its string representation. ";
```
[Answer]
# CJam, ~~62~~ ~~61~~ ~~59~~ 57 bytes
```
q~Wf%~UX@{1$*@+\@(+_W=@*@\}/;\;{\(+_W=@\md@@}h;;]W%_0=!>p
```
Reads the input arrays as `[O I D]` from STDIN. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
```
q~ " Read from STDIN and evaluate the input. Result: [O I D] ";
Wf%~ " Reverse each of the three arrays and dump them on the stack. ";
UX@ " Push U (0) and X (1); rotate D on top of both. ";
{ " For each N in D: ";
1$* " N *= X ";
@+ " U += N ";
\@(+ " I := I[1:] + I[:1] ";
_W=@* " X *= I[-1] ";
@\ " ( U I X ) ↦ ( I U X ) ";
}/ " ";
;\; " Discard I and X. ";
{ " R := []; Do: ";
\(+ " O := O[1:] + O[:1] ";
_W=@\md " R += [U / O[-1]], U %= O[-1] ";
@@ " ( O U R[-1] ) ↦ ( R[-1] O U ) ";
}/ " While U ";
;;] " Discard U and O. ";
W% " Reverse R. ";
_0=!> " Execute R := R[!R[0]:] to remove a potential leading zero. ";
p " Print a string presentation of R. ";
```
### Test cases
```
$ cjam mixed-base.cjam <<< '[ [2] [10] [1 0 0] ]'
[1 1 0 0 1 0 0]
$ cjam mixed-base.cjam <<< '[ [10] [2] [1 0 0] ]'
[4]
$ cjam mixed-base.cjam <<< '[ [10] [2 10] [1 9 0 3 1 5] ]'
[7 6 7 5]
$ cjam mixed-base.cjam <<< '[ [4 3 2] [2 10] [1 9 0 3 1 5] ]'
[2 0 1 1 0 1 3 0 1]
$ cjam mixed-base.cjam <<< '[ [10] [100 7 24 60 60] [52 0 0 0 0] ]'
[3 1 4 4 9 6 0 0]
$ cjam mixed-base.cjam <<< '[ [42] [2 4 8 16] [0 2 10] ]'
[1 0]
$ cjam mixed-base.cjam <<< '[ [13] [123 456] [] ]'
""
$ cjam mixed-base.cjam <<< '[ [13] [123 456] [0 0] ]'
""
```
Note that empty strings and empty arrays are indistinguishable to CJam, so `[]p` prints `""`.
[Answer]
# Python 2 - 318
```
from operator import *
d,i,o=input()
c=len
def p(l):return reduce(mul,l,1)
n=sum(x[1]*p((i[-x[0]%c(i)-1:]+x[0]/c(i)*i)[1:]) for x in enumerate(d[::-1]))
r=[]
j=1
t=[]
k=c(o)
while p(t)*max(o)<=n:t=(o[-j%k-1:]+j/k*o)[1:];j+=1
while j:j-=1;t=(o[-j%k-1:]+j/k*o)[1:];r+=[n/p(t)];n%=p(t)
print (r if r[0] else [])
```
~~I messed up the order of the arguments by accident, so I had to reverse them. I will work on the slice-fu to get the lists to work in the other direction later, I already wasted my entire lunch break :p~~
Fixed
[Answer]
# APL, 78
```
{1↓(⊃1⌷⍺)({t←⍺[(⍴⍺)|⍴⍵]
(⌊0⌷⍵÷t)(t|0⌷⍵),1↓⍵}⍣{0=0⌷⍵}),+/(0,⍵)×⌽×\1,(⍴⍵)⍴⌽⊃0⌷⍺}
```
Examples:
```
f←{1↓(⊃1⌷⍺)({t←⍺[(⍴⍺)|⍴⍵]
(⌊0⌷⍵÷t)(t|0⌷⍵),1↓⍵}⍣{0=0⌷⍵}),+/(0,⍵)×⌽×\1,(⍴⍵)⍴⌽⊃0⌷⍺}
(,10)(,2) f 1 0 0
1 1 0 0 1 0 0
(,2)(,10) f 1 0 0
4
(2 10)(,10) f 1 9 0 3 1 5
7 6 7 5
(2 10)(4 3 2) f 1 9 0 3 1 5
2 0 1 1 0 1 3 0 1
(100 7 24 60 60)(,10) f 52 0 0 0 0
3 1 4 4 9 6 0 0
(2 4 8 16)(,42) f 0 2 10
1 0
(123 456)(,13) f ⍬
⍴(123 456)(,13) f ⍬
0
(123 456)(,13) f 0 0
⍴(123 456)(,13) f 0 0
0
```
[Answer]
# Python 2 - 122
Very straightforward, didn't manage to find any special golf tricks on this one.
```
def f(D,I,O):
n,i,l=0,-len(D),[]
for d in D:n=n*I[i%len(I)]+d;i+=1
while n:i-=1;b=O[i%len(O)];l=[n%b]+l;n/=b
return l
```
Ungolfed:
```
def f(D,I,O):
n = 0
for i in range(len(D)):
dn = len(D) - i
n = n * I[-dn % len(I)] + D[i]
l = []
i = 0
while n:
i -= 1
b = O[i%len(O)]
l = [n%b] + l
n /= b
return l
```
### Edit: 116-byte program version thanks to FryAmTheEggman
```
D,I,O=input()
n,i,l=0,-len(D),[]
for d in D:n=n*I[i%len(I)]+d;i+=1
while n:i-=1;b=O[i%len(O)];l=[n%b]+l;n/=b
print l
```
This version accepts comma-separated input e.g. `[1,9,0,3,1,5], [2,10], [10]`
[Answer]
# k2 - ~~83~~ 74 char
Function taking one argument. This was just a lot better suited for K than J, which is why I'm not using J. It would just be a load of boxing/unboxing garbage, and nobody wants that. This is in the k2 dialect (may require some adaptation to work in the open source implementation Kona), but I'll change this to k4 if I can golf it down shorter there.
```
{:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}
```
I will note that I take a stand for pickiness here and say that one item lists have to be input as such. `,2` is a list of one item, that item being the scalar `2`. Often scalars and 1-item lists are interchangable, but there is logic in this golf that relies on the assumption of list arguments.
To explain the golf, I'll break it into two parts. `F` is the golf, `L` is the main loop that calculates the output. The exact mechanism of the looping is that `L` is applied to its arguments repeatedly until the second argument is zero, then that result is returned. (This is the `.[L]/` part.)
```
L: {_(x,y!*z;y%*z;1!z)}
F: {:[#x@:|&~&\~x;|*{x 1}.[L]/(();+/x*1*\(1-#x)#y;|z);()]}
```
By explosion:
```
{_(x,y!*z;y%*z;1!z)} /function, args x y z
( ; ; ) / update each arg as follows:
1!z / new z: rotate z left
*z / head of z (current base digit)
y% / y divided by that
_ / new y: floor of that
y!*z / y modulo head of z
x, / new x: append that to old x
{:[#x@:|&~&\~x;|*{x 1}.[L]/(();+/x*1*\(1-#x)#y;|z);()]} /function, args x y z
~x /find the 0s in x
&\ /find leading zeros
&~ /indices of digits that aren't
x@ | /those items from x, reverse order
x : /assign to x
:[# ; ] /if length is 0:
() / return empty list
; /else:
.[L]/ / loop L repeatedly
{x 1} / until y = 0
( ; ; ) / starting with args:
() / Lx: empty list
1-#x / number of input digits, minus 1
( )#y / cyclically extend base leftward
1*\ / running product, start at 1
x* / multiply digits by these
+/ / Ly: sum of the above
|z / Lz: out base, reverse order
|* / first elem of result, reversed
```
In action:
```
{:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}[1 0 0; ,10; ,2]
1 1 0 0 1 0 0
f:{:[#x@:|&~&\~x;|*{x 1}.[{_(x,y!*z;y%*z;1!z)}]/(();+/x*1*\(1-#x)#y;|z);()]}
f[1 0 0; ,2; ,10]
,4
f .' ((1 9 0 3 1 5; 2 10; ,10) /f apply each
> (1 9 0 3 1 5; 2 10; 4 3 2)
> (52 0 0 0 0; 100 7 24 60 60; ,10)
> (0 2 10; 2 4 8 16; ,42)
> ((); 123 456; ,13)
> (0 0; 123 456; ,13))
(7 6 7 5
2 0 1 1 0 1 3 0 1
3 1 4 4 9 6 0 0
1 0
()
())
```
[Answer]
# [Perl 6](https://perl6.org), 67 bytes
```
{[R,] [+]([R,](@^a)Z*1,|[\*] |[R,](@^b)xx*).polymod: |[R,](@^c)xx*}
```
[Try it](https://tio.run/nexus/perl6#jZDbasJAEIbv8xSDFzXRcc1JrYpiwZtCQSi9arKFmGwhJZqQxKKoT9RH6J0vZmdjPBZKk7BkZv5v/pldZAI@28zvK7MV3PlxIGCwXzvPyMGpc1X@qKM3T3utGbhx3BqHTZmbastlTWNJHK1mcdA75X2Z3@6p3SgXWQ4DqO@@onAuMlXbfbMsicJcbbpZvSlDP55NKQoo6isLGuaFmL6SRN4c6kWDvvIep2WvxhBUd4zuI7oTdMUyEX4uAg3WCkCYNQIhkmgFcgt1jI840dhTmOUIR2UZHop44tnMS9Qae0hTb8USkUYsT715plahOhhWq5rGPuJw3oOKm1eU7d4xUEedw/FxjIugTJn8WMNCfTi58os1b9FzO8cu9F0iLOJbvNDjrdtZ38E2dkj3L8qmsjSnmpzOKE5LnsS3zGLo46hkoVNn08a2Th@/cpUuNr1dcj/sqOOVHznYeI9G@2Jtu9xb3gcR/PYKTAvt1gVAKaskCoOrbf6W/wA "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with placeholder parameters @a,@b,@c
[R,] # reduce the following using reverse meta op 「R」 combined with 「,」 op
# (shorter than 「reverse」)
[+]( # sum
[R,](@^a) # reverse of first argument
Z[*] # zipped using &infix:<*> with the following
1,
| # slip the following in (flattens)
[\*] # triangle reduce
|[R,](@^b) xx* # reverse of second argument repeated infinitely
)
.polymod: |[R,](@^c) xx* # moduli the reverse of third argument repeated
}
```
---
In case you aren't sure what triangle reduce does:
```
[\*] 1,2,3,4,5
# 1, 1*2, 1*2*3, 1*2*3*4, 1*2*3*4*5
# 1, 2, 6, 24, 120
```
---
If I could take the inputs reversed, and output the reverse, it would be 47 bytes.
```
{[+](@^a Z*1,|[\*] |@^b xx*).polymod: |@^c xx*}
```
[Try it](https://tio.run/nexus/perl6#jVDNboJAEL7zFJMeKsh0y59aa2xs4sWkiZeeCpggbBMaEMKikVSfqI/QW1/MzlJo1SZNWTLZmfl@ZnYtOGz6LBwpaQWXYRZxGB9eXd1XJ4sAnrom7lyv68NusljCdtvVWJ4lVZpFt7IUytL@QNRJyUUJY9A/3pJ4xYWqfbwzkSdxqV57Qr@WaZilS8oiykbKmowfiTNS8iRYgV4LjJTnrGi0ru5A9abozdCbo8e3OQ9LHmnwqgDE4iriPE8qkBOrU1bwDS8Ex9n3bd7etPbCHmJRIrRKTapOcYZz/NZnaZCrXXZfFEHFcl4krCyClVA70BnfdTqaxl6yeHULF155oewProkGGj60n2seJU3J8tse1uiv6Cu/uNY59UfOdWr8kBg28Xt@jcdztx/8APs4INy/WA61pTn15HRmHW0Zid@z6qHbUcnCIGXLwb5Bv3/iKl0cOkNy/9rRwBM/cnDwBs3@0dpOs7d8D2L4509g2ej0jghUshtGbXCyzd/wTw "Perl 6 – TIO Nexus")
] |
[Question]
[
## Kakuro Combinations
Because I can't do mental arithmetic, I often struggle with the [Kakuro](http://en.wikipedia.org/wiki/Kakuro) Puzzle, which requires the victim to repeatedly work out which distinct numbers in the range 1 to 9 (inclusive) sum to another number in range 1 to 45 when you know how many numbers there are. For example, if you may want to know how to get 23 from 3 numbers, the only answer is 6 + 8 + 9. (This is the same idea as Killer Sudoku if you are familiar with that).
Sometimes you will have other information, such as that the number 1 *cannot* be present, thus to achieve 8 in just 2 numbers, you can only use 2 + 6 and 3 + 5 (you can't use 4 + 4, because they are not distinct). Alternatively, it may be that you have already found a 3 in the solution, and so something like 19 in 3 numbers must be 3 + 7 + 9.
Your task is to write a program that lists all the possible solutions to a given problem, in a strict order, in a strict layout.
### Input
Your solution can receive the inputs as a *single ASCII string* either through stdin, a command line argument, an argument to a function, a value left on the stack, or whatever madness your favourite esoteric language employs. The string is in the form
```
number_to_achieve number_of_numbers_required list_of_rejected_numbers list_of_required_numbers
```
The first 2 arguments are typical base-10 non-negative non-zero integers in the ranges 1 to 45 and 1 to 9 respectively (using a decimal point would be invalid input), the two lists are just digits strung together with no delimitation in no particular order without repetition, or '0' if they are empty lists. There can be no shared digits between the lists (except for 0). The delimiters are single spaces.
### Output
Your output must start with a line that contains the number of possible solutions. Your program must print out line-break delimited solutions sorted by each increasingly significant digit, where each digit is placed at the position it would be if you listed the numbers from 1 to 9. The examples below will hopefully make this clearer.
If an invalid input is provided I do not care what your program does, though I'd rather it didn't zero my boot sector.
### Examples
For this example input
```
19 3 0 0
```
The expected output would be
```
5
2 89
3 7 9
4 6 9
4 78
56 8
```
Note the spaces in place of each "missing" number, these are required; I'm not bothered about spaces which don't have a number after them (such as the missing 9s above). You can assume that whatever you are printing to will use a mono-space font. Note also the ordering, whereby solutions with a smaller smallest digit are listed first, and then those with a smallest next smallest digit, etc.
Another example, based on that above
```
19 3 57 9
```
The expected output would be
```
2
2 89
4 6 9
```
Note that every result contains a 9, and no result contains a 5 or 7.
If there are no solutions, for example
```
20 2 0 0
```
Then you should just output a single line with a 0 on it.
```
0
```
I've intentionally made the parsing of the input part of the fun of this question. This is code-golf, may the shortest solution win.
[Answer]
# JavaScript (E6) 172 ~~180 275 296~~
As a (testable) function with 1 string argument and returning the requested output.
To have a real output change return with alert(), same byte count, but beware, the alert font is not monospace.
```
F=i=>{
[t,d,f,m]=i.split(' ');
for(l=0,r='',k=512;--k;!z&!h&!o&&(++l,r+=n))
for(z=n='\n',h=d,o=t,b=i=1;i<=9;b+=b)
z-=~(b&k?(--h,o-=i,n+=i,f):(n+=' ',m)).search(i++);
return l+r
}
```
**Test** In FireFox or FireBug console
```
console.log(['19 3 0 0','19 3 57 9','19 3 57 4','20 2 0 0'].map(x=>'\n'+x+'\n' +F(x)).join('\n'))
```
Test output:
```
19 3 0 0
5
2 89
3 7 9
4 6 9
4 78
56 8
19 3 57 9
2
2 89
4 6 9
19 3 57 4
1
4 6 9
20 2 0 0
0
```
**Ungolfed**
```
F=i=>{
[target, digits, forbidden, mandatory]=i.split(' ')
result = '', nsol=0
for (mask = 0b1000000000; --mask > 0;)
{
cdigits = digits
ctarget = target
bit = 1
numbers = ''
for (digit = 9; digit > 0; bit += bit, digit--)
{
if (bit & mask)
{
if (forbidden.search(digit)>=0) break;
cdigits--;
ctarget -= digit;
numbers = digit + numbers;
}
else
{
if (mandatory.search(digit)>=0) break;
numbers = ' '+numbers;
}
}
if (ctarget==0 && cdigits == 0)
{
result += '\n'+numbers
nsol++
}
}
return nsol + result
}
```
[Answer]
### GolfScript, 88 characters
```
~[[]]10,:T{{1$+}+%}/\{\0+`-!}+,\{0`+\`&!}+,\{\,=}+,\{\{+}*=}+,.,n@{1T>''*T@-{`/' '*}/n}/
```
A straight-forward implementation in GolfScript. Takes input from STDIN or stack.
The code can be tested [here](http://golfscript.apphb.com/?c=IjE5IDMgNTcgOSIKCn5bW11dMTAsOlR7ezEkK30rJX0vXHtcMCtgLSF9KyxcezBgK1xgJiF9Kyxce1wsPX0rLFx7XHsrfSo9fSssLixuQHsxVD4nJypUQC17YC8nICcqfS9ufS8%3D&run=true).
*Code with some comments:*
```
### evaluate the input string
~
### build all possible combinations of 0...9
[[]] # start with set of empty combination
10,:T #
{ # for 0..9
{1$+}+% # copy each item of set and append current digit to this copy
}/ # end for
### only keep combination which the digits given as last argument (minus 0)
\{ # start of filter block
\0+` # add zero to combination and make string out of it
-! # subtract from last argument -> check argument contains any
# excess characters
}+, # end of filter block
### remove any combination which contains either 0 or any digit from 2nd last argument
\{ # start of filter block
0`+ # take argument and append 0
\` # stringify combination
&! # check if no characters are common
}+, # end of filter block
### filter for correct length
\{ # start of filter block
\, # calc length of combination
= # check if equal to second argument
}+, # end of filter block
### filter for correct sum
\{ # start of filter block
\{+}* # sum all digits of combination
= # compare with first argument
}+, # end of filter block
### output
., # determine size of set
n # append newline
@{ # for each combination in set
1T>''* # generate "123456789"
T@- # generate anti-set of current combination
{`/' '*}/ # replace (in the string) each digit within the
# anti-combination with a space characters
n # append newline
}/ # end for
```
[Answer]
## Mathematica, 239 bytes
(I admit I started working on this while it was still in the sandbox.)
```
{t,n,a,b}=FromDigits/@StringSplit@i;Riffle[c=Cases[Union/@IntegerPartitions[t,n,Complement[r=Range@9,(d=IntegerDigits)@a]],k_/;(l=Length)@k==n&&(b==0||l[k⋂d@b]>0)];{(s=ToString)@l@c}~Join~((m=#;If[m~MemberQ~#,s@#," "]&/@r)&/@c),"\n"]<>""
```
Ungolfed
```
{t, n, a, b} = FromDigits /@ StringSplit@i;
Riffle[
c = Cases[
Union /@ IntegerPartitions[
t, n, Complement[r = Range@9, (d = IntegerDigits)@a
]
],
k_ /; (l = Length)@k ==
n && (b == 0 || l[k ⋂ d@b] > 0)
];
{(s = ToString)@l@c}~
Join~((m = #; If[m~MemberQ~#, s@#, " "] & /@ r) & /@ c),
"\n"] <> ""
```
It expects the input string to be stored in `i`.
It's fairly straightforward. First, input parsing. Then I use `IntegerPartitions` to figure out how I can split up the first number into the allowed numbers. Then I filter out all partitions that use duplicates or don't contain required numbers. And then for each solution I create a list from `1` to `9` and convert the present numbers into their string representation and the others into spaces. And then I concatenate everything.
[Answer]
## Groovy - 494 chars
Large, uninspired answer, but it uses Google Guava to generate the "power set".
Golfed:
```
@Grab(group='com.google.guava', module='guava', version='17.0')
m=(args.join(" ")=~/(\d+) (\d+) (\d+) (\d+)/)[0]
i={it as int}
n=i(m[1])
r=i(m[2])
j=[]
m[3].each{if(i(it))j<<i(it)}
q=[]
m[4].each{if(i(it))q<<i(it)}
d=1..9 as Set<Integer>
t=[]
com.google.common.collect.Sets.powerSet(d).each{x->
if(x.sum()==n&&x.size()==r&&x.disjoint(j)&&x.containsAll(q)) {
s="";for(i in 0..8){if(x.contains(i+1)){s+=(i+1) as String}else{s+=" "}};t<<s}
}
p={println it}
p t.size()
t.sort().reverse().each{p it}
```
Sample runs:
```
$ groovy K.groovy 19 3 0 0
5
2 89
3 7 9
4 6 9
4 78
56 8
$ groovy K.groovy 19 3 5 0
4
2 89
3 7 9
4 6 9
4 78
$ groovy K.groovy 19 3 5 9
3
2 89
3 7 9
4 6 9
$ groovy K.groovy 20 2 0 0
0
```
Ungolfed:
```
@Grab(group='com.google.guava', module='guava', version='17.0')
m=(args.join(" ")=~/(\d+) (\d+) (\d+) (\d+)/)[0]
i={it as int}
n=i(m[1])
r=i(m[2])
j=[]
m[3].each{if(i(it))j<<i(it)}
q=[]
m[4].each{if(i(it))q<<i(it)}
d=1..9 as Set<Integer>
t=[]
com.google.common.collect.Sets.powerSet(d).each{ x ->
if(x.sum()==n && x.size()==r && x.disjoint(j) && x.containsAll(q)) {
s=""
for(i in 0..8) {
if(x.contains(i+1)){s+=(i+1) as String}else{s+=" "}
}
t<<s
}
}
p={println it}
p t.size()
t.sort().reverse().each{p it}
```
] |
[Question]
[
Write a program that encodes given text into its own text, provided as input, without disrupting its logic. The program must also work as a decoder, restoring the original message from its text. It must retain its encoding/decoding functions after transformation.
More formally speaking, the required program P must perform the following transformations with the given message text M:
**P(M,P)->P\*
P\*(P\*)->M**
Here **P\*** is the transformed program, which also must satisfy the above rules, that is:
**P\*(M2,P\*)->P\*\***
**P\*\*(P\*\*)->M2**
and so on... Each subsequent encoding doesn't erase previously encoded text, so P\*\* carries two messages - M and M2.
The easiest way for the program to distinguish between encoding/decoding modes is by the presence of the extra argument M, but the final decision is up to you, provided it is clearly stated. The program **may** read it's own text from the file. If the chosen language doesn't have means for this, the source text can be passed to the program in any other way.
There are trivial solutions, of course, so this is rather a popularity contest. Nevertheless, I impose restriction forbidding comments in the program text.
[Answer]
# Perl
This is a one-liner in Perl just because it's possible.
```
if($ARGV[0]){open(F,__FILE__);while(<F>){print;print"$ARGV[0]\n"if/^_/;}}else{print<DATA>;}
__DATA__
```
The messages are written after `__DATA__`, most recent first.
[Answer]
# Python
You know what? Why not make it a single expression?
```
P = (lambda M,P=None:(lambda t:P[:74]+repr(M)[1:-1]+"'))"if P else M[74:-3])(''))
Pc = "(lambda M,P=None:(lambda t:P[:74]+repr(M)[1:-1]+\"'))\"if P else M[74:-3])(''))"
P2c = P('Hi there, mate!', Pc)
print "Encode tests:"
print " P2 = P('Hi there, mate!', Pc) =", P2c
exec 'P2 = ' + P2c
print " P2(\"Test 2's the best.\", P2c) =", P2("Test 2's the best.", P2c)
print "Decode tests:"
print "P2(P2) =", P2(P2c)
print "P(P2) =", P(P2c)
print "P2(P) =", P2(Pc)
print "P(P) =", P(Pc)
```
---
Old message; The function P takes the arguments as specified and outputs the resulting code / decoded text.
```
def P(data,func=None):
text = ""
if func:
return func[:35]+data+'"\n'+'\n'.join(func.split('\n')[2:])
return data[35:].split('\n')[0][:-1]
# The source code.
Pc = """def P(data,func=None):
text = ""
if func:
return func[:35]+data+'"\\n'+'\\n'.join(func.split('\\n')[2:])
return data[35:].split('\\n')[0][:-1]"""
P2c = P('Hi there, mate!', Pc)
print "Encode test:"
print "P('Hi there, mate!', P) ->"
print P2c
# This is outputted by P('Hi there, mate!', code-of-P)
def P2(data,func=None):
text = "Hi there, mate!"
if func:
return func[:35]+data+'"\n'+'\n'.join(func.split('\n')[2:])
return data[35:].split('\n')[0][:-1]
print "P2('Text 2', P2) -<"
print P2('Text 2', P2c)
print "Decode test:"
print "P2(P2) =", P2(P2c)
print "P(P2) =", P(P2c)
print "P2(P) =", P2(Pc)
print "P(P) =", P(Pc)
```
[Answer]
## JavaScript
```
var transform = function (p, m) {
var _M_ = '';
var source = arguments.callee.toString();
var msgre = /(_M_ = ').*(';)/;
var regex = new RegExp(source.replace(/[.*+?^$\[\]{}()\\|]/g, "\\$&").replace(msgre, "$1(.*)$2"));
var a = p.toString().match(regex);
if (!a) {
throw "first argument must be a transform function"
} else {
a = a[1];
}
if (typeof m == "undefined") {
return eval("[" + a.split("|")[0] + "]").map(x=>String.fromCharCode(x)).join("");
} else {
a = m.toString().split("").map(x => x.charCodeAt(0)) + (a.length ? "|" + a: a);
return eval("(" + source.replace(msgre, "$1" + a + "$2") + ")");
}
}
```
Not sure if I understand the problem statement correctly: my decoder will decode **any** program and return the latest message that is encoded in the given program.
Test code:
```
P1 = transform(transform, "first message");
P2 = P1(P1, "second message");
console.log(P1(P1));
console.log(P2(P2));
console.log(P2(P1));
console.log(P1(P2));
// Unspecified behavior
console.log(transform(transform))
```
[Answer]
## Batch
```
@echo off
setLocal enableDelayedExpansion
for /f %%a in (%0) do set a=%%a
if "%~1"=="e" (
set /a a+=1
echo !a! %~2 >> %0
echo message encoded as !a!
) else if "%~1"=="d" for /f "skip=12 tokens=1*" %%a in (%0) do if "%%a"=="%~2" echo %%b
goto :EOF
```
Note there needs to be a carriage return after 'the last line' of `goto :EOF`.
This takes two inputs from stdin. The first of which is what you want to do; `e`, or `d` (encode and decode). The second input depends on the first - if the first input is `e`, then the second input will be the message that you want to encode - if it is `d`, then the second input will be the number of the message you wish to decode (that will be provided after encoding a message).
```
H:\uprof>ed.bat e "Just a message"
message encoded as 1
H:\uprof>ed.bat d 1
Just a message
```
[Answer]
# Cobra
```
use System.Diagnostics
class Program
var message as int[]? = nil
def decode(program as String)
temp = List<of String>(program.split('\n'))
temp.insert(4, '\t\tEnvironment.exit(0)')
temp.add('\t\tmessage = \'\'')
temp.add('\t\tfor i in .message, message += Convert.toString(i to char)')
temp.add('\t\tFile.writeAllText(\'message.txt\', message)')
program = temp.join('\n')
File.writeAllText('decode.cobra', program)
process = Process()
process.startInfo.fileName = 'cmd.exe'
process.startInfo.arguments = '/C cobra decode.cobra'
process.start
def encode(message as String, program as String)
temp = List<of String>()
for i in message.toCharArray, temp.add(Convert.toString(i to int))
message = '@' + Convert.toString(c'[')
for n in temp.count-1, message += temp[n] + ','
message += temp.pop + ']'
temp = List<of String>(program.split('\n'))
temp.insert(26,'\t\t.message = .message ? [message]')
program = temp.join('\n')
File.writeAllText('encode.cobra', program)
def main
#call methods here
#.encode(message, program)
#.decode(program)
```
While the *idea* is trivial, the *execution* of said idea is less-so.
## Encoding
Encoding a message in the program will add the line `.message = .message ? x` immediately after `def main`. This line checks if `.message` is nil, and if so, then it sets `.message` to an integer array containing the character code values of each character in the message; the nil-check and positioning avoid overwriting the new message with an older one. The new program is saved to `encode.cobra`
## Decoding
Decoding the program will add three lines at the end of the main method which cause the program to convert the char codes in `.message` to a string, which is then saved to `message.txt` when the new program is run. The new program is then saved to `decode.cobra` and the compiler is invoked on it.
`decode.cobra` is used like a temporary file and cannot be used to encode or decode another message, use the original or `encode.cobra`
] |
[Question]
[
## My Problem
At my current place of employment, I single-handedly (ok dual-handedly because I'm missing no limbs) maintain approximately 700 laptops. Due to the nature and frequency of their use, I often find they are returned with a bit of damage. For this problem, my primary concern is when a laptop is returned with a broken or defunct keyboard. When the hardware repairman fixes these broken keyboards, it becomes necessary to test them. The test involves using each...and...every...single...key. What a drag right? The problem is, sometimes I lose track of if I typed a key or not.
## A solution?
Write a program/script that:
1. Takes user input
2. Upon submission (in whatever way you deem fit), determines whether each key was pressed.
3. Outputs yes or no or any way to indicate that either I was successful in pressing all the keys or not. (Indicate in your answer the two possible outputs if it's not something obvious).
Assumptions:
1. Uppercase, lowercase, both? Whichever way you deem fit. As long as it's [A-Z], [a-z] or [A-Za-z]. Same goes with numbers and other symbols. (So if `=` was typed in, `+` doesn't matter). Your choice if you want to include shifted characters or not.
2. You needn't worry about tabs or spaces
3. No needs for function keys, CTRL, ALT, Esc or any other keys that don't output something on the screen
4. This assumes an EN-US keyboard and the laptops **do not** include a numpad.
5. OS agnostic, whatever language you prefer
6. It doesn't matter if the key has been pressed multiple times (for when the tester just gets lazy and starts button smashing like it's Mortal Kombat)
Here's a potential input set that would return true (or yes, or "You did it!")
```
`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
```
Winner is determined by the least number of characters.
[Answer]
## GolfScript, 11
Printable ASCII isn’t that interesting…
```
127,32,-^,!
```
## Ruby, 68
With flag `-rset` for 4 characters.
```
p Set.new(?`..?z)+(?,..?9)+%w{[ ] \\ ; '}==Set.new(gets.split'')
```
and
## Python 3, 76
```
print(set("`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./")==set(input()))
```
[Answer]
## JavaScript - 62 70
```
alert(!(47-prompt().match(/([',-\/\d;=a-z\[-\]`]?)(?!.*\1)/g).length))
```
And a bit shorter:
```
alert(!!prompt().match(/([',-\/\d;=a-z\[-\]`])(?!.*\1)/g)[46])
```
[Answer]
# CJam - 9
```
',33>q-!
```
It checks for the "shifted" characters too (including uppercase letters).
Try it at <http://cjam.aditsu.net/>
Note: there is an invisible character (with code 127) after the apostrophe.
[Answer]
# PHP
```
foreach (str_split("`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./") as $v) {
if (strpos($_GET['i'],$v)!==false)die(NO);
}
```
`$_GET['i']` is the input
[Answer]
# GolfScript, 6 bytes
```
.&,94=
```
If all ASCII characters with codes between 33 and 127 are present, it prints 1. Otherwise, it prints 0.
This approach will fail if the input contains other characters (including a final newline), which [has been allowed by the OP](https://codegolf.stackexchange.com/questions/30344/testing-keyboards#comment65468_30344) and is also true for the existing GolfScript solution.
### Usage
```
$ echo -n '!"#$%&'"'"'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~' |
> golfscript <(echo '.&,94=')
1
```
### How it works
```
.& # Compute the intersection of the input string with itself. This removes duplicates.
, # Compute the length of the resulting string.
94= # Push 1 if the length is 94, otherwise push 0.
```
[Answer]
# Python 72:
```
f=lambda x:set(x)==set("`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./")
```
[Answer]
# Haskell, 41 (two solutions)
```
interact(\y->show$all(`elem`y)[' '..'`'])
```
or (point-free style)
```
interact$show.(`all`[' '..'`']).flip elem
```
Need to input at least these characters:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`
```
in any order, any number of times. Extra characters are allowed. Run in an interpreter. Must hit Enter when you are done, but if you hit Enter before you are done, you can keep entering characters, and press Enter again. Will print `True` if you have hit every character, otherwise it won't print anything.
[Answer]
# Perl, 70 characters
```
say[sort grep!$s{$_}++,<>=~/\S/g]~~[sort"',-./;=[\]`"=~/./g,0..9,a..z]
```
Usage:
```
echo `134223423567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./ | perl -E 'say[sort grep!$s{$_}++,pop=~/\S/g]~~[sort"',-./;=[\]`"=~/./g,0..9,a..z]'
```
Prints 1 if all keystrokes present, else prints nothing.
[Answer]
# C, 97 characters
```
main(long a,char**u){a=0xfb0000000750003d;for(u++;**u;a|=2L<<*(*u)++-39);a=48+!~a;write(1,&a,1);}
```
Need to call the program with argument containing at least the letters:
```
`1234567890-=AZERTYUIOPQSDFGHJKLMWXCVBN[]\;',./
```
and get answer 1 (true). The charset can be changed by changing the initialization value of a.
] |
[Question]
[
There have been many questions involving calculators; however, it does not appear that any involve implementing a graphing calculator.
**The Challenge**
You are to write a complete program that takes multiple formulas as input from STDIN and graphs them to STDOUT. Input will take the form `f1(x)=x^2-x-1`. There will be an `f` followed by a number 0-9 (inclusive), followed by `(x)=`, followed by the formula to graph. Your program should be able to take input, graph, take more input, graph, etc.
This is code golf.
Your graph should have the X-axis range from -5 to 5, with a resolution of at least one point every 1/2 unit. Y-axis requirements are the same. This may seem like a small range compared to modern calculators, but it will most likely be trivial in increase this. The graph should have the axis drawn on them, with tick marks in the form of `+` on the integers.
The formula should be evaluated with the normal order of operation. There will not be any vertical asymptotes/undefined regions in these formulas. The variable will always be x. If two formulas are entered with the same equation number, the oldest one should be erased and replaced with the new formula. Blank formulas should evaluate to zero. Since it is likely that the formula will not always give a nice multiple of 1/2, you are to round to the nearest 1/2.
When a formula is graphed, its line should be formed out of the number of the formula. When a line crosses an axis, the axis should be drawn on top. When two lines cross each other, it does not matter which is shown.
**Example Input**
```
f1(x)=x+1
```
**Output**
```
+ 1
| 1
+ 1
| 1
+ 1
| 1
+ 1
|1
+
1|
+-+-+-+-+-+-+-+-+-+-+
1 |
1 +
1 |
1 +
1 |
1 +
1 |
1 +
|
+
```
**Input**
```
f2(x)=(x^2)^0.25
```
**Output**
```
+ 1
| 1
+ 1
| 1
+ 1
| 1
2222 + 1 2222
222 |1 222
22 + 22
2|2
+-+-+-+-+-+-+-+-+-+-+
1 |
1 +
1 |
1 +
1 |
1 +
1 |
1 +
|
+
```
**Input**
```
f1(x)=-x
```
(note, it is acceptable for your program to reject this input and only except 0-x or x\*-1, but this should be documented)
**Output**
```
1 +
1 |
1 +
1 |
1 +
1 |
2222 1 + 2222
2221 | 222
22 + 22
2|2
+-+-+-+-+-+-+-+-+-+-+
|1
+ 1
| 1
+ 1
| 1
+ 1
| 1
+ 1
| 1
+ 1
```
[Answer]
### Ruby, 200 characters
```
f={}
r=0..20
(f[gets[1]]=$_[6..-1].gsub /\^/,'**'
s=r.map{' '*21}
f.map{|n,k|r.map{|y|x=y*0.5-5
v=(2*eval(k)).round
v.abs<11&&y!=10&&s[10-v][y]=n
s[y][10]='+|'[y%2]
s[10][y]='+-'[y%2]}}
puts s)while 1
```
A plain ruby implementation using the standard evaluator for expressions (`^` will be replaced so that the examples given above work fine). It is not very robust and assumes the input exactly as specified in the question.
[Answer]
### Perl, 177 characters (+1 command line switch)
```
perl -nE 's!\^!**!g;s!x!(\$k/2-6)!g;s/\d.*=/;/;$f[$&]=$_;my%a;for$k(@x=2..22){$i=0;$a{int 12.5-2*eval}[$k-2]=$i++for@f}$p="|";$$_[10]=$p^=W,$a{12}=[$p."-+"x10],say map$_//$",@$_ for@a{@x}'
```
Per [this meta thread](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), I believe this should count as 178 characters in total.
Like the Ruby solution, I'm also using `eval` and replacing `^` with `**`.
The input parsing is both incredibly fragile and incredibly robust at the same time: `f1(x)=` can be written as `f 1 ( x ) =` or `foo 1 bar =` or even just `1=`, but very strange things could happen if you replaced the `f` with something that isn't a valid, side-effectless Perl statement. You have been warned.
Other details of interest include the way the vertical axis is drawn, which exploits the fact that the bitwise XOR of the characters `+` and `|` is `W`. Obviously, this won't work on EBCDIC systems.
The output is rendered into a hash of arrays, not an array of arrays — it turns out that it takes fewer chars to explicitly truncate the hash keys to integers and then loop over a hash slice than it takes to ensure that an array isn't indexed with negative values. I could shave off two more characters if it weren't for the annoying way Perl's `int` truncates negative values towards zero, which forced me to number the output rows from 2 to 22 instead of 0 to 20 in order to avoid rounding artifacts at the top edge of the output area.
I do make use of Perl's liberal string-to-number conversion in the input parsing, where I use the entire string `1(x)=` as an array index (it gets converted to just 1).
I could also save three more characters (and make the parsing slightly more robust) by replacing `s/\d.*=/;/;$f[$&]=$_` with `/\d.*=/;$f[$&]=$'`, but then I'd have to spend the same number of extra characters to write `$'` as `$'\''` in a single-quoted shell string. I suppose technically I wouldn't have to count those, but it feels sort of like cheating.
[Answer]
### Python 2: 320 characters
```
N=20
r=range(N+1)
d={}
while(1):
l=raw_input()
d[l[1]]=l[6:].replace('^','**')
g=[[' ']*(N+1) for i in r]
for n,f in d.items():
for x in r:
v=N/2+int(round(2*eval(f.replace('x','(%f)'%(x/2.0-N/4)))))
if 0<=v<=N:g[N-v][x]=n
for i in r:
g[i][N/2]='+|'[i%2]
g[N/2][i]='+-'[i%2]
for l in g:print''.join(l)
```
Could probably be made shorter, but I'm a bit of a newbie at this :)
Making `N` a variable wastes 9 chars but I like it better that way.
] |
[Question]
[
Write the shortest function to generate the [American Soundex code](http://www.archives.gov/research/census/soundex.html) for a surname only containing the uppercase letters A-Z. Your function must produce output consistent with all the linked page's examples (given below), although it need not and should not remove prefixes. Hyphens in the output are optional. Have fun!
**Note:** You may *not* use the `soundex()` function included in PHP or equivalents in other programming languages.
The examples:
```
WASHINGTON W-252
LEE L-000
GUTIERREZ G-362
PFISTER P-236
JACKSON J-250
TYMCZAK T-522
VANDEUSEN V-532
ASHCRAFT A-261
```
[Answer]
### Perl, 143 150 characters
```
sub f{$_="$_[0]000";/./;$t=$&;s/(?<=.)[HW]//g;s/[BFPV]+/1/g;s/[CGJKQSXZ]+/2/g;s/[DT]+/3/g;s/L+/4/g;s/[MN]+/5/g;s/R+/6/g;s/(?<=.)\D//g;/.(...)/;"$t$1"}
```
This solution contains only regular expressions which are applied one after another. Unfortunately I didn't find a shorter representation with a loop so I hard-coded all the calls into the script.
The same version but a little bit more readable:
```
sub f{
$_="$_[0]000"; # take first argument and append "000"
/./;$t=$&; # save first char to variable $t
s/(?<=.)[HW]//g; # remove and H or W but not the first one
s/[BFPV]+/1/g; # replace one or more BFPV by 1
s/[CGJKQSXZ]+/2/g; # replace one or more CGJKQSXZ by 2
s/[DT]+/3/g; # replace one or more DT by 3
s/L+/4/g; # replace one or more L by 4
s/[MN]+/5/g; # replace one or more MN by 5
s/R+/6/g; # replace one or more R by 6
s/(?<=.)\D//g; # remove and non-digit from the result but not the first char
/.(...)/;"$t$1" # take $t plus the characters 2 to 4 from result
}
```
*Edit 1:* Now the solution is written in form of a function. The previous one was reading/writing from/to STDIN/STDOUT. It cost me seven characters to work around that.
[Answer]
## J - 99
```
{.,([:-.&' '@":3{.!.0[:(#~1,}.~:}:)^:#,@(;:@]>:@I.@:(e.&>"0 _~)[#~e.))&'BFPV CGJKQSXZ DT L MN R'@}.
```
Testing:
```
sndx=: {.,([:-.&' '@":3{.!.0[:(#~1,}.~:}:)^:#,@(;:@]>:@I.@:(e.&>"0 _~)[#~e.))&'BFPV CGJKQSXZ DT L MN R'@}.
test=: ;: 'JACKSON PFISTER TYMCZAK GUTIERREZ ASHCRAFT ASHCROFT VANDEUSEN ROBERT RUPERT RUBIN WASHINGTON LEE'
(,. sndx&.>) test
+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+
|JACKSON|PFISTER|TYMCZAK|GUTIERREZ|ASHCRAFT|ASHCROFT|VANDEUSEN|ROBERT|RUPERT|RUBIN|WASHINGTON|LEE |
+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+
|J250 |P123 |T520 |G362 |A261 |A261 |V532 |R163 |R163 |R150 |W252 |L000|
+-------+-------+-------+---------+--------+--------+---------+------+------+-----+----------+----+
```
[Answer]
eTeX, 377.
```
\let\E\expandafter
\def\x#1;#2#3{\def\s##1#2{##1\s#3}\edef\t{\s#1\iffalse#2\fi}\E\x\t;}
\def\a[#1#2]{\if{{\fi\uppercase{\x#1,#2};B1F1P1V1C2G2J2K2Q2S2X2Z2D3T3L4M5N5R6A7E7I7O7U7
H{}W{}Y{}{11}1{22}2{33}3{44}4{55}5{66}6{{}\toks0\bgroup}!}\E\$\t0000!#1}}
\def\$#1,#2{\if#1#2\relax\E\%\else\E\%\E#2\fi}
\def\%{\catcode`79 \scantokens\bgroup\^}
\def\^#1#2#3#4!#5{\message{#5#1#2#3}\end}
\E\a
```
Run as `etex filename.tex [Ashcraft]`.
[Answer]
**Python, ~~274~~ ~~285~~ ~~241~~ ~~235~~ ~~225~~ ~~200~~ ~~190~~ ~~183~~ ~~179~~ ~~174~~ ~~166~~ 161**
~~- Fixed last clause (H or W as consonant separators). Ashcraft now has the right result.
- Made the dict smaller
- Formating is smaller (doesn't require python 2.6)
- Simpler dict search for `k`
- Changed vowel value from `'*'` to `''` and `.append` to `+=[i]`
- List comprehension FTW
- Removed call to `upper` :D~~
~~I Can't golf any further. Actually I did. Now I think I can't golf any further!~~ Did it again...
Using translate table:
```
def f(n):z=n.translate(65*'_'+'#123#12_#22455#12623#1_2#2'+165*'_').replace('_','');return n[0]+(''.join(('',j)[j>'#']for i,j in zip(z[0]+z,z)if i!=j)+'000')[:3]
```
Old list comprehension code:
```
x=dict(zip('CGJKQSXZDTLMNRBFPV','2'*8+'3345561111'))
def f(n):z=[x.get(i,'')for i in n if i not in'HW'];return n[0]+(''.join(j for i,j in zip([x.get(n[0])]+z,z)if i!=j)+'000')[:3]
```
Old code:
```
x=dict(zip('CGJKQSXZDTLMNRBFPV','2'*8+'3345561111'))
def f(n):
e=a=[];k=n[0]in x
for i in[x.get(i,'')for i in n.upper()if i not in'HW']:
if i!=a:e+=[i]
a=i
return n[0]+(''.join(e)+'000')[k:3+k]
```
Test:
```
[f(i) for i in ['WASHINGTON', 'LEE', 'GUTIERREZ', 'PFSTER', 'JACKSON',
'TYMCZAK', 'VANDEUSEN', 'ASHCRAFT']]
```
Gives:
```
['W252', 'L000', 'G362', 'P236', 'J250', 'T522', 'V532', 'A261']
```
As expected.
[Answer]
## Perl, 110
```
sub f{$_="$_[0]000";/./;$t=$&;s/(?<=.)[HW]//g;y/A-Z/:123:12_:22455:12623:1_2:2/s;s/(?<=.)\D//g;/.(...)/;$t.$1}
```
I'm using Howard's solution with my translate table (`y/A-Z/table/s` instead of every `s/[ABC]+/N/g`)
[Answer]
## GolfScript (74 chars)
This implementation uses a magic string which has non-printable characters. In `xxd` output form it's
```
0000000: 7b2e 313c 5c5b 7b36 3326 2741 4c15 c252 {.1<\[{63&'AL..R
0000010: d056 4c1e 8227 3235 3662 6173 6520 3862 .VL..'256base 8b
0000020: 6173 653d 7d25 7b2e 373d 2432 243d 7b3b ase=}%{.7=$2$={;
0000030: 7d2a 7d2a 5d31 3e31 2c2d 5b30 2e2e 5d2b }*}*]1>1,-[0..]+
0000040: 333c 7b2b 7d2f 7d3a 533b 3<{+}/}:S;
```
Without using the base changes to compress a list of 3-bit numbers, it would be
```
{.1<\[{63&[1 0 1 2 3 0 1 2 7 0 2 2 4 5 5 0 1 2 6 2 3 0 1 7 2 0 2]=}%{.7=$2$={;}*}*]1>1,-[0..]+3<{+}/}:S;
```
[Online test](http://golfscript.apphb.com/?c=ey4xPFxbezYzJjMwODM1NzM0MTg0MjgwMzg5NzY3MTI5OCA4YmFzZT19JXsuNz0kMiQ9ezt9Kn0qXTE%2BMSwtWzAuLl0rMzx7K30vfTpTOwoKJ1dBU0hJTkdUT04KTEVFCkdVVElFUlJFWgpQRklTVEVSCkpBQ0tTT04KVFlNQ1pBSwpWQU5ERVVTRU4KQVNIQ1JBRlQKV00nbi8Ke1N9JWAKbgonVzI1MgpMMDAwCkczNjIKUDIzNgpKMjUwClQ1MjIKVjUzMgpBMjYxClc1MDAnbi9g)
It's basically a bunch of boring loops, but there's one interesting trick:
```
.7=$2$=
```
This is inside a fold whose purpose is to handle double-letters. Adjacent letters with the same code are merged into one unit, even if separated by an `H` or a `W`. But this can't be implemented trivially by removing all `H`s and `W`s from the string, because in the (admittedly unlikely in real life, but not ruled out by the spec) case that the first letter is `H` or `W` and the second letter is a consonant, we need to not elide that consonant when we remove the first letter. (I added a test case `WM` which should give `W500` to check this).
So the way I handle that is to do a fold and to delete each letter *other than the first* (a convenient side-effect of using fold) which is either equal to the previous one or equal to `7`, the internal code for `H` and `W`.
Given `a` and `b` on the stack, the naïve way to check whether `a == b || b == 7` would be
```
.2$=1$7=+
```
But there's a 2-character saving by using a computed copy-from-stack:
```
.7=$
```
If `b` is equal to `7` then it copies `a`; otherwise it copies `b`. So by then comparing with `a` we get a guaranteed truthy value if `b` was `7` regardless of the value of `a`. (Before any pedants weigh in, GolfScript doesn't have NaNs).
[Answer]
## APL (83)
```
{(⊃⍵),,/⍕¨3↑0~⍨1↓K/⍨~K=1⌽K←0,⍨{7|+/' '=S↑⍨⍵⍳⍨S←' BFPV CGJKQSXZ DT L MN R'}¨⍵~'HW'}⍞
```
[Answer]
## PowerShell, 150 ~~161~~
First try and I'm sure there can be golfed quite a bit more.
```
filter s{$s=-join$_[1..9]
1..6+'$1','',$_[0]|%{$s=$s-replace('2[bfpv]2[cgjkqsxz]2[dt]2l2[mn]2r2(.)\1+2\D|^.2^'-split2)[++$a],$_}
-join"${s}000"[0..3]}
```
Works correctly with the test cases from both the linked page and the Wikipedia article:
>
> Jackson, Pfister, Tymczak, Gutierrez, Ashcraft, Ashcroft, VanDeusen, Robert, Rupert, Rubin, Washington, Lee
>
>
>
[Answer]
# Ruby 140
I'm using Ruby 2.0, but I think it should work with earlier versions too.
```
def f s
a=s[i=0]
%w(HW BFPV CGJKQSXZ DT L MN R).each{|x|s.gsub!(/[#{x}]+/){i>0&&$`[0]?i: ''};i+=1}
a+(s[1..-1].gsub(/\D/,'')+'000')[0,3]
end
```
Example:
`puts f "PFISTER"` => `P236`
] |
[Question]
[
Input a list of strings `a` and a string `s` for search keyword. Find out all strings in `a` which contains `s` as subsequence. And sort them in the following order:
1. Exactly equals to `s`
2. Starts with `s`
3. Contains `s` as substring (continuous subsequence)
4. Contains `s` as subsequence
## Detail
* When two strings belongs to the same sorting group, you may sort them in any order you prefer.
* String matching is case sensitive. "A" and "a" are different characters.
* All strings will only contain printable ASCII (#32~#126).
* All strings will not have leading or trailing whitespaces.
* All strings will be non-empty.
* List `a` does not contain duplicate strings.
## Example
When the list is `["center","encounter","enter","enterprise","event"]`, and the search target is `"enter"`, output should be `["**enter**","**enter**prise","c**enter**","**en**coun**ter**"]`. `"event"` is not included in the output as it doesn't contain `"enter"` as subsequence.
## Test cases
```
["center","encounter","enter","enterprise","event"]
"enter"
-> ["enter","enterprise","center","encounter"]
["celebration","cooperation","generation","operation","ratio"]
"ratio"
-> ["ratio","celebration","cooperation","generation","operation"]
["combination","explanation","international","nation","national","nomination","notation"]
"nation"
-> ["nation","national","combination","explanation","international","nomination","notation"]
["ever","every","here","very","where"]
"everywhere"
-> []
["interaction","traditional","train","training","transformation"]
"train"
-> ["train","training","interaction","traditional","transformation"]
["condition","confusion","construction","contribution","information","organization","recommendation","transportation"]
"onion"
-> ["condition","confusion","construction","contribution","organization","recommendation"]
["...","---",".-.-.-","..--","-..-"]
"--"
-> ["---","..--",".-.-.-","-..-"]
["#","##","###","####","#####"]
"####"
-> ["####","#####"]
["Another", "example", "with spaces", "and also", "question marks", "...??"]
"a"
-> ["and also", "example", "with spaces", "question marks"]
["/.\\", "...", "><", "[[]]", "~.~", ".1.2", "_[(("]
"."
-> ["...", ".1.2", "/.\\", "~.~"]
["(())", "()()", "((()))", "(())()", "()(())", "()()()"]
"(())"
-> ["(())", "(())()", "((()))", "()(())", "()()()"]
["]["]
"]["
-> ["]["]
["\\", "\\\\", "\\\\\\"] # Input is encoded as JSON, while "\\" means a string with a single backslash
"\\"
-> ["\\", "\\\\", "\\\\\\"]
```
Output from your program may be different from above test cases, as the order of words in same group is not required.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
## Input / Output
Input / Output are flexible. For example, you may use any reasonable ways including but not limited to:
* You may I/O `string` as
+ Your languages built-in `string` in ASCII or any ASCII compatible encoding (e.g. UTF-8);
+ Your languages built-in `string` in any codepage that supports all printable ASCII characters (e.g. UTF-16);
+ NUL terminated array of characters;
+ array of integers, each integer is the ASCII value of character
+ 0 terminated integer array;
* You may I/O the array of `string` as
+ A collection (`OrderedSet`, `LinkedList`, `Array`, ...; or `HashSet` only for input) of `string`s
+ A character (or ASCII value) matrix with NUL (0) padding at the ending to each short ones;
- Output matrix may have unnecessarily extra 0 padding;
+ Line break (CR / LF / CRLF) separated single string;
+ JSON encoded array of string
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
≬ṗ⁰cFsµ₌ǎṗJ⁰ḟ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiazhuZfigbBjRnPCteKCjMeO4bmXSuKBsOG4nyIsIiIsIltcIigoKSkoKVwiLCBcIigpKClcIiwgXCIoKCgpKSlcIiwgXCIoKCkpXCIsIFwiKCkoKCkpXCIsIFwiKCkoKSgpXCJdXG5cIigoKSlcIiJd) Input as `a` then `s`. Inefficient approach.
```
≬ # a 3-element lambda:
ṗ # get all subsets
c # does it contain
⁰ # the last input (s)?
F # filter according to lambda
s # sort alphabetically (handles ordering of 1 and 2)
µ # a sorting lambda:
₌ # parallel apply:
ǎ # substrings (handles 1, 2, and 3)
ṗ # subsets (handles 4)
J # join together
ḟ # find the first occurrence of
⁰ # last input
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs a 2D-array; add 1 byte if that isn't permitted. Works in theory for all tests cases but there is a bug in Japt that prevents it from being able to handle mismatched square brackets in strings within an input array.
```
fÈà øVÃüøV ÔËñbV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZsjgIPhWw/z4ViDUy/FiVg&input=WyJpbnRlcmFjdGlvbiIsInRyYWRpdGlvbmFsIiwidHJhaW4iLCJ0cmFpbmluZyIsInRyYW5zZm9ybWF0aW9uIl0KInRyYWluIgotUQ)
```
fÈà øVÃüøV ÔËñbV :Implicit input of array U & string V
f :Filter U by
È :Passing each element through the following function
à : Combinations
øV : Contains V?
à :End filter
ü :Group & sort by
øV : Contains V?
Ô :Reverse
Ë :Map
ñ : Sort by
bV : First index of V
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 85 bytes
```
~(L$`^.+
$&¶mN$$`^(.$*$\$&)?.$\*¶-$$#1¶mO$$`^(.$\*?)$\$&.$*¶$$1
\G.
$\$&.$*
^
0A`¶O`¶G`
```
[Try it online!](https://tio.run/##NcpRDsIgDAbg917DZtk0EjnB4tNeFneBZYE4NCTSJYxnj8UBuBgW1Ie2f/vVm2BJy5zf7YhqESfAJkV3Q15agUecsel6DimeEQ@Sbfpb3xWthihhHgT8DrDA5apSnLgGlXPw2hJYCsbre7AbAR@coQB7JbMCz9UW0i/4vtdu6VkC7Y/NO138Aw "Retina – Try It Online") Takes the keyword as the first line and the search strings on the remaining lines. Explanation:
```
~(`
```
Evaluate the output of the rest of the program on the original input.
```
L$`^.+
```
Match just the keyword but replace the entire input with...
```
$&¶mN$$`^(.$\*$\$&)?.$\*¶-$$#1¶mO$$`^(.$\*?)$\$&.$\*¶$$1
```
... the keyword followed by two sort commands (see below).
```
\G.
$\$&.$*
```
Escape the keyword and insert `.*` between each escaped character.
```
^
0A`¶O`¶G`
```
Prefix two commands to the keyword and turn the keyword into a filter command.
For the example of the input keyword of `train`, the program that gets evaluated is as follows:
```
0A`
O`
G`t.*r.*a.*i.*n.*
mN$`^(.*train)?.*
-$#1
mN$`^(.*?)train.*
$.1
```
Explanation:
```
0A`
```
Delete the keyword.
```
O`
```
Sort the input. (This ensures that `train` appears before `training`.)
```
G`t.*r.*a.*i.*n.*
```
Filter for strings that have `train` as a subsequence.
```
mN$`^(.*train)?.*
-$#1
```
Sort strings that contain `train` first.
```
mO$`^(.*?)train.*
$1
```
Sort strings that contain `train` by the (length of the) prefix of the word `train`.
[Answer]
# [Python 3](https://docs.python.org/3/), 104 bytes
```
lambda a,s:sorted([i for i in a if all(j in i for j in s)],key=lambda x:(x==s)-(x[:len(s)]==s)-(x in s))
```
I used `sorted` to order the result of the nested `list` comprehension.
[Try it online!](https://tio.run/##VZDBDoMgEETv/QriCRJ76s2EL7E9oK4tLe4aoA1@vQWxak/M25kdCOPkH4SXuZfX2aih6RRTpascWQ8drzXryTLNNDLFdM@UMfyZKBuLdOJWvmCS63qoeJDSiTMPdWUAefRXzmkxj1aj5z2vixbQgy3KArCl96YPZ8w6SPCJWNxKttpCnI41BhqrvCaM0ZZohI3ugDscjUUsjVn9N9LQaPxFIYxGbaTTAzIpE3kzjjMa9nUkn2W6bJ3Gb/gC "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
Fθ«≔ηζFιF¬⌕ζκ≔Φζνζ¿¬ζ⊞υ⟦¬№ιη⌕ιηι⟧»≔⟦⟧εW⁻υε⊞ε⌊ιEε⊟ι
```
[Try it online!](https://tio.run/##NZDNasMwEITP8VMsPkmgPkFOpZBbiu/GB2Er8VJ5leinAYc@u7qS7dPOznw7CI2z9qPTNueb8yCeEt7N6TMEvJOYFazy3JxqghLq/HZRXJAmsSr4kVLCDl/QRuOLS3K/w9uGr0x1KcwiKeiL8eUSRYEKZslsbauLAhz48K/ZO/tBgWHjNaM1IK5IKZQScxQaBWzikhZ@H4OdRy6@6kdJOvcorjzn3PctB8brMaKjVrVe42IosgqRNZmJJasJC6DttiEdE@m@SQr8C4uuNcMBDfnj1/4D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fθ«
```
Loop through the list of strings.
```
≔ηζ
```
Start with none of the letters of the search keyword found.
```
Fι
```
Loop through the letters in the current string.
```
F¬⌕ζκ
```
If the search keyword starts with the current letter, then...
```
≔Φζνζ
```
... remove the first letter from the copy of the search keyword.
```
¿¬ζ
```
If the search keyword is now empty, then...
```
⊞υ⟦¬№ιη⌕ιηι⟧
```
... push a list of three terms to the predefined empty list: i) a flag that is zero if the keyword is contained in the string rather than just a subsequence ii) the position of the keyword in the string iii) the string.
```
»≔⟦⟧εW⁻υε⊞ε⌊ι
```
Sort the matches.
```
Eε⊟ι
```
Output just the strings.
[Answer]
# JavaScript (ES10), 126 bytes
*-7 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
Expects `(array)(string)`.
```
a=>s=>[`^${q=s.replace(/\W/g,'\\$&')}$`,"^"+q,q,q.replace(/\\?./g,'.*$&')].flatMap(e=>a.filter(s=>a[0+s]?0:a[0+s]=s.match(e)))
```
[Try it online!](https://tio.run/##nVTBctMwEL3nKzRuB0skUQPHgpPhAAdmgEMPHGyXqo6cGGzJsZyE0mm/gBkuHOE/@J7@AJ8QdiXHTiGFoeMZ7b7dt283K7XvxUqYpMrKeqj0VG7SYCOCsQnG4dnp4eUiMLySZS4SSY@it0ezgR9Fhw98dnV4NvBOvf5iAN8OJZpwJPGHSIp5mov6lSipDMaCp1ley4qCtghHfRNPRsfOgSaFqJM5lYyxTSUXy6yS1E@Nz0BaTF9kuTy5UAkdMV7rk7rK1Iwybso8q6kXqUh5jKe6ei5Aw5BgTC57hOSyJiERA7IeEPmxlEktpyQmATFdJdQVON5K5OxJU1NJkCApFYyubTDRyuhc8lzP6MuTN6@5sRNk6QUFLiN94sPXJ4gQ@CQIuo4T4v/88eXm21c4fXJM/Jvvn5G9JTDoccU2oZdIBevxBp5UiV62/o4tq8xIBCuAXtxrsr1wP22PYNzrYaNcnleizrRCltalbNFMqg7sJqyDPZ0DMs4Z3EfOjaGL80xtk7COXLQow2kdEjngNrEb00VXrnS9ld6SocW@sv9qe0cL3PjKrRbMBdi5rHDlDVpbiBeEAYd6oa2zLUTSaNaVmGZtO0CZ2lp4Yc5VBp520f46RwKlPex/iN9WslegHMPuRaVL0/rwxpdJl4IXf75st9TJwK1WM6GyT@07kbDgQqqp6KZQptRVdz9aNddzv/Z/b2h/F@ccMsPhEE4@xA8dbvEQLE4BAJgNh9@mNhzIHwA6cEdzbs0BiliLtNtxiDyD5zJ3T@SjKMocX8c6q@fElPCf0gASakpEbvBPaLGUBqcnhag@GDsQn0ywgUD1HeZdYr8p2BGOeBQ5LTjHT@EIwzgGc82vMf6IPwbzLqQUO3GvXVyTaeqRbfUoZQwwZdQahM5hTYTtMCACojawU9pS2@I/aoAdh1gL59YHa0eJotaAAxw478pBfISUkee8Xw "JavaScript (Node.js) – Try It Online")
Escaping characters in the regular expressions costs ~~41~~ 34 bytes ... :'(
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 121 bytes
```
s=>a=>a.filter(a=>g(a,s),g=([c,...x],y)=>c?g(x,y.slice(c==y[0])):!y).sort((x,y)=>(g=i=>s==i?-1:i.indexOf(s)>>>0)(x)-g(y))
```
[Try it online!](https://tio.run/##nVRLU9swEL7nV6ThEGnGVoFTB2pneuHQQzlwtD2NcGSj1pGM5IDdTvnr6a7kR6ChnTLJaPfbx7e70ibf@AO3uZF1Eyq9EfuraG@jmMOXFbJqhCGgl4QHlgZlRJI8YIy1WdDRKM5XJWmDjtlK5oLkUdQlpxmlF@86yqw2DUEvxJEyklFso0iuwrMLyaTaiPa6IJbGcXxKSUvDknSU7i9nRtzvpBFkWdglZUbwzZWsxE2ncnIaLHdN8QHMtq5ks05VqtZsy2vSRvHPNmpH@/oy18rqSrBKl@TzzfUXZhsjVSmLjlwR8cAr0iZn0OqgY9s0WKZqGbTJeUZ/0cvZPlnkQsENLIKFULnejfqBrI20AsEDwEU2672zMJ4nxyOPcGazGdaqxK3hjdQKo7SuxYhKoSZw6HAKlvWKL@v14C2MvhO9vZVqcIq2rviIJDbsEa8Aj45Dm95O6Uo3A/UQ7Ls8lvlflV@pAgPAYxj/JqYDeScMXnyPHh3El0KDR64jl@qq8LynbQzfyLEiIKkGCdvkVWULbbbjjD7Ij3gk4R/8z8ncWygf4W5HFTs76rDSu3xywYLf7sa7mmjgeU3Jlfwx7oyAa94KteFTF8rW8Hsdh9Bqeqe3dfD3mm40@B8BTxiGcLIQP6gwh0OQ2AgA30Ufxp5H92FAdgLoxB/9OYgT5HHSM71wQe4n2J473Jg5rBzf1pVA9VE2d3Nb81xYhFxt5ryyGvX7nbA4x3zLzXfnhVlWKyzE@yqH4a@TviBy3bxnadpToog/4pkkWYbyiT053xk7R/k1IQSrsr5qnzO4ByrMctyEUIoGQomXaOg1OtjoYRTYgN9ZfInROSVMJH@mQtEsQQo4PYGDYPatpekkQYNAOH3g8YDf "JavaScript (Node.js) – Try It Online")
no regex is shorter
# [JavaScript (Node.js)](https://nodejs.org), ~~133~~ ~~126~~ 125 bytes
```
s=>a=>a.filter(x=>x.match(s.replace(/(\w)|./g,(c,d)=>'.*'+[d||'\\'+c]))).sort((x,y)=>(g=i=>s==i?-1:i.indexOf(s)>>>0)(x)-g(y))
```
[Try it online!](https://tio.run/##nVRLU9swEL7nV2TCwVKxxePUKbWZXjj0UA4cbU8jbCVR60hGcsBpKX893ZX8CDS0UyYZ7X77@L7VI/nG77ktjKybSOlS7K7inY0TDl@2kFUjDGnjpGVr3hQrYpkRdcULQU5I9kAf2ckyJEVY0jgJ2LvgOC0fH4MsC46LnFLKrDYNIW24hTxZxjJObBzLy@jsg2RSlaK9XhBLkyQ5paSl0ZJsKd1dTIy420gjSLCwAQVFXl7JStxsVUFOw2DTLN5D2NaVbOaZytQchqtxyp9t3A7x@UWhldWVYJVeks8311@YbYxUS7nYkisi7nlF2vQM5uz9U5w5DDIVhG16ntNf9GKyS2eFUHAKs3AmVKE3g79nayOtQHAPcJZPuuwkSqbp4coDnPlkglqVuDW8kVphlda1GNBSqBHsJ5yDst7xst4P38LoJ9HrW6n6pGjh1gckcWCPeAV4SOzH9HpsV7rpqftiP@Whzv9SfkUFNgCXYfydmC3YlTB48B16cBBvCgMeuYlcq1PhRUfbGF7KQRGQVL2F1@RdZRfarIc9@iK/xQMN/@B/TubuQvkKdzpqsbGDD096U4wpeOC3m@GsRhq4XrPkSv4Y3oyAY14LVfJxCmVr@L0Om9BqvKe3TfB3Tbc1xhhkoiiClUX4QYc5HIHFQQD4Kboy9ry6KwOyI0BHfunW3hwhj7Oe6UUKej/B61nhi5nCk@PruhLoPshmNbU1/OFZhFyVU15Zjf7dRljcx3TNzXeXhb1cXqIQ71T2y18nfUHkpjlhWdZRokk@4pqmeY72iT253Bk7R/s1JQRVWafa9fTpngq7HDchlGKAUOItBjqP9jG6XwUx4HcRLzEkx4aR5M9WEM1TpIDVEzgIYT9alo0WPCiE1RceLvgN "JavaScript (Node.js) – Try It Online")
Sort equality then the first occurrence
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ʒæIå}ΣηR¬œ€Œ˜«Ik
```
[Try it online](https://tio.run/##yy9OTMpM/f//1KTDyzwPL609t/jc9qBDa45OftS05uik03MOrfbM/v8/WklPT09JR0lXVxdI6umCIIihB@brAmmlWC5dXQA). (Way too slow for a test suite of all test cases.)
**Explanation:**
```
ʒ # Filter the first (implicit) input-list by:
æ # Get the powerset of the current word
Iå # Check if the second input is in this list
}Σ # After the filter, sort by:
η # Get the prefixes of the current word
R # Reverse this list
¬œ # Get the permutations of the current word as well
€Œ # Get the substrings of each permutation
˜ # Flatten this list
« # Merge the two lists together
Ik # Get the index of the second input in this list
# (after which the filtered and sorted list of words is output implicitly)
```
[Try just `ηR¬œ€Œ˜«` online](https://tio.run/##AR0A4v9vc2FiaWX//863UsKsxZPigqzFksucwqv//3p5eA) to see how its order corresponds to the order of \$1\$ through \$4\$.
[Answer]
# [Haskell](https://www.haskell.org/), 137 bytes
```
import Data.List
o s a=map snd.filter((<0).fst)$sort[(-length(
takeWhile($x)[isSubsequenceOf s,isInfixOf s,isPrefixOf s,(==)s]),x)|x<-a]
```
[Try it online!](https://tio.run/##PY29CoMwFIV3nyKIQwIqfQCzdSkUWujQQRxSvakXY2JzY@vQd7eh2C6H88H56RUNYMy64jg5H9heBVUekULiGDElRzUxsl2p0QTwnFc7UWoKIqOYrnlhwN5DzxMW1ADXHg3wbBE10mW@ETxmsC2cNKMc6WA1Lps/e/gBl1JQI/JFvJeqUM06KrRy8mhD5lKw8TbNXs53lLZfYnHTzZv7aywQMHhGSNcP "Haskell – Try It Online")
[Answer]
# [Raku](https://raku.org/), 98 bytes
```
{$^s;@^a.grep(/<{S:g[(\W)|.]='\\'x?$0~$/~'.*'
given $s}>/).sort:{first :k,$_~~*,$s,/^$s/,/$s/,!0}}
```
[Try it online!](https://tio.run/##RZJLbsIwEIb3nGKKrDpBiQNddMGzPUMXXQSIDDUQkdipHQoIyNWpx0lAkWa@ef0zllIInb3f8zO8bmByv5ClGX0sOdtqUXjR@PI13Mbe/Nu/ssWEzuf0NCP9ikQVZT3a2aZ/QgIxt2nkM6N0ObxsUm1KGO4DklRVLyAmiJbEREGE5qV/u90NP0OXJHF/wQq72/NHYKNBG8FkOpcAl3jjXUni1@lbFzZKdwC88VrIUmgQcq0ODT1soVMjQNijymkA1OWoHzRzmVhpXqZKwlopq1rzVsgWn0nnUMLBQ0Llq1TWHeJUZLzhFPfUzDNoks9Y5e2QVKUDVK5TrbS9WePh@gw7oQU4OiK6h2DoorafMQZhGAIL8QPGLIfWYncYNl0e/bQb7RhFjRPPi0wgHtNyB6bga2Ew5PIHeGYU8u9BGHdqzvXeVe2m2cwK2r6HbMTsn1DX0E3HaON4sUBfscrVBuwNfRLbARxn1O/c/wE "Perl 6 – Try It Online")
I'm dismayed to learn that Raku has lost Perl 5's `quotemeta` function and `\Q` quoting construct. Reproducing the concept cost many bytes.
Anyway...
* The functions arguments are passed in the placeholder variables `@^a` (the list of strings) and `$^s` (the search keyword).
* The `grep` call on `@^a` filters the list to those elements in which the search keyword appears as a subsequence. This is done by transforming the search keyword into a new string by prefixing every non-word character with a backslash and appending a `.*` to every character.
* Then `sort` sorts the remaining strings. The sort function is `first :k, $_ ~~ *, $s, /^$s/, /$s/, !0`. This returns the index (due to the `:k` flag) of the first of `$s`, `/^$s/`, `/$s/`, or `!0` (a shorter way to write `True`) against which the current word smart-matches. The current word matches the string `$s` if it's the same as the search keyword, matches the regex `/^$s/` if the search keyword appears at the start of the string, matches the regex `/$s/` if the search keyword appears anywhere inside the string, and always matches `True`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 113 bytes
```
(s=#2;SortBy[Select[#1,StringContainsQ[#,s]&],(d=Last@LongestCommonSequencePositions[s,#];{Length@d,First@d})&])&
```
[Try it online!](https://tio.run/##TU3BCoJAEL33FbELYrCXuoYgBZ08GB6XPWw62YI7U@4ERfjtZljaZd68N@@98ZYv4C270vbnpI9DIjfbglrePXUBDZSs5VoV3Dqs94RsHYajliqYyKi4SjIbOM0Iawi8J@8JC7jdAUvIKTh2hEEHJc32lQHWfEkrdXDtkKm6VWRWUZ8PzZye9UtIoZZCfucPJpSiU4tRMYs5VJI/ObSfR0IJeFwbO7HBA@3IbDPw6fCvkZ/jSDyu3WQ2/Rs "Wolfram Language (Mathematica) – Try It Online")
Thank you for the interesting challenge, golf it on Mathematica is hard, but I tried (-\_-)
`LongestCommonSequencePositions` is one of longest function names in WM 8)
] |
[Question]
[
What general tips do you have for golfing in BQN? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to BQN (e.g. "remove comments" is not an answer).
Please post one tip per answer.
At the moment of writing, the [official BQN site](https://mlochbaum.github.io/BQN) is the most comprehensive resource for learning BQN. BQN is the [Language of the Month for December 2021](https://codegolf.meta.stackexchange.com/q/24119/78410); you can find some more information and resources on the LotM page.
Additional resources:
* [Tips for golfing in APL](https://codegolf.stackexchange.com/q/17665/78410)
* [Tips for golfing in J](https://codegolf.stackexchange.com/q/6596/78410)
* [BQNcrate](https://mlochbaum.github.io/bqncrate/), a collection of short snippets for common tasks
[Answer]
# Use `⊒˜` instead of `↕∘≠`
Suggested by [Marshall](https://codegolf.stackexchange.com/users/95592/marshall)
`⊒`(progressive index of) consumes indices given any array, providing a range of the array's size when applied with selfie. You can save a byte by using it in any place instead of `↕∘≠`.
[Try it!](https://mlochbaum.github.io/BQN/try.html#code=YXJyYXkg4oaQICJhYWFhYWEiCgrin6jihpXiiJjiiaAsIOKKksuc4p+pIHvwnZWO8J2VqX3CqDwgYXJyYXk=)
[Answer]
# BQN's combinators
BQN allows Lisp style functional programming and hence comes with its own set of combinator symbols. Some basic patterns can be simplified using combinators instead of trains:
| Lambda | Train | Combinator |
| --- | --- | --- |
| `{ùï© F ùï©}` | `‚ä¢ F ‚ä¢` | `FÀú` |
| `{F G ùï©}` | `F G` | `F‚àòG`, `F‚óãG` |
| `{ùï© F (G ùï©)}` | `‚ä¢ F G` | `F‚üúG` |
| `{(F ùï©) G ùï©}` | `F G ‚ä¢` | `F‚ä∏G` |
| `{ùï© F ùï®}` | `‚ä¢ F ‚ä£` | `FÀú`(See: [this APL tip](https://codegolf.stackexchange.com/a/158231/80214), replace `‚ç®` with `Àú`) |
| `{F ùï® G ùï©}` | `F G` | `F‚àòG` |
| `{(G ùï®) F (G ùï©)}` | `G F G` | `F‚óãG` |
| `{(ùï® F ùï©) G (ùï® H ùï©)}` | `F G H` | `F‚ä∏G‚üúH` |
You can use the shorter one between the train and the combinator versions wherever necessary, and sometimes in conjunction.
For a more visual explanation of the combinators, see [here](https://mlochbaum.github.io/BQN/doc/primitive.html#modifiers)
[Answer]
# Don't forget about `¬`
BQN doesn't have increment and decrement primitives, which means you're often spending two bytes on `1+`, or potentially three on `¯1+`. Sometimes `¬` can help:
* Monadic `¬¨ùï©` ("not") is logical negation, but it's actually implemented as `1-ùï©`.
* Dyadic `ùﮬ¨ùï©` ("span") is even more interesting: it's `1+ùï®-ùï©`.
These can save bytes under some specific circumstances. For instance, if you need to decrement the result of an expression, `-¬aFb` is shorter than `¯1+aFb`. Similarly, `a¬-b` is shorter than `a+1+b`, and `a-¬b` is shorter than `a-1+b`. If you need to multiply a number by 2 and add 1, `¬⟜-` is equivalent to `1+2×⊢`.
This is similar to the use of `~` in C-like languages (although there, `~x` is `-x-1`, not `1-x`).
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.