text
stringlengths 180
608k
|
---|
[Question]
[
# Introduction
[Nine-Ball](https://en.wikipedia.org/wiki/Nine-ball) is a popular pool game played casually and as a competitive sport.
There is one of each numbered ball, with the numbers 1 to 9.
The game starts with all 9 of the balls in a diamond shaped rack, like so:
```
1
2 3
4 9 6
5 7
8
```
The 1 ball is always at the front of the diamond, and the 9 ball is always in the middle, with all the other balls placed randomly (the "X"s in this diagram):
```
1
X X
X 9 X
X X
X
```
# Challenge
Your challenge, given no input, is to generate and output random 9-ball pool racks in the text format of the examples. Extra surrounding whitespace is allowed.
Output may be through any convenient method, standard loopholes apply. A new rack MUST be generated on each run, you cannot just produce a single randomly-chosen rack every time. Extra surrounding whitespace is allowed.
# Example Outputs
```
1
2 3
4 9 5
6 7
8
```
```
1
8 3
2 9 7
4 6
5
```
```
1
2 8
3 9 7
5 4
6
```
Least bytes per language wins.
[Answer]
# [R](https://www.r-project.org/), 61 bytes
```
cat(paste0(c(" 1
","","
","9 ","
","","
"),sample(2:8)))
```
[Try it online!](https://tio.run/##K/r/PzmxRKMgsbgk1UAjWUNJQcGQS0FJRwmIuIDYEsSGCygoKGnqFCfmFuSkahhZWWhqav7/DwA "R – Try It Online")
Prints alternately the proper whitespace/newline (with 1 and 9 included) and elements of a random permutation of \$\{2,\ldots,8\}\$.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~91~~ 87 bytes
```
from random import*
print(" 1\n %d %d\n%d 9 %d\n %d %d\n%3d"%(*sample(range(2,9),7),))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVaCgpKBjG5CmopgBRTB6QsgQz4ALGKUqqGlrFibkFOakaQBPSUzWMdCw1dcw1dTQ1//8HAA "Python 3 – Try It Online")
-4 bytes thanks to xnor (final `\n %d` -> `\n%3d` and `tuple(...)` -> `(*...,)`)
[Answer]
# [Bash](https://www.gnu.org/software/bash/) or any Bourne Shell, with modern coreutils, 54 52 bytes
```
printf ' 1
%s %s
%s 9 %s
%s %s
%s' `shuf -i2-8`
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUFdQcGQS0G1GIi4gKQliIZyFYCEukJCcUZpmoJuppGuRcL//wA "Bash – Try It Online")
-2 bytes thanks to @dzaima (use shuf -i option for an implicit seq)
Originally:
```
printf ' 1
%s %s
%s 9 %s
%s %s
%s' `seq 2 8|shuf`
```
[Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUFdQcGQS0G1GIi4gKQliIZyFYCEukJCcWqhgpGCRU1xRmlawv//AA "Bash – Try It Online")
I saved one byte by not including a newline at the end of the source, and another by not including one at the end of the output.
Explanation:
`seq 2 8` outputs `2 3 4 5 6 7 8` on separate lines.
`|shuf` randomly reorders them. (This is what needs modern coreutils.)
`printf <formatstring> <args>` does a C-like printf of the arguments with the format string.
[Answer]
# JavaScript (ES6), 89 bytes
```
_=>` 1
X X
X 9 X
X X
X`.replace(/X/g,g=_=>m^(m|=1<<(i=Math.random()*9|0))?i:g(),m=3)
```
[Try it online!](https://tio.run/##HYy9DoIwFEZ3nuJu3CvIT3RBqD6BewejNFAqhrakEBfx2Wvj8p0znHwv8RZL58Z53RvbSz8w/2DnFqCMgAOPOFRh/wrA28zJeRKdxJznKlUstPqOemNl0@DIrmJ9Zk6Y3mqkXbUVRJfxpJBSzQ7kB@vQAIOiBgMNHAOShOATrjtrFjvJbLIKByRIIL6ZmOro638 "JavaScript (Node.js) – Try It Online")
### How?
We replace each "X" in the template with a random integer \$0\le i<9\$ such that the \$i\$-th bit in the bitmask \$m\$ is not already set, and we simultaneously update \$m\$.
We start with \$m=3\_{10}=000000011\_2\$ so that \$0\$ and \$1\$ are never chosen.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 25 bytes
```
F⁷⊞υ‽⁻E⁷⁺²κυ↖⪪⁺⪫⪪⪫υω⁴9¦1³
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw1xTIaC0OEOjVEchKDEvJT9Xwzczr7RYwzexQMNcRyEgB8g20lHI1tTUUSjV1LTmCijKzCvRsAot8ElNK9FRCC7IySzRACvzys/M04DwwUygkeVAXSZArGSpBCINQaQx0JT////rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⁷
```
Loop 7 times.
```
⊞υ‽⁻E⁷⁺²κυ
```
Create a list of the integers from 2 to 8, perform set difference with the list of integers collected so far, select a random integer, and push it to the empty list. This shuffles the integers from 2 to 8.
```
⁺⪫⪪⪫υω⁴9¦1
```
Concatenate the integers, insert a `9` after the fourth, and append a `1`. Edit: Saved 2 bytes by using @JonathanAllan's trick to insert the `9`.
```
↖⪪...³
```
Split the string into a 3×3 grid and print it diagonally thus achieving the desired output.
[Answer]
# [Python 3](https://docs.python.org/3/), 128 bytes
```
from random import*
l=[1]+sample(range(2,9),7)
l.insert(4,9)
for i in[1,2,3,2,1]:print(f"{' '.join(map(str,l[:i])):^5}");l=l[i:]
```
[Try it online!](https://tio.run/##DYnNCgIhGADvPoXsZbVkwd0iMvZJxEBI6wv/@PQS0bObh2FgpnzaK6etd485UrTpMQSxZGwHEnYtzbHaWIJj4z0dW8WViwsnYYFUHTZ2GoH4jBQoJC3FKraBNKogpMb89J3pvLwzJBZtYbWhCFqB4Vzdz7@J38IeNCjT@x8 "Python 3 – Try It Online")
Unfortunately not even close to the [straightforward solution](https://codegolf.stackexchange.com/a/197692/90219), but I spent so much time on this that I still wanted to share it.
# Ungolfed:
```
from random import *
# Generate random sampling and ensure 1st element is 1
l = [1] + sample(range(2, 9), 7)
# Ensure 5th element is 9
l.insert(4, 9)
for i in [1, 2, 3, 2, 1]: # Numbers of digits per row
# Take i numbers from the beginning of l, join them with spaces
# Then center the resulting string in a field of length 5 and print
print(f"{' '.join(map(str,l[:i])):^5}")
# Drop the just printed numbers
l = l[i:]
```
It can be shortened but then it no longer makes use of the nifty `:^5` format specifier:
# [Python 3](https://docs.python.org/3/), 112 bytes
```
from random import*
l=[1]+sample(range(2,9),7)
l.insert(4,9)
for i in[1,2,3,2,1]:print(' '*(3-i),*l[:i]);l=l[i:]
```
[Try it online!](https://tio.run/##DYnLCsMgEADvfoW3qN0WjIVSS75EPARq2oX1wcZLv956GAZm2q9/a3FjHFyz5L28pzC3yt0I2oKNl3PPjZKa75PUCk8NDy3ohuVM3NV9BnFUliixBAsruImNvjGWrha5GOWuqMFQ8Bj1izYK6OMYfw "Python 3 – Try It Online")
A funny one without `insert` which bounces the 9 into the middle by slicing with a step size of 2:
# [Python 3](https://docs.python.org/3/), 115 bytes
```
from random import*
l=[1]+sample(range(2,9),7)+[9]
for i in[2,4,6,4,2]:print(' '*(3-i//2),*l[:i:2]);l=l[i:]+l[1::2]
```
[Try it online!](https://tio.run/##DYnLCoMwEADvfkVu5lXEWCpu8UuWHIRqu7B5kObSr09zGAZm8q9@Ulxau0oKohzx1UUhp1L1wDvO3nyPkPmU/b1P6eym7KoMbn64UhEkKKKzd/voOA@5UKxyFKOWy42mySmrGYHAefXknZHAG8YZemjtDw "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/en/), ~~66~~ 52 bytes
```
$><<" 1
%d %d
%d 9 %d
%d %d
%d"%[*2..8].shuffle
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkZJQcGQS0E1BYi4gKQliIZyFYCEkmq0lpGenkWsXnFGaVpaTur//wA "Ruby – Try It Online")
Also quite a boring answer, similar to the Perl and Bash solutions.
Saved 14 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)!
[Answer]
# [Kotlin](https://kotlinlang.org), ~~102 95 93~~ 92 bytes
```
{List(7){it+2}.shuffled().fold(" 1\n XX\nX9 X\n XX\n X"){s,c->s.replaceFirst("X", "$c ")}}
```
[Try it online!](https://tio.run/##Lc2xDoIwFEbhWZ7iT@NwbwQSXYwmMjq5uXRgIUC1oRbSFpemz14Z3M70nWkORtv87QzUFcRV8wxO2xduOT60D3TmqMPhlGr/XpUy40Bcq9kMJIBjayFla@UF8p@AFBx92VeNr924mK4f79ptkJCihNj3EJxSVqvFp9OWGLHYLdsykCLmIuUf "Kotlin – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y
```
A full program which prints the result.
**[Try it online!](https://tio.run/##AToAxf9qZWxsef//N@G6isW7xZJIajjigJg74oKs4oG24oG9wqbhu7VEwqTFk@G5lnrigbZa4bma4oKsWf// "Jelly – Try It Online")**
### How?
```
7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y - Main Link: no arguments
7 - seven
Ẋ - shuffle (implicit range [1..7])
Ż - prepend a zero
ŒH - split in half
j8 - join with an eight
‘ - increment (vectorises)
;€ - concatenate each with:
⁶ - a space character
œṖ - partition before indices:
¤ - nilad followed by link(s) as a nilad:
⁽¦ỵ - 2479
D - digits -> [2,4,7,9]
z⁶ - transpose with space filler
Z - transpose
Ṛ€ - reverse each
Y - join with newline characters
- implicit, smashing print
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 51 bytes
```
printf ' 1
%s %s
%s 9 %s
%s %s
%s',pick *,2..8
```
[Try it online!](https://tio.run/##K0gtyjH7/7@gKDOvJE1BXUHBkEtBtRiIuICkJYiGchWAhLpOQWZytoKWjpGensX//wA "Perl 6 – Try It Online")
I'm not really happy with how boring this solution is.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 60 bytes
```
' 1
{0} {1}
{2} 9 {3}
{4} {5}
{6}'-f(2..8|Sort{Random})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X11BwZBLodqgVqHasJar2qhWwVKh2rgWKGQCFDIFMhSqzWrVddM0jPT0LGqC84tKqoMS81Lyc2s1//8HAA "PowerShell – Try It Online")
-17 bytes thank you @Veskah for cleaning up whitespaces
Originally:
```
'
1
{0} {1}
{2} 9 {3}
{4} {5}
{6}
' -f (2..8 | Sort {Get-Random})
```
[Answer]
# Perl 5, 62 bytes
```
printf" 1
%d %d
%d 9 %d
%d %d
%d",sort{int(rand 3)-1}2..8
```
[Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1JQcGQS0E1BYi4gKQliIZyFYCEkk5xflFJNVClRlFiXoqCsaauYa2Rnp7F//8A "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 26 bytes
```
4>þ`ṚŒḄYṣ1µ7ẊŻs4j8‘;€⁶ż@o⁶
```
[Try it online!](https://tio.run/##ATgAx/9qZWxsef//ND7DvmDhuZrFkuG4hFnhuaMxwrU34bqKxbtzNGo44oCYO@KCrOKBtsW8QG/igbb//w "Jelly – Try It Online")
A full program that takes no arguments and outputs a pool rack.
## Explanation
```
4>þ` | Outer table using 1,2,3,4 on both sides and > as the the function [0,1,1,1],[0,0,1,1],[0,0,0,1],[0,0,0,0]
Ṛ | Reverse [0,0,0,0],[0,0,0,1],[0,0,1,1],[0,1,1,1]
ŒḄ | Bounce [0,0,0,0],[0,0,0,1],[0,0,1,1],[0,1,1,1],[0,0,1,1],[0,0,0,1],[0,0,0,0]
Y | Join with newlines
ṣ1 | Split at 1s
µ | Start a new monadic chain
7Ẋ | Shuffle list of 1..7
Ż | Prepend with zero
s4 | Split into pieces of length 4
j8 | Join with 8
‘ | Increment by 1
;€⁶ | Append space to each
ż@ | Zip with list generated above
o⁶ | Replace 0s with spaces
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Y8L.r1†9ª•26Ià•Λ
```
-2 bytes thanks to *@Grimmy* by using a fixed length of `2` with some directions duplicated.
[Try it online.](https://tio.run/##yy9OTMpM/f8/0sJHr8jwUcMCy0OrHjUsMjLzPLwASJ@b/f8/AA)
**Explanation:**
```
Y # Push 2
8L # Push a list in the range [1,8]
.r # Randomly shuffle it
1† # Filter the 1 to the front
9ª # Append a trailing 9 (i.e. [1,3,4,8,5,2,6,7,9])
•26Ià• # Push compressed integer 33557713
Λ # And use the Canvas builtin with those three values
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•26Ià•` is `33557713`.
*Canvas explanation:*
The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the fixed length of `2`.
2. The string to 'draw', which in this case is the list `[1,#,#,#,#,#,#,#,9]` (where the `#` are random digits in the range `[2,8]`).
3. The directions, which in this case is `33557713`. These will be the directions `[↘,↘,↙,↙,↖,↖,↗,↘]`.
With these arguments, it will draw as follows (let's take the random list `[1,3,4,8,5,2,6,7,9]` as example here):
```
2 characters (1,3) in direction 3 (↘):
1
3
2-1 characters (4) in direction 3 (↘):
1
3
4
2-1 characters (8) in direction 5 (↙):
1
3
4
8
2-1 characters (5) in direction 5 (↙):
1
3
4
8
5
2-1 characters (2) in direction 7 (↖):
1
3
4
2 8
5
2-1 characters (6) in direction 7 (↖):
1
3
6 4
2 8
5
2-1 characters (7) in direction 1 (↗):
1
7 3
6 4
2 8
5
2-1 characters (9) in direction 3 (↘):
1
7 3
6 9 4
2 8
5
```
NOTE: Since we use a fixed length of `2`, the directions are leading in drawing the Canvas. So the trailing `3` in the directions `33557713` is mandatory for outputting the `9` here, whereas my previous 18-byter used the leading `3` with implicit wraparound to output the `9`, since the lengths-list were leading for drawing instead.
[See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# [Dyalog APL Extended](https://github.com/abrudz/dyalog-apl-extended), 38 bytes
```
{5 5⍴(~2⊤29010619)⍀∊⍕¨∊,∘9¨@4⊢1,1+?⍨7}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24RqUwXTR71bNOqMHnUtMbI0MDQwM7TUfNTb8Kij61Hv1EMrgLTOo44ZlodWOJg86lpkqGOobf@od4V5LUh/7xqFR90tCuoK6lzEcQA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 90 bytes
```
t: random[2 3 4 5 6 7 8]foreach c{ 1
; ;
; 9 ;
; ;
;}[prin either c >#":"[take t][c]]
```
[Try it online!](https://tio.run/##JchNCsIwFADhfU4x1AOIWv8a8BBuQxYhedIiJuU14EI8exTdDB@jktpVkvNGQ07lsV5EErk8Wx34L7dlR8@eA0dO/lZUQhyJL9gYLNZYzt/@CPbtZp0yMtVRlMhl1Q2dq@EuVO@i9619AA "Red – Try It Online")
[Answer]
## SAS, 160 Bytes
```
data;array j[9](1:9);do i=1to 1e4;l=int(2+7*ranuni(0));m=int(2+7*ranuni(0));n=j[l];j[l]=j[m];j[m]=n;end;put+2j[1]/+1j[2]j[3]/j[4]j[9]j[5]/+1j[6]j[7]/+2j[8];run;
```
Ungolfed:
```
data _null_;
array j[9] (1:9); **Define and populate an array;
do i = 1 to 1e4; **Iterate ten thousand times;
l=int(2+7*ranuni(0)); **make a random int;
m=int(2+7*ranuni(0)); **make another random int;
n=j[l]; **save num in first slot;
j[l]=j[m]; **swap second to first slot;
j[m]=n; **swap original first to second slot;
end;
put +2j[1]/+1j[2]j[3]/j[4]j[9]j[5]/+1j[6]j[7]/+2j[8];
**outputs the string, / is linebreak, +# is shift over, always adds one space;
run;
```
If I wanted to do it a bit "better" but longer, I would use rand("integer",2,8);, as that is a better random number distribution, but 1 char longer each line...
I'm pretty sure PROC IML would be much smaller, as that would be more similar to the R/Python implementation. Base SAS has tools to sort rows randomly, but not columns/variables. I figure doing 10,000 random swaps is sufficiently randomized here (probably as random as any of the other implementations, anyway); could easily do 1 billion random swaps for no more characters, but 10k seems enough.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 62 bytes
```
2345678(~z%|&(~z%|')&^) ,,1.
, ,. ,.
,. ,9. ,.
, ,. ,.
, ,,.
```
[Try it online!](https://tio.run/##y05N///fyNjE1MzcQqOuSrVGDUyqa6rFaSoo6OgY6nHpKOjoAREXiLSEsGAiIBV6//8DAA "Keg – Try It Online")
Remove the `z%`' s for -4 bytes but a *really long* execution time.
This:
* Pushes the numbers 2-8 onto the stack.
* Shuffles everything in a very interesting way.
* Prints out the required shape.
[Answer]
# APL, 37 chars/bytes
```
2⌽t⌽↑⍕¨((t←1 2 3 2 1)/⍳5)⊆1,5⌽9,1+?⍨7
```
permutation of numbers from 2 to 8
```
1+?⍨7
```
add leading 9, shift 5 positions to the left, add leading 1
```
1,5⌽9,
```
replicate numbers from 1 to 5, 1-2-3-2-1 times respectively
```
(t←1 2 3 2 1)/⍳5
```
make 5 nested vectors of length 1-2-3-2-1 respectively
```
((t←1 2 3 2 1)/⍳5)⊆
```
transform numerical arrays into char vectors
```
⍕¨
```
nested vectors into matrix
```
↑
```
shift each line 1-2-3-2-1 positions to the left respectively, and then 2 more for every line
```
2⌽t⌽
```
[Answer]
# PHP, ~~83~~ 81 bytes
*83 bytes*
```
<?=($l=range(2,8))&&shuffle($l)?vsprintf(" 1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l):0;
```
[Try it online!](https://tio.run/##K8go@P/fxt5WQyXHtigxLz1Vw0jHQlNTTa04ozQtLScVKK5pX1ZcUJSZV5KmoaSgYBiTp6CaomqUEpOnmqJgCWQDGUZQAeMUJR2gBisD6///AQ)
---
*81 bytes*
Splitting code into 2 fragments to save 2 characters. Thanks for the comment [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork).
```
<?$l=range(2,8);shuffle($l)?><?=vsprintf(" 1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l);
```
[Try it online!](https://tio.run/##LctBCsMgEEDRq0iIYCBdxG5aEutFAiGgxoCMg056/E5cdPf48DEi82L7ZMoOh1d6fA1zjVcIyas@DfazWPOtWE6goDohphWEdFK7FaQT7@YG/Q9P141tmpl/GenMUPnhRI250JbRw0b7Yahc/gY)
[Answer]
# C (GCC) ~~161~~ 158 bytes
-3 bytes from ceilingcat
```
#define B,b[i++]
b[]=L"";main(a,t,i){srand(time(0));for(i=b;--i;b[a]=t)*b=b[a=rand(t=*b)%7];printf(" 1\n %d %d\n%d 9 %d\n %d %d\n %d"B B B B B B B);}
```
`L""` has non-printing characters that I can't get to show in SE is equivalent to `{2,3,4,5,6,7,8}`
this code makes the assumption that the address of `b` is at least 14 in order to guarantee all results are possible
[Try it online!](https://tio.run/##TYrNCgIhHMShb/YpxFjQXYU6RYiXPfcGrgddNf6HtTBv0bObFEHMMPNjmIlfp6mUvfMBokcDswr6XjdWaXnBi@VqvdnusJgNRGJYZkCfj2SiIxlmTw6UinBLBKQVnIOwymiZaWdlJfn9yc7S9qTFPUHMgWCEjmNEraseY63zB34DqokH9CcqXqW8AQ "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~42~~ 32 bytes
```
` 1
% %
% 9 %
% %
%`7ɾ1+Ṗ℅%
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%20%201%0A%20%25%20%25%0A%25%209%20%25%0A%20%25%20%25%0A%20%20%25%607%C9%BE1%2B%E1%B9%96%E2%84%85%25&inputs=&header=&footer=)
-10 thanks to lyxal.
[Answer]
# Java 10, ~~140~~ 139 bytes
```
v->{var r=" 1\n x x\nx 9 x\n x x\n x";for(int d=9,m=3;m<511;r=r.replaceFirst("x",d+""))for(;m==(m|=1<<(d*=Math.random()));d=9);return r;}
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/197681/52210), so make sure to upvote him as well!
[Try it online.](https://tio.run/##dZA9T8MwEIb3/opXnmxoIiLUoXLcka1dkFgog0lScLGd6OJEQSW/PThNGVnudN/Pe2fd6@Rcfk2F1W2LvTb@sgKMDxWddFHhMIfAcyDjP1Dwl9qU6IWM2XEVTRt0MAUO8FBTn@wuvSaQYkB29BgwHP2A7eyWABiYPNXE4wmUart26lG6fJNlkhSlVDU2nn0y1AbOBrYu7xkTYh6QTinuflSW57y8U3sdPlPSvqwdF0LIuEtIqkJHHiTHSc50TfduI90Nsp/ZXZTIFzmvb9Bi0fdHZNRGwiTJ7kHiVoriv9tQubTuQtrEuWA992nBfWetuH7in6Zbbbz@apx@AQ)
**Explanation:**
```
v->{ // Method with empty unused parameter and String return-type
var r=" 1\n x x\nx 9 x\n x x\n x";
// Result-String, starting at:
// " 1
// x x
// x 9 x
// x x
// x"
for(int d=9, // Temp integer for the random digit, starting at 9
m=3; // Bit-mask `m`, starting at 3 (binary 000000011)
m<511 // Loop as long as `m` is not 511 yet (binary 111111111):
; // After every iteration:
r=r.replaceFirst("x",d+""))
// Replace the first "x" with digit `d`
for(;m== // Inner loop as long as `m` is unchanged after
(m|= // `m` is bitwise-ORed with:
1<< // 2 to the power
(d*=Math.random()));
// a random digit in the range [0,9)
d=9); // After every iteration: reset `d` to 9 again
return r;} // And finally return the result-String
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 139 bytes
```
char a[7],c;r(){for(srand(time(0));c=rand()%7,a[c]++;);c+=2;}f(){printf(" 1\n %d %d\n%d 9 %d\n %d %d\n %d",r(),r(),r(),r(),r(),r(),r());}
```
Generates a random number 0-6, tests if that number has been generated before, and if not, prints it.
[Try it online!](https://tio.run/##lY3BCoMwDIbvPkUoCAk62HaREXwS66HEdevBKtXtIj57F4Qdd1hI/iQfJL@cHiI5y9MlcF3T18IJafNTwiW5OOAaxjueiVjaY6eyqV0nfVWxsqq98u71YE4hrh4NwMVGKAdNG7XdjuELQNXUavCriPesj2B0IeJ7CgMVWwEa6sEwv9YFjY2G@A@45w8 "C (gcc) – Try It Online")
] |
[Question]
[
*I need to stop thinking of punny names*
Your task is to create as many snippets (programs that have input and output built-in), functions or full programs as possible that sorts whatever your language's version of integer arrays is in ascending order, but for each program, you're only allowed to use the characters in ASCII (or your language's code page, if it's directly specified as not ASCII) which haven't been used in the previous programs.
This is an example answer (separate programs separated by newlines):
```
Derp
ASdFGHJKLAAA
qwEEERtyRty
```
In this (fictional language), my first answer is `Derp`, which used up `D`, `e`, `r` and `p`. In the second program, I'm not allowed to use those character again, but I can reuse as many characters I want. Same with the third program, and so on.
Each program must take an array of integers, so something like this (see input/output examples for valid input/output styles):
```
[3 4 -2 5 7 196 -44 -2]
```
And it must output the items in the array as an array, in ascending order:
```
[-44 -2 -2 3 4 5 7 196]
```
**Your score will be the total amount of submissions. If there is a tie, the lowest bytecount (least amount of bytes in your code) wins!**
## Rules for programs:
* All submissions must run correctly in one language version (so `Python 2 != Python 3`).
* Your submissions can be snippets, functions, or full programs. You're even allowed to mix and match them - however, you must say which is which, and provide links to working submissions.
* Please provide online links to all solutions, if possible.
* All submissions must take an array (or a string delimited with any character) as input, and output the array sorted (in your language's array form or as a `{any character}`-delimited string.
* You are not allowed to use any characters outside of ASCII (or your language's code page).
For example, these are valid inputs/outputs:
```
[1 2 3 4] (Clojure style arrays)
[1, 2, 3, 4] (Python style arrays)
1 2 3 4 5 (Space-delimited - separated by spaces)
1#2#3#4#5 ("#"-delimited - separated by "#" characters)
1\n2\n3\n4\n (newline-delimited)
```
## Specs for input:
* You are guaranteed that the array contains only integers. However, there may be negative numbers, and numbers may repeat indefinitely.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 programs, 65 bytes
```
·π¢
¬π√û
Ụị
Œ!Ṃ
7778Ọv
Ẋ>2\S$¿
ĠFḣṪ¥@€
~Ṁ~rṀxLœ&
C»/ð+ÆNPÆfÆC_ḷ
<þḅ1‘WiþJḄ³ṫZḢ
```
There's some inevitable overlap with [@Lynn's Jelly answer](https://codegolf.stackexchange.com/a/113067/12012). Credits for the bogosort idea go to her.
[Try it online!](https://tio.run/nexus/jelly#Aa4AUf//4bmiCsK5w54K4buk4buLCsWSIeG5ggo3Nzc44buMdgrhuoo@MlxTJMK/CsSgRuG4o@G5qsKlQOKCrAp@4bmAfnLhuYB4TMWTJgpDwrsvw7Arw4ZOUMOGZsOGQ1/huLcKPMO@4biFMeKAmFdpw75K4biEwrPhuata4bii/zEwUuKBuOG5m8S/w5DigqxH//9bMywgNCwgLTIsIDUsIDcsIDE5NiwgLTQ0LCAtMl0 "Jelly – TIO Nexus") or [verify uniqueness](https://tio.run/nexus/jelly#AX4Agf//4bu0UeKCrEbhuaLFknJH////4bmiCsK5w54K4buk4buLCsWSIeG5ggo3Nzc44buMdgrhuoo@MlxTJMK/Cn7huYB@cuG5gHhMxZMmCkPCuy/DsCvDhk5Qw4Zmw4ZDX@G4two8w77huIUx4oCYV2nDvkrhuITCs@G5q1rhuKI "Jelly – TIO Nexus").
### How they work
```
·π¢ Main link. Argument: A (array)
·π¢ Sort A.
```
```
¬π√û Main link. Argument: A (array)
¬π√û Sort A, using the identity function as the key.
```
```
Ụị Main link. Argument: A (array)
Ụ Grade up; yield all indices of A, sorted by their corr. values.
ị Index into A.
```
```
Œ!Ṃ Main link. Argument: A (array)
Œ! Yield all permutations of A.
Ṃ Minimum; yield the lexicographically smallest permutation.
```
```
7778Ọv Main link. Argument: A (array)
7778Ọ Unordinal; yield chr(7778) = 'Ṣ'.
v Evaluate with argument A.
```
```
Ẋ>2\S$¿ Main link. Argument: A (array)
¬ø While the condition it truthy, execute the body.
>2\S$ Condition:
$ Combine the two links to the left into a monadic chain.
>2\ Perform pairwise greater-than comparison.
S Sum; add the results.
This returns 0 iff A contains an unsorted pair of integers.
Ẋ Body: Shuffle A.
```
```
ĠFḣṪ¥@€ Main link. Argument: A (array)
Ġ Group the indices of A by their sorted values.
F Flatten the result.
€ Apply the link to the left to each index in the previous result,
calling it with the index as left argument and A as the right one.
¥@ Combine the two links to the left into a dyadic chain and swap
its arguments, so A is left one and the index i is the right one.
·∏£ Head; take the first i elements of A.
·π™ Tail; yield the last of the first i, i.e., the i-th element of A.
```
```
~Ṁ~rṀxLœ& Main link. Argument: A (array)
~ Take the bitwise NOT of all integers in A.
Ṁ Take the maximum.
~ Take the bitwise NOT of the maximum, yielding the minimum of A.
Ṁ Yield the maximum of A.
r Range; yield [min(A), ... max(A)].
L Yield the length of A.
x Repeat each integer in the range len(A) times.
œ& Take the multiset-intersection of the result and A.
```
```
C»/ð+ÆNPÆfÆC_ḷ Main link. Argument: A (array)
C Complement; map (x -> 1-x) over A.
»/ Reduce by dyadic maximum, yielding 1-min(A).
√∞ Begin a new, dyadic chain. Arguments: 1-min(A), A
+ Add 1-min(A) to all elements of A, making them strictly positive.
ÆN For each element n of the result, yield the n-th prime number.
P Take the product.
Æf Factorize the product into prime numbers, with repetition.
ÆC Prime count; count the number of primes less than or equal to p,
for each prime p in the resulting factorization.
·∏∑ Yield the left argument, 1-min(A).
_ Subtract 1-min(A) from each prime count in the result to the left.
```
```
<þḅ1‘WiþJḄ³ṫZḢ Main link. Argument: A (array)
<þ Construct the less-than matrix of all pairs of elements in A.
·∏Ö1 Convert each row from base 1 to integer (sum each).
‘ Increment. The integer at index i now counts how many elements
of A are less than or equal to the i-th.
W Wrap the resulting 1D array into an array.
J Yield the indices of A, i.e., [1, ..., len(A)].
iþ Construct the index table; for each array T in the singleton array
to the left and index j to the right, find the index of j in T.
This yields an array of singleton arrays.
Ḅ Unbinary; convert each singleton from base 2 to integer, mapping
([x]-> x) over the array.
³ Yield A.
ṫ Tail; for each integer i in the result of `Ḅ`, create a copy of A
without its first i-1 elements.
Z Zip/transpose. The first column becomes the first row.
·∏¢ Head; yield the first row.
```
[Answer]
# Jelly, 8 programs
```
·π¢ Built-in sort.
¬π√û Sort-by the identity function.
Ụị Sort indices by values, then index into list.
Œ!Ṃ Smallest permutation.
7778Ọv Eval Unicode 7778 (Ṣ).
ẊI>@-.S$$¿ Bogosort.
<;0œṡ0⁸ṁjµ/ Insertion sort.
AṀ‘¶+Ç©ṬT_©®³ċЀ®x' A terrifying hack.
```
The last program is really annoying…
```
AṀ‘¶+Ç© Add ® = abs(max(L)) + 1 to the entire list.
Now it’s offset to be entirely positive.
·π¨ Create a binary array with 1s at these indices.
T Find the indices of 1s in this array.
The result is sorted, but offset wrong, and lacks duplicates.
_©® Subtract the offset, saving this list to ®.
Now restore the duplicates:
³ċЀ Count occurences in the original list.
®x' Repeat the elements of ® that many times.
```
If I can remove the `œṡ` from `<;0œṡ0⁸ṁjµ/`, there’s also this weird one: `²SNr²ZFœ&`. Help is appreciated.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), score = 6
**05AB1E** uses [CP-1252](http://www.cp1252.com/) encoding.
Thanks to *Kevin Cruijssen* for program 4.
Thanks to *Riley* for inspiration to program 6.
**Program 1**
```
{ # sort
```
[Try it online!](https://tio.run/nexus/05ab1e#@1/9/3@0sY6CiY6CrpGOgqmOgrmOgqGlGZBrAhaLBQA)
**Program 2**
```
`[Ž.^]¯
` # flatten input list to stack
[≈Ω ] # loop until stack is empty
.^ # add top of stack to global list in sorted order
¯ # push global list
```
[Try it online!](https://tio.run/nexus/05ab1e#@58QfXSvXlzsofX//0cb6yiY6CjoGukomOoomOsoGFqaAbkmYLFYAA)
**Program 3**
```
WrZŠŠŸvy†
Wr # get minimum value in input list and reverse stack
ZŠ # get maximum value in input list and swap move it to bottom of stack
Š # move input down 2 levels of the stack
≈∏ # create a range from max to min
v # for each y in range
y† # move any occurrence of it in the input list to the front
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9eFHV0ARDuKKt81LDg//9oYx0FEx0FXSMdBVMdBXMdBUNLMyDXBCwWCwA)
**Program 4**
```
ϧ
œ # get a list of all permutations of input
ß # pop the smallest
```
[Try it online!](https://tio.run/nexus/05ab1e#@3908uH5//9HG@somOgo6BrpKJjqKJjrKBhamgG5JmCxWAA)
**Program 5**
```
êDgFDNè¹sUXQOFXs}}\)
ê # sort with duplicates removed
Dg # duplicate and get length
F # for N in [0 ... len-1] do
DNè # duplicate and get the Nth element in the unique list
¬πs # push input and move the Nth element to top of stack
UX # save it in X
Q # compare each element in the list against the Nth unique element
O # sum
FXs} # that many times, push X and swap it down 1 level on stack
} # end outer loop
\ # remove the left over list of unique items
) # wrap stack in a list
```
[Try it online!](https://tio.run/nexus/05ab1e#@394lUu6m4vf4RWHdhaHRgT6u0UU19bGaP7/H22so2Cio6BrpKNgqqNgrqNgaGkG5JqAxWIB)
**Program 6**
```
©€Ý逤þ((®€Ý逤(þ(Rì
© # store a copy of input in register
€Ý # map range[0 ... n] over list
é # sort by length
€¤ # map get_last_element over list
þ(( # keep only non-negative numbers
# now we have all positive numbers sorted
®€Ý逤(þ( # do the same thing again on input
# except now we only keep negative numbers
R # reverse sorting for negative numbers
ì # prepend the sorted negative numbers to the positive ones
```
[Try it online!](https://tio.run/nexus/05ab1e#@39o5aOmNYfnHgZRh5Yc3qehcWgdsogGUCjo8Jr//6ONdRRMdBR0jXQUTHUUzHUUDC3NgFwTsFgsAA)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), score = ~~ 4~~  5
### Program 1 - Shuffle sort
[```
ṣ.↔:1≥₎∧|↰
```](https://tio.run/nexus/brachylog2#@/9w52K9R21TrAwfdS591NT3qGN5zaO2Df//RxvrmOjEG@mY6pjrGFqa6cSbgLix/6MA)
We shuffle and check that the reverse of the list is non-increasing. If not we retry recursively.
### Program 2 - Permutation sort
[```
p≤₁
```](https://tio.run/nexus/brachylog2#@1/wqHPJo6bG//@jjXVMdOKNdEx1zHUMLc104k1A3Nj/UQA)
Output the first permutation which is non-decreasing.
### Program 3 - Built-in
[```
o
```](https://tio.run/nexus/brachylog2#@5///3@0sY6JTryRjqmOuY6hpZlOvAmIG/s/CgA)
Order.
### Program 4 - Built-in
[```
≜ᵒ
```](https://tio.run/nexus/brachylog2#@/@oc87DrZP@/4821jHRiTfSMdUx1zG0NNOJNwFxY/9HAQA)
Order by labeling. Since the integers in the list are already fixed, this does the same as `o`.
### Program 5 - Min printing
[```
g~kKt~lg~kK{⌋M&~cṪ↺Th[M]hẉTb↺c}ⁱ⁾
```](https://tio.run/nexus/brachylog2#@59el@1dUpcDoqof9XT7qtUlP9y56lHbrpCMaN/YjIe7OkOSgLzk2keNGx817vv/P9pYx0Qn3kjHVMdcx9DSTCfeBMSN/Q8A)
Here's an explanation for this monstrosity of Nature:
```
g~kK K = [Input list, a variable]
t~lg~kK That variable is the length of the Input list
{ }ⁱ⁾ Iterate length-of-the-Input times on the Input:
‚åãM M is the min of the input
&~c·π™ ·π™ is a triplet of lists which concatenate to the input
Ṫ↺Th[M] T is Ṫ cyclically permuted once ccw; [M] is
the first element of T
hẉ Write M followed by a new line
Tb↺c Remove the first element of T (i.e. [M]), cyclically
pemute T once ccw and concatenate; this is
the input for the next iteration
```
[Answer]
# JavaScript, score ~~1~~ 2
*Doubled the score thanks to @ETHproductions who reminded me of string escapes*
### Snippet 1 (21 bytes, characters `\ ,-.=>289`Facehilnorstux`)
```
Function`return this.sort\x28\x28t,h\x29=>t-h\x29`.call
```
### Snippet 2 (9117 bytes, characters `(+)[!]`)
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(![]+[])[+!+[]]+[[]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+(+(+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+[]])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[!+[]+!+[]]+(![]+[])[+!+[]]+(+((+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+[+[]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+!+[]]])+[])[!+[]+!+[]]+(+(+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+[]])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]
```
You can test both versions in your browser's console. The first version is just a function, the second version is a snippet that needs the parentheses and argument added.
## Examples
```
< {function snippet here}([1, -44, 65, -105, 12])
> [-105, -44, 1, 12, 65]
```
## How?
The first snippet calls the sort method on the array you pass it. By default, the sort method sorts lexicographical, which is bad for integers (especially multi-digit negative numbers). As such, we have to pass it a callback in the form of an arrow function that takes two elements and subtracts the latter from the former. Depending on the resulting value, the two elements are rearranged: if it is smaller than 0, `a` will appear before `b`, if it is larger than 0, `a` will appear after `b`, and if it is 0, both elements will end up next to each other.
The second snippet is nothing more than an encoded version of the first snippet and it takes advantage of the fact that in JavaScript, `object.function()` equals `object["function"]()`. It also uses empty arrays, `!` operators and number casting to generate all kinds of strings, in which the needed characters for the function name can be found. Then the brackets are used once more to get the character at a certain index in the string, and all those characters are concatenated, resulting in the following JavaScript code:
```
[]["fill"]["constructor"]("return this.sort((a,b)=>a-b)")["call"]
```
`[]["fill"]` equals `[].fill`, whose `["constructor"]` is the `Function` object. We then call that with a string (which is to be evaluated when the function is called), which is the first function, but notice that the argument has been replaced by `this`. To set the value of `this` to the argument, we need to call a function on this function, namely `["call"]`. In conventional JavaScript, you would write this as:
```
function _() {
return this.sort((a,b)=>a-b);
}
_.call(argument);
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), score ~~3~~, 4
This was a really fun challenge! Thankfully, vim has a builtin "sort" function, otherwise this would basically be impossible. Unfortunately, it since V/vim are string based it needs an argument to sort by numeric values. So I'm calling
* Sort by numerical value `n`,
* Sort by hexadecimal value `x`, and
* Sort by floating point value `f`
Little side-note: When I write something like `<esc>` or `<C-r>`, this is a actually a single-byte. It represents unprintable characters, and since V unfortunately relies heavily on unprintable characters, this method makes everything easier. The TIO links have the `-v` flag, which makes the V interpreter read these as if they were the characters they represent.
### Program 1, 2 bytes
```
√∫n
```
[Try it online!](https://tio.run/nexus/v#@394V97//4ZcplwmRobGXGaWZuZcukaGAA)
This calls the V specific *sort* function.
### Program 2, 10 bytes
```
Qsor x
vi
```
This just calls 'sort' directly. The only interesting thing about this is that we do it from `ex` mode, which is a weird mode that emulates the text editor 'ex', V's great-great-grandfather. `vi` is a shortcut for `visual`, the command used to leave ex mode. This requires a trailing newline.
[Try it online!](https://tio.run/nexus/v#@x9YnF@kUMFVlsn1/78hlymXiZGhMZeZpZk5l66RIQA)
### Program 3, 14 bytes
```
OSOR X<esc>V~DJ:<C-r>"
```
[Try it online!](https://tio.run/nexus/v#@@8f7B@kEGGTWpxsF1bn4mVl46xbZKf0/78hlymXiZGhMZeZpZk5l66R4X/dMgA)
Alright, here is where the explanations start to get a *little* weird. If we can build up the text `sor x`, we can delete it and insert it into the current command with `<C-r><register-name>`. So we'll enter it uppercase.
```
O " Open a newline above the current line, and enter insert mode
SOR X " From insert mode, enter 'SOR X'
<esc> " Leave insert mode
V " Select this whole line
~ " And toggle the case of every selected character ('u' would also work here)
D " Delete this line (into register '"')
J " Get rid of a newline
: " Enter command-line mode
<C-r>" " Insert register '"'
" Implicitly hit enter, running the 'sor x' command
" Implicitly print the buffer
```
### Program 4, 19 bytes
```
YPC<C-v>58fbe a<C-c>g?_dd@1
```
[Try it online!](https://tio.run/nexus/v#@x8Z4GzjrFtmZ2qRlpSqkAhkJ9ul28enpDgY/v9vyGXKZWJkaMxlZmlmzqVrZPhftwwA)
And here is where the explanations start to get *very* weird. Similar to last time, we'll build the command up in normal mode so that we can use different keys.
```
YP " Create a copy of this line up one line. This is mostly so that we have a line to work with without messing with the numbers.
C " Delete this line and enter insert mode
<C-v>58 " Insert ASCII '58' (which is ':')
fbe a " Insert 'fbe a'
<C-c> " Pretty much equivalent to <esc>
g?_ " ROT13 this line. Now the line is ':sor n'
dd " Delete this whole line
@1 " And run it as if typed
```
[Answer]
# CJam, score 4
### [Program 1: Built-in](https://tio.run/nexus/cjam#K6z7r/K/4H@0oYKpgpmCkYKFgkksAA)
```
$
```
### [Program 2: Eval'ed Built-in](https://tio.run/nexus/cjam#K6z7b2yWXPe/4H@0oYKpgpmCkYKFgkksAA)
```
36c~
```
36 is the ASCII value of `$`.
### [Program 3: Permutation Sort](https://tio.run/nexus/cjam#K6z7n6poYPu/4H@0oYKpgpmCkYKFgkksAA)
```
e!0=
e! e# Find unique permutations of the input
0= e# Take the first one, which happens to be in sorted order
```
### [Program 4: Min Values](https://tio.run/nexus/cjam#K6z7H10dH68ZYx1THe8Q72BTHVOrZl2rFVdtmGtTW60ZU2tfm2Ed@7/gf7ShgqmCmYKRgoWCSSwA)
```
[{__)\;\{_@_@<{\}&;}*^{1m<}{)\}?}h;]
```
Explanation of this unearthly monstrosity:
```
[ e# Begin working in an array
{ e# Do this block while the TOS is truthy (doesn't pop)
__ e# Duplicate TOS twice (the array)
)\; e# Take the last element of the array
\ e# Swap top two elements, bringing the other array copy to the top
{ e# Reduce the array using this block
_@_@<{\}&; e# The minimum of two values (e was already used, so can't use e<)
}* e# (result is the minimum value from the array)
^ e# Bitwise XOR of last element with minimum element;
e# if the numbers are the same, result is 0, otherwise non-zero
{ e# If non-zero (i.e. last element wasn't the minimum element)
1m< e# Rotate the array 1 to the left
}{ e# Else
)\ e# Remove the last element and bring the array back to TOS
}? e# (end if)
}h e# (end do-while)
; e# Remove the empty array left behind
] e# End the array
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score = 4
**Program 1**
```
n
```
[Try it online!](https://tio.run/nexus/japt#@5/3/3@0sY6CiY6CrpGOgqmOgrmOgqGlGZBrAhaLBQA)
**Program 2**
```
ñ
```
[Try it online!](https://tio.run/nexus/japt#@3944///0cY6CiY6CrpGOgqmOgrmOgqGlmZArglYLBYA)
**Program 3**
```
s)$.sort((a,b)=>a-b
```
[Try it online!](https://tio.run/nexus/japt#@1@sqaJXnF9UoqGRqJOkaWuXqJv0/3@0sY6CiY6CrpGOgqmOgrmOgqGlGZBrAhaLBQA)
**Program 4**
```
Ov85d +110d
```
[Try it online!](https://tio.run/nexus/japt#@@9fZmGaoqBtaGiQ8v9/tLGOgomOgq6RjoKpjoK5joKhpRmQawIWiwUA)
[Answer]
# Octave, 2 points
It's hard to compete with esolangs, but here goes:
I'm impressed if someone beats this. `unique` can be used to sort values, but it will strip out the duplicates. In order to insert the duplicates you would need parentheses, and they are heavily used in the bubble-sort. You'd also need `@`, which is used too.
### Number 1:
This one is quite simple: Create an anonymous function, assigned to the variable `ans`.
```
@sort
```
Call it this way: `ans([-5, 3, 0, -2, 100])`. It doesn't work on tio, but it works on [octave-online](http://octave-online.net/).
---
### Number 2:
This is simply an implementation of bubble sort, without using the characters `@sort`. We can't make this a function, because of `o`, and we can't use `input` because of the `t`. We're therefore stuck with `eval`.
```
eval(['a=inpu',116,'("");']);i=1;k=0;
while~k,k=1;i=1;while i<numel(a),if a(i)>a(i+1),a([i+1,i]) = a([i,i+1]);k=0;
end,i++;end,end,a
```
`eval(['a=inpu',116,'("");']);` evaluates to: `a=input("");`, that we can use to enter our input vector. The rest is bubble-sorting without using `for` or `mod`. Note that this must be saved in a script and called from the GUI/CLI. You can't copy-paste it, because of `input("")` (it will use the rest of the code as input, thus fail miserably).
[Answer]
## Haskell (lambdabot), 3 functions
```
sort
vv v|vvv:vvvv<-v=vv vvvv|v==v=v
vvvv==:vvv|vvvv==vv vvvv=vvv:vvvv|v:vv<-vvvv,vvv<v=vvv:v:vv|v:vv<-vvvv=v:vv==:vvv
vv=:vvvv|v:vvv<-vvvv=vv==:v=:vvv
vv=:v=vv
v vvv=vv vvv=:vvv
fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))
```
I'm using the lambdabot environment to avoid lots of `import` statements. Even `sort` needs `import Data.List`. lambdabot imports a bunch of modules by default. Besides the missing `imports`, it's standard Haskell code according to our rules.
[Try it online!](https://tio.run/nexus/haskell#hYzBTsMwDIbveQofOCQsixgTQ1TzaYgTPMG2Q8Q0ydKaVG3mcei7FyfdYEgILFn@/X@/TXUT2wTPPnn3Sl1SNBqrGFIbD@4tBr@7mCX1cgzviWIYOuzEVIoZuGfmSpqXU8ZsSPWMKIvKGrEqTpFnjpebPg85lLL5xZlUPwhmOb6Rj/h9@MULvQpgFjCiMgpSJ9zTh/aNrikYJ1NPJsbtDySOb8x6tnXa6btbY5wWICmqj7UsObvZGP1v1Jih9hQAYRcVQNNSSHADHazndjqzC3tvH@zcPtnH7RXmv/HpFzx8Ag "Haskell – TIO Nexus").
### Function 1
```
sort
```
The library function from `Data.List`. Nothing much to say here.
### Function 2
```
vv v|vvv:vvvv<-v=vv vvvv|v==v=v
vvvv==:vvv|vvvv==vv vvvv=vvv:vvvv|v:vv<-vvvv,vvv<v=vvv:v:vv|v:vv<-vvvv=v:vv==:vvv
vv=:vvvv|v:vvv<-vvvv=vv==:v=:vvv
vv=:v=vv
v vvv=vv vvv=:vvv
```
Function `v` implements an insert-sort.
I use pattern guards to avoid `()` for parameters. Compare `vv v|vvv:vvvv<-v=...` to `vv(vvv:vvvv)=...`.
The first line, function `vv` is a helper function to create the empty list. With it I don't have to use `[]` to write literal empty lists. More readable:
```
mkEmpty list | hd:tl <- list = mkEmpty tl | otherwise = list
```
`(==:)` is insert, which inserts an element into a sorted list, so that the resulting list is still sorted. More readable:
```
list `insert` el
| list == [] = el:list
| hd:tl <- list, el<hd = el:hd:tl
| hd:tl <- list = hd : tl `insert` el
```
`(=:)` is reduce. More readable:
```
acc `reduce` list
| hd:tl <- list = (acc `insert` hd) `reduce` tl
acc `reduce` list = acc
```
And finally `v` which reduces the input list staring with `[]`:
```
sort list = [] `reduce` list
```
### Function 3
```
fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))
```
`sort` from Function 1 makes most of the list-walking functions (`fold`, `scan`, `until`) unavailable. Recursion needs `=` which is used in Function 2. The only option left is using the fixpoint combinator `fix`. I've started with
```
fix (\f x -> min x ([minimum x]++f(x\\[minimum x])))
```
which is a selection-sort. Turning it to point-free (I cannot use lambdas `\f x ->...`, because of the `-` which is used by the pattern gurads in Function 2) gives:
```
fix (ap min . ap ((++) . return . minimum) . (. ap (\\) (return . minimum)))
```
Making singleton lists out of a value with `return` is forbidden (same for `pure`), so I have to build my own function: `\x -> map (\y -> x+0*y) [1]` or point-free `flip map[1].(.(0*)).(+)`. Replacing `return` yields
```
fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 programs
### Program 1
```
S
```
This just uses the builtin function, with implicit input and display.
Try it at [MATL online](https://matl.io/?code=S&inputs=%5B3+4+-2+5+7+196+-44+-2%5D&version=19.8.0).
### Program 2
```
`GGnZrd0<a}3M
```
This keeps generating random permutations of the inputs until all consecutive differences of the result are non-negative (this is [bogosort](https://en.wikipedia.org/wiki/Bogosort), as noted by [@c.z.](https://codegolf.stackexchange.com/users/67047/c-z)). Running time is non-deterministic and its average increases very fast with input size (namely, ùí™(*n!*) for a size-*n* array with all entries different).
Try it at [MATL Online](https://matl.io/?code=%60GGnZrd0%3Ca%7D3M&inputs=%5B3+4+-2+5+7+196%5D&version=19.8.0).
### Program 3
```
t:"tt_X>_=&)]&h
```
This is a loop that computes the minimum of the array, removes all elements equal to that value, and proceds with the rest. This is done as many times as the input size. If not all entries in the input are different, some of the iterations will be useless (but harmless), because the array will have already been emptied.
Try it at [MATL online](https://matl.io/?code=t%3A%22tt_X%3E_%3D%26%29%5D%26h&inputs=%5B3+4+-2+5+7+196+-44+-2%5D&version=19.8.0).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 programs
### [Program 1](https://tio.run/nexus/pip#q7CKNrY2sdY1sja1Nrc2tDSz1jUxsTYACsT@D/ar@P//v24BAA) - builtin
Snippet; assumes list in `x`.
```
SNx
```
(`SN` for Sort Numeric)
### [Program 2](https://tio.run/nexus/pip#q7SKNrY2sdY1sja31jUxsTYAMmP/R6rY2Ma7eQb4Vgb4V/7//1@3AAA) - filter permutations
Snippet; assumes list in `y`. Very slow for inputs longer than about 7 items.
```
Y$<=_FIPMyPOy
PMy List of permutations of y
FI Filter on this lambda function:
$<=_ Fold on less-than-or-equal
(gives 1 if the permutation is sorted ascending, 0 otherwise)
Y Yank that result back into y
Filter returned a list of (one or more) permutations, so we need to
POy Pop the first one
```
### [Program 3](https://tio.run/nexus/pip#q7KKNrY2sdY1sja1Nrc2tDSz1jUxsTYACsRa/w9T8FJwjrYwVjC3UDA0Mor9//@/bgEA) - eval
Snippet; assumes list in `z`.
```
V J C[83 78 122]
C[83 78 122] Apply chr to each number; yields ["S" "N" "z"]
J Join that list into a string
V Eval
```
### [Program 4](https://tio.run/nexus/pip#TcixCsIwEADQj@mSg4bGGiveQUyHbl2cOojD3YFToR26xXx7jJvTg2dKEmw4bHfz5mjahrseYNW/@1VrAIAZ10XSItEFje5TfVQTjxNWNQbc8oEiqIpH5nHWXJ5n8mR7utCVTreBrPfkarygFLt/AQ) - MergeSort
Anonymous function; call with list as argument (like `({...} [1 2])` or `f:{...} (f [1 2])`.
```
{b:#a>o?(fa@(,#a/2))lc:#a>o?(fa@(#a/2,()))aa:lWb{Wb@0>c@0|b@0Qc@0{aAE:c@0c@>:o}t:bb:cc:t}aALc}
```
Ungolfed:
```
{
; If more than one element in a, b gets result of recursion with first half
; else b gets l (empty list)
b: #a>o ? (f a@(,#a/2)) l
; If more than one element in a, c gets result of recursion with second half
; else c gets a
c: #a>o ? (f a@(#a/2,())) a
; Now we merge b and c
; We'll put the results in a, which must be initialized to l (empty list)
a:l
; Loop while b is nonempty
W b {
; Loop while 0th element of c exists and is less than or equal to 0th element
; of b (note: Q is string equality)
W b@0>c@0 | b@0Qc@0 {
; Append 0th element of c to a
a AE: c@0
; Slice c from 1st element on and assign that back to c (removing 0th)
c @>: o
}
; Swap b and c
t:b
b:c
c:t
}
; When b is empty, we only need append the rest of c to a and return
aALc
}
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 2
```
|sort
```
[Try it online!](https://tio.run/nexus/powershell#@2@sY6Kja6RjqmOuY2hppqNrAuLWFOcXlfz/DwA "PowerShell – TIO Nexus")
This is a snippet that runs in (e.g.) PowerShell's equivalent of a REPL. The TIO link shows usage. The `sort` is an alias for the `Sort-Object` cmdlet.
---
```
PARAM($A)[ARRAY]::SORT($A);$A
```
[Try it online!](https://tio.run/nexus/powershell#@x/gGOToq6HiqBntGBTkGBlrZRXsHxQCErBWcfz//7@GsY6Jjq6RjqmOuY6hpZmOrgmIqwkA "PowerShell – TIO Nexus")
PowerShell commands are case-insensitive, so we can use `sort` for one and `SORT` for the other. This takes an input array, sorts it in-place, and then outputs it.
[Answer]
# Ruby, 2 programs
First - the straightforward:
```
->t{t.sort}
```
Second - the tricky part:
```
def w(g)
eval ""<<103<<46<<115<<111<<114<<116
end
```
[Answer]
# J
**Program one: 3 bytes**
```
/:~
```
as in `/:~ 3,1,2,1` outputs `1 1 2 3`
[Try it online!](https://tio.run/nexus/j#@///v75VnYKxjpGOoY7J17x83eTE5IxUAA "J – TIO Nexus")
NOTE in J, negative numbers are preceded by \_ not - so you can try 4,\_10,56,\_333 etc.
**Program two: 5 bytes**
```
|.\:~
```
[Answer]
# PHP 7, 2 programs
Both programs can be golfed more.
### Program 1, 254 bytes, characters `! "$&+.01:;=>?[]adeginoprtv`
```
$a=$argv;0 .$a[1+1]?$i=$n=$d=0:print$a[1]and die;g:$r=0 .$a[++$i+1];$i=!$r?1:$i;$n=!$r?$n+1:$n;$v=$i+1;$d=$v>$d?$v:$d;$n>$d?print$a[$d]and die:0;$e=$d>$n&&$a[$i]>$a[$v];$t=$a[$i];$a[$i]=$e?$a[$v]:$a[$i];$a[$v]=$e?$t:$a[$v];$n==$d?print"$a[$i] ":0;goto g;
```
Bubble sort. Uses `goto` to create a loop as built-in loops require `()`.
### Program 2, 155 bytes, characters `#%'(),-67ACEFINORTUYZ^_{|}~`
```
IF(CREATE_FUNCTION('','NEFTIEZIENAECCERCTZIENA~N~UEEFECTZIENAUERTEF~CFACTY~YRZIENAUE'^')))6()~(7)7~6-677|~(7)7%~#|~6)77|~(7)7|~77-)^))(-|~^~~~(7)7|~')()){}
```
`IF(...){}` avoids usage of `;`. The main code is encoded with XOR, because `$` has been already used in the previous program. The code:
```
global$argv;unset($argv[0]);sort($argv);echo join(' ',$argv);
```
] |
[Question]
[
Let's try to golf this piece of ascii-art representing a golfing man:
```
'\ . . |>18>>
\ . ' . |
O>> . 'o |
\ . |
/\ . |
/ / .' |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Source: JGS - <http://www.retrojunkie.com/asciiart/sports/golf.htm>
**Rules:**
* No input allowed
* No external resources allowed
* The output must be exactly this text, displayed in a monospace font (OS console, JS console, HTML <pre> tag, ...), including the leading and trailing line-break.
* Surrounding quotes or double-quotes are allowed (the JS console adds double quotes when you output a string, this is okay)
The best answer will be the one using the less **characters** in any language.
Have fun!
[Answer]
## Ruby, 107
I thought I'd actually try to "generate" the image in code (instead of using some existing compression function):
```
S=?\s*351+?^*60
"‚†ÄÈ∞áóÄàΆúΆüüÄ∏Ô†πÏê∫ÓĪԆºÔ†Ω‚†æóÅáΰñȱ†Î°¢üÅ∂‚°∑ì±øÔ¢ÄÔ¢Å΢ãÈ≤ùõ≤ûüÇØ‚¢∞óÇπΣÅüÉ®‚£©Î≥≤óÉ≥Σ∏üÑ°‚§¢Î¥™Î¥¨Î§ØÈ¥∞üÖö‚•õö•ùôµûúµüòÖß".chars{|q|S[511&r=q.ord]=(r>>10).chr}
puts S
```
There are some non-printable characters in that array literal.
Here is the hex view of the file, to show the non-printable characters, too:
```
0000000: 533d 3f5c 732a 3335 312b 3f5e 2a36 300a S=?\s*351+?^*60.
0000010: 22e2 a080 e9b0 87f0 9780 88eb a09c eba0 "...............
0000020: 9ff0 9f80 b8ef a0b9 ec90 baee 80bb efa0 ................
0000030: bcef a0bd e2a0 bef0 9781 87eb a196 e9b1 ................
0000040: a0eb a1a2 f09f 81b6 e2a1 b7f0 93b1 bfef ................
0000050: a280 efa2 81eb a28b e9b2 9df0 9bb2 9ef0 ................
0000060: 9f82 afe2 a2b0 f097 82b9 eba3 81f0 9f83 ................
0000070: a8e2 a3a9 ebb3 b2f0 9783 b3eb a3b8 f09f ................
0000080: 84a1 e2a4 a2eb b4aa ebb4 aceb a4af e9b4 ................
0000090: b0f0 9f85 9ae2 a59b f09a a59d f099 b59e ................
00000a0: f09c b59f f098 85a7 222e 6368 6172 737b ........".chars{
00000b0: 7c71 7c53 5b35 3131 2672 3d71 2e6f 7264 |q|S[511&r=q.ord
00000c0: 5d3d 2872 3e3e 3130 292e 6368 727d 0a70 ]=(r>>10).chr}.p
00000d0: 7574 7320 53 uts S
```
Thanks to Ventero for some major improvements! (He basically reduced the code by 50%.)
[Answer]
# CJam, 62 characters
```
"·Ç†ÏßÄÂ∞¶Î†íÓåü>√ьćæÄ„∏Ä‚°ÖÏáãËíß ∏ÈøÄ ÉϺÄÔ†ÉÓÑ´Ë¢ß∆ºËüÄ ÑÂ∞éΧ∑ÏÄÇËêØ≈∞‚ã•·ºÄ‡®éÎ∞äÔÅãËÄßÂè∞¬†‚¢ô‚ø∂Íùç„ïüÂä¢ÌñüÈ®§ÔûõÍ©èËÑΩÓö¨Âïé"2G#b128b:c~
```
[Try it online.](http://cjam.aditsu.net/#code=%22%01%E1%82%A0%EC%A7%80%E5%B0%A6%EB%A0%92%EE%8C%9F%3E%C3%84%CE%80%E0%BE%80%E3%B8%80%E2%A1%85%EC%87%8B%E8%92%A7%CA%B8%E9%BF%80%CA%83%EC%BC%80%EF%A0%83%EE%84%AB%E8%A2%A7%C6%BC%E8%9F%80%CA%84%E5%B0%8E%EB%A4%B7%EC%80%82%E8%90%AF%C5%B0%E2%8B%A5%E1%BC%80%E0%A8%8E%EB%B0%8A%EF%81%8B%E8%80%A7%E5%8F%B0%C2%A0%E2%A2%99%E2%BF%B6%EA%9D%8D%E3%95%9F%E5%8A%A2%ED%96%9F%E9%A8%A4%EF%9E%9B%EA%A9%8F%E8%84%BD%EE%9A%AC%E5%95%8E%222G%23b128b%3Ac~ "CJam interpreter")
### Test run
```
$ base64 -d > golf.cjam <<< IgHhgqDsp4DlsKbroJLujJ8+w4TOgOC+gOO4gOKhheyHi+iSp8q46b+AyoPsvIDvoIPuhKvooqfGvOifgMqE5bCO66S37ICC6JCvxbDii6XhvIDgqI7rsIrvgYvogKflj7DCoOKimeK/tuqdjeOVn+WKou2Wn+mopO+em+qpj+iEve6arOWVjiIyRyNiMTI4Yjpjfg==
$ wc -m golf.cjam
62 golf.cjam
$ cjam golf.cjam
'\ . . |>18>>
\ . ' . |
O>> . 'o |
\ . |
/\ . |
/ / .' |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$
```
### How it works
`2G#b` converts the preceding string into an integer by considering it a base-65536 number.
`128b:c` converts that integer back to a string (**110 bytes**) by considering it a base-128 number, which `~` then executes:
```
"
^F'^@\^S.^B.^X|^@>^@1^@8^@>^@>^@
^H\^N.^I'^A.^S|^@
^GO^@>^@>^I.^Q'^@o^P|^@
^H\^G.&|^@
^H/^@\^D.(|^@
^G/^A/^B.^@')|^@
^A"2/{)iS*}%"jgs"'^7*'`'^51*N
```
*(caret notation)*
```
2/{)iS*}%
```
splits the string into pairs of two characters and does the following for each pair: Pop the second character of the string, convert it into an integer and repeat the string `" "` that many times.
For example, `".("` becomes `". "`, because the ASCII character code of `(` is 40.
Finally,
```
"jgs"'^7*'`'^51*N
```
pushes the string `"jgs"`, the character `^` repeated 7 times, the character ```, the character `^` repeated 51 times and a linefeed.
[Answer]
# bash + iconv + DosBox/x86 machine code (~~104~~ ~~97~~ ~~96~~ 95 characters)
```
echo ‚ÜæÍ∞ÅÏäàÏÇ®‡©Ω‚Ç≤…ªÂ∫≤ÓÇÉÈåø ¥‚áçÁΩãÍ≥πÏÇÑÓ뵇´ÉËòäÂ∞ß‚∫ì‚∫ÇÁ≤ò„Ñæ„∏∏‡®æÂ≤à‚∫é‚ûâ‚∏†Á≤ìËúä„πè˧æÈÑÆʺßÁ≤êˆäËùúÍòƇ©º‚æàËëú͆Ƈ©º‚æႺ†‚∫Çͧ߇©ºÊ®†ÁçßÊÉᇴ≥|iconv -futf8 -tucs2>o.com;dosbox o*
```
I suggest to put this in a script in an empty directory, it's almost guaranteed that copy-pasting it in a terminal will break everything; even better, you can grab the script [here](https://bitbucket.org/mitalia/pcg/downloads/launcher.sh) ready-made.
Expected output: ![expected output](https://i.stack.imgur.com/6K8qH.png)
## How it works
The bash part is just a launcher that uses `iconv` to "decompress" a `.com` file from the UTF-8 characters of the script and launches it with DosBox.
Notice that this poses some limitation on the content, as not all the input sequences can be interpreted as UCS-2 with `iconv` not complaining; for example, for some reason many operations involving the `bx` register broke havoc depending on the place where I used them, so I had to work around this problem several times.
Now, the Unicode thing is just to take advantage of the "character count" rules; the actual size (in bytes) of the script is way larger than the original `.COM` file.
The extracted `.com` file is
```
00000000 be 21 01 ac 88 c2 a8 c0 7d 0a b2 20 7b 02 b2 5e |.!......}.. {..^|
00000010 83 e0 3f 93 b4 02 cd 21 4b 7f f9 ac 84 c0 75 e4 |..?....!K.....u.|
00000020 c3 0a 0a 86 27 5c 93 2e 82 2e 98 7c 3e 31 38 3e |....'\.....|>18>|
00000030 3e 0a 88 5c 8e 2e 89 27 20 2e 93 7c 0a 87 4f 3e |>..\...' ..|..O>|
00000040 3e 89 2e 91 27 6f 90 7c 0a 88 5c 87 2e a6 7c 0a |>...'o.|..\...|.|
00000050 88 2f 5c 84 2e a8 7c 0a 87 2f 20 2f 82 2e 27 a9 |./\...|../ /..'.|
00000060 7c 0a 20 6a 67 73 c7 60 f3 0a 0a 00 ||. jgs.`....|
0000006c
```
and is 108 bytes long. The NASM source for it is:
```
org 100h
start:
; si: pointer to current position in data
mov si,data
; load the character in al
lodsb
mainloop:
; bx: repetition count
; - zero at startup
; - -1 after each RLE run
; - one less than each iteration after each "literal" run
; the constant decrement is not really a problem, as print
; always does at least one print, and there aren't enough
; consecutive literal values to have wraparound
; if the high bit is not set, we have a "literal" byte;
; we prepare it in dl just in case
mov dl,al
; then check if it's not set and branch straight to print
; notice that bx=0 is fine, as print prints always at least one character
; test the top two bits (we need the 6th bit below)
test al,0xc0
; to see if the top bit was set, we interpret it as the sign bit,
; and branch if the number is positive or zero (top bit not set)
jge print
rle:
; it wasn't a literal, but a caret/space with a repetition count
; space if 6th bit not set, caret otherwise
mov dl,' '
; exploit the parity bit to see if the 6th bit was set
jnp nocaret
mov dl,'^'
nocaret:
; lower 6 bits: repetition count
; and away the top bits and move in bx
; we and ax and not al because we have to get rid of the 02h in ah
and ax,3fh
xchg ax,bx
print:
; print bx times
mov ah,2
int 21h
dec bx
jg print
; read next character
lodsb
test al,al
; rinse & repeat unless we got a zero
jnz mainloop
end:
ret
data:
; here be data
incbin "compressed.dat"
; NUL terminator
db 0
```
All this is just a decompresser for `compressed.dat` whose format is as follows:
* if the high bit is not set, print the character as-is;
* otherwise, the low 6 bits are the repetition count, and the second-highest bit specifies if it has to print a space (bit not set) or a caret (bit set).
`compressed.dat` in turn is generated using a [Python script](https://bitbucket.org/mitalia/pcg/src/master/golf/compress.py) from the original text.
The whole thing can be found [here](https://bitbucket.org/mitalia/pcg/src/master/golf/).
[Answer]
## Python, 156
```
print'''
%6s'\%19s. .%24s|>18>>
%8s\%14s.%9s' .%19s|
%7sO>>%9s.%17s'o%16s|
%8s\%7s.%38s|
%8s/\%4s.%40s|
%7s/ / .'%41s|
jgs'''%(('',)*19)+'^'*7+'`'+'^'*51
```
This uses string formatting with space padding for some basic compression.
[Answer]
# PHP, 147
This runs on the command line and outputs directly to the console:
```
php -r 'echo gzinflate(base64_decode("41IAA/UYBUygB0bYQY2doYWdHReMG4OhEwrUsRpRA9Pob2eHRRNccz5OjXAbcboQl0b9GBK0IWnUB0IFPXUFEjRmpRfHQUBCHOmAiwsA"));'
```
[Answer]
# Perl - 127 ~~129~~ ~~130~~ ~~132~~ ~~135~~ ~~137~~ ~~145~~
```
print q(
6'\19.2.24|>18>>
8\14.9'1.19|
7O>>9.17'o16|
8\7.38|
8/\4.40|
7/1/2.'41|
1jgs^^^^^^^`0
)=~s/\d++(?!>)/$"x$&||'^'x51/reg
```
Thanks to **Ventero** and **m.buettner** for their help in my RegEx optimization.
[Answer]
## GCC C - 203 bytes
I figured I'd have some fun with this one. This compiles on my version of MinGW and outputs the expected text.
Whitespace added for clarity.
```
char*v="\n ú'\\ í. . è|>18>>\n ø\\ ò. ÷' . í|\n ùO>> ÷. ï'o ð|\n ø\\ ù. Ú|\n ø/\\ ü. Ø|\n ù/ / .' ×|\n jgs^ù`^Í\n";
main(g,o,l){
for(;*v;
g=!g&*v<0&l?-*v++:g){
v+=!(l=*v-35);
putchar((g-=g>0)?o:(o=*v++));
}
}
```
None of the online code pasting sites allow the use of single byte characters outside the ASCII range, so I had to escape them for an uploaded example. It's otherwise identical though. <http://codepad.org/nQrxTBlX>
You can always verify it with your own compiler, too.
[Answer]
# LOLCODE, 590 characters
Cuz LOLCODE iz perfik language 4 golfin: iz easy 2 compres an obfuscate an it isnt verbose at all.
```
HAI
HOW DUZ I D C T
I HAZ A O
I HAZ A N ITZ 0
IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN T
O R SMOOSH O AN C MKAY
IM OUTTA YR LOOP
FOUND YR O
IF U SAY SO
VISIBLE ""
VISIBLE SMOOSH " '\" AN D " " 19 AN ". ." AN D " " 24 AN "|>18>>" MKAY
VISIBLE " \ . ' . |"
VISIBLE " O>> . 'o |"
VISIBLE SMOOSH " \ ." AN D " " 38 AN "|" MKAY
VISIBLE SMOOSH " /\ ." AN D " " 40 AN "|" MKAY
VISIBLE SMOOSH " / / .'" AN D " " 41 AN "|" MKAY
VISIBLE SMOOSH "jgs^^^^^^^`" AN D "^" 51 MKAY
VISIBLE ""
KTHXBYE
```
Im pritee sure dis werkz, but I doan has an LOLCODE interpretr an <http://repl.it>'s seems 2 not liek funcshuns.
(Tranzlashun generously providd by <http://speaklolcat.com>'s robots cuz I doan speek lolcat)
---
Indented, spaced, and commented version of the code (LOLCODE comments start with BTW):
```
HAI BTW All LOLCODE programs start with HAI
HOW DUZ I D C T BTW Function declarations follow the form "HOW DUZ I <func-name>[ <func-arg1>[ <func arg2>[ ...]]]". In this case, D is a function that repeats a YARN C (YARN is the equivalent of string in LOLCODE) NUMBR T (NUMBR = int) times.
I HAZ A O BTW Variable declarations follow the form "I HAZ A <var-name>"
I HAZ A N ITZ 0 BTW Variables can be intialised when declared by appending " ITZ <init-value>" to the declaration
IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN T BTW Loops follow the form "IM IN YR LOOP <action> TIL <condition>" where action and condition are "UPPIN YR N" and "BOTH SAEM N AN T", respectively, in this case
O R SMOOSH O AN C MKAY BTW "R" assigns a new value to a variable. YARN (string) concatenation follows the form "SMOOSH <str-1> AN <str-2>[ AN <str-3>[...]] MKAY"
IM OUTTA YR LOOP BTW "IM OUTTA YR LOOP" ends LOLCODE loops
FOUND YR O BTW "FOUND YR <value>" returns a value
IF U SAY SO BTW "IF U SAY SO" ends functions
VISIBLE "" BTW "VISIBLE" prints its argument to stdout
VISIBLE SMOOSH " '\" AN D " " 19 AN ". ." AN D " " 24 AN "|>18>>" MKAY BTW The function I wrote above only "pays off" in terms of characters added/saved when repeating 19 or more characters (the function call itself takes 8 characters, assuming a one-character first argument and a 2-digit second one; you need to factor in the added quotes (2 characters), spaces (4) and ANs (4) for 18 total extra characters; and possible SMOOSH/MKAY)
VISIBLE " \ . ' . |"
VISIBLE " O>> . 'o |"
VISIBLE SMOOSH " \ ." AN D " " 38 AN "|" MKAY
VISIBLE SMOOSH " /\ ." AN D " " 40 AN "|" MKAY
VISIBLE SMOOSH " / / .'" AN D " " 41 AN "|" MKAY
VISIBLE SMOOSH "jgs^^^^^^^`" AN D "^" 51 MKAY
VISIBLE ""
KTHXBYE BTW "KTHXSBYE" ends LOLCODE programs
```
[Answer]
# Python - ~~205~~ ~~203~~ 197
```
i="""
G^y`G^MsGgGj!G
G|!o'G.!H/!G/!M
G|!n.!J\G/!N
G|!l.!M\!N
G|!VoG'!W.!O>HO!M
G|!Y.!G'!O.!T\!N
G>H8G1G>G|!^.!H.!Y\G'!L
G""".replace('!','G ')
o=''
j=140
while j:j-=2;o+=ord(i[j+1])%70*i[j]
print o
```
The string `i` interleaves the characters in the ascii art with their multiplicites, represented as characters, all in in reverse order. In addition, I save a bit of space by using '!' instead of 'G ' in `i` and then just replacing it.
[Answer]
# Python (145)
```
'eJzjUgAB9RgFTKAHRthBjZ2hhZ0dF5SHphuhSx2rCTVQff52dlj0wPXm49IHtw+n83Do048hQRdCnz4QKuipE6sNqC8rvTgOAhLiSAdcAG/9Ri8='.decode('base64').decode('zip')
```
Not very original, I know.
[Answer]
# Javascript (*ES6*) 193 175 bytes
Edit: [Modified RegPack v3](http://jsfiddle.net/8pfLh/) to maintain newlines, use a `for in` loop to save 3 bytes, and removed eval for implicit console output.
```
_="\nx'\\w{. z~|>18>>\n~\\~x.~ 'z{yx O>>~z 'owy~\\xzwxy~/\\{zw~yx / / .'ww~ y jgs}`}}}}}}}^^\n~x }^^^^^^^{ z .wy|\nx{{w~~";for(i of "wxyz{}~")with(_.split(i))_=join(pop())
```
# Using xem's unicode compression: 133 characters
```
eval(unescape(escape('ß∞Ωò°ú´°∏ô±úßÅ∑Æ∞ÆòÅ∫Ø°ºü†±ûÄæü°ú´°æßÅúØ°∏õ°æòÄßÆ°ªÆë∏òÅèü†æØ°∫òÄß´±∑ÆëæßÅúÆÅ∫≠±∏Æëæõ±úßŪư∑Ø°πÆĆõ∞†õ∞†òÄÆô±∑≠±æòÅπòÅ™©±≥Øë†ØëΩØëΩØëΩØëûß°ú´°æÆĆòÅΩß°ûß°ûß°ûß°ªòĆòÅ∫òÄÆ≠±πØÅú´°∏Ʊª≠±æ؆¢û±¶´±≤öÅ©òÅØ©††ò°∑ÆÅπÆ°ªØëæò†©≠±©≠Å®öÅüõ°≥¨Å¨™ë¥öÅ©öê©ß∞Ω™°Ø™ëÆöÅ∞´±∞öÄ©öê†').replace(/uD./g,'')))
```
[Answer]
## ES6, 155 chars
Just trying anorher approach:
Run this in Firefox's JS console.
Each unicode character has the following form: \uD8[ascii charcode]\uDC[number of repeats].
```
"í†ÅòÄÜô∞ÅßÄÅòÄìõ†ÅòÄÇõ†ÅòÄòØÄÅü†ÅúêÅûÄÅü†Çí†ÅòÄàßÄÅòÄéõ†ÅòÄâô∞ÅòÄÅõ†ÅòÄìØÄÅí†ÅòÄá£∞Åü†ÇòÄâõ†ÅòÄëô∞Å´∞ÅòÄêØÄÅí†ÅòÄàßÄÅòÄáõ†ÅòĶØÄÅí†ÅòÄàõ∞ÅßÄÅòÄÑõ†ÅòÄ®ØÄÅí†ÅòÄáõ∞ÅòÄÅõ∞ÅòÄÇõ†Åô∞ÅòÄ©ØÄÅí†ÅòÄÅ™†Å©∞Ũ∞Å߆á®ÄÅ߆≥í†Å".replace(/../g,a=>String.fromCharCode(a[c='charCodeAt']()&255).repeat(a[c](1)&255))
```
(Unicode string made with: <http://jsfiddle.net/LeaS9/>)
[Answer]
# PHP
Method 1, simpler (139 bytes):
Using a pre-deflated string.
```
<?=gzinflate(base64_decode('41IAA/UYBUygB0bYQY2doYWdHReMG4OhEwrUsRpRA9Pob2eHRRNccz5OjXAbcboQl0b9GBK0IWnUB0IFPXUFEjRmpRfHQUBCHOmACwA='));?>
```
Method 2, encoding runs of spaces into alphabet letters (192 bytes):
```
<?=preg_replace_callback('#[D-NP-Zu]#',function($e){return str_repeat('a'<$e[0]?'^':' ',ord($e[0])-66);},"
H'\U.D.Z|>18>>
J\P.K' .U|
IO>>K.S'oR|
J\I.WS|
J/\F.ZR|
I/ /D.'ZS|
jgs^^^^^^^`u
")?>
```
[Answer]
## PowerShell, ~~192~~ ~~188~~ 119
```
-join('̠§Üঠ®Ġ®ఠü¾±¸ľРÜܠ®Ҡ§ ®ঠüΠÏľҠ®ࢠ§ïࠠüРÜΠ®ጠüР¯ÜȠ®ᐠüΠ¯ ¯Ġ®§ᒠü êçóϞà᧞'[0..70]|%{"$([char]($_%128))"*(+$_-shr7)})
```
The part above contains a few non-characters. Hex dump:
```
00: 002D 006A 006F 0069 │ 006E 0028 0027 008A -join('
10: 0320 00A7 00DC 09A0 │ 00AE 0120 00AE 0C20 ̠§Üঠ®Ġ®ఠ
20: 00FC 00BE 00B1 00B8 │ 013E 008A 0420 00DC ü¾±¸ľРÜ
30: 0720 00AE 04A0 00A7 │ 00A0 00AE 09A0 00FC ܠ®Ҡ§ ®ঠü
40: 008A 03A0 00CF 013E │ 04A0 00AE 08A0 00A7 ΠÏľҠ®ࢠ§
50: 00EF 0820 00FC 008A │ 0420 00DC 03A0 00AE ïࠠüРÜΠ®
60: 1320 00FC 008A 0420 │ 00AF 00DC 0220 00AE ጠüР¯ÜȠ®
70: 1420 00FC 008A 03A0 │ 00AF 00A0 00AF 0120 ᐠüΠ¯ ¯Ġ
80: 00AE 00A7 14A0 00FC │ 008A 00A0 00EA 00E7 ®§ᒠü êç
90: 00F3 03DE 00E0 19DE │ 0027 005B 0030 002E óϞà᧞'[0.
A0: 002E 0037 0030 005D │ 007C 0025 007B 0022 .70]|%{"
B0: 0024 0028 005B 0063 │ 0068 0061 0072 005D $([char]
C0: 0028 0024 005F 0025 │ 0031 0032 0038 0029 ($_%128)
D0: 0029 0022 002A 0028 │ 002B 0024 005F 002D )"*(+$_-
E0: 0073 0068 0072 0037 │ 0029 007D 0029 shr7)})
```
Encoding scheme is RLE with the length encoded above the lower 7 bit, which are the character to display.
[Answer]
# Python - 236
```
s=' ';print('\n'+6*s+"'\\"+19*s+'. .'+24*s+"|>18>>\n"+8*s+'\\'+14*s+'.'+9*s+"' ."+19*s+"|\n O>>"+9*s+'.'+17*s+"'o"+16*s+'|\n'+8*s+"\\ ."+38*s+'|\n'+8*s+"/\\ ."+40*s+"|\n / / ."+42*s+"|\n jgs^^^^^^^`"+51*'^'+'\n')
```
[Answer]
## JS (190b) / ES6 (146b) / ES6 packed (118chars)
Run this in the JS console:
JS:
```
"\n7'\\20.3.25|>18>>\n9\\15.10'2.20|\n8O>>10.9 9'o17|\n9\\8.39|\n9/\\5.41|\n8/2/3.'42|\n2jgs^^^^^^^`".replace(/\d+/g,function(a){return 18==a?a:Array(+a).join(' ')})+Array(51).join("^")+"\n"
```
ES6:
```
"\n6'\\19.2.24|>0>>\n8\\14.9'1.19|\n7O>>9.17'o16|\n8\\7.38|\n8/\\4.40|\n7/1/2.'41|\n1jgs58`101\n".replace(/\d+/g,a=>' ^'[a>51|0].repeat(a%51)||18)
```
ES6 packed: (<http://xem.github.io/obfuscatweet/>)
```
eval(unescape(escape('ò°ú´†∂ô±úßıûêÆú†Æú†¥ØÄæúÄæü°ú´†∏ßÅúúê¥õ†πô∞±õ†±ûëºßÅÆù±èü†æûêÆúê∑ô±Øúê∂ØÅú´†∏ßÅúù∞Æú∞∏ØÅú´†∏õ±úßÄ¥õ†¥úźßÅÆù∞ØúêØú†Æô∞¥úëºßÅÆú뙩±≥ùê∏®Ä±úıßÅÆò†Æ¨°•¨Å¨®ë£©ê®õ±ú©Ä´õ±ßõÅ°üêæô∞†ß†ß¶±°ü†µúëºúÅùõ°≤©ë∞©ë°≠Ä®®ê•ùê±öëºØıûÄ©').replace(/uD./g,'')))
```
Thanks to @nderscore!
[Answer]
## ES6, 163b / 127 chars
Yet another approach, thanks to @nderscore.
Execute it in Firefox's console
JS (163b):
```
"\n'\\..|>18>>\n\\. '.|\nO>> .'o|\n\\.&|\n/\\.(|\n//.')|\njgs<`h\n".replace(/[^'`Og\n>\\,-8j-|]/g,a=>" ^"[a=a.charCodeAt(),a>53|0].repeat(a%53))
```
Packed (127c):
```
eval(unescape(escape('ò°ú´†Üô±úßÄìõ†Çõ†òØÄæúê∏ü†æßÅÆíÅúßÄéõ†âô∞Åõ†ìØÅú´†á£∞æü†âõ†ëô±ØîźßÅÆíÅúßÄáõ†¶ØÅú´†àõ±úßÄÑõ†®ØÅú´†áõ∞Åõ∞Çõ†ßöëºßÅÆê뙩±≥üņ™Åú´†¢õ°≤©ë∞´Å°®±•öÄض±ûô±†£±ßßÅÆü°úßĨõê∏™†≠ØÅùõ±ßõÅ°üêæò††ß†¢¶±°üë°õ°£™Å°¨°É´±§©ëÅ≠Ä®öꨮêæùê≥ØÄ∞ßêƨ°•¨Å•®ë¥öÅ°ôêµú∞©öê†').replace(/uD./g,'')))
```
[Answer]
# Python, 70 UTF-16 chars
```
挣摯湩㩧呕ⵆ㘱䕂
print砧RԘꁌ䘇䇘鶍薡ᶝ谗ꚋꄝᵍᆫ〵ﺍ癶㑘㗁ࣔᆷ஧楱返䄡鈛絆吠叐嘧䠟噣煺М쐤ຑꀀ䜮'.decode(稧楬b')
```
Of course you're probably going to have to use the hex version:
```
23 63 6F 64 69 6E 67 3A 55 54 46 2D 31 36 42 45 0A 00 70 00 72 00 69 00 6E 00 74 00 27 78 9C E3 52 00 03 F5 18 05 4C A0 07 46 D8 41 8D 9D A1 85 9D 1D 17 8C 8B A6 1D A1 4D 1D AB 11 35 30 8D FE 76 76 58 34 C1 35 E7 E3 D4 08 B7 11 A7 0B 71 69 D4 8F 21 41 1B 92 46 7D 20 54 D0 53 27 56 1F 48 63 56 7A 71 1C 04 24 C4 91 0E 00 A0 2E 47 05 00 27 00 2E 00 64 00 65 00 63 00 6F 00 64 00 65 00 28 00 27 7A 6C 69 62 00 27 00 29 00
```
or the base64 version:
```
I2NvZGluZzpVVEYtMTZCRQoAcAByAGkAbgB0ACd4nONSAAP1GAVMoAdG2EGNnaGFnR0XjIumHaFNHasRNTCN/nZ2WDTBNefj1Ai3EacLcWnUjyFBG5JGfSBU0FMnVh9IY1Z6cRwEJMSRDgCgLkcFACcALgBkAGUAYwBvAGQAZQAoACd6bGliACcAKQA=
```
The first "line" of the program declares the UTF-16 encoding. The entire file is UTF16, but the Python interpreter always interprets the coding line in ASCII (it is `#coding:UTF-16BE`). After the newline, the UTF-16 text begins. It simply amounts to `print'<data>'.decode('zlib')` where the text is a deflated version of the target ASCII image. Some care was taken to ensure that the stream had no surrogates (which would ruin the decoding).
[Answer]
# C# - 354 332
```
using System;
using System.IO;
using System.IO.Compression;
class X
{
static void Main(string[] args)
{
var x= Convert.FromBase64String("41IAA/UYBUygB0bYQY2doYWdHReMG4OhEwrUsRpRA9Pob2eHRRNccz5OjXAbcboQl0b9GBK0IWnUB0IFPXUFEjRmpRfHQUBCHOmAiwsA");
Console.WriteLine(new StreamReader(new DeflateStream(new MemoryStream(x), CompressionMode.Decompress)).ReadToEnd());
}
}
```
A bit golfed:
```
using System;using System.IO;using System.IO.Compression;class X{static void Main(){var x=Convert.FromBase64String("41IAA/UYBUygB0bYQY2doYWdHReMG4OhEwrUsRpRA9Pob2eHRRNccz5OjXAbcboQl0b9GBK0IWnUB0IFPXUFEjRmpRfHQUBCHOmAiwsA");Console.WriteLine(new StreamReader(new DeflateStream(new MemoryStream(x),(CompressionMode)0)).ReadToEnd());}}
```
[Answer]
**bzip2, 116**
After seeing the CJAM answer, I figured this one should qualify too.
```
$ wc -c golf.txt.bz2
116 golf.txt.bz2
$ bzip2 -dc golf.txt.bz2
'\ . . |>18>>
\ . ' . |
O>> . 'o |
\ . |
/\ . |
/ / .' |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$
```
I doubt any further explanation is required. :)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 190 bytes
```
r(n,c){while(n--)putchar(c);}f(c){for(char*s="F'\\S.B.X|>18>>\nH\\N.I' .S|\nGO>>I.Q'oP|\nH\\G.ZL|\nH/\\D.ZN|\nG/ /B.'ZN |\n jgs^^^^^^^`";c=*s++;)c>64&&c<91&&c^79?r(c-64,32):r(1,c);r(51,94);}
```
[Try it online!](https://tio.run/##JY7BCoJAEIZfRTzobumKZZZZG0RkQljhJWSJYkgtagstOmTPbmPN4We@mYH5wMwA6rog0gD6fuWny5FI06T35wPyQ0GA@p8U853eEHDSKsfqXBciZlO2rbg94FzIhRARC3WFxZWQwYrzkG3027r6bQKWLJvOEmLGkqi5sBRryvQkUhCUc1bu/rVXfRi3ynbbp8BdR9Ng5NmYu743we@m6xjdDh0WxEZZvyA92/AcFKyvh5Mk6Ega@AI "C (gcc) – Try It Online")
[Answer]
# Vim, 99 keystrokes
```
63i^<Esc>0R jgs<C-O>7l`<Esc>O<Esc>55I <Esc>A|<Esc>Y5PA>18>><Esc>7|R'\<Down>\<Down><Left><Left>O>><Down><Left><Left>\<Down>\<Down><Left><Left><Left>/<Up>/<Down>/<Right><Right>.'<Up>.<Right><Up>.<Right><Right><Up>.<Right><Right><Right><Up>.<Right><Right><Right><Up>.<Right><Right>.<Right><Right><Down>'<Right>.<Down><Right>'o
```
probably golfable
Explanation:
```
63i^<Esc>0R jgs<C-O>7l`<Esc>
Bottom line, 63 '^'s, replace the beginning with ' jgs', then move 7 caracters to the right and replace one character with '`'
O<Esc>55I <Esc>A|<Esc>
Above current line, add one line and insert 55 spaces, then a trailing '|'
Y5PA>18>><Esc>
Copy that line and paste it above five times. Cursor ends up in topmost line. Append '>18>>'
7|R'\<Down>\<Down><Left><Left>O>><Down><Left><Left>\<Down>\<Down><Left><Left><Left>/<Up>/<Down>/<Right><Right>.'<Up>.<Right><Up>.<Right><Right><Up>.<Right><Right><Right><Up>.<Right><Right><Right><Up>.<Right><Right>.<Right><Right><Down>'<Right>.<Down><Right>'o
Go to 7th column, enter Replace-mode, and replace spaces with golfer and golf ball trail. Arrow keys are used to move around, since it uses fewer keypresses to use the arrow keys instead of <C-o>+movement for up to three keypresses.
```
] |
[Question]
[
Your challenge is to write a program that constantly prompts for input, and when input is given, output that five seconds\* later. However, your program must continue prompting for input during that time.
Since this is a bit confusing, here's a demo.
```
<pre id=x></pre><input id=h onchange='var k=this;(()=>{let a=k.value;setTimeout(_=>document.getElementById("x").innerText+=a+"\n", 5000)})();this.value="";' >
```
(Try typing multiple things into the box and pressing enter.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
\*Anywhere between four and six seconds is fine.
## Definition of "prompting for input"
I'm not really sure how to define "prompting for input" in a way that works across most languages, so here's a couple of ways you can do this:
* Prompt for input in a terminal, recieving it on pressing enter
* Open a dialog box that asks for input
* Record every keypress and output those delayed - see [this fiddle](https://jsfiddle.net/6zegdjfq/) thanks to tsh
If you're not sure, ask. Note that for the first two options, the operation must not block further output.
[Answer]
# JavaScript, ~~53~~ ~~51~~ 44 bytes
Now 44 bytes thanks to @DomHasting's suggestion to omit `window.`.
(Records every keypress; keyboard events won't register unless you focus on the opened iframe when you click run)
```
onkeyup=e=>setTimeout(console.log,5e3,e.key)
```
[Answer]
# Minecraft Command Blocks, ~895 bytes
[![enter image description here](https://i.stack.imgur.com/zBY3J.png)](https://i.stack.imgur.com/zBY3J.png)
[![enter image description here](https://i.stack.imgur.com/gZc3s.jpg)](https://i.stack.imgur.com/gZc3s.jpg)
My Java answer I already have on this question is pretty good, but as I do also have some skill with Minecraft redstone, I wondered if there was a decent way to do this in Minecraft, and it turns out there is. Because inputting data into Minecraft programs is never quite easy, but I was able to figure out a decent method for this: input is provided by placing a named Creeper mob in a specific location; output is much simpler, as it is simply read out to the game chat.
## Explanation
This "program" consists of two chains of command blocks, as follows:
```
chain 1:
Repeat block, Always active: data modify entity @e[type=minecraft:creeper,dx=2,dy=1,dz=0,limit=1,sort=nearest] PersistenceRequired set value 1
Chain block, Conditional: tp @e[type=minecraft:creeper,dx=3,dy=1,dz=0,limit=1,sort=nearest] ~1 ~222 ~-1
chain 2:
Impulse block, Needs Redstone: say @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=creeper,limit=1,sort=nearest]
Chain block, Unconditional: kill @e[type=item]
```
Minecraft command block programs are mainly formed by chaining command blocks, where a start block (of either Impulse or Repeat type) can activate a Chain block its pointing at, and those Chain blocks can activate more Chain blocks, etc.
Chains can be started by either an Impulse or Repeat block, where Impulse blocks trigger once when activated, and then do not trigger again until they are de- and then re-activated, while Repeat blocks trigger every in-game tick while they are activated. both of these blocks can be in either "Always active" or "Needs Redstone" mode, where they are either, respectively, active all the time, or only active when powered by a Redstone signal. Chain blocks also have a conditional feature, where they can be set to only activate if the command of the block that triggered them executed successfully.
The first chain queues up the signal Creeper, with the Repeat block looking continuously for a nearby Creeper and trying to set its PersistenceRequired property to 1 (true). If it succeeds at this, the Conditional Chain block is triggered, which teleports the Creeper up 222 blocks, a distance which I calculated takes almost exactly 5 seconds for it to fall. The first command block is necessary as that property prevents it from despawning, as normally all mobs despawn instantly if they are more than 128 blocks from the player.
This teleport also lines it up so it falls into a tripwire, which provides the Redstone signal that triggers the start of the second chain, which writes the name of the Creeper to chat, kills the Creeper, and then destroys all the items the creeper dropped, as otherwise these would clog up the tripwire and prevent further messages from functioning. There is a pool of water placed under the tripwire to prevent the fall from killing the Creeper, as it needs to stay there long enough for the command block to read its name.
The sign indicates where the Creeper should go, although this positioning is not precise, and is mainly there to fulfill my interpretation of the "prompt for input" requirement.
## Byte Count Calculation and Golfing
Per [consensus](https://codegolf.meta.stackexchange.com/a/9529/111305), MC "program" bytecounts are calculated using the size of the structure block .nbt file needed to contain them, which I have uploaded to dropbox [here](https://www.dropbox.com/s/0fct2gsc6af837d/laggytext.nbt?dl=0), so that you can test it in your own world if you want.
Golfing with structure block files is irritating, as its often not clear what increases or decreases bytecount except through trial and error, and bytecount even seems to vary by a few bytes for identical structures. I have tried a few variations of commands, but the ones here seem to have the lowest bytecount. I have tried to fit the "program" into the smallest possible bounding box, and all air blocks in the program are replaced with structure void blocks. I had the sandstone floor as voids too, but that somehow seemed to be larger, so I returned it to sandstone, although it is possible some other block may reduce the file size. The iron block the tripwire is on can also be any block, as long as it supports the tripwire. The sign also seems to be contributing almost 100 bytes, so if it is judged to be unnecessary for the "prompting user" requirement, it would certainly shave off a good deal.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 37 bytes
Doesn't work online for obvious reasons!
[@Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) correctly pointed out an unnecessary spaces for -1, thanks!
```
while read a;do sleep 5&&echo $a&done
```
[Try it online!](https://tio.run/##S0oszvj/vzwjMydVoSg1MUUh0TolX6E4JzW1QMFUTS01OSNfQSVRLSU/L/X//5LU4hJDLhBpBCaNAQ "Bash – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 46 bytes
```
[ readln '[ _ print ] 5 seconds later t ] loop
```
Factor has a nice timer vocabulary. `later` Takes a quotation to perform and a duration and calls the quotation after the duration has passed. Since TIO is unsuited for displaying the functionality, here's an animated GIF of running this code in Factor's REPL:
[![enter image description here](https://i.stack.imgur.com/TEW1e.gif)](https://i.stack.imgur.com/TEW1e.gif)
[Answer]
# Java 8, 447 437 404 380 374 278 272 259 219 210 bytes
This is my first code golf, and I'm certain both that I could golf this down more, and that Java is a horrible language for this problem and for golfing in, but for my first try I think this isn't too bad. I tried to golf this in Python, which I'm more familiar with, first, but I simply couldn't get around the non-blocking input restriction in Python.
Edit: Screwing around a lot more I found a much shorter version using threads and waiting instead of my list+timestamp idea for the old one:
```
import java.util.*;class B{static void main(String[]a){Scanner s=new Scanner(System.in);for(;;){String t=s.nextLine();new Thread(()->{try{Thread.sleep(5000);}finally{System.out.println(t);return;}}).start();}}}
```
Edit: -6 bytes, I think I'm solidly addicted to code golfing now.
Edit 2: -13 bytes, realized I could put the whole thing in one class and it'd still work.
Edit 3: -41 bytes from @Clashsoft's excellent idea to use a lambda for the thread class instead.
Edit 4: Apparently the lambda actually means I don't need to extend `Thread` anymore, although I do now need `Thread.sleep()` instead of just `sleep()`
### Old Solution
```
import java.util.*;class A{long t;String s;A(long T,String S){t=T;s=S;}public static void main(String[]a)throws java.io.IOException{List<A>L=new ArrayList<>();Scanner s=new Scanner(System.in);for(;;){if(System.in.available()>0&&s.hasNext()){L.add(new A(System.nanoTime(),s.nextLine()));}if(L.size()>0&&L.get(0).t+5e9<System.nanoTime()){System.out.println(L.remove(0).s);}}}}
```
Edit: -10 bytes from trimming the "public" off Main class declaration and a bit of whitespace.
Edit 2: -33 bytes with a bit more trimming and a better import.
Edit 3: -18 bytes by using System.nanoTime() instead of System.currentTimeMillis(), and -6 by Seggan's suggestion to switch to an interface to drop the public modifier, for total of -24.
Edit 3.5: Pasted the wrong code for edit 3, now showing the correct code (I think, I don't have the actual code or an IDE on hand at the moment) with those changes.
Edit 4: @Neil's suggestion to put it all in one class let me save another six bytes, I think I'm getting close to how far this approach can be golfed in Java, but there could be something more I'm not seeing yet.
[Answer]
# [Rust](https://rust-lang.org), ~~180~~ 127 bytes
```
use std::{io::*,thread::*};fn main(){for s in stdin().lock().lines(){spawn(move||{sleep_ms(5000);println!("{}",s.unwrap())});}}
```
Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.
```
use std::{io::*, thread::*};
fn main() {
for s in stdin().lock().lines() {
spawn(move || {
sleep_ms(5000);
println!("{}", s.unwrap())
});
}
}
```
Thanks to Xiretza and the community in #rust matrix server :)
## Old answer
```
use std::*;fn main(){let s=io::stdin();loop{let mut b=String::new();s.read_line(&mut b).unwrap();thread::spawn(move||{thread::sleep(time::Duration::from_secs(5));print!("{b}")});}}
```
Runs an infinite loop, reads the string and spawns a new thread. After 5s of blocking that thread, it prints it back to the console.
```
use std::*;
fn main() {
let s = io::stdin();
loop {
let mut b = String::new();
s.read_line(&mut b).unwrap();
thread::spawn(move || {
thread::sleep(time::Duration::from_secs(5));
print!("{b}")
});
}
}
```
Sadly it's not possible to run such programs in [rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=use%20std%3A%3A*%3B%0Afn%20main()%20%7B%0A%20%20%20%20let%20s%20%3D%20io%3A%3Astdin()%3B%0A%20%20%20%20loop%20%7B%0A%20%20%20%20%20%20%20%20let%20mut%20b%20%3D%20String%3A%3Anew()%3B%0A%20%20%20%20%20%20%20%20s.read_line(%26mut%20b).unwrap()%3B%0A%20%20%20%20%20%20%20%20thread%3A%3Aspawn(move%20%7C%7C%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20thread%3A%3Asleep(time%3A%3ADuration%3A%3Afrom_secs(5))%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20print!(%22%7Bb%7D%22)%0A%20%20%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20%7D%0A%7D%0A).
Not the best language for code-golf, I know, but just wanted to give it a shot. :)
[Answer]
# Python 63 bytes
```
from threading import*
while 1:Timer(5,print,[input()]).start()
```
Thanks AnttiP for showing me that [Timer](https://docs.python.org/3/library/threading.html#threading.Timer) can directly pass arguments to the callback itself, which cut the solution by 20 bytes.
Thomas Baruchel pointed out a valid criticism of the original recursive solution: that the program would crash after 1000 inputs because of Python's recursion limit. Luckily AnttiP's new design is even shorter without recursion.
[Answer]
## Batch, 63 bytes
```
@set/ps=
@start /b cmd /c"ping -n 6 0.0.0.0>nul&echo %s%"
@%0
```
Explanation: `start /b` runs a command in the background in the same console. `ping` is used for the five second delay between the first and last pings. Note that the string is echoed unquoted so that some shell metacharacters may cause the echo to fail.
[Answer]
# [QBasic](https://en.wikipedia.org/wiki/QBasic), 167 bytes
```
DIM d(999),o$(999)
DO
c$=INKEY$
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP
```
Runs as an infinite loop; outputs character-by-character. Don't run this unless you have a good way to kill the program. Here's a nicer version that quits when you press Escape:
```
DIM d(999),o$(999)
CLS
DO
c$=INKEY$
IF c$=CHR$(27)THEN END
IF""<>c$THEN o$(j)=c$:d(j)=TIMER+5+86400*(TIMER>=86395):j=(j+1)MOD 1E3
IF(INT(TIMER-d(i))=0)*d(i)THEN?o$(i);:d(i)=0:i=(i+1)MOD 1E3
LOOP
```
You can try it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack).
### Approach
QBasic doesn't have any non-blocking sleep command or multithreading capabilities that I'm aware of, so we're going to go low-tech on this and use `TIMER`, which provides the (floating-point) number of seconds since midnight. When a key is pressed, we store it in the `o$` array, and we also store `TIMER + 5` at the same index in the `d` array. Then we check the first time in `d` to see if it has arrived yet; if so, we output the corresponding character.
Some complexity is added because:
* QBasic has fixed-size arrays rather than lists, so there aren't any pop or push operations. We have to track the index of the next insertion and the index of the next removal, and we have to wrap both around when they reach the size of the array.
* `TIMER` resets at midnight, which breaks the math unless we correct for it.
### Ungolfed
```
CONST ARRAYSIZE = 999
CONST TIMERMAX = 86400 ' Number of seconds in a day
DIM d(ARRAYSIZE) ' Times at which to output characters
DIM o$(ARRAYSIZE) ' Characters to output
i = 0 ' Index of first meaningful entry in d and o$
j = 0 ' Index just past last meaningful entry in d and o$
' Clear screen
CLS
' Loop forever
DO
' If a key is being pressed, store it in c$
c$ = INKEY$
' If it is Esc, quit the program
IF c$ = CHR$(27) THEN END
' For any other key...
IF c$ <> "" THEN
' Store it in o$
o$(j) = c$
' Store 5-seconds-in-the-future time in d
d(j) = TIMER + 5
' Correct for midnight wraparound
IF d(j) >= TIMERMAX THEN d(j) = d(j) - TIMERMAX
' Increment next-entry index
j = j + 1
' Wrap index around if necessary
IF j > ARRAYSIZE THEN j = 0
END IF
' If we've reached the time for the first character in the array...
IF d(i) > 0 AND TIMER - d(i) > 0 AND TIMER - d(i) < 1 THEN
' Print it without a newline
PRINT o$(i);
' Zero out the time for that character
d(i) = 0
' Increment first-entry index
i = i + 1
' Wrap index around if necessary
IF i > ARRAYSIZE THEN i = 0
END IF
LOOP
```
[Answer]
# [Julia](https://julialang.org/), ~~53~~ 42 bytes
```
~_=(r=readline();~@async sleep(5)print(r))
```
[![Demonstration of laggy text editor in Julia](https://i.stack.imgur.com/T5FRx.gif)](https://i.stack.imgur.com/T5FRx.gif)
*-11 bytes thanks to @MarcMush*
Previous version that's perhaps easier to understand at a glance:
```
while 1>0
r=readline()
@async (sleep(5);print(r))
end
```
[Answer]
# C, ~~63~~ ~~62~~ 57 bytes
```
main(b){for(;;){gets(&b);if(fork()){sleep(5);puts(&b);}}}
```
[Try online!](https://tio.run/##LYq7DsMgDAB3f4Wnyh46NI@Jr0mQQ6xQiAJtBsS3U4ZOJ92dfTprW3svGmjlssWLjOHiJCd6rGx0o@4OYi7Ji5w0szk//1hrbe0FA4wwwQwiAnefE8pXAt6ad1zQx@Aw5Us7vB6CedeEMcgP)
Similar to [Amir reza Riahi's answer](https://codegolf.stackexchange.com/a/243654/111351) managed to remove `i` variable and used an 8 byte int buffer.
Shaved off a byte by declaring b as `int b`(instead of `int b[8]`) and by using `&` operator
-5 bytes: `b` is passed in to the main function instead of being declared.
[Answer]
# C, ~~83~~ ~~73~~ 69 bytes
```
main(){for(int i=0;;){char*b;gets(b);if(fork()){sleep(5);puts(b);}}}
```
[Try online!](https://tio.run/##JcpLCoAgEADQ/Zyi5UwQ9HM1dJiU0aQvWivx7Ba0fs80zphS9tkfSMmeAf1xV35qmSmZZQ61Zid3RE3sLX5hRaIUN5ELFfH1/JZzhlI66GGAERSICMAL)
The only problem is that the program should break by ctrl-c and is not terminated by the ctrl-d.
Thanks to Neil, I removed 10 bytes.
[Answer]
# HTML/CSS, 73 72 bytes
I wanted to try solving this without JavaScript, so I came up with this solution. To use it, open it in a browser, press tab, then enter, then start typing and submit a line by pressing enter again. Up to you to decide whether or not this user interaction disqualifies the answer.
```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1
```
## Demo
Note that this demo has to close off the CSS for it to work as a code snippet - this is not necessary when opening the HTML by itself in a browser.
```
<p contenteditable><style>p>:last-child{font:0 a}*{transition:5s steps(1)}
```
## Explanation
The `contenteditable` tag makes it possible for the user to edit the DOM text directly. If you've never heard of it before, run `document.body.setAttribute("contenteditable", true)` on random sites and have fun! Since in this case a `<p>` tag is being edited, adding a newline creates a new `<div>` element for each line, which we can use to our advantage in the CSS.
A simplified version of the CSS is pretty self-explanatory:
```
div {
font: initial; /* implied */
transition: font 5s steps(1);
}
div:last-child {
font: 0px Arial;
}
```
The only uncommon part here is the `steps(1)` setting for the transition, which makes the transition go straight from one state to another (instead of fading smoothly).
[Answer]
# TI-Basic (TI-84), ~~76~~ ~~128~~ ~~121~~ 120 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
1→X
1→Y
{0→A
Ans→B
While 1
startTmr→ʟB(X
getKey→ʟA(X
X+tanh(Ans→X
If 5≤checkTmr(ʟB(Y
Then
ʟA(Y
Disp sub("ABC.HDEFGMIJKLRNOPQWTSUV.XYZ",5int(Ans/10-4)+5fPart(Ans/5),1
IS>(Y,X
End
End
```
`ʟA` stores the pressed [keycodes](http://tibasicdev.wikidot.com/userinput#toc4), `ʟB` the time at which they were pressed, `X` is the length of the lists, and `Y` the index of the next letter to print. The precision is one second (precision of `startTmr`) so it should be between 4 and 6 seconds delay. `tanh` serves as a `sign` function since `getKey` is big enough (> 41 for letters)
there's no built-in to translate numbers to characters, hence the long line with all the letters (strange ordering to use mod 5 instead of mod 10). I'm pretty sure this can be further goffed by being clever. Outputing the keycodes instead would save 52 bytes (previous solution)
-1 byte: I believe this is the first time I successfully use [`IS>(`](http://tibasicdev.wikidot.com/is) in code golf, which only works because X is always greater than Y
[![Demo with laggy characters](https://i.stack.imgur.com/MgrzS.gif)](https://i.stack.imgur.com/MgrzS.gif)
[Answer]
# **Kotlin, 122 bytes**
```
import kotlinx.coroutines.*;suspend fun main()=coroutineScope{while(true){readLine()?.let{launch{delay(5000);print(it)}}}}
```
Also my first code-golf. Looking forward for tips and advices.
Explanation: main function is suspendable for non-blocking print. Infinite loop is running under CoroutineScope created with [coroutineScope()](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) function. In infinite loop program constantly reads the prompt with standard function readLine(). Result of readLine() is used under scope function let() in newly created coroutine created with launch() builder, which delays printing for 5 seconds without blocking the next propmt
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 34 bytes
```
f(){ read c;sleep 5&&echo $c&f;};f
```
[Try it online!](https://tio.run/##S0oszvj/P01Ds1qhKDUxRSHZujgnNbVAwVRNLTU5I19BJVktzbrWOu3//0SuJK5krhQA "Bash – Try It Online")
Pretty similar to [Dom Hasting's answer](https://codegolf.stackexchange.com/a/243625/17152), but managed to save 4 bytes by using a function instead of a loop.
Does *not* work correctly on TIO.
[Answer]
# [Seal](https://seallang.netlify.app/), 25 bytes
```
w(1){i=h#l;t{z(5);p(i);}}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
loop{a=gets;fork{sleep 5;$><<a}}
```
Spawns child processes for each timer. They aren't terminated since the program is non-terminating anyways, so if this is ever run it should be followed with a `Process.waitall`.
No TIO link since TIO has static input.
`fork` is not supported on all OSes (most notably Windows), but [it is listed in Ruby documentation](https://ruby-doc.org/core-2.6.2/Process.html#method-c-fork). An alternative solution that works on all OSes is:
```
loop{a=gets;Thread.new(a){sleep 5;$><<_1}}
```
which is 42 characters instead.
[Answer]
# [Scratch](https://scratch.mit.edu/), 168 bytes
[Try it online!](https://scratch.mit.edu/projects/709395019/)
This takes advantage of a clone storing a variable's value at the time of the clone's creation. Alternatively, 11 blocks.
```
when gf clicked
delete all of[O v
forever
ask()and wait
set[t v]to(answer
create clone of[myself v
when I start as a clone
wait(5)seconds
add(t)to[O v
delete this clone
```
```
when gf clicked Syntax
delete all of[O v Clears the output
forever Loops code forever
ask()and wait Prompts user input
set[t v]to(answer Sets variable 't' to the input
create clone of[myself v Creates clone
when I start as a clone Syntax, also ends 'forever' loop
wait(5)seconds Waits 5 seconds
add(t)to[O v Adds to the output the value of 't' at the time of the clone's creation
delete this clone Deletes itself to avoid the 300 clone limit
```
[Answer]
# TI-Basic (TI-89), 117 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
Prgm
{}→g
g→t
xscl→x
x→y
Loop
startTmr()→t[x]
getKey()→g[x]
x+min(xscl,g[x])→x
If checkTmr(t[y])≥5 Then
Disp char(g[y])
y+xscl→y
EndIf
EndLoop
EndPrgm
```
Port of [my answer for the TI-84](https://codegolf.stackexchange.com/a/243743/98541). The TI-Basic of the TI-89 is much more advanced (it has the `char` command and much much more) but the [tokens](http://tibasicdev.wikidot.com/68k:tokenization) are often longer (a literal `1` is stored as 3 bytes, that's why we use `xscl` [2 bytes] instead)
[![demo](https://i.stack.imgur.com/JF3v5.gif)](https://i.stack.imgur.com/JF3v5.gif)
] |
[Question]
[
**UPDATE:** isSuicidal() was added to the plane class, this allows you to check if a plane is on an irreversible collision course with the walls!!
**UPDATE:** updateCoolDown() separated from simulateMove()
**UPDATE:** non-Java entry wrapper, written by [Sparr](https://codegolf.stackexchange.com/users/4787/sparr), available for testing, see comments
**UPDATE** [Zove Games](https://codegolf.stackexchange.com/users/20666/zove-games) Has written an [awesome 3D visualizer](https://codegolf.stackexchange.com/questions/35328/3d-discrete-dogfighting-duel/35492#35492) for this KOTH, [here's a shitty youtube video](https://www.youtube.com/watch?v=gTGDDYDVtCM&feature=youtu.be) of PredictAndAVoid fighting PredictAndAVoid.
The simulateMove() function of the Plane class was slightly modified so it doesn't update the cool down anymore, use the new updateCoolDown() function for that, after shooting. The new isSuicidal() returns true if a plane is bound to end up dead, use it to prune enemy moves and avoid hitting walls. To get the updated code, simply replace the Controller and Plane classes by [**the ones in the github repo.**](https://github.com/overactor/Dogfight-KOTH)
## Description
The goal of this challenge is to code two [dogfighting planes](http://en.wikipedia.org/wiki/Dogfight) that will face off against two planes by another contestant.
Every turn you move one space and have the opportunity to shoot. That's it, it's as simple as that.
Well, almost...
## Arena and possible moves
The arena is a 14x14x14 walled in space. the planes of contestant 1 start at the locations (0,5,0) and (0,8,0) and those of contestant 2 at (13,5,13) and (13,8,13). All planes start out by flying horizontally away from the vertical walls they are closest to.
Now since you are flying planes and not helicopters, you can't just change direction at will or even stop moving, so each plane has a direction and will move one tile in that direction every turn.
The possible directions are: North(N), South(S), East(E), West(W), Up(U) and Down(D) and any logical combination of those six. Where the NS axis corresponds to the x axis, WE to y and DU to z.
NW, SU and NED come to mind as possible examples of directions; UD is a great example of an invalid combination.
You can of course change the direction of your planes, but there is a limitation, you can only change your direction by at most 45 degrees. To visualize this, grab your rubik's cube (I know you have one) and imagine all of the 26 outer little cubes are the possible directions (one letter directions are faces, two letter direction are edges and three letter directions are corners). If you're heading in a direction represented by a little cube, you can change direction to each cube that touches yours (diagonally touching counts, but only touching visibly, that is not touching through the cube).
After all planes have indicated to which direction they would like to change, they do so and move one tile simultaneously.
You can also opt to move in a valid direction but keep flying in the direction you were going, in stead of changing your direction into the direction you moved to. This is analogous to the difference between a car going around a corner and a car changing lanes.
## Shooting and dying
You can shoot at most once per round and this has to be decided at the same time you decide which direction to fly in and whether you want to keep your plane (and by extension, your gun) pointed in the same direction or not. The bullet gets shot right after your plane moves. There is a cool down of one turn after shooting, on the third turn, you're good to go again. You can only shoot in the direction you're flying in. A bullet is instant and flies in a straight line until it hits a wall or a plane.
Taking into account the way you can change direction as well as 'change lanes', this means that you can threaten up a column of up to 3x3 lines in front of you additionally to some diagonal, single lines.
If it hits a plane, this plane dies and promptly disappears from the board (because it totally explodes or something). Bullets can only hit one plane at most. Bullets get shot simultaneously, so two planes can shoot each other. Two bullets can not collide in the air though (sad, I know).
Two planes can collide however (if they end up in the same cube and NOT if they cross each other without ending up in the same plane), and this results in both planes dying (and totally exploding). You can also fly into the wall which will result in the plane in question dying and being put in the corner to think about its actions. Collisions get handled before shooting does.
## Communication with the controller
I will accept entries in java as well as other languages.
If your entry is in java, you will get input through STDIN and will output through STDOUT.
If your entry is in java, .your entry must extend the following class:
```
package Planes;
//This is the base class players extend.
//It contains the arena size and 4 plane objects representing the planes in the arena.
public abstract class PlaneControl {
// note that these planes are just for your information, modifying these doesn't affect the actual plane instances,
// which are kept by the controller
protected Plane[] myPlanes = new Plane[2];
protected Plane[] enemyPlanes = new Plane[2];
protected int arenaSize;
protected int roundsLeft;
...
// Notifies you that a new fight is starting
// FightsFought tells you how many fights will be fought.
// the scores tell you how many fights each player has won.
public void newFight(int fightsFought, int myScore, int enemyScore) {}
// notifies you that you'll be fighting anew opponent.
// Fights is the amount of fights that will be fought against this opponent
public void newOpponent(int fights) {}
// This will be called once every round, you must return an array of two moves.
// The move at index 0 will be applied to your plane at index 0,
// The move at index1 will be applied to your plane at index1.
// Any further move will be ignored.
// A missing or invalid move will be treated as flying forward without shooting.
public abstract Move[] act();
}
```
The instance created of that class will persist throughout the entire competition, so you can store any data you'd like to store in variables. Read the comments in the code for more information.
I've also provided you with the following helper classes:
```
package Planes;
//Objects of this class contain all relevant information about a plane
//as well as some helper functions.
public class Plane {
private Point3D position;
private Direction direction;
private int arenaSize;
private boolean alive = true;
private int coolDown = 0;
public Plane(int arenaSize, Direction direction, int x, int y, int z) {}
public Plane(int arenaSize, Direction direction, Point3D position) {}
// Returns the x coordinate of the plane
public int getX() {}
// Returns the y coordinate of the plane
public int getY() {}
// Returns the z coordinate of the plane
public int getZ() {}
// Returns the position as a Point3D.
public Point3D getPosition() {}
// Returns the distance between the plane and the specified wall,
// 0 means right next to it, 19 means at the opposite side.
// Returns -1 for invalid input.
public int getDistanceFromWall(char wall) {}
// Returns the direction of the plane.
public Direction getDirection() {}
// Returns all possible turning directions for the plane.
public Direction[] getPossibleDirections() {}
// Returns the cool down before the plane will be able to shoot,
// 0 means it is ready to shoot this turn.
public int getCoolDown() {}
public void setCoolDown(int coolDown) {}
// Returns true if the plane is ready to shoot
public boolean canShoot() {}
// Returns all positions this plane can shoot at (without first making a move).
public Point3D[] getShootRange() {}
// Returns all positions this plane can move to within one turn.
public Point3D[] getRange() {}
// Returns a plane that represents this plane after making a certain move,
// not taking into account other planes.
// Doesn't update cool down, see updateCoolDown() for that.
public Plane simulateMove(Move move) {}
// modifies this plane's cool down
public void updateCoolDown(boolean shot) {
coolDown = (shot && canShoot())?Controller.COOLDOWN:Math.max(0, coolDown - 1);
}
// Returns true if the plane is alive.
public boolean isAlive() {}
// Sets alive to the specified value.
public void setAlive(boolean alive) {}
// returns a copy of itself.
public Plane copy() {}
// Returns a string representing its status.
public String getAsString() {}
// Returns a string suitable for passing to a wrapped plane process
public String getDataString() {}
// Returns true if a plane is on an irreversable colision course with the wall.
// Use this along with simulateMove() to avoid hitting walls or prune possible emeny moves.
public boolean isSuicidal() {}
}
// A helper class for working with directions.
public class Direction {
// The three main directions, -1 means the first letter is in the direction, 1 means the second is, 0 means neither is.
private int NS, WE, DU;
// Creates a direction from 3 integers.
public Direction(int NSDir, int WEDir, int DUDir) {}
// Creates a direction from a directionstring.
public Direction(String direction) {}
// Returns this direction as a String.
public String getAsString() {}
// Returns The direction projected onto the NS-axis.
// -1 means heading north.
public int getNSDir() {}
// Returns The direction projected onto the WE-axis.
// -1 means heading west.
public int getWEDir() {}
// Returns The direction projected onto the DU-axis.
// -1 means heading down.
public int getDUDir() {}
// Returns a Point3D representing the direction.
public Point3D getAsPoint3D() {}
// Returns an array of chars representing the main directions.
public char[] getMainDirections() {}
// Returns all possible turning directions.
public Direction[] getPossibleDirections() {}
// Returns true if a direction is a valid direction to change to
public boolean isValidDirection(Direction direction) {}
}
public class Point3D {
public int x, y, z;
public Point3D(int x, int y, int z) {}
// Returns the sum of this Point3D and the one specified in the argument.
public Point3D add(Point3D point3D) {}
// Returns the product of this Point3D and a factor.
public Point3D multiply(int factor) {}
// Returns true if both Point3D are the same.
public boolean equals(Point3D point3D) {}
// Returns true if Point3D is within a 0-based arena of a specified size.
public boolean isInArena(int size) {}
}
public class Move {
public Direction direction;
public boolean changeDirection;
public boolean shoot;
public Move(Direction direction, boolean changeDirection, boolean shoot) {}
}
```
You can create instances of these classes and use any of their functions as much as you like. **You can find the full code for these helper classes [here](https://github.com/overactor/Dogfight-KOTH).**
**Here's an example of what your entry could look like** (Hopefully you'll do better than I did though, most of the matches with these planes end with them flying into a wall, despite their best efforts to avoid the wall.):
```
package Planes;
public class DumbPlanes extends PlaneControl {
public DumbPlanes(int arenaSize, int rounds) {
super(arenaSize, rounds);
}
@Override
public Move[] act() {
Move[] moves = new Move[2];
for (int i=0; i<2; i++) {
if (!myPlanes[i].isAlive()) {
moves[i] = new Move(new Direction("N"), false, false); // If we're dead we just return something, it doesn't matter anyway.
continue;
}
Direction[] possibleDirections = myPlanes[i].getPossibleDirections(); // Let's see where we can go.
for (int j=0; j<possibleDirections.length*3; j++) {
int random = (int) Math.floor((Math.random()*possibleDirections.length)); // We don't want to be predictable, so we pick a random direction out of the possible ones.
if (myPlanes[i].getPosition().add(possibleDirections[random].getAsPoint3D()).isInArena(arenaSize)) { // We'll try not to fly directly into a wall.
moves[i] = new Move(possibleDirections[random], Math.random()>0.5, myPlanes[i].canShoot() && Math.random()>0.2);
continue; // I'm happy with this move for this plane.
}
// Uh oh.
random = (int) Math.floor((Math.random()*possibleDirections.length));
moves[i] = new Move(possibleDirections[random], Math.random()>0.5, myPlanes[i].canShoot() && Math.random()>0.2);
}
}
return moves;
}
@Override
public void newFight(int fightsFought, int myScore, int enemyScore) {
// Using information is for schmucks.
}
@Override
public void newOpponent(int fights) {
// What did I just say about information?
}
}
```
DumbPlanes will join the tournament along with the other entries, so if you end last, it's your own fault for not at least doing better than DumbPlanes.
## Restrictions
The restrictions mentioned in the [KOTH wiki](https://codegolf.stackexchange.com/tags/king-of-the-hill/info) apply:
* Any attempt to tinker with the controller, runtime or other submissions will be disqualified. All submissions should only work with the inputs and storage they are given.
* Bots should not be written to beat or support specific other bots. (This might be desirable in rare cases, but if this is not a core concept of the challenge, it's better ruled out.)
* I Reserve the right to disqualify submissions that use too much time or memory to run trials with a reasonable amount of resources.
* A bot must not implement the exact same strategy as an existing one, intentionally or accidentally.
## Testing your submission
Download the Controller code from [here](https://github.com/overactor/Dogfight-KOTH). Add your submission as Something.java. Modify Controller.java to include entries for your plane in entries[] and names[]. Compile everything as an Eclipse project or with `javac -d . *.java`, then run the Controller with `java Planes/Controller`. A log of the contest will be in `test.txt`, with a scoreboard at the end.
You can also call `matchUp()` directly with two entries as arguments to just test two planes against each other.
## Winning the fight
The winner of the fight is the one who has the last plane flying, if after 100 turns, there is still more than 1 team left, the team with the most planes left wins. If this is equal, it's a draw.
## Scoring and the competition
The next official tournament will be run when the current bounty runs out.
Each entry will fight every other entry (at least) 100 times, the winner of each match up is the ones with the most wins out of the 100 and will be awarded 2 points. In case of a draw, both entries are awarded 1 point.
The winner of the competition is the one with most points. In case of a draw, the winner is the one who won in a the match up between the entries that drew.
Depending on the amount of entries, The amount of fights between entries could be increased significantly, I might also select the 2-4 best entries after the first tournament and set up an elites tournament between those entries with more fights (and possibly more rounds per fight)
## (preliminary) Scoreboard
We've got a new entry who firmly take sthe second place in [yet another exciting tournament](https://gist.githubusercontent.com/overactor/bd3c5d3eae776d1639b3/raw/0e1e76488633d8f376dcf2d1e120fcd9567afe3e/toouurnament.txt), it seems like Crossfire is incredibly hard to shoot for everyone except for PredictAndAvoid. Note that this tournament was run with only 10 fights between each set of planes and is therefor not an entirely accurate representation of how things stand.
```
----------------------------
¦ 1. PredictAndAvoid: 14 ¦
¦ 2. Crossfire: 11 ¦
¦ 3. Weeeeeeeeeeee: 9 ¦
¦ 4. Whirligig: 8 ¦
¦ 4. MoveAndShootPlane: 8 ¦
¦ 6. StarFox: 4 ¦
¦ 6. EmoFockeWulf: 2 ¦
¦ 7. DumbPlanes: 0 ¦
----------------------------
```
Here is an example of output from the non-Java wrapper:
`NEW CONTEST 14 20` indicates that a new contest is starting, in a 14x14x14 arena, and it will involve 20 turns per fight.
`NEW OPPONENT 10` indicates that you're facing a new opponent, and that you will fight this opponent 10 times
`NEW FIGHT 5 3 2` indicates that a new fight against the current opponent is starting, that you've fought this opponent 5 times so far, winning 3 and losing 2 fights
`ROUNDS LEFT 19` indicates there are 19 rounds left in the current fight
`NEW TURN` indicates that you're about to receive data for all four planes for this round of the fight
```
alive 13 8 13 N 0
alive 13 5 13 N 0
dead 0 0 0 N 0
alive 0 8 0 S 0
```
These four lines indicate that both of your planes are alive, at coordinates [13,8,13] and [13,5,13] respectively, both facing North, both with zero cooldown. The first enemy plane is dead, and the second is alive, at [0,8,0] and facing south with zero cooldown.
At this point your program should output two lines similar to the following:
```
NW 0 1
SU 1 0
```
This indicates that your first plane will travel NorthWest, without turning from its current heading, and shooting if able. Your second plane will travel SouthUp, turning to face SouthUp, not shooting.
Now you get `ROUNDS LEFT 18` followed by `NEW TURN` etc. This continues until someone wins or the round times out, at which point you get another `NEW FIGHT` line with the updated fight count and scores, possibly preceded by a `NEW OPPONENT`.
[Answer]
```
/*
PREDICT AND AVOID
Rules of behavior:
- Avoid hitting walls
- Move, safely, to shoot at spaces our enemy might fly to
- (contingent) Move to a safe space that aims closer to the enemy
- Move to a safe space
- Move, unsafely, to shoot at spaces our enemy might fly to
- Move to any space (remember to avoid walls)
Chooses randomly between equally prioritized moves
contingent strategy is evaluated during early fights
*/
package Planes;
import java.util.Random;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class PredictAndAvoid extends PlaneControl {
public PredictAndAvoid(int arenaSize, int rounds) {
super(arenaSize, rounds);
}
private int fightsPerMatch = 0;
private int fightNum = 0;
private int roundNum = 0;
private boolean useHoming = true;
private int homingScore = 0;
private int[][][] enemyHistory = new int[arenaSize][arenaSize][arenaSize];
// don't need to take roots here, waste of cpu cycles
int distanceCubed(Point3D a, Point3D b) {
return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) + (a.z-b.z)*(a.z-b.z);
}
// is this plane guaranteed to hit a wall, now or soon?
boolean dangerZone(Plane icarus) {
// outside the arena?
// already dead
// this should never happen for my planes
if (!icarus.getPosition().isInArena(arenaSize)) {
return true;
}
// adjacent to a wall?
// directly facing the wall?
// death next turn
if (
icarus.getDirection().getMainDirections().length==1 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[0]) == 0
) {
return true;
}
// on an edge?
// 2d diagonal facing into that edge?
// death next turn
if (
icarus.getDirection().getMainDirections().length==2 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[0]) == 0 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[1]) == 0
) {
return true;
}
// near a corner?
// 3d diagonal facing into that corner?
// death in 1-2 turns
if (
icarus.getDirection().getMainDirections().length==3 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[0]) < 2 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[1]) < 2 &&
icarus.getDistanceFromWall(icarus.getDirection().getMainDirections()[2]) < 2
) {
return true;
}
// there's at least one way out of this position
return false;
}
@Override
public Move[] act() {
Move[] moves = new Move[2];
for (int i=0; i<2; i++) {
Plane p = myPlanes[i];
if (!p.isAlive()) {
moves[i] = new Move(new Direction("N"), false, false); // If we're dead we just return something, it doesn't matter anyway.
continue;
}
// a list of every move that doesn't commit us to running into a wall
// or a collision with the previously moved friendly plane
ArrayList<Move> potentialMoves = new ArrayList<Move>();
for (Direction candidateDirection : p.getPossibleDirections()) {
if (i==1 && myPlanes[0].simulateMove(moves[0]).getPosition().equals(myPlanes[1].simulateMove(new Move(candidateDirection,false,false)).getPosition())) {
} else {
Plane future = new Plane(arenaSize, 0, p.getDirection(), p.getPosition().add(candidateDirection.getAsPoint3D()));
if (!dangerZone(future)) {
potentialMoves.add(new Move(candidateDirection, false, false));
}
future = new Plane(arenaSize, 0, candidateDirection, p.getPosition().add(candidateDirection.getAsPoint3D()));
if (!dangerZone(future)) {
potentialMoves.add(new Move(candidateDirection, true, false));
}
}
}
// everywhere our enemies might end up
// including both directions they could be facing for each location
ArrayList<Plane> futureEnemies = new ArrayList<Plane>();
for (Plane e : enemyPlanes) {
if (e.isAlive()) {
for (Direction candidateDirection : e.getPossibleDirections()) {
futureEnemies.add(new Plane(
arenaSize,
e.getCoolDown(),
candidateDirection,
e.getPosition().add(candidateDirection.getAsPoint3D())
));
// don't make a duplicate entry for forward moves
if (!candidateDirection.getAsPoint3D().equals(e.getDirection().getAsPoint3D())) {
futureEnemies.add(new Plane(
arenaSize,
e.getCoolDown(),
e.getDirection(),
e.getPosition().add(candidateDirection.getAsPoint3D())
));
}
}
}
}
// a list of moves that are out of enemies' potential line of fire
// also skipping potential collisions unless we are ahead on planes
ArrayList<Move> safeMoves = new ArrayList<Move>();
for (Move candidateMove : potentialMoves) {
boolean safe = true;
Point3D future = p.simulateMove(candidateMove).getPosition();
for (Plane ec : futureEnemies) {
if (ec.getPosition().equals(future)) {
if (
(myPlanes[0].isAlive()?1:0) + (myPlanes[1].isAlive()?1:0)
<=
(enemyPlanes[0].isAlive()?1:0) + (enemyPlanes[1].isAlive()?1:0)
) {
safe = false;
break;
}
}
if (ec.isAlive() && ec.canShoot()) {
Point3D[] range = ec.getShootRange();
for (Point3D t : range) {
if (future.equals(t)) {
safe = false;
break;
}
}
if (safe == false) {
break;
}
}
}
if (safe == true) {
safeMoves.add(candidateMove);
}
}
// a list of moves that let us attack a space an enemy might be in
// ignore enemies committed to suicide vs a wall
// TODO: don't shoot at friendly planes
ArrayList<Move> attackMoves = new ArrayList<Move>();
for (Move candidateMove : potentialMoves) {
int attackCount = 0;
Plane future = p.simulateMove(candidateMove);
Point3D[] range = future.getShootRange();
for (Plane ec : futureEnemies) {
for (Point3D t : range) {
if (ec.getPosition().equals(t)) {
if (!dangerZone(ec)) {
attackMoves.add(new Move(candidateMove.direction, candidateMove.changeDirection, true));
attackCount++;
}
}
}
}
if (attackCount > 0) {
}
}
// find all attack moves that are also safe moves
ArrayList<Move> safeAttackMoves = new ArrayList<Move>();
for (Move safeCandidate : safeMoves) {
for (Move attackCandidate : attackMoves) {
if (safeCandidate.direction == attackCandidate.direction) {
safeAttackMoves.add(attackCandidate);
}
}
}
// choose the safe move that aims closest potential enemy positions
int maxDistanceCubed = arenaSize*arenaSize*arenaSize*8;
Move homingMove = null;
int bestHomingMoveTotalDistancesCubed = maxDistanceCubed*1000;
for (Move candidateMove : safeMoves) {
int totalCandidateDistancesCubed = 0;
for (Plane ec : futureEnemies) {
if (ec.isAlive()) {
int distThisEnemyCubed = maxDistanceCubed;
Point3D[] range = p.simulateMove(candidateMove).getShootRange();
for (Point3D t : range) {
int d1 = distanceCubed(t, ec.getPosition());
if (d1 < distThisEnemyCubed) {
distThisEnemyCubed = d1;
}
}
totalCandidateDistancesCubed += distThisEnemyCubed;
}
}
if (totalCandidateDistancesCubed < bestHomingMoveTotalDistancesCubed) {
bestHomingMoveTotalDistancesCubed = totalCandidateDistancesCubed;
homingMove = candidateMove;
}
}
Random rng = new Random();
// move to attack safely if possible
// even if we can't shoot, this is good for chasing enemies
if (safeAttackMoves.size() > 0) {
moves[i] = safeAttackMoves.get(rng.nextInt(safeAttackMoves.size()));
}
// turn towards enemies if it's possible and safe
// tests indicate value of this strategy varies significantly by opponent
// useHoming changes based on outcome of early fights with[out] it
// TODO: track enemy movement, aim for neighborhood
else if (useHoming == true && homingMove != null) {
moves[i] = homingMove;
}
// make random move, safe from attack
else if (safeMoves.size() > 0) {
moves[i] = safeMoves.get(rng.nextInt(safeMoves.size()));
}
// move to attack unsafely only if there are no safe moves
else if (attackMoves.size() > 0 && p.canShoot()) {
moves[i] = attackMoves.get(rng.nextInt(attackMoves.size()));
}
// make random move, safe from walls
else if (potentialMoves.size() > 0) {
moves[i] = potentialMoves.get(rng.nextInt(potentialMoves.size()));
}
// keep moving forward
// this should never happen
else {
moves[i] = new Move(p.getDirection(), false, true);
}
}
roundNum++;
return moves;
}
@Override
public void newFight(int fightsFought, int myScore, int enemyScore) {
// try the homing strategy for 1/8 of the match
// skip it for 1/8, then choose the winning option
if (fightsFought == fightsPerMatch/8) {
homingScore = myScore-enemyScore;
useHoming = false;
} else if (fightsFought == (fightsPerMatch/8)*2) {
if (homingScore*2 > myScore-enemyScore) {
useHoming = true;
}
}
fightNum = fightsFought;
roundNum = 0;
}
@Override
public void newOpponent(int fights) {
fightsPerMatch = fights;
}
}
```
[Answer]
# Dogfight 3D Visualizer
I wrote a small, quick visualizer for this challenge. Code and jar files are on my github repo: <https://github.com/Hungary-Dude/DogfightVisualizer>
It's made using libGDX (<http://libgdx.com>). Right now the UI is pretty bad, I did put this together kind of fast.
I'm just learning how to use Git and Gradle so please comment if I did something wrong
Run `dist/dogfight.bat` or `dist/dogfight.sh` to see DumbPlanes in action!
To build from source, you'll need Gradle (<http://gradle.org>) and Gradle integration for your IDE, if you have one. Then clone the repo and run `gradlew desktop:run`. Hopefully Gradle will import all the libraries required. The main class is `zove.koth.dogfight.desktop.DesktopLauncher`.
### Running without importing
Copy any plane class files into `dist/`. Then, run `dist/desktop-1.0.jar` with this command:
```
java -cp your-class-folder/;desktop-1.0.jar;Planes.jar zove.koth.dogfight.desktop.DesktopLauncher package.YourPlaneController1 package.YourPlaneController2 ...
```
I will update as the source for the Planes controller is updated, but to update yourself, you'll need to add in some code to `Planes.Controller`. See the github readme for info on this.
Here's a screenshot:
![Screenshot](https://i.stack.imgur.com/bR5EJ.png)
If you have any questions or suggestions, leave a comment below!
[Answer]
# EmoFockeWulf
He's back. He's starved himself to 224 bytes. He doesn't know how he ended up like this.
```
package Planes;public class EmoFockeWulf extends PlaneControl{public EmoFockeWulf(int s, int r){super(s,r);}public Move[] act(){Move[] m=new Move[2];m[0]=new Move(myPlanes[0].getDirection(),false,false);m[1]=m[0];return m;}}
```
[Answer]
**Weeeeeeeeeeee** - *344 bytes after removing whitespace*
Does awesome loops n stuff. Can't lose if you're doing loops.
```
package Planes;
public class W extends PlaneControl{
int i,c;
int[] s={1,1,1,0,-1,-1,-1,0};
public W(int a,int r){
super(a,r);
}
public void newFight(int a,int b,int c){
i=4;
}
public Move[] act(){
Plane p=myPlanes[0];
if(++i<6)
c=p.getX()==0?1:-1;
Move n=new Move(i<8?p.getDirection():new Direction(c*s[(i+2)%8],0,c*s[i%8]),0<1,i%2<1);
Move[] m={n,n};
return m;
}
}
```
**EDIT:** apparently when my plane started as team 2, they just crashed immediately into the wall. I think I fixed that now. Hopefully.
[Answer]
# Move-and-Shoot plane
Avoids walls by finding when it's close to a wall & turning, shoots when it can.
```
package Planes;
public class MoveAndShootPlane extends PlaneControl {
public MoveAndShootPlane(int arenaSize, int rounds) {
super(arenaSize, rounds);
}
@Override
public Move[] act() {
Move[] moves = new Move[2];
for (int i=0; i<2; i++) {
if (!myPlanes[i].isAlive()) {
moves[i] = new Move(new Direction("N"), false, false); // If we're dead we just return something, it doesn't matter anyway.
continue;
}
// What direction am I going again?
Direction currentDirection = myPlanes[i].getDirection();
// Is my plane able to shoot?
boolean canIShoot = myPlanes[i].canShoot();
// if a wall is near me, turn around, otherwise continue along
if (myPlanes[i].getDirection().getAsString().equals("N") && myPlanes[i].getDistanceFromWall('N') <= 2) {
if (myPlanes[i].getDistanceFromWall('U') > myPlanes[i].getDistanceFromWall('D')) {
moves[i] = new Move(new Direction("NU"), true, canIShoot);
} else {
moves[i] = new Move(new Direction("ND"), true, canIShoot);
}
} else if (myPlanes[i].getDirection().getAsString().equals("S") && myPlanes[i].getDistanceFromWall('S') <= 2) {
if (myPlanes[i].getDistanceFromWall('U') > myPlanes[i].getDistanceFromWall('D')) {
moves[i] = new Move(new Direction("SU"), true, canIShoot);
} else {
moves[i] = new Move(new Direction("SD"), true, canIShoot);
}
} else {
if (myPlanes[i].getDirection().getAsString().equals("N") || myPlanes[i].getDirection().getAsString().equals("S")) {
moves[i] = new Move(currentDirection, false, canIShoot);
} else if (myPlanes[i].getDistanceFromWall('N') < myPlanes[i].getDistanceFromWall('S')) {
if (myPlanes[i].getDirection().getAsString().equals("NU")) {
moves[i] = new Move(new Direction("U"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("U")) {
moves[i] = new Move(new Direction("SU"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("SU")) {
moves[i] = new Move(new Direction("S"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("ND")) {
moves[i] = new Move(new Direction("D"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("D")) {
moves[i] = new Move(new Direction("SD"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("SD")) {
moves[i] = new Move(new Direction("S"), true, canIShoot);
}
} else {
if (myPlanes[i].getDirection().getAsString().equals("SU")) {
moves[i] = new Move(new Direction("U"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("U")) {
moves[i] = new Move(new Direction("NU"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("NU")) {
moves[i] = new Move(new Direction("N"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("SD")) {
moves[i] = new Move(new Direction("D"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("D")) {
moves[i] = new Move(new Direction("ND"), true, canIShoot);
} else if (myPlanes[i].getDirection().getAsString().equals("ND")) {
moves[i] = new Move(new Direction("N"), true, canIShoot);
}
}
}
}
return moves;
}
@Override
public void newFight(int fightsFought, int myScore, int enemyScore) {
// Using information is for schmucks.
}
@Override
public void newOpponent(int fights) {
// What did I just say about information?
}
}
```
*Disclaimer: I am not at all a Java programmer, so if I screwed anything up, please fix it for me!*
[Answer]
# Whirligig
Both planes head towards the center(ish), then loop while shooting as often as possible. One of three axes is chosen per fight, and the pair always rotate around the same axis in opposite directions.
```
package Planes;
public class Whirligig extends PlaneControl{
public Whirligig(int arenaSize, int rounds) {
super(arenaSize, rounds);
cycle = -1;
}
int cycle;
String[][] cycles = {
{"E","EU","U","WU","W","WD","D","ED"},
{"N","NU","U","SU","S","SD","D","ND"},
{"S","SW","W","NW","N","NE","E","SE"},
{"ED","D","WD","W","WU","U","EU","E"},
{"ND","D","SD","S","SU","U","NU","N"},
{"SE","E","NE","N","NW","W","SW","S"},
};
private Move act(int idx){
Plane plane = myPlanes[idx];
Move move = new Move(plane.getDirection(), true, plane.canShoot());
if(!plane.isAlive())
return new Move(new Direction("N"), false, false);
if(cycle < 0){
if(idx == 0 && (myPlanes[1].getZ() == 0 || myPlanes[1].getZ() == 13)){
return move;
}
if(distanceToCenter(plane.getPosition()) > 2){
move.direction = initialMove(plane);
} else {
cycle = (int)(Math.random()*3);
}
} else {
move.direction = continueCycle(plane, cycle + (idx*3));
}
return move;
}
private Direction initialMove(Plane plane){
if(plane.getDirection().getNSDir() > 0)
return new Direction("SU");
else
return new Direction("ND");
}
private Direction continueCycle(Plane plane, int pathIndex){
Direction current = plane.getDirection();
String[] path = cycles[pathIndex];
for(int i=0;i<path.length;i++)
if(path[i].equals(current.getAsString()))
return new Direction(path[(i+1)%path.length]);
Direction[] possible = plane.getPossibleDirections();
int step = (int)(Math.random()*path.length);
for(int i=0;i<path.length;i++){
for(int j=0;j<possible.length;j++){
if(path[(i+step)%path.length].equals(possible[j].getAsString()))
return new Direction(path[(i+step)%path.length]);
}
}
return plane.getDirection();
}
private int distanceToCenter(Point3D pos){
int x = (int)Math.abs(pos.x - 6.5);
int y = (int)Math.abs(pos.y - 6.5);
int z = (int)Math.abs(pos.z - 6.5);
return Math.max(x, Math.max(y,z));
}
@Override
public Move[] act() {
Move[] moves = new Move[2];
for(int i=0;i<2;i++){
moves[i] = act(i);
}
return moves;
}
@Override
public void newFight(int fought, int wins, int losses){
cycle = -1;
}
@Override
public void newOpponent(int fights){
cycle = -1;
}
}
```
[Answer]
# Crossfire
My initial idea was to shoot an enemy plane with both my planes at the same time, but I couldn't work it out... So here is a plane that tries to stay away from walls and out of the shooting-range of the enemy. The planes should never collide nor shoot friendly planes.
**Edit:** the method `possibleHits` always returned 0, after fixing it and adding several little improvements, it performs better than before.
```
package Planes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Crossfire extends PlaneControl {
final List<Point3D> dangerList = new ArrayList<>(); //danger per point
final List<Plane> targets = new ArrayList<>(); //targets being shot
Plane[] futurePlanes = null; //future friendly planes
public Crossfire(int arenaSize, int rounds) {
super(arenaSize, rounds);
}
@Override
public Move[] act() {
dangerList.clear(); //initialize
targets.clear();
final int PLANE_COUNT = myPlanes.length;
Move[] moves = new Move[PLANE_COUNT];
futurePlanes = new Plane[PLANE_COUNT];
// calculate danger per field/enemy
for (int i = 0; i < PLANE_COUNT; i++) {
updateDanger(enemyPlanes[i]);
}
// get best moves for each plane
for (int i = 0; i < PLANE_COUNT; i++) {
moves[i] = getBestMove(myPlanes[i]);
futurePlanes[i] = myPlanes[i].simulateMove(moves[i]);
updateTargets(futurePlanes[i]);
}
// try to shoot if no friendly plane is hit by this bullet
for (int i = 0; i < myPlanes.length; i++) {
if (myPlanes[i].canShoot() && canShootSafely(futurePlanes[i]) && possibleHits(futurePlanes[i]) > 0) {
moves[i].shoot = true;
}
}
return moves;
}
private void updateTargets(Plane plane) {
if (!plane.canShoot() || !canShootSafely(plane)) {
return;
}
Point3D[] range = plane.getShootRange();
for (Plane enemyPlane : enemyPlanes) {
for (Move move : getPossibleMoves(enemyPlane)) {
Plane simPlane = enemyPlane.simulateMove(move);
for (Point3D dest : range) {
if (dest.equals(simPlane.getPosition())) {
targets.add(enemyPlane);
}
}
}
}
}
private void updateDanger(Plane plane) {
if (!plane.isAlive()) {
return;
}
for (Move move : getPossibleMoves(plane)) {
Plane futurePlane = plane.simulateMove(move);
// add position (avoid collision)
if (!isOutside(futurePlane)) {
dangerList.add(futurePlane.getPosition());
// avoid getting shot
if (plane.canShoot()) {
for (Point3D dest : futurePlane.getShootRange()) {
dangerList.add(dest);
}
}
}
}
}
private Move getBestMove(Plane plane) {
if (!plane.isAlive()) {
return new Move(new Direction("N"), false, false);
}
int leastDanger = Integer.MAX_VALUE;
Move bestMove = new Move(new Direction("N"), false, false);
for (Move move : getPossibleMoves(plane)) {
Plane futurePlane = plane.simulateMove(move);
int danger = getDanger(futurePlane) - (possibleHits(futurePlane) *2);
if (danger < leastDanger) {
leastDanger = danger;
bestMove = move;
}
}
return bestMove;
}
private int getDanger(Plane plane) {
if (!plane.isAlive() || hugsWall(plane) || collidesWithFriend(plane) || isOutside(plane)) {
return Integer.MAX_VALUE - 1;
}
int danger = 0;
Point3D pos = plane.getPosition();
for (Point3D dangerPoint : dangerList) {
if (pos.equals(dangerPoint)) {
danger++;
}
}
// stay away from walls
for (char direction : plane.getDirection().getMainDirections()) {
if (plane.getDistanceFromWall(direction) <= 2) {
danger++;
}
}
return danger;
}
private boolean collidesWithFriend(Plane plane) {
for (Plane friendlyPlane : futurePlanes) {
if (friendlyPlane != null && plane.getPosition().equals(friendlyPlane.getPosition())) {
return true;
}
}
return false;
}
private boolean hugsWall(Plane plane) {
if (!plane.isAlive() || isOutside(plane)) {
return true;
}
char[] mainDirs = plane.getDirection().getMainDirections();
if (mainDirs.length == 1) {
return plane.getDistanceFromWall(mainDirs[0]) == 0;
}
if (mainDirs.length == 2) {
return plane.getDistanceFromWall(mainDirs[0]) <= 1
&& plane.getDistanceFromWall(mainDirs[1]) <= 1;
}
if (mainDirs.length == 3) {
return plane.getDistanceFromWall(mainDirs[0]) <= 1
&& plane.getDistanceFromWall(mainDirs[1]) <= 1
&& plane.getDistanceFromWall(mainDirs[2]) <= 1;
}
return false;
}
private Set<Move> getPossibleMoves(Plane plane) {
Set<Move> possibleMoves = new HashSet<>();
for (Direction direction : plane.getPossibleDirections()) {
possibleMoves.add(new Move(direction, false, false));
possibleMoves.add(new Move(direction, true, false));
}
return possibleMoves;
}
private boolean canShootSafely(Plane plane) {
if (!plane.canShoot() || isOutside(plane)) {
return false;
}
for (Point3D destPoint : plane.getShootRange()) {
for (Plane friendlyPlane : futurePlanes) {
if (friendlyPlane == null) {
continue;
}
if (friendlyPlane.isAlive() && friendlyPlane.getPosition().equals(destPoint)) {
return false;
}
}
}
return true;
}
private int possibleHits(Plane plane) {
if (!plane.canShoot() || !canShootSafely(plane)) {
return 0;
}
int possibleHits = 0;
Point3D[] range = plane.getShootRange();
for (Plane enemyPlane : enemyPlanes) {
for (Move move : getPossibleMoves(enemyPlane)) {
Plane simPlane = enemyPlane.simulateMove(move);
for (Point3D dest : range) {
if (dest.equals(simPlane.getPosition())) {
possibleHits++;
}
}
}
}
return possibleHits;
}
private boolean isOutside(Plane plane) {
return !plane.getPosition().isInArena(arenaSize);
}
}
```
[Answer]
# DumbPlanes
DumbPlanes try so hard to not fly into the walls, but they're not very smart about it and usually end up hitting the walls anyway. They also shoot occasionally, if only they knew what they're shooting at.
```
package Planes;
public class DumbPlanes extends PlaneControl {
public DumbPlanes(int arenaSize, int rounds) {
super(arenaSize, rounds);
}
@Override
public Move[] act() {
Move[] moves = new Move[2];
for (int i=0; i<2; i++) {
if (!myPlanes[i].isAlive()) {
moves[i] = new Move(new Direction("N"), false, false); // If we're dead we just return something, it doesn't matter anyway.
continue;
}
Direction[] possibleDirections = myPlanes[i].getPossibleDirections(); // Let's see where we can go.
for (int j=0; j<possibleDirections.length*3; j++) {
int random = (int) Math.floor((Math.random()*possibleDirections.length)); // We don't want to be predictable, so we pick a random direction out of the possible ones.
if (myPlanes[i].getPosition().add(possibleDirections[random].getAsPoint3D()).isInArena(arenaSize)) { // We'll try not to fly directly into a wall.
moves[i] = new Move(possibleDirections[random], Math.random()>0.5, myPlanes[i].canShoot() && Math.random()>0.2);
continue; // I'm happy with this move for this plane.
}
// Uh oh.
random = (int) Math.floor((Math.random()*possibleDirections.length));
moves[i] = new Move(possibleDirections[random], Math.random()>0.5, myPlanes[i].canShoot() && Math.random()>0.2);
}
}
return moves;
}
@Override
public void newFight(int fightsFought, int myScore, int enemyScore) {
// Using information is for schmucks.
}
@Override
public void newOpponent(int fights) {
// What did I just say about information?
}
}
```
[Answer]
## Starfox (WIP - not yet working):
He doesn't actually utilize all the available moves. But he does try to shoot down enemies and not crash into walls.
```
package Planes;
import java.util.ArrayList;
import java.util.function.Predicate;
public class Starfox extends PlaneControl
{
public Starfox(int arenaSize, int rounds)
{
super(arenaSize, rounds);
}
private ArrayList<Point3D> dangerousPositions;
private ArrayList<Point3D> riskyPositions;
@Override
public Move[] act()
{
dangerousPositions = new ArrayList<>();
riskyPositions = new ArrayList<>();
// add corners as places to be avoided
dangerousPositions.add(new Point3D(0,0,0));
dangerousPositions.add(new Point3D(0,0,arenaSize-1));
dangerousPositions.add(new Point3D(0,arenaSize-1,0));
dangerousPositions.add(new Point3D(0,arenaSize-1,arenaSize-1));
dangerousPositions.add(new Point3D(arenaSize-1,0,0));
dangerousPositions.add(new Point3D(arenaSize-1,0,arenaSize-1));
dangerousPositions.add(new Point3D(arenaSize-1,arenaSize-1,0));
dangerousPositions.add(new Point3D(arenaSize-1,arenaSize-1,arenaSize-1));
for (Plane p : super.enemyPlanes)
{
for (Direction d : p.getPossibleDirections())
{
Point3D potentialPosition = new Point3D(p.getX(), p.getY(), p.getZ()).add(d.getAsPoint3D());
if (potentialPosition.isInArena(arenaSize))
{
riskyPositions.add(potentialPosition);
if (p.canShoot())
{
for (Point3D range : p.getShootRange())
{
riskyPositions.add(range.add(potentialPosition));
}
}
}
}
}
ArrayList<Move> moves = new ArrayList<>();
for (Plane p : myPlanes)
{
if (p.isAlive())
{
ArrayList<Direction> potentialDirections = new ArrayList<>();
for (Direction d : p.getPossibleDirections())
{
Point3D potentialPosition = new Point3D(p.getX(), p.getY(), p.getZ()).add(d.getAsPoint3D());
if (potentialPosition.isInArena(arenaSize))
{
potentialDirections.add(d);
}
}
// remove dangerous positions from flight plan
potentialDirections.removeIf(new Predicate<Direction>()
{
@Override
public boolean test(Direction test)
{
boolean result = false;
for (Point3D compare : dangerousPositions)
{
if (p.getPosition().add(test.getAsPoint3D()).equals(compare))
{
result = true;
}
}
return result && potentialDirections.size() > 0;
}
});
// remove positions with no future from flight plan
potentialDirections.removeIf(new Predicate<Direction>()
{
@Override
public boolean test(Direction test)
{
boolean hasFuture = false;
for (Direction compare : p.getPossibleDirections())
{
Plane future = new Plane(arenaSize, 0, compare, p.getPosition().add(compare.getAsPoint3D()));
if (future!=null && future.getDirection()!=null) {
for (Direction d : future.getPossibleDirections())
{
if (future.getPosition().add(d.getAsPoint3D()).isInArena(arenaSize))
{
hasFuture = true;
break;
}
}
}
}
return !hasFuture;
}
});
// remove risky positions from flight plan
potentialDirections.removeIf(new Predicate<Direction>()
{
@Override
public boolean test(Direction test)
{
boolean result = false;
for (Point3D compare : riskyPositions)
{
if (p.getPosition().add(test.getAsPoint3D()).equals(compare))
{
result = true;
}
}
return result && potentialDirections.size() > 0;
}
});
// check for targets
Direction best = null;
if (p.canShoot())
{
int potentialHits = 0;
for (Direction d : potentialDirections)
{
Plane future = new Plane(arenaSize, 0, d, p.getPosition().add(d.getAsPoint3D()));
for (Point3D t : future.getShootRange())
{
int targets = 0;
for (Plane e : super.enemyPlanes)
{
for (Direction s : e.getPossibleDirections())
{
Plane target = new Plane(arenaSize, 0, s, e.getPosition().add(s.getAsPoint3D()));
if (target.getPosition().equals(t))
{
targets++;
}
}
}
if (targets > potentialHits)
{
best = d;
potentialHits = targets;
}
}
}
}
if (best == null)
{
if (potentialDirections.size() > 0) {
best = potentialDirections.get((int) Math.floor(Math.random() * potentialDirections.size()));
} else {
best = new Direction("N");
}
}
moves.add(new Move(best, true, false));
dangerousPositions.add(p.getPosition().add(best.getAsPoint3D()));
}
else
{
// this plane is dead, not much to do but go hide in corner
moves.add(new Move(new Direction("N"), false, false));
}
}
Move[] movesArr = {moves.get(0), moves.get(1)};
return movesArr;
}
@Override
public void newFight(int fightsFought, int myScore, int enemyScore)
{
// Using information is for schmucks.
}
@Override
public void newOpponent(int fights)
{
// What did I just say about information?
}
}
```
[Answer]
# DangerZoner
* Written in Python and interfaces with the non-Java code wrapper written by Sparr.
* Does all its math in pure Python and is completely unoptimized. A bit slow.
* Highly configurable and extensible.
* Does very well against past submissions. Wins **2:1** fights for every one lost against `Crossfire` or `PredictAndAvoid`, and wins **98+%** of all fights against other contenders.
### Includes its own optional visualization tool:
Fighting `Crossfire`/`PredictAndAvoid`, with the eponymous danger zone ratings visualized in the surrounding volume:
[![Video of four planes dogfighting in two rounds with a coloured voxel grid morphing around them, part 1.](https://i.stack.imgur.com/gV9km.gif)](https://i.stack.imgur.com/gV9km.gif)
[![Video of four planes dogfighting in two rounds with a coloured voxel grid morphing around them, part 2.](https://i.stack.imgur.com/WwpjR.gif)](https://i.stack.imgur.com/WwpjR.gif)
* Visualized using `nipy_spectral` colourmap from `matplotlib`.
More dangerous coordinates are rendered using colours closer to red/white in the electromagnetic spectrum, and are drawn with bigger dots.
* Danger: Blue < Green < Yellow < Red < Light Grey
### Performance:
1000 rounds with the eight top other algorithms on the leaderboard:
```
SCORE: DumbPlanes: 0 Dangerzoner: 1000
SCORE: Crossfire: 132 Dangerzoner: 367
SCORE: PredictAndAvoid: 165 Dangerzoner: 465
SCORE: Wee: 0 Dangerzoner: 1000
SCORE: Whirligig: 0 Dangerzoner: 989
SCORE: MoveAndShootPlane: 0 Dangerzoner: 1000
SCORE: Starfox: 4 Dangerzoner: 984
SCORE: DumbPy: 0 Dangerzoner: 1000
```
```
SCORES:
DumbPlanes: 2 points.
Crossfire: 12 points.
PredictAndAvoid: 14 points.
Wee: 10 points.
Whirligig: 8 points.
MoveAndShootPlane: 6 points.
Starfox: 4 points.
DumbPy: 0 points.
Dangerzoner: 16 points.
THE OVERALL WINNER(S): Dangerzoner
With 16 points.
```
### Code:
```
#!/usr/bin/env python3
"""
DangerZoner
Each turn:
1) Make a list of all possible locations to move to, explicitly excluding suicidal positions that will collide with the walls, an ally, or an ally's bullet.
2) Rate each possible location using heuristics that estimate the approximate danger in that zone, accounting for the following factors:
-Proximity to walls. (Manoeuvring constrictions and risk of collision.)
-Proximity to fronts of planes. (Risk of mid-air collisions.)
-High distance from enemy planes. (Risk of enemies easily turning to shoot.)
-Intersection with all enemy attack vectors. (Explicit safety on the next round.)
-Proximity to enemy forward vectors. (Approximate probability of being targeted in upcoming rounds.)
3) If certain respective thresholds are met in the possible moves' danger ratings, then do the following if possible:
-Take a potshot at a random position that an enemy might move to next turn (but never shoot an ally).
-Take a potshot at an extrapolated position that an enemy will likely move to next turn if they keep up their current rate of turn (but never shoot an ally).
-Turn to pursue the closest enemy.
-Move randomly to confound enemy predictive mechanisms. (Disabled since implementing explicit enemy attack vectors in danger zone calculation.)
4) If none of those thresholds are met, then choose the move rated as least dangerous.
"""
import math, random, functools, sys
#import NGrids
NGrids = lambda: None
class NSpace(object):
"""Object for representing an n-dimensional space parameterized by a list of extents in each dimension."""
def __init__(self, dimensions):
self.dimensions = tuple(dimensions)
def check_coordshape(self, coord):
return len(coord) == len(self.dimensions)
def enforce_coordshape(self, coord):
if not self.check_coordshape(coord):
raise ValueError(f"Attempted to access {len(coord)}-coordinate point from {len(self.dimensions)}-coordinate space: {coord}")
def check_coordrange(self, coord):
return all((0 <= c <= b) for c, b in zip(coord, self.dimensions))
def enforce_coordrange(self, coord):
if not self.check_coordrange(coord):
raise ValueError(f"Attempted to access coordinate point out of range of {'x'.join(str(d) for d in self.dimensions)} space: {coord}")
def check_coordtype(self, coord):
return True
def enforce_coordtype(self, coord):
if not self.check_coordtype(coord):
raise TypeError(f"Attempted to access grid point with invalid coordinates for {type(self).__name__}(): {coord}")
def enforce_coord(self, coord):
for f in (self.enforce_coordshape, self.enforce_coordrange, self.enforce_coordtype):
f(coord)
def coords_grid(self, step=None):
if step is None:
step = tuple(1 for i in self.dimensions)
self.enforce_coord(step)
counts = [math.ceil(d/s) for d, s in zip(self.dimensions, step)]
intervals = [1]
for c in counts:
intervals.append(intervals[-1]*c)
for i in range(intervals[-1]):
yield tuple((i//l)*s % (c*s) for s, l, c in zip(step, intervals, counts))
NGrids.NSpace = NSpace
def Pythagorean(*coords):
return math.sqrt(sum(c**2 for c in coords))
class Plane(object):
"""Object for representing a single dogfighting plane."""
def __init__(self, alive, coord, vec, cooldown=None, name=None):
self.alive = alive
self.set_alive(alive)
self.coord = coord
self.set_coord(coord)
self.vec = vec
self.set_vec(vec)
self.cooldown = cooldown
self.set_cooldown(cooldown)
self.name = name
def set_alive(self, alive):
self.lastalive = self.alive
self.alive = alive
def set_coord(self, coord):
self.lastcoord = self.coord
self.coord = coord
def set_vec(self, vec):
self.lastvec = self.vec
self.vec = vec
def set_cooldown(self, cooldown):
self.lastcooldown = self.cooldown
self.cooldown = cooldown
def update(self, alive=None, coord=None, vec=None, cooldown=None):
if alive is not None:
self.set_alive(alive)
if coord is not None:
self.set_coord(coord)
if vec is not None:
self.set_vec(vec)
if cooldown is not None:
self.set_cooldown(cooldown)
def get_legalvecs(self):
return getNeighbouringVecs(self.vec)
def get_legalcoords(self):
return {tuple(self.coord[i]+v for i, v in enumerate(vec)) for vec in self.get_legalvecs()}
def get_legalfutures(self):
return (lambda r: r.union((c, self.vec) for c, v in r))({(vecAdd(self.coord, vec),vec) for vec in self.get_legalvecs()})
class DangerZones(NGrids.NSpace):
"""Arena object for representing an n-dimensional volume with both enemy and allied planes in it and estimating the approximate safety/danger of positions within it. """
def __init__(self, dimensions=(13,13,13), walldanger=18.0, walldistance=3.5, wallexpo=2.0, walluniformity=5.0, planedanger=8.5, planeexpo=8.0, planeoffset=1.5, planedistance=15.0, planedistancedanger=2.0, planedistanceexpo=1.5, firedanger=9.0, collisiondanger=10.0, collisiondirectionality=0.6, collisiondistance=2.5, collisionexpo=0.2):
NGrids.NSpace.__init__(self, dimensions)
self.walldanger = walldanger
self.walldistance = walldistance
self.wallexpo = wallexpo
self.walluniformity = walluniformity
self.planedanger = planedanger
self.planeexpo = planeexpo
self.planeoffset = planeoffset
self.planedistance = planedistance
self.planedistancedanger = planedistancedanger
self.planedistanceexpo = planedistanceexpo
self.firedanger = firedanger
self.collisiondanger = collisiondanger
self.collisiondirectionality = collisiondirectionality
self.collisiondistance = collisiondistance
self.collisionexpo = collisionexpo
self.set_planes()
self.set_allies()
self.clear_expectedallies()
def filteractiveplanes(self, planes=None):
if planes is None:
planes = self.planes
return (p for p in planes if all((p.alive, p.coord, p.vec)))
def rate_walldanger(self, coord):
self.enforce_coordshape(coord)
return (lambda d: (max(d)*self.walluniformity+sum(d))/(self.walluniformity+1))((1-min(1, (self.dimensions[i]/2-abs(v-self.dimensions[i]/2))/self.walldistance)) ** self.wallexpo * self.walldanger for i, v in enumerate(coord))
def rate_planedanger(self, coord, planecoord, planevec):
for v in (planecoord, planevec, coord):
self.enforce_coordshape(v)
return max(0, (1 - vecAngle(planevec, vecSub(coord, vecSub(planecoord, vecMult(planevec, (self.planeoffset,)*len(self.dimensions)))) ) / math.pi)) ** self.planeexpo * self.planedanger
offsetvec = convertVecTrinary(planevec, length=self.planeoffset)
relcoord = [v-(planecoord[i]-offsetvec[i]) for i, v in enumerate(coord)]
nrelcoord = (lambda m: [(v/m if m else 0) for v in relcoord])(Pythagorean(*relcoord))
planevec = (lambda m: [(v/m if m else 0) for v in planevec])(Pythagorean(*planevec))
return max(0, sum(d*p for d, p in zip(planevec, nrelcoord))+2)/2 ** self.planeexpo * self.planedanger + min(1, Pythagorean(*relcoord)/self.planedistance) ** self.planedistanceexpo * self.planedistancedanger
def rate_planedistancedanger(self, coord, planecoord, planevec):
return Pythagorean(*vecSub(planecoord, coord))/self.planedistance ** self.planedistanceexpo * self.planedistancedanger
def rate_firedanger(self, coord, plane):
return (min(vecAngle(vecSub(coord, c), v) for c, v in plane.get_legalfutures()) < 0.05) * self.firedanger
def rate_collisiondanger(self, coord, planecoord, planevec):
if coord == planecoord:
return self.collisiondanger
offsetvec = tuple(p-c for p,c in zip(planecoord, coord))
return max(0, vecAngle(planevec, offsetvec)/math.pi)**self.collisiondirectionality * max(0, 1-Pythagorean(*offsetvec)/self.collisiondistance)**self.collisionexpo*self.collisiondanger
def set_planes(self, *planes):
self.planes = planes
def set_allies(self, *allies):
self.allies = allies
def rate_planesdanger(self, coord, planes=None):
if planes is None:
planes = {*self.planes}
return max((0, *(self.rate_planedanger(coord, planecoord=p.coord, planevec=p.vec) for p in self.filteractiveplanes(planes))))
def rate_planedistancesdanger(self, coord, planes=None):
if planes is None:
planes = {*self.planes}
return max((0, *(self.rate_planedistancedanger(coord, planecoord=p.coord, planevec=p.vec) for p in self.filteractiveplanes(planes))))
def rate_firesdanger(self, coord, planes=None):
if planes is None:
planes = {*self.planes}
return sum(self.rate_firedanger(coord, p) for p in self.filteractiveplanes(planes))
def rate_collisionsdanger(self, coord, pself=None, planes=None):
if planes is None:
planes = {*self.planes, *self.allies}
return max((0, *(self.rate_collisiondanger(coord , planecoord=p.coord, planevec=p.vec) for p in self.filteractiveplanes(planes) if p is not pself)))
def rate_sumdanger(self, coord, pself=None, planes=None):
return max((self.rate_walldanger(coord), self.rate_planesdanger(coord, planes=planes), self.rate_planedistancesdanger(coord, planes=planes), self.rate_firesdanger(coord, planes=planes), self.rate_collisionsdanger(coord, pself=pself, planes=planes)))
def get_expectedallies(self):
return {*self.expectedallies}
def clear_expectedallies(self):
self.expectedallies = set()
def add_expectedallies(self, *coords):
self.expectedallies.update(coords)
def get_expectedshots(self):
return {*self.expectedshots}
def clear_expectedshots(self):
self.expectedshots = set()
def add_expectedshots(self, *rays):
self.expectedshots.update(rays)
def tickturn(self):
self.clear_expectedallies()
self.clear_expectedshots()
def stringException(exception):
import traceback
return ''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))
try:
import matplotlib.pyplot, matplotlib.cm, mpl_toolkits.mplot3d, time
class PlottingDangerZones(DangerZones):
"""Arena object for calculating danger ratings and rendering 3D visualizations of the arena state and contents to both files and an interactive display on each turn."""
plotparams = {'dangersize': 80, 'dangersizebase': 0.2, 'dangersizeexpo': 2.0, 'dangeralpha': 0.2, 'dangerres': 1, 'dangervrange': (0, 10), 'dangercmap': matplotlib.cm.nipy_spectral, 'dangermarker': 'o', 'allymarker': 's', 'enemymarker': 'D', 'vectormarker': 'x', 'planesize': 60, 'vectorsize': 50, 'planecolour': 'black', 'deathmarker': '*', 'deathsize': 700, 'deathcolours': ('darkorange', 'red'), 'deathalpha': 0.65, 'shotlength': 4, 'shotcolour': 'darkviolet', 'shotstyle': 'dashed'}
enabledplots = ('enemies', 'allies', 'vectors', 'danger', 'deaths', 'shots', 'names')
def __init__(self, dimensions=(13,13,13), plotparams=None, plotautoturn=0, plotsavedir=None, enabledplots=None, disabledplots=None, tickwait=0.0, plotcycle=0.001, **kwargs):
DangerZones.__init__(self, dimensions, **kwargs)
self.figure = None
self.axes = None
self.frame = None
self.plotobjs = {}
self.plotshown = False
if plotparams:
self.set_plotparams(plotparams)
self.plotautoturn = plotautoturn
self.plotsavedir = plotsavedir
if enabledplots:
self.enabledplots = tuple(enabledplots)
if disabledplots:
self.enabledplots = tuple(m for m in self.enabledplots if m not in disabledplots)
self.tickwait = tickwait
self.plotcycle = plotcycle
self.lasttick = time.time()
def set_plotparams(self, plotparams):
self.plotparams = {**self.plotparams, **plotparams}
def prepare_plotaxes(self, figure=None, clear=True):
if self.figure is None and figure is None:
self.figure = matplotlib.pyplot.figure()
self.frame = 0
if self.axes is None:
self.axes = self.figure.add_subplot(projection='3d')
elif clear:
self.axes.clear()
for d, h in zip((self.axes.set_xlim, self.axes.set_ylim, self.axes.set_zlim), self.dimensions):
d(0, h)
return (self.figure, self.axes)
def plotter(kind):
def plotterd(funct):
def plott(self):
kws = dict(getattr(self, funct.__name__.replace('plot_', 'plotparams_'))())
if '*args' in kws:
args = tuple(kws.pop('*args'))
else:
args = tuple()
if False and funct.__name__ in self.plotobjs:
self.plotobjs[funct.__name__].set(**kws)
else:
self.plotobjs[funct.__name__] = getattr(self.axes, kind)(*args, **kws)
return plott
return plotterd
def plotparams_enemies(self):
r = {'xs': tuple(), 'ys': tuple(), 'zs': tuple(), 'marker': self.plotparams['enemymarker'], 's': self.plotparams['planesize'], 'c': self.plotparams['planecolour']}
planes = tuple(self.filteractiveplanes(self.planes))
if planes:
r['xs'], r['ys'], r['zs'] = zip(*(p.coord for p in planes))
return r
def plotparams_allies(self):
r = {'xs': tuple(), 'ys': tuple(), 'zs': tuple(), 'marker': self.plotparams['allymarker'], 's': self.plotparams['planesize'], 'c': self.plotparams['planecolour']}
planes = tuple(self.filteractiveplanes(self.allies))
if planes:
r['xs'], r['ys'], r['zs'] = zip(*(p.coord for p in planes))
return r
def plotparams_vectors(self):
r = {'xs': tuple(), 'ys': tuple(), 'zs': tuple(), 'marker': self.plotparams['vectormarker'], 's': self.plotparams['vectorsize'], 'c': self.plotparams['planecolour']}
planes = tuple(self.filteractiveplanes(self.allies+self.planes))
if planes:
r['xs'], r['ys'], r['zs'] = zip(*(vecAdd(p.coord, p.vec) for p in planes))
return r
def plotparams_danger(self):
r = {'xs': tuple(), 'ys': tuple(), 'zs': tuple(), 'marker': self.plotparams['dangermarker'], 'cmap': self.plotparams['dangercmap'], 'alpha': self.plotparams['dangeralpha']}
coords = tuple(self.coords_grid((self.plotparams['dangerres'],)*len(self.dimensions)))
r['xs'], r['ys'], r['zs'] = zip(*coords)
r['c'] = tuple(self.rate_sumdanger(c) for c in coords)
m = max(r['c'])
r['s'] = tuple((d/m)**self.plotparams['dangersizeexpo']*self.plotparams['dangersize']+self.plotparams['dangersizebase'] for d in r['c'])
if self.plotparams['dangervrange']:
r['vmin'], r['vmax'] = self.plotparams['dangervrange']
return r
def plotparams_deaths(self):
r = {'xs': tuple(), 'ys': tuple(), 'zs': tuple(), 'marker': self.plotparams['deathmarker'], 's': self.plotparams['deathsize'], 'c': self.plotparams['deathcolours'][0], 'linewidths': self.plotparams['deathsize']/180, 'edgecolors': self.plotparams['deathcolours'][1], 'alpha': self.plotparams['deathalpha']}
deaths = tuple(p.lastcoord for p in self.planes+self.allies if p.lastalive and not p.alive)
if deaths:
r['xs'], r['ys'], r['zs'] = zip(*deaths)
return r
def plotparams_shots(self):
r = {'length': self.plotparams['shotlength'], 'linestyles': self.plotparams['shotstyle'], 'color': self.plotparams['shotcolour'], 'arrow_length_ratio': 0.0, '*args': []}
planes = tuple(p for p in self.filteractiveplanes(self.allies+self.planes) if not (p.lastcooldown is None or p.cooldown is None) and (p.cooldown > p.lastcooldown))
if planes:
for s in zip(*(p.coord for p in planes)):
r['*args'].append(s)
for s in zip(*(p.vec for p in planes)):
r['*args'].append(s)
else:
for i in range(6):
r['*args'].append(tuple())
return r
@plotter('scatter')
def plot_enemies(self):
pass
@plotter('scatter')
def plot_allies(self):
pass
@plotter('scatter')
def plot_vectors(self):
pass
@plotter('scatter')
def plot_danger(self):
pass
@plotter('scatter')
def plot_deaths(self):
pass
@plotter('quiver')
def plot_shots(self):
pass
def plot_names(self):
if 'plot_names' in self.plotobjs:
pass
self.plotobjs['plot_names'] = [self.axes.text(*p.coord, s=f"{p.name}") for i, p in enumerate(self.filteractiveplanes(self.allies+self.planes))]
def plotall(self):
for m in self.enabledplots:
getattr(self, f'plot_{m}')()
def updateallplots(self):
self.prepare_plotaxes()
self.plotall()
if self.plotautoturn:
self.axes.view_init(30, -60+self.frame*self.plotautoturn)
matplotlib.pyplot.draw()
if self.plotsavedir:
import os
os.makedirs(self.plotsavedir, exist_ok=True)
self.figure.savefig(os.path.join(self.plotsavedir, f'{self.frame}.png'))
self.frame += 1
if not self.plotshown:
matplotlib.pyplot.ion()
matplotlib.pyplot.show()#block=False)
self.plotshown = True
def tickturn(self):
DangerZones.tickturn(self)
self.updateallplots()
matplotlib.pyplot.pause(max(self.plotcycle, self.lasttick+self.tickwait-time.time()))
self.lasttick = time.time()
except Exception as e:
print(f"Could not define matplotlib rendering dangerzone handler:\n{stringException(e)}", file=sys.stderr)
def vecEquals(vec1, vec2):
return tuple(vec1) == tuple(vec2)
def vecAdd(*vecs):
return tuple(sum(p) for p in zip(*vecs))
def vecSub(vec1, vec2):
return tuple(a-b for a, b in zip(vec1, vec2))
def vecMult(*vecs):
return tuple(functools.reduce(lambda a, b: a*b, p) for p in zip(*vecs))
def vecDiv(vec1, vec2):
return tuple(a-b for a, b in zip(vec1, vec2))
def vecDotProduct(*vecs):
return sum(vecMult(*vecs))
#return sum(d*p for d, p in zip(vec1, vec2))
def vecAngle(vec1, vec2):
try:
if all(c == 0 for c in vec1) or all(c == 0 for c in vec2):
return math.nan
return math.acos(max(-1, min(1, vecDotProduct(vec1, vec2)/Pythagorean(*vec1)/Pythagorean(*vec2))))
except Exception as e:
raise ValueError(f"{e!s}: {vec1} {vec2}")
def convertVecTrinary(vec, length=1):
return tuple((max(-length, min(length, v*math.inf)) if v else v) for v in vec)
def getNeighbouringVecs(vec):
vec = convertVecTrinary(vec, length=1)
return {ve for ve in (tuple(v+(i//3**n%3-1) for n, v in enumerate(vec)) for i in range(3**len(vec))) if all(v in (-1,0,1) for v in ve) and any(v and v==vec[i] for i, v in enumerate(ve))}
def getVecRotation(vec1, vec2):
#Just do a cross product/perpendicular to tangential plane/normal?
pass
def applyVecRotation(vec, rotation):
pass
class DangerZoner(Plane):
"""Dogfighting plane control object."""
def __init__(self, arena, snipechance=0.60, snipechoices=3, firesafety=7.5, chasesafety=5.0, jinkdanger=math.inf, jink=0, name=None):
Plane.__init__(self, True, None, None)
self.arena = arena
self.lookahead = 1
self.snipechance = snipechance
self.snipechoices = snipechoices
self.firesafety = firesafety
self.chasesafety = chasesafety
self.jinkdanger = jinkdanger
self.jink = jink
self.vec = None
self.name = name
def get_enemies(self):
return (p for p in self.arena.filteractiveplanes(self.arena.planes))
def get_vecsuicidal(self, vec, coord=None, steps=5):
if coord is None:
coord = self.coord
if all(3 < c < self.arena.dimensions[i]-3 for i, c in enumerate(coord)):
return False
if not all(0 < c < self.arena.dimensions[i] for i, c in enumerate(coord)):
return True
elif steps >= 0:
return all(self.get_vecsuicidal(v, coord=vecAdd(coord, vec), steps=steps-1) for v in getNeighbouringVecs(vec))
return False
def get_sanevecs(self):
legalvecs = self.get_legalvecs()
s = {vec for vec in legalvecs if vecAdd(self.coord, vec) not in self.arena.get_expectedallies() and not any(vecAngle(vecSub(vecAdd(self.coord, vec), sc), sv) < 0.05 for sc, sv in self.arena.get_expectedshots()) and not self.get_vecsuicidal(vec, coord=vecAdd(self.coord, vec))}
if not s:
return legalvecs
raise Exception()
return s
def rate_vec(self, vec, lookahead=None):
if lookahead is None:
lookahead = self.lookahead
return self.arena.rate_sumdanger(tuple(c+v*lookahead for v, c in zip(vec, self.coord)), pself=self)
def get_validshots(self, snipe=True):
if snipe and random.random() < self.snipechance:
enemypossibilities = set.union(*({vecAdd(p.coord, p.vec)} if not p.lastvec or vecEquals(p.vec, p.lastvec) else {vecAdd(p.coord, ve) for ve in sorted(p.get_legalvecs(), key=lambda v: -vecAngle(v, p.lastvec))[:self.snipechoices]} for p in self.get_enemies()))
else:
enemypossibilities = set().union(*(p.get_legalcoords() for p in self.get_enemies()))
validshots = []
if self.cooldown:
return validshots
for vec in self.get_sanevecs():
coord = tuple(c + v for c, v in zip(self.coord, vec))
if any(vecAngle(tuple(n-v for n, v in zip(t, self.coord)), self.vec) < 0.1 for t in enemypossibilities if t != self.coord) and not any(vecAngle(vecSub(a, coord), self.vec) < 0.05 for a in self.arena.get_expectedallies()):
validshots.append({'vec': vec, 'turn': False, 'fire': True})
if any(vecAngle(tuple(n-v for n, v in zip(t, self.coord)), vec) < 0.1 for t in enemypossibilities if t != self.coord) and not any(vecAngle(vecSub(a, coord), vec) < 0.05 for a in self.arena.get_expectedallies()):
validshots.append({'vec': vec, 'turn': True, 'fire': True})
if snipe and not validshots:
validshots = self.get_validshots(snipe=False)
return validshots
def get_chase(self):
enemydirs = {vecSub(vecAdd(p.coord, p.vec), self.coord) for p in self.get_enemies()}
paths = sorted(self.get_sanevecs(), key=lambda vec: min([vecAngle(vec, e) for e in enemydirs if not all(v == 0 for v in e)]+[math.inf]))
if paths:
return paths[0]
def get_move(self):
if not self.alive:
return {'vec': (1,1,1), 'turn': False, 'fire': False}
fires = self.get_validshots()
if fires:
fires = sorted(fires, key=lambda d: self.rate_vec(d['vec']))
if self.rate_vec(fires[0]['vec']) <= self.firesafety:
return fires[0]
vec = self.get_chase()
if vec is None or self.rate_vec(vec) > self.chasesafety:
vec = sorted(self.get_sanevecs(), key=self.rate_vec)
vec = vec[min(len(vec)-1, random.randint(0,self.jink)) if self.rate_vec(vec[0]) > self.jinkdanger else 0]
return {'vec': vec, 'turn': True, 'fire': False}
def move(self):
move = self.get_move()
coord = vecAdd(self.coord, move['vec'])
self.arena.add_expectedallies(coord)
if move['fire']:
self.arena.add_expectedshots((coord, move['vec'] if move['turn'] else self.vec))
return move
VecsCarts = {(0,-1):'N', (0,1):'S', (1,1):'E', (1,-1):'W', (2,1):'U', (2,-1):'D'}
def translateCartVec(cartesian):
vec = [0]*3
for v,l in VecsCarts.items():
if l in cartesian:
vec[v[0]] = v[1]
return tuple(vec)
def translateVecCart(vec):
vec = convertVecTrinary(vec)
return ''.join(VecsCarts[(i,v)] for i, v in enumerate(vec) if v != 0)
def parsePlaneState(text):
return (lambda d: {'alive':{'alive': True, 'dead': False}[d[0]], 'coord':tuple(int(c) for c in d[1:4]), 'vec':translateCartVec(d[4]), 'cooldown': int(d[5])})(text.split(' '))
def encodePlaneInstruction(vec, turn, fire):
return f"{translateVecCart(vec)} {int(bool(turn))!s} {int(bool(fire))!s}"
class CtrlReceiver:
"""Object for interacting through STDIN and STDOUT in a dogfight with an arena, controlled planes, and enemy planes."""
def __init__(self, logname='danger_log.txt', arenatype=DangerZones, arenaconf=None, planetype=DangerZoner, planeconf=None, enemyname='Enemy', stdin=sys.stdin, stdout=sys.stdout):
self.logname = logname
self.arenatype = arenatype
self.arenaconf = dict(arenaconf) if arenaconf else dict()
self.planetype = planetype
self.planeconf = dict(planeconf) if planeconf else dict()
self.enemyname = enemyname
self.stdin = stdin
self.stdout = stdout
self.log = open('danger_log.txt', 'w')
def __enter__(self):
return self
def __exit__(self, *exc):
self.log.__exit__()
def getin(self):
l = self.stdin.readline()
self.log.write(f"IN: {l}")
return l
def putout(self, content):
self.log.write(f"OUT: {content}\n")
print(content, file=self.stdout, flush=True)
def logout(self, content):
self.log.write(f"MSG: {content}\n")
def logerr(self, content):
self.log.write(f"ERR: {content}\n")
def run_setup(self, arenasize, rounds):
self.arena = self.arenatype(dimensions=(arenasize,)*3, **self.arenaconf)
self.planes = [self.planetype(arena=self.arena, name=f"{self.planetype.__name__} #{i}", **self.planeconf) for i in range(2)]
self.arena.set_planes(*(Plane(True, None, None, name=f"{self.enemyname} #{i}") for i in range(2)))
self.arena.set_allies(*self.planes)
def run_move(self):
self.arena.tickturn()
for p in self.planes:
p.update(**parsePlaneState(self.getin()))
for p in self.arena.planes:
p.update(**parsePlaneState(self.getin()))
for p in self.planes:
self.putout(encodePlaneInstruction(**p.move()))
def run(self):
line = ''
while not line.startswith('NEW CONTEST '):
line = self.getin()
self.run_setup(arenasize=int(line.split(' ')[2])-1, rounds=None)
while True:
line = self.getin()
if line.startswith('NEW TURN'):
self.run_move()
if True and __name__ == '__main__' and not sys.flags.interactive:
import time
DoPlot = False
#Use the arena object that visualizes progress every turn.
DangerPlot = True
#Compute and render a voxel cloud of danger ratings within the arena each turn if visualizing it.
SparseDangerPlot = False
#Use a lower resolution for the voxel cloud if visualizing danger ratings.
TurntablePlot = True
#Apply a fixed animation to the interactive visualization's rotation if visualizing the arena.
with CtrlReceiver(logname='danger_log.txt', arenatype=PlottingDangerZones if DoPlot else DangerZones, arenaconf=dict(disabledplots=None if DangerPlot else ('danger'), plotparams=dict(dangerres=2) if SparseDangerPlot else dict(dangeralpha=0.1), plotautoturn=1 if TurntablePlot else 0, plotsavedir=f'PngFrames') if DoPlot else None, planetype=DangerZoner) as run:
try:
run.run()
except Exception as e:
run.logerr(stringException(e))
```
] |
[Question]
[
Inspired by...
>
> [Networking - How can I work out how many IP addresses there are in a given range?](https://softwareengineering.stackexchange.com/questions/241402/how-can-i-work-out-how-many-ip-addresses-there-are-in-a-given-range)
>
>
>
Write a program or function that takes two strings as input, each being an IPv4 address expressed in standard dotted notation and outputs or returns the number of IP addresses covered by this range, including the two IP addresses input.
* You must not use any external code, libraries or services designed to parse an IP address. (Other string processing standard library functions are acceptable.)
* All 2^32 IP addresses are equal. No distinction is made to broadcast, class E, etc.
* Normal code-golf rules apply.
For example:
```
"0.0.0.0","255.255.255.255" returns 4294967296.
"255.255.255.255","0.0.0.0" also returns 4294967296.
"1.2.3.4","1.2.3.4" returns 1.
"56.57.58.59","60.61.62.63" returns 67372037.
"1","2" is invalid input. Your code may do anything you like.
```
[Answer]
# GolfScript, 20 bytes
```
~]7/${2%256base}/)\-
```
[Try it online.](http://golfscript.apphb.com/?c=OyAiNTYuNTcuNTguNTkgNjAuNjEuNjIuNjMiICMgU2ltdWxhdGUgaW5wdXQgZnJvbSBTVERJTi4KCn5dNy8kezIlMjU2YmFzZX0vKVwt)
### Test cases
```
$ echo 0.0.0.0 255.255.255.255 | golfscript range.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | golfscript test.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | golfscript test.gs
1
$ echo 56.57.58.59 60.61.62.63 | golfscript test.gs
67372037
```
### How it works
```
~] # Evaluate and collect into an array.
#
# “.” duplicates, so for "5.6.7.8 1.2.3.4", this leaves
# [ 5 5 6 6 7 7 8 1 1 2 2 3 3 4 ] on the stack.
#
7/ # Split into chunks of length 7: [ [ 5 5 6 6 7 7 8 ] [ 1 1 2 2 3 3 4 ] ]
$ # Sort the array of arrays: [ [ 1 1 2 2 3 3 4 ] [ 5 5 6 6 7 7 8 ] ]
{ # For each array:
2% # Extract every second element. Example: [ 1 2 3 4 ]
256base # Convert the IP into an integer by considering it a base 256 number.
}/ #
) # Add 1 to the second integer.
\- # Swap and subtract. Since the integers were sorted, the result is positive.
```
[Answer]
# Python 2 - 106
See it [here](http://repl.it/TWl/1).
```
def a():x=map(int,raw_input().split("."));return x[0]*2**24+x[1]*2**16+x[2]*2**8+x[3]
print abs(a()-a())+1
```
**Example Input**
>
> 0.0.0.0
>
> 0.0.0.255
>
>
>
**Example Output**
>
> 256
>
>
>
[Answer]
# CJam - 15
```
{r'./256b}2*-z)
```
Try it at <http://cjam.aditsu.net/>
Thanks Dennis, wow, I don't know how to get the best out of my own language :p
[Answer]
# Pure bash, 66 bytes
```
p()(printf %02x ${1//./ })
r=$[0x`p $1`-0x`p $2`]
echo $[1+${r/-}]
```
Notes:
* Defines a function `p` that is passed a dotted decimal IP address, and outputs the hex representation of that address:
+ `${1//./ }` is a parameter expansion that replaces `.` with in the IP address passed to `p()`
+ The `printf` is mostly self explanatory. Since there is only one format specifier `%02x` and four remaining args, the format specifier is reused for each remaining arg, effectively concatenating the 2 hex digits of each of the 4 octets together
* `$[]` causes arithmetic expansion. We do a basic subtraction, and assign to the variable `r`
* `${r/-}` is a parameter expansion to remove a possible `-` character - effectively abs()
* Display 1 + the absolute difference to give the range.
Output:
```
$ ./iprangesize.sh 0.0.0.0 255.255.255.255
4294967296
$ ./iprangesize.sh 255.255.255.255 0.0.0.0
4294967296
$ ./iprangesize.sh 1.2.3.4 1.2.3.4
1
$ ./iprangesize.sh 56.57.58.59 60.61.62.63
67372037
$ ./iprangesize.sh 1 2
2
$
```
[Answer]
## Python 2.7 - ~~96~~ ~~91~~ ~~90~~ 87
Made a function.
```
f=lambda a:reduce(lambda x,y:x*256+int(y),a.split("."),0)
p=lambda a,b:abs(f(a)-f(b))+1
```
Usage:
```
>>> p("1.2.3.4","1.2.3.5")
2
```
**Edit:** Removed unnecessary `int()` from `f` function. Thanks to isaacg
**Edit2:** Removed `LF` at the end of file (thanks to @Rusher) and removed `map()` at cost of `reduce()` initializer (thanks to @njzk2)
[Answer]
# CoffeeScript - ~~94~~, ~~92~~, ~~79~~, 72
```
I=(a)->a.split(".").reduce((x,y)->+y+x*256)
R=(a,b)->1+Math.abs I(b)-I a
```
**Un-golfed**:
```
I = ( a ) ->
return a.split( "." ).reduce( ( x, y ) -> +y + x * 256 )
R = ( a, b ) ->
return 1 + Math.abs I( b ) - I( a )
```
**Equivalent JavaScript**:
```
function ip2long( ip_str )
{
var parts = ip_str.split( "." );
return parts.reduce( function( x, y ) {
return ( +y ) + x * 256; //Note: the unary '+' prefix operator casts the variable to an int without the need for parseInt()
} );
}
function ip_range( ip1, ip2 )
{
var ip1 = ip2long( ip1 );
var ip2 = ip2long( ip2 );
return 1 + Math.abs( ip2 - ip1 );
}
```
[Try it online](http://coffeescript.org/#try%3aI%3D(a)-%3Ea.split(%22.%22).reduce((x%2Cy)-%3E%2By%2Bx%2a256)%0AR%3D(a%2Cb)-%3E1%2BMath.abs%20I(b)-I%20a%0A%0Atest%20%3D%20%5B%0A%20%20%20%20%5B%20%220.0.0.0%22%2C%20%22255.255.255.255%22%2C%204294967296%20%5D%2C%0A%20%20%20%20%5B%20%22255.255.255.255%22%2C%20%220.0.0.0%22%2C%204294967296%20%5D%2C%0A%20%20%20%20%5B%20%221.2.3.4%22%2C%20%221.2.3.4%22%2C%201%20%5D%2C%0A%20%20%20%20%5B%20%2256.57.58.59%22%2C%20%2260.61.62.63%22%2C%2067372037%20%5D%2C%0A%20%20%20%20%5B%20%221%22%2C%20%222%22%2C%202%20%5D%0A%5D%0A%0Apass%20%3D%20yes%0A%0Afor%20x%20in%20test%0A%20%20%20%20pass%20%3D%20pass%20and%20R(%20x%5B0%5D%2C%20x%5B1%5D%20)%20is%20x%5B2%5D%0A%0Aalert%20if%20pass%20then%20%22All%20tests%20passed.%22%20else%20%22Something%20went%20wrong.%22).
[Answer]
## GolfScript, 27 bytes
```
' '/{'.'/{~}%256base}/-abs)
```
Examples:
```
$ echo 0.0.0.0 255.255.255.255 | ruby golfscript.rb iprange.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | ruby golfscript.rb iprange.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | ruby golfscript.rb iprange.gs
1
$ echo 56.57.58.59 60.61.62.63 | ruby golfscript.rb iprange.gs
67372037
```
[Answer]
# Perl, 43 bytes
```
#!perl -pa
$_=1+abs${\map{$_=vec eval,0,32}@F}-$F[0]
```
Counting the shebang as two bytes.
Sample Usage:
```
$ echo 0.0.0.0 255.255.255.255 | perl count-ips.pl
4294967296
$ echo 255.255.255.255 0.0.0.0 | perl count-ips.pl
4294967296
$ echo 56.57.58.59 60.61.62.63 | perl count-ips.pl
67372037
```
---
**Notes**
* `vec eval,0,32` is a drop-in for `ip2long`. Perl allows character literals to be expressed as their ordinal prefixed with a `v`, for example `v0` can be used for the null char. These can also be chained together, for example `v65.66.67.68` → `ABCD`. When three or more values are present, the initial `v` is unnecessary. The `vec` function interprets a string as an integer array, each cell having the specified number of bits (here, 32). `unpack N,eval` would have worked equally as well.
[Answer]
# dc, 61 characters
```
?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p
```
I think it's pretty amazing that this can be solved with dc at all since it has no ability to parse strings. The trick is that 192.168.123.185 goes on the stack as
```
.185
.123
192.168
```
and `dXIr^*` shifts the decimal point right as many fraction digits as there are and it even works for .100.
```
$ echo 56.57.58.59 60.61.62.63 | dc -e '?[dXIr^*rdXIr^*256*+r1~dXIr^*r256*+65536*+]dspxsalpxla-d*v1+p'
67372037.00
```
Subtract a character if you let the input already be on the stack.
[Answer]
# Powershell - ~~112~~ ~~108~~ ~~92~~ 78 bytes
This is my first time golfing. Here goes nothing:
### Golfed (Old):
```
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f[int]$_};[uint32]$t};1+[math]::abs($a-$b)
```
### Golfed (new)
```
$a,$b=$args|%{$t='0x';$_-split'\.'|%{$t+="{0:X2}"-f+$_};[long]$t}|sort;1+$b-$a
```
### Ungolfed:
```
$a, $b = $args | % { #powershell's way of popping an array. In a larger array
#$a would equal the first member and $b would be the rest.
$t = '0x'; #string prefix of 0x for hex notation
$_ -split '\.' | % { #split by escaped period (unary split uses regex)
$t += "{0:X2}" -f +$_ #convert a dirty casted int into a hex value (1 octet)
};
[long]$t #and then cast to long
} | sort; #sort to avoid needing absolute value
1 + $b - $a #perform the calculation
```
### Usage
Save as file (in this case getipamount.ps1) and then call from the console
```
getipamount.ps1 255.255.255.255 0.0.0.0
```
[Answer]
# C# with LINQ - 139 bytes
(From 140 after applying Bob's suggestion.)
```
long f(params string[] a){return Math.Abs(a.Select(b=>b.Split('.').Select(long.Parse).Aggregate((c,d)=>c*256+d)).Aggregate((e,f)=>e-f))+1;}
```
Ungolfed....
```
long f(params string[] a) // params is shorter than two parameters.
{
return Math.Abs( // At the end, make all values +ve.
a.Select( // Go through both items in the array...
b => // Calling each one 'b'.
b.Split('.') // Separating out each "." separated byte...
.Select(long.Parse) // Converting them to a long.
.Aggregate((c, d) => c*256 + d) // Shift each byte along and add the next one.
)
.Aggregate((e,f) => e-f) // Find the difference between the two remaining values.
)+1; // Add one to the result of Math.Abs.
}
```
<https://dotnetfiddle.net/XPTDlt>
[Answer]
## JavaScript ES6 - 68 bytes
```
f=x=>prompt().split('.').reduce((a,b)=>+b+a*256);1+Math.abs(f()-f())
```
Try it with the console (press F12) of Firefox.
[Answer]
# Python 2.7, 104 bytes
```
y=lambda:map(int,input().split("."));a,b=y(),y();print sum(256**(3-i)*abs(a[i]-b[i])for i in range(4))+1
```
[Answer]
# Perl, 72 bytes
```
#!perl -ap
@a=map{unpack N,pack C4,split/\./,$_}@F;$_=abs($a[1]-$a[0])+1
```
Usage:
```
$ echo 10.0.2.0 10.0.3.255 | perl ip-range.pl
512$
```
This is already longer than [primo's Perl program](https://codegolf.stackexchange.com/a/28782/4065), so not too interesting.
# Perl, 119 bytes, for obsolete IP address format
```
#!perl -ap
sub v(){/^0/?oct:$_}@a=map{$m=3;@p=split/\./,$_;$_=pop@p;$s=v;$s+=v<<8*$m--for@p;$s}@F;$_=abs($a[1]-$a[0])+1
```
Usage:
```
$ echo 10.0.2.0 10.0.3.255 | perl ip-obsolete.pl
512$
$ echo 10.512 10.1023 | perl ip-obsolete.pl
512$
$ echo 0xa.0x200 012.01777 | perl ip-obsolete.pl
512$
```
This program accepts the obsolete format for IP addresses! This includes addresses with 1, 2, or 3 parts, or with hexadecimal or octal parts. Quoting the [inet\_addr(3)](http://www.openbsd.org/cgi-bin/man.cgi?query=inet_addr&apropos=0&sektion=0&manpath=OpenBSD%20Current&arch=i386&format=html) manual page,
>
> Values specified using dot notation take one of the following forms:
>
>
>
> ```
> a.b.c.d
> a.b.c
> a.b
> a
>
> ```
>
> ... When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. ... When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the rightmost three bytes of the network address. ... When only one part is given, the value is stored directly in the network address without any byte rearrangement.
>
>
> All numbers supplied as ``parts'' in a dot notation may be decimal, octal, or hexadecimal, as specified in the C language (i.e., a leading 0x or 0X implies hexadecimal; a leading 0 implies octal; otherwise, the number is interpreted as decimal).
>
>
>
Most programs no longer accept this obsolete format, but `ping 0177.1` still worked in OpenBSD 5.5.
[Answer]
# PHP, ~~138~~ 110 bytes
```
<?php
function d($a,$b){foreach(explode('.',"$a.$b")as$i=>$v){$r+=$v*(1<<24-$i%4*8)*($i<4?1:-1);}return 1+abs($r);}
// use it as
d('0.0.0.0','255.255.255.255');
```
[Answer]
# Mathematica 9, 108 bytes
```
c[f_,s_]:=1+First@Total@MapIndexed[#1*256^(4-#2)&,First@Abs@Differences@ToExpression@StringSplit[{f,s},"."]]
```
Ungolfed:
```
countIpAddresses[first_, second_] := Module[{digitArrays, differences},
(* Split the strings and parse them into numbers.
Mathematica automatically maps many/most of its functions across/
through lists *)
digitArrays = ToExpression[StringSplit[{first, second}, "."]];
(* Find the absolute value of the differences of the two lists,
element-wise *)
differences = Abs[Differences[digitArrays]];
(* differences looks like {{4, 4, 4, 4}} right now,
so take the first element *)
differences = First[differences];
(* now map a function across the differences,
taking the nth element (in code, '#2') which we will call x (in
code, '#1') and setting it to be equal to (x * 256^(4-n)).
To do this we need to track the index, so we use MapIndexed.
Which is a shame,
because Map can be written '/@' and is generally a huge character-
saver. *)
powersOf256 = MapIndexed[#1*256^(4 - #2) &, differences];
(* now we essentially have a list (of singleton lists,
due to MapIndexed quirk) which represents the digits of a base-256,
converted to decimal form.
Example: {{67108864},{262144},{1024},{4}}
We add them all up using Total,
which will give us a nested list as such: {67372036}
We need to add 1 to this result no matter what. But also,
to be fair to the challenge, we want to return a number -
not a list containing one number.
So we take the First element of our result. If we did not do this,
we could chop off 6 characters from our code. *)
1 + First[Total[powersOf256]]
]
```
[Answer]
# PHP, 46 Bytes
```
<?=abs(ip2long($argv[1])-ip2long($argv[2]))+1;
```
[Try it online!](https://tio.run/nexus/php#@29jb5uYVKyRWWCUk5@XrqGSWJReFm0Yq6mLKmIUq6mpbWj9//9/UzM9U3M9Uws9U8v/ZgZ6ZoZ6ZkZ6ZsYA "PHP – TIO Nexus")
[ip2long](http://php.net/manual/en/function.ip2long.php)
[Answer]
## C# - 135
```
long f(string x,string y){Func<string,long>b=s=>s.Split('.').Select((c,i)=>long.Parse(c)<<(3-i)*8).Sum();return Math.Abs(b(x)-b(y))+1;}
```
Properly formatted
```
long g(string x, string y) {
Func<string, long> b = s => s.Split('.').Select((c, i) => long.Parse(c) << (3 - i) * 8).Sum();
return Math.Abs(b(x) - b(y)) + 1;
}
```
<https://dotnetfiddle.net/Q0jkdA>
[Answer]
# Ruby, 93 bytes
```
a=->(x){s=i=0;x.split('.').map{|p|s+=256**(3-i)*p.to_i;i+=1};s}
s=->(x,y){1+(a[x]-a[y]).abs}
```
Output
```
irb(main):003:0> s['1.1.1.1', '1.1.1.2']
=> 2
irb(main):006:0> s['0.0.0.0', '255.255.255.255']
=> 4294967296
```
[Answer]
# J, 25 bytes
Takes the dotted-quad IP strings as left and right arguments.
```
>:@|@-&(256#.".;.2@,&'.')
```
Explained:
```
>:@|@-&(256#.".;.2@,&'.') NB. ip range
&( ) NB. on both args, do:
,&'.' NB. append a .
;.2@ NB. split by last character:
". NB. convert each split to number
256#. NB. convert from base 256
|@- NB. absolute difference
>:@ NB. add 1 to make range inclusive
```
Examples:
```
'0.0.0.0' >:@|@-&(256#.".;.2@,&'.') '255.255.255.255'
4294967296
iprange =: >:@|@-&(256#.".;.2@,&'.')
'255.255.255.255' iprange '0.0.0.0'
4294967296
'1.2.3.4' iprange '1.2.3.4'
1
'56.57.58.59' iprange '60.61.62.63'
67372037
```
[Answer]
# Factor, 73 bytes
Translation of the CoffeeScript answer.
```
[ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ]
```
[Answer]
# Javascript ES6, 81 chars
```
(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1
```
Test:
```
f=(a,b)=>Math.abs(eval(`(((((${a})>>>0)-(((((${b})>>>0)`.replace(/\./g,")<<8|")))+1
;`0.0.0.0,255.255.255.255,4294967296
255.255.255.255,0.0.0.0,4294967296
1.2.3.4,1.2.3.4,1
56.57.58.59,60.61.62.63,67372037`.split`
`.map(x=>x.split`,`).every(x=>f(x[0],x[1])==x[2])
```
PS: I'll try to optimise it a bit later.
[Answer]
## Lua, 153 Bytes
It's a shame that lua doesn't have a split function, I had to define mine!
```
a,b=...r=0y=8^8x={}t={}function f(t,s)s:gsub("%d+",function(d)t[#t+1]=d end)end
f(x,a)f(t,b)for i=1,4 do r=r+y*math.abs(t[i]-x[i])y=y/256 end print(r+1)
```
### Ungolfed
```
a,b=... -- unpack the arguments into two variables
r=0 -- initialise the sume of ip adress
y=8^8 -- weight for the rightmost value
x={}t={} -- two empty arrays -> will contains the splittedip adresses
function f(t,s) -- define a split function that takes:
-- a pointer to an array
-- a string
s:gsub("%d+",function(d) -- iterate over the group of digits in the string
t[#t+1]=d -- and insert them into the array
end)
end
f(x,a) -- fill the array x with the first address
f(t,b) -- fill the array t with the second address
for i=1,4 -- iterate over t and x
do
r=r+y*math.abs(t[i]-x[i])-- incr r by weight*abs(range a- range b)
y=y/256 -- reduce the weight
end
print(r+1) -- output the result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes, language postdates challenge
```
ṣ”.V€ḅ⁹µ€ạ/‘
```
[Try it online!](https://tio.run/nexus/jelly#@/9w5@JHDXP1wh41rXm4o/VR485DW0HMXQv1HzXM@H@4Hcj5/z86WslADwyVdJSMTE31kLBSrA6XQjSGqA5cB0TeUM9Iz1jPBCgOY0HETc30TM31TC30TC2BcmYGemaGemZGembGSrGxAA "Jelly – TIO Nexus")
## Explanation
```
ṣ”.V€ḅ⁹µ€ạ/‘
µ€ On each element of input:
ṣ”. Split on periods
V€ Convert string to number in each section
ḅ⁹ Convert base 256 to integer
ạ/ Take absolute difference of the resulting integers
‘ Increment
```
The number of elements in an inclusive range is the absolute difference of their endpoints, plus 1.
[Answer]
# Axiom, 385 bytes
```
c(a:String):INT==(d:=digit();s:NNI:=#a;t:INT:=0;for i in 1..s repeat(~member?(a.i,d)=>return-1;t:=t+(ord(a.i)-48)*10^(s-i)::NNI);t)
g(x:String):List NNI==(a:=split(x,char".");s:NNI:=#a;r:=[];for i in s..1 by -1 repeat(y:=c(a.i);y=-1=>return [];r:=concat(y,r));r)
m(x:NNI,y:NNI):NNI==x*256+y
f(a:String,b:String):INT==(x:=g(a);y:=g(b);#x~=4 or #y~=4=>-1;1+abs(reduce(m,x)-reduce(m,y)))
```
ungolf it and test
```
-- convert the string only digit a in one not negative number
-- return -1 in case of error
cc(a:String):INT==
d:=digit();s:NNI:=#a;t:INT:=0
for i in 1..s repeat
~member?(a.i,d)=>return -1
t:=t+(ord(a.i)-48)*10^(s-i)::NNI
t
-- Split the string x using '.' as divisor in a list of NNI
-- if error return []
gg(x:String):List NNI==
a:=split(x,char".");s:NNI:=#a;r:=[]
for i in s..1 by -1 repeat
y:=cc(a.i)
y=-1=>return []
r:=concat(y,r)
r
mm(x:NNI,y:NNI):NNI==x*256+y
-- Return absolute value of difference of address for IP strings in a and in b
-- Retrun -1 for error
-- [Convert the IP strings in a and in b in numbers ad subtract and return the difference]
ff(a:String,b:String):INT==(x:=gg(a);y:=gg(b);#x~=4 or #y~=4=>-1;1+abs(reduce(mm,x)-reduce(mm,y)))
(14) -> f("0.0.0.0", "255.255.255.255")
(14) 4294967296
Type: PositiveInteger
(15) -> f("255.255.255.255", "0.0.0.0")
(15) 4294967296
Type: PositiveInteger
(16) -> f("1.2.3.4", "1.2.3.4")
(16) 1
Type: PositiveInteger
(17) -> f("56.57.58.59", "60.61.62.63")
(17) 67372037
Type: PositiveInteger
(18) -> f("1", "2")
(18) - 1
Type: Integer
```
] |
[Question]
[
## Input
* A list of between 1 and 255 positive integers (inclusive), each in the range 1 to 232 - 1 (inclusive).
* Your input format does not need to be identical to the test cases.
* Input without leading zeroes is required to be accepted.
* Input with leading zeroes is not required to be accepted.
* You may use whatever delimiter you wish between the integers.
* An integer may be represented by a string but the individual digits of a specific integer must be contiguous.
* You may choose to use any base for the input (including binary and unary), provided the output is also in that base.
## Output
* A single integer.
* The output must have no leading zeroes.
* The output must be in the same base as the input.
* The output can be calculated in whatever way you wish but must match the result of the following calculation:
## Calculating biplex
* The bits of a binary representation are numbered from the right starting from zero, so bit *i* is in the column representing 2*i*.
* The *i* th *bitsum* is the sum of the *i* th bits of the binary representations of each of the input numbers.
* The *bitsum maximum* is the highest value taken by the bitsums.
* The *bitsum minimum* is the lowest ***non-zero*** value taken by the bitsums.
* The *i* th digit of the binary representation of the output is:
+ 1 if the *i* th bitsum is equal to the bitsum maximum or the bitsum minimum.
+ 0 otherwise.
---
## Worked example
This example uses binary for input and output.
```
Input: 100110
1101110
1100101
_______
Bitsums: 2301321
Output: 101101
```
The bitsum maximum is 3 and the bitsum minimum is 1, so the output has 1s everywhere that the bitsum is 3 or 1, and 0s everywhere else.
---
## Test cases
Test cases are in the form:
```
Input => Output
```
**The test cases in binary:**
```
[1] => 1
[10] => 10
[1, 10, 101] => 111
[11111111111111111111111111111111] => 11111111111111111111111111111111
[10010010010010010010010010010010, 10101010101010101010101010101010, 11011011011011011011011011011011] => 11100011100011100011100011100011
[10001011100010100110100101001001, 10110000111110010000111110111010, 1101110001101101011010010100101, 1010101010001011101001001010101] => 11
```
**The same test cases in decimal:**
```
[1] => 1
[2] => 2
[1, 2, 5] => 7
[4294967295] => 4294967295
[2454267026, 2863311530, 3681400539] => 3817748707
[2341103945, 2969112506, 1849078949, 1430639189] => 3
```
---
## Leaderboard
Thanks to [Martin's Leaderboard Snippet](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet "Leaderboard Snippet on Meta")
```
var QUESTION_ID=62713,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
---
The operator was named biplex, short for binary plane extrema, following [discussion in chat](http://chat.stackexchange.com/transcript/message/24975175#24975175).
[Answer]
# Pyth, ~~26~~ 25 bytes
```
JsM.T_MjR2Qi_}RhM_BS-J0J2
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=JsM.T_MjR2Qi_%7DRhM_BS-J0J2&input=[2454267026%2C+2863311530%2C+3681400539]&test_suite_input=[1]%0A[2]%0A[1%2C+2%2C+5]%0A[4294967295]%0A[2454267026%2C+2863311530%2C+3681400539]%0A[2341103945%2C+2969112506%2C+1849078949%2C+1430639189]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=JsM.T_MjR2Qi_%7DRhM_BS-J0J2&input=[2454267026%2C+2863311530%2C+3681400539]&test_suite=1&test_suite_input=[1]%0A[2]%0A[1%2C+2%2C+5]%0A[4294967295]%0A[2454267026%2C+2863311530%2C+3681400539]%0A[2341103945%2C+2969112506%2C+1849078949%2C+1430639189]&debug=0)
### Explanation
```
JsM.T_MjR2Q
jR2Q convert each input number to binary (lists of 1s and 0s)
_M reverse each list
.T transpose (with top justify)
sM sum up each list (numbers of 1s at each position)
J store this list in J
i_}RhM_BS-J0J2
-J0 J without 0s
S sorted
_B create the list [sorted, reverse(sorted)]
hM take the first elments of each (bitsum-min and bitsum-max)
}R J check for each value in J, if it is part of ^
_ reverse this list of booleans
i 2 convert from binary to base 10 and print
```
[Answer]
# J, ~~31~~ ~~30~~ ~~24~~ ~~23~~ 21 bytes
```
+/(e.>./,<./@#~@)&.#:
```
This is a tacit, monadic verb that takes a list of decimal integers and returns their decimal biplex.
*Thanks to @Zgarb for his suggestions, which saved 4 bytes directly and paved the way for 2 more!*
*Thanks to @randomra for golfing off 2 more bytes!*
### Test cases
```
biplex =: +/(e.>./,<./@#~@)&.#:
biplex ,1
1
biplex ,2
2
biplex 1 2 5
7
biplex ,4294967295
4294967295
biplex 2454267026 2863311530 3681400539
3817748707
biplex 2341103945 2969112506 1849078949 1430639189
3
```
### How it works
```
&. Dual. Apply the verb to the right, the verb to the left,
and finally the inverse of the verb to the right.
#: Convert the input list from integer to base 2.
( @) Define an adverb, i.e., an operator that takes a verb as
its left argument.
+/ Call it with "reduce by sum". This calculates the sum of
the corresponding binary digits of all integers before
executing the remainder of the adverb's body, i.e, this:
#~ Replicate the sum N a total of N times, i.e., turn
0 1 2 3 into 1 2 2 3 3 3. This eliminates zeroes.
<./@ Calculate the minimum of the result.
>./ Calculate the maximum of the sums.
, Append; wrap both extrema into a list.
e. Check if each of the sums is in the list of extrema.
This yields 1 if yes and 0 if no.
(from &.) Convert from base 2 to integer.
```
[Answer]
## [Minkolang 0.10](https://github.com/elendiastarman/Minkolang), ~~109~~ 79 bytes
```
(n1$(d2%$r2:d)99*I-DmI2:[+1R]$I)rI$d$(s0(x0gd,)Ik3R2g1-X0I3-[2*2gd0c=$r1c=++]N.
```
Input and output are in decimal. [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=%28n1%24%28d2%25%24r2%3Ad%2999%2AI-DmI2%3A%5B%2B1R%5D%24I%29rI%24d%24%28s0%28x0gd%2C%29Ik3R2g1-X0I3-%5B2%2A2gd0c%3D%24r1c%3D%2B%2B%5DN%2E&input=2341103945%2C+2969112506%2C+1849078949%2C+1430639189)
### Explanation
```
( $I) Loop until input is empty
n Read in number from input
1$( d) Start a while loop with only the top of stack
d2% Next least-significant bit (modulo by 2)
$r Swap top two values
2: Divide by 2
99*I-D Pad with 0s
(when the while loop exits, top of stack is 0)
m Merge (interleave) stack
I2:[ ] For each pair...
+1R Add and rotate stack to the right
<<This does the work of computing bitsums>>
r Reverse stack
I Push length of stack
$d Duplicate whole stack
<<This lets me sort the bitsums without affecting the original order>>
$( Start while loop with <top of stack> elements
s Sort
0( ) Push a 0 and start another while loop
x Dump top of stack
0g Get front of stack and put it on top
d, Duplicate and <not> for end-while condition check
Ik Push length of stack and break out of while loop
3R Rotate [min, max, length] to front
2g1- Get length and put it on top, then subtract 1
X Dump that many elements off the top of stack
<<Now I have min and max>>
0 Initialize decimal with 0
I3-[ ] For as many bits as there are...
2* Multiply by 2
2gd Get the next most significant bit and put it on top
0c= Copy min and check for equality
$r Swap top two elements of stack
1c= Copy max and check for equality
++ Add 1 if bitsum item is equal to min or max, 0 otherwise
N. Output as integer and stop
```
---
### Old version:
```
$nI[(d2%i1+0a+i1+0A00ai`4&i00A2:d)x]00a1+[i1+0a]s0(x0gd,)rI2-[x]00a1+[i1+0ad0c=$r1c=+]0gx0gx0(xd,)0I1-[2*+]N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=%24nI%5B%28d2%25i1%2B0a%2Bi1%2B0A00ai%604%26i00A2%3Ad%29x%5D00a1%2B%5Bi1%2B0a%5Ds0(x0gd%2C)rI2-%5Bx%5D00a1%2B%5Bi1%2B0ad0c%3D%24r1c%3D%2B%5D0gx0gx0(xd%2C)0I1-%5B2*%2B%5DN%2E&input=2341103945%2C%202969112506%2C%201849078949%2C%201430639189)
### Explanation
The crux of it is that the **array** feature is heavily used (`a A`) to store the bitsums, of which the minimum and maximum are found, then `1`s and `0`s are outputted appropriately, with dumping of leading `0`s in two places.
```
$n Read in whole input as integers
I[( x] Convert each number to binary
d2% Get next least significant bit (modulo by 2)
i1+0a Get current value in array for that position
+ Add
i1+0A Put current value in array for that position
00ai` Get first value of array (bitsum length)
i` Greater than loop counter?
4&i00A If not, put loop counter there
2: Divide by 2
d) If 0, exit loop
00a Get first value of array (maximum length
1+ Add one
[i1+0a] Get bitsum values from array and push on stack
s Sort
0( Push a 0 (for dump) and start a while loop -- dumps leading 0s
x Dump top of stack
0g Get bottom of stack
d, Duplicate and <not> it
) Exit loop when top of stack is non-zero (i.e., the minimum)
r Reverse stack (so now it's [min, max, <stuff>])
I2-[x] Dump everything else
00a1+[ ] Get bitsum length and loop that many times
i1+0a Get bitsum value at current position
d Duplicate
0c= Copy front of stack and check for equality
$r Swap
1c= Copy next-to-front of stack and check for equality
+ Add (so it's 1 if it's equal to min or max, 0 otherwise)
0gx0gx Dump front two elements of stack (the min and max)
0(xd,) Dump leading 0s
0 Push 0 for conversion to decimal
I1-[ ] For each bit...
2*+ Multiply by 2 and add
N. Output as integer and stop
```
[Answer]
# [Brainfuck](http://esolangs.org/wiki/Brainfuck), 619 bytes
First answer in far too long here, so I thought I'd do a good one!
```
>->->->>>,----------[--<++++++[>------<-]>>>>,----------]-<<<+[-<<<+]->>,<++++[>--------<-]>[<++++[>+++++<-]>++[--<++++++[>------<-]>>>+>]<-[+>-<<+[-<<<+]-<<+[->+[->[-[->>>+<<<]<<<+]+[-->>>++]-<+]<<<+[-[->+<]<<<+]->>+>]<-[+>->>>>+[->>>+]->+[-<[-[->>>+<<<]<<<+]+[-->>>++]->+]-<+<<<+[-[->+<]<<<+]->>]]>,<++++[>--------<-]>]>+[->>>+]>->->>-[+<<<<<<+[-<-<<+]->>[+>>>[>>>]>+[<<->>[->>>+]->>>[-]+<<<<<+[-<<<+]+>->]<]>->>+>-]<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>-[+<<<<<<+[-<+<<+]->>[->>>[>>>]>+[<<<->>>[->>>+]->>>[-]+<<<<<<+[-<<<+]+>>+>]<]>->>>-]<<<<-<<<<+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]
```
Did... Did I win?
This program expects newlines (ASCII `10`) after every binary number, and requires a space (ASCII `32`) at the end.
Test runs:
```
Me$ bf bpx.bf
1
10
101
111
Me$ bf bpx.bf
11111111111111111111111111111111
11111111111111111111111111111111
Me$ bf bpx.bf
10010010010010010010010010010010
10101010101010101010101010101010
11011011011011011011011011011011
11100011100011100011100011100011
Me$ bf bpx.bf
10001011100010100110100101001001
10110000111110010000111110111010
1101110001101101011010010100101
1010101010001011101001001010101
11
```
(Newlines added after each case with `++++++++++.` added at the end of the program)
# Explanation
Still a work in progress, but a slow one. For lack of time, I've just copied the notes I made whilst writing this program, which will suffice for an explanation for now:
```
[Biplex Calculator]
[
Bitsum writing philosophy:
Start with [0 255 255 255 ...].
The 255s will be markers that we can 'search' for to get back to the start.
After that, the next byte should be a 0, fairly permanently. (The first reference 0)
It is useful to have 0-bytes handy for general calculations.
The next byte is where we will read the first digit of any binary number. (The first read)
The next byte holds the first bitsum.
Afterward, the next byte is 0, the following byte is the place
to read the second binary digit, the following byte is the second bitsum,
and so on.
I'll use the terminology nth reference 0, nth read, and nth bitsum to refer to
each part of the triplet of bytes.
The location three places after the final bitsum will be 255,
and the location three places after the final read will be 255.
We can move entire numbers by lining up these 255s after every binary number.
]
>->->->>>~ [0 255 255 255 0 0 0 0 0 ]
[From the first bitsum, read input to create an initial set of bitsums ]
,----------
[
--<++++++[>------<-] [Convert the input '1' or '0' into a bit ]
>>>>,----------
]~
-<<<+[-<<<+]->> [Mark 255 after the last bit, then go back to first read]
,<++++[>--------<-] [Check for space, using the first reference 0 ]
>
[
<++++[>+++++<-] [Check for \n ]
>++
[
--<++++++[>------<-] [It wasn't \n, so convert the input into a bit ]
>>>+> [Write 1 to the next reference 0, and go to next read ]
]
<-
[
+> [It was \n ]
-< [Mark 255 on this (nth) read and go to (n-1)th bitsum ]
<+[-<<<+] [Search for a 255 off to the left ]
[We've either struck our marker, or the last bitsum. We need to check. ]
-<<+
[
- [We hit the last bitsum. Move the bitsums right. ]
>+
[
->[-[->>>+<<<]<<<+] [Move until we reach the start ]
+[-->>>++] [From the start, move to our last bitsum ]
[Repeat this move until the read here is a 255 ]
-<+
]
[We now need to go to the first reference zero, and put a 1 there ]
<<<+[-[->+<]<<<+]->>+> [Add bits to bitsums and end on first read ]
]
<-
[
+>->>>>+[->>>+] [Go to the 255 after our reads ]
->+
[
-<[-[->>>+<<<]<<<+] [Move until we reach the start ]
+[-->>>++] [From the start, move to the 255 after our reads]
[Repeat this move until we see the 255 bitsum ]
->+
]
[We now need to go to the first read ]
-<+<<<+[-[->+<]<<<+]->> [Add bits to bitsums and end on first read ]
]
>>>>>>>>>>>>>>>>>>>>>>>>>~<<<<<<<<<<<<<<<<<<<<<<<<<
]
[We're at the reference 0 to the left of our next read ]
>,<++++[>--------<-] [Check for space, using the first reference 0 ]
>
]
[
Let BN be the nth bitsum. Then our situation at the moment is:
[0 255 255 255 0 0 B1 0 0 B2 ... 0 0 BN 0 0 255]
^
I'm just happy nothing's exploded yet.
]
[Next goal: Mark the minimums ]
>+[->>>+]>->->>~ [Zero the 255 and put 2 255s after it, then move after it ]
-[
+<<<<<<
+[-<-<<+] [Subtract one from each bitsum ]
->>
[
+>>>[>>>] [Find the first 0 bitsum ]
>+
[
<<->>[->>>+]->>>[-] [Mark the zero as a minimum, and set a flag ]
+<<<<<+[-<<<+]+>->
]
<
]
>->>+>-
]~
[Hey, that worked. Weird. Alright, moving on... ]
[Reset the bitsums to what they were before we messed them all up ]
<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>~
[After the stuff up there, that's not too bad. ]
[Now it's time to mark the maximums, in virtually the opposite way we did the minimums. ]
-[
+<<<<<<
+[-<+<<+] [Add one to each bitsum ]
->>
[
->>>[>>>] [Find the first 0 bitsum ]
>+
[
<<<->>>[->>>+]->>>[-] [Mark the zero as a maximum, and set a flag ]
+<<<<<<+[-<<<+]+>>+>
]
<
]
>->>>-
]~
[Alright, now OR the maxs and mins, take care of leading zeros, output, and cross fingers ]
<<<<->>~<<<<<<~+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]
```
[Answer]
## CJam, 27 bytes
```
q~2fbWf%:.+_0-$(\W>|fe=W%2b
```
Takes input as a base-10 CJam-style list. [Test it here.](http://cjam.aditsu.net/#code=q~2fbWf%25%3A.%2B_0-%24(%5CW%3E%7Cfe%3DW%252b&input=2454267026%202863311530%203681400539%5D) Alternatively, [run all test cases](http://cjam.aditsu.net/#code=qN%2F%7B%22%3D%3E%22%2F0%3D'%2C-%3AQ%3B%0A%0AQ~2fbWf%25%3A.%2B_0-%24(%5CW%3E%7Cfe%3DW%252b%0A%0A%5DoNo%7D%2F&input=%5B1%5D%20%3D%3E%201%0A%5B2%5D%20%3D%3E%202%0A%5B1%2C%202%2C%205%5D%20%3D%3E%207%0A%5B4294967295%5D%20%3D%3E%204294967295%0A%5B2454267026%2C%202863311530%2C%203681400539%5D%20%3D%3E%203817748707%0A%5B2341103945%2C%202969112506%2C%201849078949%2C%201430639189%5D%20%3D%3E%203) (the script discards the expected output and converts the input format as necessary).
### Explanation
```
q~ e# Read and evaluate input.
2fb e# Convert each number to base 2.
Wf% e# Reverse each digit list, to align digits in case there are numbers with different
e# widths.
:.+ e# Add up the bit planes.
_0- e# Make a copy and remove zeroes.
$ e# Sort the bit plane sums.
(\W>| e# Get the first and last element. We use set union instead of addition so that the
e# resulting array will contain only one value if min = max.
fe= e# For each element in the bit plane sums, count how often it appears in the min/max
e# array, which is either 1 or 0.
W% e# Reverse the digits again (to undo the initial reversing).
2b e# Interpret as base-2 digits.
```
[Answer]
# JavaScript (ES6), 215 185 176 bytes
```
f=a=>{s=[];for(i of a)for(b=i.toString(2),d=l=b.length;d--;)s[x=l-d-1]=(s[x]|0)+(b[d]|0);q=255;for(r of s)d=r>d?r:d,q=r<q?r||q:q;o="";s.map(r=>o=(r==q|r==d)+o);return+("0b"+o)}
```
## Usage
```
f([2454267026, 2863311530, 3681400539])
=> 3817748707
```
## Explanation
```
f=a=>{
// Create an array of bitsums
s=[]; // s = bitsums
for(i of a) // iterate through the passed array of numbers
for(
b=i.toString(2), // b = number as binary string
d=l=b.length; // l = number of digits in b
d--; // iterate through each digit of the binary string
)
s[x=l-d-1]= // add to the digit of the bitsum array
(s[x]|0)+ // get the current value of the bitsum array (or 0 if null)
(b[d]|0); // add the result to the bitsum array
// Get the maximum and minimum bitsums
q=255; // q = min bitsum
//d=0; // d = max bitsum
for(r of s) // iterate through the bitsums
d=r>d?r:d, // set d to maximum
q=r<q?r||q:q; // set q to minimum
// Calculate the result
// (unfortunately JavaScript only supports bitwise operations on signed 32-bit
// integers so the temporary binary string is necessary)
o=""; // o = output
s.map(r=> // iterate through the bitsum digits
o=(r==q|r==d)+o // add a 1 to the string if the digit is equal to min or max
);
return+("0b"+o) // convert the binary string to a number
}
```
[Answer]
# Julia, 141 bytes
```
A->(s=reduce(.+,map(i->digits(i,2,maximum(map(i->ndigits(i,2),A))),A));parse(Int,reverse(join([1(i∈extrema(filter(j->j>0,s)))for i=s])),2))
```
Ungolfed:
```
function biplex(A::AbstractArray)
# Get the maximum number of binary digits in each element
# of the input array
L = maximum(map(i -> ndigits(i, 2), A))
# Create an array of arrays of binary digits corresponding
# to the inputs
B = map(i -> digits(i, 2, L), A)
# Get the bitsums
S = reduce(.+, B)
# Replace the minimum and maximum bitsums with ones and
# the rest with zeros
s = [1 * (i in extrema(filter(j -> j > 0, S))) for i in S]
# Join this into a string and parse it as a base 2 integer
# Reverse is required because digits() returns the digits
# in reverse order
p = parse(Int, reverse(join(s)), 2)
return p
end
```
[Answer]
# [Simplex v.0.7](http://conorobrien-foxx.github.io/Simplex/), 38 bytes
*Simpl*ified comments. Input in Binary, no interpreter working at the moment. Hopefully the comments are sufficient.
```
hj&=j&Lun?&RvRpp]{Ri}^XKRJ@jqLhR@LhuTo
h ] ~~ define macro 0
j& ~~ insert a new byte and write register to it
= ~~ equal to the previous byte?
j& ~~ insert a new byte and write register to it
L ~~ return to equality
u v ~~ go up/down a strip
n?& ~~ write the register iff byte = 0
R ~~ go right
Rpp ~~ remove two bytes
{Ri} ~~ take input until input = 0
^X ~~ take the sum of the strip
K ~~ split that sum into digits
RJ@ ~~ take the max; write to register
jq ~~ take the min
Lh ~~ call macro 0
R@ ~~ set min to register
Lh ~~ apply macro 0
uTo ~~ output result
```
[Answer]
# Octave, 50 bytes
```
@(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48]
```
**Example:**
```
octave:1> g = @(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48] ;
octave:2> g(["10010010010010010010010010010010"; "10101010101010101010101010101010"; "11011011011011011011011011011011"])
ans = 11100011100011100011100011100011
```
[Answer]
# JavaScript (ES6), 158
A function with a numeric array parameter, returning a number. With the same byte count it could get a string array parameter (containing base 2 rapresentations) and return a base 2 string - just move the `.toString(2)` at the end after `r`.
```
f=l=>(l.map(v=>[...v.toString(2)].reverse().map((x,i)=>t[i]=~~t[i]-x),t=[]),t.map(v=>(r+=v==Math.min(...t)|v==Math.max(...t.filter(x=>x))&&b,b+=b),r=0,b=1),r)
// More readable
u=l=>(
t=[],
l.map(v =>
[...v.toString(2)]
.reverse()
.map((x,i) => t[i] = ~~t[i] - x)
),
r=0,b=1,
t.map(v => (
r += v==Math.min(...t) | v==Math.max(...t.filter(x=>x)) && b, b+=b
)),
r
)
// Test
console.log=s=>O.innerHTML+=s+'\n'
;[
[[1], 1]
,[[2], 2]
,[[1, 2, 5], 7]
,[[4294967295], 4294967295]
,[[2454267026, 2863311530, 3681400539], 3817748707]
,[[2341103945, 2969112506, 1849078949, 1430639189], 3]
].forEach(t =>{
r=f(t[0])
x=t[1]
console.log('Test '+(r==x?'OK':'Fail (Expected: ' + x +')')
+'\nInput: '+t[0]+'\nResult: ' +r+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
# Haskell, ~~198~~ ~~182~~ ~~178~~ 161 character
I'm still beginner at golfing. Only 80 reputation comes from answer.
```
m=map
v=reverse
(b:x)&(c:y)=(b+c):x&y
[]&a=a
b&_=b
l=(show=<<).v.(\a->m(fromEnum.(`elem`[maximum a,minimum$(replicate=<<id)=<<a]))a).foldl1(&).m(m(read.(:[])).v)
```
How does it work.
Instead of padding, I reverse the array then I add using user defined (&). I don't use foldl1(zipWith(+)) that is shorter because zipWith will delete the superflous item. Then I find the maximum and nonzero minimum, that also required user defined function. Then I match the item with the maximum and nonzero minimum, 1 if match, 0 if it doesn't match. Then we reverse and turn it into binary number.
TODO:
1. Using `Data.List`
[Answer]
## Python 3, ~~181~~ ~~126~~ 122 bytes
(I took out most of the byte count slashes because it was getting a bit ridiculous.) 21 bytes off thanks to **Sp3000**!
```
*z,=map(sum,zip(*[map(int,t.zfill(99))for t in input().split()]))
k=0
for x in z:k=k*10+(x in[min(z)or 1,max(z)])
print(k)
```
Slightly less golfed:
```
s=input().split()
k=list(map(lambda t:list(map(int,t))[::-1],s))
z=list(map(sum,zip(*k)))
y=z[:]
while min(y)==0:y.remove(0)
a,b=min(y),max(y)
f=''.join(map(lambda x:str(1*(x in[a,b])),z[::-1]))
print(int(f))
```
Input is expected in binary with only spaces separating the numbers. Output is in binary as well.
[Answer]
# Javascript, 154 150 bytes
```
t=i=>(m=0,r=[],i.map(n=>{for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);}),r.map(n=>m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2),m)
```
Thanks for edc65 method for min/max calculation, it shortened my code by 4 bytes.
# Explanation
```
t=i=>(
m=0,//m=>output
r=[],//Bitsum then final number in binary
i.map(
n=>
{
//Decimal to binary + bitsum
for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);
}),
//Output formatting
r.map(
n=>
m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2
),
m
)
```
[Answer]
# [ShapeScript](https://github.com/DennisMitchell/ShapeScript), 186 bytes
```
'"1
"$0?_1-"+"*":2"@~@"0
"~"0
"$"
"~+'1?_*!"2"$"0"~"
"$""~":"1?'@1?"+"$_1>"+"*+@1?"0"+$""~'1?_*!#"0"+@":+"'1?1?"0"+$_2<"+"*+'1?_*!"0"+$"1"~@$"1"~":"$""~"+"$""~'"
"@+"
0"$""~'1?_*!"
"$""~
```
An important, useless language for an important, useless operator.
I/O is in binary. The program expects each number on a separate line, each ending with a linefeed.
[Try it online!](http://shapescript.tryitonline.net/#code=JyIxCiIkMD9fMS0iKyIqIjoyIkB-QCIwCiJ-IjAKIiQiCiJ-KycxP18qISIyIiQiMCJ-IgoiJCIifiI6IjE_J0AxPyIrIiRfMT4iKyIqK0AxPyIwIiskIiJ-JzE_XyohIyIwIitAIjorIicxPzE_IjAiKyRfMjwiKyIqKycxP18qISIwIiskIjEifkAkIjEifiI6IiQiIn4iKyIkIiJ-JyIKIkArIgowIiQiIn4nMT9fKiEiCiIkIiJ-&input=MTAwMDEwMTExMDAwMTAxMDAxMTAxMDAxMDEwMDEwMDEKMTAxMTAwMDAxMTExMTAwMTAwMDAxMTExMTAxMTEwMTAKMTEwMTExMDAwMTEwMTEwMTAxMTAxMDAxMDEwMDEwMQoxMDEwMTAxMDEwMDAxMDExMTAxMDAxMDAxMDEwMTAxCg==)
### Test cases
```
$ echo -e '1' | shapescript biplex.shape; echo
1
$ echo -e '10' | shapescript biplex.shape; echo
10
$ echo -e '1\n10\n101' | shapescript biplex.shape; echo
111
$ echo -e '11111111111111111111111111111111' | shapescript biplex.shape; echo11111111111111111111111111111111
$ echo -e '10010010010010010010010010010010\n10101010101010101010101010101010\n11011011011011011011011011011011' | shapescript biplex.shape; echo
11100011100011100011100011100011
$ echo -e '10001011100010100110100101001001\n10110000111110010000111110111010\n1101110001101101011010010100101\n1010101010001011101001001010101' | shapescript biplex.shape; echo
11
```
[Answer]
# APL, 27 bytes
```
{2⊥S∊(⌈/,⌊/)0~⍨S←+/⍵⊤⍨32⍴2}
```
This is a monadic function that takes a list of decimal integers and returns their decimal biplex.
Try it online in the [ngn/apl demo](http://ngn.github.io/apl/web/#code=%7B2%u22A5S%u220A%28%u2308/%2C%u230A/%290%7E%u2368S%u2190+/%u2375%u22A4%u236832%u23742%7D%20%A8%20%28%2C1%29%20%28%2C2%29%20%281%202%205%29%20%28%2C4294967295%29%20%282454267026%202863311530%203681400539%29%20%282341103945%202969112506%201849078949%201430639189%29).
### How it works
```
32⍴2 Create a list of 32 2's.
⍵⊤⍨ Base-encode the right argument.
+/ Add the corresponding binary digits.
S← Save the sums in S.
0~⍨ Remove 0's.
(⌈/,⌊/) Apply minimum (⌊/), maximum (⌈/) and concatenate.
S∊ Check which binary digits are in the extrema list.
2⊥ Convert from base 2 to integer.
```
[Answer]
# Wolfram Language, 113 bytes
This version takes input from a popup window, with the numbers being input in the form "{x,y,z,...}", (no quotes).
```
FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@Input[]]
```
Input:
![popup window dynamic](https://i.stack.imgur.com/WIi1t.png)
Output:
![output](https://i.stack.imgur.com/OM2bi.png)
Takes input in a dynamic Manipulate as a string of the form "{x,y,z}" with x, y, and z being base 10 integers (with or without leading zeroes). The output is also in base 10.
```
Manipulate[FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@i],{i,"{1}"}]
```
![example](https://wolfr.am/8apzjEPd)
There are other ways to input this in a way that would save on character counts, but I think this solution is an elegant use of a dynamic GUI that performs the computation
If you want to run this in the cloud, we can use CloudDeploy:
```
o=CloudDeploy[FormPage[{"i"->"String"},(FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@#i])&]];SetOptions[o,Permissions->{All->{"Read","Execute"},"Owner"->{"Read","Write","Execute"}}];o
```
The Cloud deploy brings the character count up to 256 however...
The input to the FormPage is also a string of the form "{x,y,z}" with x, y, and z being base 10 integers.
I cloud-deployed this myself and you can try it out at <https://www.wolframcloud.com/objects/97b512df-64f8-4cae-979b-dba6d9622781>
![cloud example](https://i.stack.imgur.com/C8BbN.png)
[Answer]
# Jelly
**14 bytes**
```
BUSµḟ0Ṣ.ịe€@UḄ
```
[Try it online!](http://jelly.tryitonline.net/#code=QlVTwrXhuJ8w4bmiLuG7i2XigqxAVeG4hA&input=&args=WzIzNDExMDM5NDUgLDI5NjkxMTI1MDYgLDE4NDkwNzg5NDkgLDE0MzA2MzkxODld)
### How it works
```
BUSµḟ0Ṣ.ịe€@UḄ Main link. Input: A (list)
B Convert each item in A to binary.
U Reverse each array of binary digits.
S Add them across columns.
µ Monadic chain. Argument: S (list of column sums)
ḟ0 Remove all occurrences of 0.
Ṣ Sort the remaining sums.
.ị Take the elements with indices around 0.5.
Indices are 1-bases, so this selects the last and the first one.
U Yield S, reversed.
@ Reverse the arguments.
e€ Test each item in the left list for membership in the right one.
Ḅ Convert from binary to integer.
```
[Answer]
# Python 3, 197
```
import itertools
o='0'
d=[sum(map(int,n))for n in itertools.zip_longest(*map(reversed,input().split(' ')),fillvalue=o)]
m=max(d),min(d)or 1
print(''.join((o,'1')[g in m]for g in d[::-1]).lstrip(o))
```
It takes in space delimited binary numbers.
Ungolfed version:
```
import itertools
nums = map(reversed, input().split(' '))
digits = []
for num in itertools.zip_longest(*nums, fillvalue='0'):
current_digit = sum(map(int,num))
digits.append(current_digit)
bit_max = max(digits)
bit_min = min(digits) or min(digits) + 1
print(''.join(('0','1')[digit in(bit_max,bit_min)]for digit in digits[::-1]).lstrip('0'))
```
[Answer]
# C#, 255
A complete program, input as command line arguments - space separated - in decimal.
```
using System.Linq;class P{static void Main(string[]l){var n=new uint[32];uint i,r=0,b;foreach(var v in l)for(i=0,b=uint.Parse(v);b!=0;b/=2)n[i++]+=b&1;b=1;foreach(var v in n){r+=(v==n.Max()|v== n.Min(x=>x>0?x:n.Max()))?b:0;b+=b;}System.Console.Write(r);}}
```
More readable:
```
using System.Linq;
class P
{
static void Main(string[] l)
{
var n = new uint[32];
uint i, r = 0, b;
foreach (var v in l)
for (i = 0, b = uint.Parse(v); b != 0; b /= 2) n[i++] += b & 1;
b = 1;
foreach (var v in n)
{
r += (v == n.Max() | v == n.Min(x => x > 0 ? x : n.Max())) ? b : 0;
b += b;
}
System.Console.Write(r);
}
}
```
[Answer]
# Ruby, 127 bytes
```
def f l;a=[];32.times{|i|a[i]=0;l.each{|n|;a[i]+=n[i]}};a.map{|b|a.reject{|c|c==0}.minmax.index(b)?1:0}.reverse.join.to_i 2;end
```
Takes an array as input.
[Answer]
# CoffeeScript, 194 bytes
Takes input as coma separated binary numbers, outputs in binary.
```
a=(s.split('').reverse()for s in prompt().split(','))
for i in b=[0..31]
b[i]=0
b[i]+=+c[31-i]||0for c in a
m=1/M=0
for d in b
M=d if d>M;m=d if m>d&&d
alert +(+(d in[m,M])for d in b).join ''
```
[Try it.](http://coffeescript.org/#try:a%3D(s.split('').reverse()for%20s%20in%20prompt().split('%2C'))%0Afor%20i%20in%20b%3D%5B0..31%5D%0A%20b%5Bi%5D%3D0%0A%20b%5Bi%5D%2B%3D%2Bc%5B31-i%5D%7C%7C0for%20c%20in%20a%0Am%3D1%2FM%3D0%0Afor%20d%20in%20b%0A%20M%3Dd%20if%20d%3EM%3Bm%3Dd%20if%20m%3Ed%26%26d%0Aalert%20%2B(%2B(d%20in%5Bm%2CM%5D)for%20d%20in%20b).join%20'')
[Answer]
# GolfScript, 46 bytes
```
~{2base-1%}%zip{{+}*}%-1%.$0-)\1<|`{&,}+%2base
```
Try it online on [Web GolfScript](http://golfscript.apphb.com/?c=OyAiWzIzNDExMDM5NDUgMjk2OTExMjUwNiAxODQ5MDc4OTQ5IDE0MzA2MzkxODldIiAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2BezJiYXNlLTElfSV6aXB7eyt9Kn0lLTElLiQwLSlcMTx8YHsmLH0rJTJiYXNl).
### Test cases
```
$ golfscript biplex.gs <<< '[1]'
1
$ golfscript biplex.gs <<< '[2]'
2
$ golfscript biplex.gs <<< '[1 2 5]'
7
$ golfscript biplex.gs <<< '[4294967295]'
4294967295
$ golfscript biplex.gs <<< '[2454267026 2863311530 3681400539]'
3817748707
$ golfscript biplex.gs <<< '[2341103945 2969112506 1849078949 1430639189]'
3
```
[Answer]
# C++, 192 bytes
Accepts input a 32 bit unsigned integer array, and a count of items in that array.
```
typedef unsigned long U;U b(U*a,int c){U x[32],t,i,j,M=0,m=c,r=0;for(i=0;i<32;x[i++]=t,m=t&&m>t?t:m,M=M<t?t:M)for(t=j=0;j<c;)t+=a[j++]>>i&1;for(i=0;i<32;++i)r|=(x[i]==m||x[i]==M)<<i;return r;}
```
Ungolfed :
```
unsigned long b(unsigned long*a, int c){
unsigned long x[32],t,i,j,M=0,m=c,r=0;
for(i=0;i<32;x[i++]=t){
m = (t && m > t)?t:m;
M = M < t ? t:M;
for(t=j=0;j<c;){
t+=a[j++]>>i&1;
}
}
for(i=0;i<32;++i)
r|=(x[i]==m||x[i]==M)<<i;
return r;
}
```
] |
[Question]
[
[Deadfish](http://esolangs.org/wiki/Deadfish) is a joke "programming language" with four commands. Because the Esolang page is a bit contradictory and the interpreters on that page don't all work exactly the same, you should implement the following variation:
---
## Specification
1. There is an accumulator which is *at least* 16 bits in size, more is allowed but less is not. Negative numbers do not need to be supported. The accumulator is `0` when the program starts.
2. There are the following two sets of four commands, and your program must support both at the same time.
```
Standard Deadfish │ XKCD Variant │ Meaning
─────────────────────┼──────────────────┼────────────────────────────────────
i │ x │ Increment accumulator
d │ d │ Decrement accumulator
s │ k │ Square ( acc = acc * acc )
o │ c │ Output accumulator, as a number
```
3. If, after executing a command, the accumulator is either `-1` or `256`, the accumulator must be reset to zero. **Note that this is not normal wrap-around.** If, say, the accumulator is `20`, and the `s` command is run, the accumulator should be `400` afterward. Similarly, if the accumulator is `257` and the `d` command is run, the accumulator should become `0`.
4. Any input that isn't one of these commands should be ignored.
---
## Test programs
* `xiskso` should output `0`
* `xiskisc` should output `289`
---
## I/O
Your program should display a prompt: `>>`. The prompt must be at the beginning of a new line. It should then read a line of user input, and run the given commands left-to-right. When outputing numbers, the numbers must be separated. I.e., `12 34` is OK, `12,34` is OK,
```
12
34
```
is OK, but `1234` is not.
Your program should keep doing this in a loop, at least until `EOF` is reached.
Example session:
```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
[Answer]
## [Perl 5](https://www.perl.org/), 90 bytes
```
do{print+(map{$?+=/i|x/-/d/;$?**=1+/s|k/;$?=~s/-1|^256$/0/;"$?
"x/o|c/}/./g),'>> '}while<>
```
[Try it online!](https://tio.run/##ZYfRCoIwAEXf9xUiA8tlNwV7sW1/EoSTGlobLkhw9usr9xR0udxzru3GoQ5BmdmO@vFkm/vFzlQyDu0nFFBoqMxzXjI436@Hvx2K0p@r@khxQJNSSdIJxrdYsMd1u8uESLLlddNDdxIhTNr1zpAV2rVEfWOSuH/@K1FjtfkA "Perl 5 – Try It Online")
Thanks to [@xfix](https://codegolf.stackexchange.com/users/72767/xcali) for his help on this previously! Saved 4 bytes thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali)!
[Answer]
# K, 77 bytes
```
{1">>";0{x*2=-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{-1@$x;x};-1+))@0:0;.z.s`}`
>>xiskso
0
>>xiskisc
289
```
Note this is [K4](http://kx.com/). A [K6](http://kparc.com/) solution is slightly longer because the IO verbs are longer, even if everything else is better:
```
{""0:">>";0{x*^-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{""0:,$x;x};-1+))@0:"";o`}`
```
* `""0:` prints and returns its argument. Note in K4 we simply apply to [1](http://code.kx.com/wiki/Reference/One).
* `0 f/ args` demonstrates reduce with an initial value, i.e. `f[f[0;first arg];second arg]…`
* `{x*2=-1 256?x…` classifies x into the 0 (for -1), 1 (for 256) and 2 for all other values. `2=` means we get `1` for unclassified values and `0` otherwise, multiplying by `x` is shorter than a conditional. In K6 we can do a little better because `{x*^-1 256?x:y@x}` relies on the fact that `-1 256?x` returns `0N` (null) and `^` detects nulls.
* The "parser" is the map `"xkcdiso"` instead of the suggested order because `7#` will wrap around the four arguments i.e. `7#"abcd"` returns `"abcdabc"` which keeps our table smaller
* The map translates `"x"` and `"i"` to the projection `1+` which is equivalent to the function `{1+x}` but shorter.
* The map translates `"d"` to the projection `-1+` which is equivalent to the function `{-1+x}` but shorter.
* The map translates `"k"` and `"s"` to the function `{x*x}`
* The map translates `"c"` and `"o"` to the output function `{-1@$x;x}` which again in K6 is slightly longer: `{""0:,$x;x}` but both print its output followed by a newline, and then returns the argument.
* [.z.s](http://code.kx.com/wiki/Reference/dotzdots) is self-recursion. In K6 we can simply say `o`` which is shorter.
[Answer]
## Powershell, ~~131~~ ~~126~~ ~~121~~ ~~114~~ 113
```
for($x=0){[char[]](read-host ">>")|%{switch -r($_){"i|x"{$x++}"d"{$x-=!!$x}"s|k"{$x*=$x}"o|c"{$x}}
$x*=$x-ne256}}
```
* `for($x=0){...}` - set the accumulator to 0 and loop forever
* `read-host '>>'` - get the user input with prompt `>>`
* `[char[]](...)` - convert the user input to an array of characters
* `|%{...}` - perform what's inside `{}` for each character
* `switch -r($_)` - regex switch for each character
* `"i|x"{$x++}` - match `i` or `x` - increase the accumulator
* `"d"{$x-=!!$x}` - match `d` - decrease `$x` by `!!$x`, which will be `0` if `$x` is `0`, and `1` otherwise. This makes sure the accumulator never reaches `-1`.
* `"s|k"{$x*=$x}` - match `s` or `k` - square
* `"o|c"{$x}` - match `o` or `c` - output the accumulator
* `$x*=$x-ne256` - multiply the accumulator by `0` if it is `256` or by `1` otherwise
**Example output**
```
>>: xiskso
0
>>: xiskisc
289
>>: ddddo ddddo
285
281
>>: ddddo ddddo
277
273
>>: dddddddo
266
>>: dddddddddo
257
>>: do
0
>>: do
0
>>: io
1
>>:
```
I guess the implementation of `read-host` is host specific, so this Powershell host (ConsoleHost) appends `:` to the specified prompt.
[Answer]
## Rebol 3, ~~178~~ ~~169~~ ~~161~~ 159
```
f: does [if a = -1 or (a = 256)[a: 0]]d: [any[["i"|"x"](++ a f)|["d"](-- a f)|["s"|"k"](a: a * a f)|["o"|"c"](print a)| skip]]a: 0 forever [parse (ask ">>") d]
```
Prettier version:
```
f: does [if a = -1 or (a = 256) [a: 0]]
d: [
any [
["i"|"x"] (++ a f) |
["d"] (-- a f) |
["s"|"k"] (a: a * a f) |
["o"|"c"] (print a) |
skip
]
]
a: 0
forever [parse (ask ">>") d]
```
[Answer]
## Haskell, 202
```
r=pure;-1%c=0%c;256%c=0%c;s%'o'=s<$print s;s%'c'=s%'o';s%'i'=r$s+1;s%'x'=s%'i'
s%'d'=r$s-1;s%'s'=r$s^2;s%'k'=s%'s';s%_=r s;n s(c:[])=s%c;n s(c:f)=s%c>>=(`n`f)
main=p 0;p s=putStr">> ">>getLine>>=n s>>=p
```
[Answer]
# Python 3, 141
I know I am to late, but I wanted to take the opportunity to post a shorter Python-version (and my first CodeGolf-attempt). :)
```
v=0
m=lambda y:(0,y)[-1!=y!=256]
i=x='+1'
d='-1'
s=k='*v'
c=o=');print(v'
while 1:
for n in input('>>'):exec('v=m(v'+locals().get(n,'')+')')
```
The print-statement was kinda tricky for this.
If the prompt has to end with a whitespace, add one char to the count. :)
## Explanation
`v` is the accumulator.
`m` checks whether the given value is `-1` or `256`. If so, `0` will be returned, the value otherwise.
In the following lines the operations are assigned to the corresponding variables (as some have the same meaning (like `i` and `x`) this is shorter than instantiating a new dictionary). Those are then used in the `exec` below.
`while 1:` is the main-loop
Now the fun begins. Like [@jazzpi](https://codegolf.stackexchange.com/questions/16124/write-an-interactive-deadfish-interpreter/16128#16128 "thanks for that :)")'s solution, it iterates over each char of the input. `locals()` is the dictionary of all current (visible) variables. With `.get(n,'')` the corresponding key will be put into the exec-string (an empty string, if the key (= other input) was not found). This then will be, when executed, concatenated with `v` and passed towards `m`. The return value will be stored in `v` again.
>
> ### Short example:
>
>
> Be `n = 'i'` (`n` = input-char), we get `'+1'` out of the `locals`-block as `i` is the variable with value `'+1'`.
>
> The string for the `exec` than looks like this: `'v=m(v+1)'`.
>
> Maybe now it is easier to see, that, when executing, it will call `m` with the value of `v+1` and store it's output in `v` again.
>
>
>
Repeat this until you are bored. :)
[Answer]
# Ruby, ~~140~~ 138
```
a=0
loop{$><<'>> '
eval gets.gsub(/./){|c|({i:i='a+=1',x:i,d:'a-=1',s:s='a**=2',k:s,o:o='p a',c:o}[:"#{c}"]||'')+';a=a==-1||a==256?0:a;'}}
```
Sample session (same as yours):
```
c:\a\ruby>deadfish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
[Answer]
# K, 121
```
i:0;while[1;1">> ";{i{(r;0)(-1~r)|256~r:y x}/d{x@&x in y}[x;!d:"ixdskoc"!,/(2#(1+);-1+;2#{x*x};2#{-1@$i::x;})]}'" "\:0:0]
```
.
```
C:\q>q deadfish.k -q
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
[Answer]
## Ada
Here's an Ada implementation for the few who're interested by this language. It took me quite some time in order to use some of Ada's best practices (like the use of Indefinite\_Holders instead of access) and also to fully comprehend how's Deadfish must work.
```
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Holders;
with Ada.Integer_Text_IO;
procedure Deadfish is
package String_Holder is new Ada.Containers.Indefinite_Holders(String);
use String_Holder;
value_output : Natural := 0;
str_input : String_Holder.Holder := To_Holder("");
begin
Prompt :
loop
Put(">> ");
String_Holder.Replace_Element(str_input, Get_Line);
for rg in str_input.Element'Range loop
case str_input.Element(rg) is
when 'i' | 'x' =>
case value_output is
when 255 => value_output := 0;
when others => value_output := Natural'Succ(value_output);
end case;
when 'd' =>
case value_output is
when 257 => value_output := 0;
when 0 => null;
when others => value_output := Natural'Pred(value_output);
end case;
when 's' | 'k' =>
case value_output is
when 16 => value_output := 0;
when others =>value_output := value_output * value_output;
end case;
when 'o' | 'c' => Ada.Integer_Text_IO.Put(value_output, Width => 0); Put_Line("");
when others => null;
end case;
end loop;
end loop Prompt;
end Deadfish;
```
And the output :
```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
If some people experimented in Ada could give me some optimisation hints, I would be thankful.
[Answer]
## C, 159 chars
```
A; main(c) {
printf(">> ");
while (c = getchar(), ~c)
A = c - 'i' & c - 'x'?
c - 'd'?
c - 's' & c - 'k'?
c - 'o' & c - 'c'?
c - '\n'?
A :
printf(">> "), A :
printf("%d\n", A), A :
A * A :
A - 1 :
A + 1,
A *= ~A && A - 256;
}
```
I tried another approach based on setting up a look-up table for instruction decoding, but unfortunately that ended up longer (**169**). I included it since someone might come up with a clever tweak to cut down the size. (Must be run without any arguments)
```
#define X !--c?A
A,M[256];
main(c) {
for(; !M['x']; c++) M["@osid\nckx"[c]]-=c%5+1;
for (printf(">> "); c = ~M[getchar()]; A *= ~A && A - 256)
A= X,printf("%d\n", A),A:X*A:X+1:X-1:A;
main();
}
```
[Answer]
## C, 163
```
#define i(u,v);if(c==u+89|c==v+89)
a;main(c){printf(">>");while(c=getchar()-10){i(6,21)a++i(1,1)a--i(8,16)a*=a;i(0,12)printf("%d\n",a);a=a==-1|a==256?0:a;}main();}
```
[Answer]
# Python 3, 181 175 171 162
```
a=0
s=lambda x:"a=%d"%(x!=-1and x!=256and x)
while 1:
for i in input(">>"):u,b,o=s(a+1),s(a*a),"print(a)";exec(dict(i=u,x=u,d=s(a-1),s=b,k=b,o=o,c=o).get(i,""))
```
This outputs a newline after the `>>`, but the OP didn't say that wasn't allowed. *Not anymore!*
Thanks to `GlitchMr`, `minitech` and `golfer9338`!
[Answer]
# R, 161, 148, 138
```
a=0;repeat{x=readline(">> ");for(i in utf8ToInt(x)-99){a=a^((i==8|i==16)+1)+(i==6|i==21)-(i==1&a);a=a*(a!=256);if(i==0|i==12)cat(a,"\n")}}
```
Ungolfed version:
```
a = 0
repeat{
x = readline(">> ")
for(i in utf8ToInt(x) - 99) {
a = a ^ ((i == 8 | i == 16) + 1) + (i == 6 | i == 21) - (i == 1 & a)
a = a * (a != 256)
if(i == 0 | i == 12) cat (a, "\n")
}
}
```
Example session (in interactive mode):
```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
[Answer]
# **Python 2, 139**
```
a=0
while 1:
for c in raw_input(">> "):
if c in'ix':a+=1
if c=='d':a-=1
if c in'sk':a*=a
if c in'oc':print a
if a in(-1,256):a=0
```
This is neat, but also pretty straightforward.
Here's a longer, cooler version:
```
def i(a):
while 1:
c=yield
if c in'ix':a+=1
if c=='d':a-=1
if c in'sk':a*=a
if c in'oc':print a
if a in(-1,256):a=0
j=i(0);next(j)
while 1:
for c in raw_input(">> "):j.send(c)
```
Weighing in at 190 characters, it's perhaps not the most competitively-lengthed answer here. On the other hand, coroutines are pretty rad and I'm always looking for an excuse to use (and share) them
[Answer]
# TI-BASIC, ~~104 107~~ ~~102~~ ~~100~~ 98
For TI-83+/84+ series calculators.
Name this `prgmD`; it eventually overflows the stack by calling itself. Replace the recursion with a `While 1`, at the cost of two bytes, to fix this.
```
Input ">>",Str1
For(I,1,length(Str1
int(.5inString("?ixskd?oc",sub(Str1,I,1
If Ans=4
Disp Y
imag(i^Ans)+Y^int(e^(Ans=2 //decrements when Ans=3; increments when Ans=1
min(0,Ans(Ans≠256→Y
End
prgmD
```
Y is 0 by default, so either run this with a freshly memory-cleared calculator or store 0 to Y manually before running this.
Too bad that the lowercase letters (in the string literals) are two bytes each; otherwise this would be shorter than Dom Hastings' answer.
EDIT: Fixed a divide-by-zero (0^0) error at the cost of three bytes.
107 -> 102: Used imaginary exponentiation trick to save four bytes (including 1 from parentheses and -1 from lengthening the lookup string) and used Y instead of X, which takes one less byte to initialize.
[Answer]
# Postscript 272
```
/cmd<</i{1 add}/x 1 index/d{1 sub}/s{dup mul}/k 1 index/o{dup =}/c 1 index>>def
0{(>> )print flush{/f(%lineedit)(r)file def}stopped{exit}if{f
1 string readstring not{exit}if cmd exch 2 copy known{get exec}{pop pop}ifelse
dup -1 eq 1 index 256 eq or{pop 0}if}loop pop}loop
```
Ungolfed:
```
/cmd << % define commands
/i { 1 add }
/x 1 index
/d { 1 sub }
/s { dup mul }
/k 1 index
/o { dup = }
/c 1 index
>> def
0 % accumulator on stack
{
(>> )print flush % print prompt
{ /f (%lineedit) (r) file def } stopped {exit} if % read input line or quit
{
f 1 string readstring not {exit} if % read 1-char string from line
cmd exch 2 copy known { get exec }{ pop pop } ifelse % execute command or don't
dup -1 eq 1 index 256 eq or { pop 0 } if % adjust accumulator if needed
} loop
pop
}loop
```
[Answer]
# C (~~224~~ 212 characters)
This is probably a bad language choice, but oh well. It's not that language like C can do better than some dynamic programming language. On Clang, you will need to specify a value for `return` (this is not necessary for gcc).
```
#define s(x,y)case x:y;break;
main(){int c=10,a=0;for(;;){switch(c){s(-1,return)s('i':case'x',++a)s('d',--a)s('s':case'k',a*=a)s('c':case'o',printf("%d\n",a))s(10,printf(">> "))}a!=-1&a!=256||(a=0);c=getchar();}}
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~186~~ 178 bytes
This needs to be run with `runhaskell` (or inside `ghci`) since they both set the `BufferMode` to `NoBuffering` by default which safes quite a lot of bytes:
```
infix 4#
-1#x=0#x
256#x=0#x
r#x:y=case x of 'i'->r+1#y;'x'->r+1#y;'d'->r-1#y;'s'->r^2#y;'k'->r^2#y;'o'->print r>>r#y;'c'->r#'o':y;_->r#y
r#_=putStr">> ">>getLine>>=(r#)
main=0#""
```
[Try it online!](https://tio.run/##Zc5fa4MwEADw93yKwzyoSMZatj7UmcfBoLDB9rwiGttDTeSSQvz0LtFBBwv580vuuNy1tr0ahgXHyZCDD1LDrVVwxRb1BbLp5j4d5YwJAa@GYCLl3KyVtWA0fL29Q5mzLQkq2HDS8ABZUUCSkarXOh2ZEV6sCxeZJ/mCukMPT5yJHffVI/ds/3z4FXF/nKumtgo8mA5STIWkYsfnMvV3tpFipY383kf2d5rAiVA7ICkpvjQxyEPgOJfnyDl8dq62rhMpIayLcifUSsoqI56zsUYdukqSZfFoe2tYPNA2rA3DwLr/81@sXCeaHw "Haskell – Try It Online")
### Explanation
This defines a new operator `state # source` (the fixity declaration allows us to drop parentheses when using it in conjunction with other operators `(+)`,`(-)`,`(^)`,`(:)` and `(>>)`):
* the first two lines "fix" the states `-1` and `256`
* it then matches the first character and acts upon it
* once it runs out of characters (`r#_`), it reads new ones and starts over again keeping the old state
To start the process we initialize the state with `0` and read a new source line, ie. begin with an empty source:
```
main=0#""
```
[Answer]
# [Python 3](https://docs.python.org/3/), 130 119 bytes
```
a=0
while 1:
for c in input(">> "):
a+=(c in'ix')-(c=='d')+(a*a-a)*(c in'sk')
if c in'oc':print(a)
a*=-1!=a!=256
```
[Try it online!](https://tio.run/##ZYzRCoMwDEXf@xXRl7QVYW5sD0L8l1AnBocV65j7@q52L4OFS3K495LlvY1@vsTIdFKvUR53aFoFg1/BgcxJy3PTZddBaZIPXJE@ApQdTa0dEfZoKs2Wazb2m4UJTerKkH@gd9guq8yb5sNmS3VTEBd0vt5i3CVMwavjSHCqT@Mh7z/@hYxZ4j8 "Python 3 – Try It Online")
This is just a conversion of [stackspace's response](https://codegolf.stackexchange.com/a/35738/106764) to Python 3, with an improvement to the wrap-around code. We gain 1 byte from losing the print statement, but save 4 bytes from switching to `input()`, and remove another 6 from the new wrap-around code.
Edit: Saved another 11 bytes by moving all the math operations onto one line. Moving the square operation doesn't actually save any bytes, but it does look cooler.
[Answer]
# Lua, 230 228
```
a=0repeat io.write(">> ")x=io.read()for i=1,#x do c=x:sub(i,i)if c=="i"or c=="x"then a=a+1 elseif c=="d"then a=a-1 elseif c=="s"or c=="k"then a=a*a elseif c=="o"or c=="c"then print(a)end if a==256or a==-1then a=0 end end until _
```
Not the worst, not the best.
NOTE: as reported by [@mniip](https://codegolf.stackexchange.com/users/7162/mniip) `256or` may not work in your interpreter. More info in comments.
(more or less) Readable version:
```
a=0
repeat
io.write(">> ")
x=io.read()
for i=1,#x do
c=x:sub(i,i)
if c=="i"or c=="x"then
a=a+1
elseif c=="d"then
a=a-1
elseif c=="s"or c=="k"then
a=a*a
elseif c=="o"or c=="c"then
print(a)
end
if a==256or a==-1then
a=0
end
end
until _
```
Output:
```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>
```
Edit: thanks to [@mniip](https://codegolf.stackexchange.com/users/7162/mniip) for 2 char optimization: `until nil` -> `until _`
[Answer]
## Windows Batch, 204 256
```
@echo off
set a=0
:a
set /p i=^>^>
if %i%==i set /a a=%a%+1
if %i%==x set /a a=%a%+1
if %i%==d set /a a=%a%-1
if %i%==s set /a a=%a%*%a%
if %i%==k set /a a=%a%*%a%
if %i%==o echo %a%
if %i%==c echo %a%
if %a%==256 set a=0
if %a%==-1 set a=0
set i=n
goto a
```
Successfully ignores other commands. Really got bloated without having `or` to work with...
Edit:
>
> Fixed:
>
>
> * No more Echoing all commands
> * Made it actually DO math with /a
> * Reset on -1
> * Reset input after every cycle
>
>
> This cost 52 characters.
>
>
> Didn't fixed:
>
>
> * Squaring 0 writes "0\*0" in a.
> * Inputting space (or inputing nothing, when you just opened it) crashes script.
> * You NEED to input one char at a time.
>
>
>
[Answer]
## Windows Command Script - 154
Abusin unknown features to the max.
```
@echo off
set i=1
set x=1
set d=-1
set/as=[*[-[
set/ak=[*[-[
set.=0
set/p.=^>^>
set/a[=[+%.%
e%.:o=c%h%.:c=o% %[% 2>nul
set[=%[:-1=%
if;%[%==256 set[=
%0
```
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 258 bytes
I've done another ><> answer since I couldn't test [phase's](https://codegolf.stackexchange.com/a/52559/41881) and it used pre-stacked commands rather than emulating a shell anyway.
```
0v
"<vooo">>
!~>i:0)?v~ >
^?=a: / ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
voan:< ~< v*:~< < v-1~< v+1~< <
< < < <vv?=-10:v?=*:+1f:
v <> >~0
```
It can certainly be golfed down, but I'm not sure I'll have the needed ~~insanity~~bravery !
I tested it with the official interpreter running under python 3.5 under cygwin under windows 7 and could reproduce the test run :
```
$ python fish.py deadfish.fish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>> (pressed ctrl-Z)Stopped
```
In case you can't run it on your machine (input seems to be tricky) or you just want to try it without any other software, you can use the following version on the [online interpreter](http://fishlanguage.com/).
```
0v
<vooo">> "<
>i:0)?v~
o:/ ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
^oanoa:< ~< v*:~< < v-1~< v+1~< <
< < < <vv?=-10:v?=*:+1f:
v <> >~0
```
It obviously disregards \n and EOF since you can't input them in the online interpreter, but will behave as if enter had been pressed after each output command.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 139 bytes
Compile with `-Dk="_nZZiaeY"` (included in byte count). -2 bytes if prompt `>>\n` is allowed.
```
x;f(c){for(printf(">>");c=getchar()-10;x+=c--?c--?c--?c||printf("%i\n",x),0:x*x-x:-1:1,x*=~x&&x^256)c=strchr(k,c)-k>>1;f();}
```
[Try it online!](https://tio.run/##ZY3dCoJAEIXv9yliodgtBzWoC2XtppcoopBJbbE0doUG@nn0NhWKosOcMx/MwEEoEJ2jOBcor3ltxNnoqskFTxIuY1RF1uAhNUJCGMQ0UQiw@Ph2e38P9abiHkkviGhMQBGEUejRWD1oNKLtdDaXqGxj8GBE6aGEMknCtlTGd9@HZan4rlqvdZqtuDuluhLyyroruzvStrQ165a2yPat6kGff/wNPfaja8bYE/NjWlgHF/db9wI "C (gcc) – Try It Online")
## Degolf
```
/** Preprocessor **/
-Dk="_nZZiaeY" // This is a lookup string; it corresponds to "ixddskoc",
// with 10 deducted from each character. Upon compilation,
// all occurences of the string literal are replaced with a
// pointer to its location in memory.
/** Source **/
x;f(c){ // x: 32-bit accumulator, c: local variable for read character
for(printf(">>"); // Start for-loop and print prompt.
c=getchar()-10; // Read a character from STDIN.
// Loop breaks if it is '\n'.
// The below happens at the end of each iteration.
x+=c--?c--?c--?
// Find the correct operation by testing c and post-
// decrementing with multiple ternary-ifs. If c is 0,
// operation was found, add the else-value to the
// accumulator x.
// If the character is invalid, the value of c is
// very large, and will not reach 0 with 3 decrements.
c||printf("%i\n",x),0
// If c-3 is 0, print accumulator, else do nothing.
// Returns 0 regardless of what happens. (No change to x)
:x*x-x
// Square. Results in x=x+x*x-x, and is shorter than (x*=x)
:-1:1,
// Decrement, Increment.
x*=~x&&x^256
// Because -1==0xffffffff, ~x==0 when x==-1. Likewise,
// x^256==0 only when x==256. The logical-AND coerces the result
// to boolean 1 (no match) or 0 (match). Multiplication resets
// the accumulator as appropriate.
)
// This is the actual body of the for-loop
c=strchr(k,c)-k>>1;
// Finds the index of the read character in the lookup string,
// then "divides" it by two.
// Because strchr() returns NULL (0) when character is not found,
// deducting k from it results in a very negative number.
// The right-shift results in division by 2 for positive numbers,
// while the negative numbers become very large positive numbers
// (c >= 0x70000000) because of the 2's complement representation.
// Finally, recurse until forceful termination.
f();
}
```
[Answer]
## [Keg](http://esolangs.org/wiki/Keg), 68B
```
0{'::"ÿ1+=$0<+['_0"] \>\>\
,,,,?:o=[':."]:i=['1+"]:d=['1-"]:s=[':*"
```
[Answer]
## Haskell, 230
```
import System.IO
i""n=[]
i(a:b)n
|a=='o'||a=='c'=[n]++i b n
|True=i b$v a n
v a n=w(case a of 'i'->n+1;'x'->n+1;'d'->n-1;'s'->n^2;'k'->n^2)
w(-1)=0
w 256=0
w n=n
main=do;putStr ">> ";hFlush stdout;s <- getLine;print$i s 0;main
```
If only I could get rid of that pesky `hFlush stdout` call! Without it, the prompt is not displayed until an `o` operation is performed. Any advice?
[Answer]
## PHP+HTML 345
```
<form><?php $i=0;$o='';if(isset($_GET[i])){$i=$_GET[a];foreach(@str_split($_GET[i]) as $j=>$v){$v==i||$v==x?$i++:($v==d?$i--:($v==k||$v==s?$i*=$i:($v==o||$v==c?$o.=$i."\n":'')));($i==256||$i==-1)&&$i=0;}$_GET[p].='>> '.$_GET[i]."\n".$o;echo"<textarea locked name=p>$_GET[p]</textarea><input type=hidden name=a value=$i><br>";}?>>> <input name=i>
```
output is a little sketchy (history/session is shown on a textarea, and with error reporting enabled a lot warnings are printed) but everything works
[Answer]
# ><>, 239
```
v
\r0&
v <
\&::&01-=$f1+:*=+?v
v &0~&<
\:"i"=?v
>~&1+& ^
\:"d"=?v
>~&1-& ^
\:"s"=?v
>~&:*& ^
\:"o"=?v
>~&:o& ^
\:"h"=?v
>~; (^)
>~ ^
```
The initial stack is the input.
You can try it online [here](http://fishlanguage.com/playground/ZGgFCR2nTYSA6XGn5).
[Answer]
## Golf-Basic 84, 88 characters
```
:0_A:0_O:1_I:2_D:3_S:O_C:I_X:S_Kl`1i`N@A=256:0_A@N=0d`A@N=1:A+1_A@N=2:A-1_A@N=3:A^2_Ag`1
```
Prompts one command at a time, as in at least 3 other solutions. Here is a test run for `xiskisc`:
```
?X
?I
?S
?K
?I
?S
?C
289
```
Also, `xiskso` outputs 0, as it should.
[Answer]
# JavaScript (Node.js), 204 Bytes
```
process.openStdin(f=a=>process.stdout.write((i=0,""+a).split` `.map(x=>([...x.slice(0,-1)].map(d=>({i:x=e=>i++,d:e=>i--,s:k=e=>i*=i,o:c=e=>e,x,k,c})[d](i=-1||i==256?i=0:0)),i))+"\n>> "),f``).on("data",f)
```
This can probably be golfed. Node.js again proves it's strange disguised verbosity once again.
Code explained:
```
process.openStdin( // This function has to be called to take input, but doesn't have arguments
f=a=> // Define a function f. This is the deadfish interpreter. It takes an argument `a` which is a Buffer
process.stdout.write( // Same as console.log, but doesn't output trailing newline
(i = 0, "" + a) // Take advantage of comma operator to (A) define the accumulator i, and casts a (which is a Buffer) to a String
.split` ` // Split the string a at spaces, making it an array
.map( // Map through each element of the array
x=> // Map function, takes argument x, the value in the array (string)
([...x.slice(0,-1)] // Remove the last character (newline) and than use the spread operator to divide the string into an array of it's chars
.map(d=> // Map function, you know how this works
({ // Here I define the various deadfish commands
i: x = e => i++,
d: e => i--,
s: k = e => i*=i,
o: c = e => e,
// Take advantage of ES6 object notation. Equivilent to {"x": x, "k": k, "c", c}
x,
k,
c
})
[d] // Get the command to execute. If this is passed something which isn't valid, a giant error will appear
(
i==-1 || i==256 ? i = 0 : 0 // Take advantage of the fact that none of the command functions take arguments to handle the strange "overflow"
)
),
i)
) +
"\n>> "), // Display the prompt again, as well as a newline
f`` // Initalize the prompt by passing an empty script
)
.on("data",f) // Bind the f function to newline on STDIN
```
] |
[Question]
[
## Background
The Zundoko Kiyoshi function originates from [this tweet](https://twitter.com/kumiromilk/status/707437861881180160) by kumiromilk. Translated from Japanese, it reads roughly as follows:
>
> The test for my Java lecture had a problem that said "Implement and describe your own function". I made it continuously output either "zun" or "doko" randomly; if the sequence "zun", "zun", "zun", "zun", "doko" appears, it outputs "ki-yo-shi!" and terminates. Then I got full marks and earned a unit.
>
>
>
This is in reference to Kiyoshi Hikawa's song Kiyoshi no Zundoko Bushi: when he sings the aforementioned line, the crowd cheers "ki-yo-shi!" in response.
## Task
Write a program or function that takes no input and replicates the behavior outlined in the tweet:
* Repeatedly output either `zun` or `doko`, choosing uniformly randomly each time.
* If the sequence `["zun", "zun", "zun", "zun", "doko"]` appears in the output, output `ki-yo-shi!` and halt.
Example output:
```
doko
zun
zun
doko
doko
zun
zun
zun
zun
zun
doko
ki-yo-shi!
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* Your output can be a list of strings, or each string printed with some delimiter.
* Your output has to be non-deterministic.
[Answer]
# JavaScript (ES6), 72 bytes
```
f=x=>x%17^2?['doko ','zun '][j=Math.random()*2|0]+f(x<<7|j):'ki-yo-shi!'
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1q5C1dA8zsg@Wj0lPztfQV1Hvao0T0E9NjrL1jexJEOvKDEvJT9XQ1PLqMYgVjtNo8LGxrwmS9NKPTtTtzJftzgjU1H9f3J@XnF@TqpeTn66RpqGpoK2gnpMnromF4Ximv8B "JavaScript (Node.js) – Try It Online")
### How?
We keep track of the last 5 words in a 32-bit integer stored in \$x\$ (which is initially undefined). At each iteration, we left-shift it by 7 positions and set the LSB to \$0\$ for *doko* or \$1\$ for *zun*.
The sequence *zun, zun, zun, zun, doko* results in:
```
x = **1**000000**1**000000**1**000000**1**000000**0**
```
or \$270549120\$ in decimal, which is the only value for which we have \$x\equiv 2\pmod{17}\$, as shown [in this table](https://tio.run/##fZDNasMwEITveoo5pETCsUhdSghxeusT5FgKUS01dbEl4wgjcP3s7sr9IS0mc9FIs/q0q3fVqXPRlo1PrdNmHAtnz64ysnInvkSjvDetxQe@ZUKjrDb6N/kS5doUZa2q6GuncbvBUrA/tPRHSXpdyZwnGnt1La@xx3qHGjnuMlqTRKBnQJjOyTxJKV9KS9taenfwbWlPPBOyUfrgVev5/Qpr8SwJ9qiKN95h/zDdDshzbKj/ThDmsnUWZzwCi57AQxxx0Yd5eLaN9OF/yUXFdkojjAfc0EeJ2bJMDEd6V7BhHD8B). This is our halt condition.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~54~~ ~~50~~ 44 ~~43~~ ~~42~~ ~~39~~ 37 bytes
```
[.•BΓßb¥•#TΩDˆè¯J30bÅ¿#}"ki-yo-shi!"»
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/Wu9RwyKnc5MPz086tBTIVA45t9LldNvhFYfWexkbJB1uPbRfuVYpO1O3Ml@3OCNTUenQ7v//AQ)
~~I doubt string compression is going to help here. Prove me wrong.~~ It did help. -5 thanks to @Kevin
Forgive me, Adnan, for writing such a long program.
## Explained (old)
```
[1ÝΩ
```
First of all, we start an infinite loop, generate the range `[0, 1]` and pick a random object from that list.
```
D
```
We then duplicates that random number for later use.
```
.•BΓßb¥•#
```
Next, we push the compressed string "doko zun" and split it upon spaces.
```
sè,
```
Then, we swap that splitted string and the randomly generated number from earlier and index the string at that position. `,` prints the word to STDOUT.
```
ˆ¯5.£J
```
Here's where the fun begins. After the indexing and printing, we are left with the original random number on the stack. We append it to the global array and then push the global array to obtain the last 5 items from the list. This will be a string of 1s and 0s. The joining is simply to mould the list into a single string.
```
30b
```
We then convert the number 30 into its binary representation: 11110. This represents four zuns followed by a doko, as that's the order they appear in the compressed string from earlier.
```
Q#]
```
Then, we check to see if the last 5 items (which we joined into a string) is equal to the binary of 30. If it is, the infinite loop will stop, moving on to the next step. Otherwise, the above steps are repeated again.
```
"ki-yo-shi!",
```
At this stage, the loop has finished, meaning all that is left to do is print the required end string.
[Answer]
# [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), ~~347~~ ~~255~~ ~~170~~ ~~119~~ ~~115~~ 92 Bytes
```
for(int k=3;k!=1;Write(k%2<1?"zun ":"doko "))k=k<<7^new Random().Next(2);Write("ki-yo-shi!")
```
# Explanation
```
// Only every 7th bit changes
// k is set to three so that the code won't terminate until
// at least 5 shifts have occured
// Terminate when k is one
// so that every 7th bit matches 00001
for(int k=3;k!=1;){
k=k<<7;
// Shift the bits in k
k=k^new Random().Next(2);
// Set the last bit to random value
Write(k%2<1?"zun ":"doko ")
// Output zun or doko based on last bit
//zun = 0, doko = 1. kiyoshi = 00001
}
//we only get here if we have 00001
Write("ki-yo-shi!")
```
[Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb9IIzOvRCHb1tg6W9HW0Dq8KLMkVSNb1cjG0F6pqjRPQclKKSU/O19BSVMz2zbbxsY8Li@1XCEoMS8lP1dDU88vtaJEw0gTqk8pO1O3Ml@3OCNTUUnz/38A "C# (Visual C# Interactive Compiler) – Try It Online")
~~Added a TIO link and also saved almost 100 bytes :) (Not counting the `class Program` + `static void Main()` declarations and also implied `using System`).~~
~~My friends and I went back and forth with what I had originally and ended up with this. Basically cut the bytes in half. You can potentially run out of memory in the rare scenario that you never get a kiyoshi but whatever.~~
Thanks to Kevin and monicareinstate in the comments, this is now 119 bytes. Using the interactive compiler instead you can put functions outside of the main function and it implies `using`.
Last edit: we got this to 92 bytes! Can't even believe it given how verbose C# is.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 44 ~~42~~ ~~40~~ 38 bytes
```
Wn30i>5Y2%2>"dzoukno"eaYO2;"ki-yo-shi!
```
[Try it online!](https://tio.run/##K6gsyfj/PzzP2CDTzjTSSNXITimlKr80Oy9fKTUx0t/IWik7U7cyX7c4I1Px/38A "Pyth – Try It Online")
**Approach**: Repeatedly generate a random number from the set {0, 1} using `O2`. Store that number in the array `Y` and use it to index into the string `"dzoukno"` (which is `"zun"` and `"doko"` interleaved). Once the last five elements of `Y` are `[1,1,1,1,0]`, break the loop and print `"ki-yo-shi!"`.
[Answer]
# [K4](https://kx.com/download/), ~~56~~ ~~48~~ ~~47~~ 46 bytes
**Solution:**
```
{x,1?$`zun`doko}/[75-2/:<-5#;()],,"ki-yo-shi!"
```
**Example:**
```
q)k){x,1?$`zun`doko}/[75-2/:<-5#;()],,"ki-yo-shi!"
"doko"
"zun"
"doko"
"doko"
"doko"
"doko"
"doko"
"doko"
"doko"
"zun"
"zun"
"zun"
"zun"
"zun"
"zun"
"doko"
"ki-yo-shi!"
```
**Explanation:**
Generate `zun` or `doko` and append to a list whilst the distinct set of the last 5 elements aren't `zun zun zun zun doko`, and add `ki-yo-shi!` to the end.
Indices to order `zun zun zun zun doko` ascending are `4 0 1 2 3`. Converted from base-2 yields 75. Other combinations will not yield the same result.
```
{x,1?$`zun`doko}/[75-2/:<-5#;()],,"ki-yo-shi!" / solution
,"ki-yo-shi!" / 1-item list of "ki-yo-shi!"
, / append to
{ }/[ ; ] / {function}/[while;starting value]
() / empty list
-5# / take last 5 elements
< / indices to sort ascending
2/: / convert from base 2
75- / subtract from 75
$`zun`doko / string ($) -> ("zun";"doko")
1? / choose (?) 1 item from domain ("zun";"doko")
x, / append to input
```
**Extra:**
* **[K (oK) TIO](https://tio.run/##y9bNz/7/X6O6QsfQXiWhqjQvISU/O79WP9rcVNdI30bXVNlaQzNWU0dHKTtTtzJftzgjU1Hp/38A "K (oK) – Try It Online")** for **47 bytes** as we need an extra set of brackets but can drop a colon...
[Answer]
# [Python 2](https://docs.python.org/2/), ~~102 101 97 95 92~~ 91 bytes
*-3 bytes thanks to @dingledooper !*
*Thanks @JhynjhiruuRekrap for reminding that Python source code can include unprintable characters!*
*Thanks @xnor for saving 1 byte!*
```
import os
s=1
while~s%32:s+=s-(os.urandom(1)>"");print"dzoukno"[~s%2::2]
print"ki-yo-shi!"
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRCG/mKvY1pCrPCMzJ7WuWNXYyKpY27ZYVyO/WK@0KDEvJT9Xw1DTTqleSdO6oCgzr0QppSq/NDsvXykaqNrIysoolgsinp2pW5mvW5yRqaj0/z8A "Python 2 – Try It Online")
Stores the history as bits in the integer s, where 0,1 corresponds to "zun" and "doko". Each time, shift `s` by 1, then subtract the new bit. Stops when the lowest 5 bits of s are 11111, aka `~s%32 == 0`.
Generates a random 0 or 1 by generating a random byte, then checking if the byte is more than 127.
```
os.urandom(1)>"{unprintable DEL character}"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2Xµị“zun“doko”Ṅȧ;ɼḄß“ki-yo-shi!”%?32
```
A full program which takes no input and prints as it runs.
**[Try it online!](https://tio.run/##y0rNyan8/98o4tDWh7u7HzXMqSrNA5Ip@dn5jxrmPtzZcmK59ck9D3e0HJ4PFM7O1K3M1y3OyFQESqraGxv9/w8A "Jelly – Try It Online")**
### How?
```
2Xµị“zun“doko”Ṅȧ;ɼḄß“ki-yo-shi!”%?32 - Main Link (no arguments)
2 - literal two
X - random number in [1..x] -> z = 1 or 2
µ - start a new monadic chain, f(z)
“zun“doko” - list of strings = ["zun", "doko"]
ị - index into -> v = "zun" or "doko"
Ṅ - print v and a newline and yield v
ȧ - (v) logical AND (z) -> z
ɼ - recall from the register (initially 0), apply
- the following and store the result back
- into the register:
; - concatenate
Ḅ - convert from base-2 (e.g. [0,2,1,1,1,1,2] -> 96
- since 0×2⁶+2×2⁵+1×2⁴+1×2³+2×2²+1×2¹+2×2°=96)
? - if...
% 32 - ...condition: modulo 32 (is non-zero)
ß - ...then: call this Link again (Main Link)
“ki-yo-shi!” - ...else: string "ki-yo-shi!"
- implicit print
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 54 bytes
```
({⍵⌷'zun' 'doko'}¨⍪∘?∘2⍣{1 1 1 1 2≡¯5↑⍺}⍬)'ki-yo-shi!'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ooz39v0b1o96tj3q2q1eV5qkrqKfkZ@er1x5a8ah31aOOGfZAbPSod3G1oQIEGj3qXHhovemjtomPenfVPupdo6menalbma9bnJGpqA4y8X86VzoA "APL (Dyalog Classic) – Try It Online")
## Explanation
```
({⍵⌷'zun' 'doko'}¨⍪∘?∘2 {1 1 1 1 2≡¯5↑⍺} )'ki-yo-shi!'
⍬ ⍝ Start with an empty list
⍣ ⍝ Do this until the condition turns true:
⍪∘?∘2 ⍝ Append a random number in [1..2]
{1 1 1 1 2≡¯5↑⍺} ⍝ Condition: The list ends in "1 1 1 1 2"
¨ ⍝ For every item in this list:
{⍵⌷'zun' 'doko'} ⍝ 1-Index into the list ['zun','doko']
( )'ki-yo-shi!' ⍝ After that: Append the string 'ki-yo-shi!'
⍝ To the end of the output list
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 67 bytes
```
do{random($a=,'zun'*4+'doko')-ov +o}until("$o"-match$a)'ki-yo-shi!'
```
[Try it online!](https://tio.run/##BcFbCoAgEAXQrVQI08u/flvMkIKSesOsqGjt0zkbLpt3Z0MQMXgzJ4PYKp5Heo5E/TSQwQrqNM5qwHek4kPbKDQ6clmc4o5Wr2/o3fmaRH4 "PowerShell – Try It Online")
Unrolled:
```
do{
$array=,'zun'*4+'doko' # 'zun','zun','zun','zun','doko'
random $array -OutVariable +out # choose one element from the array randomly. 'doko' may appear in 20% of cases. it's still random.
# output a result to the output channel (console by default) AND to the variable $out.
# '+out' means adding to $out instead of replacing of $out
# see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters
}until("$out" -match $array) # powershell casts the $array to a string implicitly
'ki-yo-shi!'
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 50 bytes
```
/(n¶.+){4}o$/^+?(`\z
zun¶
)`\z
doko¶
\z
ki-yo-shi!
```
[Try it online!](https://tio.run/##K0otycxLNPz/X18j79A2PW3NapPafBX9OG17jYSYKq6qUqAolyaImZKfnQ9kA1nZmbqV@brFGZmK//8DAA "Retina – Try It Online") Explanation:
```
/(n¶.+){4}o$/^+
```
Repeat until the buffer ends with 4 lines ending with `n` and a line ending in `o`. Note that the `$` anchor works like `\Z` or `¶?\z`, so I don't need to match the trailing newline explicitly.
```
?(`
)`
```
Execute one of the inner stages chosen randomly.
```
\z
zun¶
\z
doko¶
```
Append either `zun` or `doko`. Note that I can't use `$` here as I only want to match the very end and the `$` would match before the final newline as well as after it.
```
\z
ki-yo-shi!
```
Finally append `ki-yo-shi!`.
[Answer]
My first attempt at a golf, and using a language not remotely suited for golfing, no less! ~~I can't think of any ways to shrink this~~ because Lua is a verbose, spacey language. But I still love her anyways.
I should give a heads-up: when the Lua interpreter starts, its pRNG seed seems to always default to the same value (rather than polling `/dev/random` or something), so running it once will always provide the same result. TIO, therefore, creates the same output repeatedly. [This will change when 5.4 is released](https://www.lua.org/work/doc/manual.html#8.2).
Credits to manatwork for a 22% reduction over four changes.
# [Lua](https://www.lua.org/), ~~132~~ ~~123~~ ~~107~~ ~~104~~ 103 bytes
```
z=0repeat if math.random(2)<2then print"zun"z=z+1 else w=z>3z=0print"doko"end until w print"ki-yo-shi!"
```
[Try it online!](https://tio.run/##LctRCoMwDADQq2T9coji3O/qXQrNaLCmUlOKuXw30O/Hi8W1pnbKuKMToC9sTsKYHfu0dfPzM0tAhj0Ti9HCRq32L8B4IFSry/t/L/RpTQbZQ2GhCPU@Kw1nGo5AD9PaDw "Lua – Try It Online")
Explanation, because why not?
```
z=0 --set a variable to count consecutive "zun"s
repeat --loop until we hit the target circumstance
if math.random(2)<2 then --pick 1 or 2: 1 = "zun", 2 = "doko"
print"zun" --print "zun"
z=z+1 --increment the "zun" counter
else --when the pRNG lands 2
w=z>3 --after 4 consecutive "zun"s, w will be false
z=0 --reset the counter
print"doko" --print doko
end
until w --loop kills when w is defined (as true)
--execution only gets here if we succeed...
print"ki-yo-shi!" --...so print "ki-yo-shi!" and halt
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~71...59~~ 57 bytes
*-4 bytes thanks to @ValueInk!*
```
$/+=p %w[zun doko].sample until$/=~/n.{9}d/;p'ki-yo-shi!'
```
[Try it online!](https://tio.run/##KypNqvz/X0Vf27ZAQbU8uqo0TyElPzs/Vq84MbcgJ1WhNK8kM0dF37ZOP0@v2rI2Rd@6QD07U7cyX7c4I1NR/f9/AA "Ruby – Try It Online")
Stores output history by appending `zun` or `doko` to the string `$/` (the predefined input record separator). Halts when the string contains an `n`, followed by exactly 9 characters, followed by a `d`. This can only occur when the string ends with `zu**n**zunzunzun**d**oko`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~104~~ \$\cdots\$ ~~96~~ 91 bytes
Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved a byte thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!
Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
f(m){srand(time(0));for(m=3;m%32-1;m+=m+puts(rand()%2?"doko":"zun")-4);puts("ki-yo-shi!");}
```
[Try it online!](https://tio.run/##bY7LCoMwEEX3fkUaECaEgNV206n0R7oRHzXYJKKR0orfnkaxtovezTCcw@Xm4pbnzlWg2Nh3mS7ASlVCxBhWpgOVJqjCJBZ7VDxVvB1sD4vGwvhCC9MYeqKvQVMmDgwXTBspnkb0tdxRhpNTmdTAyBgQn7lUakskSUmE/pzJEQnn8iPMmQXrhXUKbqCCn6ftvFcBFX9y9YO@5qOW9xJ841a5wimY3Bs "C (gcc) – Try It Online")
**How**
\$m\$ stores a history of what's randomly been printed over time in its bits, the least-significant bit storing the most recent. A bit in \$m\$ at time \$t\$ is set to:
$$
m\_t = \left\{
\begin{array}{ll}
0 & \text{zun} \\
1 & \text{doko}
\end{array}
\right.
$$
When the binary pattern \$00001\_2\$ occurs in the least-significant \$5\$ bits of \$m\$ the sequence \$(\text{zun}, \text{zun}, \text{zun}, \text{zun}, \text{doko})\$ has just appeared. \$m\$ is initialised to \$11\_2\$ so, at the beginning, it appears as though \$(\text{doko},\text{doko})\$ has just occurred forcing at least \$5\$ spins before \$00001\_2\$ can occur.
[Answer]
# [Python 2](https://docs.python.org/2/), 94 bytes
```
from random import*
s=""
while"zo">s[-21::19]:s+=choice(["zun,","doko,"])
print s+"ki-yo-shi!"
```
[Try it online!](https://tio.run/##DcU7DoMwEAXA3qcgryLBLqCLJbgIooj4yCvAa3mNEFzeYZoJV3Lsm5yXyHsRf356oj1wTB8lLaBOR9uMm9FJb5ra2vo7WKna0TGNc9njPryGxsQrawxvFSL5VEiFlczFRhy9kPMf "Python 2 – Try It Online")
This is an improvement based on an older version of [Surculose Sputum's answer](https://codegolf.stackexchange.com/a/204458/20260).
The idea is to identify the ending sequence in the comma-separated string by checking that the 21st and 2nd characters from the end are `z` and `o` respectively.
```
...,zun,zun,zun,zun,doko,
^ ^
z o
```
This is the only ending that satisfies this. To get a `z` in the 21st-to-last position, the last five words must be exactly four `zun,` and one `doko,`, since their lengths of 4 and 5 can add up to 21 only as `4*4+5`. Then, the one `doko,` must be at the end to get `o` in the second-to-last position. Moreover, because `zo` is the largest string that could be made here, we can check inequality with `<` rather than `!=`, saving a byte.
It would be shorter to use `urandom` similarly to [Surculose Sputum's new answer](https://codegolf.stackexchange.com/a/204458/20260).
[Answer]
# [Julia 1.0](http://julialang.org/), 92 bytes
A simple recursive implementation. `i` keeps track of how often "zun" has occured.
```
f(i=0)=(r=rand(1:2);println([:zun,:doko][r]);r>1 ? i>3 ? print("ki-yo-shi!") : f() : f(i+1))
```
[Try it online!](https://tio.run/##JcxBDkAwEEDRq5TVTJAou0rrIGLRRMTQtDJIcPkSNm/18@fDkZVnjCOQLlEDa7Z@AKkqbFYmvzsPnboPn6shLKHvuMeGjRStIFO/fhGkCxVXKLaJkhSFEiP8UiYR3znGBw "Julia 1.0 – Try It Online")
[Answer]
# Java 10, ~~148~~ ~~141~~ ~~137~~ ~~136~~ ~~125~~ ~~123~~ ~~112~~ ~~110~~ 107 bytes
```
v->{var r="";for(int k=3;k!=1;r+=k%2<1?"zun/":"doko/")k=k<<7^(int)(Math.random()*2);return r+"ki-yo-shi!";}
```
Golfed version of [the approach that *@loohhoo* used in her C# answer](https://codegolf.stackexchange.com/a/204466/52210).
-4 bytes thanks to *@ceilingcat*.
An additional -11 bytes from *@loohhoo*'s new approach (after I helped her golf it a bit), so make sure to upvote her if you haven't already!
Uses `/` instead of newlines as delimiter.
[Try it online.](https://tio.run/##LY9NasMwEEb3OcVEEJAa7JB0Eais5gTJptBNaWEqO40iWwojWZAGn92VqTcD88N8710xYXGt7ahbDAGOaNxjAWBcbOiMuoHT1AK8RTLuBzR/96aGJGSeDotcQsRoNJzAgYIxFa@PhASkGJNnTzw/AquepV2qraS1sqtdtT2w395t2AurvfUbJqyyVbX/mo4FP2K8lISu9h0XTzshqYk9OaA1s6a4@yJczJLJYZRT/K3/bnP8TJEmuC478H/ej09AMQvcQ2y60vexvOVV5K7U3PVtK2aXYfwD)
**Explanation:**
```
v->{ // Method with empty unused parameter and String return-type
var r=""; // Result-String, starting empty
for(int k=3; // Bit-mask integer
k!=1; // Loop as long as `k` is not 1 yet:
; // After every iteration:
r+=k%2<1? // If `k` is even:
"zun/" // Append "zun" and a "/" to the result
: // Else (`k` is odd):
"doko/") // Append "doko" and a "/" to the result
k= // Change `k` to:
k<<7 // First bit-wise left-shift it by 7
^(int)(Math.random()*2);
// And then bitwise-XOR it with a random 0 or 1
return r // Return the result-String
+"ki-yo-shi!";} // appended with "ki-yo-shi!"
```
[Answer]
# [Zsh](https://www.zsh.org/), 83 bytes
```
>zun>doko
49744()<<<ki-yo-shi!>>*
*(){`sum<<<$@`||$@ `ls|shuf -n1|tee -a *`}
z* * *
```
[Try it online!](https://tio.run/##qyrO@P/frqo0zy4lPzufy8TS3MREQ9PGxiY7U7cyX7c4I1PRzk6LS0tDszqhuDQXKKHikFBTo@KgkJBTXFOcUZqmoJtnWFOSmqqgm6iglVDLVaWlAIT/kxNLFIDG/gcA "Zsh – Try It Online")
Outputs to the files named `zun` and `doko` (both should be identical).
* `>zun>doko` - create the files `zun` and `doko`
* `49744()` - define a function called `49744`
+ `<<<ki-yo-shi!` - output `ki-yo-shi!`
+ `>>*` - append to all files
* `*(){}` - define a function with the names of all the files in the current directory (i.e. `zun` and `doko`)
+ `sum<<<$@` - take the checksum of the arguments
+ ```` - try to execute that as a command
- the checksum of `zun zun zun doko` is `49744`, which is defined as a command. All other combinations are not.
+ `||` - if that fails (i.e. the arguments are not `zun zun zun doko`):
- `ls` - list all files in the current directory
- `shuf -n1` - pick one item at random
- `tee -a *` - append to all the files in the current directory, as well as being captured by the ````
- ```` - then pass that as the last argument to:
* `$@` - execute the arguments: the first argument is the command to execute, the remaining ones are passed as arguments. Since the first argument is always either `zun` or `doko`, this actually recurses, passing all but the first argument, with the new random string appended.
* `z* * *` - initial recursive call - call the function with the name "all files that start with `z`" (i.e. `zun`),
+ `* *` - with the arguments "all files" and "all files" (i.e. `doko zun doko zun`)
[Answer]
# VBScript, 257 bytes
```
Randomize():z="zun,":d="doko,":Do:a=a&Array(z,d)(Round(Rnd())):Loop While UBound(Split(a,","))<5:Do:a=Split(a,","):a(0)="a":a=Replace(Join(a,",")&Array(z,d)(Round(Rnd())),"a,",e):MsgBox a:Loop While Not Cbool(Instr(a,"zun,zun,zun,doko,")):MsgBox"ki-yo-shi!"
```
[Answer]
# [Raku](http://raku.org/), 61 bytes
```
(<doko zun>[{^2 .pick}...{:2[@_]%32==30}],'ki-yo-shi!')».say
```
[Try it online!](https://tio.run/##K0gtyjH7/1/DJiU/O1@hqjTPLro6zkhBryAzObtWT0@v2soo2iE@VtXYyNbW2KA2Vkc9O1O3Ml@3OCNTUV3z0G694sTK//8B "Perl 6 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
W›⁴⌕✂υ±⁵Lυ¹doko⊞υ‽⪪dokozun⁴υki-yo-shi!
```
[Try it online!](https://tio.run/##NYtBCsIwEEX3nmLMagLJQqir7nUjUuwJQjo0Q2NS0kTRy8couPjw4L1vnUk2Gl/r07EnwHMikylhp@DEYcLRsyUsCq40N4FHqeBCYc4OS8NDm5jiUoSUEoayuW97M2GKdxxXzxl/@l2CUNC1qN8NiUNu7z@JhfUr6s3xXsi@1qof/gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W›⁴⌕✂υ±⁵Lυ¹doko
```
Repeat until the string `doko` is the last of the last 5 strings in the initially empty list (thus the first four must all be `zun`)...
```
⊞υ‽⪪dokozun⁴
```
... split the string `dokozun` into substrings of length at most 4 and push one randomly to the list.
```
υki-yo-shi!
```
Output the list and `ki-yo-shi!`. (Charcoal automatically outputs each list element on its own line.)
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), 109 bytes
```
Join[NestWhile[#~Join~{RandomChoice@{z,d}}&,{},#[[-5;;]]=!={z,z,z,z,d}&]/.z->"zun"/.d->"doko",{"ki-yo-shi!"}]
```
[Try it online!](https://tio.run/##JcixCoMwFEDRb/EJTolOncQidOsgbZcOIUMwgTxs8qDGoQnx11NLucvlOBWscSrgrMp9QxPG2xt9EOVK6MVk1vC0@DKi3n@wp4fymtzFEs5mTJHpnBuWMquF4Ke@l3KohoP/6dzIro38DHHz0LX6OE0LAUuwIP8QXy1WkGWR5Qs "Wolfram Language (Mathematica) – Try It Online")
Pretty straightforward: randomly appends `z` or `d` to a list until the last five elements match `{z,z,z,z,d}`, converts each to the proper string, then appends `"ki-yo-shi!"`.
[Answer]
# [R](https://tio.run/#R) ~~161~~ ~~143~~ 69 bytes
An initial & fairly clumsy attempt at a code golf challenge involving text!, and defining
`b=c("doko","zun")`
as a header.
`for(i in -3:which(apply(matrix((a<-sample(0:1,2e5,r=T))[outer(1:5,1:1e5,"+")],5)*2^(0:4),2,sum)==15)[1])cat(b[1+a[i+5]],"\n")
cat("ki-yo-shi!")`
[Try it online!](https://tio.run/##FY7LDoIwEADvfgXuaVeWxKK9NPYvvNWaVMTQ8CgpEMWfx3qdTDITt4euEJ6hDcDwXQag7RUi@swPWXFS78ZXDbpx7Fbs3Rz9B9Fdisn1Y1fjUQkua8lRX4lMWOY6olCShRKJQg5kWdKhvCfzTFzytPSktZBkhKXKzfgwInfG59Jahluq7/4UWl@soZgav08/2w8 "R – Try It Online")
Using the original Japanese characters with
`b=c("ドコ","ズン")`
and
`cat("キヨシ!")`
brings the score down to 137 bytes...
>
> A better alternative to using `cat(` would be appreciated as the
> `,"\n"` part wastes 5 bytes for a `newline` command.
>
>
>
A different approach reducing the count
```
e=0
while(e<1){x=rt(1,1)<0)
cat(b[1+x],"\n")
e=e*x-x+(!x&-3>e)}
cat(a)
```
when adding
```
a="ki-yo-shi!"
```
to the header.
[Try it online!](https://tio.run/##K/qfZJusoZSSn52vpKNUVZqnpGmdaKuUnalbma9bnJGpqPQ/1daAqzwjMydVI9XGULO6wraoRMNQx1DTxoArObFEIynaULsiVkcpBqiVK9U2VatCt0JbQ7FCTdfYLlWzFqwmUfP/fwA "R – Try It Online")
[Answer]
# [ThumbGolf](https://github.com/easyaspi314/thumbgolf), 53 bytes
Machine code (little endian pairs):
```
2100 de78 0840 bf2c a008 a009 4149 de00
de3a f001 011f 291e d1f3 a001 de00 4770
696b 792d 2d6f 6873 2169 000a 757a 006e
6f64 6f6b 00
```
Commented assembly:
```
// Include ThumbGolf wrapper macros
.include "thumbgolf.inc"
.globl main
.thumb_func
main:
// Set our counter bitmask to zero
movs r1, #0
.Lloop:
// Store a 32-bit random integer into r0.
rand r0
// Using lsrs, test the lowest bit.
lsrs r0, r0, #1
// Set up an IT block, checking the carry flag set from lsrs
ite cs
// If the lowest bit was 1, set r0 to "zun"
adrcs r0, .Lzun
// Otherwise, set it to "doko"
adrcc r0, .Ldoko
// Add to the bitmask using adcs.
// r1 = r1 * 2 + (rand() & 1)
adcs r1, r1
// Print the string in r0
puts r0
// Print a newline. We could technically put the newline in the strings
// themselves for a THEORETICALLY identical byte count, but the true
// reason for this (and the main reason I added this instruction) is to
// make it so the string literals are aligned, preventing wide ADR.
putspc '\n'
// Mask the lowest 5 bits using wide AND
and r1, r1, #0b11111
// 0b11110 means zun zun zun zun doko, loop while it is not that
cmp r1, #0b11110
bne .Lloop
.Lloop.end:
// Print "ki-yo-shi!"
adr r0, .Lkiyoshi
puts r0
// Return
bx lr
// These string literals are very carefully placed so that they are
// all 4 byte aligned. That is the only reason for the trailing newline:
// it makes kiyoshi an even multiple of 4 bytes.
.Lkiyoshi:
.asciz "ki-yo-shi!\n" // 12 bytes (aligned)
.Lzun:
.asciz "zun" // 4 bytes (aligned)
.Ldoko:
.asciz "doko" // 5 bytes (aligned)
```
Output is to stdout.
It wasn't easy figuring out how to align my string literals, but it was definitely worth it.
Note that I created [ThumbGolf](https://github.com/easyaspi314/thumbgolf) after this question was submitted.
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), 66 bytes (filename).
Unprintables are as a backslash followed by its code point in three-digit octal.
```
\001.t.z\002.r.wzun.p.m\001.+.t\001o.r.ao.zdok.p.m\004.xki-yo-shi!.p.d.a\001.tXX.a.a
```
## With comments
```
XX.z
# heap: 1 as counter
.a\001.t.zXX.z
# choosing either zun or doko
.a\002.r.wXX.z
.azun.pXX.z
# increment counter
.a.m\001.+.tXX.z
# push o for next dot-z and get out
.a\001o.r.aXX.z
# if empty; then push o and get in
# else pop it and ignore next block
.ao.zXX.z
# reusing the o
.adok.pXX.z
# print kiyoshi and exit if counter is >4
.a.m\004.xki-yo-shi!.p.d.aXX.z
# else reset counter to 1
.a\001.tXX.aXX.z
# pop a garbage of an o if any
.a.a
```
[Try it online!](https://tio.run/##fVdrV@JIE/7ur2iykXQTcmlERWJ0GPR12FVGHdfjaNATSNBgSFgSFA3sX5@3upMImZ0zniPpp6q67n17jp5@/IFqeo0ifQfRhor2dre2bbqzs1PbCEJMcAm5g6cQiQlVoqdlLfSdg3KNGIwVOkhpBUh5iWd0EU@R0o6Qdacrez0k3VlBpSctHqfuBKnEiNwYKe7MmI3t6Bnpeq1muPNJOI3RafuhdXpqtg0cv01c9OjGgzAYlsscDcLx2A4ccqA57osWzHwf1Q7KtFzOJp@3rr6YgogzOaRMcgWcRcSEfeTmMh0oSyE3@3e3c/Pw7erIrOn6Vk48//qtc3P6/aH99fLyuH1lUuMOCWLyufXty8P18eW3ztduE3SgXrnMAwrRJIy8eYrkz6n07X@F3fHMt2MXRU9cNJzEMHwNp0408b24XLZ9z46Q8ogkSLMsiJ@EpWRK7CuVy92/T0/bZ0dmk6vHzJRjRE/eMOZZdRCTywhpqf4gAjIRZZaD0HBfbB8JJTS0/cgVFgsgcUVcdr6IXAdJkTbX3jQjgp93TeLT31GPySLgGwMoNheXhuEU@3bf9U0BjBokAS9xuMBci3Zf3xG1pNkyxL7RNTQr4Pgc9N6rqhVomtFvGcsUqpTWRG2iGXGGG3oBUkpFLVzh3b0CpBTEgzV2owCpvi1q3hp7qwD3gPuwBkH3YAV3dguQUpCO1hzdKkBKwfTLGnunAKkOYQ7XPNELkOoQprtme68AKa2L2nRNea0AKQXx1zX2bgHSGhibr7EbBUhrYPttjb1XgLQGxt7XsqQXIdiy1xzfLkBKIQ3xmu56AVIdbI3XsrJbgFQHW86a8kYB1qEC8hoE08oKbgG3tAbBEXENgqVNBpdSulwckq4Bje9cWnLCunduONCoJ2yOhVWLWNgK2K9asYioWVtWzaIaSEWaWoG2nuc7Xaqq6RtiKdHuXudv77bT00pJ1@j7oHBpvMGq0JBmaHf3GZc1k6ghRyvoUAIkZebv7j9Ve2AXPMB36RBcqH1CzIWnTCalI7UCLO5Zah3imXA3Ra3KqH1wAcqUAColEYxa2sToXwA1Fat@AgUfgs6HoKMd5YIFsZyT5aE5NcQkNfcJMdWwF3Bp1MopcYunVix1gWMFd0h571Ucpi2erlEgJJ6fXhqsxlk2iE14JdPg7HTWErxtXnyoVLlv8UWxJnk@vkBmjlqQl3lWXJ7ZVd7S/Jxkmvh/6krqSVb1X02U8r10rR6aN8z2S1OwqEASHgi@m4SB9zCIXobuNB7LJXFT6TFpi2JiaI@pDGtHK6FVa8lY59iiGc9e9yia9bHA6iFU2exDGAtN2Jyr3CxZZgaL8r8TPhK1/tS1nzmAsrWw4IfhBAVhjMZ2PHjygkcBRD/CBe0ycx8TrQ9OYkoId7PECXoKRAD/5GCTAwpAIkuBbPz4X7d1dmxKlq5TNVbf4VtTp@rr@yxQJ@qYk2U1Zt8Q6Haovjvhc8aqq/NnT3kL4XrilYDmqHaq5@ZGtVVb2mh/7V4dd6/MjY2BHblw9HFrAvIChCtaZVGxLH17t0LSi46kMQYXkeCmYxhuZA82JlMviIcfcxevA6QMgP1jaA5nwSD2wsBCRjQdmNLn45NON4mmcB@BY9F1yBLOyKEgneMjkny7e67@hUnPPDJg2JPljHmMSTJ149k0QCUZBDLynysyEA9oRv5rRWZaMupVgcrMKDTn3eBLklyaIMLtKoqRSV5mAjPcJkkapWDB32YoVNsZ7wRfVm8/dMMFy/cC90A/FPWmkrv0JTUgUoM32D3vXhn6TBBIgYRS0k/m/2bmZ4GZm2zhs8wddLYQBnYMuWZ3Ny9GucUJhPv65PkuLkH2SPiRNBglQFksZvgGGBk1wJ3qdfWo6pME1iSfklybIGD4pu8Gj/ETviYGu98YnX3fIDOMj0xwPIqn@Loqy50q9PW/Ag9CODyS641mfZssM@0e2DzHJytzD/is2q7eVr@T5MwU1Icm6sL6sZHjDrwxXMggMvfRncJ3MosFo23CXOMWbpzcA4M7Wd/db5fL7f3tBuEr0gBa@1/hvn63td0TYTO5Net1pZ1NThctiOBGOo3WIQdt09yqkSQVgYtx7AUzd8nSy0Tb@/UGyBxs7xJGSo2vzKaayXcTfyeordQbBquTcY5vK9/zQAd5ts/x1Sr8KKfefJTlBQowql6TpGPq3NDI5C0K6R6xpqyOFKVnXrOqMNTpcWJHlnscj3p5rqcri5BFzBcaqbBS56ZeVyvhJyfm@KLKTZRgabF8lgBd8Da4Ni/2mWA28Tqb8fbbGQe/mPH@YZ1N4daVlQdx7v0TrENzRR8D/ZltPfBGOMeMmXP62IbEpX37J2vbc2wfwkTZZkE3b7LgjdWir5hUqVWwva@TCqsKfPPk/fOzslG2Bm6y6PCo4hPoBrAhqJtwOqjQaUIT3bpTuCt5L14Ee53AmoAl3z4cHfiHo02/6W@Omnys8THUYpnuhOCWqfeg5uyp8PM@OiCClHk2xOlr4kMk27eFRchPGjM9b9IzHq5QcP6wN5syDZ7pYjCDkSMhCSnDWn4wwZXkHJcJe9DkRlzehOlpl0DD8UZ8lmVDlkf7mG2NrNkghWk6RxmEATF@7RyLwHF9F553UDRoYa6yY0Jjw6axD9NlmrYy3/A7XKNMob/TrVhOMWzURriwX5/hOY3YscGetXAVGiD@9J2xLg/H7EkHxOl/iKunuFNHSrdeEFgs8ASely14rnpO1Y29sVudDCaz6kv0bjjwMCWLtad8/bdP@UVsez7cTutrWWY35KTBrin8LiQtMGiwrADJ6Q1bqdH6br2xtVNvkEUfEgb5g6NSyMOF7dcUMUYizh/vrcuTh7PWzWLB59f1vR2i1RRaQ4QgKdut@2YfiTo5AJidFH2jbwrC8rh7lBOWElrM7ekjRN@Zo6x48x//Bw "ksh – Try It Online")
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 96 bytes
```
"ki-oy-shi!">"okod">"nuz">666661[p09?5Gfps[p<0]p<0&:p[o](10)opl[p>0]p>l:rp&s&+lr2=fp*[<<<&o;]p1]
```
[Try it online!](https://tio.run/##y6n8/18pO1M3v1K3OCNTUclOKT87PwVI5ZVWKdmZgYBhdIGBpb2pe1pBcXSBjUEsEKtZFUTnx2oYGmjmF@REF9gBBe1yrIoK1IrVtHOKjGzTCrSibWxs1PKtYwsMY///BwA "Ly – Try It Online")
This code uses 4 stacks, one for each of the output lines, and one holding `0|1` indicators of the last 4 output choices (picked using random numbers). Then it writes the `ki-oy-shi!` line and exits if the sum of the choices (and last choice) show that the exit pattern was generated.
```
"ki-oy-shi!">"okod">"nuz"> # Push the strings onto separate stacks
66666 # Initialize the stack to a "not done" state
1[p ...code... 1] # An infinite loop pattern
09?5Gfp # Pushes 0|1 on the stack randomly
s # Save the choice on the backup stack
[p<0]p< # Shift 1 or 2 stacks, depending on random choice
0&:p # Duplicate the stack with a 0 sep, pop the top 0
[o](10)op # Print one copy of the stack, plus LF, pop the 0
l[p>0]p> # Restore random choice, shift back 1 or 2 stacks
l: # Restore random choice, duplicate it on stack
rp # Reverse the stack, delete top (remove oldest choice)
&s&+l # Save stack, sum the choices, restore stack
r2=fp # Reverse stack to move sum on top, compare to 2
* # Combine with latest choice, if 1 we are done
[<<<&o;] # Time to go, switch stacks, print and exit
p # Delete the test results from the stack, then loop...
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `o`, 36 bytes
```
{₀℅:£J:5NȯB30≠«ǎ⌈8τ«½¥i,|}`ki-yo-∪Ǎ!
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=o&code=%7B%E2%82%80%E2%84%85%3A%C2%A3J%3A5N%C8%AFB30%E2%89%A0%C2%AB%C7%8E%E2%8C%888%CF%84%C2%AB%C2%BD%C2%A5i%2C%7C%7D%60ki-yo-%E2%88%AA%C7%8D!&inputs=&header=&footer=)
-7 thanks to lyxal.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 51 bytes
```
(⌷∘'zun' 'doko'¨⍪∘?∘2⍣{(2,⍨4/1)≡¯5↑⍺}⍬)'ki-yo-shi!'
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9/b/Go57tjzpmqFeV5qkrqKfkZ@erH1rxqHcVUMweiI0e9S6u1jDSedS7wkTfUPNR58JD600ftU181Lur9lHvGk317Ezdynzd4oxMRXWQgf/TudIB "APL (Dyalog Unicode) – Try It Online")
Slight improvement on the other solution, since the account is deleted.
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 54 bytes
```
;=aF;W-30;O I=x%R2"zun""doko"=a%+x*2a 32xO"ki-yo-shi!"
```
[Try it online!](https://tio.run/##rVnrU9tIEv9s/xWDUtga2U5kwVVt2cgUyUKKOgJZSC4fwBeELGNVZMknyTyWcP96rrvnoZFtcrd7ywfLmunHrx/T3WPC3m0Y/ngVp2GynER7RTmJs9ezUdNcSeKb2lJYPi6iFaI8Tm9rS2U8FzSTaBqnEUsSlmTpLX009eqn088fWL96vfh0zrzq9R8H52y3ej06fcd@qV7PP7N@RXx0cmHQnn4@MUg/n344uPi7XXBm40eL/bv/N653Dy5ArdgMZ0HOHF4xmFSAVYsYjdhutXd6@AU3U9gki74z/L63t0KDaogGzQSaJOFIWKN5e3Z2QkT4sU9GDtA2A8j5e0EA/AbWuyBZRpxfpmPebJIdEJXLsX9uHZ4d2T@GfnA0/NLbcYdn7Nh/2D73rN@XqWVNsm@Z5QfbnQfHC9iO93BmfYt7j1mvmMVb1g8OzNZQyHNAYBTMmY@Sh80mqF8EeRHZnD01G3FasnjYbMAqQekyZ7pMQ1gh5hDey/miWyzSS2/sP7ld9xlkNGIQR/TwdHHhzRsUHy/Y/Swuo2IRhFGzAd@TyIZ1YLcFjC6zrsqr9Gp6lbOn58uxzQevLE5QGvGU2Rqtz9qv2pwJEWp1C1avUljudMQK4GxESRGZC88CTjiLwm9smuUsXc5voryQeJgdF5P4Ni6VVNCO5vS72iLxdFjfZR3mSOSdDmc91nbboAKRxpzlUbnMU6aSR7BR/gxXMdwFeRzcJJFCASCS7D7K7RD0KSDs@3emwIX0FpIjvra5dE@8wfTY73chRr5eXkGHx1GmLZCkk@XCxpAy6dMeg7d1wKI4FEKagHHVbleYrLYIGjCDBRoUAyFQTOA7IFsERcnKWQTCgrwEYhkAR3kUAxpytESBNc7Yi2Dhs88p0I3KGQQfU7eMsxRgY8a6Y4AWKo8Uy8UCHc5VVqkV0/1m/oHbDWejDJXKixTyGAobZq5ELrzyqa1Pv1g4wgUscgMsbghTJRnVRWGqjbgRapAkWWjvut0@RwNxWRtBBqbLJAnyR9PQKj7nRng@tjUyUij5l@kKN6noowpZFDZZenD49t31b1snv54ZBptib@KNcr11uVs1we@PL16QWEY5iQzSCfvXMlCvKPbOVLGzrkI44H1b@@J4gy@IebfOXKd5plKZL1OM0FAWZ6fMClvVSjoAkNplHDLavVlOL73dscQhAt2i8qABFAs4VuXUBlKwfztJJpaqO9ScuihkVQAcCi1AtD2hv0a3x/o7dTvReMzFfWaV@TKyIAf1OqYkrE8DqCC4YWFmWZUT0E60XfYncsfXt1mWwM5N3QMv2lqZ9TODnD9ukQnzZg1mghjTvxQjJG2ZJYltQu0ytwsd4k9ATtcgYxf@cPDxtIu9WCQavB5f9l3XhXQCU@BVvRXx79HXkuFjaOSoYS16AN66@OHR547fVy0dKxx2dXzQpyceO0BwdHxy6LApFMdhQ6e21IdlOAwW3SRKaQIwfKXGJ@EzOHcvOWOVEXsTtjZsOHZMswT04j3yxRCaSoybum6E88VKBMhJ8bgqIeimeIxqivu4DGe2A55Zm7bAR0z@hdin2gftAUMtgsBHh@K8BlWYt8goKV5OjLWU5UPqwhUFjaVljq2LJtPLMX@q0gwGKKrtQvE5KK7LzqHi2bzlPkzxr6L8CJQgVfjoNioTGCrtFsWyhRHCFjmJUz6Mp7ZN8cSBIJzliKULecq5CLPvDjdihQenMUDoOxT6xOSI1UA6ZKjwopNk7axQvq3sEfR65121g5ymizXNNdBgNkD@@YtsEaW2obhr5RaNCoDKn4tOCfnoe@7uL7QuhwtbTCRTgD5Bo2CEg5Tt4nwH5DA70BvqANUqvWxYZB2fRiE8sUDJpbtBDukiV6MEx2eeObNUbqws@Q0siR5gjMPTvmbnVi3qdHfYwkq2Rniylh6gJan7xSD/tT2Qc@KGRNaVT3Yg65TGYht7EFdNaDTa5dVguVYOFesFDYf2doGM9cOwzgzuhNHH1AuVlFsVqdrA9hIFqRT7UguTPcuMgKwt0gtnlRfwYIiLDzpNxLPmOtZq0YWr10PSsRhzr2jcbihY26@dAvDY8MaZOmq5AX9ZFir6OifErCcAdTQgqpNQL7EkY2oZ4RHTdKMebXF7RWqY@5nKJU/EHOdfOgwiAESFy3jKfWWlxzenahiU6iGnzn6nchNX31EWh2m0S89S1ghpV28tO41sx1G9jlcwOVV0NnhhtT1v8IOz5gcR101emG8wzSEa3xRCDNCDbKqQfvsKLnlINOz1SJ50FLXM1UALj5a10//mp455s9kx2z9l2t7M9E/yZs0gcXWgNc@0cijdLrzus15/1cvEAhHow3Hr9eGo9WtM3p/k2oNyuYnH95GF4AyYXHF1KCgA3siVMfA4jTGOT3Fprh4U2iReuDtQ4UUU8B2vErMoj9oFSzOYreOkjFN2HzyCP9kkg7tqGd1GOfAssjRKyzjA2wWc8IzdR2wW3EVAKAUhecnmQbqEtHp8jato5Q1GAlxDnimWSYk/JpByXQgVSc@kUSprvqvzaZIV8SjvZUr3ZSCabK9G5dK9PUiwZz6C1ekkiSbsuoJ9raU84TcxsBlKKmNGKKzXU@@cyBuS1DGgP@v6uEdJvNIQsRjW6qVfr5b7zCwKe@bxQNaB/L2uxQTBPqsNkLTYZUaVRBmu4FSt2BP9AWm3fOhCxnQ0gsOKqZVNsgGbR/NwgWmWstH1/v9ryugvMGWkTNnaYIsvbZGm7L/sfaF1A2Tc3mc1Ak9TeKqxbm3CWb1o81RFMgVoeK2qLKItm3rGvskpa4nm//6/8MsiZIjR/MP2wKSujb@rtH5Vjevbf/iCo2be6oaDdI3aLUeXQqJBiWO/xm2USeRAik5HswnIX8A88WuYOYDWrGPmTCPZjuvTPJIa/PveYMdwy3txlfCNyatjNqb1u1MqLyRdfRZ2aoPuhXD0itDhaiv0NrXCHa7nA09z79LifxmUEBg@MRShvhToMcmcmTywELV2@jg80eAg8l9s0oMoOvIkgPZJNA2gSIJlavKMU9iMJ/TjUhCW0Kba22EbZ1Fc4eyF2y0K0z0QpkT5A8M8iFMcYlmQ34ZdEuo48P2O489YdO/Ef//YLqGpX@@ef/wH)
Uses the bitmask setup.
```
# Initialize with FALSE. We will coerce it to
# Number later, just get some form of 0.
; = mask FALSE
# loop while mask != 30
; WHILE( - 30
# chaining ftw
; OUTPUT
: IF (= x % RAND 2){"zun"}{"doko"}
# mask = ((mask << 1) | x) % 32
: = mask % (+ x (* 2 mask)) 32
) {
: NOP # we use "x" in the golfed code.
}
: OUTPUT "ki-yo-shi!"
```
] |
[Question]
[
A laser shoots a straight beam in one of the four orthogonal directions, indicated by `<>^v`. Determine whether it will hit the target `O` on a rectangular grid.
Each of these will hit (True):
```
.....
...O.
.....
...^.
.....
>O.
...
v....
O....
...........
...........
O.........<
...........
```
These will miss (False):
```
......
......
.^..O.
......
.....>
O.....
......
......
.O.
...
.v.
.....<.
..O....
```
**Input:** A rectangular grid of `.`, sized at least 2x2, with exactly one target `O` and one laser that's one of `<>^v`. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.
**Output**: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.
I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put `(no regex)` after the language name, your answer will appear separately in the leaderboard.
```
var QUESTION_ID=80196,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/80196/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Snails](https://github.com/feresum/PMA), 19 bytes
```
\>|\<l|\^u|\vd).,\O
```
The spec for this one can be implemented as literally as possible, no thinking required.
[Answer]
# Retina, ~~56~~ ~~52~~ ~~42~~ ~~38~~ ~~31~~ 30 bytes
*Saved 1 byte thanks to @MartinBüttner*
```
O.*<|>.*O|[vO](.*¶)[^O]*[O^]\1
```
Abuses properties of rectangles. Requires input to have a trailing newline.
[Try it online](http://retina.tryitonline.net/#code=Ty4qPHw-LipPfFt2T10oLipcbilbXk9dKltPXl1cMQ&input=Li4uTy4uLgouLi4uLi4uCi4uLl4uLi4K)
## Explanation
This works in three parts:
* Matching `>`
* Matching `<`
* Matching `^` and `v` this is because the logic for `^` and `v` are really the same, just the characters.
**Validating `<`**
This is simple:
```
O.*<
```
This matches an `O`, optionally followed by non-newline chars, then a `<`
**Validating `>`**
This is much the same as the previous way except the other way around. First a `>` is matched, then the `O`
**Validating `^` and `v`**
This was difficult to golf and took adverting of the input always being valid. First, we match whether it's `v` or an `O`:
```
[vO]
```
If it's an `^`, the first character that's encountered should be a `O`. So, this matches the first character to match. Next we count the amount of `.`s following it up to the newline:
```
(.*\n)
```
Next, this can go into two parts, I'll cover the first:
So first, we match until the following `O`, using:
```
[^O]*O
```
This optionally matches all non-`O` characters until an `O` is encountered, if this is successful, then it continues... if not, then the following happens...
Now, it attempts to find the `^` using:
```
[^^]*\^
```
`^` is a special character in regex so it needs to be escaped. `[^^]` matches all characters except `^`, this works the same as the above, if this succeeds, then the following happens...
So now, one of the above has matched succesfully, the `\1` checks and sees if the capture group from before `(.*\n)`, this capture group stored the amount of `.`s there were after either the `v` or `O` from before, so now `\1` just checks if the amount of dots in the same.
[Answer]
# Java (no regex), ~~413~~ ~~412~~ ~~246~~ ~~242~~ ~~212~~ ~~211~~ ~~209~~ 198 bytes
Competing in golf challenges using java has less sense than take a part in Formula 1 race on bicycle, but I'm not always doing thinks which makes any sense.
Here is my extremely long java solution
Golfed version
```
boolean l(char[][]w){int[]t={},l={};for(int y=0;y<w.length;y++)for(int x=0;x<w[0].length;x++){if(w[y][x]=='O')t=new int[]{x,y};if(w[y][x]=='<')l=new int[]{x,y,1};if(w[y][x]=='>')l=new int[]{x,y,2};if(w[y][x]=='v')l=new int[]{x,y,3};if(w[y][x]=='^')l=new int[]{x,y,4};};return(l[2]==1&&l[1]==t[1]&&l[0]>t[0])||(l[2]==2&&l[1]==t[1]&&l[0]<t[0])||(l[2]==3&&l[0]==t[0]&&l[1]<t[1])||(l[2]==4&&l[0]==t[0]&&l[1]>t[1]);}
```
and ungolfed
```
boolean l(char[][] w) {
int[] t = {}, l = {};
for (int y = 0; y < w.length; y++)
for (int x = 0; x < w[0].length; x++) {
if (w[y][x] == 'O')
t = new int[] { x, y };
if (w[y][x] == '<')
l = new int[] { x, y, 1 };
if (w[y][x] == '>')
l = new int[] { x, y, 2 };
if (w[y][x] == 'v')
l = new int[] { x, y, 3 };
if (w[y][x] == '^')
l = new int[] { x, y, 4 };
}
;
return (l[2] == 1 && l[1] == t[1] && l[0] > t[0])
|| (l[2] == 2 && l[1] == t[1] && l[0] < t[0])
|| (l[2] == 3 && l[0] == t[0] && l[1] < t[1])
|| (l[2] == 4 && l[0] == t[0] && l[1] > t[1]);
}
```
Seems like my entire concept was wrong, here is my shorter solution
```
boolean z(char[][]w){int x=0,y=0,i=0,a=w.length,b=w[0].length;for(;w[y][x]!=79;)if(++y==a){y=0;x++;}for(;i<(a<b?b:a);)if(i<b&w[y][i]==(i<x?62:60)|i<a&w[i][x]==(i++<y?'v':94))return 1<2;return 1>2;}
```
and ungolfed version
```
oolean z(char[][] w) {
int x = 0, y = 0, i = 0, a = w.length, b = w[0].length;
for (; w[y][x] != 79;)
if (++y == a) {
y = 0;
x++;
}
for (; i < (a < b ? b : a);)
if (i < b & w[y][i] == (i < x ? 62 : 60) | i < a
& w[i][x] == (i++ < y ? 'v' : 94))
return 1 < 2;
return 1 > 2;
}
```
**EDIT**
I rewrote code for looking for 'O', now it contains single loop is much shorter, and I also used @Frozn suggestion to replace some of characters with their ascii values.
In result,another 30 bytes bites the dust.
Another suggestion from @Frozn, and we are couple bytes closer to Python solution
Another rewrite drop one loop, and combine two if statements
[Answer]
# MATL (no regex), ~~26~~ ~~25~~ ~~24~~ 22 bytes
```
'>v<^'XJymfX!tZpYswJm)
```
[Try it Online!](http://matl.tryitonline.net/#code=Jz52PF4nWEp5bWZYIXRacFlzd0ptKQ&input=Wyc-Ty4nOyAnLi4uJ107)
[Modified version for all test cases](http://matl.tryitonline.net/#code=YGknPnY8XidYSnltZlghdFpwWXN3Sm0pRFQ&input=WycuLi4uLic7ICcuLi5PLic7ICcuLi4uLic7ICcuLi5eLic7ICcuLi4uLiddClsnPk8uJzsgJy4uLiddClsndi4uLi4nOyAnTy4uLi4nXQpbJy4uLi4uLi4uLi4uJzsgJy4uLi4uLi4uLi4uJzsgJ08uLi4uLi4uLi48JzsgJy4uLi4uLi4uLi4uJ10KWycuLi4uLi4nOycuLi4uLi4nOycuXi4uTy4nXQpbJy4uLi4uLic7ICcuLi4uLj4nOyAnTy4uLi4uJzsgJy4uLi4uLic7ICcuLi4uLi4nXQpbJy5PLic7ICcuLi4nOyAnLnYuJ10KWycuLi4uLjwuJzsgJy4uTy4uLi4nXQoK)
**Explanation**
```
% Implicitly grab input
'>v<^' % String literal indicating the direction chars
XJ % Store in the J clipboard
y % Copy the input from the bottom of the stack
m % Check to see which of the direction chars is in the input. The
% result is a 1 x 4 logical array with a 1 for the found direction char
f % Get the 1-based index into '>v<^' of this character
X! % Rotate the input board 90 degrees N times where N is the index. This
% Way we rotate the board so that, regardless of the direction char,
% the direction char should always be BELOW the target in the same column
t % Duplicate
Zp % Determine if any elements are prime ('O' is the only prime)
Ys % Compute the cumulative sum of each column
w % Flip the top two stack elements
J % Grab '>v<^' from clipboard J
m % Create a logical matrix the size of the input where it is 1 where
% the direction char is and 0 otherwise
) % Use this to index into the output of the cumulative sum. If the
% direction char is below 'O' in a column, this will yield a 1 and 0 otherwise
% Implicitly display the result
```
[Answer]
# CJam (no regex), 25
Earlier versions were wrong, this will have to do for now:
```
q~_z]{'.-HbI%}f%[HF].&~+,
```
[Try it online](http://cjam.aditsu.net/#code=q%7E_z%5D%7B%27.-HbI%25%7Df%25%5BHF%5D.%26%7E%2B%2C&input=%5B%0A%22...O.%22%0A%22.....%22%0A%22.....%22%0A%22...%5E.%22%0A%22.....%22%0A%5D)
**Explanation:**
```
q~ read and evaluate the input (given as an array of strings)
_z copy and transpose
] put the original grid and transposed grid in an array
{…}f% map the block to each grid (applying it to each string in each grid)
'.- remove all dots (obtaining a string of 0 to 2 chars)
Hb convert to base H=17, e.g. ">O" -> 62*17+79=1133
I% calculate modulo I=18
[HF] make an array [17 15]
.& set-intersect the first array (mapped grid) with 17 and 2nd one with 15
~+ dump and concatenate the results
, get the array length
```
I tried a few mathematical formulas for distinguishing between "good" and "bad" strings, and for each type of formula I tried plugging in various numbers. I ended up with the `HbI%` above.
"good" strings for the original grid are ">O" and "O<" and they give the result 17
"good" strings for the transposed grid are "vO" and "O^" and they give the result 15
"bad" strings for both grids are: ">", "<", "^", "v", "O", "", "O>", "Ov", "<O", "^O" and they give the results 8, 6, 4, 10, 7, 0, 1, 3, 1, 3
[Answer]
# Python 3 (no regex), 184 bytes.
Hooray for eval hacking!
```
def f(a,o=0,d={},q=''):
for r in a:
i=0
for c in r:d[c]=o,i;i+=1;q=(c,q)[c in'O.']
o+=1
z,y=d['O'];e,j=d[q];return eval("z%se and y%sj"%(('><'[q<'v'],'=='),('==',q))[q in'><'])
```
[Answer]
# TSQL (sqlserver 2012) (no regex), 358 bytes
```
DECLARE @ varchar(1000)=
'......'+ CHAR(13)+CHAR(10)+
'......'+ CHAR(13)+CHAR(10)+
'...0..'+ CHAR(13)+CHAR(10)+
'...^..'+ CHAR(13)+CHAR(10)
;
WITH C as(SELECT
number n,SUBSTRING(@,number,1)a,1+min(IIF(SUBSTRING(@,number,1)=char(13),number,99))over()m
FROM master..spt_values
WHERE'P'=type and
SUBSTRING(@,number,1)in('>','<','^','v','0',char(13)))SELECT
IIF(c.n%c.m=d.n%c.m and c.a+d.a in('0^','v0')or
c.n/c.m=d.n/c.m and c.a+d.a in('>0','0<'),1,0)FROM c,c d
WHERE c.n<d.n and char(13)not in(c.a,d.a)
```
Had to use funky linechange in the declaration to force the online version to execute it(assigning values to input variables doesn't affect the length calculation anyway)
[Try it online!](https://data.stackexchange.com/stackoverflow/query/489382/will-the-beam-hit)
[Answer]
# Pyth, 43 bytes
```
KxJ"^<v>"[[email protected]](/cdn-cgi/l/email-protection)}\Ohc_W>K1hf}@JKTCW!%K2.z@JK
```
[Live demo.](https://pyth.herokuapp.com/?code=KxJ%22%5E%3Cv%3E%22h%40Js.z%7D%5COhc_W%3EK1hf%7D%40JKTCW%21%25K2.z%40JK&input=.....%0A...O.%0A.....%0A...%5E.%0A.....&debug=1)
[Answer]
## JavaScript (ES6), 78 bytes
```
s=>s.match(`>.*O|O.*<|(?=v)([^]{${l=s.search`\n`+1}})+O|(?=O)([^]{${l}})+\\^`)
```
Regexp of course. Turned out to be similar in principle to the Ruby answer.
[Answer]
# Ruby, ~~71~~ ~~55~~ 54 bytes
Regex solution, which means that it's probably going to be easily beaten by Retina or Perl.
Returns an index number (truthy) if there is a match.
Now with a similar trick to @Downgoat Retina answer, matching for down and up beams at the same time.
```
->m{m=~/>\.*O|O\.*<|(?=[vO])(.{#{??+m=~/\n/}})+[O^]/m}
```
[Answer]
## JavaScript (ES6) (no regex), 126 bytes
```
s=>([n,o,l,r,u,d]=[..."\nO<>^"].map(c=>1+s.indexOf(c)),l>o&l-o<n&l%n>o%n||r&&r<o&o-r<n&r%n<o%n||u>o&u%n==o%n||d&&d<o&d%n==o%n)
```
Where `\n` represents the literal newline character.
[Answer]
## Clojure (no regex), 293 bytes
```
(defn z[f](let[v(sort(keep-indexed(fn[i v](if(some #{v}[\v\>\<\^\O])[(if(= v\O)\& v)i]))f))l(+(.indexOf f"\n")1)d((nth v 1)0)q((nth v 1)1)p((nth v 0)1)r(=(quot p l)(quot q l))i(> q p)](cond(= d\^)(and i(=(mod(- q p)l)0))(= d\v)(and(not i)(=(mod(- p q)l)0))(= d\>)(and(not i)r):else(and i r))))
```
Doesn't feel great. Straightforward solution, finding the index of corresponding characters and calculating if they're on the same line.
You can try it here <https://ideone.com/m4f2ra>
[Answer]
# Python (no regex), 105 bytes
```
def f(s):t=s.strip('.\n');return not['\n'in t,len(t)%(s.find('\n')+1)!=1,1]['>O<vO^'.find(t[0]+t[-1])//3]
```
returns True or False
First, strips '.' and '\n' from the ends so that the characters of interest, '0<>v^', are the first and last characters.
`'>O<vO^'.find(t[0]+t[-1])//3` - checks if the characters are a potentially valid arrangement. Evaluates to 0 for '>O' or 'O<', to 1 for 'vO' or 'O^', and to -1 for anything else.
`'\n'in t` - checks if the characters are in different rows,
`len(t)%(s.find('\n')+1)!=1` - checks if they are in different columns, and
`1` - is the default
The `not` inverts the result selected from the list, so the `return` expression is equivalent to:
```
t[0]+t[-1] in '>0<' and '\n' not in t or t[0]+t[-1] in 'vO^' and len(t)%(s.find('\n')+1)==1
```
[Answer]
# Julia (no regex), 98
```
a->(c=rotr90(a,findlast("i1Q/",sum(a-46)));
f(n)=find(any(c.!='.',n));b=c[f(2),f(1)];
(b'*b)[1]==97)
```
Function operating on an array of chars, normalizing by rotation, removing rows and columns containing only dots by range indexing and finally checking for location of 'O' taking into account if the remainder b is a column or row vector using matrix multiplication.
[Try it online](http://julia.tryitonline.net/#code=YSA9IHJlc2hhcGUoYiIiIgogICAgICAgICAgICAgIC4uLi4uCiAgICAgICAgICAgICAgLi4uTy4KICAgICAgICAgICAgICAuLi4uLgogICAgICAgICAgICAgIC4uLl4uCiAgICAgICAgICAgICAgLi4uLi4KICAgICAgICAgICAgICAiIiIsNiw1KSdbOiwxOjVdCgpwcmludCgoYS0-KGM9cm90cjkwKGEsZmluZGxhc3QoWzEwNSw0OSw4MSw0N10sc3VtKGEtNDYpKSk7CiAgICAgICBmKG4pPWZpbmQoYW55KGMuIT0nLicsbikpOwogICAgICAgYj1jW2YoMiksZigxKV07CiAgICAgICBiWzFdKnNpemUoYiwxKT09NzkpKShhKSkK&input=&debug=on)
[Answer]
## Python 2 (no regex), 268 bytes
```
import numpy
def q(i):
s=numpy.asmatrix(i)
for n in s:
n=n.tolist()[0]
try:
a=n.index("0")
if n.index(">")<a or n.index("<")>a:return 1
except:0
for n in range(len(i)):
c=[x[0] for x in s[:,n].tolist()]
try:
a=c.index("0")
if c.index("v")<a or c.index("^")>a:return 1
except:0
return 0
```
Truthy and Falsy values returned by the function are 1 and 0, respectively.
I haven't had a chance to golf yet. Honestly, I'm not too hopeful for this one...
Any suggestions would be greatly appreciated!
[Answer]
# C# (No Regex), 282 bytes
```
bool F(char[,]b){int k=0,l=1,m=1,n=0,o=0;for(int x=0;x<b.GetLength(0);x++)for(int y=0;y<b.GetLength(1);y++){char i=b[x,y];if(i=='O'){k=x;l=y;}if(new[]{'<','>','^','v'}.Contains(i)){m=x;n=y;o=i;}}return(o==60&&k==m&&l<n)||(o==62&&k==m&&l>n)||(o==94&&l==n&&k<m)||(o==118&&l==n&&k>m);}
```
Works like the java version but transpiled and reduced
### Expanded (Explanation included):
```
bool F(char[,] b)
{
// declare variables for goal x, goal y, laser x, laser y, and laser direction respectively (laser direction is char code for directions)
int k = 0, l = 0, m = 0, n = 0, o = 0;
// go through each cell
for (int x = 0; x < b.GetLength(0); x++)
{
for (int y = 0; y < b.GetLength(1); y++)
{
// get cell contents
char i = b[x, y];
// set goal position if goal
if (i == 'O')
{
k = x;
l = y;
}
// set laser position and direction if laser
if (new[]{ '<', '>', '^', 'v' }.Contains(i))
{
m = x;
n = y;
o = i;
}
}
}
// check everything is on the same line and in right direction
return (o == 60 && k == m && l < n) ||
(o == 62 && k == m && l > n) ||
(o == 94 && l == n && k < m) ||
(o == 118 && l == n && k > m);
}
```
[Answer]
# C (ANSI) (No regex), 237 bytes
```
#define l b[1][i]
main(i,b,c,d,x,y,z,p)char **b;{for(y=z=i=0,x=1;z<2&&(l==10?x=0,++y:1);i++,x++)if(l>46){if(l!=79)p=l;if(!z++)c=x,d=y;}i--;x--;z=(c==x)*((p=='v')*(l==79)+(p==94)*(l==p))+(d==y)*((p==60)*(l==p)+(p==62)*(l==79));return z;}
```
Expanded:
```
#define l b[1][i]
main(i,b,c,d,x,y,z,p)char **b;{
for(y=z=i=0,x=1;z<2&&(l==10?x=0,++y:1);i++,x++)
if(l>46){if(l!=79)p=l;if(!z++)c=x,d=y;}
i--;x--;
z=(c==x)*((p=='v')*(l==79)+(p==94)*(l==p))+(d==y)*((p==60)*(l==p)+(p==62)*(l==79));
printf("%i\n",z);
return z;
}
```
I think I took a decently different approach here compared to the Java or C# implementations. I got coordinates of the 'O' and arrow ((c,d) and (x,y)) and then compared them to see if the arrow was pointing in the correct direction.
Returns 0 if false and 1 if true
[Answer]
## [Grime v0.1](https://github.com/iatorm/grime/tree/v0.1), 31 bytes
```
n`\>.*a|a.*\<|\v/./*/a|a/./*/\^
```
Not a very interesting solution. Prints `1` for truthy instances, and `0` for falsy ones. [Try it online!](http://grime.tryitonline.net/#code=ZWAoXD4uKmF8YS4qXDx8XHYvLi8qL2F8YS8uLyovXF4pIw&input=Li4uLi4KLi4uTy4KLi4uLi4KLi4uXi4KLi4uLi4)
## Explanation
We simply search the input rectangle for a minimal-size (n×1 or 1×n) pattern that contains the laser and target in the correct order.
The `n`` flag makes the interpreter print the number of matches, of which there will always be at most one.
The rest of the line consists of four patterns separated by `|`-characters, which means a logical OR: a rectangle is matched if it matches one of the patterns.
The patterns work as follows:
```
\>.*a Literal ">", horizontal row of any chars, one alphabetic char
a.*\< One alphabetic char, horizontal row of any chars, literal "<"
\v/./*/a Literal "v", on top of vertical column of any chars, on top of one alphabetic char
a/./*/\^ One alphabetic char, on top of vertical column of any chars, on top of literal "^"
```
] |
[Question]
[
# Challenge:
Write a function or program that accepts a list of boolean values and returns all of the ranges of True's.
# Test Cases:
```
f [F] = []
f [T] = [[0,0]]
f [T,T,F,T] = [[0,1],[3,3]]
f [F,T,T,F,F,T,T,T] = [[1,2],[5,7]]
f [F,T,T,F,F,F,T,T,T,T] = [[1,2],[6,9]]
f [T,T,F,F,F,T,T,T,T,T,T,T,T,T,T,F] = [[0,1],[5,14]]
f [F,F,T,T,F,F,F,F,F,F,F,F,T,T,T,T,T,T,T,T,F,F,F,F,F,F,F,F,F,F,F,F,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,T,T] = [[2,3],[12,19],[33,54],[93,94]]
```
# Rules:
* You may choose how input is encoded, e.g. a list, array, string, etc.
* The output must be encoded as a list-like of list-likes or a string showing such, so arrays, lists, tuples, matrices, vectors, etc.
* The boolean values must be encoded as constants, but otherwise any simple conversion of T/F to desired constants is allowed
* EDIT: *eval* or similar during runtime IS allowed.
* Don't to forget to explain how input is passed to the program/function and give its input/output for the test cases
* Conversion to desired input format not counted
* [Standard loopholes are disallowed](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* If your language has a function to do this, it's not allowed
* I will not accept my own submission
* EDIT: Output format is flexible. If not printing a list or similar, range values must be separated by one non-numeric character and separate ranges as well.
# Scoring:
* Score is in bytes, unless unfit to your language (such as codels in Piet)
* Lowest score wins
There's a good bit of flexibility in input and output, but solutions where T/F are replaced with functions that do all the work are disallowed.
# Debugging:
If you write yours in Haskell or can call it from Haskell, the following will check your function/program:
```
import Test.QuickCheck
tf = cycle [True,False]
gen l = foldl (++) [] $ map (\i -> [tf!!i | x<-[1..i]]) l
putIn (a,b) l = zipWith (||) l [(a <= p) && (p <= b) | p <- [0..length l]]
putAllIn rs len = foldr putIn [False|i<-[1..len]] rs
main = print $ quickCheck (check functionNameGoesHere)
```
[Answer]
# Pyth, 18 bytes
```
CxR.:++~Zkz02_B_`T
```
[Test suite](https://pyth.herokuapp.com/?code=CxR.%3A%2B%2B~Zkz02_B_%60T&input=%0A0%0A1%0A1101%0A01100111%0A0110001111%0A1100011111111110%0A00110000000011111111000000000000011111111111111111111110000000000000000000000000000000000000011&test_suite=1&test_suite_input=0%0A1%0A1101%0A01100111%0A0110001111%0A1100011111111110%0A00110000000011111111000000000000011111111111111111111110000000000000000000000000000000000000011&debug=0)
True is represented as `1`, False as `0`.
Ranges are represented inclusively.
[Answer]
# Pyth, 17 16 bytes
```
fT.b*Y,~+ZNtZrQ8
```
Uses some fancy post-assign counter magic together with run length encoding.
Takes input as an array of `0`s and `1`s, e.g. `[1, 1, 0, 1, 0]`. Outputs like in the challenge, e.g. `[[0, 1], [3, 3]]`.
[Test Suite](https://pyth.herokuapp.com/?code=fT.b%2aY%2C~%2BZNtZrQ8&input=%5B0%5D%0A%5B1%5D%0A%5B1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D&test_suite=1&test_suite_input=%5B0%5D%0A%5B1%5D%0A%5B1%2C1%2C0%2C1%5D%0A%5B0%2C1%2C1%2C0%2C0%2C1%2C1%2C1%5D%0A%5B0%2C1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%5D%0A%5B1%2C1%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%5D%0A%5B0%2C0%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%5D&debug=0)
[Answer]
## [Retina](https://github.com/mbuettner/retina/issues), ~~82~~ ~~34~~ 27 bytes
```
\b(?<=(.)*_?)
$#1
_+
S_`:
```
The empty line should contain a single space.
Input is a flat string of `_` for true and `:` for false. Output is space-separated pairs, each on a separate line.
[Try it online.](http://retina.tryitonline.net/#code=XGIoPzw9KC4pKl8_KQokIzEKXysKIApTX2A6&input=Xzo6X186Ojo6Ojo6Ol9fX19fX19fOjo6Ojo6Ojo6Ojo6Ol9fX19fX19fX19fX19fX19fX19fX186Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ojo6Ol9f)
### Explanation
The heavy golfing from 82 down to 27 bytes was possible by clever choice of the representation of true and false. I've picked a word character, `_`, (that isn't a digit) for true and a non-word character, `:`, (that doesn't need escaping) for false. That allows me to detect the ends of ranges as word boundaries.
```
\b(?<=(.)*_?)
$#1
```
We match a word boundary. We want to replace that boundary with the corresponding index of the truthy value. In principle that is quite easy with Retina's recent `$#` feature, which counts the number of captures of a group. We simply capture each character in front of that position into a group. By counting those characters we get the position. The only catch is that the ends of the range are off by one now. We actually want the index of the character *in front* the match. That is also easily fixed by optionally matching a `_` which isn't captured, thereby skipping one character when we're at the end of a range.
```
_+
<space>
```
Now we replace all runs of underscores with a space. That is, we insert a space between the beginning and end of each range, while getting rid of the underscores.
```
S_`:
```
That leaves the colons (and we still need to separate pairs). We do that by splitting the entire string into lines around each colon. The `S` actives split mode, and the `_` suppresses empty segments such that don't get tons of empty lines when we have runs of colons.
[Answer]
## Python 2, 69 bytes
```
p=i=0
for x in input()+[0]:
if x-p:b=x<p;print`i-b`+';'*b,
p=x;i+=1
```
Example output:
```
2 3; 7 16; 18 18;
```
A direct approach, no built-ins. Tracks the current value `x` and the previous value `p`. When these are different, we've switched runs. On switching `0` to `1`, prints the current index `i`. On switching `1` to `0`, prints the current index minus one followed by a semicolon.
The `if` is pretty smelly. Maybe recursion would be better,
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 17 ~~18~~ ~~20~~ bytes
```
j'T+'1X32X34$2#XX
```
Uses [current version (9.1.0)](https://github.com/lmendo/MATL/releases/tag/9.1.0) of the language/compiler.
Input is a string containing characters `T` and `F`. Output is a two-row table, where each column indicates a range using 1-indexing, which is the language default.
Thanks to [Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) for removing 2 bytes.
### Example
```
>> matl
> j'T+'1X32X34$2#XX
>
> FTTFFFTTTT
2 7
3 10
```
### Explanation
It's based on a simple regular expression:
```
j % input string
'T+' % regular expression: match one or more `T` in a row
1X3 % predefined string literal: 'start'
2X3 % predefined string literal: 'end'
4$2#XX % regexp with 4 inputs (all the above) and 2 outputs (start and end indices)
% implicitly display start and end indices
```
[Answer]
# Octave, 43 Bytes
```
@(x)reshape(find(diff([0,x,0])),2,[])-[1;2]
```
`find(diff([0,x,0]))` finds all the positions where the input array changes between true and false. By reshaping this into a 2-by-n matrix we achieve two things: The changes from true to false, and from false to true are divided into two rows. This makes it possible to subtract 1 and 2 from each of those rows. Subtracting 1 from row one is necessary because Octave is 1-indexed, not zero-indexed. Subtracting 2 from row two is necessary because the `find(diff())` finds the position of the first false value, while we want the last true value. The subtraction part is only possible in Octave, not in MATLAB.
```
F=0;T=1;
x=[F,F,T,T,F,F,F,F,F,F,F,F,T,T,T,T,T,T,T,T,F,F,F,F,F,F,F,F,F,F,F,F,F,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,T,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,F,T,T]
reshape(find(diff([0,x,0])),2,[])-[1;2]
ans =
2 12 33 93
3 19 54 94
x=[T,T,F,F,F,T,T,T,T,T,T,T,T,T,T,F]
reshape(find(diff([0,x,0])),2,[])-[1;2]
ans =
0 5
1 14
```
[Answer]
## CJam, ~~27~~ 25 bytes
```
0qe`{~~{+}{1$+:X(]pX}?}/;
```
Expects input like `TTFTFT`. [Try it online](http://cjam.aditsu.net/#code=0qe%60%7B~~%7B%2B%7D%7B1%24%2B%3AX%28%5DpX%7D%3F%7D%2F%3B&input=FFTTFFFFFFFFTTTTTTTTFFFFFFFFFFFFFTTTTTTTTTTTTTTTTTTTTTTFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFTT).
### Explanation
```
0 Push 0, to kick off index
qe` Push input and run length encode
e.g. FFFFTTTFT -> [[4 'F] [3 'T] [1 'F] [1 'T]]
{ }/ For each pair in the RLE...
~ Unwrap the pair
~ Evaluate T -> 0 (falsy), F -> 15 (truthy)
{ }{ }? Ternary based on T/F
+ If 'F: add count to index
1$+:X(]pX If 'T: output inclusive range, updating index
; Discard the remaining index at the top of the stack
```
[Answer]
# Japt, ~~34~~ ~~31~~ 25 bytes
Trying a new approach really worked out this time.
```
V=[]Ur"T+"@Vp[YY-1+Xl]};V
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=Vj1bXVVyIlQrIkBWcFtZWS0xK1hsXX07Vg==&input=IkZURkZUVFRGVCI=)
Input is an string with `F` for `false` and `T` for `true`. Output is an array of arrays; the string representation makes it look like a single array.
### How it works
```
// Implicit: U = input string
V=[] // Set V to an empty array. (Why don't I have a variable pre-defined to this? :P)
Ur"T+" // Take each group of one or more "T"s in the input,
@ // and map each matched string X and its index Y to:
Vp[ // Push the following to an array in V:
Y // Y,
Y-1+Xl // Y - 1 + X.length.
]}; // This pushes the inclusive start and end of the string to V.
V // Implicit: output last expression
```
Note: I now see that several people had already come up with this algorithm, but I discovered it independently.
### Non-competing version, 22 bytes
```
;Ur"T+"@Ap[YY-1+Xl]};A
```
In the [latest GitHub commit](https://github.com/ETHproductions/Japt/commit/0e43c90f2853308f4f7f7aca7759dd29a1eac1a5), I've added a new feature: a leading `;` sets the variables `A-J,L` to different values. `A` is set to an empty array, thus eliminating the need to create it manually.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~12~~ 11 bytes
```
0J0p¯T⁽‹ẇ2ẇ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0J0p%C2%AFT%E2%81%BD%E2%80%B9%E1%BA%872%E1%BA%87&inputs=%5B0%2C0%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%2C1%5D&header=&footer=)
Translation of [my Jelly answer](https://codegolf.stackexchange.com/a/214394/98955).
## Explanation
```
0J0p¯T⁽‹ẇ2ẇ
0J Append 0
0p Prepend 0
¯ Deltas
T Truthy indices
⁽ ẇ Apply to even indices
‹ Decrement
2ẇ Split into chunks of 2
```
*-1 byte thanks to lyxal*
[Answer]
## Haskell, 74 bytes
```
import Data.Lists
map(\l->(fst$l!!0,fst$last l)).wordsBy(not.snd).zip[0..]
```
Usage example: `map(\l->(fst$l!!0,fst$last l)).wordsBy(not.snd).zip[0..] $ [True,False,True,True,False]` -> `[(0,0),(2,3)]`.
How it works:
```
-- example input: [True,False,True,True,False]
zip[0..] -- pair each element of the input with it's index
-- -> [(0,True),(1,False),(2,True),(3,True),(4,False)]
wordsBy(not.snd) -- split at "False" values into a list of lists
-- -> [[(0,True)],[(2,True),(3,True)]]
map -- for every element of this list
(\l->(fst$l!!0,fst$last l)) -- take the first element of the first pair and the
-- first element of the last pair
-- -> [(0,0),(2,3)]
```
[Answer]
## J, 26 bytes
```
[:I.&.|:3(<`[/,]`>/)\0,,&0
```
This is an unnamed monadic verb (unary function) that returns a 2D array or integers.
It is used as follows.
```
f =: [:I.&.|:3(<`[/,]`>/)\0,,&0
f 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0
0 1
5 14
```
## Explanation
```
[:I.&.|:3(<`[/,]`>/)\0,,&0
,&0 Append 0 to input
0, then prepend 0.
3( )\ For each 3-element sublist (a b c):
]`>/ Compute b>c
<`[/ Compute a<b
, Concatenate them
Now we have a 2D array with 1's on left (right) column
indicating starts (ends) or 1-runs.
[:I.&.|: Transpose, get indices of 1's on each row, transpose back.
```
[Answer]
# Ruby, 39
```
->s{s.scan(/T+/){p$`.size..s=~/.#$'$/}}
```
Sample invocation:
```
2.2.3 :266 > f=->s{s.scan(/T+/){p$`.size..s=~/.#$'$/}}
=> #<Proc:0x007fe8c5b4a2e8@(irb):266 (lambda)>
2.2.3 :267 > f["TTFTTFTTTFT"]
0..1
3..4
6..8
10..10
```
The `..` is how Ruby represents inclusive ranges.
The one interesting thing here is how I get the index of the end of the range. It's weird. I dynamically create a regular expression that matches the last character of the range, and then all subsequent characters and the end of the string in order to force the correct match. Then I use `=~` to get the index of that regex in the original string.
Suspect there might be a shorter way to do this in Ruby using the -naF flags.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 11 10 bytes
```
;0ŻIT’Ðes2
```
[Try it online!](https://tio.run/##y0rNyan8/9/a4Ohuz5BHDTMPT0gtNvr//3@0gY6BjiEQGqBBQzRogBMakgANqAiB5sUCAA "Jelly – Try It Online")
Accepts a list of zeros and ones. Outputs a list of 1-based ranges.
## Explanation
Using [1,1,0,1] as an example.
```
;0ŻIT’Ðes2 Main monadic link
;0 Append a zero: [1,1,0,1,0]
Ż Prepend a zero: [0,1,1,0,1,0]
I Increments: [1,0,-1,1,-1]
T Indices of truthy alements: [1,3,4,5]
Ðe Apply to even indices:
’ Decrement: [1,2,4,4]
s2 Split into groups of two: [[1,2],[4,4]]
```
[Answer]
# JavaScript (ES6), 59
An anonymous function, input as a string of `T` and `F`, returning output as an array of arrays
```
x=>x.replace(/T+/g,(a,i)=>o.push([i,a.length+i-1]),o=[])&&o
```
**TEST**
```
f=x=>x.replace(/T+/g,(a,i)=>o.push([i,a.length+i-1]),o=[])&&o
// TEST
arrayOut=a=>`[${a.map(e=>e.map?arrayOut(e):e).join`,`}]`
console.log=x=>O.textContent+=x+'\n'
;[
'F','T','TTFT','FTTFFTTT','FTTFFFTTTT','TTFFFTTTTTTTTTTF',
'FFTTFFFFFFFFTTTTTTTTFFFFFFFFFFFFFTTTTTTTTTTTTTTTTTTTTTTFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFTT'
].forEach(t=>console.log(t+'\n'+arrayOut(f(t))+'\n'))
```
```
<pre id=O></pre>
```
[Answer]
# ùîºùïäùïÑùïöùïü, 18 chars / 28 bytes
```
ïħ`T+`,↪ᵖ[_,$Ꝉ+‡_]
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=TTFT&code=%C3%AF%C4%A7%60T%2B%60%2C%E2%86%AA%E1%B5%96%5B_%2C%24%EA%9D%88%2B%E2%80%A1_%5D)`
# Explanation
```
ïħ`T+`,↪ᵖ[_,$Ꝉ+‡_] // implicit: ï=input
ïħ`T+`, // for each T-sequence...
↪ᵖ[_,$Ꝉ+‡_] // push [start index of sequence, end index of sequence] to the stack
// implicit stack output
```
[Answer]
## Haskell, 62 bytes
```
f l|s<-zip3[0..](0:l)$l++[0]=zip[i|(i,0,1)<-s][i-1|(i,1,0)<-s]
```
Takes as input a list of 0's and 1's.
Given the list `l`, pads it with 0 on both sides and computes the indexed list of consecutive pairs. For example
```
l = [1,1,0]
s = [(0,0,1),(1,1,1),(2,1,0),(3,0,0)]
```
Then, extract the indices corresponding to consecutive elements `(0,1)` and `(1,0)`, which are the starts of blocks of 0 and 1, subtracting 1 from the starts of 0 to get the ends of 1, and zips the results.
[Answer]
## Pyth, ~~19~~ 18 bytes
```
m-VdU2cx1aV+ZQ+QZ2
```
Explanation:
```
implicit: Q=input
m map lambda d:
-V Vectorized subtraction by [0,1]
d
U2
c split every 2 elements
x find all indexes of
1 1s
aV in vectorized xor:
+ZQ Q with a 0 on the front
+QZ Q with a 0 on the end
2
```
Try it [here](https://pyth.herokuapp.com/?code=m%2Chdtedcx1aV%2BZQ%2BQZ2&input=1%0A0%0A0010%0A10011000%0A1001110000%0A0011100000000001%0A11001111111100000000111111111111100000000000000000000001111111111111111111111111111111111111100&test_suite=1&test_suite_input=%5B0%5D%0A%5B1%5D%0A%5B1%2C+1%2C+0%2C+1%5D%0A%5B0%2C+1%2C+1%2C+0%2C+0%2C+1%2C+1%2C+1%5D%0A%5B0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+1%5D%0A%5B1%2C+1%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+0%5D%0A%5B0%2C+0%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+0%2C+1%2C+1%5D&debug=0).
[Answer]
## Perl, 47 bytes
```
s/F*(T*)(T)F*/[$-[0],$+[1]],/g;chop$_;$_="[$_]"
```
With the following perlrun options `-lpe`:
```
$ perl -lpe's/F*(T*)(T)F*/[$-[0],$+[1]],/g;chop$_;$_="[$_]"' <<< 'TTFFFTTTTTTTTTTF'
[[0,1],[5,14]]
```
Alternative where output is line separated (34 bytes):
```
$ perl -pE's/F*(T*)(T)F*/$-[0] $+[1]\n/g;chomp' <<< TTFFFTTTTTTTTTTF
0 1
5 15
```
[Answer]
## APL, 17 chars
```
{(↑,↑∘⊖)¨⍵⊂⍵×⍳⍴⍵}
```
In `‚éïIO‚Üê0` and `‚éïML‚Üê3`.
In English:
* `⍵×⍳⍴⍵`: zero out the elements of the index vector as long as the argument where the argument is false
* `⍵⊂`: cut at the beginning of each run of truths and throw away the false's
* `(↑,↑∘⊖)¨`: take the first and last element of each subarray
[Answer]
## Python 2, 108 bytes
```
l=input();l+=[0];o=[];s=k=0
for i,j in enumerate(l):s=j*~k*i or s;~j*l[i-1]and o.append([s,i-1]);k=j
print o
```
Test cases:
```
$ python2 rangesinlists2.py
[0]
[]
$ python2 rangesinlists2.py
[-1]
[[0, 0]]
$ python2 rangesinlists2.py
[-1,-1,0,-1]
[[0, 1], [3, 3]]
$ python2 rangesinlists2.py
[0,-1,-1,0,0,-1,-1,-1]
[[1, 2], [5, 7]]
$ python2 rangesinlists2.py
[0,-1,-1,0,0,0,-1,-1,-1,-1]
[[1, 2], [6, 9]]
$ python2 rangesinlists2.py
[-1,-1,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0]
[[0, 1], [5, 14]]
$ python2 rangesinlists2.py
[0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1]
[[2, 3], [12, 19], [33, 54], [93, 94]]
```
Surely there's a shorter solution than this, but it works.
[Answer]
## Haskell: 123 bytes (Example, cannot win)
```
f l=[(s,e)|let m=length l-1,let r=[0..m],s<-r,e<-r,and[l!!x|x<-[s..e]],s<=e,let(#)p=not$l!!p,s==0||(#)(s-1),e==m||(#)(e+1)]
```
Less golfed:
```
f l = [(start,end) | start <- [0..max], end <- [0..max], allTrue start end, start <= end, notBelow start, notAbove end]
where
max = (length l) - 1
allTrue s e = and (subList s e)
subList s e = [l !! i | i <- [s,e]]
notBelow s = (s == 0) || (not (l !! (s-1)))
notAbove e = (s == m) || (not (l !! (e+1)))
```
[Answer]
## CJam, 30 bytes
```
0l~0++2ewee{1=$2,=},{~0=-}%2/`
```
Input as a CJam-style array of `0`s and `1`s. Output as a CJam-style array of pairs.
[Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7BS%2F1%3D%22FT%2C%22%2201%20%22er%3AL%3B%0A%0A0L~0%2B%2B2ewee%7B1%3D%242%2C%3D%7D%2C%7B~0%3D-%7D%252%2Fp%0A%0A%5Do%7D%2F&input=f%20%5BF%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%20%5B%5D%0Af%20%5BT%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%20%5B%5B0%2C0%5D%5D%0Af%20%5BT%2CT%2CF%2CT%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%20%5B%5B0%2C1%5D%2C%5B3%2C3%5D%5D%0Af%20%5BF%2CT%2CT%2CF%2CF%2CT%2CT%2CT%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%20%5B%5B1%2C2%5D%2C%5B5%2C7%5D%5D%0Af%20%5BF%2CT%2CT%2CF%2CF%2CF%2CT%2CT%2CT%2CT%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%20%5B%5B1%2C2%5D%2C%5B6%2C9%5D%5D%0Af%20%5BT%2CT%2CF%2CF%2CF%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CF%5D%20%3D%20%5B%5B0%2C1%5D%2C%5B5%2C14%5D%5D%0Af%20%5BF%2CF%2CT%2CT%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CT%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CF%2CT%2CT%5D%20%3D%20%5B%5B2%2C3%5D%2C%5B12%2C19%5D%2C%5B33%2C54%5D%2C%5B93%2C94%5D%5D) (Takes care of the conversion of the input formats.)
[Answer]
# Japt, 27 bytes
```
A=[];Ur"T+"@Ap[YXl +´Y]};A·
```
There has to be a way to golf this down...
Anyway, it's the same as my ùîºùïäùïÑùïöùïü answer.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
§zeW<om←W>`:0Θ
```
[Try it online!](https://tio.run/##yygtzv7//9DyqtRwm/zcR20Twu0SrAzOzfj//3@0gY6BjiEQGqBBQzRogBMakgANqAiB5sUCAA "Husk – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 19 bytes
```
+&:'+{y&~x,z}.'-3':
```
[Try it online!](https://tio.run/##y9bNz/7/P81KW81KXbu6Uq2uQqeqVk9d11jd6n@auoZBkrUhEBkaAEkDIAXEMBaICZGDMCEAqMEAIg0GcGFkYIgVGBAFgFZq/gcA)
Uses `-n':` (window) so the inner `{y&!x,z}` function has access to the previous (`x`), current (`y`), and next (`z`) value in the input boolean list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
TI’kƊ.ịⱮ$ḢẠ?U
```
[Try it online!](https://tio.run/##y0rNyan8/z/E81HDzOxjXXoPd3c/2rhO5eGORQ93LbAP/X@4/VHTmqOTHu6c8f9/NBdntEGsjgJ@oKxgqxAdC1RqSJzSaAMdg1iweh1DHQMdfLpg6oFqoo11jMG6gDywPgiNTTdEl6GOEVCXqY45mi6oPgydyLrMdCyRXIikBwWCggbZhaY6hiZQy5CtQ0AMA3BCQxKgARUhKFigfjIChrdOtKGRjqElKPSNdUxNgLSlsY4lyJOxAA "Jelly – Try It Online")
+4 bytes to handle the all `0`s test cases. Without that, a much cleaner [9 bytes](https://tio.run/##y0rNyan8/z/E81HDzOxjXXoPd3c/2rgu9P/h9kdNa45Oerhzxv//0Vyc0YaxOgr4gbKCrUJ0tIGOQWwsSL2OoY6BDj5dMPVANdHGOsZgXUAeWB@ExqYbostQxwioy1THHE0XVB@GTmRdZjqWSC5E0oMCDYAmILvQVMfQBGoZsnUIiGEATmhIAjSgIgQFC9RPRsDw1ok2NNIxtASFvrGOqQmQtjTWsQR5MhYA). This uses 1 indexing, which is Jelly's default.
## How it works
```
TI’kƊ.ịⱮ$ḢẠ?U - Main link
T - Indices of truthy elements
Ɗ - Group the previous links into a monad f(T):
I - Increments
’ - Decrement
k - Partition T at truthy indexes in the decremented increments
This returns [[]] for [0] (and repeats) and
[[a, b], [c, d, e], ...] for every other input
? - If:
Ạ - Condition: All truthy?
$ - If:
Ɱ - For each partition:
.ị - Take the 0.5th element
·∏¢ - Else: Return []
For non-integer left argument, x, Jelly's ị atom takes
floor(x) and ceil(x) and returns [floor(x)ịy, ceil(x)ịy]
As Jelly's indexing is 1-based and modular:
0ị returns the last element
1ị returns the first element
.ị returns [0ị, 1ị]
U - Reverse, as the ranges yielded by .ị are "reversed"
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
m§e←→ġo=→ηf
```
[Try it online!](https://tio.run/##yygtzv7/P/fQ8tRHbRMetU06sjDfFkid2572////aAMdAx1DIDRAg4Zo0AAnNCQBGlARAs2LBQA "Husk – Try It Online")
```
m§e←→ġo=→ηf
ηf # get truthy indices
ƒ°o=‚Üí # group runs of adjacent values
m # then, for each group
§e←→ # get the first & last elements
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
Uses `0/1` for `F/T`.
```
Åγ.¥ü2sÏ€εN-
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cOu5zXqHlh7eY1R8uP9R05pzW/10//@PNtAx0DEEQgM0aIgGDXBCQxKgARUh0LxYAA "05AB1E – Try It Online")
`Åγ` run-length encodes the input, pushing the chunk elements and the chunk lengths.
`.¥` takes the cumulative sum of the chunck lengths and prepends a 0.
`ü2` creates pairs of all adjacent numbers in this list.
`s` swaps to the list of chunk elements.
`Ï` selects each pair which is at the same index as a truthy chunk. The selected pairs are now the half-inclusive truthy range `[a, b)`.
`€ε` iterates over every number in every range, and `N-` subtracts the 0-based index from each number to get the inclusive ranges.
[Try it with step-by-step output!](https://tio.run/##yy9OTMpM/f//cOu5zQpAoKQABkGlebo5qXnpJRkKqXnJ@SmpVgpK9pouCcX2SgqJeSlAjk5RAheX3qGlSJqAwLk0tzQnsSSzLFWhuDQXpMmWi@vwHiNUVY4pWYnJqXklCgWJmUXFUFXFh/vBqoJTc1KTSxQSSxRKikpLMioVkjNK87Jhqh41rTm31U@3Fm5acGlSSVEiUENmXkpmcipE3f//0YY6hjoGYGiIBRrEAgA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ẏ‡?iŻv₍gG
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo/igKE/acW7duKCjWdHIiwiIiwiWzAsMSwwLDEsMSwxLDAsMV0iXQ==)
[Answer]
# PowerShell, 82 bytes
```
("$args"|sls 't+'-A).Matches|%{if($_){'{0},{1}'-f$_.Index,($_.Index+$_.Length-1)}}
```
Regex solution, using [MatchInfo](https://msdn.microsoft.com/en-us/library/microsoft.powershell.commands.matchinfo.aspx) object's properties.
# Example
```
PS > .\BoolRange.ps1 'F'
PS > .\BoolRange.ps1 'T'
0,0
PS > .\BoolRange.ps1 'TTFFFTTTTTTTTTTF'
0,1
5,14
```
] |
[Question]
[
A three-fruit pie is made of three *different* fruits. What is the most three-fruit pies you can make from the quantities of 5 fruits you have?
For example, with
```
1 apple
1 banana
4 mangoes
2 nectarines
0 peaches
```
you can make 2 pies:
```
apple, mango, nectarine
banana, mango, nectarine
```
**Input:** Five non-negative integers, or a list of them.
**Output:** The maximum number of three-fruit pies you can make from those quantities of fruit. Fewest bytes wins.
**Test cases:**
```
1 1 4 2 0
2
2 2 2 2 2
3
0 6 0 6 0
0
12 5 3 2 1
5
1 14 14 3 2
6
0 0 1 0 50
0
```
**Leaderboard:**
```
var QUESTION_ID=59192,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Pyth, ~~19~~ ~~18~~ 14 bytes
*-1 byte by @FryAmTheEggman*
*14-byte program by @isaacg*
I claim that the number of pies that can be formed from an ascending list `[x1,x2,x3,x4,x5]` is:
```
floor(min((x1+x2+x3+x4+x5)/3,(x1+x2+x3+x4)/2,x1+x2+x3))
```
Or in code:
```
JSQhS/Ls~PJ_S3
```
[See revision history for TI-BASIC and APL programs]
## Proof of correctness
Let
```
s3 = x1+x2+x3
s4 = x1+x2+x3+x4
s5 = x1+x2+x3+x4+x5
```
We want to show that `P(X)=floor(min(s5/3,s4/2,s3))` is always the greatest number of pies for a list `x1≤x2≤x3≤x4≤x5` of numbers of fruits 1~5.
First, we show that all three numbers are upper bounds.
* Since there are `s5` total fruits, and each pie has three fruits, `⌊s5/3⌋` is an upper bound.
* Since there are `s4` fruits that are *not* fruit 5, and at least two non-5 fruits are required in each pie, `⌊s4/2⌋` is an upper bound.
* Since there are `s3` fruits that are neither fruit 4 nor fruit 5, and at least one such fruit is required in each pie, `s3` is an upper bound.
Second, we show that the method of taking fruits from the three largest piles always satisfies the bound. We do this by induction.
**Base case:** 0 pies can obviously be formed from any valid list with `P(X)>=0`.
**Inductive step:** Given any list `X` where `P(X) > 0`, we can bake one pie, leaving behind a list `X'` with `P(X') >= P(X)-1`. We do this by taking a fruit from the largest three piles `3,4,5`, then resorting if needed. Bear with me; there's some casework.
* If `x2<x3`, then we don't need to sort the list after removing fruits. We already have a valid `X'`. We know that `P(X') = P(X)-1` because `s5'` is 3 less (because three fruits of type 1~5 were removed), `s4'` is 2 less, and `s3'` is 1 less. So `P(X')` is exactly one less than P(X).
* If `x3<x4`, then we're similarly done.
* Now we take the case where `x2=x3=x4`. We'll need to rearrange the list this time.
+ If `x5>x4`, then we rearrange the list by switching piles 4 and 2. `s5'` and `s4'` are still a decrease of 3 and 2 respectively, but `s3'=s3-2`. This isn't a problem, because if `x2=x3=x4`, then `2*x4<=s3`->`2*x4+s3 <= 2*s3` -> `(x4 + s4)/2 <= s3`. We have two subcases:
+ Equality, i.e. `(x4,x3,x2,x1)=(1,1,1,0)`, in which case `P(X)` = `1` and we can clearly make a pie from piles `5,4,3`, or:
+ `(s4+1)/2 <= s3`, in which case decreasing `s4` by an extra `1` doesn't mean an extra decrease to P(X).
* Now we're left with the case where `x1<x2=x3=x4=x5`. Now `s3` will also be decreased by 1, so we need `(s5/3+1)` to be `<=s4/2`; that is, `8x5+2x1+2<=9x5+3x1`, or `x5+x1>=2`. All cases smaller than this can be checked manually.
* If every number is equal, it is clear that we can achieve the bound of `⌊s5/3⌋`, which is always less than the other two—we simply go through the numbers in sequence.
Finally we're done. Please comment if I'm missing something, and I'll be giving a small bounty for a more elegant proof.
[Answer]
# CJam, 34
```
q~L{J2be!\f{\.-_W#){j)7}|;}0+:e>}j
```
[Try it online](http://cjam.aditsu.net/#code=q~L%7BJ2be!%5Cf%7B%5C.-_W%23)%7Bj)7%7D%7C%3B%7D0%2B%3Ae%3E%7Dj&input=%5B1%2014%2014%203%202%5D)
**Explanation:**
```
q~ read and evaluate the input array
L{…}j calculate with memoized recursion and no initial values
using the input array as the argument
J2b convert 19 to base 2 (J=19), obtaining [1 0 0 1 1]
e! get permutations without duplicates
these are all the combinations of three 1's and two 0's
which represent the choices of fruit for one pie
\ swap with the argument array
f{…} for each combination and the argument
\ swap to bring the combination to the top
.- subtract from the argument array, item by item
_ duplicate the resulting array
W#) does it contain the value -1? (calculate (index of W=-1) + 1)
{…}| if not
j recursively solve the problem for this array
)7 increment the result, then push a dummy value
; pop the last value (array containing -1 or dummy value)
0+ add a 0 in case the resulting array is empty
(if we couldn't make any pie from the argument)
:e> get the maximum value (best number of pies)
```
[Answer]
## Haskell, 62 bytes
```
f x=maximum$0:[1+f y|y<-mapM(\a->a:[a-1|a>0])x,sum y==sum x-3]
```
This defines a function `f` that takes in the fruit list `x` and returns the maximum number of pies.
### Explanation
We compute the number of pies recursively.
The part `mapM(\a->a:[a-1|a>0])x` evaluates to the list of all lists obtained from `x` by decrementing any positive entries.
If `x = [0,1,2]`, it results in
```
[[0,1,2],[0,1,1],[0,0,2],[0,0,1]]
```
The part between the outer `[]` is a list comprehension: we iterate through all `y` in the above list and filter out those whose sum is not equal to `sum(x)-3`, so we get all lists where 3 different fruits have been made into a pie. Then we recursively evaluate `f` on these lists, add `1` to each, and take the maximum of them and `0` (the base case, if we can't make any pies).
[Answer]
## **C#, 67**
Recursively make one pie per iteration with fruits you have the most until you run out.
```
int f(List<int>p){p.Sort();p[3]--;p[4]--;return p[2]-->0?1+f(p):0;}
```
[Test cases here](https://dotnetfiddle.net/Widget/Preview?url=/Widget/WN3CxR)
[Answer]
# Pyth, 29
```
Wtt=QS-Q0=Q+tPPQtM>3.<Q1=hZ;Z
```
[Test suite](http://pyth.herokuapp.com/?code=Wtt%3DQS-Q0%3DQ%2BtPPQtM%3E3.%3CQ1%3DhZ%3BZ&input=1%2C14%2C14%2C2%2C3&test_suite=1&test_suite_input=1%2C1%2C4%2C2%2C0%0A2%2C2%2C2%2C2%2C2%0A0%2C6%2C0%2C6%2C0%0A12%2C5%2C3%2C2%2C1%0A1%2C14%2C14%2C3%2C2%0A0%2C0%2C1%2C0%2C50&debug=00)
Sorts the input list and removes zeroes. Then, as long as you have 3 fruits, decrement the first and two last elements, and add the remaining elements to the list, before sorting it and removing zeroes again. Then increment a counter by 1.
This is actually rather quick so long as there are only 5 fruits, it can solve for very large bins of fruits, i.e. `1000,1000,1000,1000,1000` in under a second.
[Answer]
# Python, general solution, ~~128~~ 92 bytes
*-36 bytes from @xnor, you da real mvp*
```
g=lambda l,k:0if k>sum(l)else-(-1in l)or-~g(map(sum,zip(sorted(l),[0]*(len(l)-k)+[-1]*k)),k))
```
~~`def g(a,k):b=[i for i in a if i];return 0if len(b)<k;c=sorted(b,reverse=True);return 1+g([c[i]-(k-1>i)for i in range(len(c))],k)`~~
This works so long as [my proof](https://cloud.sagemath.com/projects/0006c19e-2e0f-48a0-8a6f-c5770416a7cc/files/2015-10-10-043825.pdf) is correct. If it's not, let me know why so I can try to fix it. If it's uncomprehendable, let me know, and I'll attack it after a few cups of coffee.
[Answer]
## Python 2, 78 bytes
### Taking 5 numbers as input: ~~91~~ ~~89~~ 88 bytes
```
s=sorted([input()for x in[0]*5])
while s[2]:s[2]-=1;s[3]-=1;s[4]-=1;s.sort();x+=1
print x
```
*Edit*:
Changing `s=sorted([input()for x in[0]*5])` by `s=sorted(map(input,['']*5));x=0` saves 1 byte.
Takes 5 numbers as input and prints the number of possible pies that can be made. It takes the same approach as Reto Koradi's answer -without improving byte count- but it felt like this question was missing an answer in Python.
Thanks @ThomasKwa and @xsot for your suggestion.
**How it works**
```
s=sorted([input()for x in[0]*5]) takes 5 numbers as input, puts them in a list
and sorts it in ascending order. The result
is then stored in s
while s[2]: While there are more than 3 types of fruit
we can still make pies. As the list is
sorted this will not be true when s[2] is 0.
This takes advantage of 0 being equivalent to False.
s[2]-=1;s[3]-=1;s[4]-=1 Decrement in one unit the types of fruit
that we have the most
s.sort() Sort the resulting list
x+=1 Add one to the pie counter
print x Print the result
```
Note that variable `x` is never defined, but the program takes advantge of some leakage python 2.7 has. When defining the list `s` with list comprehension the last value in the iterable (`[0]*5` in this case) is stored in the variable used to iterate.
To make things clearer:
```
>>>[x for x in range(10)]
>>>x
9
```
### Taking a list as input: 78 bytes
Thanks @xnor @xsot and @ThomasKwa for suggesting changing the input to a list.
```
s=sorted(input());x=0
while s[2]:s[2]-=1;s[3]-=1;s[4]-=1;s.sort();x+=1
print x
```
**How it works**
It works the same way the above code, but in this case the input is already a list so there is no need of creating it and variable `x` has to be defined.
Disclaimer: This is my first attempt at golfing and it feels it can still be golfed, so suggest any changes that could be made in order to reduce byte count.
[Answer]
# CJam, 23 bytes
```
0l~{\)\$2/~+:(+_2=)}g;(
```
[Try it online](http://cjam.aditsu.net/#code=0l~%7B%5C)%5C%242%2F~%2B%3A(%2B_2%3D)%7Dg%3B(&input=%5B1%2014%2014%203%202%5D)
This takes fruit from the 3 largest piles in each iteration, and counts the number of iterations.
I don't have a mathematical proof that this always gives the correct result. It does for the given test examples, and I'll believe that it works for all cases until somebody gives me a counter example.
The intuitive explanation I used to convince myself: To maximize the number of pies, you need to keep as many piles non-empty as you can. That's because you lose the ability to make more pies as soon as you have 3 or more empty piles.
This is achieve by always taking fruit from the largest piles. I can't think of a case where taking fruit from a smaller pile would lead to a better situation than taking fruit from a larger pile.
I have slightly more formal reasoning in my head. I'll try to think of a way to put it into words/formula.
[Answer]
# ><>, 76 bytes
```
0&4\/~}&?!/
@:@<\!?:}$-1@@$!?&+&:)@:@
,:&:@(?$n;/++:&+::2%-2,:&:@(?$&~+:3%-3
```
Turns out sorting in ><> isn't easy! This program relies on the proof put forward by Thomas Kwa to be true, which certainly looks to be the case with the test cases.
The 5 input numbers are expected to be present on the stack at the program's start.
The first two lines sort the numbers on the stack, and the third performs the calculation `floor(min((x1+x2+x3+x4+x5)/3,(x1+x2+x3+x4)/2,x1+x2+x3))`, taken from Thomas's answer.
[Answer]
## Python 2, 59 bytes
```
h=lambda l,k=3:k*'_'and min(h(sorted(l)[:-1],k-1),sum(l)/k)
```
A general method that works for any `n` and `k`. The `k=3` makes the fruits per pie default to 3, but you can pass in a different value. The recursion uses the fact that strings are bigger than numbers in Python 2, letting the empty string represent the base case of infinity.
This method uses the fact that always taking the most common fruit is optimal, so we consider each possible rank of fruit as a limiting factor. I've reproven that fact below.
---
[Mego's proof](https://codegolf.stackexchange.com/a/60286/20260) made me think of this more direct proof that repeatedly taking the most common fruits is optimal. This is stated with pies of `k` fruits.
**Theorem:** Repeatedly taking the `k` most common fruits gives the optimal number of pies.
**Proof:** We will show that if `N` pies are possible, then the most-common-fruit strategy produces at least `N` pies. We do this by switching fruits among the `N` pies to make them match the ones produced by this strategy, while keeping the pies valid.
Let's make it so the first pie (call it `p`) contain the most common fruits. If it doesn't yet, it must contain a fruit `i`, but not a more common fruit `j`. Then, the remaining pies have strictly more of fruit `j` than fruit `i`, and so some other pie `q` must contain `j` but not `i`. Then, we can swap fruit `i` from pie `p` with fruit `j` from pie `q`, which keeps `N` pies having distinct fruit.
Repeat this process until `p` has the `k` most common fruits.
Then, set pie `p` aside, and repeat this process for the next pie to make it have the most common remaining fruits. Keep doing this until the pies are the sequence produced by the most-common-fruit stategy.
[Answer]
# PowerShell, 92 Bytes
```
$a=($args|sort)-ne0;while($a.count-ge3){$a[0]--;$a[-1]--;$a[-2]--;$a=($a-ne0;$c++}($c,0)[!$c]
```
Uses the same greedy-based algorithm as FryAmTheEggman's [answer](https://codegolf.stackexchange.com/a/59203/42963) ... just a lot wordier in PowerShell....
```
$a=($args|sort)-ne0 # Take input arguments, sort them, remove any 0's
while($a.count-ge3){ # So long as we have 3 or more fruit piles
$a[0]-- # Remove one from the first element...
$a[-1]-- # ... the last element ...
$a[-2]-- # ... and the second-to-last.
$a=$a-ne0 # Remove any 0's from our piles
$c++ # Increment how many pies we've made
} #
($c,0)[!$c] # Equivalent to if($c){$c}else{0}
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/32092/edit)
# The scenario
You live in a country that is having a presidential election. Each voter gets one vote, and [therefore](http://en.wikipedia.org/wiki/Duverger%27s_law) there is a firmly-entrenched two-party system. (Third parties exist, but get hardly any votes).
The latest opinion poll shows the race in a dead heat:
* 49%: Alberto Arbusto
* 49%: Jorge Sangre
* 2%: various minor candidates
# The program requirements
You have been hired by the government to write part of the vote counting software. You will be given, on standard input, an unordered list of one precinct’s votes, one per line, like this:
```
Alberto Arbusto
Jorge Sangre
Jorge Sangre
Alberto Arbusto
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
Jorge Sangre
Juan Perez
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
…
```
and, after it has read all the votes, outputs a summary of how many votes each candidate got, sorted in descending order by number of votes, like this:
```
492 Jorge Sangre
484 Alberto Arbusto
18 Juan Perez
6 Mickey Mouse
```
# The underhanded part
You're a partisan hack who wants to steal the election for one of the two main candidates (you can choose which one). So, your program must deliberately print *incorrect* vote counts, with a systematic bias towards your favorite candidate.
Of course, you must do this is such a way that a person looking at your code or its output would likely not recognize the incorrect behavior.
[Answer]
# Scala
Long live Alberto Arbusto!
```
import scala.io.Source
import java.util.concurrent.atomic.LongAdder
object Votes extends App {
val votes = Source.stdin.getLines.toIndexedSeq
val registeredCandidates = Seq(
"Alberto Arbusto",
"Juan Perez",
"Mickey Mouse",
"Jorge Sangre"
)
val summaries = registeredCandidates map (Summary.apply(_, new LongAdder))
var currentCandidate: String = _
for (vote <- votes.par) {
currentCandidate = vote
summaries.find(s => s.candidate == currentCandidate).map(_.total.increment)
}
for (summary <- summaries.sortBy(-_.total.longValue)) {
println(summary)
}
}
case class Summary(candidate: String, total: LongAdder) {
override def toString = s"${total.longValue} ${candidate}"
}
```
Alberto Arbusto will almost always come out slightly ahead of Jorge Sangre, provided enough votes are cast (~10,000). There's no need to tamper with the votes themselves.
>
> There's a race condition. And by putting Alberto Arbusto earlier in the list, we increase his chances of winning the race.
>
>
>
Side note: This code is loosely based on a "custom" connection pool that I encountered on a project. It took us weeks to figure out why the application was perpetually out of connections.
[Answer]
# Ruby
```
vote_counts = $<.readlines.group_by{|s|s}.collect{ |name, votes| [votes.count, name] }
formatted_count_strings = vote_counts.map do |row,
formatter = PrettyString.new|"%#{formatter[1][/[so]/]||'s'} %s"%
[row,formatter]
end
sorted_count_strings = formatted_count_strings.sort_by(&:to_i).reverse
puts sorted_count_strings
```
Jorge Sangre will get a substantial boost in his vote count (for example, 492 votes will be reported as 754). Alberto's votes will be reported accurately.
>
> As you might guess, it's not who counts the votes but who formats the votes. I've tried to obscure it (`PrettyString.new` isn't a real thing and never gets called), but `formatter` is actually the name string. If the second letter of the name is 'o', the vote count will be printed out in octal instead of decimal.
>
>
>
[Answer]
# Bash
(Does this meet the specification?)
```
uniq -c|sort -rk2,2|uniq -f1|sort -gr
```
As always, this takes extra precautions to ensure valid output.
`uniq -c` prefixes each line with the number of times it occurs. This basically does all the work.
Just in case `uniq -c` does something wrong, we now sort its output by the names of candidates in reverse order, then run it through `uniq -f1` (don't print duplicate lines, ignoring the first field [the number of votes]) to remove any duplicate candidates. Finally we use `sort -gr` to sort in "General Numeric" and "Reverse" order (descending order by number of votes).
>
> `uniq -c` counts consecutive occurences, not occurences over the whole file. The winner will be the candidate with the most consecutive votes.
>
>
>
[Answer]
# C#
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
class Program
{
static void Main(string[] args)
{
var candidates = new SortedDictionary<string, int>();
string candidate;
using (var sr = new StreamReader("candidates.txt"))
{
while ((candidate = sr.ReadLine()) != null)
{
if (candidates.ContainsKey(candidate))
candidates[candidate]++;
else
candidates.Add(candidate, 1);
}
}
// order by the votes
var votes = candidates.OrderByDescending(k => k.Value).Select(x => x.Value);
Console.WriteLine("Candidate | Votes");
for (int i = 0; i < candidates.Count; i++)
{
Console.WriteLine(candidates.ElementAt(i).Key + " " + votes.ElementAt(i));
}
Console.ReadKey();
}
}
```
The first candidate in the text file will always win!
It will make *Alberto Arbusto* the winner!
>
> The candidates' names are ordered alphabetically in the dictionary, but the votes are ordered by number.
>
>
>
[Answer]
# C
```
#include <stdio.h>
#define NCANDIDATES 4
static const char * const cand_list[NCANDIDATES] = {
"Alberto Arbusto",
"Juan Perez",
"Mickey Mouse",
"Jorge Sangre"
};
#define BUFFER_SIZE 100
int
main(int argc, char **argv)
{
int votes[NCANDIDATES];
int candidate;
size_t name_start;
int i;
int j;
int place;
int max;
size_t bytes;
char buffer[BUFFER_SIZE];
/*
Make sure input is read in text mode, so we don't have to
worry about whether line endings are LF or CRLF.
*/
freopen(NULL, "rt", stdin);
/* Initialize vote tally. */
for (candidate = 0; candidate < NCANDIDATES; candidate++) {
votes[candidate] = 0;
}
/* Read and process vote file. */
do {
/* Read a block of data. */
bytes = fread(buffer, 1, BUFFER_SIZE, stdin);
/* Loop over the data, finding and counting the votes. */
name_start = 0;
for (i = 0; i < bytes; i++) {
if (buffer[i] == '\n') {
/* Found name. */
buffer[i] = '\0'; // nul-terminate name so strcmp will work
/* Look up candidate. */
for (j = 0; j < NCANDIDATES; j++) {
if (strcmp(&buffer[name_start], cand_list[j]) == 0) {
candidate = j;
break;
}
}
/* Count vote. */
++votes[candidate];
/* Next name starts at next character */
name_start = i + 1;
}
}
} while (bytes > 0);
/* Output the candidates, in decreasing order of votes. */
for (place = 0; place < NCANDIDATES; place++) {
max = -1;
for (j = 0; j < NCANDIDATES; j++) {
if (votes[j] > max) {
candidate = j;
max = votes[j];
}
}
printf("%8d %s\n", votes[candidate], cand_list[candidate]);
votes[candidate] = -1; // Remove from consideration for next place.
}
return 0;
}
```
Favors Jorge Sangre.
In testing with randomly generated vote files, even when Alberto Arbusto receives up to 1.4% more of the actual votes (49.7% vs 48.3% for Jorge Sangre), my man Jorge Sangre usually wins the count.
>
> Reading the data in fixed-size blocks often splits a line across two blocks.
>
> The fragment of the line at the end of the first block doesn't get counted because it doesn't have a newline character.
>
> The fragment in the second block does generate a vote, but it doesn't match any of the candidate's names so the 'candidate' variable doesn't get updated. This has the effect of transferring a vote from the candidate whose name was split to the candidate who received the previous vote.
>
> A longer name is more likely to be split across blocks, so Alberto Arbusto ends up being a vote "donor" more often than Jorge Sangre does.
>
>
>
[Answer]
## Python
```
from collections import defaultdict
def count_votes(candidate, votes=defaultdict(int)):
with open('votes.txt') as f:
for line in f:
votes[line.strip()] += 1
return votes[candidate]
if __name__ == '__main__':
candidates = [
'Mickey Mouse',
'Juan Perez',
'Alberto Arbusto',
'Jorge Sangre'
]
results = {candidate: count_votes(candidate) for candidate in candidates}
for candidate in sorted(results, key=results.get, reverse=True):
print results[candidate], candidate
```
The vote counts will favour candidates closer to the end of the list.
>
> In Python, mutable default arguments are created and bound to the function at definition. So the votes will be maintained between function calls and carried over for subsequent candidates. The number of votes will be counted twice for the second candidate, three times for the third, and so on.
>
>
>
[Answer]
## tr | sed | dc
```
tr ' [:upper:]' '\n[:lower:]' <votes |\
sed -e '1i0sa0ss0sp' -e \
'/^[asp]/!d;s/\(.\).*/l\1 1+s\1/
${p;c[Alberto Arbusto: ]P lap[Jorge Sangre: ]P lsp[Juan Perez: ]P lpp
}' | dc
```
This counts my buddy Alberto twice every time.
*"Oh - `tr`? Well, it's just necessary because computers aren't very good with capital letters - better if they're all lowercase.... Yeah, I know, computers are crazy."*
### OUTPUT
```
Alberto Arbusto: 12
Jorge Sangre: 5
Juan Perez: 1
```
Here's another version that gives Juan Perez's vote to Jorge Sangre:
```
tr '[:upper:]' '[:lower:]' <votes |\
sed -e '1i0sj0sa1so' -e \
's/\(.\).*/l\1 1+s\1/
${p;c[Alberto Arbusto: ]P lap[Jorge Sangre: ]P ljp[Others: ]P lop
}' | dc
```
### OUTPUT
```
Alberto Arbusto: 6
Jorge Sangre: 6
Others: 1
```
[Answer]
## **JavaScript**
```
function Election(noOfVoters) {
candidates = ["Albert", "Jorge", "Tony", "Chip"];
votes = [];
for (i = 1; i <= noOfVoters; i++) {
votes.push(prompt("1 - Albert, 2 - Jorge, 3 - Tony , 4 - Chip"))
}
votes.sort();
WinningOrder = count(votes);
var placement = [];
for (x = 0; x < candidates.length; x++) {
placement.push(x + " place with " + WinningOrder[x] + " votes is " + candidates[x] + "\n");
}
placement.reverse();
alert(placement)
}
function count(arr) {
var a = [],
b = [],
prev;
arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== prev) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length - 1]++;
}
prev = arr[i];
}
b.sort();
return b;
}
```
The last person in the candidates list will always win.
] |
[Question]
[
Given a distance in meters as an integer \$60\le d \le 260\$, return the number of clubs that may be used according to the following arbitrary chart, where both \$min\$ and \$max\$ are inclusive:
```
club | min | max
----------------+-----+-----
Driver | 200 | 260
3-wood | 180 | 235
5-wood | 170 | 210
3-iron | 160 | 200
4-iron | 150 | 185
5-iron | 140 | 170
6-iron | 130 | 160
7-iron | 120 | 150
8-iron | 110 | 140
9-iron | 95 | 130
Pitching Wedge | 80 | 115
Sand Wedge | 60 | 90
```
## Notes
* The club names are given for information only.
* Of course, the choice of the club depends on several other parameters. For instance the *Sand Wedge* is designed to escape from a sand bunker. But for the purposes of this challenge, only the distance matters.
* This is undoubtedly a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
## Example
For \$d=130\$, we may choose *6-iron*, *7-iron*, *8-iron* or *9-iron*, so the expected answer is \$4\$.
## Test cases
```
Input Output
60 1
79 1
80 2
93 1
105 2
110 3
116 2
129 3
130 4
200 4
201 3
235 2
260 1
```
Or as lists:
```
Input : 60, 79, 80, 93, 105, 110, 116, 129, 130, 200, 201, 235, 260
Output: 1, 1, 2, 1, 2, 3, 2, 3, 4, 4, 3, 2, 1
```
[Answer]
# x86-16 machine code, ~~47~~ 42 bytes
```
00000000: be14 01b3 01b1 0bad 3ad0 7205 3ad4 7701 ........:.r.:.w.
00000010: 43e2 f4c3 505a 5feb 6e73 78d2 8282 8c8c C...PZ_.nsx.....
00000020: 9696 a0a0 aaaa b4b9 c8c8 ..........
```
**Listing:**
```
BE 0114 MOV SI, OFFSET CHART ; SI point to distance chart
B3 01 MOV BL, 1 ; start counter at 1
B1 0B MOV CL, 11 ; loop 11 clubs
SCORE_LOOP:
AD LODSW ; load AL = min, AH = max
3A D0 CMP DL, AL ; is d less than min?
72 05 JB DONE ; if so, continue
3A D4 CMP DL, AH ; is d greater than max?
77 01 JA DONE ; if so, continue
43 INC BX ; otherwise increment counter
DONE:
E2 F4 LOOP SCORE_LOOP ; loop through end of chart
C3 RET ; return to caller
CHART DB 80,90,95,235,110,115,120,210,130,130,140,140
DB 150,150,160,160,170,170,180,185,200,200
```
Callable function, input `d` in `DX`, output in `BL`.
No compression (the data is only ~~24~~ 22 bytes in binary anyway) just a table comparison.
**Edit:** Huge props to [@SE - stop firing the good guys](https://codegolf.stackexchange.com/a/209859/84624) for re-arranging the list and eliminating need to offset the `d` value, saving **5 bytes**!
**Test program runs:**
[![enter image description here](https://i.stack.imgur.com/uMRrq.png)](https://i.stack.imgur.com/uMRrq.png)
[![enter image description here](https://i.stack.imgur.com/2etja.png)](https://i.stack.imgur.com/2etja.png)
### Alternate version, 50 bytes
```
BB 0501 MOV BX, 0501H ; init counter to 1 in BL and
BF 556D MOV DI, 0556DH ; magic number to 0x5556D in BH:DI
BE 011C MOV SI, OFFSET CHART ; SI point to transition table
B1 16 MOV CL, 22 ; loop 22 transitions
SCORE_LOOP:
AC LODSB ; load AL = next transition
3A C2 CMP AL, DL ; is d less than?
77 0B JA EXIT ; if not, end
D0 EF SHR BH, 1 ; cascade bit shift high word into CF
D1 DF RCR DI, 1 ; bit shift lsb into CF
43 INC BX ; increment counter
72 02 JC NEXT ; if CF was a 1, continue to next
4B DEC BX ; otherwise subtract 2
4B DEC BX
NEXT:
E2 F0 LOOP SCORE_LOOP ; keep looping
EXIT:
C3 RET
CHART DB 80,91,95,110,116,120,130,131,140,141,150,151,160,161,170,171,180,186,200,201,211,236
```
This is heavily inspired by [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/209653/84624). This uses a table of values of `d` where the number of clubs transitions either `+1` or `-1`, and a corresponding binary *magic number* of `0x5556d` where a `1` indicates a positive change and `0` indicates a negative change.
Unfortunately, this doesn't help a lot here since encoding the original table is **24 bytes** versus the **22** transitions plus the **3 byte** magic number so really it's larger. It was fun trying though!
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda n:sum(a<=n/5<=b for a,b in zip(b'($"
',b'4/*(%"
'))
```
[Try it online!](https://tio.run/##HY7LCsIwEEX3xYUoqIjIIEoTCTRpbH3QfEntIkGLBZuWNi7052OSzbnz4s7tv@bVaW5rcbdv2aqHBH0bPy2ShdBJVggFdTeAJAoaDb@mRypG@x1sN@vVYj6dxETFp@SIDmG0nMUYW/MczQgCypwSOF8JXJxeOQFGMwdGPXKH1O0Yd21KA5gDdydpTqso6odGG1TWyPvhEMNXPkf4UGH7Bw "Python 3 – Try It Online")
The byte strings contain some unprintables, their escaped form is `b'($" \x1e\x1c\x1a\x18\x16\x13\x10\x0c'` and `b'4/*(%" \x1e\x1c\x1a\x17\x12'`.
---
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda n:sum(b>n-a*5>-1for a,b in zip(b'($"
',b'=8))$$$'))
```
[Try it online!](https://tio.run/##HY7RC4IwEMbfpYcgiIjIIwbbYsLm0DTQf8R82ChJyCm6HuqfX1v38Ls7vuO7b/rY52ik66qbe6lB3xWY6/IeiK5Nos5ZnYhunEExDb2Bbz8RjQk6wfGw32036xVmGlcFpSj2hVCMKXX2sdgFKmhyzuBSMih8LyUDwTMPwQNyj9RrQvo15X8ID@lP0py3UTTNvbGk6UjwoxBihCnk@H9oqfsB "Python 3 – Try It Online")
---
# [Python 3.8](https://docs.python.org/3.8/), ~~90~~ 86 bytes
```
lambda x:-~sum([79<x<91,94<x<236,-1<(a:=x-110)<6,9<a<101,69<a<76,a/10in{2,3,4,5,6,9}])
```
[Try it online!](https://tio.run/##HY3RCoMwDEXf9xV5rBBZ02q1Ur/E@dCxyYRZRR04xvbrLvXlnBtySab3@hiDLqd57@rL/vTD9eZhq9Lf8hpEU1i3OUtoM7bSBlNywlf1lhLJxBm0zjuShCaGwqA/k@zDR6HGDHPkwrdN9vW@rAvU0BiJUFiEkm01AsmcQTLCMBTvSPOo5AFiaK4oI9vTaZr7sIqmE/FeAt04Q0zQh8MLf/oD "Python 3.8 (pre-release) – Try It Online")
The last condition can also be written as `a%10<1<a/10<7,a==90` at the same length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“Ḳœẹ“rɓ?’ḃ5×5“ZO‘;"Ä⁸>§I‘
```
A full program which prints the result (or a monadic Link which returns a single-element list).
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHOzYdnfxw104gs@jkZPtHDTMf7mg2PTzdFCgQ5f@oYYa10uGWR4077A4t9wTy/v//b2hkCQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw5yHOzYdnfxw104gs@jkZPtHDTMf7mg2PTzdFCgQ5f@oYYa10uGWR4077A4t9wTy/h9uf9S05v9/MwMdBXNLHQULIG1prKNgaGAKJAwNQIQZkDACyhkaA7lGBmDCEEgYA5UYmRkAAA "Jelly – Try It Online").
### How?
For any valid input, in \$[60,260]\$ we are able to use at least one club. For any given yardage, in \$[61,260]\$, we are able to use either the same, one more, or one less club than we could have done for one yard less. The code below encodes the yardages at which the number of available clubs goes up, and those at which the number of available clubs goes down and uses that to calculate the result.
```
“Ḳœẹ“rɓ?’ḃ5×5“ZO‘;"Ä⁸>§I‘ - Main Link: integer, Y e.g. 129
“Ḳœẹ“rɓ?’ - list of (two) base-250 integers = [11132965,7226564]
ḃ5 - convert to bijective base five -> [[5,3,2,2,2,2,3,3,2,5],[3,3,2,2,2,2,2,2,2,4]]
×5 - multiply by five -> [[25,15,10,10,10,10,15,15,10,25],[15,15,10,10,10,10,10,10,10,20]]
“ZO‘ - list of code-page indices = [90,79]
" - zip with:
; - concatenation -> [[90,25,15,10,10,10,10,15,15,10,25],[79,15,15,10,10,10,10,10,10,10,20]]
Ä - Cumulative values -> [[90,115,130,140,150,160,170,185,200,210,235],[79,94,109,119,129,139,149,159,169,179,199]]
⁸> - is Y greater than (those)? -> [[1,1,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0]]
§ - sums -> [2,4]
I - deltas -> [2]
‘ - increment -> [3]
- implicit print -> "3"
```
[Answer]
# [J](http://jsoftware.com/), 63 58 55 50 bytes
```
1#.1=(59 90+/\@,|:5*2+4#.inv 2424834 3408207)I."1]
```
[Try it online!](https://tio.run/##Zc@xCsJADAbg3af4sUOtrWeSu2t7hYIgCIKTs05iUQfdnHz3s7RD9S6Q5eNPSB5@rtIObYMUBQhN3yuF7fGw85wobhfWwVG@Pm2KT2OXkptE3Z9viBFTawNtqBaqsr2a89lns76ul9sLYLToUBL6@qPK/ZAMVMcpp6MUk51Ij8QUpbiMUuImMiNpCkmIwkEhDteLtuGpMjzpvw "J – Try It Online")
*-5 bytes thanks to xash*
Encodes lists as numbers in base 4, reconstructs, then uses interval index `I.` to count how many of the ranges the input falls within.
[Answer]
# [R](https://www.r-project.org/), ~~77~~ ~~76~~ 72 bytes
*Edit: -4 bytes thanks to Robin Ryder*
```
sum((d=scan()/10-9)>=c(11,9:2,.5,-1,d)&d<=c(d,14.5,12,11,9.5,8:4,2.5,0))
```
[Try it online!](https://tio.run/##FYlBCoAwDAR/IwlstSkVbLH@RZqrHiy@P8bTDDOP2XgvIm2jnzfxIjEUPlonEZSaMK8IAuVJd48KyV4k4d9uW81IzshskqN9 "R – Try It Online")
Fairly naive solution, but benefits from [R](https://www.r-project.org/)'s automatic vectorization and its `:` sequence operator.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~180~~ ~~155~~ ~~153~~ ~~97~~ 88 bytes
```
lambda n:sum(a<=chr(n)<b for a,b in zip('<P_nx‚Œ– ª´È','[tƒ—¡«ºÉÓìą'))
```
[Try it online!](https://tio.run/##HY5BC4JAEIXv/oq5ucIeViVL0f/Q3SK0FAVdRTeojkVQUKegrnWtjp06jv0vW718j3lvmHnlWiQFN9vYm7RZkIeLALhTL3MSuN48qQjX3BDiooKAhpBy2KQlUd3xjK9wiye84h2f@GkOKlV9gTs84w0f@MJvc2wuzfu3VzWtFVEtavDAtxiFoU1hJNU2KehsIKGzDpaEITPdlKPBeugSplwxLDZVuhZRFuVdjf6io0BZpVyQmHS@fPQH "Python 3 – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~85~~ 82 bytes
**Solution:**
```
{+/z=x|y&z}.(-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17),-9+.1*
```
[Try it online!](https://tio.run/##TY07EsIwDESv8ip@wUayEjuG4TppUtBCgLMbuaPYmf3N7hoea1uu7@Gy3Z@f1277xkMwghInEsbIRKYwU1G9CcmDP9OVKprQsdNyPIc6RD21ZZ@FUpmFaqj0njiyl33KfEk6lGR@laW1Hw "K (oK) – Try It Online")
**Explanation:**
Decidedly naive; highly likely that this is a bad approach. *Although nice golf by ngn to simplify the comparison logic!*.
```
{+/z=x|y&z}.(-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17),-9+.1* / the solution
.1* / multiply input by 0.1
-9+ / subtract 9 from input
, / append to
(-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17) / club stats
{ }. / call lambda with multiple args
y&z / min of input and min distance
x| / max compared to max distance
z= / is input the same?
+/ / sum up
```
**Extra:**
* **-3 bytes** thanks to `ngn`
[Answer]
# [Python 3](https://docs.python.org/3/), 105 bytes
```
lambda n,a=[1],b=[2],c=[3],d=[4]:(a*20+b*11+a*4+b*15+c*6+b*4+c+(c*9+d)*6+d*5+c*14+d+c*10+b*25+a*25)[n-60]
```
[Try it online!](https://tio.run/##HYzLDoIwEEX3fMWEFbRD0gegkNQfqV2UViKJVkJw4dfjlFmce@@81t/@/CR9zOZ@vPx7ih4SemOlw8lY5TAYqx1GY1s3Vp4pwScmJfeszabjgfVkWh54FdjAY005styXLY9Z8oXq6EJ1tU1NL9yxpPW7gwHbC4TLgHAlHTSCFB1BioyeoGgmNUUlTkiCphVFX4pi/mzw8OEJS4Lz5VgA1botaa/yAKFsbiXCfKa6Pv4 "Python 3 – Try It Online")
Explanation: A simple bruteforce to store the list of answers and print the required index.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
NθIΣE¹²⁻›θ⁺⁵⁹×⁵Σ…”)⊞⊟‹G↔”ι›θ⁺⁹⁰×⁵Σ…”)⊟+.D↥”ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RCO4NFfDN7FAw9BIR8E3M6@0WMO9KDWxBKRQRyEgB8g3tdRRCMnMTQWydBRAyp0rk3NSnTPyCzSUTIyNjSDARElHIVMTBHQU0E2wNMBtginYAKAxxqZwE8DA@v9/Q2OD/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Port of @JonathanAllen's answer. Explanation:
```
Nθ
```
Input `d`.
```
IΣE¹²⁻
```
Map over the 12 clubs and print the sum of the results cast to string of taking the differences between...
```
›θ⁺⁵⁹×⁵Σ…”)⊞⊟‹G↔”ι
```
... `d` compared with `59` added to `5` times the digital sum of prefix of the compressed string `43322222224`, and...
```
›θ⁺⁹⁰×⁵Σ…”)⊟+.D↥”ι
```
... `d` compared with `90` added to `5` times the digital sum of prefix of the compressed string `53222233235`.
Previous 48-byte answer:
```
NθIΣEI⪪”)¶∧!✂η}⌊⍘⪫⪫⊕#<e⌊W[qY9¤…”²∧›θ⁻×⁵ι﹪κ²⊖⊗﹪κ²
```
[Try it online!](https://tio.run/##VY1BCsIwFET3nqK4@oUKyf9prbgSBXFREfQCsQ0YTNOaJl4/xuLG2cw8mGHah3TtIE2MJzsGfw79XTl45dvFxWnrYS8nD9fQQyPHH4xGe1iWKJhYUyWQhGCEtCZGAmtCrIhhSpgS3yDxitccl0WGeV5kO9vB0SnpvzdF1mgbJrjpXk1QFplOjWboghngOQ8SH1TrVK@sVx0chnA3yf87s7YxcmJx9TYf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The ending and starting distances of the 12 clubs are split from a compressed string of integers from 12 to 52 which are multiplied by 5. `d` is compared against them all, scoring `1` for greater or equal distances in odd positions and `-1` for greater distances in even positions and the final total is printed.
[Answer]
# [Python 3](https://docs.python.org/3/), 62 60 bytes
```
lambda d:sum(b//25<=b%25+23-d/5<=7for b in b'BUNSWYQ+-}')+1
```
[Try it online!](https://tio.run/##zY5PC4JAEMXvfYKOc4lcNNydTftDXvoAQUREmAeXzQrKQu3Qoc9uoyepyIoOwY83DO8xb06XbHuMZR55q3wfHpQOQQ/T88FQto3OyFMtdEyUHW3T0ouOCSjYxaDa4/lktlhOzc612WamyLN1mqXgge9yC3oDC/o0B9ICwR0SwQtxSZA8IWlFXoogkRRBlweNU7KLM8OPDM2gKNNFWXk6YM/NJIw3a6MoRVewADx6gU5@DdbxUbiKfOC1W6X7r@4d8m1qw/g7xK8IWH4D "Python 3 – Try It Online")
There's an invisible (on Stack Exchange) `\x18` character at the end of the string.
[Answer]
*I think it's possible to achieve more aggressive compression ratios in most non-esolangs.*
*As a little incentive, here are my own scores in Python and Node.*
*I will unveil both code snippets below as soon as a shorter or equally long answer is posted (or updated) in either language, or at 2PM UTC on Friday August 21, 2020 in the unlikely event that no such answer is published by then.*
**EDIT (2020-08-19):** Congratulations to [@flornquake](https://codegolf.stackexchange.com/users/7409/flornquake) for being the first to post [a Python answer](https://codegolf.stackexchange.com/a/209762/58563) below 70 bytes, using an idea similar to mine but pushing it a step further for a total of 62 bytes!
---
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 70 bytes
```
lambda d,n=12:sum((n:=n+x//8-4)<=d/5<=n+x%8+6for x in b' A980001225F')
```
[Try it online!](https://tio.run/##HcpBDoIwEIXhq8zG0IYapq3UQujCjZdQF5CGSCKlQUzw9HXq5pu8/BO/23MJ2sY1je6eXv08@B68CE6q9v2ZGQutC@VeVfZ44p3zVd3lfbClGZcVdpgCDAVcGouIUqn6WvCUi8/lZlDAuRFg6TZagMSakJgxhKImNU2FfySh6UUZfLQQ1ylsbGSe8/QD "Python 3.8 (pre-release) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
d=>Buffer(' A980001225F').map(x=>t-=d/5<(n+=x-32>>3)|d/5>n+x%8+6,n=t=12)|t
```
[Try it online!](https://tio.run/##HcrLDoIwEAXQX@nG2IaCfYQK0TbRRH/CuCCU@gi2BKphwb/X0c25mXvn2XyaqR0fQ8x9sF1yOlltjm/nuhGv0aGuGGNciPK8JsWrGfCsTcy13ZR77DM951IYI8kChfHZvKoyRb2OmguyxLS7KEbRtqaogqwlRZyVAGc/FCBg4xJOwf5wQMKLUOxauDCemvaOLdIGtcFPoe@KPtywpchhSwhJXw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
The first byte in the string is added in `\x##` notation for easy testing, but is a literal byte.
```
$_=grep"@F">=($k+=(ord>>4)*5)&"@F"<=$k+(15&ord)*5,"\xc6G76&&&'((+L"=~/./g
```
Stores the details for each club (divided by 5) as a byte where the first four bits are the difference from start of the previous range and the start of this one, and the second four bits are the difference between the start of this range and the end.
```
start end => / 5 => binary #
--------------------------------------------
60 90 => 12 6 => 11000110 # counter starts at 0
80 115 => 4 7 => 00100100 # counter is 12 from before so we only need an extra 4
95 130 => 3 7 => 00110111
110 140 => 3 6 => 00110110
```
[Try it online!](https://tio.run/##NY1LDoIwEED3nKJBUov4oS0UiZa40o1HMDEEKjEQaVoWrjy6tbRxNi/vTSYjhRpyE/U8PYAFqNtWtOAxKjAJPYGm1kKb6M47JWR4OocVR1GfcDSqtqqyeJXHcM5HbivCObTdxnV4ezfsUjAI4RKh5Bryz26764xhKbCDg6L03DsnQUm94zR3jvG8oJbMOym907lnAUn/xK4T6u@Ie4C/o5ye40ubjayHHw "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~83~~ 75 bytes
(not all characters show correctly on stack exchange, but are correct in TIO)
```
*i;c;f(d){c=0;for(i=L"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z";*i;c+=d/ *i++&*i++/d);d=c;}
```
[Try it online!](https://tio.run/##VY4xT8MwEIX3/IqTpaCkCaqTQCA1Fn@AgRkhochOwALcqg4SUpWlYujQiaFz57KysDr8rxCnKZjlSe@@d/eOHd8z1rYjQRgpPe4vGMWknM49Qa9Qs/p@05/Nh94173rbrPRGf@m13uml3r7qjdTrO728Vhc3iJgDAeVjGIkgODIy5j7hlJG6rQpVeVyoKpesCIFNX2Tlw8IBELIC9lCwR6BQ/kZ8MqBZrlRHhgTdbxo4m3e49JCrJuBy8Fzu93IrUdhvXSKjaILKXDx1s/7EUB2CVVQ7jml6zoX0zE/9rymGEKKO9u4ss925YfHBZYnNInxqsSjCISR/LrVZnNks6ZInBxfj/y6yknFiN8Qp3rfX7Q8 "C (gcc) – Try It Online")
[Answer]
# [Io](http://iolanguage.org/), 89 bytes
```
method(a,"
\"$("asList select(i,v,v at(0)<=a/5and a/5<="
\"%(*/4"at(i))size)
```
[Try it online!](https://tio.run/##NY7dCsIwDIXvhxeioCIioSi0UrDt5vxhewMfwZuiHRbmpmvZhS8/sw5D@ELIyUls3RVwyeHWvYx/1g@qORmNp7PFcrWGG9lQot3VOg/OlObuqeUtb0F7KliW6/1BVw/AkuVkMh9WtnS3TwgqLGPOfg3rPv2BEk2o5ICp/oz/TEIOrWRRFMSp4HA8czhhPeNMigNCih4pQuFMxtgqEdB7xihRqWBQ1I3R9yf@Cy2PACN4FrRl/APDd/BubOXLKmLdDw "Io – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 36 bytes
```
s/RC-QTrV"2FUdnx‚Œ– ª¾""Qjyƒ—¡°¿Éâû
```
[Try it online!](https://tio.run/##K6gsyfjvFhj4v1g/yFk3MKQoTMnILTQlr@JQ06GeQ9MOLTi06tA@JaXArMpDzYd6D00/tPDQhkP7D3ceXnR49///0WYGOgrmljoKFkDa0lhHwdDAFEgYGoAIMyBhBJQzNAZyjQzAhCGQMAYqMTIziAUA "Pyth – Try It Online")
## Explanation
```
"... # String literal with end of ranges minus 10 as characters
"..." # String literal with start of ranges minus 10 as characters
rV # Generate the ranges
/R # Count occurrences of
C-QT # input minus 10 converted to a characters (based on ascii value)
# in each of the ranges
s # sum
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~142~~ ~~132~~ ~~117~~ 113 bytes
-10 bytes: applied -9 to ranges and input after division rather than only dividing by 10 (inspired by other answers, understood why it was worth it after observing my range/10 numbers)
-15 bytes thanks to Arnauld's improvements
-5 bytes thanks to Shaggy's further improvements
```
d=>[11,17,9,14.5,8,12,7,11,6,9.5,...'58473625',.5,4,-1,2.5,-3,t=0].map((e,i,r)=>t+=++i%2&d>=e&d<=r[i],d=d/10-9)|t
```
[Try it online!](https://tio.run/##PY3NroIwEIVfpRuVhkPttFBo4vAixAWxeMONikHiynfH0YWb7/zMSea/f/aP0zzel@LZrGdeE7cdEahGBJWmQgNyqCFdQJRsjNlVTVn74KodpChREJyYwmNhezTX/p5lA0bMmtsl5zwfN26bWh626cBzNx6ROO3JFlG/lvU03R7TZTCX6S/rgoWqI1QjGj0U2UpA9oMgcHIjL9HZL0jgZeLC77FW3KqzqNbrGw "JavaScript (V8) – Try It Online")
Pretty naive solution but I wasn't comfortable attempting more complex methods used in other answers (not to mention I'm not sure if they're even possible/worth golfing with in JS!). I'll happily take advice/improvements, though.
Unminified & explained (slightly outdated but still explains the overall process):
```
f = (distance) => {
// divide input by 10 and subtract 9 since the hardcoded ranges are shorter when those operations are done.
distance = distance / 10 - 9
// hardcoded ranges divided by 10 then subtracted 9 to save bytes (probably can be done better).
// Will be used in pairs, only processing even indexes and using i & i+1
//ranges = [20,26,18,23.5,17,21,16,20,15,18.5,14,17,13,16,12,15,11,14,9.5,13,8,11.5,6,9] // /10
//ranges = [14,20,12,17.5,11,15,10,14,9,12.5,8,11,7,10,6,9,5,8,3.5,7,2,5.5,0,3] // /10 -6
ranges = [11,17,9,14.5,8,12,7,11,6,9.5,5,8,4,7,3,6,2,5,0.5,4,-1,2.5,-3,0] // /10 -9 (winner! inspired by other answers)
// .map used as .reduce
ranges.map((e, i)=> { // e: current element, i: current index
totalValidClubs += ( // increment total 'valid' counter if within range
i%2 == 1 ? 0 : // skip odd indexes, will use i & i+1 on even indexes only
distance>=e && distance<=ranges[i+1] ? 1 : 0) // if even index and distance is between ranges[i] & [i+1] (inclusive), increment by 1.
}, totalValidClubs=0); // initialize valid club counter as 0
return totalValidClubs;
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ 36 bytes
**38 Bytes**
```
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z"Ç2ôε.SOÄ2‹}O
```
I'm bad at compressing :( The best I could have think of is converting each number to an ASCII character.
Explanation:
```
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z"Ç2ôε.SOÄ2‹}O
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z" Ranges of clubs as ASCII chars
Ç Convert to values
2ô Split into chunks of two
ε } Map on pairs
.S -1 if lower than input, 1 if greater, 0 it equal
O Sum the result of the pair
Ä Absolute value
2‹ Is it lower than 2? (The only cases the absolute value is 2 are when the input is out of range)
O Now we have list of 0 and 1 for each range. Sum it up :)
```
[Try it online!](https://tio.run/##AUoAtf9vc2FiaWX//yLDiMSEwrTDq8Kqw5LCoMOIwpbCucKMwqrCgsKgeMKWbsKMX8KCUHM8WiLDhzLDtM61LlNPw4Qy4oC5fU///zEyOQ)
**36 Bytes** (thanks to @ovs)
```
"ÈĄ´ëªÒ ȹª xn_Ps<Z"Ç2ôε-P(d}O
```
Using `-P(d` inside map, which will subtract the pair with the input, product it (out of range values will be positive), then apply `negative` with `(` and check if the value is non-negative using `d`.
[Try it online!](https://tio.run/##AUUAuv9vc2FiaWX//yLDiMSEwrTDq8Kqw5LCoMOIwpbCucKMwqrCgsKgeMKWbsKMX8KCUHM8WiLDhzLDtM61LVAoZH1P//8xMjk)
[Answer]
# [><>](http://esolangs.org/wiki/Fish), 51 bytes
```
"Çɳº©«Ÿ¡•—‹ƒwÓmt^ìO["1&{:})${:}(*&+&55*0l3)?.&n;
```
(contains 7 unprintables)
[Try it online!](https://tio.run/##AVIArf9maXNo//8iw4fDicKzwrrCqcKrwp/CocKVwpfCi8KNwoHCg3fDk210XsOsT1siMSZ7On0pJHs6fSgqJismNTUqMGwzKT8uJm47////LXYgMTg1)
Since there's at least 1 club for every input, one may re-arrange the ranges to get rid of one range, which has the added benefit of removing the "260" part which is just barely outside the range of a byte.
[Answer]
## [Desmos](https://www.desmos.com/calculator), 106 bytes:
```
f(d)=total(\left\{join([18...11],[9.5,8,6,20])*10<=d<=[47,42,40,37,34,32,30,28,26,23,18,52]*5:1,0\right\})
```
[View graph online](https://www.desmos.com/calculator/setzfaelgl)
Delete `f(d)=` and subtract 5 bytes if you're cool with using a slider as input.
[Answer]
## APL, ~~52~~ ~~45~~ 50 bytes:
```
{+⌿1=(↓12 2⍴⎕ucs'Èą´ìªÓ ɺ«¡xn_Pt<[')∘.⍸⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///Pz0/J@1R24Rq7Uc9@w1tNR61TX7UN7U0uVjB0EjB6FHvFvXDHUdaD205vObQqsOTDy043Hlo2qFdh3oOrT7UdGhhxaHpeYd64w81B5TYRKtrPuqYofeod8ej3q21EIMVzAwUzC0VLAwULI0VDA1MFQwNDYDYDGi4pYKhsYGCkQEIGyoYGZsqGJkZAAA)
] |
[Question]
[
I was going through a bizarre thread on Reddit, and came across this:
( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)
It's representing a group of people smiling somewhat suspiciously.
(In the challenge below though, spaces to the left of the right eyes were dropped somehow while I was writing the challenge. Note the spec).
---
Your goal is to create a group of smiling lenny faces `n` deep with the following rules:
1. At depth one, a full face (`( ͡° ͜ʖ ͡°)`) is shown.
2. At depth two, half faces are shown. On the left side, a little over half the face (`( ͡° ͜ʖ`) is represented. On the right however, the right side is shown, and the mouth is omitted (`ʖ ͡°)`)
3. Any deeper, and only the sides of head and eyes are shown (`( ͡°` and `͡°)`. There's a space between the eye and left side of the head, but there are, despite appearances, no spaces on the right side. The spacing is due the `͡` character which messes with things a bit.
---
Input:
* `n`, showing how many layers deep of faces to show.
* `n` will always be in the range `0 <= n <= 500`. You are not required to handle anything outside of this range.
* `n` may be offset by 1 so that 0 means one face instead of no faces. You'll need to handle -1 then though.
Output:
* A string, or character array, or anything remotely comparable (like a list of single-character strings in Python/Javascript). It can also be printed directly. Trailing white-space is fine.
You can submit a complete program, or a function.
---
Since it's difficult to see what characters are involved, here's it laid out in Python:
```
>> [ord(c) for c in '( ͡° ͜ʖ ͡°)']
[40, 32, 865, 176, 32, 860, 662, 32, 865, 176, 41]
>> [ord(c) for c in '( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)']
[40, 32, 865, 176, 40, 32, 865, 176, 40, 32, 865, 176, 32, 860, 662, 40, 32, 865, 176, 32, 860, 662, 32, 865, 176, 41, 662, 32, 865, 176, 41, 865, 176, 41, 865, 176, 41]
```
---
Test Cases:
```
face_crowd(0)
''
face_crowd(1)
'( ͡° ͜ʖ ͡°)'
face_crowd(2)
'( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)'
face_crowd(5)
'( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)'
face_crowd(10)
'( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)'
face_crowd(500)
'( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)͡°)'
```
---
[Here's](https://gist.github.com/carcigenicate/3cd9dd7bbcbe8b2e7e3620c6b6df33a4) an extraordinarily naive recursive reference implementation (posted on my Github). I tried to keep it as plain as possible for clarity; but there's a lot of duplication
I posted it externally because I wanted to wrap it in a spoiler in case people don't want to see a reference, but that complicates copying the code. I figure it's not important to the challenge really, so it isn't a big deal if it goes down I can paste it here if it's deemed important.
---
This is code-golf, so the least number of bytes in each language wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~89~~ ~~87~~ 80 bytes
*7 bytes off thanks to xnor*
```
(!!)$"":x:iterate(4#8)(7#6$x)
x="( ͡° ͜ʖ ͡°)"
(a#b)y=take a x++y++drop b x
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NRUVNFScmqwiqzJLUosSRVw0TZQlPDXNlMpUKTq8JWSUPh7MJDGxTOzjk1DczSVOLSSFRO0qy0LUnMTlVIVKjQ1q7U1k4pyi9QSFKo@J@bmJlnm5tY4BuvUVBaElxS5JOnl6YZbaCnZxr7/19yWk5ievF/3QjngAAA "Haskell – Try It Online")
To start we assign ( ͡° ͜ʖ ͡°) to a string `x` for convenience.
```
x="( ͡° ͜ʖ ͡°)"
```
Then we build a list of the answers and index it to find the solution. This is done by hardcoding the first two answers as the first two elements of the list and then iterating a function that adds the first 4 characters and the last 4 characters to front and back of the string across the third answer.
```
(!!)$"":x:iterate(4#8)(7#6$x)
```
We also have the special function `(#)` which adds a specified amount of ( ͡° ͜ʖ ͡°) to the front and back of a string:
```
(a#b)y=take a x++y++drop b x
```
[Answer]
# JavaScript (ES6), 66 bytes
```
f=n=>n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":""
```
[Try it online!](https://tio.run/##Zc4xDoJAEAXQ3lNMtmEmyEYNNiRgDBWNjaVYkJVViM4aIB6FysYbeAZLEs6Eqx2hm//yZzJl9shqVRX3xmNzyodBhxxGvBEI/evzFi56HkfLjUamQED/7Fpr/M@u6FoQVgXZ@Vcnm8SgDNfmmsurOaPGBdFsLMuJrCaynm79Do3MSXm7j5MElP28Bm0q2IV@kLLjHqSUGn06ylt2RwVhBEqqS1bFtrptkEiWpmB05uAQDV8 "JavaScript (Node.js) – Try It Online")
Or try it with the following snippet for a better rendering.
```
f=n=>n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":""
for(n = 0; n <= 10; n++) {
o.innerHTML += '"' + f(n) + '"\n';
}
```
```
pre { font-family:Arial }
```
```
<pre id="o"></pre>
```
### Commented
In the following code, we use the character set `"eEMN"` (eyebrow, eye, mouth and nose respectively) in order to preserve the formatting.
```
f = n => // f is a recursive function taking the number n of remaining
// faces to draw
n ? // if n is greater than 0:
"( eE" + ( // append the left cheek + a space + the left eye
--n > 1 ? // decrement n; if it's still greater than 1:
f(n) // append the result of a recursive call
: // else (n = 0 or 1):
"MN" + ( // append the mouth and the nose
n ? // if n = 1:
f(n) // append the result of a recursive call
+ "N " // followed by the nose + a space
: // else (n = 0):
" " // append a space and stop recursion
) //
) //
+ "eE)" // append the right eye + the right cheek
: // else:
// the special case n = 0 is reached only if the original
"" // input is 0; just return an empty string
```
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
f=lambda i:L[:7+~2%~i]+f(i-1)+L[6+2%i:]if i>1else L*i
L='( ͡° ͜ʖ ͡°)'
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIdPKJ9rKXLvOSLUuM1Y7TSNT11BT2yfaTNtINdMqNjNNIdPOMDWnOFXBRyuTy8dWXUPh7MJDGxTOzjk1DczSVP@fll@kkKmQmadgoGOoY6RjqmNooGNqYGBVUJSZV6IBNFJT8z8A "Python 3 – Try It Online")
-6 bytes thanks to xnor
[Answer]
# Excel, 85 bytes
```
=IF(A1>1,REPT("( ͡°",A1-1)&" ʖ( ͡° ͜ʖ ͡°)ʖ "&REPT("͡°)",A1-1),REPT("( ͡° ͜ʖ ͡°)",A1))
```
Naive solution for `n>1`. Second repeat required to handle `0` testcase.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes
```
.+
$*< $&$*>
>>
>ʖ >
<(?=<? )
< ͜ʖ
<
( ͡°
>
͡°)
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRctGQUVNRcuOS8EOhE9NU7DjstGwt7WxV9DkslE4O@fUNC4bLg2FswsPbeCy4wJRmv//mwIA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*< $&$*>
```
Generate the cheeks, but use `<`s and `>`s because `(`s and `)`s would need to be quoted. A space in the middle ends up between the middle man's nose and left eye.
```
>>
>ʖ >
```
If the man in the middle has a man on his left, give that man a nose and a space between it and his left eye.
```
<(?=<? )
< ͜ʖ
```
Add the mouth and nose to the man in the middle and the man to his right if any. We don't see the left eye of the man to his right so he doesn't need a space, and we gave the man in the middle a space on the first stage.
```
<
( ͡°
```
Fix the right cheeks and add the right eyes.
```
>
͡°)
```
Fix the left cheeks and add the left eyes.
[Answer]
# [Inform 7](https://en.wikipedia.org/wiki/Inform#Inform_7), 262 bytes
```
To say x:say "[Unicode 865][Unicode 176]".
To say y:say Unicode 860.
To say z:say Unicode 662.
To say p (N - number):say "( [x][p N minus 1][x])".
To say p (N - 2):say "( [x] [y][z][p 1][z][x])".
To say p (N - 1):say "( [x] [y][z] [x])".
To say p (N - 0):say "".
```
This takes advantage of Inform 7's function overloading: the most specific overload will be run, and the function that takes a number (any integer) as its argument is less specific than the function that takes the number two (and only two) as its argument.
There are some repeated bits of text, like "( [x]", which could potentially be abstracted as functions of their own—but I7 is so verbose, defining a new function takes more bytes than this would save! The only places defining a new function seems to save bytes is for the non-ASCII characters, since the syntax for printing them is *even more* verbose than the syntax for function definitions.
Boilerplate to run this:
```
Foo is a room. When play begins: say p 7.
```
Replace 7 with a non-negative integer of your choice.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 102 bytes
```
#include <string>
std::string f(int n){return n?"( ͡°"+(--n>1?f(n):" ͜ʖ"+(n?f(n)+"ʖ ":" "))+"͡°)":"";}
```
[Try it online!](https://tio.run/##TY5NDoIwEIXX9BSTurAVSNCEDRA4iLpoyo9NdDCluCFcg5Ubb@AZXJJwJiy4cTXv@zJ5efJ@9ysp541CeW3zAhJVN0YX4pb@OWsUVilpTB5FP4CSKTSAvNOFaTUCZpTB9Pq8qct8H9N9VjLkEYXpOQ7W4couHQeg1lJu8/LOLdG4n5e2m1C41gpdSQ/kRWjY2fw4njl0xClrzURralARdIEHew8OHoQ2WAiDoOfEcdaRsm4NJMmyki93e8JtTPr5Cw "C++ (gcc) – Try It Online")
Shameless port of Arnauld's JavaScript solution.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 96 bytes
```
$\='( ͡° ͜ʖ ͡°)'if$_--;$\="( ͡° ͜ʖ$\ʖ ͡°)"if$_-->0;$\="( ͡°$\ ͡°)"while$_-->0}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlZdQ@HswkMbFM7OOTUNzNJUz0xTidfVtQZKKiFJqsTAFChBFNgZIClRiYHKlWdk5qRCpGur//@3/JdfUJKZn1f8X7cAAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 42 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü/┐▐Φd¬•U►^τ∩█┴êZ3↔uº'µ3ó(▀◄Ü▒iÇÆ'[∞_¥▄>A√
```
[Run and debug it](https://staxlang.xyz/#p=812fbfdee864aa0755105ee7efdbc1885a331d75a727e633a228df119ab1698092275bec5f9ddc3e41fb&i=0%0A1%0A2%0A5%0A10&a=1&m=2)
I think it appears not to work in Firefox in Windows. But that's just because the FF default font for monospace is Courier, which seems not to support these fancy unicode modifiers or whatever. I think.
[Answer]
# Java 7, ~~133~~ ~~90~~ 89 bytes
```
String f(int n){return--n<0?"":"( ͡°"+(n>1?f(n):" ͜ʖ"+(n>0?f(n)+"ʖ ":" "))+"͡°)";}
```
Port of [@Arnauld's recursive JavaScript answer](https://codegolf.stackexchange.com/a/190098/52210), since it's shorter than my initial first attempt using a Java 8+ lambda.
[Try it online.](https://tio.run/##LU8xbsJAEOx5xWirO52MTGsTeEHSUCKKi7GjA3uNzmckhPwNKhp@kDekROJNztq4We3OzGpmDvZso8P@2GelbRp8WsfXGeA45L6wWY6v4QQ2wTv@QaaEAetUwG4mowk2uAz9xBcTf/V5aD1HES/jNVFCCq/H3y8ZxavFulCsE8Lr/ryNSDwihp43iBSkZR/kmtKuTwebU/tdis3kdq7dHpVEVW/b7Q5Wv3MWtR8juI84hVsuhmmMHjlpcWlCXs3rNsxP8hhKVs5QAjISXE@tuv4f)
**Explanation:**
```
String f(int n){ // Recursive method with integer parameter & String return-type
return--n // Decrease the input by 1 first
<0? // And if the input is now -1:
"" // Return an empty string
: // Else:
"( ͡°" // Return the left part of Lenny's face
+(n>1? // And if the modified input is larger than 1:
f(n) // Append a recursive call with this now decreased input
: // Else (the input is here either 0 or 1):
" ͜ʖ" // Append Lenny's nose
+(n>0? // And if the input is larger than 0 (thus 1):
f(n) // Append a recursive call
+"ʖ " // As well as the right part of its nose
: // Else (thus 0):
" " // Append a space instead
))+"͡°)";} // And also append the right part of Lenny's
```
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
f=lambda i:i*'x'and"( ͡° ͜ʖ"[:7+~2%~i]+f(i-1)+"ʖ ͡°)"[2%i:]
```
[Try it online!](https://tio.run/##7dhLqsIwFAbgeVZxKEgSW6GtiFDoSkqRqC0GNIrpQCcuw9Gd3B24BoeCa6pVwSe3cEV08mfwETiPnAyT2bIYTU27LPN4rCb9oSId6SZfcGWGjqD973ZD@5/d2kmirrsKGyudurnQrUC6zm59iksnCRs6Sssis0VvoGxmKaaECd8jzqVHIqg2N73OVadIeB95SrpNZqJzyX62vv6Bc7vAr@lX779O@5NqjOpS/utjQAghhBBCCD/je54AAAAAAADg23DJUsby6ZyMR9liRtrQ9Wc7YlQtZW02LygXRlIcH7M8MuUB "Python 3 – Try It Online")
The index calculation idea is borrowed from @xnor in [@Jitse's solution](https://codegolf.stackexchange.com/a/190121/88506).
[Answer]
# [Julia 1.0](http://julialang.org/), 85 bytes
```
f(n,s="( ͡° ͜ʖ ͡°)")=n<3 ? ["",s,s[1:10]s*s[10:17]][n+1] : s[1:5]f(n-1)s[12:17]
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/P00jT6fYVklD4ezCQxsUzs45NQ3M0lTStM2zMVawV4hWUtIp1imONrQyNIgt1gIyDKwMzWNjo/O0DWMVrBRAMqaxQGN0DTWBbCOQ5H@H4oz8coU0DQNNLhjTEME0QjCNkRQAFf8HAA "Julia 1.0 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 47 bytes (UTF-8)
```
?"( ͡°{´U>1?ß:" ͜ʖ"+(U?'ʖiß:S} ͡°)":P
```
Saved a byte thanks to Shaggy
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PyIoIFx1MDM2MbB7tFU%2bMT/fOiIgXHUwMzVjXHUwMjk2IisoVT8nXHUwMjk2ad86U30gXHUwMzYxsCkiOlA&input=OQ)
[Answer]
# [Python 3](https://docs.python.org/3/), 80 chars, 86 bytes
```
x='( ͡° ͜ʖ ͡°)'
n=3-1
print(x[:4]*(n-1)+x[:7]*(n!=0)+x+x[6:]*(n!=0)+x[8:]*(n-1))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8JWXUPh7MJDGxTOzjk1DczSVOfKszXTNeQqKMrMK9GoiLYyidXSyNM11NQGss1BbEVbAyAHyDWzQnCjLayg6jT//wcA "Python 3 – Try It Online")
To put input, change the 3 to whatever input you want, leaving the -1 alone.
If anyone knows a better way to do input that would reduce the char count let me know.
Nothing fancy going on here, just string slicing and abuse of booleans
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 46 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
b*5USy{↖qYq⇵≡„a¹„┬Hc+
⁷m;⁷±m±└++
H?34⁸]]⁷]57⁸}
```
[Try it here!](https://dzaima.github.io/Canvas/?u=YiV1RkYwQTVVU3klN0IldTIxOTYldUZGNTFZJXVGRjUxJXUyMUY1JXUyMjYxJXUyMDFFYSVCOSV1MjAxRSV1MjUyQyV1RkYyOCV1RkY0MyV1RkYwQiUwQSV1MjA3NyV1RkY0RCV1RkYxQiV1MjA3NyVCMSV1RkY0RCVCMSV1MjUxNCV1RkYwQiV1RkYwQiUwQSV1RkYyOCV1RkYxRiV1RkYxMyV1RkYxNCV1MjA3OCV1RkYzRCV1RkYzRCV1MjA3NyV1RkYzRCV1RkYxNSV1RkYxNyV1MjA3OCV1RkY1RA__,i=Mw__,v=8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes
```
NθP⭆θ✂ʖ ͡°)⊗‹¹ι←⭆θ✂ʖ͜ °͡ (∧‹¹ι³
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndrzfs@HR2rZzOx7NaTo1TeHswkMbNB91TX/UsPPQznM7H7VNQEienaNwaMPZhQoajzqWQ@UPbf7/3xQA "Charcoal – Try It Online") The deverbosifier tries to quote the second string for some reason, but it doesn't seem to be necessary, but here's the [verbose version](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLtzSnJLOgKDOvRCO4BEil@yYWaBTqKATnZCanaiidmqZwduGhDZpKOgou@aVJOakpGj6pxcUahjoKmZogYM0VANZs5ZOaVgLUhtWMs3MUDm04u1BBA2iMYx6yEToKxmBT/v83/a9blgMA "Charcoal – Try It Online") if you want it. Explanation:
```
Nθ
```
Input the number of faces.
```
P⭆θ✂ʖ ͡°)⊗‹¹ι
```
Print the left sides of the faces (on our right as we see them). These consist of the string `ʖ ͡°)` repeated up to twice, and then that string without the first two characters repeated the remaining number of times.
```
←⭆θ✂ʖ͜ °͡ (∧‹¹ι³
```
Print the right sides of the faces (on our left as we see them). These consist of the (reversed) string `ʖ͜ °͡ (` repeated up to twice, and then that string without the first two characters repeated the remaining number of times.
The more observant among you will have noticed that the middle face has its nose generated twice which is why I'm printing in such a way that they overlap.
] |
[Question]
[
Given a list or delimited string, output a list or delimited string with the first character of each word one word later.
For this challenge, a "word" consists of only all printable ASCII characters, except the space, newline, and tab character.
For example, take the string "Good afternoon, World!" (space-delimited):
```
1. String
"Good afternoon, World!"
2. Get the first characters:
"[G]ood [a]fternoon, [W]orld!"
3. Move the characters over. The character at the end gets moved to the beginning.
"[W]ood [G]fternoon, [a]orld!"
4. Final string
"Wood Gfternoon, aorld!"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
**Test cases:**
```
Input -> output (space-delimited)
"Good afternoon, World!" -> "Wood Gfternoon, aorld!"
"This is a long sentence." -> "shis Ts i aong lentence."
"Programming Puzzles and Code Golf" -> Grogramming Puzzles Pnd aode Colf"
"Input -> output" -> "onput I> -utput"
"The quick brown fox jumped over the lazy dog." -> "dhe Tuick qrown box fumped jver ohe tazy log."
"good green grass grows." -> "good green grass grows."
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
```
€ćÁ2ôJ
```
Explanation:
```
€ć Extract head of each
Á Rotate to the right
2ô Split into pieces of length two
J Join
```
[Try it online!](https://tio.run/nexus/05ab1e#@/@oac2R9sONRoe3eP3/H63unp@foq6joJ6YVpJalJefnwfihOcX5aQoqscCAA "05AB1E – TIO Nexus")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ ~~10~~ ~~9~~ 8 bytes
Takes advantage of Japt's index wrapping and negative indexing.
```
ËhUgEÉ g
```
[Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=y2hVZ0XJIGc=&input=WyJUaGlzIiwiaXMiLCJhIiwibG9uZyIsInNlbnRlbmNlLiJd)
---
## Explanation
```
:Implicit input of array U (each element is an individual word).
Ë :Map over the array.
h :Replace the first character of the current element (word) ...
Ug : with the word in the array at index ...
EÉ : current index (E) -1's ...
g : first character.
:Implicit output of array of modified words
```
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
p%((a:b):r)=(p:b):a%r
_%e=e
(%)=<<head.last
```
[Try it online!](https://tio.run/nexus/haskell#FcZbCoAgEEDRf1cxDAkK0QKiWUlEjDg9wESmWr/lx@XcWqxzPAY/qidX2rBVs1ohMRs562maDuE4JL6fevGZgaDomR/oYPubUSViDxjSK81dRTIu9QM "Haskell – TIO Nexus") Uses a list of strings for input and output.
Remembers the first letter of the previous word `p`, and recursively makes it the first letter of the current word while sending the new first letter down the chain. The previous first letter is initialized as the first letter of the last word.
[Answer]
# Ruby, ~~85~~ ~~77~~ 63 bytes
Pretty sure this could be much shorter.
Edit: Thanks for @manatwork for collect -> map
```
a=gets.split;$><<a.zip(a.rotate -1).map{|x,y|y[0]+x[1..-1]}*' '
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Ḣ€ṙ-;"
```
[Try it online!](https://tio.run/nexus/jelly#@/9wx6JHTWse7pypa630/3D70UkPd874/z9a3dFJXUfd2QVIuLqpxwIA "Jelly – TIO Nexus")
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for reading the rules better than me, this returns a list of the words. It doesn't work as a full program.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~12~~ ~~10~~ 9 bytes
Saved 1 byte thanks to jimmy23013
```
q~Sf+:()o
```
Takes input as a list of words.
[Try it online!](https://tio.run/nexus/cjam#@19YF5ymbaWhmf//f7SSe35@ipKCUmJaSWpRXn5@ng6QE55flJOiqBQLAA "CJam – TIO Nexus")
### Explanation
```
e# Example input: ["Good" "afternoon," "World!"]
q~ e# Read and eval the input.
e# STACK: [["Good" "afternoon," "World!"]]
Sf+ e# Append a space to each word.
e# STACK: [["Good " "afternoon, " "World! "]]
:( e# Remove the first character from each substring.
e# STACK: [["ood " 'G "fternoon, " 'a "orld! " 'W]]
)o e# Remove and print the last element of the array.
e# STACK: [["ood " 'G "fternoon, " 'a "orld! "]]
e# Implicitly join the remaining array with no separator and output.
```
[Answer]
## JavaScript (ES6), 46 bytes
```
s=>s.map((k,i)=>s.slice(i-1)[0][0]+k.slice(1))
```
Takes advantage of the fact that `slice(-1)` returns the last element of an array.
**Snippet**
```
f =
s=>s.map((k,i)=>s.slice(i-1)[0][0]+k.slice(1))
console.log(f(['Good', 'afternoon,', 'World!']));
console.log(f(['This', 'is', 'a', 'long', 'sentence.']));
console.log(f(['Programming', 'Puzzles', 'and', 'Code', 'Golf']));
console.log(f(['Input', '->', 'output']));
console.log(f(['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog.']));
console.log(f(['good', 'green', 'grass', 'grows.']));
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 7 bytes
```
Îxjp
{P
```
[Try it online!](https://tio.run/nexus/v#@3@4ryKrgKs64P//gKL89KLE3NzMvHSugNKqqpzUYq7EvBQu5/yUVC73/Jw0AA "V – TIO Nexus")
Explanation:
```
Î " On every line:
x " Delete the first character
j " Move down a line
p " And paste a character (into column 2)
{ " Move to the beginning of the input
P " And paste the last thing we deleted (into column 1)
```
[Answer]
# Vim, ~~16~~, 9 bytes
```
<C-v>GdjPGD{P
```
*7 bytes saved thanks to @Wossname!*
Takes input one word per line, e.g.
```
Hello
world
and
good
day
to
you
```
I believe this should be fine since taking the input as a list is allowed.
[Try it online!](https://tio.run/nexus/v#@y/mnpIV4O5SHfD/f0BRfnpRYm5uZl46V0BpVVVOajFXYl4Kl3N@SiqXe35OGgA)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~44~~ 45 bytes
```
90.f3+0.>&i&01.>~r&l0=?;o20.
i:" "=?^:1+ ?!^
```
Assumes space-separated words.
Correction by Aaron added 1 byte
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 6 bytes
Takes matrix with one word per column.
```
¯1∘⌽@1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///37M8seBR24RD6w0fdcx41LPXwRAipvCobypQ/FHbxGgDPdNYdff8/BR1BfXEtJLUorz8/DwdICc8vygnRVEdAA "APL (Dyalog Unicode) – Try It Online")
`¯1∘⌽` rotate one step right
`@` at
`1` row 1
[Answer]
## Python 2, 74 bytes
[Try it online](https://tio.run/nexus/python2#DcixCoAgEADQva@4JpVMag2a@wCHBnFQKriIOzFb@nlrevCqnZHSU6Qyd7rwt0kZqQgQ5mQkGd3gu@DGyR@cIegISPBiklZb1//dWTf1o1eqVrEwbxCOsmdiJg0r52trxQc)
```
S=input().split()
print' '.join(b[0]+a[1:]for a,b in zip(S,S[-1:]+S[:-1]))
```
-5 bytes, thanks to @Rod
[Answer]
# [Haskell](https://haskell.org), 50 bytes
```
f=zipWith(:).((:).last<*>init).map head<*>map tail
```
Input and output are as lists of words.
[Answer]
# PHP, 62 bytes
```
$c=end($_GET);foreach($_GET as$g)echo$g|$g[0]=$c^$g^$c=$g,' ';
```
[Answer]
# C#, ~~78~~ 77 bytes
```
using System.Linq;a=>a.Select((s,i)=>a[i-->0?i:a.Count-1][0]+s.Substring(1));
```
Compiles to a `Func<List<string>, IEnumerable<string>>`, Full/Formatted version:
```
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
static void Main()
{
Func<List<string>, IEnumerable<string>> f = a =>
a.Select((s, i) => a[i-- > 0 ? i : a.Count - 1][0] + s.Substring(1));
Console.WriteLine(string.Join(" ", f(new List<string>() { "Good", "afternoon,", "World!" })));
Console.WriteLine(string.Join(" ", f(new List<string>() { "This", "is", "a", "long", "sentence." })));
Console.ReadLine();
}
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
{hᵐ↻|bᵐ}ᶠzcᵐ
```
[Try it online!](https://tio.run/nexus/brachylog2#@1@d8XDrhEdtu2uSgHTtw20LqpKBjP//o5Xc8/NTlHSUEtNKUovy8vPzdICc8PyinBRFpdj/UQA "Brachylog – TIO Nexus")
### Explanation
```
Example input: ["Good","afternoon,","World!"]
{ }ᶠ Find: [["W","G","a"],["ood","fternoon,","orld!"]]
hᵐ↻ Take the head of each string, cyclically permute them
| (and)
bᵐ Get the strings without their heads
z Zip: [["W","ood"],["G","fternoon,"],["a","orld!"]]
cᵐ Map concatenate on each list: ["Wood","Gfternoon,","aorld!"]
```
[Answer]
# R, ~~72~~ 70 bytes
`function(x)paste0(substr(x,1,1)[c(y<-length(x),2:y-1)],substring(x,2))`
[Try it online](https://tio.run/##Jco7CsMwDADQq7SeJFCgzhjaOUfoUDrkY6cGIwVbgeT0rkPGBy@V4l9@40mDMOy4DlndA/I2Zk2wkyWLnwmOZxMdL/qrhdruaCx@6UqBl/paxOIhhqxgepHZ0M0MXl1iEaZTb0lxvpv6yh8)
2 bytes saved thanks to Giuseppe.
Input and output are lists. Takes a substring consisting of the first letters, cycles the last one to the front, and pastes it together with a substring of the rest of each word. The cycling step is a killer, but I can't figure out a way to cut it down any further.
[Answer]
## Python 2 + Numpy, 104 bytes
```
from numpy import *
s=fromstring(input(),"b")
m=roll(s==32,1)
m[0]=1
s[m]=roll(s[m],1)
print s.tobytes()
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$13\log\_{256}(96)\approx\$ 10.701 bytes
```
j/ +e[qJ]xxep
```
*-2.469 bytes thanks to one of the @Sʨɠɠans*
[Try it online!](https://fig.fly.dev/#WyJqLyArZVtxSl14eGVwIiwiW1N3YXAsIHRoZSwgZmlyc3QsIGxldHRlcnNdIl0=)
Explanation:
```
J # Append
x # the input
]x # to the first item from the input,
q # then remove the first item from that.
e[ # Get the first character from each item.
ep # Get the input with the first char of each word removed.
+ # Add,
j # join by
/ # space
```
[Answer]
## Mathematica, 59 bytes
```
""<>#&/@Thread@{RotateRight@#~StringTake~1,#~StringDrop~1}&
```
[Try it online!](https://sandbox.open.wolframcloud.com/)
Takes and returns a list of words.
If you prefer to take and return strings, this works for 87 bytes:
```
StringRiffle[Thread@{RotateRight@#~StringTake~1,#~StringDrop~1}&@StringSplit@#," ",""]&
```
[Answer]
# kdb+, ~~25~~ 22 bytes
**Solution:**
```
rotate[-1;1#'a],'1_'a:
```
**Example:**
```
q)rotate[-1;1#'a],'1_'a:("The";"quick";"brown";"fox";"jumped";"over";"the";"lazy";"dog.")
"dhe"
"Tuick"
"qrown"
"box"
"fumped"
"jver"
"ohe"
"tazy"
"log."
```
**Explanation:**
```
1_'a: // (y) drop first character of each element of a
,' // join each left with each right
rotate[-1;1#'a] // (x) take first character of each element of a, rotate backwards 1 char
```
**Extra:**
A version that takes a regular string (37 bytes):
```
q){" "sv rotate[-1;1#'a],'1_'a:" "vs x}"The quick brown fox jumped over the lazy dog."
"dhe Tuick qrown box fumped jver ohe tazy log."
```
[Answer]
# [Perl 5](https://www.perl.org/), 40 bytes
39 bytes of code + 1 for `-a`
```
$F[-1]=~/./;$a=$&,s/./$a/ for@F;say"@F"
```
[Try it online!](https://tio.run/##K0gtyjH9/1/FLVrXMNa2Tl9P31ol0VZFTacYyFRJ1FdIyy9ycLMuTqxUcnBT@v/fPT8/RSExrSS1KC8/P09HITy/KCdF8V9@QUlmfl7xf11fUz0DQ4P/uokA "Perl 5 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 34 bytes
```
;@(,.~_1|.])~/@|:@(split;.2)@,&' '
```
[Try it online!](https://tio.run/##FU7NSgMxGLzvU4wXt4VtRI8WS6BgETz0IHgSiZsvaWo235ofq0vpq68RhmGYGYY5zrN5EFjLRScu77dn8ba83MjzvVyk0bu8FndL2V23aGfqDyyN3KAv@fkRKWsX0LbzjllDmUwxMIcOrxy9vmpeDi6hQsFzsEgUMoWeRLOPbKMaBlfdfZkmT7UUNLasCTv2pnkKY8lYbcAlV1WnCF/F9Z/4iHwKMPyDYxlG0uBvisg192r6hWYrGvv/x0aiUFmlVJlPSfwB "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
Foz:ṙ_1TmΓ,
```
Input and output as a list of strings, [try it online!](https://tio.run/##yygtzv5f/qipsfy/W36V1cOdM@MNQ3LPTdb5//9/SEaqQmFpZnK2QlJRfnmeQlp@hUJWaW5BaopCfllqkUIJUD4nsapSISU/XQ8A "Husk – Try It Online")
(The header just transforms the input to a list of words and joins the output list with spaces.)
### Explanation
```
F(z:ṙ_1)TmΓ, -- example input: ["Good" "afternoon,","World!"]
m -- map the following (example on "Good")
Γ -- | pattern match head & tail: 'G' "ood"
, -- | construct tuple: ('G',"ood")
-- : [('G',"ood"),('a',"fternoon,"),('W',"orld!")]
T -- unzip: ("GaW",["ood","fternoon,","orld!"])
F( ) -- apply the function to the pair
ṙ_1 -- | rotate first argument by 1 (to right): "WGa"
z: -- | zip the two by (example with 'W' and "ood")
-- | | cons/(re)construct string: "Wood"
-- :-: ["Wood","Gfternoon,","aorld!"]
```
### Alternative, 11 bytes
```
§oz:ṙ_1m←mt
```
[Try it online!](https://tio.run/##yygtzv5f/qipsfz/oeX5VVYPd86MN8x91DYht@T///8hGakKhaWZydkKSUX55XkKafkVClmluQWpKQr5ZalFCiVA@ZzEqkqFlPx0PQA "Husk – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~46~~ ~~37~~ 31 bytes
*Several bytes saved thanks to @Neil and @PunPun1000*
```
(\S)(\S* +)
$2$1
(.* .)(.)
$2$1
```
[Try it online!](https://tio.run/##JU7LasNADLzvV0wgATttFtIPyKUH01ughV566CYrb9yupXQfTeKfdxUKo2E0GsQkKgO77bxqus@5@XhtddZ4aM3yabk1jV3Dto39X@e5E/FwfaHEIvyId0nRL8zbachQOEThgExciI9kzT5JSG4cB3X3dZoiaYg9nsUTOom9eeFzLdjsILWo0leEnzocv3FIcmH0csVXHc/kIb@UUPQe3XSDl2BNuPcJiYiVXc7Kcsn2Dw "Retina – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `S`, 7 bytes
```
vhǔ?vḢ+
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJTIiwiIiwidmjHlD924biiKyIsIiIsIltcIlN3YXBcIiwgXCJ0aGVcIiwgXCJmaXJzdFwiLCBcIkxldHRlcnNcIl0iXQ==)
```
vh # Get the first item of each
ǔ # Rotate to the right
? # Push the input
vḢ # Get the all but the first char of each
+ # Add
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~25~~ 20 bytes
Byte count assumes ISO 8859-1 encoding.
```
Om$`^.((?=.*¶))?
$#1
```
[Try it online!](https://tio.run/nexus/retina#FU5LagJBFNz3KSpoYNSkIQeILrIQVwoRshGxY7/pjPa8p/3xMwfzALnYpANFUVQVRT1Xn7tNnPTLdrjb6qqavevx72M0mqnh4K3fsEI/F7EwdaLAIvyCLwnePqn1TxNRYOCFHSJxIt6TVqsgLpi2bYq7yl3nqZTY4kMsYS6@Vgs@5YTXKSSnosoU4Zyb/RHfQa6MWm445PZEFnKhgFRyb7o7rDit3P8fF4i4sImxsFyj/gM "Retina – TIO Nexus")
Input and output are linefeed-separated. The test suite performs the necessary I/O conversion from space-separation.
[Answer]
## Mathematica, 134 bytes
```
(w=Characters@StringSplit@#;d=Drop[w,0,1];StringRiffle[StringJoin/@Table[PrependTo[d[[i]],RotateRight[First/@w][[i]]],{i,Length@w}]])&
```
[Answer]
# Pyth, 12 bytes
```
.b+hNtY.>Q1Q
```
Takes a list of words and returns a list of words.
[Try it!](https://pyth.herokuapp.com/?code=.b%2BhNtY.%3EQ1Q&input=%5B%27Good%27%2C+%27afternoon%2C%27%2C+%27World%21%27%5D&debug=0)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 97 bytes
```
for(int n=s.length,i=0,j=n-1;i<n;j%=n)System.out.print(s[j++].charAt(0)+s[i++].substring(1)+" ");
```
[Try it online!](https://tio.run/##LY6xDoJAEER7v2I1MbkLSLBGCisrKwsLQnEC6p24S24XEkP49hOM00zyJjMZZwazo65BV79C199aW0HVGmY4G4swrmDWn7MYmW0gW8N7TtVFvMVHUQJrGMOdvLIogDknbYMPecY2T2OX426f2QNmbpujvnxYmndCvSTd3BbFhYuiMqmexh9FpTriwi6A@xv/9tVeRxvY6CwsX6bVFMKJqA7mLo1HIozDlXxbr78 "Java (OpenJDK 8) – Try It Online")
] |
[Question]
[
Given *N* (2 <= *N*), print *N* lines of the letter Fibonacci series like this (i.e. *N* = 5)
First, start with `a` and `b`:
```
a
b
```
Next, add the two lines.
```
a
b
ab
```
Keep adding the last two lines.
```
a
b
ab
bab
```
Keep going...
```
a
b
ab
bab
abbab
```
And we're done.
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins.
[Answer]
# Python 2, 41 bytes
*Saved 3 bytes thanks to @xnor*
```
a,b="ab";exec"print a;a,b=b,a+b;"*input()
```
[Test on Ideone](http://ideone.com/zeXj9d)
Simply follows the recursive definition.
[Answer]
## Haskell, ~~29~~ ~~35~~ 32 bytes
```
a%b=a:b%(a++b)
(`take`("a"%"b"))
```
Simple recursion.
For reference: the old version (an adaption of [this answer](https://codegolf.stackexchange.com/a/86961/34531)),
concatenated the strings in the wrong order, so I had to add a `flip(...)` which made it too long (35 bytes).
```
f="a":scanl(flip(++))"b"f
(`take`f)
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes
Thanks to *Emigna* for saving a byte!
```
'a='b¹GD=Š«
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=J2E9J2LCuUdEPcWgwqs&input=OQ)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
”a”bṄ;¥@¡f
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCdYeKAnWLhuYQ7wqVAwqFm&input=&args=NQ)
### How it works
```
”a”bṄ;¥@¡f Main link. Argument: n
”a Set the return value to 'a'.
”b ¡ Call the link to the left n times, with left argument 'b' and right
argument 'a'. After each call, the right argument is replaced with the
left one, and the left argument with the return value. The final
return value is yielded by the quicklink.
¥ Combine the two atoms to the left into a dyadic chain.
Ṅ Print the left argument of the chain, followed by a linefeed.
; Concatenate the left and right argument of the chain.
@ Call the chain with reversed argument order.
f Filter the result by presence in n. This yields an empty string
and thus suppresses the implicit output.
```
[Answer]
# Java 7, 69 bytes
```
String c(int n,String a,String b){return n--<1?"":a+"\n"+c(n,b,a+b);}
```
### ungolfed
```
class fibb {
public static void main(String[] args) {
System.out.println( c( 7, "a" , "b" ) );
}
static String c(int n,String a,String b) {
return n-- < 1 ? "" : a + "\n" + c(n,b,a + b);
}
}
```
[Answer]
# Emacs, ~~26~~, 25-ish keystrokes
### Program
`#n` to be read as key with digit(s) *n*:
`A``RET``B``RET``F3``UP``UP``C-SPACE``C-E``M-W``DOWN``DOWN``C-Y`
`UP``C-A``C-SPACE``C-E``M-W``DOWN``C-E``C-Y``RET``F4``C-#(n-2)``F4`
## Explanation
```
command(s) explanation buffer reads (| = cursor aka point)
-----------------------------------------------------------------------------------------------
A<RET> B<RET> input starting points "a\nb\n|"
<F3> start new macro "a\nb\n|"
<UP><UP> move point two lines up "|a\nb\n"
C-<SPACE> C-E M-W copy line at point "a|\nb\n"
<DOWN><DOWN> move point two lines down "a\nb\n|"
C-Y yank (paste) "a\nb\na|"
<UP> move point one line up "a\nb|\na"
C-A C-<SPACE> C-E M-W copy line at point "a\nb|\na"
<DOWN> move point one line down "a\nb|\na|"
C-E C-Y <RET> yank (paste) and add new line "a\nb|\nab\n|"
<F4> stop macro recording "a\nb|\nab\n|"
C-#(n-3) <F4> apply macro n-3 times "a\nb|\nab\nbab\nabbab\n|"
```
## With n=10
```
a
b
ab
bab
abbab
bababbab
abbabbababbab
bababbababbabbababbab
abbabbababbabbababbababbabbababbab
bababbababbabbababbababbabbababbabbababbababbabbababbab
```
[Answer]
# JavaScript (ES6), ~~43~~ 42 bytes
*Saved a byte thanks to @Arnauld*
```
f=(n,a="a",b="b")=>n&&f(n-!alert(a),b,a+b)
```
[Answer]
# CJam, ~~19~~ 17 bytes
```
'a'b{_@_n\+}ri*;;
```
explanation
```
"a": Push character literal "a" onto the stack.
"b": Push character literal "b" onto the stack.
{_@_p\+}
{: Block begin.
_: duplicate top element on the stack
@: rotate top 3 elements on the stack
_: duplicate top element on the stack
n: print string representation
\: swap top 2 elements on the stack
+: add, concat
}: Block end.
r: read token (whitespace-separated)
i: convert to integer
*: multiply, join, repeat, fold (reduce)
;: pop and discard
;: pop and discard
```
[Answer]
# [V](http://github.com/DJMcMayhem/V), 18 bytes
```
ia
bkÀñyjGpgJkñdj
```
[Try it online!](http://v.tryitonline.net/#code=aWEKYhtrw4DDsXlqR3BnSmvDsWRq&input=&args=Nw)
Or, the more readable version:
```
ia
b<esc>kÀñyjGpgJkñdj
```
Explanation:
```
ia
b<esc> " Insert the starting text and escape back to normal mode
k " Move up a line
Àñ ñ " Arg1 times:
yj " Yank the current line and the line below
G " Move to the end of the buffer
p " Paste what we just yanked
gJ " Join these two lines
k " Move up one line
dj " Delete the last two lines
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
97c98ci2-:"yyh
```
[Try it online!](http://matl.tryitonline.net/#code=OTdjOThjaTItOiJ5eWg&input=NQ)
```
97c % Push 'a'
98c % Push 'b'
i2- % Input number. Subtract 2
:" % Repeat that many times
yy % Duplicate the top two elements
h % Concatenate them
```
[Answer]
# Python 2, 55 bytes
```
def f(n):m='a','b';exec'print m[-2];m+=m[-2]+m[-1],;'*n
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), 33 bytes
```
.+
$*
^11
a¶b
+`¶(.+?)1
¶$1¶$%`$1
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCoKXjExCmHCtmIKK2DCtiguKz8pMQrCtiQxwrYkJWAkMQ&input=NQ)
Saved 10 (!) bytes thanks to @[MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender)!
### Explanation
Converts the input to unary, subtracts `2` and adds the `a` and the `b`, then recursively replaces the remaining `1`s with the concatenation of the two previous strings.
[Answer]
## Batch, ~~102~~ 93 bytes
```
@set a=a
@set b=b
@for /l %%i in (2,1,%1)do @call:l
:l
@echo %a%
@set a=%b%&set b=%a%%b%
```
Fortunately variables are expanded for every line before assignments take effect, so I can set both `a` and `b` using their old values without needing a temporary. Edit: Saved 9 bytes thanks to @nephi12.
[Answer]
# Stack my Golf, 63 bytes
Get my language here: <https://github.com/cheertarts/Stack-My-Golf>.
```
($1=(_(a))($2=(_(b))($2-f:1-f,)?)?)f\($1=(f)($1-p(\n),:f,)?)p\p
```
There is probably a shorter way but this is the most obvious.
[Answer]
# Perl, ~~36~~ 35 bytes
Includes +3 for `-n`
Give count on STDIN
```
perl -M5.010 fibo.pl <<< 5
```
`fibo.pl`
```
#!/usr/bin/perl -n
$_=$'.s/1//.$_,say$`for(a1.b)x$_
```
[Answer]
# Perl, 45 +1 = 46 bytes
+1 byte for -n flag
```
$a=a,$b=b;say($a),($a,$b)=($b,$a.$b)for 1..$_
```
Slight improvement over the existing 49-byte solution, but developed separately. The parentheses for `say($a)` are necessary because otherwise, it interprets `$a,($a,$b)=($b,$a.$b)` as the argument of `say` which outputs more junk than we need.
# Perl, 42 bytes
```
$b=<>;$_=a;say,y/ab/bc/,s/c/ab/g while$b--
```
A separate approach from the above solution:
```
$b=<>; #Read the input into $b
$_=a; #Create the initial string 'a' stored in $_
say #Print $_ on a new line
y/ab/bc/ #Perform a transliteration on $_ as follows:
#Replace 'a' with 'b' and 'b' with 'c' everywhere in $_
s/c/ab/g #Perform a replacement on $_ as follows:
#Replace 'c' with 'ab' everywhere in $_
, , while$b-- #Perform the operations separated by commas
#iteratively as long as $b-- remains truthy
```
I'm not yet convinced I can't combine the transliteration and replacement into a single, shorter operation. If I find one, I'll post it.
[Answer]
# [SOML](https://github.com/dzaima/SOML), 8 bytes
```
a b.{;t⁴+
```
explanation:
```
a b.{;t⁴+ stack on 1st cycle
a push "a" ["a"]
b push "b" ["a","b"]
.{ repeat input times ["a","b"]
; swap the two top things on the stack ["b","a"]
t output the top thing on the stack ["b","a"]
⁴ copy the 2nd from top thing from stack ["b","a","b"]
+ join them together ["b","ab"]
```
This language is still in development and I did add a couple new functions while writing this.
Also, 1st post on PPCG!
[Answer]
# Swift 3, 76 Bytes
```
func f(_ n:Int,_ x:String="a",_ y:String="b"){if n>1{print(x);f(n-1,y,x+y)}}
```
[Answer]
## Perl, 48 bytes
**47 bytes code + 1 for `-n`.**
Simple approach. Try using an array slice originally `$a[@a]="@a[-2,-1]"` but that necessitates `$"=""` or similar :(. Save 1 byte thanks to @[Dada](https://codegolf.stackexchange.com/users/55508/dada)!
```
@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@
```
### Usage
```
perl -nE '@;=(a,b);$;[@;]=$;[-2].$;[-1]for 3..$_;say for@' <<< 5
a
b
ab
bab
abbab
```
[Answer]
# 05AB1E, 15 bytes
```
'a'bVUFX,XYUYJV
```
[Answer]
# **C**, 156 bytes (without indent)
```
void f(int n)
{
char u[999]="a",v[999]="b",*a=u,*b=a+1,*c=v,*d=c+1,*e,i;
for(i=0;i<n;++i)
{
printf("%s\n",a);
for(e=c;*b++=*e++;);
e=a;a=c;c=e;e=b+1;b=d;d=e;
}
}
```
Two buffers (u & v) store the last two lines. The newest line (tracked with two pointers: start=c, end=d) is appended to the oldest one (start=a, end=b). Swap (a,b) and (c,d), and loop. Pay attention to buffer size before requesting too much lines.
Not so short (as expected of a low-level language), but was fun to code.
[Answer]
# PHP, ~~63~~ 62 bytes
Recursive version:
```
function f($n,$a=a,$b=b){return$n--?"$a
".f($n,$b,$a.$b):'';}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
a,b="ab"
for i in range(input()):
print(a+b)
a,b=b,a+b
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyVYpMUmJKy2/SCFTITNPoSgxLz1VIzOvoLREQ1PTiouzoCgzr0QjUTtJk4sTpDxJB8j@/98UAA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 44 bytes
```
a,b="ab"
exec"print(a+b);a,b=b,a+b;"*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyVYpMUmJK7UiNVmpoCgzr0QjUTtJ0xokkaQDZForaWXmFZSWaGj@/28KAA "Python 2 – Try It Online")
[Answer]
# [Pyth](http://github.com/isaacg1/pyth), 17 bytes
```
J,\a\bjP.U=+Js>2J
```
A program that takes input of an integer and prints the result.
[Try it online!](http://pyth.tryitonline.net/#code=SixcYVxialAuVT0rSnM-Mko&input=MTA)
**How it works**
```
J,\a\bjP.U=+Js>2J Program. Input: Q
,\a\b Yield the two element list ['a', 'b']
J Assign to J
.U Reduce over [0, 1, 2, 3, ..., Q] (implicit input):
=J+ J = J +
>2J the last two elements of J
s concatenated
P All of that except the last element
j Join on newlines
Implicitly print
```
[Answer]
# Pyth - ~~16~~ 15 bytes
```
A"ab" m=H+
~GHH
```
[Try it online here](http://pyth.herokuapp.com/?code=A%22ab%22+m%3DH%2B%0A%7EGHH&input=5&debug=0).
[Answer]
# APL, 30 bytes.
`⎕IO` must be `1`.
```
{⎕←⍵}¨{⍵∊⍳2:⍵⌷'ab'⋄∊∇¨⍵-⌽⍳2}¨⍳
```
[Answer]
# Mathematica, 49 bytes
```
f@1="a";f@2="b";f@n_:=f[n-2]<>f[n-1];g=f~Array~#&
```
Defines a function `g` taking the single numerical input; returns a list of strings. Straightforward recursive implementation, using the string-joining operator `<>`.
# Mathematica, 56 bytes
```
NestList[#~StringReplace~{"a"->"b","b"->"ab"}&,"a",#-1]&
```
Unnamed function, same input/output format as above. This solution uses an alternate way to generate the strings: each string in the list is the result of simultaneously replacing, in the previous string, all occurrences of "a" with "b" and all occurrences of "b" with "ab".
[Answer]
# Groovy, 79 Bytes
```
{println("a\nb");x=['a','b'];(it-2).times{println(y=x.sum());x[0]=x[1];x[1]=y}}
```
[Answer]
# PHP, 53 bytes
```
for($a=b,$b=a;$argv[1]--;$a=($_=$b).$b=$a)echo$b.'
';
```
[Answer]
# C++11, ~~89~~ 98 bytes
+7 bytes for *all* lines, not only the last one. +2 bytes more for `N` being the number of lines printed, not some 0-based stuff.
```
#include<string>
using S=std::string;S f(int n,S a="a",S b="b"){return n-1?a+"\n"+f(n-1,b,a+b):a;}
```
Usage:
```
f(5)
```
] |
[Question]
[
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of *all* input strings. If there are several substrings of equal length, and no longer substring, output any one of them.
* This may mean outputting the empty string.
* If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
* There will always be at least one string in the input, but there might not be a non-empty string.
* All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
* You may take input or produce output by any of the [default methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) aren't allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - the fewer bytes of code, the better.
## Test cases:
`[Inputs] -> [Valid outputs (choose one)]`
```
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), ~~3~~ 9 bytes
```
{sᵛ}ᶠlᵒtw
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7r44dbZtQ@3Lch5uHVSSfn//9FKuYl5lQqZeQWlJcVKOgpKqDwQJzMTxKpMzMurVIoFAA "Brachylog – Try It Online")
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
## Explanation
```
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
```
Apparently, the tiebreak order on `s` is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's `s` doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it *still* prints nothing to standard output, thus it outputs the null string as intended.
[Answer]
# [Python 2](https://docs.python.org/2/), 82 bytes
```
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
```
[Try it online!](https://tio.run/##bY7NbsMgEITvfYqVq7i25R7SY6Scq1x6SHuzrIrYEEhhscxSlad3ja30B@UAzOx8g3YIJC0@TZPYa2ZOPQNZV7STwLAHw74KWTGtCwkKwYGw43zPkspaFLLZ7tqZXvXucbuaDx72mmM5DaNCKkRRNZnkWtushuxhEW1Z3v1JP/kYYmh8J@PbKyH4yJFSkJuBFjKe17fj4eU5RVQ/91THdER@TUI5mvU5Io6Oh1klOUnlwCJfPnHAwPnT2gEr4CdNWhfv6Nb8unE6NwwDWE@DJ7fu4gfyFgIyc5NVeEX/u2iUiiowxJB2Nxu0lMf44vN7R1E1ecv0INk7esNH1cXO9A0 "Python 2 – Try It Online")
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings `h` to find the longest one that appears in all the remaining strings `t`. To do so, we recursively branch on removing the first or last character of `h`.
---
**[Python 2](https://docs.python.org/2/), 94 bytes**
```
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
```
[Try it online!](https://tio.run/##bY8xT8MwEIX3/gqrqG2MQqQyRspcdWEobCFCJnESF/tsxWeEVfrbQxwoVaIOlt/d@96dbTy2Gh77OnvtJVPvFSMyVewrshwTAcg7y0sUGqJ7xUzUxJLS@IP7THKgiyb7y9jUEgbVyZ6/m8jm27Sgo0gftgXV3WmzOfemG@ZFdZQvWy6lXsZkuRlFQenian7yzgdPubINdyXqmncccMZxZXAEw3l@OeyfdjNCVENKlEwG4lpMIYuDbAJh8bAf1NTGVliigY8jhj@SJEnIf3PKHp3FG@3LG2dtxcAT7dA4tL/rnUGniQembqECLuS0CoUQQXkG4GfR1Qo0roN7dOs7i0Hl64JJ07I3cIp3ogyR/gc "Python 2 – Try It Online")
A more direct method. The auxiliary function `g` generates the set all substrings of `s`, and the main function takes the longest one in their intersection.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 6 bytes
```
Ẇ€f/ṫ0
```
[Try it online!](https://tio.run/##y0rNyan8///hrrZHTWvS9B/uXG3w/1HDHKVHDXOtraGMY5uAcllAjg5IFEjr2oHlD7fDVHAdbgcqifzPxaWUV6mQmZmppKOgVJmYl1ep9D9aKTcRJJhXUFpSDBJH5aGrj9WJVsoAOiofJKQOZoCEwGbkl5bAtBWXlBaUlOYrVOYl5oIVKOmAEYiZB9QL1FCSnKEUCwA "Jelly – Try It Online")
Thanks to @JonathanAllan for saving 6 bytes!
[Answer]
# [Ruby](https://www.ruby-lang.org/) 2.6, ~~76 59~~ 54 bytes
```
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
```
[Try it online!](https://tio.run/##TYyxDsIgFEV3v8IwGkvSua3@gGM3wvDagqBYySNKDPDtCNEYl3uSc5KLj@mV5ZCbA4SdH6DzVOp1CRGj73uks7rbQtZS2rS8AwrGHEN00THkKaVst5IxAtO8kD35DhDON59wgmKe2tnKUaBwf3FU2lVd8ZP1Sshz8Upfrua2lpTf "Ruby – Try It Online") - Ruby 2.5 version (56 bytes)
### How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
[Answer]
# [R](https://www.r-project.org/), ~~119~~ ~~116~~ ~~108~~ 106 bytes
```
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
```
[Try it online!](https://tio.run/##VY/BTsMwDIbvPEVUtNKKgOCKqHZEUyUOLbdpYlnqkkytEyUO0KcvTacWLVJk@/8/O44bW/b6wMY2oCRtMKv5cXssUCrheFn04jfb1jn3RQVNkJBpJHAeJPFOWNsNE@/DyZPT@MWfXkruwGYxQlHeP@fT8fsfpaV6nEf5/DC2mcwSBV1nEp7czTHPb2b1G9yQcJb0QaoYG9224ABpJaC3NCPx1h/V7v1t9XQzkVqKLnr/xWJfloyep2o3ZYtBSntmEOY2zwRbf8RMy1Z3wc/B05WwrLMKvcCBmUA2kL@8FywFwwYU/TWkcWGuq1hoHbNBIA5r02aDhtKon0N66ylm@/QgOqvEJ4YenJYTPP4B "R – Try It Online")
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
*-3 bytes thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)*
*-8 bytes using* `lapply` *instead of* `Map`
*-2 bytes thanks to Kirill L. again, removing braces*
[Answer]
# [Zsh](https://www.zsh.org/), ~~126 ...~~ 96 bytes
*-3 bytes from arithmetic for, -6 bytes from implicit `"$@"` (thanks roblogic), -5 bytes from removing unneeded `{` `}`, -1 byte from short form of `for`, -1 byte by using `repeat`, -1 byte by concatenating `for s ($b)` with its body, -13 bytes by changing the repeat loop out for some eval jank.*
```
for l
eval a=\( \$l\[{1..$#l},{1..$#l}\] \)&&b=(${${b-$a}:*a})
for s ($b)(($#x<$#s))&&x=$s
<<<$x
```
~~[Try it online!](https://tio.run/##rU7NboMwDL77KTwIJIGhajsOkPYEk3buegiQLZlCUhFQaRHPzkK3R5gP34/92fLNq@2itJE4SNFhMaDRVpbYOfByxKLAiCzs9Z0HvPF9tq7R9ulCDhZRo65hN4yVOs8rEpssey45F3nNiDk@5foQeo@Bk8AnDk3oL2RpCiLWl0ysfL3ve2Sk4cAYiedwxXOepnNNPFRVReZtsvszAhs0ITqjhs5ZuVk3Km2/UL9h6/reWaBKXnFUcpAU6S4DTbgzyP48XpFSvAugSRLW0zD/ntLY78FjehLmrISdejnoFlslBk8hopRGGP3Bb0WgpDHuAy9uMN0D/ouDHw "Zsh – Try It Online")
[Try it online!](https://tio.run/##rU5LUoQwEN33KVrIED5Sli4VruAFRhYBWhMrJFMJOIwUZ8cgHsFe9Hv9@vXn28vtKpUmdCR6LB1qZegFewv0JTR6GrEsMWK7HG3vNhhgETWqGhxdSIzIzizWef7UoCjqlOlzUaiHIBWP9@r0i00GbegsbGlLJtbnXKzZCvsujylrszRl8Vyx2GdZksw181BVFZu3yeznBbYYHsEZFfTW0GbsKJX5QPWKnR0Ga4BLuuEoyRFHvtMAE@4InCMNl/F2ZDg4D/rpFPYkwfg5JbHfJ85JI/RFCjMN5FSHnRTOc4g45xFGf@mICCRpbd/wap3u7/BfKvgB "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##rU1BUoQwELznFW3IErBkq7wqfMEPbPYQlmhihWQrAZeV4u0YCv2Bc@jp6eme@Y56vWljFYKSHaoAa5x6ReeJ@pIWUQ2oKlC2yXR998mwb2QjCghmxWl@Ph5ZZpenPyLOEGWet03BZja3FZPLy6NcSrLFIwrWlkXBsqlmWSyTcWpYJHVds2kd3fZRokX6jQmGdN6p1flBG/cB84aL73vvCNfqjkGroDj4RlMbsXXCOVR/He47kp3zpB8O6U6ejJ9jnsUtccrP0l61dGOvgrngomWInFDOOQX9hb0o0cpaL3DzwXYP@JeJ/AA "Zsh – Try It Online")
We read all possible substrings into the array`a`, and then set `b` to the intersection of the arrays `a` and `b`. The construct `${b-$a}` will only substitue `$a` on the first iteration: Unlike its sibling expansion `${b:-$a}`, it will not substitute when `b` is set but empty.
```
for l; # implicit "$@"
# === OLD ===
{
a= i= # empty a and i
repeat $[$#l**2] # compound double loop using div/mod
a+=($l[++i/$#l+1,i%$#l+1]) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
# === NEW ===
eval a=\( \
\$l\[{1..$#l},{1..$#l}\] \ # The {bracket..expansions} are not escaped
\) &&
# === ===
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
€Œ.«ÃéθJ
```
-6 bytes thanks to *@Adnan*.
[Try it online](https://tio.run/##yy9OTMpM/f//UdOao5P0Dq0@3Hx45bkdXv//RyuVpBaXKOkogOnMvHQQswgkFAsA) or [verify all test cases](https://tio.run/##VY9BTsMwEEWvMjJq2ERcoUtUFiwKuyhCbuqQqWI7sseVvG0lDtBbIDgAayq2HKIXCR27pbCw/P9/fzQa6@UC1biOUwGHlx2IaRwPm/ev3c3n2367f/3@uBvLsapEp/reihLEdRJ1CZVYKxc50qHp@F9i2yqnDGWs9ECJ83t4nM/ubzPA5bGDjewZXExinhyaZwae5rOjSil16MEalQY8SPBhkZtgW/ilqbsKni7uvD87LU0EG2gI5POOMFCwEI3UfxpozoX/jg0iqyiNiXliMjGWCg5XobjyxKoqatkPnXwyQSuHzekKlSn/pyMdR3X9Aw).
**Explanation:**
```
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
```
[Try it online!](https://tio.run/##Lcm9CsIwEADg3ac4QoYEqjhLsrkIQh@gdDh/gofXa8ndkMF3jw4u3/K9UN9P5t5p2dZqcEbDw5XUdiW0U42ZUc3rr0YJx@TjpB9NexIyzSkZEiu0AZkD6UUKtbGAxjr3BUkgw1ZJDDwUmBze7g83uD/o5v4F "Haskell – Try It Online")
Get all suffixes (`tails`) of the first word `x` in the list and take all prefixes (`inits`) of those suffixes to get all substrings `s` of `x`. Keep each `s` that `isInfixOf` `all` strings in the remaining list `r`. Sort those substrings by length (using [the `(0<$)` trick](https://codegolf.stackexchange.com/a/146634/56433)) and return the last.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 48 bytes
```
M&!`(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)
O#$^`
$.&
1G`
```
[Try it online!](https://tio.run/##K0otycxL/P/fV00xQcPexjZOT0tTQ09bU8PeVkNPKyYPiA01tfS0VDS5/JVV4hK4VPTUuAzdE/7/z03Mq1TIzCsoLSnmQmKCWJmZXJWJeXmVAA "Retina 0.8.2 – Try It Online") Explanation:
```
M&!`(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)
```
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
```
O#$^`
$.&
```
Sort the substrings in reverse order of length.
```
1G`
```
Keep only the first, i.e. the longest substring.
[Answer]
# TSQL query, 154 bytes
```
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1015685/greatest-common-substring)**
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
>
> SELECT top 1with ties x FROM
>
>
>
[Answer]
## C# (Visual C# Interactive Compiler), ~~320~~ 257 bytes
```
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
```
[Try it online!](https://tio.run/##jZBfT9swFMXf@RRWphZnCpnEKyQV2zTUrQKJIu0BoclNbxKH5DqyrwELwVcvcUs6thdsyfK51@d3/KcwR4WRmx8Wi9OFNHRqSEus8uRtZSXLNm2W812d/lQSeZRESZsuoYWCuMlyhAcmkW5MugCsqP68F8e3o43LpImz/C3mm8JCDGy6vJM9b74cvYxInF6LO@DN5F1rGOlZVWmoBAHnIlkNSSKdI4E2Pnw1GM61sv1Xxx@z/HGfdanXoH2T@e4vcHG6EIYu9XcohW2Jx7Pxgi7LXTyb@be8/wg@HH6yOTn4rSXBQiLwkv/veYpqaFsVJSw63IrngfmAuAftPNDZovbrWpYlaEAKgaHraUv7uby@ml@ch2ByPeTLQrQe@1sEkDvhMUNX80EFMFRLwxTC9jDDBDN2tdtkqmT73YCkxhoK9Y6/EuLtBDqmLPWWzO5ttiermEPRBfMSR/zfyhdSeuUEogvJm0xQ0dQjjZ1@MuTVzfRWtH0t/qDtQMtim7N5BQ)
Props to @Expired Data and @dana
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~62~~ 60 bytes
```
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*]>>.join))[0]}
```
[Try it online!](https://tio.run/##VVDLbsIwEDzDV6xSCEkEhl56qaDqoaqQqh5oVVUKoTLBKaaxHcV2pQjBub/S3@qPpLFDeByymdmZ2Ww2I3l6U7IC3ATG5XYvRa68QYBiwZb9L1JICP9@fiNADGde3Q4XwTtCsAiiyQRtBOW@H46iXZmIHLyUciJ92LZbbOjNQxTczSMfBUc4vG23JC4g8Toj9PB2/@T3oQfjCfT2nev2rgydNUlT4fTB6VkQwWACoVPjduh8k7wwKtPx2rxXNElITrhqnNZFWKaszTwvr7Pp8@OFTldVgsY4NfqJHCxnjcorVU75pzFKNZtW6OCSyvQMr0xqTSUITuw8CRikXtZBEAkc1UP0xKvoRkt1Lp54JTb/cLE9w7wAoVWmlaz30pnSAgqOWWNkRsB2Q1PsMcAUe1ttit0/swNOYylvpl4yQyi1ozDnRfMZg6pot8uFco260e5VfRnP9XGarfEH14zkNG4iXSf6Bw "Perl 6 – Try It Online")
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra `.comb` and `>>` in there.
~~Another annoying thing is that `max` can't take an function for how to compare items, meaning I have to use `sort` instead.~~ As pointed out in the comments, `max` *can* take an argument, however it ends up longer since I have to take into account `max` returning negative infinity when there are common substrings ([Try it online!](https://tio.run/##VVDLTsMwEDw3X7EKbV6UFC5cUIs4IFQJcSgIIaUpclOHusR2FNuIqJQzv8Jv8SMhdpo@Dl7PeGY2m81xkV1WtAQnhWG19ly3//WOSwHR389vDCFFuReECafzaBa8hCHMgng0ClecMN@v1U/vtJH9TZXyAryMMCx8WFsdOvCmURhcT2M/DHZwcGV1BCoh9brn4e3zzb3fBxeGI3C/uxfWporsJc4ybvfBdg2I4WwEkd1gK7I/cFFqlapkqe8FSVNcYCZbp3Fhmktj0@fxaTJ@uDvSyaJOkARlWt@TreXgofYKWRD2po1CTsY12rqE1G@a1ya5JAI4w6afAARCzZsg8BR26ja653V0pYQ8FPe8Ftt/OJqeIlYCVzJXUjRzqVwqDiVDtDVSLSAzoS5mGaCL2a3Sxcyfmwb7toS1XY@ZJoSYVoixsv2MRnW012NcOlpdKeek2Yzn@CjLl@iVKYoLkrQRx47/AQ "Perl 6 – Try It Online")).
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-hF`](https://codegolf.meta.stackexchange.com/a/14339/), 8 bytes
```
Îã f@eøX
```
Thanks to Shaggy for saving 3 bytes
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWhG&code=zuMgZkBl%2bFg=&input=WyJraGVsbG8iLCAiJ2tlbGxvIiwgImt3ZWxsbyJd)
```
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 8 bytes
(I could knock off the last 3 bytes and use the `-Fh` flag instead but I'm not a fan of using `-F`)
```
mã rf iP
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg=&code=beMgcmYgaVA=&input=WyJoZWxsbyIsICInZWxsbyJd) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=beMgcmYgaVA&footer=zA&input=WwpbImhlbGxvIiwgIidlbGxvIl0KWyJ2ZXJ5IiwgIm11Y2giLCAiZGlmZmVyZW50Il0KWyJlbXB0eSIsICIiLCAiU1RSSU5HIl0KWyJpZGVudGljYWwiLCAiaWRlbnRpY2FsIl0KWyJzdHJpbmciLCAic3RSSW5nIl0KWyJ0aGlzIG9uZSIsICJpcyBhIHN1YnN0cmluZyBvZiB0aGlzIG9uZSJdClsianVzdCBvbmUiXQpbIiIsICIiLCAiIl0KWyJtYW55IG91dHB1dHMiLCAic3R1cHR1byB5bmFtIl0KWyJtYW55IGlucHV0cyIsICJhbnkgaW5wdXRzIiwgIm55IGlpaSIsICJ5YW5ueSJdClsiJSVub3QmIiwgImp1JiNzdCIsICJbJl1hbHBoYV9udW1lcmljIl0KXQ)
```
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
►LFnmQ
```
[Try it online!](https://tio.run/##yygtzv7//9G0XT5uebmB////j1bKTcyrVMjMKygtKVbSUULhgNiZmUBGZWJeXqVSLAA "Husk – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 137 bytes
```
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
```
[Try it online!](https://tio.run/##bY4/T8MwEMVn@BSnLNiiA4itqHPVhaGwRRmc@Nw4JOfIfxD@9CF2VaJEHSzfe@/3fB6jbw29TZNEBYLVfN8cylKWao@VMhYQNIEVdEHWIzHJn1958tXi42xlViavrt4t@mAJBvHLSg0p0SlpypdKz0v6nmXd5ajLEa923xgP8wo@jVaTZ4KVRYt9b4odFE95qDh/XMIftDFlQ2jadEutFFokv@FwGH0G0/n8Op8@jhtCy7mlG9EnYhFryPl5vCTC@fNpntaxb7UDQ5ifcCDAhfpaAaPgP12XuuD8Hfv22Y09CIpggh@Dd9d/hNEHA5HEcA/VdCPXKgmt0xQFUUzVh@kP "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 103 bytes
```
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
```
[Try it online!](https://tio.run/##bY4xT8MwEIV3fsWpqCUWFUPHSsyoC0NhC1HkxOfGJT5H9hkRIX57iFuVKlEHy@/e@97pup4bR5tBwzN8DK20lZJQba38zjyqWGMWkJ/KUpIqy3X@o3K9xUI7DwiGwEs6YNYiZUo8bkTy9dVH8ZsclZyqEOtP7J9HVgydN8SZzvJFg23rFmtYPJxEIcTdNfxC36fMxrpJvzJao0fiGYe24xOY3tv7fvf6MiOMGlumlm0irsMUCjzKQyIC73ejmsbcmACO8LQigIQQq3MFnIb/dFo6xsA37MuxM9tK6sFF7iKH8x2x4@igJ2lvoYYu5HRKgzFJ9ZKon1WXS3K8Sukxru4DJ5WvCtl2jSwpWvSmTpXhDw "Python 2 – Try It Online")
This is an anonymous lambda that transforms each element into the set of all substrings, then `reduce`s it by set intersection (`set.__and__`) and then returns the `max` element by `len`gth.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~147~~ 145 bytes
```
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
```
[Try it online!](https://tio.run/##jZBda8IwFIbv/RWhQ9diFe/TCGOwIcgudLALkZHV1J7ankpyslHE3@6adu7jagkk533Jed58pGaSGrg8WEyTJRhKDGnA/Tz@qixjgl2kmJ8AiYGYxUVctetByM1sO10q3FPO@2ZmRBDEO2F4VuuQQ3LgMB5HzhSi4sV4nBwmwCPIQjm9K8uwEfNmel8jSUATmj5ybd/6uBDiImrHqRIFd6lnrchqZDt@vvDB4EUDqSWgCrMQ1Qf7ff1TkKuyrIOYBbedOEcR/4d4V7pxQGXT3NUdZJnSCskHVtWROtrN9fNq8fTog8GuzYdUlg77MR5kLxxmaLVolQdDORhWo@oOM0wyc/1rVmfse9cjqbCGfHuvv@LTW0lsWG3paMn0b7NHsjVrUFbePOAV/@ucAXCqkYiNT95wiDWNHFLY0Y0hpzajrSyPuXxFWykNaZdz@QQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Perl 5 (`-aln0777F/\n/` `-M5.01` `-MList::util=max`), 99 bytes
may be golfed more certainly
```
map/(.+)(?!.*\1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
```
[TIO](https://tio.run/##TVBLTwIxGLz3V1RkF5BH5UBIII0bEyEkygH1JIaUpctWt49sW2ND9q@7tmuCXDrzzcw3bapoWUzq@4flan1qI9wBGGPQqQB3UT6vOVGoO@r3undXo5vt2OOpnZ/acdXvV0HsoUGymGviYCZLeCypOjmEUIoxJ9/Qb8NmHCT7Ktnj4CcLjEPFrhp8UqejvA7rLX9rq85pUUjQac7wjC9aOsBtmoMDyzJaUmEanXJlHADPL5vVetko7OA9lpLiggVdm5KJo4fNykNQTM40lIICDwRqu/@LQJnBsxVyH1ab88CJcFBao6zRvswqYyV0gvB/l4nGvKCBMQYcEcI1uSgS0sS@Ob7WBrzF76RQOdkJy2nJ0h@pDJNC10NSiNvpdLpAW4Hq4dMj02Y2ezWsCJ/qhcnodvwL)
[Answer]
# JavaScript (ES6), ~~98~~ 92 bytes
```
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
```
[Try it online!](https://tio.run/##fVHBboMwDL3vKyKmMpBa2l0r0R6nXjap2w2hKUCAVCFBOKnKZb/O6qA269iKhPFz3nvGzoEeKeQdb/VCqoINZTzQeBNUcRZDvKERO7KuD07x5usUcVmw01sZQBhuszhLIBJMVrpOt9ka1lUAEQies2A1XzzPHXwO8QloskrDIVcSlGCRUFVQBolXMyGUNyfek03SMCTLJUm8ET38puPfILsxeY3fgpcl65jUTvmHijWttjJ83z/2u9eXu3xenB15TgXyHbhKfpQmWtAdlxUKQe935@yqAo1VrExEuuZAlGS2HxBKwGSjEVEluZ5erVxlYnUwoG/JrjIhX3ZydxsNlT1RRrdGwziXabVRpJe0ccIGj6idEINdN8Fgb9dgsPO31uK/NlxeutwiBJxbYypl79piPrGazaTSPrIPxn8c9574KRVtTT@laVjHc2fhe@nwDQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
```
[Try it online!](https://tio.run/##VY4/C8IwEMXn9lMcna4QQWen4iRYEBxLh1DT5jC99E8qVPGzx1Q76HBw7927H6/ScqisNN5n40gN49l22KcCdLqPV2sr4BFUbQfAk@LGadRpCs84WgMXQ5VCHWICjlwNqlXs1BUpcHZhVPiOqAbMjMFewMFO7PC2HAInn4yjbqBgfYLKjApy2a3wH@C3x8v7okhayTMQd5MbEwHJv1oE0bLNknlOytJv7uYN "Charcoal – Try It Online") Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
```
≔⊟θη
```
Pop the last string from the input list into a variable.
```
≔⁰ζ
```
Zero out the substring start index.
```
FLη«
```
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
```
≔✂ηζ⊕ι¹ε
```
Obtain the current substring.
```
¿⬤θ№κε
```
Check whether this substring is contained in all of the other input strings.
```
Pε
```
If it is then overprint any previously output substring.
```
≦⊕ζ
```
Otherwise try incrementing the substring start index.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~295~~ ~~166~~ 145
```
for l;{((f++));d=${#l};i=;for((;i++<d**2;)){ echo "${l:i/d:1+i%d}">>$f;};}
for j in *;{((f++));grep -xf$j $[j+1]>$f;};egrep "^.{$(wc -L<$f)}$" $f
```
[Try it Online!](https://tio.run/##RYxBDoIwFET3nuKL36SlQaNLP7B14w2MJpW2UtKIAYwmTc9eARfuJvPezE32dYym7cCRZ8wIwTmpAv3KBbIFjYQxskLkKk33xLkHXdUtJOjdwW7VYSfsWoWkLNFQoLCYrhqwD0j/f/dOPyH7GGwAz43YXX6ynvvkuvHI3hVkpxwND5gAmhjju5YDSOisstXLta8e7q0zYJWWM5MwzvXo/OvjnPoJyGH5BQ)
Not pretty but at least it works. We write the substrings to files `$f`, then `(e)grep` for longest common line.
[Answer]
# [Red](http://www.red-lang.org), ~~266~~ 174 bytes
```
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
```
[Try it online!](https://tio.run/##ZVDBatwwEL3vVzxcsk0oYdmrG5JjyKWHbW9CFK0txRPkkZFGIf767Xi3NGuKBHp672nmjbLvTwffG7sJ7SlU7szRmtgien6V4QmlxXG3B7fYo7JQNLTAmNIENtKiS9O8m1wWOEEBISK3SIyQsnfdgLph/yE4GqUzHPe3nNjj4RGBuN91rnhUyJ2lgGyyl5oZYrUN4Rv2VlvzAnQ9YkmGe2Wbxp6mTCwIMM3gY0wNmq/n02LzKb37PKsy1m7Qo6cQfPYsjb3y@HGSxaT756/Dy4/nlUq9@qlzUeVPfO0oovBV5SKHFwUW@I7zYMTFcyGhd3/ll4GKfpFfChY4lHq8lEAK@CeuxnirRS7sFXmJvKJGxzNSlalKOQeqk9SEmd34v4/4r211WTCRgtkxz6tXNzecZKvSW91@KaLAbK2L0@B@cx19pk5Tn/4A "Red – Try It Online")
Changed the recursion to iteration and got rid of the sorting.
[Answer]
# [Perl 5](https://www.perl.org/), 87 bytes
```
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(\n.*\1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
```
[Try it online!](https://tio.run/##TVDBasJAEL3vVwzbaKOsiR7EgwRCoYoXD7Y3I7LVTbOSzIbspiXYeOwH9BP7IU03KVgv896895gZJhdFOm0eHper9dnxAxphEAQR0jk4tO1oTXT5AvG5ySqnmFOnH@5pcPFd7xyet04RXCrG2GFXs3rgDd0IvWE08YaD1g33o8murn3geLRJZ/KeyFQ4@@14F1w08xibO0VTQ15INDHQ3mg61vD9@QU9bTczOCmJLoUPoCxcDBjEroUmEWmqyH1X7bHkTRQVycpDQo4yjkUh0HS6yHJTEfL0vFmtl50ij9aTB57esFbXxl7wamGzstAqJpEaFApigYP9wF8EVAxXq82dSm2uTcaxAlWavDTaDitzUyqokGf/rsTOvKEtk5JUHLHqcr0eKtO3k/t32pBtf8fTPOF7LDNRyMOPyo1UqJsRT3E8m80WfoT@Lw "Perl 5 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 106 bytes
```
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
```
[Try it online!](https://tio.run/##VVLBboMwDL3zFRaXJRIgdm0XdpjUqVK1SdtuaFKzNrSpQoJIoOXruzjAuh4w9nvPDyf4xHtud61sXKrNXlwrduWsICtGVKKTM@Nl/p3Z7se6luhEUcoK9ayf8ucVSVOVbFJFFzyzphZkYMWQSb0Xl/eKnOlTTr3Iu6SPdHFexDElm9FOCX1wxySn12XU8xacsO6FW2GBwbaMj0IpEycQP4TkG9ICynjMozLuRTsgW3e7I773sqpEK7SblUEl6sYFGT6fXx/rt9c7Xu59h9xxhfytmCT/AK/1Z5f6gELrPtY@m1TWIYa1F7mjtGC0CH4WOIyX5hvBVPDHTq232reeOuv@k7fak/MZ7qavuR7AdK7pnB3n6hrXGRg0r2dhjQQPE2IIlwEYwt12GML8TTC42Uo9u95XWEgZrLjWw/wZzLaZbZR022ib1bwhF2AFXCYMVSM8ICx6rshAKV1GlWmB4P@X4YbmJaAR7Iy2RolMmQORfmMSkOWjj7ggVUDoCP2tm6VQMMjp8voL "JavaScript (Node.js) – Try It Online")
```
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 15 bytes
```
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
```
[Try it online!](https://tio.run/##S0/MTPz/P/Xhju5Dy9QedS16NH@FVc6hZVaPejptDy17NH/lo472//@jHzXM8UjNycl/1DBXQQHIUYdyYgE "Gaia – Try It Online")
```
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max length
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~165~~ ~~163~~ 87 bytes
*-76 bytes thanks to Nail for the [awesome regexp](https://codegolf.stackexchange.com/a/182199/80745).*
```
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
```
[Try it online!](https://tio.run/##ZZJRa8IwEMff@ymO2ta2s4KvY6JvQxh7cHscG1mNGkmT0iTbivrZXS5Bo1jI5e76@1@S41r5Szu1pZyfkjVMYX@Kkzwh3UZVO8nEMBoeFFcQ57On6ee4LPLxQ5HPpvm4/BB2TYpyXCZFXBGoanJIoSkPSnYaXqh1KKe1horDpIhPxyia5xHYb5TP8xiPlPEI4qFzCut5JyA/tOuRaEy9xX3F1mvaUaEdfU3SptUOxfX2vly8PiNzC7GVlbKacIRC4LirMAiU7pjYIK30cmE9hyqNGYwCqbdMgRTUVVZAQJlvrwa5hstfpw9R0O@M0oEIUSDOj7t/VkNED9Lo1mjl72pabST0gjSebjBN3K3RuEYBGtd/g8a9qXXyu9pMnEvfRhgw5ioSIXp/Fu5Bn6ZC6gyRnckGvnMZ4e2WfAnT0I7VXpVZUQEHSGHvxAkZQUL/Wjs@dGWnMvny6Y4qw7VNZHZY5wQGoFrCtbaNdgDOrmcqJi4FisezMo6Op38 "PowerShell – Try It Online")
Less golfed:
```
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 158 bytes
```
a->{for(int l=a.get(0).length(),i=l,j;i>=0;i--)for(j=0;j<l-i;){var s=a.get(0).substring(j++,j+i);if(a.stream().allMatch(x->x.contains(s)))return s;}return"";}
```
[Try it online!](https://tio.run/##ZVJNj9owEL3zK0apoHZJoj1vAKmXVit1e1h6W60qb3CIU8eOPGO0EcpvpzYBFsTBmo/33njG40bsRNZs/h1U21lH0IQ496R0/q2Y3OUqb0pS1kSw8@9alVBqgQjPQhnYTwBOWSRBweys2kAbMLYmp8z29Q2E2yI/UgF@nMotfimkxUhZpScL1RIOIlvtK@uYMgR6KfKtJPbAcy3NlmrGU7XUaVOo1fKhUFnGI7UJfrPQmSr4ficc4KcM/Tsei7NmPk@bueKFqpjIQ1KKlvFcaP0sqKzZR7b6yEtrKPSODDnnTpJ3BrAYRi9JiuFQHMc4zxamI4mEsDzNB7BPaqm1TVJIvh6dIYULtJOuj0jryzrajaoq6aShG5ZsOzrS4ln/eXn6/fMGV5ugUKXQEf8Mrinj0BFHenkK3jVItUKwRh7lCAIurwS2ggt6LWk80l3y3OJNshWmB@up84Tj/b4jb6E3or0nKnPm3UYxUCp6vTCmvxFOp8bSLGKNn31Bit7r7E3orhZ/jW@lU@VFMIwLi98kfo24rcdxZ/yysnWPJNs8NJ134RWoYskUH2GKUxNqf3dO9JiTHZfOopinUOWi63TPTrDA@KNHkPPx0mESzzCZHP4D "Java (JDK) – Try It Online")
## Credits
* -17 bytes thanks to [Sara J](https://codegolf.stackexchange.com/users/85386/sara-j).
[Answer]
# [Perl 5](https://www.perl.org/), 86 bytes
```
$_=join"\x1",<>;$p=".*\x1.*\\1"x($.-1);say+(sort{length$b-length$a}/(.+)(?=$p)/msg)[0]
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jYrPzNPKabCUEnHxs5apcBWSU8LyAMSMYZKFRoqerqGmtbFiZXaGsX5RSXVOal56SUZKkm6UEZirb6Gnramhr2tSoGmfm5xuma0Qez//0k5iRkKJRmZxQqZxVxQWgEk@C@/oCQzP6/4v66vqZ6BoQEA "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
eolN.U@bZm{s./dQ
```
[Try it online!](https://tio.run/##K6gsyfj/PzU/x08v1CEpKre6WE8/JfD//2iljNScnHwlHQUldTAjFgA "Pyth – Try It Online")
```
m Q # Map Q (parsed input) over the following function (lambda d:
./d # Partitions of d (all substrings)
s # Reduce on + (make one list)
{ # deduplicate
.U # reduce the result on the following lambda, with starting value result[0]
@bZ # lambda b,Z: Intersection between b and Z
# Result so far: all common substrings in random order
o # sort the resulting sets by the following lambda function:
lN # lambda N: len(N)
e # last element of that list
```
] |
[Question]
[
The [Stern-Brocot sequence](https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree) is a Fibonnaci-like sequence which can be constructed as follows:
1. Initialise the sequence with `s(1) = s(2) = 1`
2. Set counter `n = 1`
3. Append `s(n) + s(n+1)` to the sequence
4. Append `s(n+1)` to the sequence
5. Increment `n`, return to step 3
This is equivalent to:
[![s(n) = \begin{cases} 1 & \textrm{if } n = 1 \ s(\frac n 2) & \textrm{if } n \textrm{ is even} \ s(\frac{n-1}2) + s(\frac{n+1}2) & \textrm{otherwise} \end{cases}](https://i.stack.imgur.com/gJzmj.png)](https://i.stack.imgur.com/gJzmj.png)
Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, `1/3` is the 4th rational number in the sequence, but the equivalent numbers `2/6`, `3/9` etc won't appear at all.
**We can define the nth rational number as `r(n) = s(n) / s(n+1)`, where `s(n)` is the nth Stern-Brocot number, as described above.**
Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.
* The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer
* The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)
* Input can be via STDIN, function parameters, or any other reasonable input mechanism
* Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream
* Output must be as a string in the form `a/b`, where `a` and `b` are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input `12`, output should be `2/5`, not `0.4`.
* Standard loopholes are disallowed
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes will win.
**Test cases**
The test cases here are 1-indexed.
```
n r(n)
-- ------
1 1/1
2 1/2
3 2/1
4 1/3
5 3/2
6 2/3
7 3/1
8 1/4
9 4/3
10 3/5
11 5/2
12 2/5
13 5/3
14 3/4
15 4/1
16 1/5
17 5/4
18 4/7
19 7/3
20 3/8
50 7/12
100 7/19
1000 11/39
```
OEIS entry: [A002487](https://oeis.org/A002487)
Excellent Numberphile video discussing the sequence: [Infinite Fractions](https://www.youtube.com/watch?v=DpwUVExX27E)
[Answer]
## CJam (20 bytes)
```
1_{_@_2$%2*-+}ri*'/\
```
[Online demo](http://cjam.aditsu.net/#code=1_%7B_%40_2%24%252*-%2B%7Dri*'%2F%5C&input=49). Note that this is 0-indexed. To make it 1-indexed, replace the initial `1_` by `T1`.
### Dissection
This uses the characterisation due to Moshe Newman that
>
> the fraction `a(n+1)/a(n+2)` can be generated from the previous fraction `a(n)/a(n+1) = x` by `1/(2*floor(x) + 1 - x)`
>
>
>
If `x = s/t` then we get
```
1 / (2 * floor(s/t) + 1 - s/t)
= t / (2 * t * floor(s/t) + t - s)
= t / (2 * (s - s%t) + t - s)
= t / (s + t - 2 * (s % t))
```
Now, if we assume that `s` and `t` are coprime then
```
gcd(t, s + t - 2 * (s % t))
= gcd(t, s - 2 * (s % t))
= gcd(t, -(s % t))
= 1
```
So `a(n+2) = a(n) + a(n+1) - 2 * (a(n) % a(n+1))` works perfectly.
```
1_ e# s=1, t=1
{ e# Loop...
_@_2$%2*-+ e# s, t = t, s + t - 2 * (s % t)
}
ri* e# ...n times
'/\ e# Separate s and t with a /
```
[Answer]
## Haskell, ~~78 77 65~~ 58 bytes
Shamelessly stealing the optimized approach gives us:
```
(s#t)0=show s++'/':show t
(s#t)n=t#(s+t-2*mod s t)$n-1
1#1
```
Thanks to @nimi for golfing a few bytes using an infix function!
(Still) uses 0-based indexing.
---
The old approach:
```
s=(!!)(1:1:f 0)
f n=s n+s(n+1):s(n+1):(f$n+1)
r n=show(s n)++'/':(show.s$n+1)
```
Damn the output format... And indexing operators. EDIT: And precedence.
Fun fact: if heterogenous lists were a thing, the last line could be:
```
r n=show>>=[s!!n,'/',s!!(n+1)]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L‘Hị⁸Sṭ
1Ç¡ṫ-j”/
```
[Try it online!](http://jelly.tryitonline.net/#code=TOKAmEjhu4vigbhT4bmtCjHDh8Kh4bmrLWrigJ0v&input=&args=MTAwMA) or [verify all test cases](http://jelly.tryitonline.net/#code=TOKAmEjhu4vigbhT4bmtCjHDh-KBuMKh4bmrLWrigJ0vCjFyMjA7NTA7MTAwOzEwMDDDh-KCrFk&input=).
### How it works
```
1Ç¡ṫ-j”/ Main link. Argument: n
1 Set the return value to 1.
Ç¡ Apply the helper link n times.
ṫ- Tail -1; extract the last two items.
j”/ Join, separating by a slash.
L‘Hị⁸Sṭ Helper link. Argument: A (array)
L Get the length of A.
‘ Add 1 to compute the next index.
H Halve.
ị⁸ Retrieve the item(s) of A at those indices.
If the index in non-integer, ị floors and ceils the index, then retrieves
the items at both indices.
S Compute the sum of the retrieved item(s).
ṭ Tack; append the result to A.
```
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~34~~ ~~33~~ ~~25~~ 23 bytes
```
XX‚¹GÂ2£DO¸s¦ìì¨}R2£'/ý
```
**Explanation**
```
XX‚ # push [1,1]
¹G } # input-1 times do
 # bifurcate
2£ # take first 2 elements of reversed list
DO¸ # duplicate and sum 1st copy, s(n)+s(n+1)
s¦ # cut away the first element of 2nd copy, s(n)
ìì # prepend both to list
¨ # remove last item in list
R2£ # reverse and take the first 2 elements
'/ý # format output
# implicitly print
```
[Try it online](http://05ab1e.tryitonline.net/#code=WFjigJrCuUfDgjLCo0RPwrhzwqbDrMOswqh9UjLCoycvw70&input=MTAwMA)
Saved 2 bytes thanks to Adnan.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 20 bytes
```
FT+"@:qtPXnosV47]xhh
```
This uses the characterization in terms of binomial coefficients given in [the OEIS page](https://oeis.org/A002487).
The algorithm works in theory for all numbers, but in practice it is limited by MATL's numerical precision, and so it doesn't work for large entries. The result is accurate for inputs up to `20` at least.
[**Try it online!**](http://matl.tryitonline.net/#code=RlQrIkA6cXRQWG5vc1Y0N114aGg&input=MTA)
### Explanation
```
FT+ % Implicitly take input n. Add [0 1] element-wise. Gives [n n+1]
" % For each k in [n n+1]
@:q % Push range [0 1 ... k-1]
tP % Duplicate and flip: push [k-1 ... 1 0]
Xn % Binomial coefficient, element-wise. Gives an array
os % Number of odd entries in that array
V % Convert from number to string
47 % Push 47, which is ASCII for '\'
] % End for each
x % Remove second 47
hh % Concatenate horizontally twice. Automatically transforms 47 into '\'
% Implicitly display
```
[Answer]
# Python 2, ~~85~~ 81 bytes
```
x,s=input(),[1,1]
for i in range(x):s+=s[i]+s[i+1],s[i+1]
print`s[x-1]`+"/"+`s[x]`
```
This submission is 1-indexed.
Using a recursive function, 85 bytes:
```
s=lambda x:int(x<1)or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`
```
If an output like `True/2` is acceptable, here's one at 81 bytes:
```
s=lambda x:x<1 or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
3ẋḶŒpḄċ
’Ç”/⁸Ç
```
[Try it online!](https://tio.run/nexus/jelly#@2/8cFf3wx3bjk4qeLij5Ug316OGmYfbHzXM1X/UuONw@39Dg6BDWw@3n1j3cOdsoKjCiXWHtj5qWgPmzQEK/AcA "Jelly – TIO Nexus")
Ooh, looks like I can beat the accepted answer by @Dennis, and in the same language at that. This works using a formula from OEIS: the number of ways to express (the number minus 1) in hyperbinary (i.e. binary with 0, 1, 2 as digits). Unlike most Jelly programs (which work either as a full program or a function), this one works only as a full program (because it sends part of the output to stdout, and returns the rest; when used as a full program the return value is sent to stdout implicitly, so all the output is in the same place, but this wouldn't work for a function submission).
This version of the program is *very* inefficient. You can create a much faster program that works for all input up to 2ⁿ via placing *n* just after the `ẋ` on the first line; the program has O(*n* × 3ⁿ) performance, so keeping *n* small is fairly important here. The program as written sets *n* equal to the input, which is clearly large enough, but also clearly too large in almost all cases (but hey, it saves bytes).
## Explanation
As usual in my Jelly explanations, text in braces (e.g. `{the input}`) shows something that automatically filled in by Jelly due to missing operands in the original program.
**Helper function** (calculates the *n*th denominator, i.e. the *n*+1th numerator):
```
3ẋḶŒpḄċ
3ẋ 3, repeated a number of times equal to {the argument}
Ḷ Map 3 to [0, 1, 2]
Œp Take the cartesian product of that list
Ḅ Convert binary (or in this case hyperbinary) to a number
ċ Count number of occurrences of {the argument} in the resulting list
```
The first five bytes are basically just generating all possible hyperbinary numbers up to a given length, e.g. with input 3, the output of `Ḷ` is [[0,1,2],[0,1,2],[0,1,2]] so the cartesian product is [[0,0,0],[0,0,1],[0,0,2],[0,1,0],…,[2,2,1],[2,2,2]]. `Ḅ` basically just multiplies the last entry by 1, the penultimate entry by 2, the antepenultimate entry by 4, etc., and then adds; although this is normally used to convert binary to decimal, it can handle the digit 2 just fine, and thus works for hyperbinary too. Then we count the number of times the input appears in the resulting list, in order to get an appropriate entry in the sequence. (Luckily, the numerator and denominator follow the same sequence).
**Main program** (asks for the numerator and denominator, and formats the output):
```
’Ç”/⁸Ç
’Ç Helper function (Ç), run on {the input} minus 1 (‘)
”/ {Output that to stdout}; start again with the constant '/'
⁸Ç {Output that to stdout}; then run the helper function (Ç) on the input (⁸)
```
Somehow I keep writing programs that take almost as many bytes to handle I/O as they do to solve the actual problem…
[Answer]
## JavaScript (ES6), 43 bytes
```
f=(i,n=0,d=1)=>i?f(i-1,d,n+d-n%d*2):n+'/'+d
```
1-indexed; change to `n=1` for 0-indexed. The linked OEIS page has a useful recurrence relation for each term in terms of the previous two terms; I merely reinterpreted it as a recurrence for each fraction in terms of the previous fraction. Unfortunately we don't have inline TeX so you'll just have to paste it onto another site to find out how this formats:
$$ \frac{a}{b} \Rightarrow \frac{b}{a + b - 2(a \bmod b)} $$
[Answer]
# m4, 131 bytes
```
define(s,`ifelse($1,1,1,eval($1%2),0,`s(eval($1/2))',`eval(s(eval(($1-1)/2))+s(eval(($1+1)/2)))')')define(r,`s($1)/s(eval($1+1))')
```
Defines a macro `r` such that `r(n)` evaluates according to the spec. Not really golfed at all, I just coded the formula.
[Answer]
## Python 2, 66 bytes
```
f=lambda n:1/n or f(n/2)+n%2*f(-~n/2)
lambda n:`f(n)`+'/'+`f(n+1)`
```
Uses the recursive formula.
[Answer]
# C (GCC), 79 bytes
Uses 0-based indexing.
```
s(n){return!n?:n%2?s(n/2):s(-~n/2)+s(~-n/2);}r(n){printf("%d/%d",s(n),s(n+1));}
```
[Ideone](https://ideone.com/ETnVZk)
[Answer]
## Actually, 18 bytes
```
11,`│;a%τ@-+`nk'/j
```
[Try it online!](http://actually.tryitonline.net/#code=MTEsYOKUgjthJc-EQC0rYG5rJy9q&input=Ng)
This solution uses [Peter's formula](https://codegolf.stackexchange.com/a/90254/45941) and is likewise 0-indexed. Thanks to Leaky Nun for a byte.
Explanation:
```
11,`│;a%τ@-+`nk'/j
11 push 1, 1
,`│;a%τ@-+`n do the following n times (where n is the input):
stack: [t s]
│ duplicate the entire stack ([t s t s])
; dupe t ([t t s t s])
a invert the stack ([s t s t t])
% s % t ([s%t s t t])
τ multiply by 2 ([2*(s%t) s t t])
@- subtract from s ([s-2*(s%t) s t])
+ add to t ([t+s-2*(s%t) t])
in effect, this is s,t = t,s+t-2*(s%t)
k'/j push as a list, join with "/"
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~32~~ 30 bytes
```
1i:"tt@TF-)sw@)v]tGq)V47bG)Vhh
```
This uses a direct approach: generates enough members of the sequence, picks the two desired ones and formats the output.
[**Try it online!**](http://matl.tryitonline.net/#code=MWk6InR0QFRGLSlzd0Apdl10R3EpVjQ3YkcpVmho&input=MTAw)
[Answer]
# R, 93 bytes
```
f=function(n)ifelse(n<3,1,ifelse(n%%2,f(n/2-1/2)+f(n/2+1/2),f(n/2)))
g=function(n)f(n)/f(n+1)
```
Literally the simplest implementation. Working on golfing it a bit.
[Answer]
# Ruby, 49 bytes
This is 0-indexed and uses Peter Taylor's formula. Golfing suggestions welcome.
```
->n{s=t=1;n.times{s,t=t,s+t-2*(s%t)};"#{s}/#{t}"}
```
[Answer]
## Maple
```
0: do 1/(1+floor(%)-frac(%))od;
```
Uses % which is the ditto operator reevaluating the last expression.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 34+2 = 36 bytes
After seeing Peter Taylor's excellent answer, I re-wrote my test answer (which was an embarrassing 82 bytes, using very clumsy recursion).
```
&01\$n"/"on;
&?!\:@}:{:@+@%2*-&1-:
```
It expects the input to be present on the stack, so +2 bytes for the `-v` flag. [Try it online!](http://fish.tryitonline.net/#code=JjAxXCRuIi8ib247CiY_IVw6QH06ezpAK0AlMiotJjEtOg&input=&args=LXYgMTE)
[Answer]
# Octave, 90 bytes
```
function f(i)S=[1 1];for(j=1:i/2)S=[S S(j)+S(j+1) (j+1)];end;printf("%d/%d",S(i),S(i+1));end
```
[Answer]
# C#, ~~91~~ 90 bytes
```
n=>{Func<int,int>s=_=>_;s=m=>1==m?m:s(m/2)+(0==m%2?0:s(m/2+1));return$"{s(n)}/{s(n+1)}";};
```
Casts to `Func<int, string>`.
This is the recursive implementation.
Ungolfed:
```
n =>
{
Func<int,int> s = _ => _; // s needs to be set to use recursively. _=>_ is the same byte count as null and looks cooler.
s = m =>
1 == m ? m // s(1) = 1
: s(m/2) + (0 == m%2 ? 0 // s(m) = s(m/2) for even
: s(m/2+1)); // s(m) = s(m/2) + s(m/2+1) for odd
return $"{s(n)}/{s(n+1)}";
};
```
Edit: -1 byte. Turns out C# doesn't need a space between `return` and `$` for interpolated strings.
[Answer]
## Python 2, 59 bytes
```
s,t=1,1;exec"s,t=t,s+t-2*(s%t);"*input();print'%d/%d'%(s,t)
```
Uses [Peter's formula](https://codegolf.stackexchange.com/a/90254/45941) and is similarly 0-indexed.
[Try it online](http://ideone.com/fork/o8JVAT)
[Answer]
# J, 29 bytes
```
([,'/',])&":&([:+/2|]!&i.-)>:
```
## Usage
Large values of *n* require a suffix of `x` which denotes the use of extended integers.
```
f =: ([,'/',])&":&([:+/2|]!&i.-)>:
f 1
1/1
f 10
3/5
f 50
7/12
f 100x
7/19
f 1000x
11/39
```
[Answer]
# Mathematica, ~~108~~ ~~106~~ 101 bytes
```
(s={1,1};n=1;a=AppendTo;t=ToString;Do[a[s,s[[n]]+s[[++n]]];a[s,s[[n]]],#];t@s[[n-1]]<>"/"<>t@s[[n]])&
```
[Answer]
# [R](https://www.r-project.org/), 84 bytes
```
function(n,K=c(1,1)){for(i in 1:n)K=c(K,K[i]+K[i+1],K[i+1])
paste0(K[i],"/",K[i+1])}
```
[Try it online!](https://tio.run/##NY1BCsIwEEX3nqJ0NUNHnQhuSnOCHEEKDbWBgE5DEqEinj22iov/Pry/@LEkXdxDxuxnASGjR1CkEF9ujuArL5VqBTdtyFx836xoVE@/wl2wKU8M20T1sf77d7nabA8u2vsEQwLBQScbwu0JS7dfP9oT05lJ8TeMlJBEL1g@ "R – Try It Online")
The [older R implementation](https://codegolf.stackexchange.com/a/90259/67312) doesn't follow the specs, returning a floating point rather than a string, so here's one that does.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 56 bytes (SBCS)
```
{1(⍵{s←⍺⊃⍵⋄t←⍵[n←⍺+1]⋄⍺=⍺⍺:,/⍕¨s'/'t⋄n∇⍵,(s+t),t})1 1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqQ41HvVuri4HMR727HnU1A3mPultKwPyt0XkQcW3DWKAgkGELUtS7y0pH/1Hv1EMritX11UuAMnmPOtqBynU0irVLNHVKajUNFQxrgRYcWvGod7OCoQEA "APL (Dyalog Unicode) – Try It Online")
Inner operator:
```
{ ⍝ ⍺ is counter, ⍺⍺ is input, ⍵ is sequence
s ← ⍺ ⊃ ⍵ ⍝ s is the ⍺th element of ⍵ (1-indexed), i.e. s(n)
⋄t ← ⍵[n←⍺+1] ⍝ t is s(n+1). Also create variable n that holds ⍺+1
⋄⍺ = ⍺⍺: ⍝ If counter equals the n we want to reach
s ÷ t ⍝ Return s(n) / s(n+1)
⋄n ∇ ⍵,(s+t),t ⍝ Otherwise, call itself again with counter incremented
⍝ and the new terms added to the sequence
⍝ ∇ is self reference and , is concatenate
}
```
The outer function just calls the inner one with 1 as the initial value of the counter, `1 1` as the initial sequence, and its right argument as the left operand of the inner operator (n).
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 33 bytes
```
f(n)=if(n,(1+f(n\2)^q=n%2*2-1)^q)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNxXTNPI0bTOBpI6GoTaQijHSjCu0zVM10jLSNQQyNaEKVdLyizTyFGwVDHUUTA10FAqKMvNKgAJKCrp2QAJkjCZULcxwAA)
] |
[Question]
[
**This was inspired by *Problem 13 - Non-Repeating Binary* of [HP CodeWars' recent competition.](http://www.hpcodewars.org/past/cw18/problems/HPCodeWars2015ProblemSet.pdf)**
Let's take a random decimal number, say
```
727429805944311
```
and look at its binary representation:
```
10100101011001011111110011001011101010110111110111
```
Now split that binary representation into subsequences where the digits `0` and `1` alternate.
```
1010 010101 10 0101 1 1 1 1 1 10 01 10 0101 1 1010101 101 1 1 1 101 1 1
```
And convert each subsequence back into decimal.
```
10 21 2 5 1 1 1 1 1 2 1 2 5 1 85 5 1 1 1 5 1 1
```
## The Task
Take a single, positive integer as input and output the sequence of positive integers obtained by the above process.
## Details
* Input and output must be in decimal or unary.
* Numbers in the output must be separated in a sensible, human-readable fashion, and they must be in decimal or unary. No restriction on white space. Valid output styles: `[1,2,3]`, `1 2 3`, `1\n2\n3` where `\n` are literal newlines, etc.
## Test cases
```
Input | Output
0 | 0
1 | 1
2 | 2
3 | 1 1
4 | 2 0
5 | 5
6 | 1 2
7 | 1 1 1
8 | 2 0 0
9 | 2 1
10 | 10
50 | 1 2 2
100 | 1 2 2 0
1000 | 1 1 1 1 10 0 0
10000 | 2 1 1 2 0 2 0 0 0
12914 | 1 2 2 1 1 2 2
371017 | 5 42 10 2 1
```
Additional note: all numbers in the output should be of the form `(2^k-1)/3` or `2*(2^k-1)/3`. That is, `0 1 2 5 10 21, 42, 85, 170, ...`, which is [A000975](http://oeis.org/A000975) in the OEIS.
[Answer]
# Pyth, ~~17~~ 16 bytes
*1 byte thanks to Jakube*
```
iR2cJ.BQx1qVJ+dJ
```
[Demonstration](https://pyth.herokuapp.com/?code=iR2cJ.BQx1qVJ%2BdJ&input=727429805944311&debug=0)
A nice, clever solution. Uses some lesser known features of Pyth, like `x<int><list>` and `c<str><list>`.
```
iR2cJ.BQx1qVJ+dJ
Q = eval(input())
J.BQ Store in J the input in binary.
qV Vectorize equality function over
J+dJ J and J with a leading dummy char, to get the offset right.
This calculates whether each element matches its successor.
x1 Find all of the indexes of 1 (True) in this list.
cJ Chop J at those locations.
iR2 Convert from binary back to base ten and output.
```
[Answer]
# Mathematica, 47 bytes
```
#+##&~Fold~#&/@#~IntegerDigits~2~Split~Unequal&
```
Ungolfed:
```
FromDigits[#,2]&/@Split[IntegerDigits[#,2],Unequal]&
```
`Split[list,f]` splits a list into multiple lists, breaking at the position between `a` and `b` iff `f[a,b]` does not return `True`.
`FromDigits[n,2] => Fold[#+##&,n]` is a neat [tip](https://codegolf.stackexchange.com/a/12922/30688) from alephalpha.
[Answer]
# Python, 86 bytes
Since I got horribly outgolfed in Pyth, lets just do it in Python again.
```
import re
lambda n:[int(s,2)for s in re.sub("(?<=(.))(?=\\1)"," ",bin(n)[2:]).split()]
```
[Try it here!](https://repl.it/BvJY)
## Explanation
We start with converting the input number `n` into a binary string. `bin(n)[2:]` takes care of that. We need to discard the first 2 chars of this string since `bin()` returns the string in the format `0b10101`.
Next we need to identify the borders of the subsequences. This can be done with the regex `(?<=(.))(?=\1)` which matches the zero-length positions in the string which have the same number to the left and right.
The obvious way to get a list of all subsequences would be to use `re.split()` which splits a string on a certain regex. Unfortunately this function does not work for zero-length matches. But luckily `re.sub()` does, so we just replace those zero-length matches with spaces and split the string on those after that.
Then we just have to parse each of those subsequences back into a decimal number with `int(s,2)` and are done.
[Answer]
# Jelly, 12 bytes
```
BI¬-ẋż@BFṣ-Ḅ
```
[Try it online!](http://jelly.tryitonline.net/#code=QknCrC3huovFvEBCRuG5oy3huIQ&input=&args=NzI3NDI5ODA1OTQ0MzEx) or [verify all test cases](http://jelly.tryitonline.net/#code=QknCrC3huovFvEBCRuG5oy3huIQKw4figqzFkuG5mOKCrGrigbc&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTAsIDUwLCAxMDAsIDEwMDAsIDEwMDAwLCAxMjkxNCwgMzcxMDE3).
### How it works
```
BI¬-ẋż@BFṣ-Ḅ Main link. Argument: n
B Convert n to base 2.
I Compute the increments, i.e., the differences of consecutive digits.
¬ Apply logical NOT.
-ẋ Repeat -1 that many times, for the logical NOT of each difference.
[0, 0] / [1, 1] -> 0 -> 1 -> [-1]
[0, 1] / [1, 0] -> 1 / -1 -> 0 -> []
B Yield n in base 2.
ż@ Zip the result to the right with the result to the left.
F Flatten the resulting list of pairs.
ṣ- Split at occurrences of -1.
Ḅ Convert each chunk from base 2 to integer.
```
[Answer]
# Bash + GNU utilities, 51
```
dc -e2o?p|sed -r ':;s/(.)\1/\1 \1/;t'|dc -e2i?f|tac
```
Input taken from STDIN.
* `dc -e2o?p` reads input integer from STDIN and outputs a base 2 string
* `sed -r ':;s/(.)\1/\1 \1/;t'` splits the base 2 string with a space everywhere there are same consecutive digits
* `dc -e2i?f` reads the split binary in one go, putting the each part on the stack, then `f` dumps the whole `dc` stack (output numbers in reverse order) ...
* ... which is corrected by `tac`.
[Answer]
# JavaScript (ES6) 58 ~~62 63~~
**Edit** 1 byte saved thx @ETHproductions
**Edit** 4 bytes saved thx @Neil
```
x=>x.toString(2).replace(/((.)(?!\2))*./g,x=>'0b'+x-0+' ')
```
```
f=x=>x.toString(2).replace(/((.)(?!\2))*./g,x=>'0b'+x-0+' ')
console.log=x=>O.textContent+=x+'\n'
;[
[ 0,'0'],
[ 1,'1'],
[ 2,'2'],
[ 3,'1 1'],
[ 4,'2 0'],
[ 5,'5'],
[ 6,'1 2'],
[ 7,'1 1 1'],
[ 8,'2 0 0'],
[ 9,'2 1'],
[ 10,'10'],
[ 50,'1 2 2'],
[ 100,'1 2 2 0'],
[ 1000,'1 1 1 1 10 0 0'],
[ 10000,'2 1 1 2 0 2 0 0 0'],
[ 12914,'1 2 2 1 1 2 2'],
[371017,'5 42 10 2 1']
].forEach(t=>{
var i=t[0],k=t[1],r=f(i)
console.log(i+' -> '+r+(r.trim()==k.trim() ? ' ok':'ko (should be '+k+')'))
})
```
```
<pre id=O></pre>
```
[Answer]
# Pyth, 26 bytes
```
iR2c:.BQ"(?<=(.))(?=\\1)"d
```
[Try it here!](http://pyth.herokuapp.com/?code=iR2c%3A.BQ%22%28%3F%3C%3D%28.%29%29%28%3F%3D%5C%5C1%29%22d&input=727429805944311&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A50%0A100%0A1000%0A10000%0A12914%0A371017&debug=0)
## Explanation
```
iR2c:.BQ"(?<=(.))(?=\\1)"d # Q = input number
.BQ # Convert input to binary
: "(?<=(.))(?=\\1)"d # insert a whitespace between the subsequences
c # split string on whitespaces
iR2 # convert each subsequence into decimal
```
Since Python's split() function doesn't split on zero-length matches, I have to replace those matches with a space and split the result on that.
[Answer]
# Pyth, ~~22~~ 21 bytes
```
&Qu?q%G2H&
GH+yGHjQ2Z
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%26Qu%3Fq%25G2H%26%0AGH%2ByGHjQ2Z&input=371017&debug=0)
Really a tedious task in Pyth.
### Explanation:
```
&Qu?q%G2H&\nGH+yGHjQ2Z implicit: Q = input number
jQ2 convert Q to base 2
u jQ2Z reduce ^: for each digit H update the variable G=0:
?q%G2H if G%2 == H:
\nG print G
& H then update G with H
+yGH else: update G with 2*G+H
u print the last G also
&Q handle Q=0 special: only print 0 once
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 18 bytes
Code:
```
b2FNð«N«Dð-s:}ð¡)C
```
Explanation:
```
b # Convert input to binary
2F } # Do the following twice ( with N as range variable)
Nð«N« # N + space + N
D # Duplicate this
ð- # Delete spaces from the duplicate string
s # Swap the top two elements
: # Replace the first string with the second
ð¡ # Split on spaces
) # Wrap into an array
C # Convert all element back to decimal
```
[Try it online!](http://05ab1e.tryitonline.net/#code=YjJGTsOwwqtOwqtEw7Atczp9w7DCoSlD&input=MzcxMDE3)
Uses **CP-1252** encoding.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~18~~ 17 bytes
```
YBTyd~Thhfd1wY{ZB
```
[**Try it online!**](http://matl.tryitonline.net/#code=WUJUeWR-VGhoZmQxd1l7WkI&input=MzcxMDE3)
```
YB % input number. Convert to binary string
T % push true value
y % duplicate binary string and push it at the top of the stack
d~ % true for each value that equals the previous one
T % push true value
hh % concatenate: true, indices, true
f % find indices of true values
d % consecutive differences: lenghts of alternating sequences
1wY{ % split binary string according to those lengths
ZB % convert each substring into decimal number
```
[Answer]
## zsh, ~~67~~ ~~63~~ 55 bytes
```
for i in `grep -oP '1?(01)*0?'<<<$[[##2]$1]`;<<<$[2#$i]
```
I don't know why, but this doesn't work in Bash.
Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 8 bytes!
[Answer]
## PHP, ~~171~~ ~~168~~ ~~162~~ ~~160~~ ~~158~~ ~~121~~ ~~120~~ ~~131~~ ~~124~~ ~~118~~ ~~116~~ ~~113~~ 112 bytes
```
function d($i){for(;$d<$l=strlen($b=decbin($i));){$c.=$u=$b[$d];echo$u==$b[++$d]||$d==$l?bindec($c).$c=" ":"";}}
```
**Exploded view**
```
function d($i) {
for ( ; $d < $l = strlen($b = decbin($i)); ) {
$c .= $u = $b[$d];
echo $u == $b[++$d] || $d == $l ? bindec($c) . $c = " "
: "";
}
}
```
Use `d(int)` and you're off, output is an `echo`ed string of `int`s separated by a space.
**Edits:**
**-3:** Moved `$b` definition into `strlen()` call.
**-6:** Removed `$c` instantiation.
**-2:** **Finally** fixed the concatenation issue.
**-2:** No brackets for single-line `for()`.
**-37:** **Total overhaul.** Going with `Array` chunklets instead of repeated `Array`->`String`->`Array` calls.
**-1:** Sneaky `$c` reset.
**+11:** **Bugfix.** Was missing final chunk. No more.
**-7:** Don't need to instantiate `$d` at all? Nice.
**-6:** `return`->`echo`.
**-2:** Crunching `$c`.
**-3:** Ternary, my first love.
**-1:** Sneaky sneaky `$u`.
[Answer]
## Convex 0.2+, 25 bytes
Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found [here](https://github.com/GamrCorps/Convex). Input is an integer into the command line arguments. This uses the **CP-1252** encoding.
```
2bs®(?<=(.))(?=\\1)"ö2fbp
```
Explanation:
```
2bs Convert to binary string
®(?<=(.))(?=\\1)" Regex literal
ö Split string on regex
2fb Convert each split string into decimal integer
p Print resulting array
```
[Answer]
# Java 8, ~~127~~ 119 bytes
```
l->new java.util.ArrayList<Long>(){{for(String s:l.toBinaryString(l).split("(?<=(.))(?=\\1)"))add(l.parseLong(s,2));}};
```
There's probably a better regular expression out there to split the string on. I'm not proficient at regex, but I'll keep experimenting.
-8 bytes thanks to @FryAmTheEggman
[Answer]
# [APL (APL)](https://dyalog.com), ~~21~~ 25 bytes
Now handles 0 as well.
```
{0::0⋄2⊥¨⍵⊂⍨1,2=/⍵}2⊥⍣¯1⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3yU1OT@3IL849VHbhGoDKyuDR90tRo@6lh5a8ah366Oupke9Kwx1jGz1gbxakPij3sWH1hs@6lqEpFUBBAy4UPmGaHwjNL4xGt8EjW@KxjdD45uj8S3Q@JaofEM095mi8g0NUPhALjIfxEXhG1kamgAA "APL (Dyalog Unicode) – Try It Online")
`2⊥⍣¯1⊢` convert to base-2, using as many bits as needed (lit. inverse from-base-2 conversion)
`{`…`}` apply the following anonymous function
`0::` if any error happens:
`0` return 0
`⋄` now try:
`2=/⍵` pairwise equality of the argument (will fail one 0's length-0 binary representation)
`1,` prepend 1
`⍵⊂⍨` use that to partition the argument (begins new section on each 1)
`2⊥¨` convert each from base-2
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 7 bytes
```
¤ò¥ mn2
```
[Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=pPKlIG1uMg==&input=NzI3NDI5ODA1OTQ0MzEx)
---
## Explanation
```
¤ò¥ mn2
:Implicit input of integer U.
¤ :Convert to binary string.
ò¥ :Split to an array by checking for equality.
m :Map over array.
n2 :Convert to base-10 integer.
```
[Answer]
## Python 3, 115 bytes
```
def f(s):
s=bin(s);r=[s[2]]
for i in s[3:]:
if i==r[-1][-1]:r+=[i]
else:r[-1]+=i
return[int(x,2)for x in r]
```
## Explanation
```
def f(s):
s=bin(s) # convert input in binary
r=[s[2]] # initialize the result with the first char after the 'b' in binary string
for i in s[3:]: # loop on other element
if i==r[-1][-1]: # if the last element of the last string equal the current element
r+=[i] # we add the current element in a new string
else:
r[-1]+=i # we add the current element to the last sting
return[int(x,2)for x in r] # convert binary string in integer
```
## Results
```
>>> [print(i,f(i)) for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100, 1000, 10000, 12914, 371017]]
0 [0]
1 [1]
2 [2]
3 [1, 1]
4 [2, 0]
5 [5]
6 [1, 2]
7 [1, 1, 1]
8 [2, 0, 0]
9 [2, 1]
10 [10]
50 [1, 2, 2]
100 [1, 2, 2, 0]
1000 [1, 1, 1, 1, 10, 0, 0]
10000 [2, 1, 1, 2, 0, 2, 0, 0, 0]
12914 [1, 2, 2, 1, 1, 2, 2]
371017 [5, 42, 10, 2, 1]
```
**previous solution (118 bytes)**
```
def f(s):
s=bin(s);r=s[2]
for i in s[3:]:
if i==r[-1]:r+='a'+i
else:r+=i
return[int(x,2)for x in r.split('a')]
```
[Answer]
# Haskell, ~~147~~, 145 bytes
```
x%[]=[x]
x%(y:z)|or.(zipWith(==)<*>tail)$y:x=x:[]%(y:z)|1<2=(y:x)%z
b x|x<2=[x]|1<2=b(div x 2)++[mod x 2]
map(sum.zipWith((*).(2^))[0..]).([]%).b
```
`map(sum.zipWith((*).(2^))[0..]).([]%).b` is an unnamed function that computes the list.
Less golfed:
```
alternating :: Eq a => [a] -> Bool
alternating = or . (zipWith (==) <*> tail)
-- (%) is the partitioning function
(%) :: Eq a => [a] -> [a] -> [[a]]
x % [] = [x]
x % (y:z) | alternating (y : x) = x : [] % (y:z)
| otherwise = (y : x) % z
bits :: Integral t => t -> [t]
bits x | x < 2 = [x]
| otherwise = bits (div x 2) ++ [mod x 2]
unBits :: Num c => [c] -> c
unBits = sum . zipWith ((*) . (2^)) [0..]
f :: Integer -> [Integer]
f = map unBits . ([]%) . bits
```
[Answer]
# Perl, 53 bytes
Includes +1 for `-p`
Run with the number on STDIN
```
perl -p alterbits.pl <<< 371017
```
`alterbits.pl`:
```
$_=sprintf"0b%b",$_;s/(.)\K(?=\1)/ 0b/g;s/\S+/$&/eeg
```
[Answer]
## PowerShell, 103 bytes
```
[regex]::Matches([convert]::ToString($args[0],2),"(01)+0?|(10)+1?|.").Value|%{[convert]::toint32($_,2)}
```
Since I'm horrible at regex, I'm using the same expression as [edc65's answer](https://codegolf.stackexchange.com/a/75344/42963).
Absolutely destroyed by the lengthy .NET calls to do conversion to/from binary, and the .NET call to get the regex matches. Otherwise pretty straightforward. Takes the input `$args[0]`, `convert`s it to binary, feeds it into `Matches`, takes the resultant `.Value`s, pipes them through a loop `|%{...}` and `convert`s those values back to `int`. Output is left on the pipeline and implicitly printed with newlines.
---
### For extra credit - a (mostly) non-regex version at 126 bytes
```
$l,$r=[char[]][convert]::ToString($args[0],2);$l+-join($r|%{(" $_",$_)[$l-bxor$_];$l=$_})-split' '|%{[convert]::toint32($_,2)}
```
We again take input `$args[0]` and `convert` it to binary. We re-cast as a char-array, storing the first character in `$l` and the remaining characters in `$r`. We then send `$r` through a loop `|%{...}` where every iteration we select from either the character prepended with a space or just the character, depending upon the result of a binary xor with `$l`, and then set `$l` equal to the character. This effectively ensures that if we have the same character twice in a row, we prepend a space between them.
The output of the loop is `-join`ed together and appended to the first character `$l`, then `-split` on spaces (which is technically a regex, but I'm not going to count it). We then do the same loop as the regex answer to `convert` and output integers.
[Answer]
# Java 345 bytes
```
package com.ji.golf;
import java.util.regex.*;
public class Decompose {
public static String decompose(long l) {
String o="";
String s=Long.toBinaryString(l);
Matcher m=Pattern.compile("(01)+(0)?|(10)+(1)?|(1)|(0)").matcher(s);
while(m.find()){String c=s.substring(m.start(),m.end());o+=Integer.parseInt(c, 2)+" ";}
return o;
}
}
```
## Test
```
package com.ji.golf;
public class DecompseTest {
public static void main(String[] args) {
String[] inOut = new String[]{
"0,0",
"1,1",
"2,2",
"3,1 1",
"4,2 0",
"5,5",
"6,1 2",
"7,1 1 1",
"8,2 0 0",
"9,2 1",
"10,10",
"50,1 2 2",
"100,1 2 2 0",
"1000,1 1 1 1 10 0 0",
"10000,2 1 1 2 0 2 0 0 0",
"12914,1 2 2 1 1 2 2",
"371017,5 42 10 2 1"
};
for (String s : inOut) {
String[] io = s.split(",");
String result = Decompose.decompose(Long.parseLong(io[0]));
System.out.println("in: " + io[0] + ", reusult: [" + result.trim() + "], validates? " + result.trim().equals(io[1].trim()));
}
}
}
```
## Output
```
in: 0, reusult: [0], validates? true
in: 1, reusult: [1], validates? true
in: 2, reusult: [2], validates? true
in: 3, reusult: [1 1], validates? true
in: 4, reusult: [2 0], validates? true
in: 5, reusult: [5], validates? true
in: 6, reusult: [1 2], validates? true
in: 7, reusult: [1 1 1], validates? true
in: 8, reusult: [2 0 0], validates? true
in: 9, reusult: [2 1], validates? true
in: 10, reusult: [10], validates? true
in: 50, reusult: [1 2 2], validates? true
in: 100, reusult: [1 2 2 0], validates? true
in: 1000, reusult: [1 1 1 1 10 0 0], validates? true
in: 10000, reusult: [2 1 1 2 0 2 0 0 0], validates? true
in: 12914, reusult: [1 2 2 1 1 2 2], validates? true
in: 371017, reusult: [5 42 10 2 1], validates? true
```
[Answer]
# Julia, ~~70~~ 57 bytes
```
n->map(i->parse(Int,i,2),split(bin(n),r"(?<=(.))(?=\1)"))
```
This is an anonymous function that accepts an integer and returns an integer array. To call it, assign it to a variable.
The approach here is similar to DenkerAffe's nice Python [answer](https://codegolf.stackexchange.com/a/75342/20469). We get the binary representation of `n` using `bin(n)`, and split the resulting string at all matches of the regular expression `(?<=(.))(?=\1)`. It's actually a zero-length match; `(?<=(.))` is a positive lookbehind that finds any single character, and `(?=\1)` is a positive lookahead that finds the matched character in the lookbehind. This locates the places where a number is followed by itself in the binary representation. Just `parse` each as an integer in base 2 using `map` and voila!
[Answer]
# C, ~~137~~ 129 bytes
```
main(){unsigned long a,b=scanf("%lu",&a),c=!!a;while(a>=b*2)b*=2;while(b)b/=2,c=c*(~(a^a/2)&b|!b?!printf("%lu\n",c):2)+!!(a&b);}
```
Input and output are on the standard streams.
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
#:#.;.1~1,2=/\#:
```
[Try it online!](https://tio.run/##JchLCoAgFEbhuav4QYiCMK@PTMVW0iySaNIO2vpNanC@wbmYK0qCTFJlRQ@NpkybTEIc@3mjz3XoVmgQDCwcPGYELIggDd@@/vppmkgONpCmwPwC "J – Try It Online")
## Explanation
```
#:#.;.1~1,2=/\#: Input: integer n
#: Convert from decimal to list of binary digits
2 \ For each overlapping sublist of size 2
=/ Reduce using equals
1, Prepend 1
#: Binary digits
;.1~ Partition those binary digits at the 1s in the previous list
#. Convert each partition from a list of binary digits to decimal
```
[Answer]
# q/kdb+, 52 bytes
**Solution:**
```
{2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}
```
**Examples:**
```
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}0
,0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}1
,1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}3
1 1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}8
2 0 0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}10000
2 1 1 2 0 2 0 0 0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}12914
1 2 2 1 1 2 2
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}371017
5 42 10 2 1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}727429805944311
10 21 2 5 1 1 1 1 1 2 1 2 5 1 85 5 1 1 1 5 1 1
```
**Explanation:**
`q` is interpreted right-to-left.
Cast input to binary, trim off leading zeros, find indices where different, invert to get indices where the same, split list on these indices, convert back to base-10. Looks a little heavy compared to the APL solution though...
```
{2 sv'cut[0,where not differ a]a:(63^first where a)_a:0b vs x} / ungolfed solution
{ } / lambda function
cut[ ] / cut a list at indices, cut[indices]list
0b vs x / converts to 64bit binary representation
a: / save as a
_ / drop 'n' elements from a
( ) / evaluate this
first where a / returns first occurance of true in list a
63^ / fill result with 63 if null (to handle input of 0)
a: / save as a, we've stripped off all the left-most 0s
differ a / whether or not item in list a is different to previous
not / the inversion of this result
where / these are the points where we have 00 or 11
0, / add the first index too!
2 sv' / 2 sv converts binary back to base-10, ' for each list
```
[Answer]
# [PHP](https://php.net/), 98 bytes
```
function($x){foreach(str_split(decbin($x))as$c)$o[$p+=$c==$d].=$d=$c;return array_map(bindec,$o);}
```
[Try it online!](https://tio.run/##TVFPa4MwFD@bT/EoOSiTNUl1VpzsNNhhsN67Is7G6dhMSFLYKP3sLkZTSiB57/cvj0R2cnx8kp1EiCslVKW4FMr0w2dIogIhbLg2GkrYoyBjWcLyLUnzJNlQGsN6DZQAo8AgBXpdDDyyTa@EO1FAnIugYLGjgLmCoWAzIxOWzNikS12ZouBhoa0y88pJu/XaSZ0vjcUpWQa0GcR7JzclN60bhVyRZZE5bSKIT3R6Ml/kSJbT5CaI@vxNRgmdR0whYe6J7ECH6TXbcmxPQ2N6MYT4Nzq3QvG66UJtVKXld2/CI28@ekdGtcZNhMUey7sSN2WJj4d7u9m6UNyc1AC1UvVf9VPL0HqsM8YiKi5jgXwuLP9Xa1tBBGcEwJtO2C6G1btZxfClxVDxoRFHbuVtOAujGHYvu@r57bVAl/Ef "PHP – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
mḋġ≠ḋ
```
[Try it online!](https://tio.run/##yygtzv7/P/fhju4jCx91LgDS////NzcyNzGytDAwtTQxMTY0BAA "Husk – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
BI¬0;œṗBḄ
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//QknCrDA7xZPhuZdC4biE/8OHxZLhuZj//zcyNzQyOTgwNTk0NDMxMQ "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~49~~ 48 bytes
-1 byte thanks to [Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an)
Uses the regexp from [edc65’s JavaScript answer](https://codegolf.stackexchange.com/a/75344/11261).
```
->n{("%b"%n).scan(/((.)(?!\2))*./){p $&.to_i 2}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3DXTt8qo1lFSTlFTzNPWKkxPzNPQ1NPQ0NewVY4w0NbX09DWrCxRU1PRK8uMzFYxqayH6thQouEWbG5mbGFlaGJhampgYGxrGQqQWLIDQAA)
[Answer]
# PHP, 147
```
$b=decbin($argv[1]);$a=[$t=$b[0]];$k=0;for($i=1;$i<strlen($b);$i++){$v=$b[$i];if($v==$t)$k++;$t=$v;$a[$k].=$v;}foreach($a as$c)echo bindec($c).' ';
```
Need to put extra space at last of output as their are no restriction. Notices are displayed for short coding.
Ungolfed version
```
$n=$argv[1];
$b=decbin($n);
$l=strlen($b);
$t=$b[0];
$a=[0=>$t];$k=0;
for($i=1;$i<$l;$i++){
$v=$b[$i];
if($v==$t){
$k++;
}
$t=$v;$a[$k].=$v;
}
foreach($a as $c){
echo bindec($c).' ';
}
```
] |
[Question]
[
Inspired by @emanresu A's [*Is it a fibonacci-like sequence?*](https://codegolf.stackexchange.com/q/242935/9288) Make sure to upvote that challenge as well!
We say a sequence is Fibonacci-like, if, starting from the third term (\$1\$-indexed), each term is the sum of the previous two terms. For example, \$3, 4, 7, 11, 18, 29, 47, 76, 123, 199\cdots\$ is a Fibonacci-like sequence that starts with \$3, 4\$.
Similarly, for any positive integer \$n\$, we say a sequence is \$n\$-bonacci-like, if, starting from the \$n+1\$ term (\$1\$-indexed), each term is the sum of the previous \$n\$ terms. For example, \$2, 4, 5, 11, 20, 36, 67, 123, 226, 416\cdots\$ is a \$3\$-bonacci-like sequence that starts with \$2, 4, 5\$, while \$1, 2, 4, 7, 8, 22, 43, 84, 164, 321\cdots\$ is a \$5\$-bonacci-like sequence that starts with \$1, 2, 4, 7, 8\$.
In particular, constant sequences (sequences where every item are the same) are \$1\$-bonacci-like.
## Task
Given a non-empty list of positive integers, output the smallest \$n\$ such that it could be part of some \$n\$-bonacci-like sequence. You may assume that the input is (non-strictly) increasing.
Note that a list with length \$n\$ is always a part of some \$n\$-bonacci-like sequence.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Testcases
```
[3] -> 1
[2, 2, 2] -> 1
[1, 2, 2] -> 3
[2, 3, 4, 7] -> 4
[1, 3, 4, 7, 11, 18] -> 2
[1, 1, 1, 1, 1, 1, 6] -> 6
[2, 4, 5, 11, 20, 36, 67, 123, 226, 416] -> 3
[1, 2, 4, 7, 8, 22, 43, 84, 164, 321] -> 5
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -> 10
```
[Answer]
# [R](https://www.r-project.org/), ~~91~~ ~~78~~ 77 bytes
*Edit: -1 byte thanks to Giuseppe*
```
function(x){while(any((rowSums(matrix(c(0,x),sum(x|1),T))-x)[0:-T]))T=T+1;+T}
```
[Try it online!](https://tio.run/##bZDRisIwEEXf/YqALxlMIZPUbHel@xObN/GhFsXCNoVqaWT127tTakSjEAIz9547k7SD2zauKMsqH/adK09V47iHv/5Q/e544c6ct03/09VHXhentvK85FJ4EMeu5v6CICxA4mEtvxK7AbC5XeBqYa/3XAI0AJuz5Jvh7KGrBBvPWw2fNR1xWrBUsI8gpxF6kwVDKjALNhXZomOCz0TTKGs5ZSlJ4YasY7aiMUpRlaJ5u@j0iGmTbPRSQUxGHTR0aYWBW75yOgw2IeCTOHn/Ljkb/gE "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~14~~ ~~12~~ 10 bytes
```
?lṠṪ?nȯ⁼)ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiP2zhuaDhuao/bsiv4oG8KeG5hSIsIiIsIlszXVxuWzIsIDIsIDJdXG5bMSwgMiwgMl1cblsyLCAzLCA0LCA3XVxuWzEsIDMsIDQsIDcsIDExLCAxOF1cblsxLCAxLCAxLCAxLCAxLCAxLCA2XVxuWzIsIDQsIDUsIDExLCAyMCwgMzYsIDY3LCAxMjMsIDIyNiwgNDE2XVxuWzEsIDIsIDQsIDcsIDgsIDIyLCA0MywgODQsIDE2NCwgMzIxXVxuWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwXSJd)
Man this new "lambda to newline" thing is cool.
*-2 thanks to @emanresuA*
## Explained
```
?lṠṪ?nȯ⁼)ṅ
)ṅ # Get the first positive integer n where:
Ṡ # the sums of all
?l # overlapping windows of the input of length n
Ṫ # with the tail removed
⁼ # exactly equals
?nȯ # input[n:]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 25 bytes
```
f"G1@&l2&Y+3L)G@QJh)=A?@.
```
[Try it online!](https://tio.run/##XY3BCsIwEETv@YrBQ6EYarKpsR6kFYSCiCB40JaAXkSh3nro38cNTSkIS7Kz@2b2@@w7/8AHfXNGiSGDg38tal0lHSX3pTmldXU5vtPdvqwy7xxuBzQDrs63xkG0JBEqtHpu@TcSucQmLqKS0Cx0Ead/ZaOVyfVIkmKr5U1wEocQscq1ne@NsUVYsWCk4Im2/BjSM2amWDvxW8YUA2qlhBA/ "MATL – Try It Online")
Generalization of the convolution method from my [fibonacci-like sequence answer](https://codegolf.stackexchange.com/a/243026/8774).
---
*Previous*
### [MATL](https://github.com/lmendo/MATL), 30 bytes
```
f"Gn@XH-t:"G@@H+&:)J&)s=-]~?@.
```
[Try it online!](https://tio.run/##XY0/C8IwEMX3fIpHh0KxrflTYy1IMwgtDk4O0hLQRRDUxQ6d/OrxQlMKwpHcu/u9d6/b8HRXPDB0J9QYc1i4e9S8zaXNhipqjGlXcZUc4@Szz@y3NrmzFpcDuhFn63plwXqZwpdvxdLSr1IUKbZhEVQKQUKUYfpXOliJ3Eyk5GTVtPFOSSFSkiqEXu5NsaVfkSCkpInQ9CgpFkzNsXrmd4RxAviaM8Z@ "MATL – Try It Online")
[Answer]
# Python3, 102 bytes:
```
lambda x,c=0:(v(x,c)and c)or(x and f(x,c+1))
v=lambda x,i:len(x)<=i or(sum(x[:i])==x[i]and v(x[1:],i))
```
[Try it online!](https://tio.run/##XZDdboQgEIWv61NMvFnI0o2g61pT@gh9Adc0uIspiX8Ra@zT24ENe9GEEGbOd84A0@/yPQ5pMc17K697p/rmrmBjN5mUZCV4oGq4w42OM9nAHVvXPHJKo1U@cVN2eiAbfZcGkLQ/Pdmq0tRUyq0ytfNhWMXLmhlKdyvjOI6qtIbXD@BRJRi4FUrOIGWQMbgw4FjwwivCK/9W7qXcZ6Dj/HCIBCNyVF2CwDAhsMr4g059kAgjCidjgViBHZ7jlgru0XNA0xCfB88bosnjykmgRMh/Oi6@k0XuwaafxnkBZZeoHWcwYAZoTbfomXyOg2ZgT3bqzEIO1@FAaRm9KNaAhF5NBE0nlPSsui@9qo6BCbAbgDjS1mrMb4nCf2/2Pw)
[Answer]
# [Dyalog APL](https://www.dyalog.com/), ~~15~~ 13 bytes
-2 thanks to @FrownyFrog. (Since the input is non-decreasing, `⍋` can be used instead of `⍳∘≢` to save 2 bytes.)
```
⊃∘⍸⍋(⊃↓⍷+/)¨⊂
```
[Try it online!](https://tio.run/##RUw7CsJAEO09xSsVDWZm1nE9TohEhIBCKluFIJGAYOMRvIHWHmUuEneXgLzizfvMK451tj0V9WGXlXXRNPtyGCpr79Zd7Pq0/mP9bRpF@7D@PV/Ovi/rzqGDhUwqcERgGpkhcFgnJ10gAvmk/9DUdFjFlHOIQkOTBcwKRzouxn8fPDiBdyB1EKYxlDSgqbIB5T8)
Taking the sequence `1 1 2 3 5` as an example:
```
⍋( )¨⊂ For each n from 1 to the length of the sequence, 1 2 ...
↓ is the sequence with the first n terms removed 1 2 3 5 2 3 5 ...
⍷ a subsequence of
+/ the sums of each n-sized window in the sequence 1 1 2 3 5 2 3 5 8 ...
⊃ at the first position? no yes ...
⊃∘⍸ What is the first index where this is true? 2
```
[Answer]
# [Factor](https://factorcode.org/) + `lists.lazy math.unicode`, 68 bytes
```
[ 1 lfrom [ dupd clump [ Σ ] map 1 head* tail? ] with lfilter car ]
```
[Try it online!](https://tio.run/##jZG9TsMwFIX3PMVhRSKKf2oCSDAiFhbEVHWwErexcBLjOEKlytPwPrxScBwUOlDEvZOvv3PusbyVhW/d@Pz08Hh/DaM736VGvu/xolyjDHau7a1udqilr9K@0UVbKnTqtVdNobpZAeuU93vrdONxkySHBKEOYBjwV53h4hbkG6axh//BJHhzXIIQkPwXUYTpAv@0OAWLJQbHavKlGZiACDsoA6UCnEziCLPFmcYYeQDAGXIOIjgYJfOaCK@OYBbdRZRcgWTHaeYHZsmQjOsAm61ra6xR9rZEYfrahsPnBzbhK2y4r5Qsz@GlNndh9qZ9FSTaeOVQSIfNOGHp@AU "Factor – Try It Online")
## Explanation
Find the first positive integer whose sums of clumps of the input, sans the last element, is the tail end of the input.
`1 lfrom [ ... ] with lfilter car` Find the first positive integer where...
```
! { 2 4 5 11 20 36 67 123 226 416 } 3 (for example)
dupd ! { 2 4 5 11 20 36 67 123 226 416 } { 2 4 5 11 20 36 67 123 226 416 } 3
clump ! { 2 4 5 11 20 36 67 123 226 416 } {
{ 2 4 5 }
{ 4 5 11 }
{ 5 11 20 }
{ 11 20 36 }
{ 20 36 67 }
{ 36 67 123 }
{ 67 123 226 }
{ 123 226 416 }
}
[ Σ ] map ! { 2 4 5 11 20 36 67 123 226 416 } { 11 20 36 67 123 226 416 765 }
1 head* ! { 2 4 5 11 20 36 67 123 226 416 } { 11 20 36 67 123 226 416 }
tail? ! t
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 76 bytes
```
f=lambda n,i=1:i*all(E==sum(n[I:I+i])for I,E in enumerate(n[i:]))or f(n,i+1)
```
[Try it online!](https://tio.run/##XYyxDsIgFEV3v4IR7BukaG1IGDvwDU0HjBBJ4JUgHfx6JHFQm7vdc89Nr/JYUYwp1@pUMPF2NwTBKy790YRAJ6WeW6Q4a6k7vzC3ZqJhIh6JxS3abIpt1MuFsYYcbXLHWU3ZY6GOzj20NHj4ac5wAc6hP4EY/hCHb4adJJp23a0/1/UN "Python 3.8 (pre-release) – Try It Online")
This is a recursive function that increments `i` until the conditions are met with that `i`.
[Answer]
# JavaScript (ES6), ~~65~~ 64 bytes
*Saved 1 byte thanks to @tsh*
```
f=(a,w)=>a.every((v,i)=>s=i<w|s==v&&s+v-~~a[i-w],s=0)?w:f(a,-~w)
```
[Try it online!](https://tio.run/##nZDRCsIgFIbvewqvhpJbU5utyHqQ4YWsLRbRYoYSxF59nRHrYmwQiQi/@J3/w4txxuZNdX@Et/pUdF2psKGeqIOJClc0T4wdrSBaVe39yyrlgsAuXdi2JqtCr6lVMTn6XQlY2HrS5fXN1tciutZnXOJMaPTLIgStVogtRjSnqN/6P5pRJChaU7ShiEFgqZ6n@QQ92lLP0nLCHIqTTzGPwUTCgF6EgxPnkNZM6g8tJrr5YJ72zyEAlsINk3AIzvS3O5mmxWAghzFboGM9/rW4ewM "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā.Δ„üÿ.VO¨Å¿
```
Straight-forward modification of [my 5-bytes inversed approach from the related challenge](https://codegolf.stackexchange.com/a/242947/52210).
[Try it online](https://tio.run/##yy9OTMpM/f//SKPeuSmPGuYd3nN4v16Y/6EVh1sP7f//P9pQx0jHRMdcx0LHCMgw1rEw0TE0M9ExNjKMBQA) or [verify all test cases](https://tio.run/##XY09CsJAEIX7PcUglo/o/rhGCFppm84mWESzkIAYUcFK0EIPINbWHkIQjLWHyEVisgYEmeLNvPnmzTRcx8Us3FCfZmlknHQdThNDnkdDf8QGDcpPZ2oMitfBeV/y/TW7Zw9n7D9v2fH5KHZgFca2cTI3tDJhRMmCRSkjaqXLTeubVsvfA4@all2YIpATFgiUVSqvVUBCoWsd24FzcNfOv9KWVOhUW9GG1NAlKSSE0FBc14nVvVt6UBKuAtcKUvB6KW2AtkgPvD1hHw).
**Explanation:**
```
ā # Push a list in the range [1, input-length]
.Δ # Pop and find the first which is truthy for:
„üÿ # Push string "üÿ", where the `ÿ` is automatically replaced with
# the integer using string interpolation
.V # Execute it as 05AB1E code
# (`üN` creates all overlapping lists of size `N`)
O # Sum each inner overlapping list
¨ # Remove the last item
Å¿ # Check if the (implicit) input-list ends with this sublist
# (after which the found result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
g n(h:t)l|t==init l=n|1>0=g(n+1)t$zipWith(+)t l
f l=g 1l l
```
[Try it online!](https://tio.run/##jVBNi8IwEL3nV8zBQ4td6CQ11oX0b3gQD8JqG4xZcXNa/O/dF2pxtQGFUHhfM33T7X6Oe@f6viWfdZ8hd9dgjPU2kDP@yk1p2szPOQ@zX3te29Bl8xyaOEBviR25/rSzngx9fQs6X6wPNKMDbdSWHrAsKL4nlpMsKFVQVdByar8JBTEA11PD09PT2cgvhrwsMVDDFOdJjJYSqGKd/M1hbx1dAHDXYFjjoyQnE2pcpsfoColyS328z0dDLO6HGSD/g0o8nAJMJZI3gCJFujwkLd5uPSx9qy6sC/GqZ@xU/gE "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~59~~ 58 bytes
```
->l{1.step.find{|a|l.each_cons(a+1).all?{|*h,g|g==h.sum}}}
```
[Try it online!](https://tio.run/##XVDdasIwFL7vU@RSXYw9Sc06sA58gT1ADCNqa4VYi52D2fTZ62lqYAiHwPd7klxvu7@@yPr52rbAmp@8ZsWpOrTOOMtysy@/95eqmZg3mDJj7WfrZiU9umOWlay5nbuu61erzdeG2VOVN@xs6tZZVxN1z/JfYydWLbaKzbZ6oae0UHetu0gJTeZrApHilAwTIPyDwquCkoSSd88k3vBkKAEEkHqFe@VlpJekr8HEckzwGCskqkMDxzLOESUgw9LxDuOKdJARoC1FBiQegoO3LoNVhHoZMh9ojcc3xRH@Tf8A "Ruby – Try It Online")
### Let's check:
This exploits a couple of ruby-specific shortcuts to achieve the final result.
```
->l{1.step.find{|a|
```
This is easy: starting from 1, repeat until we find the right number.
```
l.each_cons(a+1).all?{|*h,g|
```
Take every possible subarray of length a+1 and check.
```
g==h.sum}}}
```
Is the last element the sum of all other elements?
So, what happens if no match is found?
After the last check, when a+1 is the length of the array, and `each_cons` returns the whole array, we try to get all subarray of length a+2 (length of the whole array plus 1), the list is empty, and that satisfies the `all?` check, so if no answer is found, the answer is the length of the array.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 12.5 bytes
```
/|,~==<*~$.`'.`,$>$_+$>@_
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWO_VrdOpsbW206lT0EtT1EnRU7FTitVXsHOIh8lBlN3WilaKNdBRMdBRMdRQMDXUUjAx0FIzNdBTMzIF8I2OggBGQZ2JoFqsUC9UEAA) / [All testcases](https://ato.pxeger.com/run?1=RU5BCsJADLz3FXNYELSuTbLGldriT1oKCkLxot6kPsRLD4pv8Cn-xu1WkIEMk5kJub-Oh6Zpd6f-YfPcPC_n_dy_F9e0K4rNtDO2ntg6NaWpZqbcVqPf_-hzk4QRkFCcDIHDKqjIIAL5oP7QkHFYDg5nEIWGFAuYFY403hmaPmzgBN6B1EGYoiWxrDGwBmXjH18)
```
/|,~==<*~$.`'.`,$>$_+$>@_
/|,~ Find first number n such that
== equals
<*~ take all except the last
$ n items of
. for each row of
`' transpose
. for each i in
`, range from 0 to (excluding)
$ n
> drop the first
$ i items of
_ input
+ sum of
$ the row
> drop the first
@ n items of
_ input
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@ãX mx ¯J eUtX}a
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QONYIG14IK9KIGVVdFh9YQ&input=WzEsIDEsIDIsIDMsIDUsIDhd)
Port of [@lyxal's Vyxal answer.](https://codegolf.stackexchange.com/a/243479/108687)
Explanation:
```
@ }a # find the first positive integer X where:
ãX # all overlapped sections of length X
mx # sum each
¯J # remove the last item
e # is this list equal to
UtX # the last X elements of the input list?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
I⌕E⊕Lθ⬤θ∨‹μι⁼Σ✂θ⁻μιμ¹λ¹
```
[Try it online!](https://tio.run/##PYvBCsIwEER/JccNrIe0ooInEQXBotBj6SGkwQY20Sapvx83Fy87bx6zZtbRvDWV8owuZDjrlOHqwgSd/sAtmGi9DdlOcLfhlWdYpERxIoIFxSOyTQk8Csf2sqyaEvSrh56csXXSubD@BxyqvpOUNZjlsZRhUCgaFFsUexQH5lpaRjZqx6dt1DiWzZd@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
L Length
⊕ Incremented
E Map over implicit range
θ Input array
⬤ All elements satisfy
μ Current index
‹ Is less than
ι Outer value
∨ Logical Or
θ Input array
✂ ¹ Every element from
μ Current index
⁻ Minus
ι Outer value
μ To current index
Σ Take the sum
⁼ Equals
λ Current element
⌕ Find first index of
¹ Literal integer `1`
I Cast to string
Implicitly print
```
In Charcoal, the `Sum` of an empty list is `None`, so the test for a 0-binacci-like sequence always fails.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+⁹\Ṗ;@ḣʋƑⱮJTḢ
```
**[Try it online!](https://tio.run/##y0rNyan8/1/7UePOmIc7p1k7PNyx@FT3sYmPNq7zCnm4Y9H///@jDXUUjHQUTHQUzHUULIBsEMcYyASKGJoBCWMjw1gA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/1/7UePOmIc7p1k7PNyx@FT3sYmPNq7zCnm4Y9H/w@2Pmtb8/x8dbRzLpRNtpKMAQiCmIYIJpI11FEx0FMyhElCejoIhkGNoARVFQ2ZQrUCVphCVRgZArWZAGZBOI6AhRkZAnomhGcI@iLEWICkgB6jEAihiaAYkjI0MEcqMYcaawdRbApUZxHLFAgA "Jelly – Try It Online").
### How?
```
+⁹\Ṗ;@ḣʋƑⱮJTḢ - Link: list of integers, A
J - range of length of A -> [1,2,3,...,length(A)]
Ɱ - map (for L in [1,2,3,...,length(A)]) with:
Ƒ - is A invariant under?:
ʋ - last four links as a dyad - f(A, L)
⁹\ - L-wise overlapping cumulative reduce A with:
+ - addition
Ṗ - remove the final value
ḣ - head A to index L
;@ - concatenate -> first L terms of A then summed terms
T - truthy (1-indexed) indices
Ḣ - head
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
|L¹V€ṫ¹mhTm∫ṫ
```
[Try it online!](https://tio.run/##RUw5DgIxEPuQi52DIfyBEtFE6VdCqRAdDVvxl@UDafcn5CMhO4qEXNhjezw/7reW6/Jqz/NWrnX5fMu6lTxfcn2vXbfWYpSEyOjoTIMZAsXRHVcgAgW//zBvKg57yhPEYL3JAmaDko3F/T90DyoICjKFMI1QfMC8cgJNKf0A "Husk – Try It Online")
```
m ṫ # for each of the tails of the input
∫ # get the cumulative sums,
T # transpose this list-of-lists,
mh # and remove the last element of each;
V€ # now check if this is one of
ṫ¹ # the tails of the input
# (and output the index if it is)
|L¹ # otherwise, output the length of the input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes
```
1//.a_/;MovingMap[Tr,#,a]!=2#~Drop~a:>a+1&
```
[Try it online!](https://tio.run/##RYy7CsJAFET7/IUspHE0ubvrGhXFwlZQtJMgFzGaIg9CtAnJr695EGSa4cxhEi7fz4TL@ME22lryvDnfvc0x@8bp68j57VpAgMPJVormUGR5w@sdT8m150/8LPenIk7Lm5jtor0I3eby4LSpnErVcCqJNl2hsUgoaCwH1lcQgYIB/GMGWWPR7dKHMjCtKxWkNNBkxtvuImghtEKgQUZDSRpX1V@Y3lmB/Nqp7Q8 "Wolfram Language (Mathematica) – Try It Online")
Uses the check from [this answer](https://codegolf.stackexchange.com/a/243005/81203) to the challenge that inspired this one.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
fqsM.:PQT>Q
```
[Try it online!](https://tio.run/##K6gsyfj/P62w2FfPKiAwxC7w//9oQx0FIx0FEx0Fcx0FCyAbxDEGMoEihmZAwtjIMBYA "Pyth – Try It Online")
### Explanation
```
fqsM.:PQT>QT # implicitly add T
# implicitly assign Q = eval(input())
f # return the first integer which satisfies lambda T
>QT # all but the first T elements of Q
q # is equal to
sM # map to their sums
.: T # all sublists of length T of
PQ # all but the last element of Q
```
[Answer]
# [Julia 1.0](http://julialang.org/), 56 bytes
```
\(L,l=[0L])=sum(l)!=L&&1+L[2:end]\(l=[l;[L]];pop!.(l);l)
```
[Try it online!](https://tio.run/##XY9BbsMgEEX3OcUkiwhUGhnsEKeWcwL3BJgFUahERR1kO1Vv7w4QS1XRCPHn/fnA58M7w3@WpScd860qOk3b6fFFPN223X7PXzol3uxw0z1B7BvVad2Ee9ge0NJ4unzcR/BusOAGGK25xfNE6AZwGXaFFqbg3Uxin8EOXi@we1Jk9tt48m5ncwhmnCwxNLMwumH2A1Gm0dBeoE8E37GoUscMvlGCQaxV8j@yTLRkUDE4pU6VDM8OA46C14mIRP6VTEimGJw45glRYIREGhMEhgmBquJyvTS/IV9RR4wCbTV2uMStFDxZj6u1XOPlOnNGa5H/VPwC "Julia 1.0 – Try It Online")
recursive function. At step `n`, `l` stores the `n` first sub-lists of length `length(L)-n` and `L` is the last one. We iterate until `sum(l)==L`
[Answer]
# [Raku](https://raku.org/), 53 bytes
```
{first {none .rotor($^n+1=>-$n).map:{[R-] $_}},1..$_}
```
[Try it online!](https://tio.run/##RYzBCoMwGINfJUgZG9Pi33adG@pD7Do28WBhMKtULyI@u6uKjBwSvoS0lfvquR5wMMjm0Xxc12O0ja3AXdM37sje9kxZHjF74nXZ3sfnI3qBFdMUEufe564cELACWY7RLE0A0zikMg@RCngtgfYgIKFw3dgaQQRKNvCX3sYKl6UXMaSG9lshIYSGIr3fLheJh1ASiQJpBSlob@V6odfNDRTn8w8 "Perl 6 – Try It Online")
* `first { ... }, 1 .. $_` returns the first number from 1 up to the size of the input list for which the brace-delimited anonymous function returns a true result. Within that function, `$^n`/`$n` is the number being tested. `$_` continues to refer to the input parameter to the outer function.
* `.rotor($^n + 1 => -$n)` produces a moving window of size `$n + 1` across the input list. For example, if the input list is `1, 3, 4, 7, 11, 18` and we're testing whether the list is 2-bonacci-like, the rotor method returns a list of the lists `1, 3, 4`, `3, 4, 7`, `4, 7, 11`, and `7, 11, 18`.
* `.map: { [R-] $_ }` reduces each of those lists with the reversed subtraction operator `R-`. (`a R- b` means `b - a`.) Because the regular subtraction operator `-` is left-associative, the reversed subtraction operator is right-associative, and so to continue the above example, it produces the numbers `4 - 3 - 1`, `7 - 4 - 3`, `11 - 7 - 4`, and `18 - 11 - 7`.
* Finally, `none` returns a truthy result if none of the reduced lists has a truthy value; that is, if all of them are zero.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 123 bytes
The function takes an array of ints for `a` and its length for `z`.
```
B(a,z,M,b,v,t,L)int*a;{int*c,*p;for(M=b=z;--b;M=v?M:b)for(c=a+z,v=0;c-b-a;v|=t)for(t=*--c,p=c-1,L=b;L--;)t-=*p--;return M;}
```
[Try it online!](https://tio.run/##bVJdb4IwFH3nV9y4mIDeLhQdc6t1yZ7lFzgfoLANszED6BIdv93dUqsO1xTae3rOPbcfir0pdTg8uzHuMMIEt1jj3MuLehCLvR4UDtbi9at0I5nInWAsEZHcPkWPiadRJePhDrfSF4olLBbbH1m3C7UcMKZwLRXjOJeJmDMmvJrJwZomZVZvygIi0Rxu8kJ9bNIMplWd5l@37zPnDMVVlZW1xqgW@IzzwvWcvQPUNKDiKqsWywX3lyBb1Ky1s1GD5yBA0P0S4tcQxSOEMcJ9h3hEETgFfNJZ7fSwk5KUd0YZ@JQqJIbOFFDSIKBozMPruozdRFMoIOqEEB7SbxTwa/rI2oRW90B0v2l5jXBOR/aRFXRiOpJ2Z0ZrhNy3H4msJi6q76zUMmn3azRBK9NBu0PSgHGiFwCuluYk8QUNU3igYTj0Otd0zk/MZ9fcaL5EU2i@9I6167Yuif3q9hY9T5zAk9XKWK3I6qgFBpwAa9pN008RegjWcrH616yfUp4Z9NOX4pJ8YUHFmh1cVHWamBfs2iMkhZR/6Y3jNIdf "C (gcc) – Try It Online")
] |
[Question]
[
This is the Grid Game:
[![Example game board](https://i.stack.imgur.com/uU3ho.png)](https://i.stack.imgur.com/uU3ho.png)
It's a game based on cellular automata, where the aim is to remove all of the pieces belonging to your opponent.
How it works:
* There are two kinds of piece in the game, cities and walkers.
* Each player starts with one city (marked with C and a number, which is it's health), which will regularly send out walkers (marked with a number, initially the number 1) in a given direction.
* The player can change the direction of all of their walkers to be north, south, east or west at any time.
* When walkers can't go any further, they will stay still and can be joined by other walkers, increasing their number.
* When 10 or more walkers join up, they become another city. All new cities have 10 health.
* When walkers meet walkers or cities belonging to the opponent, they deal damage to the opponent equal to their number, and take damage equal to the opponent's number.
* Damage is dealt to all adjacent opponent pieces.
* There is no way to replenish the health of a city.
* The game ends when either player has no pieces remaining, or when a clear stale-mate is reached.
Because this question is already very long, I've attempted to write a more detailed description of the game, addressing specific queries about it in this [wiki page](https://github.com/AJFaraday/grid_game/wiki/Extra-game-details-(tournament-conditions)).
## The Challenge
To write a bot to play Grid Game, and defeat as many rival bots as possible.
* A bot is some code which will be run on each turn of the game.
* It can only be JavaScript, sorry.
* The size of the code is immaterial.
* An object named `api` will be provided as an interface to the player from your bot.
* In this iteration of the challenge, there is no way for your bot to know what it's opponent is doing. The challenge is to write a proactive (not reactive) strategy.
Forbidden:
* Interacting with GridGame except via the documented api methods.
## The API
* **api.turn()** - Returns the numbered turn the game is on.
* **api.towardsX()** - Aim your walkers towards the opponent on the East-West axis.
* **api.towardsY()** - Aim your walkers towards the opponent on the North-South axis.
* **api.awayX()** - Aim your walkers away from the opponent on the East-West axis.
* **api.awayY()** - Aim your walkers away from the opponent on the North-South axis.
* **api.random\_direction()** - Aim your walkers in a randomly selected direction.
* **api.north()** - Alias of awayY. North for green player, South for red player.
* **api.south()** - Alias of towardsY. South for green player, North for red player.
* **api.east()** - Alias of towardsX. East for green player, West for red player.
* **api.west()** - Alias of AwayX. West for green player, East for red player.
* **api.wait(turns)** - Your bot code will not be run again until `turns` turns after this method is called.
* **api.spawning\_turn()** - Returns a boolean which if true if the Cities are going to send out a Walker this turn.
*Notes:*
* The last direction function called will define the next direction the walkers move in from that turn until a different direction is called.
* If no direction function is called walkers will continue in their current direction.
* Please do not set global variables, as these may conflict with those used by oponents, instead use `this.variable_name` to communicate between method calls.
## How to write a bot
*Note:* I recommend playing a manual game or two first; to do this, grab a friend to play against and select 'Manual (simple)' in the footer.
* Go to <https://ajfaraday.github.io/grid_game/>
* Select a default bot as your base (in the green or red box)
* Click Edit Code in the same coloured box.
* Click Use when you're happy with it.
To test it:
* Select an opponent bot as the other colour (or 'Manual' if you'd like to challenge it yourself.
* Open the developer console (f12) in case of errors in your code.
* Click Start.
* Watch the game unfold.
* Click Reset and repeat the process as desired.
## How to deploy your bot
Once you've written a boss you'd like to keep:
* Go to <https://gist.github.com>
* Log in, if not already logged in.
* (The default page is the form to create a new gist, this is where we want to be.)
* Name the file 'bot.js'
* Copy the code into bot.js
* Save the gist
* Copy the gist ID (an alphanumeric string found after the last forward slash in the URL).
This Gist ID can now be used to import your bot into Grid Game at any time:
* Select Gist Id in a coloured box.
* Paste the ID into the field which appears.
You will need to include this gist ID in your answer.
*Note:* Grid Game will use the most recent version of bot.js in the gist, updating the gist will update your answer.
## Answer Format
Your answer will consist of:
* A Title consisting of
+ A name for your bot
+ The gist ID (which should be a link the gist).
* A brief description of the bot's strategy.
* Any notes you wish to include.
Note: I would like to include answers in the respository's code, partly to sidestep rate limiting on github's gist and partly to include more interesting bots for future users to challenge or modify. Please clearly indicate if you consent to your bot becoming a part of the game code or not.
Example answer:
```
### The Faraday Cage - d9eb9a70ad0dc0fb1885be0fce032adc
The Faraday Cage is an arrangement of four cities in the player's starting corner, which this bot will attempt to build, which then allows it to repeatedly send two 9's towards the opponent.
* This is named after Alan Faraday, the elder brother of the game creator, who discovered it while playing the game manually.
* It has proven difficult to defeat.
Please include this in the repository.
```
## The Tournament
The competition will involve running a match for every permutation of two of the available bots.
There are three possible outcomes to a match:
* Outright win - A player is completely removed from the board. 3 points to the winner.
* Timeout win - The game will end if it reaches 3,000 turns. At this point, the winner is determined by the total health count. 2 points to the winner.
* Draw - If the game reaches 3,000 and the bots have an identical total health, it's a draw. Both players get 1 point.
Notes:
* The below scores are from the very first working tournament runner. I hope to present the results better in future.
* Currently this is a single match for each permutation. There will likely be multiple matches in future to smooth out the results for bots which use random functions.
* I also want to present the results of specific matches in future.
* I'll try to run it again for new bots, please alert me to changes in existing bots to request a re-run.
## Current scores
(Run at 2019/11/12 09:15 UTC)
Detailed results (with links to replay matches) can be found at <https://ajfaraday.github.io/grid_game/results/rankings.html>
```
Avi - Intercept and Destroy 60
Brilliand - Line Drive 60
Brilliand - Galeforce 57
Brilliand - CBC Goes With Everything 55
william porter - Twin Citites 54
Brilliand - CBC Forever 51
Brilliand - Feint 51
Brilliand - Cage Bar Cutter 49
Brilliand - Parry and Slice 48
Avi - Hocus Pocus(!?) 48
Alion - Evolvor: First Encounter 47
Alion - Evolvor: Overnight 45
Brilliand - Backstabber 42
BradC - Sweeping Endgame 36
BradC - Quad Rush 35
Alion - Doombeam 33
Alion - Slideout 31
AJFaraday - Faraday Cage 28
Alion - Zerg Rush 25
BradC - Double Barrel 22
Alion - Weirdflow 21
Alion - Rushdown 15
AJFaraday - Rotate 12
AllirionX - 3 Base rush 9
AJFaraday - Orbit 8
AJFaraday - All Towards 3
```
(Thanks to @brilliand for correcting the unexpected interactions between bots in the tournament runner.)
——
[Chat room for this challenge](https://chat.stackexchange.com/rooms/100140/grid-game-discussion)
[Answer]
### Doombeam - 496367ff51c27dc62ebdc473cd14f333
Time for a tryhard entry. Sets up a massive 12-city railgun and fires it off straight at the spawn point. Even if some of the cities get destroyed before the setup is complete, it still has enough firepower to devastate everything in its path. Additionally, after the far corner is filled with its cities to the brim, it clears up any potential leftovers, as a countermeasure to entries that escape the spawn point.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function* () {
yield* [[0, 30], [1, 30]];
for (let i = 0; i < 10; ++i) {
yield* [[2], [0, 2]];
}
for (let i = 0; i < 4; ++i) {
yield* [[3], [1, 2]];
}
yield* [[3], [2, 4], [1, 4]];
while (true) {
for (let i = 0; i < 30; ++i) {
yield* [[3], [2, 2]];
}
for (let i = 0; i < 3; ++i) {
yield [1, 42];
yield [0, 51];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Cage Bar Cutter - 49d7afbe8bb6d542acc871ac40d12e83
No more faraday cages!
Similar to Zerg Rush, but tuned to prevent Faraday Cages from growing at all (in either direction). In the spirit of this being a trivial bot, it makes no attempt to clean up bots that escape to the corners (but most can't manage that anyway).
```
const turn = api.turn();
const opening = "EEESSSEEESSEEEEEEEEEESSSEEESSSENEEENSNSSSSEEEEEEEEESSSEEESSEEEESE";
if(turn < opening.length) {
switch (opening[turn]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
} else if(turn >= 120) {
if(api.spawning_turn()) api.towardsY();
else api.towardsX();
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Slideout - 056b16e0dc85ee2f13cc6061cf8162ca
Builds on the Faraday Cage idea by increasing the total amount of walkers generated per 3 turns to 6.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
yield* [0, 1, 3].map(i => [i, 30]);
while (true) {
yield* [[2, 25], [3, 8]];
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I do not consent to the inclusion of this bot in the repository.
[Answer]
### Zerg Rush - 1f8b3963656f9e15577f886e0125a343
Oh boy, here we go... Of course a Zerg Rush would work. Why wouldn't it, right? It makes me feel incredibly dirty, but it had to be done.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function* () {
while (true) {
yield* [[3], [2, 2]];
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I do not consent to the inclusion of this bot in the repository.
[Answer]
# Double Barrel - 7d0a88c1533fc89b2ee26484bbcafc59
Makes a second city and immediately opens fire diagonally, catches lots of bots during setup.
```
if (api.turn() < 29) {
api.awayY();
} else if (api.turn() % 3 == 2) {
api.towardsY();
} else {
api.towardsX();
}
```
You can include this bot in your code if desired.
[Answer]
### Intercept and Destroy - [3dcc9463f47626a217a5a51762f02fe6](https://gist.github.com/SpicyKitten/3dcc9463f47626a217a5a51762f02fe6)
An improved version of [Cage Bar Cutter](https://codegolf.stackexchange.com/a/194816/89519), intercepting creation of Faraday Cage-like structures. After attempting interception, escape to the corner and attempt to build on the opponent's side. Aggressive attackers will not target themselves, so you can build up there. Non-aggressive builders will have been reasonably interrupted by the interception attempt. After some buildup, turn around and destroy everything.
At the moment of posting, this bot achieves a win against every other posted bot in under 1000 turns. [Weirdflow](https://codegolf.stackexchange.com/a/194649/89519) has the dubious distinction of lasting the most turns (808) against this strategy.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
yield* [[2, 3], [3, 3], [2, 3], [3, 2], [2, 10], [3, 3], [2, 3], [3, 3], [2, 1], [1, 1], [2, 3], [1, 1], [3, 1], [1, 1], [3, 4], [2, 9], [3, 3], [2, 3], [3, 2], [2, 4], [3, 1]];
yield* [0, 3, 2].map(i => [i, 36]);
while (true) {
for(let i = 0; i < 4; i++)
{
yield* [[2, 25], [3, 8]];
}
for(let i = 0; i < 4; i++)
{
yield* [[0, 25], [1, 8]];
}
yield* [[1, 50]];
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
As another fun little thing, here's what happens when you run this bot against itself for 4492 turns:
![](https://i.stack.imgur.com/kASCZ.png)
I **do** consent to the inclusion of this bot in the repository.
[Answer]
## Twin Cities - [46b9d27b1994c35a8ef214c1b2067609](https://gist.github.com/willuwontu/46b9d27b1994c35a8ef214c1b2067609)
Starts off with a corner start and then makes use of how attacks work to return fire before building up it's own forces. Beats most bots, loses to others.
```
//Twin Cities
const turn = api.turn();
if (turn < 31) {
switch(turn % 2) {
case 0:
api.awayY();
break;
case 1:
api.awayX();
break;
}
} else if (turn < 80) {
switch(turn % 3) {
case 0:
api.towardsY();
break;
case 1:
api.towardsX();
break;
case 2:
api.towardsX();
break;
}
} else if (turn < 127) {
api.towardsX();
} else if (turn < 246) {
api.towardsY();
} else if (turn < 350) {
api.awayX();
} else if (turn < 400) {
api.towardsY();
} else if (turn < 500) {
api.towardsX();
} else {
const late = turn % 200;
if (late < 50) {
api.awayY();
} else if (late < 100) {
api.awayX();
} else if (late < 150) {
api.towardsY();
} else if (late < 200) {
api.towardsX();
}
}
```
Feel free to include it in your repository.
Edited: Simpler initial phase, also dodges feint and hocus pocus now.
[Answer]
### Weirdflow - 8f82f8a5fd15fc29e60b9cce4343309c
This was an attempt at a very clean bot that turned into an incredibly sloppy counter to Rushdown.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
for (let i = 0; i < 10; ++i) {
yield* [[0], [2, 2]];
}
for (let i = 0; i < 5; ++i) {
yield* [[1, 2], [0]];
}
yield* [[3, 2], [0, 4]];
while (true) {
for (let i = 0; i < 5; ++i) {
yield* [[1], [3, 2]];
}
yield* [[2, 3], [3, 3], [0, 6]];
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I do not consent to the inclusion of this bot in the repository.
[Answer]
# Sweeping Endgame - 3f69bdf2be37886ff396d0c485007e80
More complex bot, with a setup phase, a sweeping mid-game strategy, and an endgame that covers all corners and directions.
```
//Sweeping Endgame v2
this.t = api.turn();
//initial city setup
if (this.t < 29) {
api.awayY();
} else if (this.t < 59) {
api.awayX();
//mid-game loop, now attempts to put cities in the two off-corners
} else if (this.t < 400) {
if (this.t % 200 < 14) {
api.towardsY();
} else if (this.t % 200 > 13 && this.t % 200 < 17) {
api.awayX();
} else if (this.t % 200 > 100 && this.t % 200 < 122) {
api.towardsX();
} else if (this.t % 200 > 121 && this.t % 200 < 126) {
api.awayY();
} else if ((this.t % 8) % 3 == 1) {
api.towardsY();
} else {
api.towardsX();
}
//endgame, now sequential, not random
} else {
if (this.t % 200 < 40) {
api.awayY()
} else if (this.t % 200 < 50) {
if (this.t % 2 == 0) {
api.towardsY();
} else {
api.awayX();
}
} else if (this.t % 200 < 90) {
api.towardsX()
} else if (this.t % 200 < 100) {
if (this.t % 2 == 0) {
api.awayY();
} else {
api.awayX();
}
} else if (this.t % 200 < 140) {
api.towardsY()
} else if (this.t % 200 < 150) {
if (this.t % 2 == 0) {
api.awayY();
} else {
api.towardsX();
}
} else if (this.t % 200 < 190) {
api.awayX()
} else {
if (this.t % 2 == 0) {
api.towardsY();
} else {
api.towardsX();
}
}
}
```
v2 makes the following changes:
1. Mid-game now deliberately attempts to get a couple of cities in the off-corners. This is crucial to "get behind enemy lines" for simple bots like Quad Rush.
2. End game is no longer random, instead it goes through a prescribed sequence of straight and diagonal moves to clean up the board.
[Answer]
### Evolvor: First Encounter - c0382c11979adc1f47773714ffc8376f
This is the first in what I hope becomes a series of bots that result from a genetic algorithm. Does some really weird things which result in tons of cities and then... usually can't convert it into a victory.
```
switch ("WNSNNNWSNWNWNWNWWNNWWNWNNNWWWNEENNNWWNNWWWWWNWWNWNWWSWENEENNENNESSSSWSWWSWWSWWSSWSNWSWWSWSSWWSWWSWWEESESSEESESSESSESWESSEWWESWESSSSSNNWNWWSWWNNWNWWEWWSWSEWWNWEEENEESEENEEEEEEEEEEENEEEEEEEESEENESEENEEESEEEEEEENEEEEEEEESEESEENEEEEEEEEENEEEESEEENEEEEEEEEEEEEEEEEESEENEENENEEESEEEEESENEEESENEEEEEESEENEEEENEEEEESEENEEEEEENEEEESEEEEENEEENENEEEEESEENEEEEEEEEESNEEEESEEEEEEENEENEEEEEWEEENEEEEENEWSEEEENNENEENEESEENEEWNEEEEEEEEWENSEENEESEEEEENENEEESEESEENEEENESENEESEWSNEENEWSENEEEEENSEEEENEEEEEENEESENEESNENWEENENSEEEENNNEEESWESWEESENENESNEEEENSNEEESEEEEEEESSEESEEEEEEESNENEEWENENNSEENEEWEEEEENWEESENNEESENNENSENWENEENWESENENNNNEENEWSENEENEEWWEEWENNWNNEEEEWSEEWESESESEEEENNWEWSSSENSENEEESESEENNNSEEEEESESSEEENENENEWEWNWSEESSENNNESSSENNENWEEEWNWNENSEWESESSEEEEENWSENEESEWNEEEWEWSEEWNNEEEENSENNESNNESNEENSEENWNNESESSWWWENEWENNSSENEESNSWWNNNWENWNNESEENEEENEESNEWSSENWWWNEEEESESWSSEWNNENWENNWNSESEEESESNSSESENWSESENNEWENNEENEESSNENEESSNWNESNENSESWWEENWWNEEEENESSEEESWWSWWEESWWEWSEENWEWEWNNSESSSNEESESNSEESSEEEEWSSSNSNSSSNNSESESSSESNWWEWENNENNNNWWEENWSNWWWSWNWWSEEEWEEWWEWENNSSEEEESNSESWENNNWENSWWNNENEESEWEWSEESEWEEWENSWNNSNENSWNWSENNENNNESNEWSEENSNNEWEENNSEEESSNEENWEESWEEWSEWWEWWWESESSSESEWEEWEESNNSNWWSNNENSSESWEEWNESENSEEEESEENEWENWSEEEEEWWEEESSNSWSEENWSESEWEWEESSNSNNNSWNWEWSWEESWSEWSNNWNNENNNNSESENNWEENSWWENSWNESNNSENWWWNESSSSENENWNENNEEEESWSWWNSEEWNNESENSENSWNWSNWNSSSSSSESSNESEWNESEWWNEWNENNESWSSEEWEEWNSENENESWEENESWWNESNEEWSSEWENEWEESSSENNWNNNESWEWWSESWNSSNENWEWWESSESSNEENNSSSSESNWEENSWSWEWEEWEWWSSESSNEWWEENWSSENWENSSWNSENSEEWNWENWNWENEENWWWEEWNWEWWNNNSSNWENWNENENNWNNWSESSESWNNENENWSSESWEEWEESNSWENEENSSWESEENWWEWNNEEENEESWENESNWNWEEWNWEESWWEEESWENENSSWENNWSWWNSWNSESESSNEENEWEENWENNWWWNSWWEESSWNNNSWNWESEESENEESEENWNNWWESSSSESNESWNSWWNSNEWEWEENSEWSESSENSWNENSESNNSWWSWEEESSNSESNEEEWEEWNSWNEENSENSWENESEESNNNEESWSNNSNWNSSSSEEESWSSSSNSNSESENENSNESSNWNSWNSSENESSSWEWNSWENSEWWSWNNWEEESESENSNNNSWNENNSSSNEWSSWEEWWWEWNSWNNEWWWENENENWSWWWEESEENWSWENESEESWNEWEESEWEWNESEWWNWWSWWNWSEEEWNSNNSENWSWSWSSWWNWWSESSSNEESWENNEENEEWEWNSENWSNSWNNSWSWSESWEWNNSNNNEWWWNWSNNENSNENNNNWNWESWWEEWNNWWNNEEWNSNNNNSNWSSSNEWEWWENNESNWNNNSWNWEWWSSSWSEWWESEEWSNNSESEEWEEWSNWENWWWSNWSESNENNEESENSNWWNWNNWEWSSWSSSNSEESNSNNSEEWNSSWWWEEWWNNESNWENSWNEWNSEWWEWESNWWNENWWEWNEWEESNNEEESNENESWEEWNSSNESSENWSENSWWEEWSSWWEWSNESSENWESSSSWWENSSENWNNWEESWWNNNSEEESSSENSESSNSSSSSWNWENESNWNESWNSNESSENESSSWWNEWNESSENNWNEEEEEWNSWWSWWSSNEWEESSWESENSWEESNWEWNEENSENESNNSEEEWENESENWWNSESENWWSWESNSWSESEWSENEWEWEWSENESSSENSNEEWESSNNESENEWENWEEEESWWNESNESSSNNEWNNENEESEESNENSWESNNWWSENNWNNNWWEESESNNWNWENNEWSSSNSNNENNNWSSWWSNWSNEWNNWSEEWNNWESNNNWENWNSENNWENWENSWNNWNWNENNWSNNWWWWWSESWWEEEEESEENESEENEENWWNWEENESSSWSSSNNWWENSWNWWENSESSSSSSWENSNWSWENEWENNWNWNSWWNNSWSWSWWWNWEEWNNESSSWSEEENEWSNWWEWEWENWWEENESNWWNSEWNEENNSNEWSWESESSWEWWWEWWWNWNESSNNWSENWSNNSENSSESWWWSSESESWWSESSSENSENEWESSWESSNNWNSEWWWWWNWSEWSENNESWNEEWWEENNNEESWSWSESNESWNSNNSWWSENEENENSSWWWWEEEWWNEEEWENNSWEEWNWWNSNSNWSNNEENESSWEENNNEEEENNWSSWENSSNWSSNSNWNENESEWNWWEEENEEWESNESNEES"[api.turn()]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
```
I do not consent to the inclusion of this bot in the repository.
[Answer]
### Line Drive - 54e4de5b03423cc19a1ec0e22f32a981
Attempts to occupy an entire column of the grid, then unleash an unstoppable barrage in the x-direction.
EDIT: Now biases its barrage toward one wall and changes direction more rapidly, allowing it to beat some bots that the previous version couldn't beat.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function* () {
yield* [[0, 24], [1], [0], [3], [0, 3]];
for (let i = 0; i < 9; ++i) {
yield* [[1], [2], [0]];
}
yield [1, 3];
for (let i = 0; i < 10; ++i) {
yield* [[3], [1, 2]];
}
for (let i = 0; i < 4; ++i) {
yield* [[2], [0, 2]];
}
yield* [[2], [3, 4], [0, 4]];
for (let i = 0; i < 4; ++i) {
yield* [[2], [0, 2]];
}
yield* [[2], [3, 2], [0], [3, 2], [0], [3, 2], [0, 3]];
while (true) {
for (let i = 0; i < 60; ++i) {
yield* [[2, 2], [1]];
}
for (let i = 0; i < 40; ++i) {
yield* [[3, 2], [2]];
}
for (let i = 0; i < 60; ++i) {
yield* [[0, 2], [3]];
}
for (let i = 0; i < 40; ++i) {
yield* [[1, 2], [0]];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Hocus Pocus(!?) - [966e8f3ad189b9535c2e1fad3ffc065a](https://gist.github.com/SpicyKitten/966e8f3ad189b9535c2e1fad3ffc065a)
Weird strategy that I'm unable to describe - it's probably(?!) an amalgam of Feint, Two Cities (??!) and whatever else I can't remember. At the moment of posting, (I think it?) beats everything but the Evolvors and Intercept & Destroy. Uses anti-CBC at the beginning, then hocus pocus(!?) strategy.
Edit: Also loses to Backstabber
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
yield* [[3, 8], [2, 16], [3], [0], [1], [0, 27]];
while (true) {
yield* [[3, 36], [2, 36], [1, 36], [0, 36]];
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [1]];
}
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [3]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [1]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [3]];
}
for (let i = 0; i < 10; ++i) {
yield* [[1], [3, 2]];
yield* [[2], [0, 2]];
yield* [[3], [1, 2]];
yield* [[0], [2, 2]];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Rushdown - 5a989c80bf1bbef32c848f248aa55dcb
Focuses on building up a bit of firepower and then rushes down what it expects to be the enemy base. Made as a counter to the Faraday Cage and similar. As a bonus, it looks like it's shuffling a deck of cards during the first phase.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
for (let i = 0; i < 5; ++i) {
for (let j = 1; j <= 2; ++j) {
yield* [[2, j], [0, j]];
}
}
while (true) {
yield* [[3, 34], [1, 1], [2, 16]];
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I do not consent to the inclusion of this bot in the repository.
[Answer]
### 3 Base rush - 3f6d1a1461564ace3d7e22cedba08c20
A bot building three cities before launching an indirect attack and proceeding to lose.
```
if (api.turn() < 29) {
api.awayX();
} else if(api.turn() < 40) {
api.awayY();
} else if(api.turn() < 42) {
api.awayX();
} else if(api.turn() == 42) {
api.awayY();
} else if(api.turn() < 45) {
api.towardsX();
} else if(api.turn()<48) {
api.awayY();
} else if (api.turn() % 2 == 1) {
api.towardsY();
} else {
api.towardsX();
}
```
This bot is not to be included in the repository, as it is only a stepping stone to explore 3 cities openings.
[Answer]
### Evolvor: Overnight - 7512fcfcef33bff323d5cdaf1bb833ff
This is utilizing exactly the same evolution code as [Evolvor: First Encounter](https://codegolf.stackexchange.com/a/194779/74965), but with a significant increase to the time provided. As of the time of posting, this only loses to 4 entries - two of them mine (whoops) and all of them rushy. I hope to be able to fix this issue soon.
```
switch ("NEWWNSNWEWWNNEWWNNNWWWNNNNNNSWWEWNNWNWENWWNWWEWNNNNENNWWNSESSSESESSWWSNSESSSWESWNSWWENNSSESSNSWESWWSWSESWSSWSWSSSNSWEENWEWEEWWSWSSWWSWNEWWEESEESEESEESEEEENEEESEEEEEEEEEEEEENEEEEEEEENEESEEEEENEEEEEEEEEEEEEENEENEEEEEEEEEEEEEEEEENNENEEEEEEEENEEEEEEEEEEEEEENNENNENNENNNNNENEEEEENEEEEEEEEWEEEEEEEEWEENEENEEESEEWEEEESEENWESEESEENEEEEEWEEESNNNENNENNEENENEENENNEENNNNEENNENEEENNNENNEENNENNEENESEEWEEEEEEEEEEEEEENNEENESSEWSENEEWSESEESSESSESSWNNNNENNNNENNNNNENNNNNNENNENNENENNNNNENNNNNNENENNNNNNENENNENNENNNENNENENNNNNENNNNNENNNNNNENENNNWNENNNNNNENNWNENNENNNWNENNENNNNENNNSWEENWNENENNENNNWNWNNENNEWNNNWENWNNNWNEENNWWNWNSSNSNSSEESSWNWESWSSWSESESSESESSSESEESSESNESSESEESESEEESSESEESSESSNSEESEEESSSSWNEESNNNESESSSESEEESEWSSSSSESESSNSNWENESNSESSSSSSSESSSSSWSSNNWSSNESSENSSESEESEWSEENSESWSSSNWESEWENSENNENNWNSSSEWNWWSSSNSESSWSNENSEEENNNNNNENSSNWEWWSSEWSSWNEEWEENSEWNESNESWNSSWWENWSENSWNNNWNNWESESEWWNNNWNWNNEWWSNWNNSWWNWWSENWNSNSWNWSNEWNNNNNNWWWWWSNWNWSSNENWSNNNSNWSNWWNNWWNNWNNSWWNNWWNENNWWSSWWNNNSWENNWWWWWWSWSWSNWNNSSNNNNNSWENWNWWEWNWNNNNWWWNSWWENNNNWNWNSWWWNNSSWNSSNWWNENNNWNWWNNWSESNNNNWWSNNWSWSWEWWNEWWWWWWSNWNNNWWWWNNEWWSEESNSWWWNNENNWWNSNWWNNWEWSWNWEWNWWSENNNWEWWSNWENWSWWWWNNSSENWSWNSNWSWWNNNNESWWNSWNNNWNWWNSWSNNENNSSWWWENSSENWNWWSSWSWWWEWSNEWWNEWWSWWSSSNWSNWEWEEWNNSWESSEESNNWWWWNSNSSNWSSWSNNSNNWSNWNWSWWSWNWEWEEWNNWNEWNSWWWWWSWNEEWWNNNSSNWWNNWWNWSNNWWNEEWESWNNNEWWWWSWWWNNSSWWNNSWSWEWSWWNSNWNESESWWEEWESSSNWEWENWSNNWNSESEEWWWWSWNNNSWNWWNWWWESSWNWNWNWEEWENEWNWSNNSNNWWWSSNNNWNNNSWNNNWSSWEWWENWNSNENEWESWNSWNEWENENSSEWSNNSNNSNNSSWSEWESSEWWSWWNSNNNNEWNWNESEENENNWSENEWNWWSNEENNSNWNNWNNNNWWWENNNEEWWENWWNNENWNNSWNNNEEWSSSSEESWWNESWNWNSWENEESENSENNNWESSNNSNWNSESESNEEENSSWENWEWNSENEENNSNWEEWNWNNEWNENNSSWWNSWSWSENENWENNWNEWWNNWSSSSESWNESSSNSWWNEESNWNNWESWENSWWNWESSWSNEWEENWESWWWSWSEWENNNNEEESSWWWNSWSNSWNSEESSSNEEWNNSSSWSSSWSNWSSSNSWNESWENNWWENNENWSWEWSEWSNWEWWESEWEEESSNEENNSWNWWWSWESSNSSSNNEWENENWNNWSSSWWESNWWSSEWSWEWNWNWSNSNEWEWEENEEWWESSENSSNNNNESNEWSNSSWENNSNNENEWNESNWNWESSWNNSWNNSWEWESSNWEWNWENEWEWESWSNNEWSWSWNEWEWSSWNWSWNSNSWESWNNWWNWNSENWNEWSWNNWNENWNENEEWSNSSSSEWSNNESNSSESESSSWWNWSESSNSSWWWWWSNWNEWESEWNEWESSNENEESNSEEWNSNNEWWWWESESSNEWWSSSNWSSWWNSSSSEWSWWWWSSNWSNWNWEEWSEWESWSENWNSWSSSSSWNWSNEWNWSSSWEWWEWNENESNNSWSSWNWNWNWNWSSSESSSWSWSWSSWSWESWSEESWEENSNNSSNNSSSWWEWSNEWWNNEENNNWSSEWWSESSNWNSEWNWNNNWNESSSSNEEWWENNEESESSNEEWEWEWSWSEWWNEWENWNEWNWENSNNEWSENESSSEESSWENNWESESSSWNNNWWNSNWEWWWEWSWSWESSENWWSENSEWSEWNSWNEENWNWWNSEEWWSWWWWWWNESEESSWEWENNSWWSNWWNSSWWNWNWNWNEWWWSWNNEESWSWWWESSEWNWSWEEWWNSENSWSWNSWWSSEWNEWWWNSNEENEWNNWNWWNSNNSWNWSNWSNNWWEWNWWWNESESNSEWWNENNSEWWWNWWWENWWNSSSEWNWEEEENWSSESEWESWWNSSWEEEEENSNWSWSEWESESSNWNWSENSSSENWWWNWWNENSSENWNWWWEWEENEENEWEWNSENENSSSWNWWSWWSNSESENESENWSSWWEENWWWWWEWSSSWSWESNSEWSSNWSWWWSSEWWEWWWSSSNEWWWWEENNSEEWWESWSSNESEENNSNENSWNNNNEENEWWWEWSEEWWEENWNSSSSWWNNENWNEWSSNENNNENSWSESSWSNENNWSWWWSESESENSNSSENWWSEENWWNSEWSEWNNWSENSNWEWWWNSSESESWSNSSEESWNEEENEEWSNNSWSESENNNWESWSWNNWESEENWWWENWWEWSSWSESWEWENSNEEEESSNWSSWSSNEENNEEEESSWWNWENSWESEWSESNE"[api.turn()]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
```
I *do* consent to the inclusion of this bot in the repository.
[Answer]
# Quad Rush - a0a4a9f3c8b8863392f109fdfd52af00
Double barrel x2.
**EDIT**: Changed the cadence so we end up with a `[2]` runner and two `[1]` instead of four `[1]`, which makes a difference in some matchups.
```
if (api.turn() < 29) {
api.awayY();
} else if (api.turn() < 59) {
api.awayX();
} else if (api.turn() % 3 == 0) {
api.towardsY();
} else {
api.towardsX();
}
```
You can include this bot in your code if desired.
[Answer]
### Galeforce - 294c357b051e6e165d18657748d02cfe
Sets up 8 cities, then sprays walkers in various directions. Looks a bit like a Doombeam followed by a Line Drive (and the Galeforce vs. Doombeam matchup comes down to persistence).
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function* () {
yield* [[1, 24], [0], [1], [2], [1, 3]];
for (let i = 0; i < 9; ++i) {
yield* [[0], [3], [1]];
}
yield [0, 3];
for (let i = 0; i < 10; ++i) {
yield* [[2], [0, 2]];
}
for (let i = 0; i < 20; ++i) {
yield* [[3], [2, 2]];
}
while (true) {
for (let i = 0; i < 20; ++i) {
yield* [[3, 2], [2]];
}
for (let i = 0; i < 20; ++i) {
yield* [[3, 2], [0]];
}
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [1]];
}
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [3]];
}
for (let i = 0; i < 20; ++i) {
yield* [[1, 2], [0]];
}
for (let i = 0; i < 20; ++i) {
yield* [[1, 2], [2]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [3]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [1]];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Backstabber - 2d632fb11ea1a7b1b73788d396a6a45d
After making Galeforce, I got to wondering if anything could beat a *really* persistent Doombeam - one that never stopped firing. None of the existing bots seemed to be able to.
This bot can do it, though, and it beats most of the other bots too!
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
yield* [[0, 24], [1], [0], [3], [0, 3]];
for(let i = 0; i < 40; i++) {
yield* [[1], [2, 2]];
}
while (true) {
for(let i = 0; i < 40; i++) {
yield* [[3, 2], [2]];
}
for(let i = 0; i < 40; i++) {
yield* [[0, 2], [1]];
}
for(let i = 0; i < 40; i++) {
yield* [[3], [0, 2]];
}
for(let i = 0; i < 40; i++) {
yield* [[0, 2], [3]];
}
for(let i = 0; i < 40; i++) {
yield* [[1], [0, 2]];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### CBC Forever - 9c65942bf924d9bb09e99d22daf0d8d0
An endless loop of inverse CBC. After a while it starts cycling walkers around behind it, to clean up any enemy cities that got into its corner.
This is partly intended as a demonstration of how to do a long inverse CBC, but of course it beats a lot of stuff in its own right.
```
const turn = api.turn();
const opening =
"SSSEEESSSEEEEEEEEEESSEEE"+
"SSSEEESSSEEEEEEESSEEEEEE"+
"SSSEEESSSEEEESSEEEEEEEEE"+
"SSSEEESSSESSEEEEEEEEEEEE";
const pattern = "NWSSSSEEESSSWNEESSEEEEEEEEEEEE";
if(turn < opening.length) {
switch (opening[turn]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
} else {
switch (pattern[(turn-opening.length)%pattern.length]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### Feint - cb68f09d808b5de34daf5c45b46f2bea
Briefly dips into a reverse Cage Bar Cutter, then jumps to a corner and tries to get behind the opponent before switching to the main circling strategy.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function* () {
yield* [[3, 8], [2, 16], [3], [0], [1], [0, 27]];
let laps = 1;
while(true) {
for (let i = 0; i < laps*10; ++i) {
yield* [[3, 2], [0]];
}
laps++;
for (let i = 0; i < laps*10; ++i) {
yield* [[2, 2], [3]];
}
laps++;
for (let i = 0; i < laps*10; ++i) {
yield* [[1, 2], [2]];
}
laps++;
for (let i = 0; i < laps*10; ++i) {
yield* [[0, 2], [1]];
}
laps++;
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
### CBC Goes With Everything - f904da9534cf91ff2d5d399f59757ebc
Repeats the CBC pattern 5 times, then proceeds to build its own Faraday Cage and perform a stock Galeforce.
6 appears to be the maximum number before it starts losing to variants of itself for being "too persistent"; I picked 5 'cause it's a nice round number close to that.
```
const turn = api.turn();
const opening = "EEESSSEEESSEEEEEEEEEESSSEEESSSENEEENSNSSSSEEEEEEEEESSSEEESSEEEESE";
if(turn < opening.length*5) {
switch (opening[turn%opening.length]) {
case 'W':
api.awayX();
break;
case 'N':
api.awayY();
break;
case 'E':
api.towardsX();
break;
case 'S':
api.towardsY();
break;
}
}
if (turn === opening.length*5) {
this.generator = (function* () {
yield* [[0, 30], [1, 30], [2, 30]];
for (let i = 0; i < 20; ++i) {
yield* [[3], [2, 2]];
}
while (true) {
for (let i = 0; i < 20; ++i) {
yield* [[3, 2], [2]];
}
for (let i = 0; i < 20; ++i) {
yield* [[3, 2], [0]];
}
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [1]];
}
for (let i = 0; i < 20; ++i) {
yield* [[2, 2], [3]];
}
for (let i = 0; i < 20; ++i) {
yield* [[1, 2], [0]];
}
for (let i = 0; i < 20; ++i) {
yield* [[1, 2], [2]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [3]];
}
for (let i = 0; i < 20; ++i) {
yield* [[0, 2], [1]];
}
}
})();
this.nextCall = turn;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
You can include this in the repository if you want to, but it's just two of my other bots grafted together.
[Answer]
### Parry and Slice - 472a33460a33c1785a28190c9406e36e
Defends against CBC with a small stack of walkers, then goes for a 3-city buildup because nothing else is fast enough after spending time on shielding. It then moves into a Backstabber variant.
Lategame, it throws in an occasional buildup phase to recover from situations where one of the endless rushers *almost* finished it off.
```
const turn = api.turn();
if (turn === 0) {
this.generator = (function*() {
for(let i = 0; i < 5; i++) {
yield* [[3], [1, 2]];
}
yield* [[0, 30]];
for(let i = 0; i < 5; i++) {
yield* [[1], [0, 2]];
}
for(let i = 0; i < 12; i++) {
yield* [[2], [1], [2, 4]];
}
while (true) {
for(let i = 0; i < 40; i++) {
yield* [[3, 2], [2]];
}
for(let i = 0; i < 20; i++) {
yield* [[1, 2], [2]];
}
for(let i = 0; i < 30; i++) {
yield* [[0, 2], [1]];
}
for(let i = 0; i < 30; i++) {
yield* [[3], [0, 2]];
}
for(let i = 0; i < 40; i++) {
yield* [[0, 2], [3]];
}
for(let i = 0; i < 30; i++) {
yield* [[1], [0, 2]];
}
for(let i = 0; i < 10; i++) {
yield* [[0], [2, 2]];
}
}
})();
this.nextCall = 0;
}
if (turn === this.nextCall) {
const [dir, delay = 1] = this.generator.next().value;
[api.awayX, api.awayY, api.towardsX, api.towardsY][dir].bind(api)();
this.nextCall += delay;
}
```
I **do** consent to the inclusion of this bot in the repository.
[Answer]
# Orbit - 1ec7b9413c34cd8cd66d5bf28a9537ef
Just quickly threw this together on a whim but...
The concept was to have the first walker keep ringing round the first city and see what happens. Uninterrupted, it keeps a pile of quite high-value walkers floating around until they build a few cities at once. Then keeps building, gradually creeping towards the enemy.
I expect it will do very badly in the tournament. ¯\\_(ツ)\_/¯
```
if(api.turn() == 0) {
api.towardsX()
} else if (api.turn() == 1) {
api.towardsY()
} else {
var dirs = ['awayX', 'awayY', 'towardsX', 'towardsY']
if (typeof api.dir == 'undefined') {
api.dir = 0;
}
if ((api.turn() + 1) % 2) {
//next dir
api[dirs[api.dir]]();
api.dir += 1;
api.dir = api.dir % 4;
}
}
```
I'd like this in the repo, regardless.
] |
[Question]
[
Given an input of a color in `#rrggbb` hex format, output its RGB complement in
the same format.
The RGB complement R2G2B2 of any color
R1G1B1 is defined as the color with
R2 value *255 - R1*, B2 value *255 -
B1*, and G2 value *255 - G1*.
Hex digits may be either in uppercase (#FFAA20) or lowercase (#ffaa20). The
case of the input and output need not be consistent (so you may take input in
lowercase but output in uppercase, and vice versa).
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins.
Test cases (note that since giving your program/function its own output should
result in the original input (it is
[involutory](https://en.wikipedia.org/wiki/Involution_(mathematics))), the test
cases should work in both directions):
```
In/Out Out/In
----------------
#ffffff #000000
#abcdef #543210
#badcab #452354
#133742 #ecc8bd
#a1b2c3 #5e4d3c
#7f7f80 #80807f
```
[Answer]
## Pyth, ~~9~~ 8 bytes
*Thanks to @isaacg for -1 byte!*
```
sXz.HM16
```
Subtracting a certain color's value from 255 is equivalent to subtracting each of its hexadecimal digits from 15. Say a number is ***16a+b***. Then the value of the number created by subtracting its digits from 15 is ***16(15-a) + (15-b) = 255 - (16a+b)***.
```
sXz.HM16 implicit: z=input()
16
.HM map hex representation over range
.HM16 '0123456789abcdef'
z the input string
X Translate characters in x1 present in x2 to reversed x2
that is, '0' becomes f, '1' becomes 'e', and so on.
The initial '#' is unchanged.
s That produced a list, so join into a string by reducing +
```
Try it [here](https://pyth.herokuapp.com/?code=sXz.HM16&input=%23a1b2c3&debug=1). [Test suite.](https://pyth.herokuapp.com/?code=sXz.HM16&test_suite=1&test_suite_input=%23ffffff%0A%23000000%0A%0A%23abcdef%0A%23543210%0A%0A%23badcab%0A%23452354%0A%0A%23133742%0A%23ecc8bd%0A%0A%23a1b2c3%0A%235e4d3c%0A%0A%237f7f80%0A%2380807f&debug=1)
[Answer]
# Retina, ~~13~~ 10 bytes
```
T`w`G-A9-0
```
There are three parts to the code, separated by backticks (```): `T` specifies transliterate mode, which replaces each character in the second part with its corresponding character in the third part.
`w` is the same as traditional regex's `\w`, or `_0-9A-Za-z`, which is expanded to `_0123456789ABCDEFGH...`.
The second part is expanded to `GFEDCBA9876543210`, thanks to Retina's nifty ability to expand in reverse order. Put these on top of each other, and we get:
```
_0123456789ABCDEFGH...
GFEDCBA987654321000...
^^^^^^^^^^^^^^^^
```
Note that the last character, `0`, is repeated to fit the length of the longer string, but we only care about the hexadecimal characters, shown by carets.
Thanks to Martin Büttner for suggesting this approach.
[Try the test suite online.](http://retina.tryitonline.net/#code=VGB3YEctQTktMA&input=I0ZGRkZGRiAgIzAwMDAwMAojQUJDREVGICAjNTQzMjEwCiNCQURDQUIgICM0NTIzNTQKIzEzMzc0MiAgI0VDQzhCRAojQTFCMkMzICAjNUU0RDNDCiM3RjdGODAgICM4MDgwN0Y)
[Answer]
# [Julia 0.6](http://julialang.org/), ~~74~~ 49 bytes
```
h->"#"join([hex(15-parse(Int,i,16))for i=h[2:7]])
```
[Try it online!](https://tio.run/##XcvNisMgGIXhvVchdaOQDlGTGgYyzKow11C68Jd8EmxQC3P3GZPlvLvzwInvFfRtv8/7cv26kEt8QaKPxf9SPl43nYunP6l20PEbY@GVMczLQ3yq55Ptx6TQ4cgwJFy2FeoHzV67FZIvlDGEW9@6FJ8rvlNgeJ5x/KfxVEA@ObRlSHVNtOa3ZzsJZxiT/gwRbazzB4yDFLyB0c5q02AYhRwHRLiUahANvLWTce3CjbDyuPjBSYuICipMfYOpn3oV/gA "Julia 0.6 – Try It Online")
Pretty long at the moment but it's a start. This is a lambda function that accepts a string and returns a string. The output will be in lowercase but the input can be in either.
As [Thomas noted](https://codegolf.stackexchange.com/a/68309/20469), subtracting each 2-digit color component from 255 is equivalent to subtracting each individual digit in the hexadecimal input from 15. Looping over the input string, excluding the leading `#`, we convert 15 - the parsed digit to hexadecimal. We join all of these then tack on a `#` and call it good.
[Answer]
# Marbelous, 41 bytes
```
00@0
\\]]\/
-W/\@0
-W
~~
<A+700
+O//]]
+O
```
[Online Interpreter here.](https://codegolf.stackexchange.com/a/40808) Input should be in uppercase.
### Explanation
The `00` and `]]` at the bottom will fetch the first character (the `#`) and it will fall to the bottom and be outputted before anything else.
The first 3 lines are a loop to fetch all the remaining characters.
First we need to convert the hex digit characters to 0-15, by doing `x -= 48, x -= x > 9 ? 7 : 0` (since `'A' - '9'` is 8).
To find the complement, we simply need to convert every digit `x` to `15-x`. This is equivalent to (for 8-bit values) `(~x)+16 = ~(x-16)`.
Finally, we have to convert these numbers back into hex digits, by doing `x += x > 9 ? 7 : 0, x += 48`.
So now we have `x -= 48, x -= x > 9 ? 7 : 0, x = ~(x - 16), x += x > 9 ? 7 : 0, x += 48`.
Note that if we remove the expression with the first ternary operator, then input digits `A`-`F` will result in a negative x after negation.
Thus we can change the previous expression to: `x -= 48, x -= 16, x = ~x, x += (x > 9 || x < 0) ? 7 : 0, x += 48`, which is equal to `x -= 64, x = ~x, x += (x > 9 || x < 0) ? 7 : 0, x += 48`.
The above code is just an implementation of the last expression. `-W` is `x -= 32` and `+O` is `x += 24`. Since Marbelous uses unsigned 8-bit arithmetic, the condition `<A` covers both the case of `x > 9` and `x < 0`.
[Answer]
# JavaScript ES6, 61 bytes ~~66 68 48 53 64~~
*Saves quite a few bytes thanks to @C·¥è…¥·¥è Ä O'B Ä…™·¥á…¥, @NinjaBearMonkey, and @nderscore*
```
s=>"#"+(1e5+(8**8+~('0x'+s.slice(1))).toString(16)).slice(-6)
```
Takes advantage of auto-type-casting. Fixing the zeros killed the byte count
[Answer]
## JavaScript ES6, ~~63~~ ~~58~~ ~~52~~ 49 bytes
```
c=>c.replace(/\w/g,x=>(15-`0x${x}`).toString(16))
```
*Thanks to [nderscore](https://codegolf.stackexchange.com/users/20160/nderscore) for saving 11 bytes!*
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
k6ḂĿ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrNuG4gsS/IiwiIiwiYTFiMmMzIl0=)
```
k6ḂĿ
k6 # Hex chars - "012356789abcdef"
Ḃ # Bifurcate - push its reverse without popping
ƒø # Transliterate the input from the hex chars to the reverse hex chars
```
[Answer]
# Jolf, 17 bytes
```
pq#-w^88C Li1~560
pq pad
_Li1 the input, w/out the first char
C ~5 parsed as a base-16 integer (~5 = 16)
w^88 8 ^ 8 - 1 (the magic number)
- subtract the parsed input from said number
# convert result to hexadecimal
60 pad the result with 6 0's
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cHEjLXdefjU2QyBMaTF-NTYw), [Test suite](http://conorobrien-foxx.github.io/Jolf/#code=cHEjLXdeODhDIExpMX41NjA&input=I2ZmZmZmZgoKI2FiY2RlZgoKI2JhZGNhYgoKIzEzMzc0MgoKI2ExYjJjMwoKIzdmN2Y4MA) (Use full run, which now works.)
[Answer]
# [Japt](http://ethproductions.github.io/japt), ~~35~~ ~~32~~ ~~22~~ ~~20~~ ~~16~~ 15 bytes
```
¬°Y?(F-XnG)sG :X
```
Explanation:
```
¬° //Take input and map (shortcut to "Um@"). Input should in the form of "#123456"
Y? //if Y is not 0, then return (F-XnG)sG, otherwise last step...
F-XnG //Subtract X, converted from hexadecimal (G is 16) to decimal, from 15
sG //convert decimal to hexadecimal
:X //...otherwise return X unchanged (happens only with #, the first char)
```
[Answer]
# Perl, 30 bytes
*includes +1 for `-p`*
```
s/\w/sprintf"%x",15&~hex$&/eg
```
usage: `echo #000000 | perl -p file.pl`
or `echo #000000 | perl -pe 's/\w/sprintf"%x",15&~hex$&/eg'`.
[Answer]
# [MATL](https://github.com/lmendo/MATL/releases/tag/6.0.0), 21 bytes
```
35,5Y216,j6L)!16ZA-)h
```
This uses [release 6.0.0](https://github.com/lmendo/MATL/releases/tag/6.0.0) of the language/compiler, which is earlier than the challenge.
Input digits should be uppercase.
### Example
This has been executed on Octave:
```
>> matl
> 35,5Y216,j6L)!16ZA-)h
>
> #FFAA20
#0055DF
```
### *Edit (June 12, 2016)*
The code can now be [**tried online**](http://matl.tryitonline.net/#code=MzUgNVkyMTYgajRMKSExNlpBLSlo&input=I0ZGQUEyMA). Commas need to be replaced by spaces, and `6L` by `4L`, to conform to changes in the language.
### Explanation
```
35, % number literal: ASCII code of '#'
5Y2 % '0123456789ABCDEF'
16, % number literal
j % input string
6L) % remove first element
! % transpose
16ZA % convert from hex to dec
- % subtract from 16
) % index into '0123456789ABCDEF' to convert back to hex
h % prepend 35, which gets automatically converted into '#'
```
[Answer]
# x86-16 machine code, IBM PC DOS, ~~60~~ ~~41~~ 32 bytes
**Binary:**
```
00000000: be82 00ac cd29 b106 ac3c 397e 022c 272c .....)...<9~.,',
00000010: 30f6 d03c f976 0204 2704 40cd 29e2 e9c3 0..<.v..'.@.)...
```
**Unassembled listing:**
```
BE 0082 MOV SI, 82H ; command line input set to string
AC LODSB ; load first '#' char
CD 29 INT 29H ; write it to console
B1 06 MOV CL, 6 ; loop 6 chars
INLOOP:
AC LODSB ; load next ASCII hex char into AL
3C 39 CMP AL, '9' ; is char an alpha (a-f)?
7E 02 JLE NOHEX_IN ; if not, is numeric
2C 27 SUB AL, 'f'-'9'-6 ; otherwise ASCII adjust a-f
NOHEX_IN:
2C 30 SUB AL, '0' ; ASCII to decimal convert
F6 D0 NOT AL ; complement the color (magic happens here)
3C F9 CMP AL, 0F9H ; is char <= 9?
76 02 JBE NOHEX_OUT ; if not, is numeric
04 27 ADD AL, 'f'-'9'-6 ; otherwise ASCII adjust a-f
NOHEX_OUT:
04 40 ADD AL, '0'+10H ; decimal convert to ASCII
CD 29 INT 29H ; write char to console
E2 E9 LOOP INLOOP ; keep looping
C3 RET ; return to DOS
```
So nearly all of this code is brute-force conversion from an ASCII hex string into a numeric value and then back again. No CPU instructions on x86-16 to help with that I'm afraid!
**I/O:**
Standalone PC DOS executable. Input via command line, output to `STDOUT`.
[![enter image description here](https://i.stack.imgur.com/TcdFJ.png)](https://i.stack.imgur.com/TcdFJ.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r\wÈnG'nF
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clx3yG5HJ25G&input=IiM3ZjdmODAi)
```
r\wÈnG'nF :Implicit input of string
r :Replace
\w : RegEx /[0-9a-z]/gi
È : Pass each match through the following function
n : Toggle base
G : 16
'n : Subtracting intermediate result from
F : 15
```
[Answer]
# Pyth, ~~20~~ 19 bytes
*[1 byte](https://codegolf.stackexchange.com/questions/68305/complementary-colors/68307?noredirect=1#comment165760_68307) thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor).*
```
%"#%06x"-t^8 8itz16
```
[Try it online.](http://pyth.herokuapp.com/?code=%25%22%23%2506x%22-t%5E8+8itz16&input=%23badcab&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=%25%22%23%2506x%22-t%5E8+8itz16&test_suite=1&test_suite_input=%23ffffff%0A%23abcdef%0A%23badcab%0A%23133742%0A%23a1b2c3%0A%237f7f80&debug=0)
### Explanation
* `z` is the input
* `tz` removes the `#`
* `itz16` parses as a hexadecimal number
* `t^8 8` calculates 88 - 1
* `-t^8 8itz16` calculates 88 - 1 - input
* `%"#%06x"-t^2 24itz16` formats it into a zero-padded 6-character hex string and adds the `#`
[Answer]
# Java, ~~95~~ 90 bytes
```
String f(String v){return v.format("#%06x",0xFFFFFF^Integer.parseInt(v.substring(1),16));}
```
Bitwise XOR.
[Answer]
# Haskell, 85 bytes
My first submission, it will probably be the longest (85 bytes) but hey, you got to start somewhere.
In Haskell:
```
import Numeric;f=('#':).concatMap((flip showHex)"".(15-).fst.head.readHex.(:[])).tail
```
It's using the same subtract from 15 trick I saw other people use.
I also tried using printf along with the other trick (subtract 8^8 - 1) and it works in ghci but for some reason it doesn't compile:
```
g=printf "#%06x" .(8^8-1-).fst.head.readHex.tail
```
If someone could make this work that would be great!
[Answer]
# Mathematica, ~~69~~ 60 bytes
```
"#"<>IntegerString[8^8-#~StringDrop~1~FromDigits~16-1,16,6]&
```
Once again, it's the string processing that kills me here.
[Answer]
# C, 94 bytes
```
t(char*b){for(int i;i=*b;++b)*b=i>96&i<103?150-i:i>64&i<71|i>47&i<54?118-i:i>53&i<58?111-i:i;}
```
Function takes in a char array, returns inverse value. Produces uppercase letters for response. The code flips each ASCII hex character to its inverse if it's valid, ignores it otherwise.
[Answer]
# ùîºùïäùïÑùïöùïü 2, 18 chars / 34 bytes
```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=%23ffffff&code=%C3%AF%C4%93%2F%5Cw%E2%8C%BF%2C%E2%86%AA%28%E1%B8%8F-%60%E1%B6%8D%E2%A6%83%24%7D%E2%80%9D%E2%93%A7)`
Using a version created after the challenge.
# Explanation
```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ // implicit: ï=input, ḏ=15
ïē/\w⌿, // replace all alphanumeric chars in ï with:
↪(ḏ-`ᶍ⦃$}”ⓧ // (15 - char's decimal form) converted to hex
// implicit output
```
# Non-competitive solution, 15 chars / 29 bytes
```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ
```
Uses transliteration.
[Answer]
## sed, 48 bytes
```
y/0123456789ABCDEFabcdef/fedcba9876543210543210/
```
Or 36 bytes if you only need to support one case.
[Answer]
## Python, 96
```
x=input()
print("#")
for i in range(3):
print(hex(255-int(x[(1+2*i)]+x[(2+2*i)],16))[2:4])
```
First code golf, please give opinions :)
[Answer]
# [Befunge](https://esolangs.org/wiki/Befunge)-[98](https://esolangs.org/wiki/Funge-98), 37 bytes
```
~,v>v
~f<^ s
>,^ >-:9w>'0+
^+W' ]^
```
This takes input in lowercase, outputs the answer in lowercase, then enters an infinite loop.
[Try it online!](https://tio.run/##S0pNK81LT9W1tPj/v06nzK6Mqy7NJk6hmMtOJ07BTtfKstxO3UCbK047XF0BCGLj/v9XTjRMMko2BgA "Befunge-98 (FBBI) – Try It Online")
[40 byte version that terminates](https://tio.run/##S0pNK81LT9W1tPj/v06nzK6MSyHNJk6huM5BmctOJ07BTtfKstxO3UCbK047XF0BCGLj/v9XTjRMMko2BgA)
## Explanation
```
~,v
```
This gets the first character of the input (which is always `#`), outputs it unchanged, and enters the loop.
```
~f< s
```
At the start of the loop, `f` pushes `15` onto the stack, `~` gets the next character of the input, and `s` puts that character one space to its left in the source code (without executing it).
```
>v
^I
```
(I'm using `I` to represent the character from the input that is now in the source code.) This section loops back around to execute that character. Every character in the range `0-9` or `a-f` pushes the corresponding hex value on the stack.
```
>-:9w
```
The hex value is subtracted from `15` (the previous top of the stack) to get its complement. `:9w` creates a copy of the complement, and compares the copy with `9`, with the IP going down, up or right depending on whether it is greater, less than, or equal.
```
>
]^
```
If the complement is greater than 9, the IP goes down and hits the `]` ("turn right") from above, turning to move left. If the copy was less than 9, the IP goes up and hits the `]` from below, turning to move right. In that case, it gets redirected back to the third line. If the copy was exactly 9, the IP goes right and hits the `>` immediately.
```
'0+
```
If the complement is less than or equal to 9 (i.e. a digit), it is added to ASCII 48 (`0`) to produce the correct digit.
```
^+W'
```
If the complement is greater than 9, it is added to ASCII 87 (`W`) to produce the correct character (in the range `a-f`).
```
<
>,^
```
In all cases, the character corresponding to the complement is printed and the IP moves back to the start of the loop.
The loop repeats, outputting the complement of every hex digit in the input.
After we print the answer, the input has been completely used up. Once EOF is reached, `~` reflects the IP. This means that `~f<` is now an infinite loop that pushes `15` on the stack forever. This doesn't produce any effects (except for possibly crashing), so we don't care about it.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~53~~ 49 bytes
```
p(*s){printf("#%06x",0xffffff-wcstol(s+1,0,16));}
```
[Try it online!](https://tio.run/##S9ZNzknMS///v0BDq1izuqAoM68kTUNJWdXArEJJx6AiDQx0y5OLS/JzNIq1DXUMdAzNNDWta//nJmbmaWhWcykoFGj4KClDVCppWheUlhRrKAEZMJnEpOSUVKwySYkpyYlJ2GQMjY3NTYywmmaYZJRsjE3GPM08zcIARab2PwA "C (clang) – Try It Online")
-4 thanks to @jdt
[Answer]
# [Julia 1.0](http://julialang.org/), 46 bytes
```
h->'#'repr(~parse(UInt,h[2:7];base=16))[13:18]
```
[Try it online!](https://tio.run/##fcy9bsMgFIbh3VdxFIaAlEYG7BglIqOlXkCnKAN/VkAWtbArZYh66y6mnfuND@clfI1e0efay/Xxdt2jfXJTwt@TSrPDH@9xOTxu7NzdL1rNTtITITfKz1Tc1@EzAfYHCAR8hHka/XLEySk7@uhmTEgFeT32RMoArxdMyccF756wI1DeCowRe5DXcvjnPc5/Sgn@3yr8VmGrXLQrGsoAUF1WIaWNdRu0DWc0g1bWKJ2haRlvmwpRzruGZXDGCG1zQjUzfEtcY7mpUDd0g6gziFrU3fAD "Julia 1.0 – Try It Online")
# [Julia 0.6](http://julialang.org/), 40 bytes
```
h->"#"hex(~parse(UInt,h[2:7],16))[11:16]
```
[Try it online!](https://tio.run/##fczNboQgFIbhvVdxIhtInEZAxUzCLE16AV1NZoH8RIihRm0yi0lv3SLtut/y4byEr9mr7hjkMV1uJSon@8Tfi1o3iz/e415Nd3YVj4p2hNwpvdLucbjPFbCvIBDwEbZl9vsbXq0ys492w4QUkDZgT6QM8HrBsvq44/IJJYH8lmGO2IO85cM/H3D6U0rw/1bhtwpnZaM5kMsDQHVegdSojT2hbTijCUZltBoTNC3jbVMgyrloWAKrdT@alNCRaX4mtjFcF0g44fo6QV/3tXA/ "Julia 0.6 – Try It Online")
Simply a bitwise not (`~`) on the full number, in hex, the rest around is to parse and print the numbers in hexadecimal and keeping the last 6 numbers
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 8 bytes (16 nibbles)
```
`($+.$hex- 15hex
```
```
`($+.$hex- 15hex
`($ # output the first element of input (the '#')
# and save the rest;
.$ # now, map over the rest
hex # convert from hex,
- 15 # subtract from 15,
hex # and convert back to hex
+ # and convert the resulting list of characters to a string
# (which is implicitly output after the '#')
```
[![enter image description here](https://i.stack.imgur.com/DfKV6.png)](https://i.stack.imgur.com/DfKV6.png)
[Answer]
# [Go](https://go.dev), 111 bytes
```
import(."strconv";."fmt")
func f(s string)string{n,_:=ParseInt(s[1:],16,64)
return Sprintf("#%06x",0xffffff-n)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LZBLasMwEIbX1SkGmYAFSvArtklJl4XuAl22JZFlyZg04yApJRBykm5CocfoprfobSo_ZjPwzfwz88_nV9Pdfo5C7kWj4CBaJO3h2Bm3oNaZFhtLv09Oz8u_buThUJAdftD7BdUHRxnRJ5SgQwujhI3pgny7Wm-EseoJXWhf4tUbj3OeZ4wY5U4G4fnoG50OaTCL8jPl0VkPMUd2ndb-DsP7w0IGFyKFVRZWa3hs1Xttw10wKgCCaAgSiErWqgfLLE1iDypRS1F5kC2TdJmRIE7TIks8UFKWVe0lcZXItJeorE4lCQpd6DLyoIzKqNA777EzsOXYrzYC_a_GSy7kbjN5mFmYP8DMviLlgNw_BBkjVzI5ud3G_A8)
[Answer]
# CJam, 16 bytes
```
qA,'G,65>+s_W%er
```
This is fairly long because CJam handles base changes differently, so it was shorter to just do transliteration. See my [Retina answer](https://codegolf.stackexchange.com/a/68308/29750) for more on transliteration.
[Try it online.](http://cjam.aditsu.net/#code=qA%2C'G%2C65%3E%2Bs_W%25er&input=%23A1B2C3)
### Explanation
```
q e# Get the input
A, e# Push [0 1 ... 8 9]
'G,65> e# Push "ABCDEF"
+s e# Combine and convert to string
_W% e# Make a copy and reverse it
er e# Replace each character in the first string with
e# the corresponding character in the second
```
[Answer]
# Python 3, 44 bytes
Originally I used `256^3`, then `16^6`. Then I saw Pietu1998's `8^8` and now this solution uses that instead.
```
"#{:06x}".format(8**8-1-int(input()[1:],16))
```
[Answer]
## Bash + tr, 35 bytes
```
tr 0-9A-Fa-f fedcba9876543210543210
```
Output is always lowercase.
Unfortunately "tr" does not take ranges in reverse order so I had to spell them out.
[Answer]
## C, 147 bytes
```
void p(char s[]){char c[3];int i=1;printf("#");while(i<6){strncpy(c,s+i++,2);i++;int x=255-strtol(c,NULL,16);x<10?printf("0%x",x):printf("%x",x);}}
```
Used strtol to convert from hex string to int then subtracted the number from 255 to get the compliment like the original post said. I am, however, wondering if there is a way to pass a range of characters from s to strtol so I don't have to waste a bunch of bytes copying to a new string?
] |
[Question]
[
My little kid has a toy like this:
[![Stacked](https://i.stack.imgur.com/lghyLm.jpg)](https://i.stack.imgur.com/lghyLm.jpg)
This toy consists of 10 stackable little buckets, that we are going to number from 1 (the smallest one) to 10 (the biggest one). Sometimes he makes small piles and the toy ends up like this:
[![Scattered](https://i.stack.imgur.com/n43Knm.jpg)](https://i.stack.imgur.com/n43Knm.jpg)
We can represent schematically the piles like this:
```
1 6
4 9 2 7
5 10 3 8
---------- <-- Floor
1 2 3 4 <-- Pile #
```
Or, put it another way:
```
[[4,5],[9,10],[1,2,3],[6,7,8]]
```
This set of bucket piles is easily restackable to rebuild the original set (the first image) just by consecutively placing piles of smaller buckets inside piles of bigger buckets:
```
1 1 6
2 2 7
1 6 3 6 3 8
4 9 2 7 4 9 7 4 9
5 10 3 8 5 10 8 5 10
---------- > [Pile 3 to 1] > ---------- > [Pile 4 to 2] > ---------- > [Pile 1 to 2] > Done!
1 2 3 4 1 2 3 4 1 2 3 4
```
Nonetheless, sometimes my kid tries to build towers, or throws buckets away, and the piles end up being inconsistent and the original set cannot be rebuild just by placing one pile inside another. Examples of this:
```
[[1,3,2],[4]] (the kid tried to build a tower by placing a bigger bucket
over a smaller one, we would need to reorder the buckets
first)
[[1,3,4],[2]] (the kid left aside an unordered bucket, we would need to remove
bucket #1 from pile #1 before restacking)
[[1,2,3],[5]] (the kid lost a bucket, we need to find it first)
```
### Challenge
Given a list of lists of integers representing a set of bucket piles, return a truthy value if the lists represent an easily restackable set of piles, or falsey in any other case.
* Input will be given as a list of lists of integers, representing the buckets from top to bottom for each stack.
* There won't be empty starting piles (you won't get `[[1,2,3],[],[4,5]]` as input).
* The total number of buckets can be any within a reasonable integer range.
* My kid only has one set of buckets so there won't be duplicate elements.
* You can select any two consistent (and coherent) values for truthy or falsey.
* The buckets will be labelled from #1 to #N, being `N` the largest integer in the lists of integers. My kid still does not know the concept of zero.
* You may receive the input in any reasonable format as long as it represents a set of piles of buckets. Just specify it in your answer if you change the way you receive the input.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win!
### Examples
```
Input: [[4,5],[9,10],[1,2,3],[6,7,8]]
Output: Truthy
Input: [[6,7,8,9,10],[1],[2],[3,4,5],[11,12,13]]
Output: Truthy
Input: [[2,3,4],[1],[5,6,7]]
Output: Truthy
Input: [[1,2],[5,6],[7,8,9]]
Output: Falsey (buckets #3 and #4 are missing)
Input: [[2,3,4],[5,6,7]]
Output: Falsey (bucket #1 is missing)
Input: [[1,3,4],[5,7],[2,6]]
Output: Falsey (non-restackable piles)
Input: [[1,4,3],[2],[5,6]]
Output: Falsey (one of the piles is a tower)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes
*Thanks to @Lynn for saving 1 byte.*
```
ṢFµJ⁼
```
[Try it online!](https://tio.run/##y0rNyan8///hzkVuh7Z6PWrc8/9w@6OmNf//RysoREeb6JjG6kRb6hgaAClDHSMdYyBtpmOuYxEbq8PFBVIC5unAlACxERAb60B0GhrqGBrpGBrDVQNN0DGBKjTVAeoFySigSMGFwaJASyFiQBJsEZIMTL05yFagCoSMCdihMJ2xsQA "Jelly – Try It Online") (comes with test-suite footer)
### Explanation
```
ṢFµJ⁼ Main link. Argument: piles
Ṣ Sort the piles by the size of the top bucket.
F Stack the piles, putting the left one to the top.
J See what a full pile with this many buckets would look like.
⁼ See if that looks like the pile you built.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~53~~ 52 bytes
*Thanks for the byte xnor*
```
lambda x:sum(sorted(x),[0])==range(len(sum(x,[]))+1)
```
[Try it online!](https://tio.run/##XY7NDoJADITvPgXHbZwDXcC/hCdZ94AB1AQWApjg068VJAYObZN@M9O27@HROO3L9OqrrL7lWTBe@let@qYbilyNBBNaStMuc/dCVYVTXzrCWKI9k2@7pxuCUhkTI7EwZ3Aog6ERyTzgiJO1tPvrphUWnZSWijDbmcEaHK0tkoX4p04gAWssx2Ygfcre4tmdiE@uiWyD4@nVJcOS/wA "Python 2 – Try It Online")
[Answer]
## JavaScript (ES6), ~~59~~ 58 bytes
```
a=>!(a.sort((a,[b])=>a[i=0]-b)+'').split`,`.some(v=>v-++i)
```
### Explanation
```
a=> // given a 2D-array 'a'
a.sort((a,[b])=>a[i=0]-b) // sort by first item
+'' // flatten
( ).split`,` // split again
.some(v=>v-++i) // i such that a[i] != i+1?
! // true if none was found
```
### Test cases
```
let f =
a=>!(a.sort((a,[b])=>a[i=0]-b)+'').split`,`.some(v=>v-++i)
// truthy
console.log(f([[4,5],[9,10],[1,2,3],[6,7,8]]))
console.log(f([[6,7,8,9,10],[1],[2],[3,4,5],[11,12,13]]))
console.log(f([[2,3,4],[1],[5,6,7]]))
// falsy
console.log(f([[1,2],[5,6],[7,8,9]]))
console.log(f([[2,3,4],[5,6,7]]))
console.log(f([[1,3,4],[5,7],[2,6]]))
console.log(f([[1,4,3],[2],[5,6]]))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
{˜āQ
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/@vScI42B//9HRxvqKBjF6ihEm@oomIFocx0FCx0Fy9hYAA "05AB1E – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
import Data.List
f l=(sort l>>=id)==[1..length$l>>=id]
```
[Try it online!](https://tio.run/##VY7LDoIwEEX3fAULFpBMiOUhmlhWLvmDpotGijaWirR@fx0oxLiYR8/c25mHsE@ptfdqnF6zi6/CibxT1kVDrGlqF6bblqo@o5SRPNfS3N0jCYz7UShDrXx/pLnJdJai78wlWYQNz1Azzcq4fBRTPHjGKqg5sDOQAxYCBZRYj9DAifOIhQ72MUaBUUJwEQKkAFKuSnRCtYlqQN8f/RHcEd6Y1783uuuaZQlOA63We3YHj/wX "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
import Data.List
(<[1..]).concat.sort
```
[Try it online!](https://tio.run/##VY7LDoMgEEX3foWLLjSZkOKjtom66tI/ICyIxZRU0Ar9fjqKpuliHtw5l5mnsC85jt4rPU@Li@/CCdIp66KhSWpGCeEp6SfTC0csAl4LZRor3x9pepksUjw6U59WsOJp2zbzoowjWszx4BkroOTAbkDPWChkkGO9QAVXziMWOjjGGBlGDsFFKdAMaL6R6IRih0pA35/6U3BHeGPe/t7Vg6vWJTgNarHdczh45L8 "Haskell – Try It Online")
Checks whether the concatenated sorted list is lexicographically smaller than the infinite list `[1,2,3,...]`. Since there are no duplicates, any missing bucket or out-of-order bucket would cause a value greater than `k` in the `k`'th place, making the resulting list be bigger..
[Answer]
# Pyth, 6 bytes
```
UItMsS
```
[Try it here.](http://pyth.herokuapp.com/?code=UItMsS&input=%5B%5B6%2C+7%2C+8%2C+9%2C+10%5D%2C+%5B1%5D%2C+%5B2%5D%2C+%5B3%2C+4%2C+5%5D%2C+%5B11%2C+12%2C+13%5D%5D&debug=0)
Explanation:
```
UItMsSQ
UI Invariant from U (range(len(A)) for our purpose)
tM Map t (A - 1 for our purpose)
s s (flatten 1-deep for our purpose)
S S (sort for our purpose)
Q Q (autoinitialized to input) (implicit)
```
[Answer]
# PROLOG (SWI), 54 bytes
```
s(L):-sort(L,M),flatten(M,N),last(N,O),numlist(1,O,N).
```
Now *that's* better. Still quite verbose, alas.
[Try it online!](https://tio.run/##pZHLDoIwEEX3foVh1SYXYnmIjxh/gMcHEBYswJBUMG0Jn48DiHvrYjqZae6ZO@1L9bJ/uHpsp0mzhF9c3SvDEqQcjayMqTuWIuOQlTYsQ87RDU/ZUiGQ04U33d3kVhQhohLFGeJAScBHQPmIGKeyxJ7NbIyqNbXsmGPUUDv8@q2bSmpqcG@3whYdNhiFTxFgnSEEhA8RWHDJFcIPMgJNsWDQbquazsXlHz7sPWz6eH4c8mLDCJc/2rb5gTC9AQ "Prolog (SWI) – Try It Online")
The `s/1` predicate takes a list as argument and is true if the list is a list of easily stackable buckets.
Improvement in algorithm: if I sort the list *before* I flatten it, this forces all the sublists to be sorted for the predicate to be true. Slightly "borrowed" from [Pietu1998's Jelly answer](https://codegolf.stackexchange.com/a/137508/71426). Thanks to that I can dump the `forall` which is more than half of the program (see below for the original answer).
## How does it work?
The predicate is true if all of its clauses are true:
```
s(L) :-
sort(L,M), % M is L sorted in ascending order
flatten(M,N), % N is the 1-dimention version of M
last(N,O), % O is the last elemnt of N
numlist(1,O,N). % N is the list of all integers from 1 to O
```
## Previous answer, PROLOG (SWI), 109 bytes
```
s(L):-flatten(L,M),sort(M,N),last(N,O),numlist(1,O,N),forall(member(A,L),(A=[B|_],last(A,C),numlist(B,C,A))).
```
[Try it online!](https://tio.run/##nZDLasNADEX3@YqSlQTXoeNH@iIUJ1sn@QBjigvjYhjbZWZCNvl3R/E07bpeaIRG3KMrfdvBDF@RO7fj6Kjg16gxtfe6pwJ7hhuspz0ODFM7TwccGf2pM60UCsdboxlsbQx1uvvUlnIUDMo35fbyUQVRjt2faIsdcmZeje9RsSnLFFmF8gXqUZJCjETyGk94rio80M0Szrb12vS09Pakl/z2Wze1cfLBq0WATTrcYRKxRIIwQymoGCqZwRVXSH@QGWTKDIbsFtTyTi5nMYKPTBzIcsKaw0inG9/d/IMwXgE "Prolog (SWI) – Try It Online")
[Answer]
# [Pyth](http://pyth.readthedocs.io), ~~9 16~~ 11 bytes (Fixed)
Uses a completely different method from the other answer. A shorter, 7-byte approach can be found below.
```
!.EtM.++0sS
```
**[Test Suite.](http://pyth.herokuapp.com/?code=%21.EtM.%2B%2B0sS&input=%5B%5B4%2C5%5D%2C%5B9%2C10%5D%2C%5B1%2C2%2C3%5D%2C%5B6%2C7%2C8%5D%5D&test_suite=1&test_suite_input=%5B%5B4%2C5%5D%2C%5B9%2C10%5D%2C%5B1%2C2%2C3%5D%2C%5B6%2C7%2C8%5D%5D%0A%5B%5B6%2C7%2C8%2C9%2C10%5D%2C%5B1%5D%2C%5B2%5D%2C%5B3%2C4%2C5%5D%2C%5B11%2C12%2C13%5D%5D%0A%5B%5B2%2C3%2C4%5D%2C%5B1%5D%2C%5B5%2C6%2C7%5D%5D%0A%5B%5B1%2C2%5D%2C%5B5%2C6%5D%2C%5B7%2C8%2C9%5D%5D%0A%5B%5B1%2C3%2C4%5D%2C%5B5%2C7%5D%2C%5B2%2C6%5D%5D%0A%5B%5B1%2C4%2C3%5D%2C%5B2%5D%2C%5B5%2C6%5D%5D%0A%5B%5B2%2C3%2C4%5D%2C%5B5%2C6%2C7%5D%5D&debug=0)**
---
# Explanation
```
!.EtM.++0sSQ -> Full program, with implicit input at the end.
SQ -> Sort the input by the highest element in each sublist.
s -> Flatten.
+0 -> Prepend a 0.
.+ -> Get the deltas of the list (i.e. differences between consecutive elements)
tM -> Decrement each element.
.E -> Any truthy element (1s are truthy, 0s are falsy)
! -> Negate (to have coherent truthy / falsy values)
```
# How does this work?
Let's take a couple of examples, which make it easier to understand. Let's assume the input is `[[1,3,4],[5,7],[2,6]]`. The core of this algorithm is that each delta in the unflattened list must be *1* in order for the buckets to be stackable.
* First off, `S` turns it into `[[1, 3, 4], [2, 6], [5, 7]]`.
* Then, `s` flattens it: `[1, 3, 4, 2, 6, 5, 7]`.
* Prepend a `0` in front: `[0, 1, 3, 4, 2, 6, 5, 7]`
* `.+` gets the deltas of the list, `[1, 2, 1, -2, 4, -1, 2]`.
* `tM` decrements each element, `[0, 1, 0, -3, 3, -2, 1]`.
* Any non-`0` integer is truthy in Pyth, so we check if there is any truthy element with `.E` (which means the stack cannot be formed correctly). We get `True`.
* `!` negates the result, which turns `True` into `False`.
If the input was, for example, `[[6,7,8,9,10],[1],[2],[3,4,5],[11,12,13]]`, the algorithm would work this way:
* Sorted by the highest element: `[[1], [2], [3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]` and flattened, with a `0` prepended: `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]`.
* Deltas: `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]`. All get decremented: `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`.
* There is no truthy element, so we get `False`. By logical negation, the result is `True`.
---
# [Pyth](http://pyth.readthedocs.io), 7 bytes
```
qSlsQsS
```
**[Test Suite.](http://pyth.herokuapp.com/?code=qSlsQsS&input=%5B%5B4%2C5%5D%2C%5B9%2C10%5D%2C%5B1%2C2%2C3%5D%2C%5B6%2C7%2C8%5D%5D&test_suite=1&test_suite_input=%5B%5B4%2C5%5D%2C%5B9%2C10%5D%2C%5B1%2C2%2C3%5D%2C%5B6%2C7%2C8%5D%5D%0A%5B%5B6%2C7%2C8%2C9%2C10%5D%2C%5B1%5D%2C%5B2%5D%2C%5B3%2C4%2C5%5D%2C%5B11%2C12%2C13%5D%5D%0A%5B%5B2%2C3%2C4%5D%2C%5B1%5D%2C%5B5%2C6%2C7%5D%5D%0A%5B%5B1%2C2%5D%2C%5B5%2C6%5D%2C%5B7%2C8%2C9%5D%5D%0A%5B%5B1%2C3%2C4%5D%2C%5B5%2C7%5D%2C%5B2%2C6%5D%5D%0A%5B%5B1%2C4%2C3%5D%2C%5B2%5D%2C%5B5%2C6%5D%5D%0A%5B%5B2%2C3%2C4%5D%2C%5B5%2C6%2C7%5D%5D&debug=0)**
Port of the Python answer and a variation of [@Erik's solution](https://codegolf.stackexchange.com/a/137520/59487).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
oc~⟦₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/Pz@57tH8ZY@aGv//j4420zHXsdCx1DE0iNWJNgRiIyA21jHRMQXxDXUMjXQMjWNjAQ "Brachylog – Try It Online")
Explained unifications:
```
?o₀c₀~⟦₁.
? The input (implicit)
o₀ Sorted (subscript default = 0 => ascending)
c₀ Concatenated (subscript default = 0 => no length check)
~ Inverse (find the input)
⟦₁ Range (subscript = 1 => [1..input])
. The output (implicit)
```
Analytical explanation:
First of all we sort the list of lists, and then we concatenate (i.e. flatten 1-deep) (`oc`) so that the buckets get stacked right-to-left if possible. Then, to check if the buckets have been stacked correctly (i.e. no missing buckets or towers), we check that the resulting list is an inclusive range from 1 to its length. Now, instead of equal-checking the list with the [1..n] range of its length (`{l⟦₁?}`), we try to find an input to a function that generates such a range (`~⟦₁`), if there is one. If an input is found, then the program ends with no issues, so it triggers a `true.` status. If no input is found, the program fails, triggering a `false.` status.
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda l:sum(sorted(l),[0])<range(len(`l`))
```
[Try it online!](https://tio.run/##XU5LCoMwEN33FC4TeAsTtT/ak6QBLca2EKNouujp0yGpFF28GZj3m/Hjn4OTobvegm36e9tk9jy/ezYPkzctsxwq1/wyNe5hmDWO1bbmPIzTy/msY0qVqDTUCSKnJSBR0N7jgKPWfPfXxRMWHUESCiS7EBASolhbKAvlT12BAtY0lSWCZsze0sldkY/aSLahy/jqkqF5@AI "Python 2 – Try It Online")
Checks whether the concatenated sorted list is lexicographically smaller than `[1,2,3,...N]` for large `N`. Since there are no duplicates, any missing bucket or out-of-order bucket would cause a value greater than `k` in the `k`'th place, making the resulting list be bigger. The string-length of the input suffices as an upper bound since each numbers takes more than 1 character.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
Sgtf=
```
[Try it online!](https://tio.run/##y00syfmf8D84vSTN9r@9gnpJUWlJRqU6V616WmJOcWqleiyXS8j/6mgTHdNYnWhLHUMDIGWoY6RjDKTNdMx1LGJruapBIkC@qY4ZkASK6ViCRYGqdExA6iFyOuZQtRBRUyBfB6jGLLZWAQA "MATL – Try It Online")
(Implicit input, say `{[4,5],[9,10],[1,2,3],[6,7,8]}`)
`S` - sort input arrays in lexicographic order (`{[1,2,3],[4,5],[6,7,8],[9,10]}`)
`g` - convert into a single array (`cell2mat`)
`t` - duplicate that
`f` - find indices of non-zero values. Since input here is all non-zeros, returns the list of indices from 1 to length(array) (`[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]`)
`=` - check that the array is equal to the range 1 to length(array)
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~13~~ ~~12~~ 11 bytes
This could probably be shorter.
```
ñÎc äaT e¥1
```
* 1 byte saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions)
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c5jIORhVCBlpTE=&input=W1s2LDcsOCw5LDEwXSxbMV0sWzJdLFszLDQsNV0sWzExLDEyLDEzXV0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=8c5jIORhVCBlpTE=&input=WwpbWzQsNV0sWzksMTBdLFsxLDIsM10sWzYsNyw4XV0KW1s2LDcsOCw5LDEwXSxbMV0sWzJdLFszLDQsNV0sWzExLDEyLDEzXV0KW1syLDMsNF0sWzFdLFs1LDYsN11dCltbMSwyXSxbNSw2XSxbNyw4LDldXQpbWzIsMyw0XSxbNSw2LDddXQpbWzEsMyw0XSxbNSw3XSxbMiw2XV0KW1sxLDQsM10sWzJdLFs1LDZdXQpdLW1S)
---
## Explanation
```
:Implicit input of 2D array `U`
ñÎ :Sort sub-arrays by their first element
c :Flatten
T :Prepend 0
äa :Consecutive absolute differences
e¥1 :Does every element equal 1?
```
[Answer]
## Scala, 49 Bytes
```
p=>{val s=p.sortBy(_(0)).flatten
s==(1 to s.max)}
```
Ungolfed:
```
piles: List[List[Int]] =>
{
val sorted = piles.sortBy(pile=>pile(0)).flatten //Since piles are sequential, we can sort them by their first element
sorted == (1 to sorted.max) //If all the buckets are present and in order, after sorting them it should be equivalent to counting up from 1 to the max bucket
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 bytes
```
ñg c
eUÌõ
```
[Try it online!](https://tio.run/##y0osKPn///DGdIVkrtTQwz2Ht/7/Hx1tqGOsYxKrE22qYw4kjXTMYmMB "Japt – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 58 bytes
```
function(v,a=unlist(v[order(sapply(v,min))]))any(a-seq(a))
```
[Try it online!](https://tio.run/##lZBLi8IwFIX3/RUBN7lwRyatHR/gYgZ0JS58rMRFJqZQpk1rU0V/fU2q1uJrNIt7Q27ynZOTFUG/CDZK5GGi6BZ5f6OiUOd0u0iylcyo5mka7c0kDhXAEoCrPeUfWq4pBygaZNz8aZIeGX6PpgMSS640yaTOufjjv5FEMpvMz@cqUfWZ4zgBLcUEbaEPKGgX2aftDF307OYL29gBAFJfDSJ3qRS5XB1lL5jyOlYUW1xbPDwJMIbMReZZ5GOMEcdWRfDRYK89vOLG/OL03rbS2UsYG9kdM//4eE5hF0q7jMWYet8LMzl6Var@M8YtxSkO "R – Try It Online")
N.B. : FALSE is the truthy outcome, TRUE is the falsy one
* -3 bytes thanks to @JayCe
Explanation :
```
a=unlist(v[order(sapply(v,min))]) # order the list of vector by the min value and flatten
all(a==seq(a=a)) # if the flattened list is equal to 1:length then it's ok
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~157~~ ~~145~~ 132 bytes
*-13 bytes thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder)*
```
l=>{var k=l.OrderBy(x=>x[0]).SelectMany(x=>x);return!Enumerable.Range(1,k.Count()).Zip(k,(x,y)=>x==y).Any(x=>!x);}
```
Byte count also includes
```
using System.Linq;
```
[Try it online!](https://tio.run/##bVLfT9swEH5e/grDS53JWE2BMdSlGkPAC2gToCEt5MFNj9bCdTrbgVaof3t3tsm2UE7yr/N33919dmX3qtrAprFST8nNyjqY89NaKaicrLXlF6DByGqYdBCXUv9@47qFpePXMG2UMGfLhQFrPcEw0WIOdiEqeEUmLwlBq5SwlpyEffR4s044WZGnWk7IlZCapn@v/oG8dQ7nja6@XErr4iS1G40YGde1GpEHkm9UPnp5EoY85op/NxMw31Z0mY@WRb9M@Q34Zq@Ejr50aMA1Ru@c6WYORowV8Guhp0Az9ojSNNrRNOW/5II@MrpkqxSD8nyV8pPIsIMU680w@RD7MV4jqReNG3Zqfp5JBYTScEVycopi1T4XiAnKC5iE7OREN0qlncCuDt58awobRxYNz@SNEDQdbkW0ScPKb42cUxSiGcdysdPXm0vQUzcje2SAJFss@NqwJCbMMXXw0K@79wUt@nvHjJQf0/ty950KfM1z4aoZWIwNHPwqnqMk78Q84E8V1YzQAIzhWGjLk24FePPC8JPJhAYUvzB1s7BFVvKfQjXAbxZKOtpjPUZ6pJfyuxkYoGJckXxEcGklGJF@@1XaW1SX/xDGBjh@idvai47vhlJtldI@752RDsL7PlBfWvqmz3XS3a2T9aYoDthhyYpjlvVxydiA7eP6iR2xz2WZFHHH2mscAxz7LEZlGcsGLNsPSIxkB6@gQ4ZxwYuM8YxzYOpg/8e1niOfBPHRexDqaTnKPw "C# (.NET Core) – Try It Online")
Ungolfed:
```
l => {
var k = l.OrderBy(x=>x[0]) // First, sort stacks by first bucket
.SelectMany(x => x); // Concatenate stacks into one
return !Enumerable.Range(1, k.Count()) // Create a sequence [1...n]
.Zip(k, (x, y) => x == y) // Check if our big stack corresponds the sequence
.Any(x => !x); // Return if there were any differences
};
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 11 bytes
```
{$:+:(_,,=}
```
[Try it online!](https://tio.run/##S85KzP1fWPe/WsVK20ojXkfHtvZ/3f/oaDMFcwULBUsFQ4NYhWhDIDYCYmMFEwVTEN9QwdBIwdA4NhYA "CJam – Try It Online")
Oww `:(`...yeah! `{$:+_,,:)=}`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes (non-competing?)
```
A▷m⟦▷s▷vθυ⟧θ⁼θ…·¹Lθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9noWPpm3PfTR/GZAqBuKyczvOtz6av/zcjkeNe4BEw7JD2w/tfL9nzbkd//9HR0eb6SiY6yhY6ChY6igYGsTqKEQbgggjEGGso2Cio2AKFjQEShsBsXFsbCwA "Charcoal – Try It Online")
-10 bytes thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only).
-3 bytes thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for a subsequent implementation (see revision history for possibly competing version).
`-` for truthy, for falsy.
Input is a singleton list of a list of lists, because of how Charcoal takes input.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
sf₅ɾ⁼
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=sf%E2%82%85%C9%BE%E2%81%BC&inputs=%5B%5B3%2C4%5D%2C%5B1%2C2%5D%2C%5B5%2C6%5D%5D&header=&footer=)
```
s # Sort
f # Flatten
₅ɾ # 1...a.length
⁼ # Is equal?
```
[Answer]
# Java 10, 213 bytes
```
import java.util.*;m->{Arrays.sort(m,(a,b)->Long.compare(a[0],b[0]));var r=Arrays.stream(m).flatMapToInt(Arrays::stream).toArray();return Arrays.equals(r,java.util.stream.IntStream.range(1,r.length+1).toArray());}
```
[Try it online.](https://tio.run/##rVLBTuMwEL33K@Zos1ND2kLZRiDtZaWVgAvcqh6mwZSU2M46DquqyreXIQkQWgGiWimy/DyZ9@Y9e0mP1F/ePmxSkzsfYMlYlSHN1EHcSzIqCrik1K57AKkN2t9RouHqGQLMncs0WUgEl6az6QyMjLlS9XgpAoU0gSuwcAYb0z9f//KeVoUqWEYYFIRz2T@/cHahEmdy8lrQ9GiGc16kjGtKf/bSFLwmI4xUdxmFS8pv3B8bRFOdTJqyVMHVJ0LGXofSW2jb9d@SskJ4fLPXtChmuW52nuxCiwi9yrRdhPsfUYdPxtXm2Rp/eTnP2Fjr79Glt2A4IcE0qV1wCCSbeA4P4caX4X41qeH1qgjaKFcGlfOfIbPCqkRY/Q/a@Nav@/UIjyt8gz8xOuriCAc47B6c4BhPq0rW@X9Tq@7FHYkuGHTBELemiyKMBhgN99RnKzj6UPoYeb5PmdvKS@a/@ab1PplzqFvCXVhn9L8cfm3qszF3yMbv7orn3pd59P5V7eTR8la9avME)
It seemed like a good idea when I started, but these builtins only make it longer.. Can definitely be golfed by using a more manual approach..
Inspired by [*@EriktheOutgolfer*'s 4-byte 05AB1E answer](https://codegolf.stackexchange.com/a/137518/52210). 4 vs 213 bytes, rofl.. >.>
**Explanation:**
```
import java.util.*; // Required import for Arrays
m->{ // Method with 2D integer-array parameter and boolean return-type
Arrays.sort(m, // Sort the 2D input-array on:
(a,b)->Long.compare(a[0],b[0]));
// The first values of the inner arrays
var r=Arrays.stream(m).flatMapToInt(Arrays::stream).toArray();
// Flatten the 2D array to a single integer-array
return Arrays.equals(r, // Check if this integer-array is equal to:
java.util.stream.IntStream.range(1,r.length+1).toArray());}
// An integer-array of the range [1, length+1]
```
] |
[Question]
[
A standard [Scrabble](https://en.wikipedia.org/wiki/Scrabble) board is a 15×15 grid of spaces to place letter tiles. Most of the spaces are blank but some are double word scores (pink), triple word scores (red), double letter scores (light blue), and triple letter scores (blue). There is usually a star in the very center (which counts as a double word score).
[![Scrabble board](https://i.stack.imgur.com/0kZO8m.jpg)](https://i.stack.imgur.com/0kZO8.jpg)
Write a program or function that outputs a standard, empty Scrabble board in ASCII form where:
* `.` represents an empty space
* `D` represents a double word score
* `T` represents a triple word score
* `d` represents a double letter score
* `t` represents a triple letter score
* `X` represents the center star
That is, your exact output must be
```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
```
optionally followed by a trailing newline.
**The shortest code in bytes wins.**
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~59~~ ~~54~~ 52 bytes
```
4t:g2I5vXdK8(3K23h32h(H14(t!XR+8: 7:Pht3$)'DtdTX.'w)
```
[Try it online!](http://matl.tryitonline.net/#code=NHQ6ZzJJNXZYZEs4KDNLMjNoMzJoKEgxNCh0IVhSKzg6IDc6UGh0MyQpJ0R0ZFRYLid3KQ&input=)
## Explanation
The code follows three main steps:
1. Generate the 8x8 matrix
```
4 0 0 3 0 0 0 4
0 1 0 0 0 2 0 0
0 0 1 0 0 0 3 0
3 0 0 1 0 0 0 3
0 0 0 0 1 0 0 0
0 2 0 0 0 2 0 0
0 0 3 0 0 0 3 0
4 0 0 3 0 0 0 5
```
2. Extend it to the 15x15 matrix
```
4 0 0 3 0 0 0 4 0 0 0 3 0 0 4
0 1 0 0 0 2 0 0 0 2 0 0 0 1 0
0 0 1 0 0 0 3 0 3 0 0 0 1 0 0
3 0 0 1 0 0 0 3 0 0 0 1 0 0 3
0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
0 2 0 0 0 2 0 0 0 2 0 0 0 2 0
0 0 3 0 0 0 3 0 3 0 0 0 3 0 0
4 0 0 3 0 0 0 5 0 0 0 3 0 0 4
0 0 3 0 0 0 3 0 3 0 0 0 3 0 0
0 2 0 0 0 2 0 0 0 2 0 0 0 2 0
0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
3 0 0 1 0 0 0 3 0 0 0 1 0 0 3
0 0 1 0 0 0 3 0 3 0 0 0 1 0 0
0 1 0 0 0 2 0 0 0 2 0 0 0 1 0
4 0 0 3 0 0 0 4 0 0 0 3 0 0 4
```
3. Index the string `'DtdTX.'` with that matrix to produce the desired result.
### Step 1
```
4 % Push 4
t: % Duplicate, range: pushes [1 2 3 4]
g % Logical: convert to [1 1 1 1]
2I5 % Push 2, then 3, then 5
v % Concatenate all stack vertically into vector [4 1 1 1 1 2 3 5]
Xd % Generate diagonal matrix from that vector
```
Now we need to fill the nonzero off-diagonal entries. We will only fill those below the diagonal, and then make use symmetry to fill the others.
To fill each value we use linear indexing (see [this answer](https://codegolf.stackexchange.com/a/76535/36398), length-12 snippet). That means accessing the matrix as if it had only one dimension. For an 8×8 matrix, each value of the linear index refers to an entry as follows:
```
1 9 57
2 10 58
3 11
4
5 ... ...
6
7 63
8 16 ... ... 64
```
So, the following assigns the value 4 to the lower-left entry:
```
K % Push 4
8 % Push 8
( % Assign 4 to the entry with linear index 8
```
The code for the value 3 is similar. In this case the index is a vector, because we need to fill several entries:
```
3 % Push 3
K % Push 4
23h % Push 23 and concatenate horizontally: [4 23]
32h % Push 32 and concatenate horizontally: [4 23 32]
( % Assign 4 to the entries specified by that vector
```
And for 2:
```
H % Push 2
14 % Push 14
( % Assign 2 to that entry
```
We now have the matrix
```
4 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
3 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0
0 2 0 0 0 2 0 0
0 0 3 0 0 0 3 0
4 0 0 3 0 0 0 5
```
To fill the upper half we exploit symmetry:
```
t! % Duplicate and transpose
XR % Keep the upper triangular part without the diagonal
+ % Add element-wise
```
### Step 2
The stack now contains the 8×8 matrix resulting from step 1. To extend this matrix we use indexing, this time in the two dimensions.
```
8: % Push vector [1 2 ... 7 8]
7:P % Push vector [7 6 ... 1]
h % Concatenate horizontally: [1 2 ... 7 8 7 ... 2 1]. This will be the row index
t % Duplicate. This will be the column index
3$ % Specify that the next function will take 3 inputs
) % Index the 8×8 matrix with the two vectors. Gives a 15×15 matrix
```
### Step 3
The stack now contains the 15×15 matrix resulting from step 2.
```
'DtdTX.' % Push this string
w % Swap the two elements in the stack. This brings the matrix to the top
) % Index the string with the matrix
```
[Answer]
## JavaScript (ES6), 112 bytes
```
a=Math.abs,f=(n=239)=>n?f(n-1)+(i=a(n%16-8),j=a((n>>4)-7),d=i%7^j%7,n&15?d%4?".":"XdtDDDDTddtd"[(i|j)+d]:`
`):''
```
## JavaScript (ES5), 121 bytes
```
c="";for(a=-8;8>++a;)for(j=0>a?-a:a,b=-8;9>++b;)i=0>b?-b:b,d=i%7^j%7,c+=i-8?d%4?".":"XdtDDDDTddtd"[(i|j)+d]:"\n";alert(c)
```
The ES5 version trades a handwritten `Math.abs()`, two `for` loops and the output via `alert` for the unavailable recursive concise arrow function.
Both versions use the idea in the Ruby/C answer above, by Level River St. Using binary `|` instead of `+` shortens the defining string, `d` stays positive when diffing by `^` instead of `-`.
[Answer]
# Ruby, ~~103~~ 97 bytes
Thanks to Mitch Schwartz for a 6 byte improvement on the iterations.
```
a=(-7..7).map &:abs
a.map{|i|puts a.map{|j|(d=i%7-j%7)%4<1?'X d t DTDdDdDtT d'[i+j+d*d/3]:?.}*''}
```
A similar but significantly different approach to my original answer below. As before, we use the fact that a letter must be printed if `i%7-j%7` is equal to 0 or 4. But here we store that difference in `d` and use the formula `i+j+d*d/3` to give an integer which is unique (up to symmetry) to that particular coloured square. Then we just look it up in the magic string.
*Just for fun: **C version of this approach, 120 bytes***
```
z,i,j,d;f(){for(z=240;z--;)i=abs(z%16-8),j=abs(z/16-7),putchar(i-8?(d=i%7-j%7)%4?46:"X d t DTDdDdDtT d"[i+j+d*d/3]:10);}
```
# Ruby, ~~115~~ 113 bytes
2 bytes saved thanks to Value Ink.
```
(k=-7..7).map{|y|k.map{|x|i=x.abs;j=y.abs
$><<=(i%7-j%7)%4<1?"#{'XdTdT'[(i+j)/3]}dtDDDD"[[i%7,j%7].min]:?.}
puts}
```
**Explanation**
The origin is considered to be the centre of the board.
A letter must be printed if the x and y coordinates of the square have magnitudes that are identical or differ by 4. The only exceptions are on the outer edge of the board, but these follow the same pattern as the central row/column of the board, so we can use the same condition if we take the x and y coordinates modulo 7.
The choice of letter displayed is based on the coordinate of minimum magnitude. In this way the doubles and triples at (1,5) and (2,6) follow the same rule as at (1,1) and (2,2) and are obtained from the 7 character string `"#{formula}dtDDDD"` This does not cover all variations for the edge and centreline squares, so the first character of the string is calculated from the formula `'XdTdT'[(i+j)/3]`.
```
(k=-7..7).map{|y|
k.map{|x|
i=x.abs;j=y.abs
print (i%7-j%7)%4<1? #IF this expression is true print a letter
"#{'XdTdT'[(i+j)/3] #select 1st character of magic string where [i%7,j%7].min==0
}dtDDDD"[[i%7,j%7].min]: #remaining 6 characters of magic string for diagonal
?. #ELSE print .
}
puts #at the end of the row print a newline
}
```
[Answer]
# [brainfuck](http://esolangs.org/wiki/Brainfuck), ~~598~~ ~~596~~ 590 bytes
Golfing tips welcome.
```
>-[++++[<]>->+]<[>++++>+++++>+++>++<<<<-]>[>>>>+>+>+<<<<<<-]<++++++++++[>+>>>>+>-<<<<<<-]>>+>->>-->++.<<..>.<...>>.<<...>.<..>>.<<<<<.>>>.<.>...<<.>>...<<.>>...<.>.<<<.>>>..<.>...>.<.>.<...<.>..<<<.>>>>.<..<.>...>.<...<.>..>.<<<<.>>>....<.>.....<.>....<<<.>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.>>>..>.<...>.<.>.<...>.<..<<<.>>>>>.<<..>.<...>>>----.<<<...>.<..>>.<<<<<.>>>..>.<...>.<.>.<...>.<..<<<.>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.>>>....<.>.....<.>....<<<.>>>>.<..<.>...>.<...<.>..>.<<<<.>>>..<.>...>.<.>.<...<.>..<<<.>>>.<.>...<<.>>...<<.>>...<.>.<<<.>>>>>.<<..>.<...>>.<<...>.<..>>.
```
**Explanation**
Initialize the tape to **[10 116 68 46 100 84 92]** i.e. **[nl t D . d T \]**
`>-[++++[<]>->+]<[>++++>+++++>+++>++<<<<-]>[>>>>+>+>+<<<<<<-]<++++++++++[>+>>>>+>-<<<<<<-]>>+>->>-->++`
Each line here then prints one line of the board.
The middle line also decreases `92 to 88 i.e. \ to X`
```
.<<..>.<...>>.<<...>.<..>>.<<<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>....<.>.....<.>....<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>>>.<<..>.<...>>>----.<<<...>.<..>>.<<<<<.
>>>..>.<...>.<.>.<...>.<..<<<.
>>>.<<.>>...<<.>>...<<.>>...<<.>>.<<<.
>>>....<.>.....<.>....<<<.
>>>>.<..<.>...>.<...<.>..>.<<<<.
>>>..<.>...>.<.>.<...<.>..<<<.
>>>.<.>...<<.>>...<<.>>...<.>.<<<.
>>>>>.<<..>.<...>>.<<...>.<..>>.
```
[Try it online!](http://brainfuck.tryitonline.net/#code=Pi1bKysrK1s8XT4tPitdPFs-KysrKz4rKysrKz4rKys-Kys8PDw8LV0-Wz4-Pj4rPis-Kzw8PDw8PC1dPCsrKysrKysrKytbPis-Pj4-Kz4tPDw8PDw8LV0-Pis-LT4-LS0-KysuPDwuLj4uPC4uLj4-Ljw8Li4uPi48Li4-Pi48PDw8PC4-Pj4uPC4-Li4uPDwuPj4uLi48PC4-Pi4uLjwuPi48PDwuPj4-Li48Lj4uLi4-LjwuPi48Li4uPC4-Li48PDwuPj4-Pi48Li48Lj4uLi4-LjwuLi48Lj4uLj4uPDw8PC4-Pj4uLi4uPC4-Li4uLi48Lj4uLi4uPDw8Lj4-Pi48PC4-Pi4uLjw8Lj4-Li4uPDwuPj4uLi48PC4-Pi48PDwuPj4-Li4-LjwuLi4-LjwuPi48Li4uPi48Li48PDwuPj4-Pj4uPDwuLj4uPC4uLj4-Pi0tLS0uPDw8Li4uPi48Li4-Pi48PDw8PC4-Pj4uLj4uPC4uLj4uPC4-LjwuLi4-LjwuLjw8PC4-Pj4uPDwuPj4uLi48PC4-Pi4uLjw8Lj4-Li4uPDwuPj4uPDw8Lj4-Pi4uLi48Lj4uLi4uLjwuPi4uLi48PDwuPj4-Pi48Li48Lj4uLi4-LjwuLi48Lj4uLj4uPDw8PC4-Pj4uLjwuPi4uLj4uPC4-LjwuLi48Lj4uLjw8PC4-Pj4uPC4-Li4uPDwuPj4uLi48PC4-Pi4uLjwuPi48PDwuPj4-Pj4uPDwuLj4uPC4uLj4-Ljw8Li4uPi48Li4-Pi4&input=)
[Answer]
## PowerShell v2+, ~~147~~ 143 bytes
```
($x='T..d...T...d..T')
($y='.D...t..','..D...d.','d..D...d','....D...','.t...t..','..d...d.'|%{$_+-join$_[6..0]})
'T..d...X...d..T'
$y[5..0]
$x
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0OlwlY9RE8vRU9PD0iB6BB1TS4NlUpbdT0XoECJnp66jroemJ0CYqZA2WBRCBvELEFSmwJRW6NarRKvrZuVn5mnEh9tpqdnEFuryQWzLQJmG5dKZbQpSJJLpeL/fwA "PowerShell – Try It Online")
Takes advantage of how the default `Write-Output` at end of program execution handles arrays (i.e., it inserts a newline between elements). Might be a better way to generate the middle of the board -- I'm still working at it.
The first line outputs the top line of the board, also storing it in `$x` for use later.
The next line generates all the Double-Word lines by taking the left "half" of each, mirroring them (the `-join$_[6..0]` statement), and storing them as elements in array `$y`.
The next line is the middle row, with an `X` in the middle, thanks to `-replace`.
The next line outputs `$y` in reverse order, giving us the bottom Double-Word lines.
The final line is just `$x` again.
```
PS C:\Tools\Scripts\golfing> .\draw-empty-scrabble-board.ps1
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
```
*-4 bytes thanks to Veskah.*
[Answer]
# ><> (Fish), 153 Bytes
```
\!o;!?l
\'T..d...T...d..T'a'.D...t...t...D.'a'..D...d.d...D..'a'd..D...d...D..d'a'....D.....D....'a'.t...t...t...t.'a'..d...d.d...d..'a'T..d...'
\'X/'02p
```
A horribly, awfully, inefficient way of doing things. Currently looking into a way of shortening it down by mirroring both horizontally and vertically properly.
[Try it online!](https://fishlanguage.com/playground/TmyT8nk9xFFzDdDhj) (If you don't want to be there all day make sure you either set execution speed to max or run without the animation.)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~57~~ 53 bytes
### Code
```
•jd]31‚ŽÔc¦Ïïì¹Ep.Üì8Ìa;“•6B4ÝJ".TdDt"‡5'.3×:Â'Xý15ô»
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiamRdMzHigJrFvcOUY8Kmw4_Dr8OswrlFcC7DnMOsOMOMYTvigJzigKI2QjTDnUoiLlRkRHQi4oChNScuM8OXOsOCJ1jDvTE1w7TCuw&input=)
---
### Explanation (outdated)
The `•4ç“–šã&$W§ñçvßÖŠ_æá_VFÛÞýi~7¾¬ÏXôc•5B` decompresses to this number:
```
1002000100020010400030003000400040002020004002004000200040020000400000400000300030003000300020002020002001002000
```
With `4ÝJ".TdtD"‡`, we transliterate the following in this big number:
```
0 -> .
1 -> T
2 -> d
3 -> t
4 -> D
```
We bifurcate the whole string, leaving the string and the string reversed on the stack and join them by `"X"` using `ý`. We split the entire string into pieces of 15 using th `15ô` code and join the whole array by newlines using `»`.
[Answer]
## C, ~~146~~ ~~145~~ ~~142~~ 138 bytes
```
i,r,c;main(){for(;i<240;)r=abs(i/16-7),c="T..12..0..12..0"[r+7-abs(i%16-7)],putchar(++i%16?c&4?c:"Xd.dd.tt.D..D.dD.dD.tTd."[c%4+r*3]:10);}
```
[Try it online!](http://coliru.stacked-crooked.com/a/0c24328d5c32d603 "Try it online!")
*~~1 byte~~5 bytes saved thanks to Level River St*
This exploits the diagonal pattern of the board for encoding. In particular, if we take the top left quadrant of the board and align the diagonal, we get:
```
T..d...T
.D...t..
..D...d.
d..D...d
....D...
.t...t..
..d...d.
T..d...X
```
...a lot of the columns now line up. If we encode columns in a line this way:
```
0..12..0 y/012/Td./
.0..12.. y/012/D.t/
..0..12. y/012/D.d/
2..0..12 y/012/D.d/
12..0..1 y/012/D../
.12..0.. y/012/tt./
..12..0. y/012/dd./
T..12..0 y/012/Xd./
```
...then the board pattern can be collapsed into a 15 character string: `T..12..0..12..0`; and we simply need the right mappings for each row.
With that in mind, here's an expanded version with comments:
```
i,r,c;
main() {
for(;i<240;) // one char per output including new line
r=abs(i/16-7) // row; goes from 7 to 0 and back to 7.
, c="T..12..0..12..0"[r+7-abs(i%16-7)] // pattern char
, putchar(++i%16 // if this is 0 we need a new line
? c&4 // hash to distinguish 'T' and '.' from '0', '1', '2'
? c // print 'T' and '.' literally
: "Xd.dd.tt.D..D.dD.dD.tTd."[c%4+r*3] // otherwise look up replacement char
: 10 // print the new line
);
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~49~~ 44 bytes
```
•1nÑ=}íge/Þ9,ÑT‰yo¬iNˆå•6B8ôû€û»5ÝJ".TtdDX"‡
```
[Try it online!](https://tio.run/nexus/05ab1e#AUUAuv//4oCiMW7DkT19w61nZS/Dnjksw5FU4oCweW/CrGlOy4bDpeKAojZCOMO0w7vigqzDu8K7NcOdSiIuVHRkRFgi4oCh//8 "05AB1E – TIO Nexus")
# Explained:
Push: `1003000104000200004000303004000300004000020002000030003010030005`
Split into chunks of 8, palindromize each.
Palindromize again.
Replace numbers with characters.
---
# Other Idea (Someone Try this in MATL)
Seeing as EVERYTHING is garunteed to have a period inbetween it...
Count the number of zeros inbetween each piece:
```
1003000104000200004000303004000300004000020002000030003010030005
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
```
`131424334342233135 => w\F6ß¿`
Taking the counts of zeros runs:
`23134312344343123 => ì:¼˜¾`
Then you would decrypt and transpose them together.
Using them in 05AB1E (results in a +5 byte increase):
# [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes
```
•w\F6ß¿•6BS•ì:¼˜¾•5BS0ׂøJJ
```
[Try it...](https://tio.run/nexus/05ab1e#@/@oYVF5jJvZ4fmH9gOZZk7BQPLwGqtDe07PObQPyDZ1CjY4PP1Rw6zDO7y8/v83MjY0NjE2NDI2MYHQAA "05AB1E – TIO Nexus")
---
Meta-golfed entry:
# [05AB1E](https://github.com/Adriandmen/05AB1E), 104 bytes
```
•G¨J´JÏÍ?»"”Ö3úoÙƒ¢y”vf%¯‚6À°IÕNO’Å2Õ=ÙŠxn®žÑŸ¶¼t¨š,Ä]ÓŽÉéȺÂ/ø‡ŸÖ|e³J—Ë'~!hj«igċ΂wî’©•7BžLR"
.DTXdt"‡
```
[Try it!](https://tio.run/nexus/05ab1e#AbAAT///4oCiR8KoSsK0SsOPw40/wrsi4oCdw5Yzw7pvw5nGksKieeKAnXZmJcKv4oCaNsOAwrBJw5VOT@KAmcOFMsOVPcOZxaB4bsKuxb7DkcW4wrbCvHTCqMWhLMOEXcOTxb3DicOpw4jCusOCL8O44oChxbjDlnxlwrNK4oCUw4snfiFoasKraWfDhOKAucOO4oCad8Ou4oCZwqnigKI3QsW@TFIiCi5EVFhkdCLigKH//w "05AB1E – TIO Nexus")
Meta-golfed using my meta-golfer for ASCII art:
<https://tio.run/nexus/05ab1e#JY9NSgNBEIWvUo4/qAQxyfi30yAioiAiuBM6M9U9DT3doao7ccBFrhI3ooss3QguJniRXCR2x01RfK9479Xqtf2@XHy2H78/tw/L6aydq8VXr5sPsuX0LeP1jCwbJD3r54v3dp5mFGbZzWp1wXBPyLpE6@GRQj0C1spiCQJ4gjjSVgG@YBG8HiM4KpHAWbgiXYqmA1wF79ONrxCGa5nBOyCUQSEyCFuCi2LEklwNjGO0YAQpNA3cBTa6hsIF60kjd9Y@jAWhF9SAk1C5Gk1yiTSQ9g1MBKcKAp4q7RGuXWCMFlYioS3iKowBhf@9Kh2DNbEHGSIexhSZeDRIUcq4oTDxDS09aAsjZ3TRHGycb25tP@/s7@51e/386Pjk9OzwDw>
[Answer]
# Python 3, 138 bytes
```
d=lambda s:s+s[-2::-1]
print(*d(list(map(d,'T..d...T .D...t.. ..D...d. d..D...d ....D... .t...t.. ..d...d. T..d...X '.split()))),sep='\n')
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes (noncompeting)
All credit for this answer goes to [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc).
```
T↑↑↘tdd↗→→↖XdtDDDD↓T..d‖O⟦↗→↓⟧UB.
```
[Try it online!](https://tio.run/nexus/charcoal#@x/yqG0iGM0oSUl51Db9UdskMJoWkVLiAgSP2iaH6OmlPGqY9n7P@kfzl8GUTH40f/n7PVvf71mk9/8/AA "Charcoal – TIO Nexus")
## Verbose
```
Print("T")
Move(:Up)
Move(:Up)
Print(:DownRight, "tdd")
Move(:UpRight)
Move(:Right)
Move(:Right)
Print(:UpLeft, "XdtDDDD")
Print(:Down, "T..d")
ReflectOverlap([:UpRight, :Right, :Down])
SetBackground(".")
```
[Try it online!](https://tio.run/nexus/charcoal#@x9QlJlXoqEUoqTJ5ZtflqphFVqAzIJIW7nkl@cFZaZnlOgoKJWkpCApBovCuNg4UBNCC3xS00DaI1JKXIBACcVsoHiInh7I3KDUtJzU5BL/stSinMQCjWiYFToKVjAapCFWkys4tcQpMTk7vSi/NC9FQ0lPSfP///@6ZQA "Charcoal – TIO Nexus")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 30 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
TDDDDtdX\tdd\62╋d41╋T81╋:⤢n┼.r
```
[Try it here!](https://dzaima.github.io/Canvas/?u=VERERER0ZFgldUZGM0N0ZGQldUZGM0MldUZGMTYldUZGMTIldTI1NEJkJXVGRjE0JXVGRjExJXUyNTRCVCV1RkYxOCV1RkYxMSV1MjU0QiV1RkYxQSV1MjkyMiV1RkY0RSV1MjUzQy4ldUZGNTI_,v=8)
A different enough approach to the existing Canvas answer to justify its own post, I think.
Constructs the art as follows:
```
T
D
D
D
D
t
d
X
```
```
T
D t
D d
D d
D
t
d
X
```
```
T d
D t
D d
D d
D
t
d
X
```
```
T d T
D t
D d
D d
D
t
d
X
```
```
T d T
D t
D d
d D d
D
t t
d d
T d X
```
```
T d T d T
D t t D
D d d D
d D d D d
D D
t t t t
d d d d
T d X d T
d d d d
t t t t
D D
d D d D d
D d d D
D t t D
T d T d T
```
```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
```
[Answer]
## Javascript (ES6), 150 bytes
```
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
```
### How it works
The string `"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3"` describes the board from its top left corner to the square just before the 'X', with consecutive empty squares encoded as digits. The `replace()` function both unpacks the empty squares and builds the mirror string `r` for the bottom of the board. Then both parts are put together and carriage returns are inserted every 15 characters.
### Demo
```
let f =
_=>(r='',"T2d3T3d2T.D3t3t3D3D3d.d3D2d2D3d3D2d4D5D5t3t3t3t3d3d.d3d2T2d3".replace(/./g,c=>(c=+c?'.'.repeat(c):c,r=c+r,c))+'X'+r).match(/.{15}/g).join`
`
console.log(f())
```
[Answer]
## JavaScript (ES6), 221 bytes
```
f=
_=>(a=[...Array(15)].map(_=>Array(15).fill`.`),r=([c,i,j])=>[a[i][j]=a[k=14-i][j]=a[i][j=14-j]=a[k][j]=c,j,i],[..."TDDDDtdX"].map((c,i)=>r([c,i,i])),"d30t51d62d73T70".replace(/.../g,s=>r(r(s))),a.map(a=>a.join``).join`
`)
;o.textContent=f()
```
```
<pre id=o>
```
Since I went to the trouble of creating this I thought I'd post it anyway even though there's a clearly superior solution available.
[Answer]
## C 234 Bytes
```
#define g(t) while(i++<8)putchar(*b++);b-=2;--i;while(--i>0)putchar(*b--);putchar('\n');b+=t;
char*r="T..d...T.D...t....D...d.d..D...d....D....t...t....d...d.T..d...X";i;f(){char*b=r;do{g(9);}while(*b);b-=16;do{g(-7);}while(b>=r);}
```
Here's the output:
```
T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 33 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
“e+╪>v.2eC}¼P↕V⁸╋USF∔uiT═Ik¼‟8n┼┼
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDFDZSsldTI1NkElM0UldUZGNTYuJXVGRjEyZUMldUZGNUQlQkMldUZGMzAldTIxOTVWJXUyMDc4JXUyNTRCJXVGRjM1JXVGRjMzRiV1MjIxNHVpJXVGRjM0JXUyNTUwJXVGRjI5ayVCQyV1MjAxRiV1RkYxOCV1RkY0RSV1MjUzQyV1MjUzQw__,v=8)
uses a huge compressed string and quad palidromizes it. Can probably be shortened by adding the main diagonal later.
[Answer]
## Haskell, 114 bytes
```
g=(++)<*>reverse.init
unlines$g$g<$>words"T..d...T .D...t.. ..D...d. d..D...d ....D... .t...t.. ..d...d. T..d...X"
```
`g` in a non-pointfree version is `g x = x ++ (reverse (init x))`. It is applied once per (half-)line and again on the result.
[Answer]
## sh + coreutils, 119 bytes
This is a binary file. Shown as hexdump:
```
00000000 74 61 69 6c 20 2d 63 39 34 20 24 30 7c 67 75 6e |tail -c94 $0|gun|
00000010 7a 69 70 0a 65 78 69 74 0a 1f 8b 08 00 2e ec ca |zip.exit........|
00000020 57 00 03 65 4f c9 0d c0 30 08 fb 7b 18 4f 91 11 |W..eO...0..{.O..|
00000030 fc e8 00 1e a1 fb ab 08 68 a4 90 07 60 d9 98 43 |........h...`..C|
00000040 a4 49 8a 59 05 ae 40 6f c7 22 98 84 b3 29 10 fc |.I.Y..@o."...)..|
00000050 13 59 1d 7a 11 9d b1 bd 15 a8 56 77 26 54 c4 b3 |.Y.z......Vw&T..|
00000060 f7 0d fd f6 9f f3 ef fd e7 7d f3 7e 8d ff 3e 05 |.........}.~..>.|
00000070 57 d9 a0 f0 00 00 00 |W......|
00000077
```
Here's the base64 form so you can copy/paste it:
```
begin-base64 755 test.sh
dGFpbCAtYzk0ICQwfGd1bnppcApleGl0Ch+LCAAu7MpXAANlT8kNwDAI+3sY
T5ER/OgAHqH7qwhopJAHYNmYQ6RJilkFrkBvxyKYhLMpEPwTWR16EZ2xvRWo
VncmVMSz9w399p/z7/3nffN+jf8+BVfZoPAAAAA=
====
```
[Answer]
# C ~~230~~ 228 Bytes
```
char *s="T.D..Dd..D....D.t...t..d...dT..d...X";
int x,y,a,b;
#define X(N) {putchar(s[a]);N y<=x?1:y;}
#define P for(y=1;y<8;y++)X(a+=)for(y--;y+1;y--)X(a-=)puts("");
main(){for(;x<8;x++){a=b+=x;P}for(x=6;x+1;x--){a=b-=(x+1);P}}
```
[try it on ideone](https://ideone.com/Cp3Jfr)
This is an attempt at improving the original C version posted that had quarter of board stored in a C array. Not as short as I was hoping for. This version only has one eighth of the board stored.
Ungolfed:
```
char *s="T.D..Dd..D....D.t...t..d...dT..d...X";
int x,y,a,b;
main(){
for(x = 0; x < 8; x++){
a=b+=x;
for(y = 1; y < 8; y++){
putchar(s[a]);
a += y<=x ? 1 : y;
}
for(y--; y >= 0; y--){
putchar(s[a]);
a -= y<=x ? 1 : y;
}
puts("");
}
for(x=6; x >= 0; x--){
a=b-=(x+1);
for(y = 1; y < 8; y++){
putchar(s[a]);
a += y<=x ? 1 : y;
}
for(y--; y >= 0; y--){
putchar(s[a]);
a-= y<=x ? 1 : y;
}
puts("");
}
}
```
[Answer]
## GNU sed, ~~219~~ 205 bytes
```
s/$/T..d...T...d..T/p;h
s/.*/.D...t...t...D./p;G;h
s/.*/..D...d.d...D../p;G;h
s/.*/d..D...d...D..d/p;G;h
s/.*/....D.....D..../p;G;h
s/.*/.t...t...t...t./p;G;h
s/.*/..d...d.d...d../p;G;h
s/.*\n//;s/T/X/2p;g
```
Taking advantage of the mirror symmetry of the board, the second half is the first one that was stored in reverse order in the hold space.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 40 bytes
```
•7â∍û¯øÉ»₄XÍ«Ÿ=SPтŸƶR±•".TdDtX"Åв8äJ€ûû»
```
[Try it online!](https://tio.run/##AU8AsP9vc2FiaWX//@KAojfDouKIjcO7wq/DuMOJwrvigoRYw43Cq8W4PVNQ0YLFuMa2UsKx4oCiIi5UZER0WCLDhdCyOMOkSuKCrMO7w7vCu/// "05AB1E – Try It Online")
```
•...•".TdDtX"Åв8äJ€ûû» # trimmed program
» # join...
Åв # list of characters of...
".TdDtX" # literal...
Åв # with indices in base-10 values of base length of...
".TdDtX" # literal...
Åв # digits of...
•...• # 10654502656792583423375424705593131734076028132261...
ä # split into...
8 # literal...
ä # equal length pieces...
# (implicit) with each element...
J # joined...
€ # with each element...
û # concatenated with itself reversed excluding the first character...
û # concatenated with itself reversed excluding the first element...
» # by newlines
# implicit output
```
[Answer]
# Excel, 115 bytes
```
=LET(j,8-ABS(8-ROW(1:15)),k,TRANSPOSE(j),n,IF(k>j,k,j),MID("T.D..Dd..D....D.t...t..d...dT..d...X",n*(n-3)/2+j+k,1))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnCOGDSxu4eGyuWT_?e=8BgSYx)
[Answer]
# Vyxal, 242 bytes
[Try it online!](http://lyxal.pythonanywhere.com?flags=&code=%60T..d...T...d..T%0A.D...t...t...D.%0A..D...d.d...D..%0Ad..D...d...D..d%0A....D.....D....%0A.t...t...t...t.%0A..d...d.d...d..%0AT..d...X...d..T%0A..d...d.d...d..%0A.t...t...t...t.%0A....D.....D....%0Ad..D...d...D..d%0A..D...d.d...D..%0A.D...t...t...D.%0AT..d...T...d..T%60%2C&inputs=&header=&footer=)
```
`T..d...T...d..T
.D...t...t...D.
..D...d.d...D..
d..D...d...D..d
....D.....D....
.t...t...t...t.
..d...d.d...d..
T..d...X...d..T
..d...d.d...d..
.t...t...t...t.
....D.....D....
d..D...d...D..d
..D...d.d...D..
.D...t...t...D.
T..d...T...d..T`,
```
For answer number 4, we have the empty Scrabble board in its natural habitat.
] |
[Question]
[
Well, sum it down really.
Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.
For example, the input `[7, 5, 0, 9]` has output
```
7 5 0 9
2 5 9
7 4
1
```
because `2` is `(7 + 5) mod 10`, `5` is `(5 + 0) mod 10`, `9` is `(0 + 9) mod 10`, etc. all the way to `1` being `(7 + 4) mod 10`.
If the list has only one item, then the output matches the input; e.g. an input of `[4]` will yield
```
4
```
Here are some additional examples:
```
[0]
0
[1, 2]
1 2
3
[8, 7]
8 7
5
[0, 0]
0 0
0
[1, 4, 2]
1 4 2
5 6
1
[0, 1, 0]
0 1 0
1 1
2
[1, 0, 0, 0]
1 0 0 0
1 0 0
1 0
1
[1, 2, 3, 4]
1 2 3 4
3 5 7
8 2
0
[1, 2, 3, 5, 8]
1 2 3 5 8
3 5 8 3
8 3 1
1 4
5
[9, 2, 4, 5, 3, 2, 2]
9 2 4 5 3 2 2
1 6 9 8 5 4
7 5 7 3 9
2 2 0 2
4 2 2
6 4
0
```
Note that in the output:
* The first line does not have leading spaces.
* Each subsequent line has one more leading space than the line previous.
* Digits are separated by a single space.
* Each line is allowed to have up to one trailing space.
* There may be a single optional trailing newline.
* You must use the characters for normal decimal digits (0 through 9).
**The shortest code in bytes wins. Tiebreaker is earlier answer.**
[Answer]
# BrainF\*\*k, ~~396~~ 391 bytes
```
>+>>++++[-<++++++++>]->,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-<+[-<+]->>+[-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>[[->+]->>+<<<+[-<+]->]>+[-<->[[->+]->+>>+<<<<+[-<+]->]<+>->+[->+]->>[->+<]>+>++++++++++>>-<<[-<-[>>]<]<->>>+[-<<<+>>>[-<->]<+++++++++>>>+]++++++++[-<++++<++++++>>]<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]>.>.[-]<[-]<<<[->+<]<<+[-<+]>+]>>[-]<<<-<+[-<+]->>+]
```
I couldn't resist the temptation to do this one. At least the triangle is pointy-side down.
Input comes in as a string of numeric characters followed by a single newline.
Output will contain a single trailing space on every line.
Examples:
```
$ bf sd.bf
010
0 1 0
1 1
2
$ bf sd.bf
123456
1 2 3 4 5 6
3 5 7 9 1
8 2 6 0
0 8 6
8 4
2
$ bf sd.bf
9245322
9 2 4 5 3 2 2
1 6 9 8 5 4
7 5 7 3 9
2 2 0 2
4 2 2
6 4
0
```
## Explanation
Since it's rather difficult to explain the code from a functional perspective, we can instead look at it from the perspective of the state of the tape at various times. The core idea here is that the triangle we output is initialized as a tightly-packed (for BF, anyway) array that shrinks in size by 1 every iteration of a loop. Another important thought is that we use `255` to indicate a "placeholder" that we can search for on the tape.
### Initialization
This is the easiest step. At the start of the program, we execute the following:
```
>+>>++++[-<++++++++>]->
```
This forces the tape into the following state (where `>N<` indicates the location of the pointer on the tape)
```
[ 0 1 32 255 >0< 0 0 ...]
```
The first number here is a "buffer" location. We're not going to use it on a long-term basis, but it's useful to make little operations simpler and for copying data around.
The second number is the number of spaces that we'll be outputting at the start of each line, starting *after* the first line. The first line will have no leading spaces.
The third number is the space character we output.
The fourth number is a placeholder 255, so that we can get back to this position relatively easily.
### Input
From this position, we will read in all of the characters. At the end of this step, we hope to be in the following situation:
```
[ 0 1 32 255 a b c d e f ... >255< 0 0 ... ]
```
Where `a b c d e f ...` indicates the string of numeric characters that was input (not the newline).
We accomplish this with the following:
```
,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-
```
There are some nuances to this. First of all, we will output each character as we get them, and then output a space after it. Secondly, we don't want to copy the ASCII value to the tape, we want to copy the actual numeric digit. Third, we want to stop when we hit a newline and leave ourselves in a good place at that time.
Say our input is `6723`. Then, upon reading the first `6`, our tape looks like this:
```
[ 0 1 32 255 >54< 0 0 ...]
```
We check that this value is not equal to `10` (an ASCII newline) with `,----------[++++++++++`. We then print out the value and continue by simultaneously subtracting 48 from the input value and adding 32 to the value next to it (`>>++++++++[-<++++<------>>]<`), leaving us here:
```
[ 0 1 32 255 6 >32< 0 ...]
```
Notice how throughout this process we can assume that all digits to the right of our input are 0--this means that we're not in danger of ruining any previous state if we use values to the right to calculate `6 * 8` and `4 * 8`.
Now we output the space character we just generated, and take in a new input, deleting the space we calculated there. Eventually, the input will be terminated by a new line and the loop will exit, leaving a `255` where the newline would have been (`,----------]-`). This is the second placeholder character we will use to navigate the tape. At this point in our scenario, our tape is exactly this:
```
[ 0 1 32 255 6 7 2 3 >255< 0 0 ... ]
```
### Calculation
The way this works is that the list of digits between our `255` placeholders is going to shrink by one every iteration of the loop. When it only has 1 digit left in it, we're done and should halt immediately (Note that, at this point, every digit in that list has already been output, so we don't have to worry about outputting it again).
We now use this trick to navigate to the first `255` placeholder: `<+[-<+]-`. This effectively searches the tape to the left for a `255`, changing nothing in between. Now that we've moved the pointer, we can check our exit condition: if there's only one digit in the list, then the cell two spaces to the right will hold `255`. Thus, we check against that and start a loop: `>>+[-<<`
The first step in our loop is to output a newline. So we move to the first cell (our buffer cell), add 10 to it and output. The next step is to output all leading space characters. After outputting them, we increment our count for number of leading spaces. These steps are accomplished by the following:
```
-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>
```
Which leaves us in this state:
```
[ 0 2 32 255 >6< 7 2 3 255 0 0 0 0 0 0 ]
```
Our next step is to copy the first value in the list over, past the second placeholder `255`:
```
[[->+]->>+<<<+[-<+]->]
```
We essentially do this by hopping back and forth between our placeholder `255`s, leaving us here:
```
[ 0 2 32 255 >0< 7 2 3 255 0 6 0 0 ... ]
```
We now start a loop, iterating through the rest of the list, stopping when we hit `255` : `>+[-<`
At this point, the digit to our immediate left is always 0. So, because we love them, we pop a placeholder `255` in there so that we can come back to our place in the list. The next step is to move the second place in the list to locations surrounding where we moved the first place to, past the second placeholder `255`. These steps are accomplished by the following:
```
->
[[->+]->+>>+<<<<+[-<+]->]
```
Leaving us here: `[ 0 2 32 255 255 >0< 2 3 255 7 6 7 0 ]`
Now, both the `6` and `7` have been moved to a location where the calculation can occur. We need two copies of the `7` because the next number in the list will need it as well. The `7` immediately after the `255` serves this purpose, whereas the other `7` will be consumed by the calculation.
First, we add the two digits:
```
<+>->+[->+]->>
[->+<]>
```
Leaving us here:
```
[ 0 2 32 255 0 255 2 3 255 7 0 >13< 0 ]
```
The next combination of steps is the most complicated. We need to see if the number we're pointing to is larger than 10, and if it is, we subtract `10`. In reality, what we do is we subtract 10 from it and see if it hits `0` at any point in the subtraction. If it does, we add `10` back on later. At the end of this, we should have the sum modulo 10.
```
Prepare a 10 to the right
+>++++++++++
Leave yet another 255 for a loop condition later
>>-<<
If the number is greater than 10 end up one space to the left
else one space to the right
[-<-[>>]<]<->
Check if the previous 255 is two spaces to the right and if it is
add 10 back to our sum--we've subtracted too much
>>+[-<<<+>>>[-<->]<+++++++++>>>+]
```
At this point, we've accomplished the goal. We have the sum modulo 10!
Also, whether or not the number was greater than 10, we'll end up here:
```
[ 0 2 32 255 0 255 2 3 255 7 0 3 0 0 >0< ]
```
Our next goals are to output this new sum, follow it with a space, and inject it back into our list. We do this all with our previous techniques of `255`-hopping and adding `48` to our sum, so I won't cover it in detail.
```
++++++++[-<++++<++++++>>]
<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]
>.>.
```
And we're here: `[ 0 2 32 255 3 255 2 3 255 7 0 0 51 >32< ]`
Notice how we put an additional `255` placeholder after our newly-injected `3` so that we don't lose place in the list. At this point, we have output our sum and its space, so we need to clean up and revert to a state where the next iteration of this loop is going to work. We need to clear out our `51` and `32` cells, move the `7` once to the right, and navigate to our list placeholder so that we can start over.
```
[-]<[-]<<<[->+<]<<+[-<+]
```
Now, we're here: `[ 0 2 32 255 3 >0< 2 3 255 0 7 0 ... ]`
Which is exactly where we want to be for our next iteration. So check for 255 and move on! (`>+]`)
When we get dropped off from the loop, we're going to have a whole new list--made up of the sums from the previous list. The first time, it'll look like this:
```
[ 0 2 32 255 3 9 5 0 >0< ]
```
Now we want to repeat that whole process on our new list, so we plop a `255` down to the left and start all over! We need to do a little bit of cleanup with `>>[-]<<`, and then drop our placeholder with `<-`. After that, we're in exactly the same place as we were after input, so we can get away with doing the same checks: `<+[-<+]->>+`, and boom! We've got our full loop! All we need is the closing bracket, and when it ends we've already output everything, so we're done: `]`.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~20~~ ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṛ+2\Ṗп%⁵z”@ṚZGḟ”@
```
[Try it online!](http://jelly.tryitonline.net/#code=4bmaKzJc4bmWw5DCvyXigbV64oCdQOG5mlpH4bif4oCdQA&input=&args=WzksIDIsIDQsIDUsIDMsIDIsIDJd)
### Background
Generating the numbers is straightforward in Jelly. The output is a bit more complicated.
Jelly has a built-in grid atom (`G`) that displays a 2D list with newlines between rows and spaces between columns. We take the 2D array of numbers (generated with each row reversed), and transpose it with fill value `@`. After revering the resulting array and transposing again, applying `G` yield the following.
```
9 2 4 5 3 2 2
@ 1 6 9 8 5 4
@ @ 7 5 7 3 9
@ @ @ 2 2 0 2
@ @ @ @ 4 2 2
@ @ @ @ @ 6 4
@ @ @ @ @ @ 0
```
To obtain the desired triangular shape, all we have to do is remove the fill value.
### How it works
```
Ṛ+2\Ṗп%⁵z”@ṚZGḟ”@ Main link. Argument: A (list of integers)
Ṛ Reverse A.
Ṗп While there's more than one element:
+2\ Compute the pairwise sum.
Collect all intermediate results in a list.
%⁵ Take all resulting integers modulo 10.
z”@ Transpose with fill value '@'.
Ṛ Reverse the order of the rows.
Z Transpose.
G Grid.
ḟ”@ Filter; remove the fill value.
```
[Answer]
# Pyth - 18 bytes
```
j.e+*dkjdbP.ueM+Vt
```
[Test Suite](http://pyth.herokuapp.com/?code=j.e%2B%2adkjdbP.ueM%2BVt&test_suite=1&test_suite_input=%5B7%2C+5%2C+0%2C+9%5D%0A%5B4%5D%0A%5B0%5D%0A%5B1%2C+2%5D%0A%5B8%2C+7%5D%0A%5B0%2C+0%5D%0A%5B1%2C+4%2C+2%5D%0A%5B0%2C+1%2C+0%5D%0A%5B1%2C+0%2C+0%2C+0%5D%0A%5B1%2C+2%2C+3%2C+4%5D%0A%5B1%2C+2%2C+3%2C+5%2C+8%5D%0A%5B9%2C+2%2C+4%2C+5%2C+3%2C+2%2C+2%5D&debug=0).
```
j Join by newlines
.e Loop over seq in var b and index in var k
+ Concatenate
*dk Space repeated k times
jdb Join b by spaces
P [:-1] to get rid of empty line
.u (Q implicit) Cumulative fixed point over input (var G)
eM Mod 10 mapped over list
+V Vectorized addition
t(G implict) G[1:]
(G implict) Vectorize cuts this off to G[:-1]
```
[Answer]
## Python 3.5, ~~74~~ ~~72~~ 71 bytes
```
f=lambda L,*S:f([sum(x)%10for x in zip(L,L[1:print(*S,*L)]or 1)],'',*S)
```
Input is a list of integers (e.g. `f([1,2,3,5,8])`), output is to STDOUT. The `%10` and the fact that `map` returns a `map` object in Python 3 is a bit annoying, meaning we can't do `map(lambda*x:sum(x)%10,L,L[1:])` or similar.
The function errors out, but by then the output would have completed. Thanks to @xsot for -1 byte by finding a good place to stick the `print`.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~20~~ ~~19~~ 17 bytes
Code:
```
DvNð×?T%Ððý,¦‚ø€O
```
Explanation:
```
D # Duplicate the input.
v # Map over it, running the following len(input) times.
Nð× # Multiply the iteration number with a space.
? # Pop and print without a newline.
T% # Take all integers modulo 10.
Ð # Triplicate the array.
ðý, # Join by spaces and print with a newline.
¦ # Remove the first element of the array.
‚ # Wrap it up, (pop a, b push [a, b]).
ø # Zip.
€O # Sum up each element.
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RHZOw7DDlz9UJcOQw7DDvSzCpuKAmsO44oKsTw&input=WzksIDIsIDQsIDUsIDMsIDIsIDJd).
[Answer]
# MATL, ~~32~~ ~~30~~ ~~29~~ ~~28~~ ~~27~~ ~~26~~ ~~25~~ 24 bytes
```
t"X@qZ"y1X9&VhDTTH&Y+10\
```
*1 Byte saved thanks to @Luis*
[**Try it Online!**](http://matl.tryitonline.net/#code=dCJYQHFaInkxWDkmVmhEVFRIJlkrMTBc&input=WzksIDIsIDQsIDUsIDMsIDIsIDJd)
[Modified version for all test cases](http://matl.tryitonline.net/#code=YGl0IlhAcVoieTFYOSZWaERUVEgmWSsxMFxdJyAnRFQ&input=WzBdClsxLCAyXQpbOCwgN10KWzAsIDBdClsxLCA0LCAyXQpbMCwgMSwgMF0KWzEsIDAsIDAsIDBdClsxLCAyLCAzLCA0XQpbMSwgMiwgMywgNSwgOF0KWzksIDIsIDQsIDUsIDMsIDIsIDJd)
**Explanation**
```
% Implicitly grab input
t % Duplicate the input
" % For each element of the input (really just a shortcut to loop numel(input) times)
X@q % Determine the current loop index and subtract 1
Z" % Create an array of blanks this size (these are the padding to the left)
y % Copy the current array of numbers from the stack
1X9 % Get the pre-defined output format of %.15g from the clipboard
&V % Convert the input to it's character representation with single spacing
h % Horizontally concatenate the left padding and the numbers
D % Display the result (consumes the string)
TT % Create a two-element vector of 1's ([1 1])
H&Y+ % Convolve [1 1] with the array (computes the pair-wise sum)
10\ % Mod 10 the result
% Implicitly close for loop
```
[Answer]
## Actually, 43 bytes
```
;l;D+#"{:^%d}"%╗W;' j1╟╜f.;pXZ`i+9u@%`MdXWX
```
[Try it online!](http://actually.tryitonline.net/#code=O2w7RCsjIns6XiVkfSIl4pWXVzsnIGox4pWf4pWcZi47cFhaYGkrOXVAJWBNZFhXWA&input=Nyw1LDAsOQ)
This program prints a single trailing newline after the output.
Explanation:
```
;l;D+#"{:^%d}"%╗W;' j1╟╜f.;pXZ`i+9u@%`MdXWX
;l;D+ calculate the width of the field (2L-1 where L = len(input))
#"{:^%d}"%╗ push to a list, make a Python new-style format string for centering text, save in reg0
W;' j1╟╜f.;pXZ`i+9u@%`MdXW while the top of the stack is truthy:
;' j1╟ duplicate list, join with spaces, push string to a list
╜f. center string and print
;pXZ zip list with itself shifted forward by 1 (zip(a,a[1:]))
`i+9u@%`M map: add each pair and mod by 10
dX discard the last value (which was not added with anything)
X discard the now-empty list after the loop to avoid printing it
```
[Answer]
# Mathematica, 67 Bytes
```
MatrixForm@NestList[Mod[Total/@Partition[#,2,1],10]&,#,Length@#-1]&
```
Example:[![enter image description here](https://i.stack.imgur.com/IR3sg.png)](https://i.stack.imgur.com/IR3sg.png)
[Answer]
## CJam, 25 bytes
```
q~{_2ew::+Af%}h;]eeSff*N*
```
[Try it online!](http://cjam.tryitonline.net/#code=cX57XzJldzo6K0FmJX1oO11lZVNmZipOKg&input=WzcgNSAwIDld)
### Explanation
This uses a fairly neat trick to generate the triangle layout.
```
q~ e# Read and evaluate input.
{ e# While the list of digits is non-empty...
_2ew e# Duplicate and get all sublists of length 2.
::+ e# Sum each pair.
Af% e# Take each result modulo 10.
}h
;] e# Discard the final empty list and wrap the others in an array.
ee e# Enumerate the array. E.g. for input `[7 5 0 9]` we now get this:
e# [[0 [7 5 0 9]]
e# [1 [2 5 9]]
e# [2 [7 4]]
e# [3 [1]]]
Sff* e# Perform S* on each element at depth two. For the integers from the
e# enumeration this gives a string of that many spaces, i.e. the correct
e# indentation. For the lists of digits this inserts a space character
e# between every two digits, thereby spacing out the digits as necessary.
N* e# Put linefeeds between the pairs of indentation and digit list.
```
[Answer]
# [Haskell](https://www.haskell.org/), 88 bytes
```
f=mapM putStrLn.(""%)
s%x@(_:y)=(s++(x>>=(:" ").last.show)):(' ':s)%zipWith(+)x y
_%_=[]
```
[Try it online!](https://tio.run/##BcHBCsIgGADg@57iR5D9P4p0iUhw9AB16tBhDPHQUHKbpJHr5e37vMuvZ4ytzWZx6QbpU@7lfV0VMsapy7xe0OqdDGYhsA6DQc2AkYouF5X99iXS2EOvM/FfSI9QPAqqsHeWWzNObXFhBQMzjCd5lAd5ntof "Haskell – Try It Online")
I chose the same I/O format and counted `f=` to compete fairly with the other Haskell answer.
Replacing the first line by just `(""%)` would give a 72-byte answer that returns a list of lines.
Instead of writing `show.(`mod`10)` or `[mod(a+b)10|(a,b)<-zip x y]`, it turns out to be shorter to use `last` on the result of `show`, which is kinda cute.
[Answer]
# JavaScript (ES6) 147 bytes
```
a=>{o=0;e=(c=>console.log(' '.repeat(o++)+c.join` `));l=1;while(l){p=0,d=[],e(a),a.map(b=>{p?d.push((v+b)%10):0;p=1,v=b});d.length<2?l=0:a=d};e(d)}
```
[Answer]
# Julia, ~~60~~ 59 bytes
```
\(x,s="")=x==[]?"":s*join(x," ")"
"*(diag(x'.+x,1)%10\" "s)
```
Based on [@Sp3000's answer](https://codegolf.stackexchange.com/a/82533). The function `\` accepts an array as input and returns a string.
[Try it online!](http://julia.tryitonline.net/#code=XCh4LHM9IiIpPXg9PVtdPyIiOnMqam9pbih4LCIgIikiCiIqKGRpYWcoeCcuK3gsMSklMTBcIiAicykKCnByaW50KFwoWzksIDIsIDQsIDUsIDMsIDIsIDJdKSk&input=)
[Answer]
## JavaScript (ES6), 77 bytes
```
a=a.map((_,i)=>(b=a,a=[a.map((e,j)=>j>i?(e+a[j-1])%10:''),b.join` `)).join`
`
```
[Answer]
## Pyke, 21 bytes
```
lVDm}R$],FsT%)od*pKDP
```
[Try it here!](http://pyke.catbus.co.uk/?code=lVDm%7DR%24%5D%2CFsT%25%29od%2apKDP&input=%5B1%2C+2%2C+3%2C+5%2C+8%5D)
I'd like to think this method's a little bit different.
```
[1, 2, 3, 5, 8] - take the input
[2, 4, 6, 10, 16] - double it
[1, 2, 3, 5, 8] - take the input again
[1, 1, 2, 3] - get the deltas
[[2,1], [4,1], [6,2], [10,3]] - transpose them together
[3, 5, 8, 13] - apply addition
[3, 5, 8, 3] - mod 10
```
[Answer]
# [Perl 6](http://perl6.org), ~~65 63 62~~ 61 bytes
```
~~{put ' 'x my$++,$\_ for @\_,{.rotor(2=>-1).map(\*.sum%10).list}...1}
{put ' 'x my$++,$\_ for @\_,{@(.rotor(2=>-1).map(\*.sum%10))}...1}
{put ' 'x my$++,$\_ for @\_,{@(map \*.sum%10,.rotor(2=>-1))}...1}~~
{put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}
```
### Explanation:
```
{ # anonymous block that takes the list as input (@_)
put # print with trailing newline
' ' x ( my $ )++, # pad with one more space than previous iteration
$_ # the list to print for this iteration
# The 「.Str」 method on a List puts spaces between elements
# which is what 「put」 calls on anything that isn't a Str
for # do that for every list produced from the following
@_, # the input list
{ # anonymous block that takes the previous list as input ($_)
[ # turn the following from a Seq into an Array
map
*.sum % 10, # sum the values and modulus 10 of the following:
# take the previous list 2 at a time, backing up one
$_.rotor( 2 => -1 )
]
}
... # repeatedly call that block until:
1 # the result is only one element long
}
```
### Example:
```
my &digital-triangle-sum = {put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}
for [7,5,0,9], [0,1,0], [1,0,0,0], [9,2,4,5,3,2,2] -> \List {
digital-triangle-sum List
put '';
}
```
```
7 5 0 9
2 5 9
7 4
1
0 1 0
1 1
2
1 0 0 0
1 0 0
1 0
1
9 2 4 5 3 2 2
1 6 9 8 5 4
7 5 7 3 9
2 2 0 2
4 2 2
6 4
0
```
[Answer]
# TSQL, ~~198~~ ~~194~~ 191 bytes
By using GOTO instead of one of the WHILE, I was able to golf 3 characters
Golfed
```
DECLARE @ varchar(100)= '1 2 3 4 5 6 7'
DECLARE @j INT=1,@i INT=LEN(@)a:
PRINT @
WHILE @i>@j
SELECT
@=STUFF(@,@i-1,2,RIGHT(SUBSTRING(@,@i-2,1)+SUBSTRING(@,@i,1)*1,1)+' '),@i-=2SELECT
@=STUFF(@,@j,1,' '),@j+=1,@i=LEN(@)IF @i>0GOTO a
```
[Try it online](https://data.stackexchange.com/stackoverflow/query/499842/sum-it-up-with-a-digital-triangle)(using old script with 2\*WHILE)
[Answer]
# Java 7, ~~230~~ ~~215~~ 213 bytes
```
int c=0;void m(int[]a){int l=a.length,j=-1,i=-1;if(l<1)return;int[]x=new int[l-1];while(++j<c)p(" ");for(;++i<l;p(a[i]+" "))if(i<l&i>0)x[i-1]=(a[i-1]+a[i])%10;p("\n");c++;m(x);}<T>void p(T s){System.out.print(s);}
```
This ended up being a bit longer than I thought.. Maybe it can be golfed a bit more though, since I kinda messed up I think..
Some bytes saved thanks to *@GiacomoGarabello*.
**Ungolfed & test code:**
[Try it here.](https://ideone.com/saafcs)
```
class Main{
static int c = 0;
static void m(int[] a){
int l = a.length,
j = -1,
i = -1;
if(l < 1){
return;
}
int[] x = new int[l-1];
while(++j < c){
p(" ");
}
for(; ++i < l; p(a[i] + " ")){
if(i < l & i > 0){
x[i - 1] = (a[i - 1] + a[i]) % 10;
}
}
p("\n");
c++;
m(x);
}
static <T> void p(T s){
System.out.print(s);
}
static void printAndReset(int[] a){
m(a);
c = 0;
System.out.println();
}
public static void main(String[] a){
printAndReset(new int[]{ 7, 5, 0, 9 });
printAndReset(new int[]{ 0 });
printAndReset(new int[]{ 1, 2 });
printAndReset(new int[]{ 8, 7 });
printAndReset(new int[]{ 0, 0 });
printAndReset(new int[]{ 1, 4, 2 });
printAndReset(new int[]{ 0, 1, 0 });
printAndReset(new int[]{ 1, 0, 0, 0 });
printAndReset(new int[]{ 1, 2, 3, 4 });
printAndReset(new int[]{ 1, 2, 3, 5, 8 });
printAndReset(new int[]{ 9, 2, 4, 5, 3, 2, 2 });
}
}
```
**Output:**
```
7 5 0 9
2 5 9
7 4
1
0
1 2
3
8 7
5
0 0
0
1 4 2
5 6
1
0 1 0
1 1
2
1 0 0 0
1 0 0
1 0
1
1 2 3 4
3 5 7
8 2
0
1 2 3 5 8
3 5 8 3
8 3 1
1 4
5
9 2 4 5 3 2 2
1 6 9 8 5 4
7 5 7 3 9
2 2 0 2
4 2 2
6 4
0
```
[Answer]
# C# 6, ~~125+31~~ 125+18 = 143 bytes
```
string f(int[] n,string s="")=>s+string.Join(" ",n)+"\n"+(n.Length>1?f(n.Zip(n.Skip(1),(a,b)=>(a+b)%10).ToArray(),s+" "):"");
```
The +18 is for `using System.Linq;`
*Thanks to @TheLethalCoder for saving 13 bytes, by pointing out a unnecessary using statement*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
A translation of [Adnan's answer](https://codegolf.stackexchange.com/a/82531/64121) to modern 05AB1E.
```
vT%DðýNú,ü+
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/LETV5fCGw3v9Du/SObxH@///aHMdBVMdBQMdBctYAA "05AB1E – Try It Online")
`ú` pads a string with a given number of spaces and `ü` applies a binary function between pairs of adjacent items.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~99~~ 69 bytes
```
($a=$args)|%{"$s$a"
$a=$a|%{($p+$_)%10;$p=$_}|select -skip 1
$s+=" "}
```
[Try it online!](https://tio.run/##NYpBCoMwFAX3OcUnPItihGrtopRAz9ALSJDYSgMJ@YILzdnTInQ3M0zwq438ts41o482Y9JbLmE0THxxtRebBMNIcaSflgg1hqpoz3cEjSHtbJ0dF2r4MwdqBbjWkmTKSQhMc@Tl6VfSdFPUKeoVXRVdDu7ECRM9/k/@Ag "PowerShell Core – Try It Online")
*-99 bytes thanks to [@mazzy](https://codegolf.stackexchange.com/users/80745/mazzy) !*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
SƝƬ%⁵µ⁶oṚżK€ṖY
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//U8adxqwl4oG1wrXigbZv4bmaxbxL4oKs4bmWWf///1s3LCA1LCAwLCA5XQ "Jelly – Try It Online")
Full program which prints the result
## How it works
```
SƝƬ%⁵µ⁶oṚżK€ṖY - Main link. Takes a list L on the left
Ƭ - Until reaching a fixed point:
S - Take the sum of:
Ɲ - All overlapping pairs
%⁵ - Mod each by 10
µ - Begin a new link with the list of steps as the argument:
⁶o - Replace all elements with spaces
Ṛ - Reverse
K€ - Join each list with spaces
ż - Zip together
Ṗ - Remove the last line of spaces
Y - Join on newlines
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `C`, 10 bytes
```
λḢ+Ṫ₀%;↔vṄ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=C&code=%CE%BB%E1%B8%A2%2B%E1%B9%AA%E2%82%80%25%3B%E2%86%94v%E1%B9%84&inputs=%5B9%2C%202%2C%204%2C%205%2C%203%2C%202%2C%202%5D&header=&footer=)
```
λ ; # Push a lambda
Ḣ # Remove first item
+ # Vectorised addition to original
Ṫ # Remove last item
₀% # For each item, modulo 10
↔ # Repeat on input while output is truthy
vṄ # Foreach, join by spaces
# (C flag) Center and join by newlines.
```
-6 thanks to Aaron Miller.
Old version, 16 bytes:
```
L(ðn*₴DṄ,0p+vtḢṪ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%28%C3%B0n*%E2%82%B4D%E1%B9%84%2C0p%2Bvt%E1%B8%A2%E1%B9%AA&inputs=%5B9%2C%202%2C%204%2C%205%2C%203%2C%202%2C%202%5D&header=&footer=)
```
L( # Length times
ðn* # (iteration number) spaces
₴ # Output without a newline
D # Triple current array
Ṅ, # Output first joined by spaces
0p # Prepend a 0 to the second
+ # Vectorised addition
vt # Foreach, get last digit
ḢṪ # And get rid of first + last items
```
[Answer]
## C, 138 bytes
Golfed
```
c,d;main(int a,char**b){b++;while(c++,d=0,--a)while(d<a)printf("%*c%c",!d?c:1,*b[d],(d+2>a)*10),++d<a?*b[d-1]=(*b[d-1]+*b[d]-96)%10+48:0;}
```
Ungolfed
```
c,d;
main(int a,char**b){
b++;
while(c++,d=0,--a)
while(d<a)
printf("%*c%c",
!d?c:1, //number of blanks in front of digit
*b[d], //digit
(d+2>a)*10), //returns 10(new line) only for d+1 == a
++d<a
? *b[d-1]=(*b[d-1]+*b[d]-96)%10+48 //update digit
: 0;
}
```
[Answer]
## C#, 167 bytes
Im actually pretty proud of this solution, lambda expressions are so fun once you get the hang of them
```
void f(List<int> a){int x=a.Count;for(int s=0;s<x;s++){Console.WriteLine(new String(' ',s)+string.Join(" ",a));a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();}}
```
here ungolfed for further improvements:
```
void f(List<int> a)
{
int x = a.Count;
for (int s = 0; s<x ;s++)
{
Console.WriteLine(new String(' ',s)+string.Join(" ",a));
a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();
}
}
```
[try it out here](http://rextester.com/XJM57878)
[Answer]
# Haskell, 139 bytes
```
f=mapM(\(r,s)->putStrLn$r++(s>>=(++" ").show)).zip(iterate(' ':)"").takeWhile(/=[]).iterate g where g(_:[])=[];g(y:p:ys)=mod(y+p)10:g(p:ys)
```
Takes input as an argument, outputs to STDOUT.
Ungolfed version:
```
f = mapM (\(r, s) -> putStrLn $ r ++ (s >>= (++ " ") . show))
. zip (iterate (' ' :) "")
. takeWhile (/= [])
. iterate sumTerms
where sumTerms (_:[]) = []
sumTerms (y:p:ys) = mod (y+p) 10 : sumTerms (p:ys)
```
[Answer]
# Python 3, 97 bytes
```
def f(x):print(*x);x[-1]==''or f(['']+[(x[i]+x[i+1])%10if''!=x[i]else''for i in range(len(x)-1)])
```
Prints a single trailing newline.
**How it works**
```
def f(x): function with input of list of numbers
print(*x) print the old line of the triangle
x[-1]==''or... if no more numbers, stop...
(x[i]+x[i+1])%10if''!=x[i]else''... ...else compute the next entry in the new line if
possible...
...for i in range(len(x)-1) ...for all relevant digit pairs...
['']+... ...concatenate with empty string to force new leading
space...
f(...) ...and pass to function
```
[Try it on Ideone](https://ideone.com/Uk230L)
[Answer]
# J, 44 bytes
```
(#\.-#)|."_1#\.(":@{."_1)2(10|+/)\^:(]i.@#)]
```
Based on this [solution](https://codegolf.stackexchange.com/a/85758/6710).
[Answer]
## Javascript (using external library) (198 bytes)
```
n=>{a=_.From(n);b=a.Write(" ");c=1;while(++c){a=a.BatchAccumulate(2).Where(y=>y.Count()==2).Select(z=>z.Sum()%10);if(a.Count()==0){break;}b+="\r\n"+_.Range(0,c).Write(" ",x=>"")+a.Write(" ")}return b}
```
Link to lib: <https://github.com/mvegh1/Enumerable/>
Code explanation: This was easy using the library! Doesn't win in bytes, but the code isn't too verbose and easy to read. So, the input "n' is an array of integers. Load it up into the library, stored in variable "a". "b" is the return string, store the joined string with " " as delimiter into b. c is the current iteration, use this to determine the number of spaces to insert. NOTE: This only seems to work nicely when the input is from 0-9. Then, while true, repeat a certain set of code. That code is to create adjacent batch sets of the current enumerable "a", i.e if we have [1,2,3,4,5,6] we get [1,2],[2,3],[3,4],...[6] ... then filter that so we only have the batches of size 2. Then we map that to a collection of the sums of the batches % 10. If a is empty, we are done, else we add the new line to our return. Finally return...
Picture coming in a few min.
[![enter image description here](https://i.stack.imgur.com/xCdSp.png)](https://i.stack.imgur.com/xCdSp.png)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_ä+ muA}hUÊN m¸û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=X%2bQrIG11QX1oVcpOIG24%2bw&input=WzcsIDUsIDAsIDld)
```
_ä+ m%A}hNUÊ m¸û :Implicit input of array U
_ :Function taking an array as input
ä : Consecutive pairs
+ : Reduced by addition
m : Map
%A : Mod 10
} :End function
h :Run that function
N : Taking the last element of the array of all inputs, and pushing the results to it
UÊ : Until it's length matches the length of U
m :Map the final N
¸ : Join with spaces
û :Centre pad each with spaces to the length of the longest
:Implicit out put joined with newlines
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üε↕Φ¬ⁿ╣VU6Co'm
```
[Run and debug it](https://staxlang.xyz/#p=81ee12e8aafcb9565536436f276d&i=%5B7,+5,+0,+9%5D&m=2)
] |
[Question]
[
Write the shortest program that takes a single integer as input and prints out a [Suanpan abacus](http://en.wikipedia.org/wiki/Suanpan)
Testcases
Input:
```
314159
```
Output:
```
|\======================================/|
|| (__) (__) (__) (__) (__) (__) ||
|| (__) (__) (__) (__) || || ||
|| || || || || || || ||
|| || || || || (__) (__) ||
|<======================================>|
|| (__) (__) (__) (__) || (__) ||
|| (__) || (__) || || (__) ||
|| (__) || (__) || || (__) ||
|| || || (__) || || (__) ||
|| || || || || || || ||
|| || || || || (__) || ||
|| || (__) || (__) (__) || ||
|| || (__) || (__) (__) || ||
|| (__) (__) || (__) (__) || ||
|| (__) (__) (__) (__) (__) (__) ||
|/======================================\|
```
Input:
```
6302715408
```
Output:
```
|\==============================================================/|
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|| || (__) (__) (__) || (__) || (__) (__) || ||
|| || || || || || || || || || || ||
|| (__) || || || (__) || (__) || || (__) ||
|<==============================================================>|
|| (__) (__) || (__) (__) (__) || (__) || (__) ||
|| || (__) || (__) (__) || || (__) || (__) ||
|| || (__) || || || || || (__) || (__) ||
|| || || || || || || || (__) || || ||
|| || || || || || || || || || || ||
|| || || (__) || || || (__) || (__) || ||
|| (__) || (__) || || (__) (__) || (__) || ||
|| (__) || (__) (__) (__) (__) (__) || (__) || ||
|| (__) (__) (__) (__) (__) (__) (__) || (__) (__) ||
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|/==============================================================\|
```
[Answer]
## J, 126 124 121 119 116 115 113 105 116 115 112 characters
```
'|'s":(' 's[:,.(_6[\' || (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1[(s=:[,.~,.)9!:7'\=/<=>/=\|='
```
Takes input from the keyboard. Example:
```
'|'s":(' 's[:,.(_6[\' || (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1[(s=:[,.~,.)9!:7'\=/<=>/=\|='
6302715408
|\==============================================================/|
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|| || (__) (__) (__) || (__) || (__) (__) || ||
|| || || || || || || || || || || ||
|| (__) || || || (__) || (__) || || (__) ||
|<==============================================================>|
|| (__) (__) || (__) (__) (__) || (__) || (__) ||
|| || (__) || (__) (__) || || (__) || (__) ||
|| || (__) || || || || || (__) || (__) ||
|| || || || || || || || (__) || || ||
|| || || || || || || || || || || ||
|| || || (__) || || || (__) || (__) || ||
|| (__) || (__) || || (__) (__) || (__) || ||
|| (__) || (__) (__) (__) (__) (__) || (__) || ||
|| (__) (__) (__) (__) (__) (__) (__) || (__) (__) ||
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|/==============================================================\|
```
The main trick here is the abuse of J's boxing by redefining the characters it uses. It uses a [global parameter](http://jsoftware.com/help/dictionary/dx009.htm) - `9!:7` - to do this. There may be room for further golfing, but to be honest I was just glad to get something working that should compensate for [my last attempt at this question](https://codegolf.stackexchange.com/a/1585/737).
Fits in a tweet with enough characters left to say 'Gaz made this' :-).
**Edit:** 3 characters of savings are due to borrowing the `2 6$' || (__)'` from [Jesse Millikan's](https://codegolf.stackexchange.com/a/1777/737) answer.
**Further edit:** Lost 11 characters adding extra spaces at either side that I hadn't noticed were not present.
**Explanation:**
The code is in three main sections:
**1) Setup**
```
[(s=:[,.~,.)9!:7'\=/<=>/=\|='
```
This is itself in two parts.
`9!:7'\=/<=>/=\|='` redefines the characters that J will use to display boxes. J's boxing normally looks like this:
```
2 2$<"0[1 2 3 4
┌─┬─┐
│1│2│
├─┼─┤
│3│4│
└─┴─┘
```
but after redefining it looks like this:
```
2 2$<"0[1 2 3 4
\===/
|1|2|
<===>
|3|4|
/===\
```
`(s=:[,.~,.)` defines a verb I'm going to be using a couple of times later. This turns out to be the best place to declare it. It takes a character on the left and an array of characters on the right and sandwiches the array between the character. For example:
```
3 5$'abcdefghijklmno'
abcde
fghij
klmno
'-' s 3 5$'abcdefghijklmno'
-abcde-
-fghij-
-klmno-
```
The final `[` just serves to separate the setup from the next part.
**2) Input and Representation**
```
,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
```
`".,.1!:1[1` takes the input from the keyboard and separates it into individual digits:
```
".,.1!:1[1
314159
3 1 4 1 5 9
```
`((i.5)</5|])` creates a zeros and ones representation of the bottom part of the abacus:
```
((i.5)</5|]) 3 1 4 1 5 9
1 1 1 1 0 1
1 0 1 0 0 1
1 0 1 0 0 1
0 0 1 0 0 1
0 0 0 0 0 0
```
`|:@(1,.<&5)` creates a zeroes and ones representation of the top part of the abacus:
```
|:@(1,.<&5) 3 1 4 1 5 9
1 1 1 1 1 1
1 1 1 1 0 0
```
These two parts are boxed together using `;`:
```
(|:@(1,.<&5);((i.5)</5|])) 3 1 4 1 5 9
\=======================/
|1 1 1 1 1 1|1 1 1 1 0 1|
|1 1 1 1 0 0|1 0 1 0 0 1|
| |1 0 1 0 0 1|
| |0 0 1 0 0 1|
| |0 0 0 0 0 0|
/=======================\
```
Then the boxes are placed one on top of the other to form the basis of the abacus, giving:
```
,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\===========/
|1 1 1 1 1 1|
|1 1 1 1 0 0|
<===========>
|1 1 1 1 0 1|
|1 0 1 0 0 1|
|1 0 1 0 0 1|
|0 0 1 0 0 1|
|0 0 0 0 0 0|
/===========\
```
**3) Output**
```
'|'s":(' 's[:,.(_6[\' || (__)'){~(,-.))&.>
```
`&.>` means that what follows will operate on both boxes in turn.
`(,-.)` this is a hook which will negate the input and then add it to the end of the original:
```
2 5$1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
(,-.) 2 5$1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
0 1 0 1 0
0 1 0 1 0
```
This is really part of the representation, but for golfing purposes it's better to have it in this section. Applied to the previous input:
```
(,-.)&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\===========/
|1 1 1 1 1 1|
|1 1 1 1 0 0|
|0 0 0 0 0 0|
|0 0 0 0 1 1|
<===========>
|1 1 1 1 0 1|
|1 0 1 0 0 1|
|1 0 1 0 0 1|
|0 0 1 0 0 1|
|0 0 0 0 0 0|
|0 0 0 0 1 0|
|0 1 0 1 1 0|
|0 1 0 1 1 0|
|1 1 0 1 1 0|
|1 1 1 1 1 1|
/===========\
```
`[:,.(_6[\' || (__)'){~` The zeroes and ones are now used to select a string to represent a bead or the absence of one:
```
([:,.(_6[\' || (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\====================================/
| (__) (__) (__) (__) (__) (__) |
| (__) (__) (__) (__) || || |
| || || || || || || |
| || || || || (__) (__) |
<====================================>
| (__) (__) (__) (__) || (__) |
| (__) || (__) || || (__) |
| (__) || (__) || || (__) |
| || || (__) || || (__) |
| || || || || || || |
| || || || || (__) || |
| || (__) || (__) (__) || |
| || (__) || (__) (__) || |
| (__) (__) || (__) (__) || |
| (__) (__) (__) (__) (__) (__) |
/====================================\
```
But now, as Howard pointed out to me, there is one space short on either side of the beads. So we use the predefined `s` verb to sandwich the contents of each box between two columns of spaces:
```
(' 's[:,.(_6[\' || (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\======================================/
| (__) (__) (__) (__) (__) (__) |
| (__) (__) (__) (__) || || |
| || || || || || || |
| || || || || (__) (__) |
<======================================>
| (__) (__) (__) (__) || (__) |
| (__) || (__) || || (__) |
| (__) || (__) || || (__) |
| || || (__) || || (__) |
| || || || || || || |
| || || || || (__) || |
| || (__) || (__) (__) || |
| || (__) || (__) (__) || |
| (__) (__) || (__) (__) || |
| (__) (__) (__) (__) (__) (__) |
/======================================\
```
Having done that, all that's left is to convert this into a string using `":` so that we can sandwich it between two columns of `|`:
```
'|'s":(' 's[:,.(_6[\' || (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
|\======================================/|
|| (__) (__) (__) (__) (__) (__) ||
|| (__) (__) (__) (__) || || ||
|| || || || || || || ||
|| || || || || (__) (__) ||
|<======================================>|
|| (__) (__) (__) (__) || (__) ||
|| (__) || (__) || || (__) ||
|| (__) || (__) || || (__) ||
|| || || (__) || || (__) ||
|| || || || || || || ||
|| || || || || (__) || ||
|| || (__) || (__) (__) || ||
|| || (__) || (__) (__) || ||
|| (__) (__) || (__) (__) || ||
|| (__) (__) (__) (__) (__) (__) ||
|/======================================\|
```
[Answer]
## Ruby 1.9, 154 characters
```
puts'|\%s/|'%$r=?=*(2+6*gets.size),(0..14).map{|a|a==4?"|<#$r>|":"|| #{$_.gsub(/./){(5*a+n=$&.hex)/10!=1&&(a-n%5)/5!=1?' (__) ':' || '}} ||"},"|/#$r\\|"
```
Assumes the input is *not* terminated by a newline.
Fun fact: Due to the way I'm turning the input digits into numbers (`$&.hex` is one byte shorter than `$&.to_i`), this abacus actually works with hex digits up to `e`:
```
$ echo -n "0123456789abcdef" | ruby suanpan.rb
|\==================================================================================================/|
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) || || || || || || ||
|| (__) (__) (__) (__) (__) || || || || || || || || || || (__) ||
|| || || || || || || || || || || (__) (__) (__) (__) (__) (__) ||
|| || || || || || (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|<==================================================================================================>|
|| || (__) (__) (__) (__) || (__) (__) (__) (__) || (__) (__) (__) (__) || ||
|| || || (__) (__) (__) || || (__) (__) (__) || || (__) (__) (__) || ||
|| || || || (__) (__) || || || (__) (__) || || || (__) (__) || ||
|| || || || || (__) || || || || (__) || || || || (__) || ||
|| || || || || || || || || || || || || || || || || ||
|| (__) || || || || (__) || || || || (__) || || || || (__) ||
|| (__) (__) || || || (__) (__) || || || (__) (__) || || || (__) ||
|| (__) (__) (__) || || (__) (__) (__) || || (__) (__) (__) || || (__) ||
|| (__) (__) (__) (__) || (__) (__) (__) (__) || (__) (__) (__) (__) || (__) ||
|| (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) (__) ||
|/==================================================================================================\|
```
For `0xf`, a third bead magically appears in the upper half.
When allowing additional flags during script invocation, this can be shortened to 152 bytes (149 bytes code + 3 bytes additional invocation flags):
```
puts'|\%s/|'%$r=?=*(2+6*~/$/),(0..14).map{|a|a==4?"|<#$r>|":"|| #{$_.gsub(/./){(5*a+n=$&.hex)/10!=1&&(a-n%5)/5!=1?' (__) ':' || '}} ||"},"|/#$r\\|"
```
Run with `ruby -n suanpan.rb`.
[Answer]
## Perl (151 chars)
(~~168~~ ~~163~~ ~~158~~ ~~157~~ ~~156~~ ~~154~~)
```
$i=<>;$c.=$_-4?"
|| $i||":"
|<$m>|",$m='==',$c=~s!\d!$m.='='x6;($_-$&%5)/5%2|(5*$_+$&)/10%7==1?' || ':'(__) '!eg for 0..14;print"|\\$m/|$c
|/$m\\|"
```
### Explanation
```
# Read the number from STDIN.
$i = <>;
# for statement starts here...
# Append to $c a line containing either the horizontal dividing bar (in row #4)
# or the current abacus row with the digits in place of the pegs.
# This relies on the fact that $m will have been computed after at least one iteration.
$c .= $_-4 ? "\n|| $i||" : "\n|<$m>|",
# Notice that $m is redundantly recomputed from scratch in each iteration.
$m = '==',
# Substitute the correct pegs for the digit characters.
$c =~ s!\d!
$m .= '=' x 6;
# Weird expression for the abacus function.
# I have to use “% 7” because otherwise the division is floating-point...
# Notice that $_ is the row and $& is the digit.
($_ - $& % 5)/5 % 2 | (5*$_ + $&)/10 % 7 == 1
? ' || '
: '(__) '
!eg
for 0..14;
# Could shorten further by using “say” if you don’t mind excluding the “-E” from the count...
print "|\\$m/|$c\n|/$m\\|"
```
### Edits
* **(154 → 151)** Changed three `\n`s to actual newline characters. Can’t believe I didn’t think of that earlier!
[Answer]
## Windows PowerShell, 191
```
$y='='*(2+6*($i=[char[]]"$input").Count)
filter f($v){"|| $((' (__)',' || ')[($i|%{iex $_%$v})]) ||"}"|\$y/|"
f 1
f 10-ge5
f 1+1
f 10-lt5
"|<$y>|"
1..5|%{f 5-lt$_}
1..5|%{f 5-ge$_}
"|/$y\|"
```
History:
* 2011-03-11 23:54 **(340)** Initial attempt.
* 2011-03-12 00:21 **(323)** Using string interpolation throughout the code.
* 2011-03-12 00:21 **(321)** Inlined `$l`.
* 2011-03-12 01:07 **(299)** Used a function for the more repetitive parts as well as a format string.
* 2011-03-12 01:19 **(284)** Changed the arguments to the function slightly. Hooray for command parsing mode.
* 2011-03-12 01:22 **(266)** More variables for recurring expressions.
* 2011-03-12 01:28 **(246)** Now every row is generated by the function.
* 2011-03-12 01:34 **(236)** Since I use the chars only in string interpolation I can safely ignore the `%` that makes numbers from the digits.
* 2011-03-12 01:34 **(234)** Slightly optimized the array index generation in the function.
* 2011-03-12 01:42 **(215)** I no longer need `$r` and `$b`. And `$a` is also obsolete. As is `$l`.
* 2011-03-12 01:46 **(207)** No need to set `$OFS` if I need it only once.
* 2011-03-12 01:49 **(202)** Inlined `$f`.
* 2011-03-12 01:57 **(200)** No need for the format string anymore. String interpolation works just fine.
* 2011-03-12 02:00 **(198)** Slightly optimized generating the individual rows (re-ordering the pipeline and array index).
* 2011-03-12 02:09 **(192)** No need for `-join` since we can actually use the additional space to good effect.
[Answer]
## Haskell, 243 characters
```
z x|x=" (__) ";z _=" || "
h[a,b]d f w='|':a:replicate(2+6*length d)'='++b:"|\n"++q z++q(z.not)
where q b=w>>=(\v->"|| "++(d>>=b.(>v).f)++" ||\n")
s d=h"\\/"d(5-)[-9,0]++h"><"d(`mod`5)[0..4]++h"/\\"d id[]
main=interact$s.map(read.(:[])).init
```
Not particularly clever. I'm sure it can be shortened somehow...
---
* Edit: (246 -> 243) took @FUZxxl's suggestion to use interact
[Answer]
## Delphi, 348
This version builds up a string to write just once; The digits are handled by a separate function that works via a `digit modulo m >= value` construct (negated if value <0).
```
var d,s,o,p:string;c:Char;i:Int8;function g(m,v:Int8):string;begin p:='|| ';for c in d do p:=p+Copy(' || (__) ',1+6*Ord(((Ord(c)+2)mod m>=Abs(v))=(v>0)),6);g:=p+' ||'^J;end;begin ReadLn(d);s:=StringOfChar('=',2+6*Length(d));for i:=1to 5do o:=g(5,6-i)+o+g(5,-i);Write('|\'+s+'/|'^J+g(1,-1)+g(10,-5)+g(1,1)+g(10,5)+'|<'+s+'>|'^J+o+'|/'+s+'\|')end.
```
Delphi, 565
First attempt :
```
var _:array[0..6]of string=(' || ',' ( ) ','======','|\==/|','|| ||','|/==\|','|<==>|');m:array[0..186]of Byte;o:array[0..16]of string;i,j,c,f,l:Word;begin for i:=0to 9do begin f:=i*17;m[f+1]:=1;m[f+2]:=Ord(i<5);m[f+3]:=0;m[f+4]:=Ord(i>4);for j:=6to 10do m[f+j]:=Ord(i mod 5>j-6);for j:=11to 15do m[f+j]:=Ord(i mod 5<=j-11);m[f]:=2;m[5+f]:=2;m[16+f]:=2;end;f:=170;m[f]:=3;for i:=1to 15do m[f+i]:=4;m[f+5]:=6;m[f+16]:=5;repeat for i:=0to 16do Insert(_[m[f+i]],o[i],l);Read(PChar(@c)^);c:=c-48;f:=c*17;l:=Length(o[0])-2;until c>9;for i:=0to 16do WriteLn(o[i])end.
```
This uses 3 arrays; one for the 7 strings that could be discerned, one for the output lines and one to map the 7 strings to 11 columns (10 digits and 1 initial column).
[Answer]
### GolfScript, 139 characters
```
0+17'|':Q*:R'\<||'4Q**'/'+@{48-.5<)[1]*2,2*$+4<\5%[1]*2,5*$+10<+`{{1$=}%+2>'=='1/*5/('='+\+}+' (|_|_ )'2//}/;;;;'/>||'4Q**'\\'+R]zip n*
```
Not much golfed yet, but it fits into a tweet (with only ASCII). Try it [here](http://golfscript.apphb.com/?c=IjMxNDE1OSIKCjArMTcnfCc6USo6UidcPHx8JzRRKionLycrQHs0OC0uNTwpWzFdKjIsMiokKzQ8XDUlWzFdKjIsNSokKzEwPCtge3sxJD19JSsyPic9PScxLyo1LygnPScrXCt9KycgICAgICh8X3xfICknMi8vfS87Ozs7Jy8%2BfHwnNFEqKidcXCcrUl16aXAgbioK&run=true).
[Answer]
# J, 225
Passes two tests given, should work up to at least several hundred digits.
```
c=:2 6$' || (__)'
f=:(2{.[),('='#~2+6*#@]),2}.[
d=:'||',"1' ||',~"1,"2&(c{~|:)
g=:('|\/|'&f,d&(1,.-.,.0,.])&(4&<),'|<>|'&f,d&(5($!.0"1)0,~"(1)1#~"0|~&5),|.&d&(5($!.0"1)1#~"0(5-5|])),'|/\|'&f)
4(1!:2)~LF,"1 g"."0}:(1!:1)3
```
First off: Yes, yes, gravedigging. Second: That's just embarassingly long. Oh well. I haven't decided yet whether to golf it further or curl up in fetal position and cry. (Or both!)
Here's a bit of explanation in lieu of a shorter program:
* c is 2x6 table of empty cell, bead cell for rendering.
* f renders an '=' row with the four outside characters as left argument.
* d renders an abacus row by translating 0/1 matrices into bead cells padded with ||
* g takes digits and vertically compiles character rows using f for 'formatting' rows and d for abacus rows.
* The last row gets input, splits into characters and converts those to numbers, feeds to g and then prints.
[Answer]
## C, ~~277~~ 274 characters
You know, it seems to me that we just don't have enough solutions here that really take advantage of the C preprocessor. Partly that's because those `#define`s actually take up a fair bit of space. But still, there's so much potential. I feel the need to address this deficiency.
```
#define L(x,z)for(printf("|"x),p=b;*p||puts(#z)<0;++p)printf(
#define F(x,y,z)L(#x,==z|)"======",y);
#define T(y)L("| ",||)*p-47 y?"(__) ":" || ");
i;char*p,b[99];main(j){gets(b);F(\\,0,/)T()T(<6)T(<1)T(>5)F(<,*p>52?*p-=5:0,>)
for(;++i<6;)T(>i)for(;++j<7;)T(<j)F(/,0,\\)}
```
That's better.
[Answer]
# Mathematica 281
```
w@n_:= Module[{t=Table,f,g},
f@d_:=ReplacePart["O"~t~{7},{2-Quotient[d,5]-> "|",3+Mod[d,5]-> "|"}];
g@k_:=IntegerDigits@n~PadLeft~10;
Grid[Insert[Insert[(f/@g@n)T,"=="~t~{10},{{1},{3},{8}}]T,""~t~{10},{{1},{11}}]T]]
```
**Example**
```
w[6302715408]
```
![abacus](https://i.stack.imgur.com/EIr1U.png)
[Answer]
## C, 548
```
#define p(a) printf(a);
#define F(x,m) for(x=0;x<m;x++)
#define I(x) {p("||")F(j,l)if(b[l*(i+x)+j]){p(" (__)")}else{p(" || ")}p(" ||\n")}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int a,char* c[]){int i,j,l,m,*b;l=strlen(c[1]);b=(int*)malloc(l*56);m=6*l;F(i,14*l)b[i]=0;
F(j,l){b[j]=1;if(c[1][j]<53){b[l+j]=1;}else{b[3*l+j]=1;c[1][j]-=5;}F(i,5){if(i<c[1][j]-'0'){
b[(i+5)*l+j]=1;}else{b[(i+9)*l+j]=1;}}}p("|\\=")F(i,m)p("=")p("=/|\n")F(i,4)I(0)p("|<=")F(i,m)
p("=")p("=>|\n")F(i,9)I(5)p("|/=")F(i,m)p("=")p("=\\|\n")}
```
First version, just a bit of golfing so far.
[Answer]
## Scala (489 characters)
```
def a(i:String){val b=" (__) ";val n=" || ";1 to 17 map{l=>;{print(l match{case 1=>"|\\=";case 6=>"|<=";case 17=>"|/=";case _=>"|| "});print(l match{case 1|6|17=>"======"*i.size;case 2|16=>b*i.size;case 4|11=>n*i.size;case 3=>i flatMap{d=>{if(d.asDigit<5)b else n}};case 5=>i flatMap{d=>{if(d.asDigit>4)b else n}};case _=>i flatMap{d=>{if(l<11)if(d.asDigit%5<l-6)n else b else if(d.asDigit%5>l-12)n else b}}});;print(l match{case 1=>"=/|";case 6=>"=>|";case 17=>"=\\|";case _=>" ||"})}}}
```
Pretty crappy attempt really.
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting), 77 chars
The bounty refers to *tweets*, and Twitter counts *characters* (not bytes). :)
```
꿓뤽꿓뤽①長復標독렽꿐②껷렊밃겠上❶가侔是丟돃렽꿐②꿧렊不돇렠글⓶①各❷❷걐剩減갰減갰分❸⓷걀大加增增감右與꺅뭟꺒갠⓵긇롼긂갠嗎⓶終丟돇렊終終돂묽꿐②뇇렊
```
I actually wrote this years ago (when this challenge was posted), but I never posted it because I invented Sclipting after this challenge was first posted. If you feel that this makes it ineligible, I understand.
## Explanation
```
꿓뤽꿓뤽①長復 | let x = "======" times the length of the input string
標 | mark
독렽꿐②껷렊 | "|\\==" + x + "/|\n"
밃겠上 | for row in [-4 .. 10]
❶가侔是 | if row == 0
丟돃렽꿐②꿧렊 | "|<==" + x + ">|\n"
不 | else
돇렠글 | "|| "
⓶①各 | foreach char c in input
| ((r-(c%5)-3)/3 & ((r + (c>4?3:2)) >> 1)) ? "(__) " : " || "
❷❷걐剩減갰減갰分❸⓷걀大加增增감右與꺅뭟꺒갠⓵긇롼긂갠嗎⓶
終丟
돇렊 | "||\n"
終
終
돂묽꿐②뇇렊 | "|/==" + x + "\\|\n"
```
[Answer]
# Python, ~~309~~ ~~301~~ 288 chars
Compact version:
```
q=p,b=" || "," (__) "
t="|| %s ||\n"
a=lambda h:t%"".join(q[i]for i in h)
n=[int(d)for d in str(input())]
c=len(n)
e="="*(c*6+2)
h="|\\"+e+"/|"
print h+"\n"+t%(b*c)+a(d<5 for d in n)+t%(p*c)+a(d>4 for d in n)+"|<"+e+">|\n"+"".join(a((d%5>i%5)^(i>4)for d in n)for i in range(10))+h[::-1]
```
Clear version:
```
bead = " (__) "
pole = " || "
template = "|| %s ||\n"
output = ""
def addline(hasbeads):
global output
output += template % "".join([bead if item else pole for item in hasbeads])
digits = [int(d) for d in str(input())]
count = len(digits)
equalsigns = "=" * (count * 6 + 2)
output = ""
header = "|\\" + equalsigns + "/|"
output += header + "\n"
output += template % (bead * count)
addline([d < 5 for d in digits])
output += template % (pole * count)
addline([d > 4 for d in digits])
output += "|<" + equalsigns + ">|\n"
for i in range(5):
addline([d % 5 > i for d in digits])
for i in range(5):
addline([d % 5 <= i for d in digits])
output += header[::-1]
print output
```
Note that for compactification, variables were renamed to a single letter, and list comprehensions were changed to generators that don't require extra brackets.
] |
[Question]
[
Consider a potentially self-intersecting polygon, defined by a list of vertices in 2D space. E.g.
```
{{0, 0}, {5, 0}, {5, 4}, {1, 4}, {1, 2}, {3, 2}, {3, 3}, {2, 3}, {2, 1}, {4, 1}, {4, 5}, {0, 5}}
```
There are several ways to define the area of such a polygon, but the most interesting one is the even-odd rule. Taking any point in the plane, draw a line from the point out to infinity (in any direction). If that line crosses the polygon an odd number of times, the point is part of the polygon's area, if it crosses the polygon an even number of times, the point is not part of the polygon. For the above example polygon, here are both its outline as well as its even-odd area:
![Outline](https://i.stack.imgur.com/kyM22.png)![Area](https://i.stack.imgur.com/kYK1h.png)
The polygon will not in general be orthogonal. I've only chosen such a simple example to make it easier to count the area.
The area of this example is `17` (not `24` or `33` as other definitions or area might yield).
Note that under this definition the area of the polygon is independent of its winding order.
## The Challenge
Given a list of vertices with integer coordinates defining a polygon, determine its area under the even-odd rule.
You may write a function or program, taking input via STDIN or closest alternative, command-line argument or function argument and either return the result or print it to STDOUT or closest alternative.
You may take input in any convenient list or string format, as long as it's not preprocessed.
The result should either be floating point number, accurate to 6 significant (decimal) digits, or a rational result whose floating point representation is accurate to 6 significant digits. (If you produce rational results they are likely going to be exact, but I can't require this, as I don't have exact results for reference.)
You must be able to solve each of the test cases below within 10 seconds on a reasonable desktop machine. (There is some leeway in this rule, so use your best judgement. If it takes 20 seconds on my laptop I'll give you the benefit of the doubt, if it takes a minute, I won't.) I think this limit should be very generous but it is supposed to rule out approaches where you just discretise the polygon on a sufficiently fine grid and count, or use probabilistic approaches like Monte Carlo. Be a good sportsman and don't try to optimise of these approaches such that you can meet the time limit anyway. ;)
You must not use any existing functions related directly to polygons.
This is code golf, so the shortest submission (in bytes) wins.
### Assumptions
* All coordinates are integers in the range `0 ≤ x ≤ 100`, `0 ≤ y ≤ 100`.
* There will be at least `3` and at most `50` vertices.
* There won't be any repeated vertices. Neither will any vertices lie on another edge. (There *may* be collinear points in the list, though.)
## Test Cases
```
{{0, 0}, {5, 0}, {5, 4}, {1, 4}, {1, 2}, {3, 2}, {3, 3}, {2, 3}, {2, 1}, {4, 1}, {4, 5}, {0, 5}}
17.0000
{{22, 87}, {6, 3}, {98, 77}, {20, 56}, {96, 52}, {79, 34}, {46, 78}, {52, 73}, {81, 85}, {90, 43}}
2788.39
{{90, 43}, {81, 85}, {52, 73}, {46, 78}, {79, 34}, {96, 52}, {20, 56}, {98, 77}, {6, 3}, {22, 87}}
2788.39
{{70, 33}, {53, 89}, {76, 35}, {14, 56}, {14, 47}, {59, 49}, {12, 32}, {22, 66}, {85, 2}, {2, 81},
{61, 39}, {1, 49}, {91, 62}, {67, 7}, {19, 55}, {47, 44}, {8, 24}, {46, 18}, {63, 64}, {23, 30}}
2037.98
{{42, 65}, {14, 59}, {97, 10}, {13, 1}, {2, 8}, {88, 80}, {24, 36}, {95, 94}, {18, 9}, {66, 64},
{91, 5}, {99, 25}, {6, 66}, {48, 55}, {83, 54}, {15, 65}, {10, 60}, {35, 86}, {44, 19}, {48, 43},
{47, 86}, {29, 5}, {15, 45}, {75, 41}, {9, 9}, {23, 100}, {22, 82}, {34, 21}, {7, 34}, {54, 83}}
3382.46
{{68, 35}, {43, 63}, {66, 98}, {60, 56}, {57, 44}, {90, 52}, {36, 26}, {23, 55}, {66, 1}, {25, 6},
{84, 65}, {38, 16}, {47, 31}, {44, 90}, {2, 30}, {87, 40}, {19, 51}, {75, 5}, {31, 94}, {85, 56},
{95, 81}, {79, 80}, {82, 45}, {95, 10}, {27, 15}, {18, 70}, {24, 6}, {12, 73}, {10, 31}, {4, 29},
{79, 93}, {45, 85}, {12, 10}, {89, 70}, {46, 5}, {56, 67}, {58, 59}, {92, 19}, {83, 49}, {22,77}}
3337.62
{{15, 22}, {71, 65}, {12, 35}, {30, 92}, {12, 92}, {97, 31}, {4, 32}, {39, 43}, {11, 40},
{20, 15}, {71, 100}, {84, 76}, {51, 98}, {35, 94}, {46, 54}, {89, 49}, {28, 35}, {65, 42},
{31, 41}, {48, 34}, {57, 46}, {14, 20}, {45, 28}, {82, 65}, {88, 78}, {55, 30}, {30, 27},
{26, 47}, {51, 93}, {9, 95}, {56, 82}, {86, 56}, {46, 28}, {62, 70}, {98, 10}, {3, 39},
{11, 34}, {17, 64}, {36, 42}, {52, 100}, {38, 11}, {83, 14}, {5, 17}, {72, 70}, {3, 97},
{8, 94}, {64, 60}, {47, 25}, {99, 26}, {99, 69}}
3514.46
```
[Answer]
# Python 2, ~~323~~ 319 bytes
```
exec u"def I(s,a,b=1j):c,d=s;d-=c;c-=a;e=(d*bX;return e*(0<=(b*cX*e<=e*e)and[a+(d*cX*b/e]or[]\nE=lambda p:zip(p,p[1:]+p);S=sorted;P=E(input());print sum((t-b)*(r-l)/2Fl,r@E(S(i.realFa,b@PFe@PFi@I(e,a,b-a)))[:-1]Fb,t@E(S(((i+j)XFe@PFi@I(e,l)Fj@I(e,r)))[::2])".translate({70:u" for ",64:u" in ",88:u".conjugate()).imag"})
```
Takes a list of vertices through STDIN as complex numbers, in the following form
```
[ X + Yj, X + Yj, ... ]
```
, and writes the result to STDOUT.
Same code after string replacement and some spacing:
```
def I(s, a, b = 1j):
c, d = s; d -= c; c -= a;
e = (d*b.conjugate()).imag;
return e * (0 <= (b*c.conjugate()).imag * e <= e*e) and \
[a + (d*c.conjugate()).imag * b/e] or []
E = lambda p: zip(p, p[1:] + p);
S = sorted;
P = E(input());
print sum(
(t - b) * (r - l) / 2
for l, r in E(S(
i.real for a, b in P for e in P for i in I(e, a, b - a)
))[:-1]
for b, t in E(S(
((i + j).conjugate()).imag for e in P for i in I(e, l) for j in I(e, r)
))[::2]
)
```
## Explanation
For each point of intersection of two sides of the input polygon (including the vertices), pass a vertical line though that point.
![Figure 1](https://i.stack.imgur.com/krhM4.png)
(In fact, due to golfing, the program passes a few more lines; it doesn't really matter, as long as we pass at least these lines.)
The body of the polygon between any two consecutive lines is comprised of vertical trapezoids (and triangles, and line segments, as special cases of those).
It has to be the case, since if any of these shapes had an additional vertex between the two bases, there would be another vertical line through that point, between the two lines in question.
The sum of the areas of all such trapezoids is the area of the polygon.
Here's how we find these trapezoids:
For each pair of consecutive vertical lines, we find the segments of each side of the polygon that (properly) lie between these two lines (which might not exist for some of the sides).
In the above illustration, these are the six red segments, when considering the two red vertical lines.
Note that these segments don't properly intersect each other (i.e., they may only meet at their end points, completely coincide or not intersect at all, since, once again, if they properly intersected there would be another vertical line in between;) and so it makes sense to talk about ordering them top-to-bottom, which we do.
According to the even-odd rule, once we cross the first segment, we're inside the polygon; once we cross the second one, we're out; the third one, in again; the fourth, out; and so on...
In other words, if we group the segments into consecutive pairs, each pair is the legs of one of the trapezoids.
Overall, this is an *O*(*n*3 log *n*) algorithm.
[Answer]
# Mathematica, ~~247~~ ~~225~~ 222
```
p=Partition[#,2,1,1]&;{a_,b_}~r~{c_,d_}=Det/@{{a-c,c-d},{a,c}-b}/Det@{a-b,c-d};f=Abs@Tr@MapIndexed[Det@#(-1)^Tr@#2&,p[Join@@MapThread[{1-#,#}&/@#.#2&,{Sort/@Cases[{s_,t_}/;0<=s<=1&&0<=t<=1:>s]/@Outer[r,#,#,1],#}]&@p@#]]/2&
```
First add the points of intersection to the polygon, then reverse some of the edges, then its area can be calculated just like a simple polygon.
![enter image description here](https://i.stack.imgur.com/EuEAh.png)
Example:
```
In[2]:= f[{{15, 22}, {71, 65}, {12, 35}, {30, 92}, {12, 92}, {97, 31}, {4, 32}, {39, 43}, {11, 40},
{20, 15}, {71, 100}, {84, 76}, {51, 98}, {35, 94}, {46, 54}, {89, 49}, {28, 35}, {65, 42},
{31, 41}, {48, 34}, {57, 46}, {14, 20}, {45, 28}, {82, 65}, {88, 78}, {55, 30}, {30, 27},
{26, 47}, {51, 93}, {9, 95}, {56, 82}, {86, 56}, {46, 28}, {62, 70}, {98, 10}, {3, 39},
{11, 34}, {17, 64}, {36, 42}, {52, 100}, {38, 11}, {83, 14}, {5, 17}, {72, 70}, {3, 97},
{8, 94}, {64, 60}, {47, 25}, {99, 26}, {99, 69}}]
Out[2]= 3387239559852305316061173112486233884246606945138074528363622677708164\
6419838924305735780894917246019722157041758816629529815853144003636562\
9161985438389053702901286180223793349646170997160308182712593965484705\
3835036745220226127640955614326918918917441670126958689133216326862597\
0109115619/\
9638019709367685232385259132839493819254557312303005906194701440047547\
1858644412915045826470099500628074171987058850811809594585138874868123\
9385516082170539979030155851141050766098510400285425157652696115518756\
3100504682294718279622934291498595327654955812053471272558217892957057\
556160
In[3]:= N[%] (*The numerical value of the last output*)
Out[3]= 3514.46
```
[Answer]
# Haskell, 549
It doesn't look like I can golf this one down far enough, but the concept was different than the other two answers so I figured I'd share it anyway. It performs O(N^2) rational operations to compute the area.
```
import Data.List
_%0=2;x%y=x/y
h=sort
z f w@(x:y)=zipWith f(y++[x])w
a=(%2).sum.z(#);(a,b)#(c,d)=b*c-a*d
(r,p)?(s,q)=[(0,p)|p==q]++[(t,v t p r)|u t,u$f r]where f x=(d q p#x)%(r#s);t=f s;u x=x^2<x
v t(x,y)(a,b)=(x+t*a,y+t*b);d=v(-1)
s x=zip(z d x)x
i y=h.(=<<y).(?)=<<y
[]!x=[x];x!_=x
e n(a@(x,p):y)|x>0=(n!y,a):(e(n!y)$tail$dropWhile((/=p).snd)y)|0<1=(n,a):e n y
c[p]k=w x[]where((_,q):x)=e[]p;w((n,y):z)b|q==y=(k,map snd(q:b)):c n(-k)|0<1=w z(y:b);c[]_=[]
b(s,p)=s*a p
u(_,x)(_,y)=h x==h y
f p=abs$sum$map b$nubBy u$take(length p^2)$c[cycle$i$s p]1
```
*Example:*
```
λ> f test''
33872395598523053160611731124862338842466069451380745283636226777081646419838924305735780894917246019722157041758816629529815853144003636562916198543838905370290128618022379334964617099716030818271259396548470538350367452202261276409556143269189189174416701269586891332163268625970109115619 % 9638019709367685232385259132839493819254557312303005906194701440047547185864441291504582647009950062807417198705885081180959458513887486812393855160821705399790301558511410507660985104002854251576526961155187563100504682294718279622934291498595327654955812053471272558217892957057556160
λ> fromRational (f test'')
3514.4559380388832
```
The idea is to rewire the polygon at every crossing, resulting in a union of polygons with no intersecting edges. We can then compute the (signed) area of each of the polygons using Gauss' shoelace formula (<http://en.wikipedia.org/wiki/Shoelace_formula>). The even-odd rule demands that when a crossing is converted, the area of the new polygon is counted negatively relative to the old polygon.
For example, consider the polygon in the original question. The crossing in the upper-left is converted to two paths which only meet at a point; the two paths are both oriented clockwise, so the areas of each would be positive unless we declared that the inner path is weighted by -1 relative to the outer path. This is equivalent to alphaalpha's path reversal.
![Polygons derived from original example](https://i.stack.imgur.com/JW7ne.png)
As another example, consider the polygon from MickyT's comment:
![Polygons derived from MickyT's comment](https://i.stack.imgur.com/ZJhza.png)
Here, some of the polygons are oriented clockwise and some counterclockwise. The sign-flip-on-crossing rule ensures that the clockwise-oriented regions pick up an extra factor of -1, causing them to contribute a positive amount to the area.
Here's how the program works:
```
import Data.List -- for sort and nubBy
-- Rational division, with the unusual convention that x/0 = 2
_%0=2;x%y=x/y
-- Golf
h=sort
-- Define a "cyclic zipWith" operation. Given a list [a,b,c,...z] and a binary
-- operation (@), z (@) [a,b,c,..z] computes the list [b@a, c@b, ..., z@y, a@z]
z f w@(x:y)=zipWith f(y++[x])w
-- The shoelace formula for the signed area of a polygon
a=(%2).sum.z(#)
-- The "cross-product" of two 2d vectors, resulting in a scalar.
(a,b)#(c,d)=b*c-a*d
-- Determine if the line segment from p to p+r intersects the segment from
-- q to q+s. Evaluates to the singleton list [(t,x)] where p + tr = x is the
-- point of intersection, or the empty list if there is no intersection.
(r,p)?(s,q)=[(0,p)|p==q]++[(t,v t p r)|u t,u$f r]where f x=(d q p#x)%(r#s);t=f s;u x=x^2<x
-- v computes an affine combination of two vectors; d computes the difference
-- of two vectors.
v t(x,y)(a,b)=(x+t*a,y+t*b);d=v(-1)
-- If x is a list of points describing a polygon, s x will be the list of
-- (displacement, point) pairs describing the edges.
s x=zip(z d x)x
-- Given a list of (displacement, point) pairs describing a polygon's edges,
-- create a new polygon which also has a vertex at every point of intersection.
-- Mercilessly golfed.
i y=h.(=<<y).(?)=<<y
-- Extract a simple polygon; when an intersection point is reached, fast-forward
-- through the polygon until we return to the same point, then continue. This
-- implements the edge rewiring operation. Also keep track of the first
-- intersection point we saw, so that we can process that polygon next and with
-- opposite sign.
[]!x=[x];x!_=x
e n(a@(x,p):y)|x>0=(n!y,a):(e(n!y)$tail$dropWhile((/=p).snd)y)|0<1=(n,a):e n y
-- Traverse the polygon from some arbitrary starting point, using e to extract
-- simple polygons marked with +/-1 weights.
c[p]k=w x[]where((_,q):x)=e[]p;w((n,y):z)b|q==y=(k,map snd(q:b)):c n(-k)|0<1=w z(y:b);c[]_=[]
-- If the original polygon had N vertices, there could (very conservatively)
-- be up to N^2 points of intersection. So extract N^2 polygons using c,
-- throwing away duplicates, and add up the weighted areas of each polygon.
b(s,p)=s*a p
u(_,x)(_,y)=h x==h y
f p=abs$sum$map b$nubBy u$take(length p^2)$c[cycle$i$s p]1
```
] |
[Question]
[
**The Situation:**
Several (`M`) dwarves have found a goblin's chest with `N` gold coins and have to divide them. Due to ancient rules governing the allocation of loot to pirates in order of seniority, the oldest dwarf should get one coin more than the next oldest dwarf, and so on, so that the youngest dwarf gets `M-1` fewer coins than the oldest dwarf. Additionally, no dwarf has to pitch in any coins (ie no negative coins to any dwarfs)
Help the dwarves to divide the coins in this way, or tell them that this is impossible.
Winner's code must always answer correctly (this challenge is deterministic) and follow the general [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules.
**Input**
You are given an integer N (3 ≤ N ≤ 1000) for number of coins and an integer M (3 ≤ M ≤ N) for number of dwarves, space-separated.
**Output**
If it is impossible to divide the coins in the way that dwarves want, print -1 (minus one). Otherwise, print the numbers of coins that each dwarf will receive, from oldest to youngest. Separate the numbers with spaces.
**Samples**:
**input**
```
3 3
```
**output**
```
2 1 0
```
**input**
```
9 3
```
**output**
```
4 3 2
```
**input**
```
7 3
```
**output**
```
-1
```
**input**
```
6 4
```
**output**
```
3 2 1 0
```
[Answer]
# J - ~~32~~ ~~29~~ ~~28~~ 25
~~Not~~ shorter than other J solution, ~~but~~ and uses a different idea
```
(]{.[:i:-:@-.@]-%)/ ::_1:
```
The answer for the number of coins the highest rank gnome is getting is simply `N/M+(M-1)/2` (if it's an integer), we construct the negative of this `-:@-.@]-%`. Then `i:` makes an array like that `2 1 0 _1 _2` for argument `_2` and we take M elements from it.
[Answer]
# J - 30 char
Very fun to golf. A lot of things worked out neatly.
```
((+/@s~i.[){ ::_1:s=.+/&i.&-)/
```
Explanation:
* `/` - Take the space-separated integers as argument, and slip the function between them. That is to say, consider N the left argument to the function in the brackets `(...)` and M the right argument.
* `i.&-` - Negate (`-`) and then take integers (`i.`). Normally, when you do something like `i.5` you get `0 1 2 3 4`. Whenever `i.` receives a negative number, however, it reverses that output list. So e.g. `i._5` will give `4 3 2 1 0`.
* `s=.+/&` - Perform the above action on each argument (`&`) and then make an addition table (`+/`) out of these arrays. We now have a table where each row is a possible coin distribution to M dwarves, though maybe not when there's N coins. Finally, this table-making verb is so useful we're going to call it `s` and use it again later.
* `+/@s~` - Now, we use `s` again, but we swap (`~`) the order of the arguments, so that we transpose the table. This is a golfy way of taking the sum of each row after creating the table (`+/@`), having to do with the way J sums multidimensional lists.
* `i.[` - In this list of sums, we search for the left argument to the verb, i.e. N. If N is an item, we get that index: else we get the length of the list, which notably is an invalid index.
* `{ ::_1:` - Now we try to use the index to pull out a row from table in `s`. `{` will throw a domain error if the index was invalid, so in that case we catch the error (`::`) and return -1 (`_1:`). This handles everything. Since we use `i.&-` previously, the coin distribution will be in descending order, as was required.
Usage:
```
((+/@s~i.[){ ::_1:s=.+/&i.&-)/ 9 3
4 3 2
((+/@s~i.[){ ::_1:s=.+/&i.&-)/ 7 3
_1
((+/@s~i.[){ ::_1:s=.+/&i.&-)/ 6 4
3 2 1 0
((+/@s~i.[){ ::_1:s=.+/&i.&-)/ 204 17
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4
```
[Answer]
# R - ~~71~~ ~~70~~ ~~67~~ ~~66~~ 65 chars
```
s=scan();m=s[2];x=s[1]-sum(1:m);cat(if(x%%m|-m>x)-1 else x/m+m:1)
```
Ungolfed:
```
s = scan() # Reads N and M by stdin.
m = s[2]
x = s[1] - m*(m-1)/2
cat(if (x %% m | x < -m) -1 else x/m + m:1)
```
Solution:
If *M* the number of dwarfs, then the sequence of paid gold can be decomposed to two singular series. First a series ending in zero: M-1, ..., 2, 1, 0 and a constant series of c, c, ..., c. The sum of the first series is always M\*(M-1)/2. So if the remainder (x = N - M\*(M-1)/2) could be divided without remainder (modulo equal 0), each dwarf gets x/M plus the part of the decreasing series.
Usage:
```
> s=scan()
1: 10 4
3:
Read 2 items
> m=s[2]
> x = s[1] - m*(m-1)/2
> cat(if (x %% m || x<0) -1 else x/m + (m-1):0)
4 3 2 1
```
[Answer]
## PHP (187)
It's my first attempt at golfing, and I know it could be better, but still :)
**Golfed:**
```
<?php
$b=fgets(STDIN);list($c,$d)=explode(' ',$b);if((($d&1)AND($c%$d==0))OR($c%$d==$d/2)){for($e=floor($c/$d)+floor($d/2);$e>floor($c/$d)-round($d/2);$e--){echo"$e ";}}else{die('-1');}?>
```
**Ungolfed:**
```
<?php
$a = fgets(STDIN);
list($coins, $dwarves) = explode(' ', $a);
if ((($dwarves & 1) AND ($coins % $dwarves == 0)) OR ($coins % $dwarves == $dwarves / 2)) {
for (
$i = floor($coins / $dwarves) + floor($dwarves / 2);
$i > floor($coins / $dwarves) - round($dwarves / 2);
$i--
) {
echo "$i ";
}
}
else {
die('-1');
}
?>
```
Execute in a shell
**Basic idea:**
Coins can be separated by these rules, if one of these is true:
1. The dwarves are odd number, and the coins are divisible by the dwarves with no remains
2. The dwarves are even number, and the coins remaining after dividing coins / dwarves is equal to half of the dwarves number
If so, we take for base the average coins per dwarf (ACPD). But we have to start from the highest and output until we reach the lowest. So we make a loop with counter starting from ACPD + the count of the rest of the dwarves towards the higher end, and go on until we reach the ACPD - the count of the rest of the dwarves towards the lower end.
It's basically the same if the dwarves are odd (i.e. 5 dwarves - the middle one is 3, and in both ends there remain 2), but not if they are even - which is why we rely on floor AND round.
**Problems so far:**
Works with too low coins number, which means some dwarves will be smacked down and robbed of their precious earnings. And this is sad. Or at least if you like dwarves.
**Solution**:
1. Think of a way to calculate the lowest amount of coins so the calculation doesn't end up with dwarves in the dust.
2. Design not-so-greedy dwarves.
**Smarter solution**:
Coins are metal. Make the dwarves melt them all, and then cast them in smaller/larger amount of coins, so they are divisible in any case.
**Smartest solution**:
Steal their mountain, rename yourself to Smaug and keep it all for yourself. After all, why do you have to bother with grumpy dwarves?
[Answer]
## Python 3 (100)
Using the same idea as [@Geobits](https://codegolf.stackexchange.com/a/25291/7258) but conforming to the input and output requirements.
```
n,m=map(int,input().split())
κ,ρ=divmod(n-m*(m-1)//2,m)
x=[-1]if ρ else range(κ,κ+m)[::-1]
print(*x)
```
[Answer]
# Python 3 - 109 107 103 102 90 93
Using the same idea as Evpok, but with a number of improvements.
```
n,m=map(int,input().split())
k=n/m+m/2
a=int(k)
print(*(range(a,a-m,-1),[-1])[k-a-.5or~a>-m])
```
The improvements are:
1. Eliminating the space after else and before ' '. 1 character
2. Eliminating the ' ' inside split(), because splitting on spaces is a default. 3 characters
3. Lowering x by 1 changing the -1 to +1 inside divmod, and then changing the range function to use the range's reversed order option. 3 characters.
4. EDIT: ... if ... else ... changed to ... and ... or ... 2 characters.
5. EDIT: Divmod made explicit, r removed. 4 characters.
6. EDIT: x removed, m//n used explicitly. 1 character
7. EDIT: used starred expressions instead of ' '.join(map(str,...)), added x to avoid repeating print(). 12 characters.
8. EDIT: I realized that I was allowing negative numbers of coins to be given to the Dwarves. I changed the code to avoid this.
[Answer]
## Python 3 - 114
```
n,m=map(int,input().split(' '))
r=range(m);n-=sum(r)
if n%m<1:
for x in r:print(m-x+n//m-1,end=' ')
else:print -1
```
Works by checking if `N-(M*(M-1)/2)` is evenly divisible by `M`. New to python, so any tips appreciated.
[Ideone.com example](http://ideone.com/hCAywr)
```
Input:
735 30
Output:
39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10
```
[Answer]
## C# - 322
```
using System;using System.Linq;namespace D{class P{static void Main(string[]args){int n=Convert.ToInt16(args[0]);int m=Convert.ToInt16(args[1]);bool b=false;int q=n/2+1;g:b=!b;int[]z=new int[m];for(int i=0;i<m;i++){z[i]=q-i;}if(z.Sum()==n)foreach(int p in z)Console.Write(p+" ");else{q--;if(b)goto g;Console.Write(-1);}}}}
```
Horrible score but I took a different approach and got to use `goto` :)
I will shorten it later.
[Answer]
# Java 210
```
class A { public static void main(String[] a){int d=Integer.parseInt(a[0]),c=Integer.parseInt(a[1]);if (2*c%d==0) for (int i=0;i<d;i++) System.out.print((((1+(2*c/d)-d)/2)+i)+" "); else System.out.print(-1);}}
```
[Answer]
### R: ~~77~~ ~~73~~ 70 chars
```
a=scan();r=a[2]:1-1;while((n=sum(r))<a[1])r=r+1;cat(`if`(n>a[1],-1,r))
```
Create a vector going from (M-1) to 0 and adds 1 to each number until the sum is no longer inferior to N. If it is superior, output -1 else output the vector.
Indented and slightly ungolfed:
```
a=scan() #Reads in stdin (by default numeric, space-separated)
r=a[2]:1-1 #Creates vector (M-1) to 0
while(sum(r)<a[1])r=r+1 #Increments all member of vector by 1 until sum is not inferior to N
cat( #Outputs to stdout
`if`(sum(r)>a[1], -1, r) #If superior to N: impossible, returns -1
)
```
Example usage:
```
> a=scan();r=a[2]:1-1;while((n=sum(r))<a[1])r=r+1;cat(`if`(n>a[1],-1,r))
1: 9 3
3:
Read 2 items
4 3 2
> a=scan();r=a[2]:1-1;while((n=sum(r))<a[1])r=r+1;cat(`if`(n>a[1],-1,r))
1: 7 3
3:
Read 2 items
-1
> a=scan();r=a[2]:1-1;while((n=sum(r))<a[1])r=r+1;cat(`if`(n>a[1],-1,r))
1: 204 17
3:
Read 2 items
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4
```
[Answer]
# Julia, 45
```
f(n,m)=(x=n/m-m/2+1/2;x%1==0?[x+m-1:-1:x]:-1)
julia> f(6,4)'
1x4 Array{Float64,2}:
3.0 2.0 1.0 0.0
```
Just a bit of algebra, took me way longer than it should have.
[Answer]
# JavaScript - 76
>
> Observe that k + (k - 1) + ... + (k - (M - 1)) = M(k - (M - 1)/2)
> Setting this equal to N gives k = N/M + (M-1)/2 for the highest amount.
> If this is integer, then k % 1 == 0 and the amounts we are looking for are k, k - 1, ..., k - (M - 1).
>
>
>
I could probably have written this shorter in another language, but there was no JS solution yet so here it is:
```
N=3;M=3;if((r=N/M+(M-1)/2)%1)console.log(-1);else while(M--)console.log(r--)
```
Run in the console.
Example input:
```
N=3;M=3;if((r=N/M+(M-1)/2)%1)console.log(-1);else while(M--)console.log(r--)
```
Output:
```
3
2
1
```
Input:
```
N=6;M=4;if((r=N/M+(M-1)/2)%1)console.log(-1);else while(M--)console.log(r--)
```
Output:
```
3
2
1
0
```
Input:
```
N=7;M=3;if((r=N/M+(M-1)/2)%1)console.log(-1);else while(M--)console.log(r--)
```
Output:
-1
Too bad console.log is so long to spell :)
Unfortunately declaring `l=console.log.bind(console)` does not make it any shorter, and just `l=console.log` does not work.
Input:
```
"N=3;M=3;if((r=N/M+(M-1)/2)%1)console.log(-1);else while(M--)console.log(r--)".length
```
Output:
```
76
```
[Answer]
# Golfscript, 35
```
~:M.(*2/-.M%{;-1}{M/M+,-1%M<' '*}if
```
### How it works
In the following example, the input is `9 3`.
```
# STACK: "9 3"
~ # Interpret the input string.
# STACK: 9 3
:M # Store the top of the stack (number of dwarves) in variable `M'.
. # Duplicate the top of the stack.
# STACK: 9 3 3
( # Decrement the top of the stack.
# STACK: 9 3 2
* # Multiply the topmost elements of the stack.
# STACK: 9 6
2/ # Divide the top of the stack by `2'.
# STACK: 9 3
# So far, we've transformed `M' into `M*(M-1)/2', which is the minimum amount of
# coins all dwarves together will get. This number comes from the fact that the
# youngest dwarf will get at least 0 coins, the next at least 1 coin, etc., and
# 0 + 1 + ... + (M - 1) = M*(M-1)/2.
- # Subtract the topmost elements of the stack.
# STACK: 6
# The remaining coins have to get reparted evenly to all dwarves.
. # Duplicate the top of the stack.
# STACK: 6 6
M% # Calculate the top of the stack modulus `M'.
# STACK: 6 0
{ # If the modulus is positive, the remaining coins cannot get reparted evenly.
;-1 # Replace the top of the stack by `-1'.
}
{ # If the modulus is zero, the remaining coins can get reparted evenly.
M/ # Divide the top of the stack by `M'.
# STACK: 2
# This is the number of coins all dwarves will get after giving 1 to the second
# youngest, etc.
M+ # Add `M' to the top of the stack.
# STACK: 5
, # Replace the top of the stack by an array of that many elements.
# STACK: [ 0 1 2 3 4 ]
# The rightmost element is the number of coins the oldest dwarf will get.
-1% # Reverse the array.
# STACK: [ 4 3 2 1 0 ]
M< # Keep the leftmost `M' elements.
# STACK: [ 4 3 2 ]
# There are only `M' dwarves.
' '* # Join the array, separating by spaces.
# STACK: "4 3 2"
}if
```
[Answer]
# Delphi XE3 (176)
```
uses SysUtils;var d,c,i:integer;begin read(c,d);for I:=1to d-1do c:=c-i;if c mod d>0then writeln(-1)else begin c:=c div d;for I:=d-1downto 0do write(IntToStr(i+c)+' ');end;end.
```
### How it works.
Reads 2 integers, coins and dwarves.
Substracts the difference per dwarf.
If the remainder mod dwarves>0 its impossible.
Else get equal share per dwarf in a loop of dwarves-1 to 0 and prints dwarfIndex+equal share
### Ungolfed
```
uses SysUtils;
var
d,c,i:integer;
begin
read(c,d);
for I:=1to d-1do
c:=c-i;
if c mod d>0then
writeln(-1)
else
begin
c:=c div d;
for I:=d-1downto 0do
write(IntToStr(i+c)+' ');
end;
end.
```
[Answer]
# Mathematica 65
The function, `g`, generates all the increasing-by-one sequences, of length m, from 0 to n and checks whether any of them sum to m. If successful, the sequence is returned; otherwise, -1 is returned.
The sequences are made by `Partition`ing the list {0,1,2,3… m} into all possible sublists of n contiguous integers.
There are, of course, more efficient ways to achieve the same effect, but those that I have found require more code.
```
n_~g~m_:=If[(s=Select[Partition[0~Range~n,m,1],Tr@#==n&])=={},-1,s]
```
Examples
```
g[9, 3]
```
>
> {{2, 3, 4}}
>
>
>
---
```
g[3, 3]
```
>
> {{0, 1, 2}}
>
>
>
---
```
g[7, 3]
```
>
> -1
>
>
>
---
```
g[705, 3]
```
>
> {{234, 235, 236}}
>
>
>
---
```
g[840, 16]
```
>
> {{45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60}}
>
>
>
---
```
g[839, 16]
```
>
> -1
>
>
>
[Answer]
**C 131**
```
#include <edk.h>
main(int a,char **v){int j=atoi(*++v),k=atoi(*++v)-j*(j-1)/2;k<0||k%j?j=1,k=-1:k/=j;while(j--)printf("%d ",k+j);}
```
Ungolfed
```
#include <edk.h> //Shortest standard header including stdio.h and stdlib.h
main(int a,char **v)
{
int j=atoi(*++v),k=atoi(*++v)-j*(j-1)/2;
k<0||k%j?j=1,k=-1:k/=j; // If youngest dwarf gets < 0 or amount not equally divisible then set values such that ...
while(j--)printf("%d ",k+j); // ... loop prints out correct values
}
```
This compiles with a warning because main has no type. If this is not valid in the rules of golf, I would have to add five characters.
[Answer]
# Cobra - 198
[Cobra Website](http://cobra-language.com/)
```
class P
def main
x,y=Console.readLine.split
a,b=x to int,y to int
l=[]
t=n=0
for i in b,t+=i
while (t+=b)<=a,n+=1
for i in b,l.insert(0,i+n)
print if(t-b<>a,-1,l.join(" "))
```
**Explained:**
```
class P
def main
```
Required for the code to run
```
x,y=Console.readLine.split
a,b=x to int,y to int
```
Takes input and stores it as `a` and `b`
```
l=[]
t=n=0
```
Initializes the output list `l`, and initializes the total required money `t` and number of coins to add to each dwarves pile `n`
```
for i in b,t+=i
```
Finds the lowest possible money value that will result in all dwarves having an allowable number of coins in their pile
```
while (t+=b)<=a,n+=1
```
Determines how many coins to add to each pile so that the total required money is >= to the total available money
```
for i in b,l.insert(0,i+n)
```
Fills the list with the different sized piles of money
```
print if(t-b<>a,-1,l.join(" "))
```
Outputs either `-1` or `l` depending whether the total required money is equal to the total available money
[Answer]
# [Perl 5](https://www.perl.org/), 78 + 1 (-n) = 79 bytes
```
($d)=/ (.*)/;$,=$";say(($b=$_-($d**2-$d)/2)%$d?-1:map$_+$b/$d,reverse 0..$d-1)
```
[Try it online!](https://tio.run/##DcpLCoMwFAXQrYRyhST15aM4qYSuoGsQJRkU/ISkFLr5Ph2fk1NZB2aJqIIV0mhlR7QBt7HOPymxBEx0qdYdXcd2qkF8kn9sc8Z0x2IR25K@qdQknDGI5BVzL/r/kT/vY69Mr8E475j2Ew "Perl 5 – Try It Online")
[Answer]
# Python (~~100~~ ~~96~~ 94):
~~A nice, round-scoring answer.~~ Not any more, but it IS shorter now.
```
def f(n,m):a=range(m)[::-1];b=n-sum(a);c=b/m;d=[i+c for i in a];return(d,-1)[-1in d or c*m!=b]
```
Ungolfed:
```
def f(n,m):
a = range(m)[::-1]
b = sum(a)
c = (n-b)/m
if c * m != n-b: return -1
d = [i+c for i in a]
return (d,-1)[-1 in d or c!=n-b]
if -d in d or c*m!=n-b:
return -1
return d
```
Output:
```
def f(n,m):a=range(m)[::-1];b=sum(a);c=(n-b)/m;d=[i+c for i in a];return (d,-1)[-1 in d or c*m!=n-b]
f(3,3)
Out[2]: [2, 1, 0]
f(9,3)
Out[3]: [4, 3, 2]
f(7,3)
Out[4]: -1
f(6,4)
Out[5]: [3, 2, 1, 0]
```
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/18348/82007)
There are special sets *S* of primes such that \$\sum\limits\_{p\in S}\frac1{p-1}=1\$. In this challenge, your goal is to find the largest possible set of primes that satisfies this condition.
**Input**: None
**Output**: A set of primes which satisfies the conditions above.
This challenge is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), where your score is the size of the set you output.
# Examples of Valid Outputs and their scores
```
{2} - 1
{3,5,7,13} - 4
{3,5,7,19,37} - 5
{3,5,7,29,31,71} - 6
```
**Important**: This challenge doesn't require any code, simply the set. However, it would be helpful to see how you generated your set, which probably involves some coding.
**Edit**: Found the [math.stackexchange post](https://math.stackexchange.com/questions/3470540/are-there-infinitely-many-finite-sets-s-of-primes-where-sum-p-in-s-1-p-i) that inspired this thanks to @Arnauld
[Answer]
# Score ~~100~~ 8605
I used an algorithm that starts with one solution and repeatedly tries to split a prime \$p\$ in the solution into two other primes \$q\_ 1\$ and \$q\_ 2\$ that satisfy \$\frac1{p-1} = \frac1{q\_1-1}+\frac1{q\_2-1}\$.
It is known (and can be quickly checked) that the positive integer solutions to \$\frac1n = \frac1x + \frac1y\$ are in one-to-one correspondence with factorizations \$n^2 = f\_ 1 f\_ 2\$, the correspondence being given by \$x = n + f\_ 1\$, \$y = n + f\_ 2\$. We can search through the factorizations of \$(p-1)^2\$ to see if any of them yielded a solution where both new denominators \$x,y\$ were one less then primes; if so, then \$p\$ can be replaced by \$q\_1=x+1\$, \$q\_2=y+1\$. (If there were multiple such factorizations, I used the one where the minimum of \$q\_1\$ and \$q\_2\$ was smallest.)
I started with this seed solution of length 44:
```
seed = {3, 7, 11, 23, 31, 43, 47, 67, 71, 79, 103, 131, 139, 191, 211, 239, 331, 419, 443, 463, 547, 571, 599, 647, 691, 859, 911, 967, 1103, 1327, 1483, 1871, 2003, 2311, 2347, 2731, 3191, 3307, 3911, 4003, 4931, 6007, 6091, 8779}
```
This seed was found using an Egyptian fraction solver that a former research student of mine, Yue Shi, coded in ChezScheme. (The primes \$p\$ involved all have the property that \$p-1\$ is the product of distinct primes less than 30, which increased the likelihood of Shi's program finding a solution.)
The following Mathematica code continually updates a current solution by looking at its primes one by one, trying to split them in the manner described above. (The number 1000 in the third line is an arbitrary stopping point; in principle one could let the algorithm run forever.)
```
solution = seed;
j = 1; (* j is the index of the element of the solution that we'll try to split *)
While[j <= 1000 && j <= Length[solution],
currentP = solution[[j]];
allDivisors = Divisors[(currentP - 1)^2];
allFactorizations = {#, (currentP - 1)^2/#} & /@
Take[allDivisors, Floor[Length[allDivisors]/2]];
allSplits = currentP + allFactorizations;
goodFactorizations = Select[allSplits,
And @@ PrimeQ[#] && Intersection[#, solution] == {} &];
If[goodFactorizations == {},
j++,
solution = Union[Complement[solution, {currentP}], First@goodFactorizations]
]
]
```
The code above yields a solution of length 4126, whose largest element is about \$8.7\times10^{20}\$; by the end, it was factoring integers \$(p-1)^2\$ of size about \$8.8\times10^{21}\$.
In practice, I ran the code several times, using the previous output as the next seed in each case and increasing the cutoff for j each time; this allowed for the recovery of some small prime splits that had become non-redundant thanks to previous splitting, which somewhat mitigated the size of the integers the algorithm factored.
The final solution, which took about an hour to obtain, is too long to fit in this answer but has been [posted online](https://pastebin.com/fxN5QuNM). It has length 8605 and largest element about \$4.62\times10^{19}\$.
Various runs of this code consistently found that the length of the solution was about 3–4 times as long as the set of primes that had been examined for splitting. In other words, the solution was growing much faster than the code scanned through the initial elements. It seems likely that this behavior would continue for a long time, yielding some gargantuan solutions.
[Answer]
# Score ~~263~~ ~~385~~ ~~425~~ 426 with only primes < 1.000.000 (*was*: non-competitive, now it is; score can be increased by running the program longer)
I followed the same path as [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard): iteratively search for primes in the solution that can be replaced with a longer list of primes with the same result. I wrote that Python program that does exactly this. It starts with solution `S = {2}` and than iterates of all elements of that solution and tries to find a decomposition of that prime for which 1/(p-1) = sum(1/(q-1) for all q in the decomposition.
After I realized that S should be a set (and not a list), I altered the program to take this into account. I also added a ton of performance optimizations. The solution of 263 came up within 200 seconds or so (running under pypy3), but if you let it running, it steadily keeps coming with additional (longer) solutions.
Current best solution (425 elements, with all primes < 1M, calculated in ~ 15 min.):
```
S = [3, 5, 13, 19, 29, 37, 103, 151, 241, 281, 409, 541, 577, 593, 661, 701, 751, 1297, 1327, 2017, 2161, 2251, 2293, 2341, 2393, 2521, 2593, 2689, 2731, 3061, 3079, 3329, 3361, 3457, 6301, 6553, 7057, 7177, 7481, 7561, 8737, 9001, 9241, 9341, 10501, 11617, 12097, 12547, 14281, 14449, 14561, 15121, 17761, 17851, 18217, 18481, 20593, 21313, 22441, 23189, 23761, 24571, 26041, 26881, 28351, 28513, 29641, 30241, 36529, 37441, 46993, 49921, 51169, 57331, 58109, 58313, 58369, 58831, 59659, 60737, 60757, 61001, 61381, 61441, 61561, 61609, 63067, 63601, 64513, 64901, 65053, 65089, 65701, 65881, 66301, 66931, 67049, 69389, 69941, 70181, 72161, 72481, 72577, 72661, 73061, 73699, 74521, 77521, 78241, 79693, 81181, 86951, 88741, 90631, 98011, 100297, 102181, 107641, 108991, 109201, 109537, 114913, 117841, 118429, 121993, 122761, 123001, 124561, 127601, 128629, 130073, 130969, 131561, 133387, 133813, 138181, 138403, 139501, 146077, 149521, 159457, 160081, 162289, 163543, 166601, 174241, 175891, 176401, 177913, 180181, 182711, 189421, 199921, 201781, 206641, 218527, 223441, 227089, 229739, 234961, 238081, 238141, 238897, 239851, 246241, 250057, 261577, 266401, 267961, 280321, 280837, 280897, 281233, 283501, 283861, 284161, 287233, 288049, 291721, 297601, 299053, 302221, 306853, 309629, 313153, 316681, 322057, 325921, 332489, 342211, 342241, 349981, 352273, 354961, 355321, 360977, 365473, 379177, 390097, 390961, 394717, 395627, 401057, 404251, 404489, 412127, 412651, 416881, 417649, 418027, 424117, 427681, 428221, 428401, 429409, 430921, 434521, 435481, 441937, 443873, 444641, 451441, 453601, 454609, 455149, 459649, 466201, 468001, 473617, 474241, 480737, 481693, 483883, 496471, 498301, 498961, 499141, 499591, 499969, 501601, 501841, 502633, 513067, 514513, 517609, 523261, 524521, 525313, 529381, 538721, 540541, 545161, 550117, 552553, 560561, 562633, 563501, 563851, 568177, 570781, 575723, 587497, 590669, 591193, 599281, 601801, 601903, 604001, 605551, 607993, 609589, 611389, 617401, 621007, 627301, 628561, 628993, 629281, 635449, 637201, 639211, 642529, 645751, 651361, 651857, 653761, 654853, 655453, 657091, 662941, 664633, 667801, 669121, 669901, 670177, 673201, 673921, 675109, 688561, 689921, 691363, 692641, 694033, 695641, 697681, 698293, 700591, 703081, 703561, 705169, 705181, 707071, 709921, 713627, 732829, 735373, 737413, 739861, 742369, 745543, 750121, 750721, 754771, 756961, 757063, 758753, 759001, 760321, 761671, 762721, 766361, 773501, 774181, 776557, 779101, 782461, 784081, 784981, 786241, 788317, 794641, 795601, 797273, 800089, 801469, 808081, 808177, 810151, 813121, 815671, 819017, 823481, 823621, 825553, 831811, 833281, 833449, 836161, 839161, 840911, 846217, 859657, 859861, 860609, 863017, 865801, 869251, 870241, 875521, 876929, 878011, 880993, 884269, 891893, 895681, 898921, 899263, 902401, 904861, 905761, 907369, 908129, 914861, 917281, 917317, 921601, 922321, 923833, 926377, 939061, 941641, 942401, 943009, 943273, 944161, 944821, 944833, 949621, 949961, 950041, 950401, 953437, 953443, 954001, 957349, 957529, 960121, 960961, 963901, 964783, 967261, 967627, 967751, 968137, 971281, 973561, 973591, 984127, 984341, 984913, 986437, 991381, 992941, 994561, 995347, 996001]
```
[Proof that is satisfies the challenge](https://tio.run/##PVfLbl03DNznK87SF3ALieJz4W1/IMuii6JoUAONbTjuol/vDocXRZAzVxIl8TmU3/79@Ov15Xx@Pn9/e33/uL69//7Hx/Pry48vX6@n69fzeNnjtQG7Hi/B/xP4vXrCNma0P4mPLixaDy0gYgURdwxj9aeFt1RvPoKvrN3f3RIiPEp6ixyeePjbpH/zKPFsBeJg5iznN1qdQ6UOZ9Rwpp@@0M1O390zsVuj0KQiLZnRZtRqyaINxXv3sp7aUKs1lUWFxbRBaedW1WrgQXBC64gLOIqknSncnrxR1hiwT7tRRMfATXsO9wkUb/DFNU/uy0O34MjeV640mtoet4kFD1OvvkGrWheD9h2KOO0ry83AJG8HcC2Ta@WGkS96A0D3bXrF90kCb/BNa317HwYPOx3tlFQq6Frj99WOB7R9bjGTtMjvofHq2z1WOxIDSlbpJAujNIkRMjETplTI5NOEP2BJdVSZJBEDSfdEeTskNw9Lr3ZkZjDQy/v2yrUZ8DVJuYSye4VPImQVsWQNGjN/a7EaEGrKIcgdCWQBY7BFJhPk0I1b7nmC6RmnUx7LcYjlHI@H9zknWSRwP9dz9DqpLLpTk6GKcDEpi4ZvKyY/ArQo7yLt1u3HtPe5z/2h9NAOS9oHc2c@xq6cACCFg/7JUp5fk1xdtpPUTj/Ba8ZyRt1yLMHAo5jjMMG1mOEnqRdwT/5ntt9R6Dk84kMltliygowL4ugnHnNOriOD2fFo5DkJj58pmjXFkyOvQzEZ9/Vk1knt4Dk1cZEq5i3qS2QoJmdcjNfpAPUYjmw7jgj1PGAnyh@kassptu9BFiqKkvIGz/R@G38c0BP3oaDaThS0ch1h4BjcVIMjXxqbY/P2N5zC@3UpyRPI@xWJyPUtzvk9ZKIdaK7n4jq028SgPeA22g2kv5HUJHSFAzh/ps4UBlBed7X/VZGuzT2qzAdwwVCSDTmoKSlDDQvEGj3cWVfqyTqB8aRcveen5pASLmMpK@KZ5DjXpkqtJJcA6R@4mXkFtBpkXSEZqAeQ9WpLvPMAlEUOg1ZkL4N/yJNypM8zGXtNbIgTzantNpjLeV3T67Cd8rig9Tds6DwxX6xnRGvu88lLIPPd4HW2yVisJwP3Cgk6tNg@UWCtT@3d9hvKjxS6ukKJ1XyAjjF0vcyMGOQhGGOk1b2HXlH4lBMwXnM3snHGOcwOtuA@ud@DOJOdTzBOfop57Ui3rgeQPls6koytF5jsHjYdDemc0wfgoTONoMj9Qp5HWdMv7pH3nsBGCpw2gkbQ/vE4c38c5qHjVragvOudw0vYfrzPK2EeOtKX56NeZjx57pV8ZgRopthvDnkJaPNYMXbPxpnHP@LcE7im6wdqZfshDgzu89CKN7HIO0hjdlq0J/JvIPrcbysGNWKeI8xfhH855TL4cLF5nCAryRNwqlMet8/Y6feIyavA9dQ34PHWDzyy7g2RcijrHKzB4dvol0DL19RvwF/cV0G@QnWSzxEkdeLweH87Pnhd8B2IZkX7Em0siMUHXqIBUB7u4DrKo@3Drdn5lCDOHGS@4X3CespTg2AhyqE/8Lx@swzSz@mLdZv9tOh5PDXW9HzyYsY8mOBV1nMGFlo@pv@jHTDvE22c9hU6Xo/LmC8JfuE@hL/jUziOj8alvB9dIwaD8S74pc8HG8062kwO0s84zOfRKYxroRF2nvbp7c8C4XMfiJuvFb3fByJuO4GMS@n0NWDKHXkOCHLGxbzCa4FvSuCcY0f59AV2XpYNfxSei@1/IOu7fPIVOOeAACgH@m0eLg@Z@WA9AMkHBa/x/Nhjd0xdNRafXcr@BOSDG8h3B6I5etW8O@Fu8gRehbO/FeY6Hjj7ty9v788vHw8//vn@8P8fLD//cv/1sB8f3n7at9v17fX9erueX66vt@vp6dq3@76//3x5@Hq7fX7@Bw):
Some of the decompositions used:
```
1/( 2-1) = sum(1/(p-1)) for p in: {(5, 7, 13, 3)}
1/( 3-1) = sum(1/(p-1)) for p in: {(7, 13, 5)}
1/( 5-1) = sum(1/(p-1)) for p in: {(13, 7)}
1/( 7-1) = sum(1/(p-1)) for p in: {(13, 19, 37)}
1/( 13-1) = sum(1/(p-1)) for p in: {(19, 37)}
1/( 19-1) = sum(1/(p-1)) for p in: {(29, 71, 181)}
1/( 29-1) = sum(1/(p-1)) for p in: {(37, 127)}
1/( 37-1) = sum(1/(p-1)) for p in: {(43, 281, 2521)}
1/( 43-1) = sum(1/(p-1)) for p in: {(53, 223, 13469)}
...
1/(8779-1) = sum(1/(p-1)) for p in: {(8969, 739861, 941641)}
1/(8807-1) = sum(1/(p-1)) for p in: {(9001, 773501, 865801)}
1/(8821-1) = sum(1/(p-1)) for p in: {(8941, 657091)}
1/(8941-1) = sum(1/(p-1)) for p in: {(9041, 808177)}
1/(8969-1) = sum(1/(p-1)) for p in: {(9463, 227089, 705169)}
1/(9001-1) = sum(1/(p-1)) for p in: {(9109, 759001)}
1/(9041-1) = sum(1/(p-1)) for p in: {(9241, 417649)}
1/(9109-1) = sum(1/(p-1)) for p in: {(10891, 55661)}
1/(9181-1) = sum(1/(p-1)) for p in: {(9343, 529381)}
1/(9241-1) = sum(1/(p-1)) for p in: {(9341, 863017)}
1/(9341-1) = sum(1/(p-1)) for p in: {(15121, 25219, 784561)}
1/(9343-1) = sum(1/(p-1)) for p in: {(9689, 261577)}
1/(9463-1) = sum(1/(p-1)) for p in: {(10957, 69389)}
1/(9689-1) = sum(1/(p-1)) for p in: {(12457, 43597)}
1/(10333-1) = sum(1/(p-1)) for p in: {(10501, 645751)}
...
1/(131561-1) = sum(1/(p-1)) for p in: {(237361, 295153)}
1/(166601-1) = sum(1/(p-1)) for p in: {(243433, 527851)}
1/(266401-1) = sum(1/(p-1)) for p in: {(386401, 857809)}
1/(355321-1) = sum(1/(p-1)) for p in: {(639577, 799471)}
```
Python3 code:
```
import itertools
import sympy
import cProfile
import functools
import bisect
import operator
def sundaram3(max_n):
# Returns a list of all primes under max_n
numbers = list(range(3, max_n + 1, 2))
half = (max_n) // 2
initial = 4
for step in range(3, max_n + 1, 2):
for i in range(initial, half, step):
numbers[i - 1] = 0
initial += 2 * (step + 1)
if initial > half:
return [2] + list([_f for _f in numbers if _f])
# Precalculate all primes up to a million to speed things up
PRIMES_TO_1M = list(sundaram3(1000000))
def nextprime(number):
# partly precalculated fast version for calculating the
# first (e.g. smallest) prime that is largest than numer
global PRIMES_TO_1M
if number <= PRIMES_TO_1M[-2]:
return PRIMES_TO_1M[bisect.bisect(PRIMES_TO_1M, number)]
return sympy.nextprime(number)
def isprime(number):
# partly precalculated fast version to determine of number is prime
global PRIMES_TO_1M
if number < 1000000:
return number in PRIMES_TO_1M
return sympy.isprime(number)
def upper_limit(prime, length=2):
# Returns the largest prime q in the decomposition of prime with the given
# length such that 1 / (prime - 1) = sum( 1 / (q - 1)) for q in
# set V, with V has the given length.
# ASSUMPTION: all q are unique; this assumption is not validated,
# but for this codegolf, the solution must be a set, so this is safe.
if length == 1:
return prime
nextp = nextprime(prime)
largestprime = (prime * nextp - 2 * prime + 1 ) // (nextp - prime)
if not isprime(largestprime):
largestprime = nextprime(largestprime)
return upper_limit(largestprime, length - 1)
def find_decomposition(prime, length=2):
# Returns a list of primes V = {q1, q2, q3, ...} for which holds that:
# 1 / (prime - 1) = sum(1 / (q - 1)) for q in V.
# Returns None if this decomposition is not found.
# Note that there may be more than one V of a given prime, but this
# function returns the first found V (implementation note: the sortest one)
print(f"Searching decomposition for prime {prime} with length {length} in range ({prime}, {upper_limit(prime, length)}]")
prime_range = PRIMES_TO_1M[bisect.bisect(PRIMES_TO_1M, prime) + 1:
bisect.bisect(PRIMES_TO_1M, upper_limit(prime, length) + 1)]
# we only search for combinations of length -1; the last factor is calculated
for combi in itertools.combinations(prime_range, length - 1):
# we find the common factor of prime and all primes in combi
# and use that to calculate the remaining prime. This is faster
# than trying all prime combinations.
factoritems = [-prime + 1] + [c - 1 for c in combi]
factor = -functools.reduce(operator.mul, factoritems)
remainder = - factor / sum(factor // p for p in factoritems) + 1
if remainder == int(remainder) and isprime(remainder) and remainder not in combi:
combi = combi + (int(remainder),)
print(f"Found decomposition: {combi}")
return combi
return None
def find_solutions():
# Finds incrementally long solutions for the set of primes S, for which:
# sum(1/(p-1)) == 1 for p in S.
# We do this by incrementally searching for primes in S that can be
# replaced by longer subsets that have the same value of sum(1/p-1).
# These replacements are stored in a dictionary "decompositions".
# Starting with the base solution S = [2] and all decompositions,
# you can construct S.
decompositions = {} # prime: ([decomposition], max tried length)
S = [2]
old_solution_len = 0
# Keep looping until there are no decompositions that make S longer
while len(S) > old_solution_len:
# Loop over all primes in S to search for decompositions
for p in sorted(set(S)):
# If prime p is not in the decompositions dict, add it
if p not in decompositions:
decompositions[p] = (find_decomposition(p, 2), 2)
# If prime p is in the decompositions dict, but without solution,
# try to find a solution 1 number longer than the previous try
elif not decompositions[p][0]:
length = decompositions[p][1] + 1
decompositions[p] = (find_decomposition(p, length), length)
# If prime p is in decompositions and it has a combi
# and the combi is not already in S, replace p with the combi
elif all(p not in S for p in decompositions[p][0]):
old_solution_len = len(S)
print(f"Removing occurence of {p} with {decompositions[p][0]}")
S.remove(p)
S.extend(decompositions[p][0])
S = sorted(S)
break # break out of the for loop
print(f"Found S with length {len(S)}: S = {S}")
print(f"Decompositions: ")
for prime in sorted(decompositions.keys()):
print(f" 1/({prime:3}-1) = sum(1/(p-1)) for p in: \u007b{decompositions[prime][0]}\u007d")
def main():
cProfile.run("find_solutions()")
if __name__ == "__main__":
main()
```
[Answer]
# Score ~~32~~ ~~34~~ 36
```
{5, 7, 11, 13, 17, 23, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 101, 113, 131, 137, 151, 211, 229, 241, 281, 313, 379, 401, 433, 457, 491, 521, 571, 601, 25117, 293362609}
```
This is an improvement of Arnauld's answer. I just noticed that
\$
\dfrac{1}{19-1}=\dfrac{1}{73-1}+\dfrac{1}{61-1}+\dfrac{1}{41-1}
\$
But 41 and 61 were already used in Arnauld's answer so I had to then figure out that
\$
\dfrac{1}{61-1} = \dfrac{1}{151-1} + \dfrac{1}{101-1}
\$
and
\$
\dfrac{1}{41-1} = \dfrac{1}{281-1}+\dfrac{1}{211-1}+\dfrac{1}{151-1}+\dfrac{1}{101-1}
\$
But now I am using 151 and 101 twice. So I spent some time and discovered that
\$
\dfrac{1}{151-1} = \dfrac{1}{401-1} + \dfrac{1}{241-1}
\$
and
\$
\dfrac{1}{101-1} = \dfrac{1}{601-1} + \dfrac{1}{571-1} + \dfrac{1}{457-1} + \dfrac{1}{229-1}
\$
So now I can just replace the `19` with `71, 151, 101, 151, 211, 229, 241, 281, 401, 457, 471, 601` and the sequence will maintain it's properties.
I also discovered that I can replace `19` with the sequence `71, 151, 101, 151, 211, 241, 241, 281, 401, 433, 541, 601`, but that has `241` twice.
After that improvement I also noticed that 79 could be replaced with `521, 313, 131`, to increase the size by 2 more.
And 73 can be replaced with `113, 379, 433` for another 2.
[Answer]
# Score 22
Just to get the ball rolling.
```
{5,7,11,13,17,19,23,31,37,41,43,47,53,59,61,67,71,79,137,491,25117,293362609}
```
[Compute the fraction](https://tio.run/##dY3BDoIwEETvfsXeLDoiS4GmIZjgzW8wHkhpjAbaRsXfxxIvXrxsJpn3Zu/du3uaxy28ds73dp5bauhcQoEZLMExaOQSkiEVCkYhUSiUEqVGxagUFEPpCMdaM/KSo5RrKau8yvQlHbsgjrfryb2SetVbFx@06cP2k7FCBJBJqDlQoA0JQztil2A59cpN4z92S8vQ/sfIFsN49/SDTQd/FYu9pXWE1l88qef5Aw "JavaScript (Node.js) – Try It Online")
I suspect that the sequence can be made arbitrary large, but my code is currently too messy and inefficient for anything significantly better than that.
[Answer]
This non-answer expands on the modifications to @GregMartin's answer referenced in [this comment](https://codegolf.stackexchange.com/questions/196941/longest-prime-sums#comment468860_196966) there.
The `allDivisors` to `goodFactorizations` block can be sped up noticeably by not asking `Divisors` to factor the square of a number (and also a few other changes). The @GregMartin's original code:
```
divMethod[p_] := Module[{},
allDivisors = Divisors[(p - 1)^2];
allFactorizations = {#, (p - 1)^2/#} & /@
Take[allDivisors, Floor[Length[allDivisors]/2]];
allSplits = p + allFactorizations;
goodFactorizations = Select[allSplits,
And @@ PrimeQ[#] &]
]
```
The intersection check at the end is removed, since it is common to both the above and my proposed replacement:
```
g[p_] := Module[
{pm1s, factorization, divisors},
pm1s = (p - 1)^2;
(* Since the original seed contains only odd
primes, we know one factor of p-1. *)
factorization = FactorInteger[(p - 1)/2];
(* For divisors d1, d2, such that d1 d2 = pm1s,
we require d1+p and d2+p are prime. p>2, so p
is odd and both d1+p and d2+p are odd, so d1
and d2 are necessarily both even. This means
we only consider splitting the powers of 2 so
that at least one falls in each divisor; we
want to know the power of 2 in pm1s, minus 1.
*)
If[factorization[[1, 1]] != 2,
pow2m1 = 1,
pow2m1 = 2 factorization[[1, 2]] + 1
];
divisors = Outer[Times,
2^Range[1, pow2m1],
Sequence @@ (
Select[
#[[1]]^Range[0, 2 #[[2]]],
(# < p - 1 &)] & /@
Rest[factorization])];
(* The Join@@ is a hack to deal with Reap's
denormalized output on no-Sow runs. See
https://mathematica.stackexchange.com/questions/67625/what-is-shorthand-way-of-reap-list-that-may-be-empty-because-of-zero-sow *)
Join @@ Reap[
Map[
(If[#1 < p - 1 && PrimeQ[#2],
(If[PrimeQ[#2],
Sow[{#1, #2}]
] &)[#2, pm1s/#1 + p]
] &)[#, # + p] &,
divisors,
{-1}];
][[2]]
]
```
Note: the replacement makes no attempt to sort the collection of pairs. The following tests do not demonstrate the potential difference in order of results from `divMethod` and `g`.
```
divMethod[3]
g[3]
(* {} *)
(* {} *)
divMethod[29]
g[29]
(* {{31, 421}, {37, 127}} *)
(* {{31, 421}, {37, 127}} *)
p = NextPrime[10^3]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.00041, {{1201, 6301}}} *)
(* {0.000487, {{1201, 6301}}} *)
p = NextPrime[10^6]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.000271, {}} *)
(* {0.0000619, {}} *)
p = NextPrime[10^9]
RepeatedTiming[divMethod[p]]
RepeatedTiming[g[p]]
(* {0.000271, {}} *)
(* {0.000103, {}} *)
```
Let's collect timing data for sets of 1000 consecutive primes starting at powers of 10 and see what trends we see.
```
divTiming = Table[{10^k, RepeatedTiming[
p = NextPrime[10^k];
For[count = 1, count <= 1000, count++,
divMethod[p];
p = NextPrime[p];
]
][[1]]}, {k, 3, 22}];
fiTiming = Table[{10^k, RepeatedTiming[
p = NextPrime[10^k];
For[count = 1, count <= 1000, count++,
g[p];
p = NextPrime[p];
]
][[1]]}, {k, 3, 22}];
ListLogLinearPlot[{divTiming, fiTiming},
PlotLegends -> {"Divisors", "FactorInteger"}]
```
![Timings chart](https://i.stack.imgur.com/xb9w4.png)
```
ListLogLinearPlot[
Transpose[{
divTiming[[All, 1]],
(divTiming/fiTiming)[[All, 2]]}],
PlotLegends -> {"Divisors/FactorInteger"}]
```
![Speedup chart](https://i.stack.imgur.com/91dyS.png)
So around 10^7 or 10^8, the `Divisors` method is noticeably slower than the `FactorInteger` method. The ratio of times rises to 3-ish for primes around 10^15. There is a dip, for slightly larger primes, but the trend suggests the speed-up will improve as we go to larger primes than tested.
] |
[Question]
[
Yes, how *much*, not how many...
As we all know, a large present is far better than a small one. Therefore, the value of the presents should always be measured in total volume, not number of presents, weight, or even combined price.
As it's frowned upon to compare the amount of presents one gets, you don't want a long script that's easily seen and read by others at the Christmas party. Therefore you need to keep the number of bytes in your script at a minimum.
Your task is simple: **Create a program that takes a list of dimensions as input, on any suitable format, and outputs the combined volume of your presents.** The dimension of each present will either be a set of three numbers, or a single number. If the input is three numbers (`L, W, H`), the present is a cuboid of dimensions `L x W x H`. If it's a single number (`R`), the present is a sphere of radius `R`.
Rules:
* It can be either a full program or a function
* The input can be in any convenient format
+ If desirable, a sphere may be represented by a number followed by two zeros
+ A cuboid will always have all non-zero dimensions.
* The output should be a single decimal number
+ Additional output is accepted as long as it's obvious what the answer is
+ Output must have at least two digits after the decimal point
+ The output can be in standard form / scientific notation if the number is larger than 1000.
+ In case your language doesn't have a Pi-constant, the answer should be accurate up to 9999.99.
Examples:
```
((1,4,3),(2,2,2),(3),(4,4,4))
197.0973 // (1*4*3 + 2*2*2 + 4/3*pi*3^3 + 4*4*4)
(5)
523.5988
(5,0,0)
523.5988
```
---
## Leaderboard
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=67027,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~19~~ 18 bytes
```
Zµ*3×1420÷339Ḣo@PS
```
[Try it online!](http://jelly.tryitonline.net/#code=WsK1KjPDlzE0MjDDtzMzOeG4om9AUFM&input=&args=WygxLDQsMyksKDIsMiwyKSwoMywwLDApLCg0LDQsNCld)
Unfortunately, Jelly does not have a **π** constant yet, and the vectorizer doesn't handle floats properly.
To overcome these issues, instead of multiplying by **4π/3**, we multiply by **1420** and divide by **339**. Since **1420 ÷ 339 = 4.18879056…** and **4π/3 = 4.18879020…**, this is sufficiently precise to comply with the rules.
The newest version of Jelly could accomplish this task in **14 bytes**, with better precision.
```
Zµ*3×240°Ḣo@PS
```
[Try it online!](http://jelly.tryitonline.net/#code=WsK1KjPDlzI0MMKw4biib0BQUw&input=&args=WygxLDQsMyksKDIsMiwyKSwoMywwLDApLCg0LDQsNCld)
### How it works
```
Zµ*3×1420÷339Ḣo@PS Left argument: A, e.g., [[1, 2, 3], [4, 0, 0]]
Z Zip A; turn A into [[1, 4], [2, 0], [3, 0]].
µ Begin a new, monadic chain with zip(A) as left argument.
*3 Cube all involved numbers.
×1420 Multiply all involved numbers by 1420.
÷339 Divide all involved numbers by 339.
This calculates [[4.19, 268.08], [33.51, 0], [113.10, 0]]
Ḣ Head; retrieve the first array.
This yields [4.19, 268.08].
P Take the product across the columns of zip(A).
This yields [6, 0].
o@ Apply logical OR with swapped argument order to the results.
This replaces zeroes in the product with the corresponding
results from the left, yielding [6, 268.08].
S Compute the sum of the resulting numbers.
```
The non-competing version uses `×240°` instead of `×1420÷339`, which multiplies by **240** and converts the products to radians.
[Answer]
## Haskell, 40 bytes
```
q[x]=4/3*pi*x^^3
q x=product x
sum.map q
```
Usage example: `sum.map q $ [[1,4,3],[2,2,2],[3],[4,4,4]]` -> `197.09733552923254`.
How it works: For each element of the input list: if it has a single element `x` calculate the volume of the sphere, else take the `product`. Sum it up.
[Answer]
# Pyth, ~~19~~ 18 bytes
```
sm|*Fd*.tC\ð7^hd3Q
```
*1 byte thanks to Dennis*
[Demonstration](https://pyth.herokuapp.com/?code=sm%7C%2aFd%2a.tC%5C%C3%B07%5Ehd3Q&input=%5B%5B1%2C4%2C3%5D%2C%5B2%2C2%2C2%5D%2C%5B3%2C0%2C0%5D%2C%5B4%2C4%2C4%5D%5D&debug=0)
Input format is list of lists:
```
[[1,4,3],[2,2,2],[3,0,0],[4,4,4]]
```
It simply multiplies the dimensions together to calculate the cube volume. If that comes out to zero, it calculates the sphere volume.
The sphere constant, `4/3*pi` is calculated as 240 degrees in radians. `.t ... 7` converts an input in degrees to radians, and `C\ð` calculates the code point of `ð`, which is 240.
[Answer]
# Python 2, ~~86~~ 70 bytes
```
lambda i:sum(x[0]*x[1]*x[2]if len(x)>1 else x[0]**3*4.18879for x in i)
```
[Answer]
## Mathematica, 34 bytes
```
Tr[1.##&@@@(#/.{r_}:>{4r^3/3Pi})]&
```
An unnamed function which takes a nested list of lengths and returns the volume as a real number.
We first replace single values with the volume of the corresponding sphere with `/.{r_}:>{4r^3/3Pi}`. Then we multiply up the contents of each list with `1.##&@@@`. Finally we compute the sum as the trace of the vector with `Tr[...]`.
[Answer]
# JavaScript (ES6), 56
```
l=>l.map(([x,y,z])=>t+=y?x*y*z:x*x*x*4/3*Math.PI,t=0)&&t
```
The more *sensible* `.reduce` version is 1 byte longer
```
l=>l.reduce((t,[x,y,z])=>t+(y?x*y*z:x*x*x*4/3*Math.PI),0)
```
[Answer]
## Python, 49 bytes
```
lambda l:sum(a*b*c or a**3*4.18879for a,b,c in l)
```
Uses the representation of spheres as `(a,0,0)`. Treated as a cuboid, this has volume 0, in which case the sphere volume is used instead. I'm not clear on how accurate the constant needs to be, so I hope this is enough.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 20 bytes
```
it!ptbw~)3^4*3/XT*hs
```
Input format is a matrix in which each row describes a cube or a sphere. A sphere is defined by only the first number in that row; the other two numbers are zero. So the first example from the challenge would be:
```
[1 4 3; 2 2 2; 3 0 0; 4 4 4]
```
This uses the current release of the language, [2.0.2](https://github.com/lmendo/MATL/releases/tag/2.0.2), which is earlier than this challenge.
### Examples:
```
>> matl it!ptbw~)3^4*3/XT*hs
> [1 4 3; 2 2 2; 3 0 0; 4 4 4]
197.0973355292326
>> matl it!ptbw~)3^4*3/XT*hs
> [5 0 0]
523.5987755982989
```
### Explanation:
```
i % input matrix
t! % duplicate and transpose: each object is now a column
p % product of elements in each column
t % duplicate
b % bubble up top-third element in stack
w % swap top two elements in stack
~ % logical 'not'. This gives logical index of speheres
) % reference () indexing. This is a logical-linear index to get sphere radii
3^4*3/XT* % formula for volume of spehere; element-wise operations
h % horizontal concatenation
s % sum
```
[Answer]
# Prolog, ~~115~~ 100 bytes
**Code:**
```
[]*0.
[[L,W,H]|T]*V:-W=0,X is 4*pi*L^3/3,T*Y,V is X+Y;X is L*W*H,T*Y,V is X+Y.
p(L):-L*V,write(V).
```
**Explained:**
```
[]*0.
[[L,W,H]|T]*V:-W=0, % When 2nd dimension is 0
X is 4*pi*L^3/3, % Calc volume of sphere
T*Y, % Recurse over list
V is X+Y % Sum volumes
; % When we have a cube
X is L*W*H, % Calc cube volume
T*Y % Recurse over list
V is X+Y. % Sum volumes
p(L):-L*V, % Get combined volume of list of lists
write(V). % Print volume
```
**Examples:**
```
p([[1,4,3],[2,2,2],[3,0,0],[4,4,4]]).
197.09733552923257
p([[5,0,0]]).
523.5987755982989
```
Try it online [here](http://swish.swi-prolog.org/p/NoqJoceN.pl)
Edit: saved 15 bytes by defining a dyadic predicate.
[Answer]
## Perl, ~~52~~ 47 bytes
```
s/,/*/g||s@$@**3*4.18879@,$\+=eval for/\S+/g}{
```
*46 + 1 for `-p` (that's been common; let me know if it's different here and I'll update)*
Usage: put in a file and `echo 1,4,3 2,2,2 3 4,4,4 | perl -p x.pl`
With comments:
```
s/,/*/g # x,y,z becomes x*y*z
|| # if that fails,
s@$@**3*1420/339@ # x becomes x**3 * 1420/339
, #
$\+=eval # evaluate the expression and accumulate
for/\S+/g # iterate groups of non-whitespace
}{ # -p adds while(<>){...}continue{print}; resets $_
```
**update 47** Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving some bytes using [this trick](https://codegolf.stackexchange.com/questions/5105/tips-for-golfing-in-perl/32884#32884).
[Answer]
## CJam, ~~24~~ 21 bytes
```
q~{3*)4P*3/*+3<:*}%:+
```
[Test it here.](http://cjam.aditsu.net/#code=q~%7B3*)4P*3%2F*%2B3%3C%3A*%7D%25%3A%2B&input=%5B%5B1%204%203%5D%20%5B2%202%202%5D%20%5B3%5D%20%5B4%204%204%5D%5D)
### Explanation
```
q~ e# Read and evaluate input.
{ e# Map this block over the list of presents...
3* e# Repeat the list of lengths 3 times. This will expand cuboids to 9 elements
e# and spheres to three copies of the radius.
) e# Pull off the last element.
4P*3/* e# Multiply by 4 pi / 3.
+ e# Add it back to the list of lengths.
3< e# Truncate to 3 elements. This is a no-op for spheres, which now have three
e# elements [r r 4*pi/3*r] but discards everything we've done to cuboids, such
e# that they're reduced to their three side lengths again.
:* e# Multiply the three numbers in the list.
}%
:+ e# Sum all the individual volumes.
```
[Answer]
## PowerShell, 67 Bytes
```
($args|%{($_,((,$_*3)+4.18879))[$_.count-eq1]-join'*'})-join'+'|iex
```
Some black magic happening here. I'll try to walk through it smoothly.
We first take our input, expected as individual comma-delimited arrays e.g. `(1,4,3) (2,2,2) (3) (4,4,4)`, and pipe that into a loop `|%{}`.
Inside the loop, we first check whether `$_`, the particular array we're considering, has only one item and use that to index into an array (essentially a shorter if/else construction). If it's more than one item, suppose `(1,4,3)` as input, we execute the first half, which is simply to spit out the array via `$_`, such as `(1,4,3)`. Otherwise, we create a new dynamic array consisting of the element three times with `(,$_*3)` and tack on an approximation of 4/3rd\*Pi. For input `(3)`, this will result in `(3,3,3,4.18879)` output.
Yes, PowerShell has a Pi constant, accessed via .NET call `[math]::PI`, but that's longer and I don't want to use it. :p
Regardless, we concatenate that output array with asterisks via `-join'*'`, so `"1*4*3"`. Once we're completely through the loop, we now have a collection of strings. We `-join'+'` all those together for our addition, and `iex` the expression to calculate the result.
Phew.
[Answer]
# Ruby, 58 characters
```
->b{b.reduce(0){|t,s|a,b,c=*s;t+(c ?a*b*c :a**3*4.18879)}}
```
Sample run:
```
2.1.5 :001 ->b{b.reduce(0){|t,s|a,b,c=*s;t+(c ?a*b*c :a**3*4.18879)}}[[[1,4,3],[2,2,2],[3],[4,4,4]]]
=> 197.09733
```
## Ruby, 50 characters
Improvement idea shamelessly stolen from [edc65](https://codegolf.stackexchange.com/users/21348/edc65)'s [JavaScript answer](https://codegolf.stackexchange.com/a/67054).
```
->b{t=0;b.map{|a,b,c|t+=c ?a*b*c :a**3*4.18879};t}
```
Sample run:
```
2.1.5 :001 > ->b{t=0;b.map{|a,b,c|t+=c ?a*b*c :a**3*4.18879};t}[[[1,4,3],[2,2,2],[3],[4,4,4]]]
=> 197.09733
```
[Answer]
# Japt, ~~27~~ 22 bytes
```
N®r*1 ª4/3*M.P*Zg ³} x
```
Takes input as space-separated arrays. [Try it online!](http://ethproductions.github.io/japt?v=master&code=Tq5yKjEgqjQvMypNLlAqWmcgs30geA==&input=WzEgNCAzXSBbMiAyIDJdIFszIDAgMF0gWzQgNCA0XQ==)
### How it works
```
N® r*1 ª 4/3*M.P*Zg ³ } x
NmZ{Zr*1 ||4/3*M.P*Zg p3 } x
// Implicit: N = array of input arrays
NmZ{ } // Map each item Z in N to:
Zr*1 // Reduce Z with multiplication.
||4/3*M.P // If this is falsy, calculate 4/3 times Pi
*Zg p3 // times the first item in Z to the 3rd power.
x // Sum the result.
// Implicit: output last expression
```
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
function(l)sum(mapply(function(x)prod(x*!!1:3)*4.18879^is.na(x[2]),l))
```
[Try it online!](https://tio.run/##PYpBCoMwFAX33sLdf/IRopFawZNICxIJBGIMRiGePqZdyNvMDG9Pekz6dOowmyOLcK60zt7bi54a4fdtoViVpRhaVLIWff96f02o3Uxxaj5gCyRN1oSDFAmW3IIVNZz3g7/JnCWAonieXdZ0Aw "R – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 23 bytes
```
{$*a|4/3*PI*@a**3}MSg^s
```
There's a couple ways to give input to this program. It can take each present as a command-line argument of three space-separated numbers (which will need to be wrapped in quotes: `pip.py present.pip "1 4 3" "3 0 0"`). Alternately, specify the `-r` flag and give each present as a line of stdin consisting of three space-separated numbers. [Try it online!](https://tio.run/##K8gs@P@/WkUrscZE31grwFPLIVFLy7jWNzg9rvj/f0MFEwVjLiMFIOQyVjBQMOAyAYqY/NctAgA "Pip – Try It Online")
### How?
```
g is list of cmdline args (or lines of stdin, if using -r flag)
s is space, PI is what it says on the tin (implicit)
g^s Split each argument on spaces, so we have a list of lists
{ }MS Map this function to each sublist and sum the results:
$*a Fold the list on * (i.e. take the product)
| Logical OR: if the above value is zero, use this value instead:
4/3*PI* 4/3 pi, times
@a First element of the list
**3 Cubed
Autoprint the result
```
[Answer]
# Perl 5, 142 bytes
Run with `-p` in the command line, and type numbers delimited with a comma, like so:
`5,0,0` or `(5,0,0)`
would produce
`523.598820058997`
There is no `pi` keyword in Perl. This is, in most cases, accurate to the significant figures specified, however even if I typed in all the figures of pi I know, it wouldn't be very accurate for some calculations. So I left it with `3.1415`. I'm unsure if this is acceptable or not.
Code:
```
@a=$_=~/(\d+,*)/g;$_=0;@n = map(split(/\D/),@a);for($i=0;$i<$#n;$i+=3){$x=$n[$i];$n[$i+1]==0?$_+=1420/339*$x**3:$_+=($x*$n[$i+1]*$n[$i+2]);}
```
Edited for greater precision on the advice of Dennis, who is better at basic mathematics than I, and from a suggestion by MichaelT to save bytes whilst remaining precise.
[Answer]
# Lua, ~~115~~ 104 bytes
```
function f(a)b=0 for i=1,#a do c=a[i]b=b+(1<#c and c[1]*c[2]*c[3]or(4/3)*math.pi*c[1]^3)end return b end
```
Straightforward solution, I have to wrap the pseudo-ternary operation `<condition> and <non-false> or <value if false>` in parenthesis else b would sum with both areas.
Input must be in the form `array={{1,4,3},{2,2,2},{3},{4,4,4}}` and the result can be seen by executing `print(f(array))`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εDgi3m4žq*3/*]PO
```
[Try it online.](https://tio.run/##yy9OTMpM/f//3FaX9EzjXJOj@wq1jPW1YgP8//@PjjbUMdExjtWJNtIBQiANYpsAxUxiYwE)
**Explanation:**
```
ε # Map each inner list of the (implicit) input to:
D # Duplicate the current inner list
gi # Is the length 1 (is it an `R`):
3m # Take the duplicated current item and take its cube
# i.e. [3] → [27]
žq # PI
4* # Multiplied by 4
3/ # Divided by 3
# → 4.1887902047863905
* # And multiply it with the current cubed `R`
# [27] and 4.1887902047863905 → [113.09733552923254]
] # Close both the if and map
P # Take the product of each inner list
# i.e. [[1,4,3],[2,2,2],[113.09733552923254],[4,4,4]]
# → [12,8,113.09733552923254,64]
O # Take the total sum (and output implicitly)
# i.e. [12,8,113.09733552923254,64] → 197.09733552923254
```
[Answer]
## R, ~~38~~ 36 bytes
```
function(x,y=4*pi/3*x,z=x)sum(x*y*z)
```
Uses default arguments to switch between the cases: with three arguments computes the product, and with one argument computes the sphere formula.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-mx`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÊÉ?U×:Um³*4/3*MP
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=ysk/Vdc6VW2zKjQvMypNUA&input=W1sxLDQsM10sWzIsMiwyXSxbM10sWzQsNCw0XV0)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/2445/edit)
As discussed in the Lounge room on Stack Overflow:
>
> if you can't implement the Quicksort algorithm given en.wikipedia.org/wiki/Quicksort in any language you have minimal knowledge of, you might want to consider a different profession. [@sbi](http://chat.stackoverflow.com/transcript/message/668507#668507)
>
>
>
but SBI also noted that maybe BrainF\*\*\* was an exception.
So, here's the puzzle/challenge: implement QuickSort in [BrainF\*\*\*](http://en.wikipedia.org/wiki/Brainfuck). The implementation must
* be interpreted by [this](http://brainfuck.tk) and/or by the interpreter(s) [here](http://www.hevanet.com/cristofd/brainfuck/) (for large scripts)
* implement the algorithm as described on Wikipedia - if possible as an in-place sort
* sort the following list of integers: [0,4,6,4,2,3,9,2,3,6,5,3] and print the result
[Answer]
**BrainF\*** *(697 bytes)*
```
>>>>>>>>,[>,]<[[>>>+<<<-]>[<+>-]<+<]>[<<<<<<<<+>>>>>>>>-]<<<<<<<<[[>>+
>+>>+<<<<<-]>>[<<+>>-]<[>+>>+>>+<<<<<-]>[<+>-]>>>>[-<->]+<[>->+<<-[>>-
<<[-]]]>[<+>-]>[<<+>>-]<+<[->-<<[-]<[-]<<[-]<[[>+<-]<]>>[>]<+>>>>]>[-<
<+[-[>+<-]<-[>+<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<]<<[>>+<<-]>[>[>+>
>+<<<-]>[<+>-]>>>>>>[<+<+>>-]<[>+<-]<<<[>+>[<-]<[<]>>[<<+>[-]+>-]>-<<-
]>>[-]+<<<[->>+<<]>>[->-<<<<<[>+<-]<[>+<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]
<<]>[[-]<<<<<<[>>+>>>>>+<<<<<<<-]>>[<<+>>-]>>>>>[-[>>[<<<+>>>-]<[>+<-]
<-[>+<-]>]<<[[>>+<<-]<]]>]<<<<<<-]>[>>>>>>+<<<<<<-]<<[[>>>>>>>+<<<<<<<
-]>[<+>-]<+<]<[[>>>>>>>>+<<<<<<<<-]>>[<+>-]<+<<]>+>[<-<<[>+<-]<[<]>[[<
+>-]>]>>>[<<<<+>>>>-]<<[<+>-]>>]<[-<<+>>]>>>]<<<<<<]>>>>>>>>>>>[.>]
```
Below is an annotated version. In order to keep track of what was supposed to be happening while developing it, I used a comment notation that looks like this: `|a|b=0|c=A0|@d|A0|A1|```|`
```
|a| represents a named cell
|b=X| means we know the cell has value X, where X can be a constant or a variable name
|@d| means the data pointer is in this cell
|A0|A1|```| is variable length array. (using ``` for ... because . is a command)
```
The memory is laid out with a left-growing stack of partitions to process on the left, a scratch space in the center, and the array being sorted to the right. Array indexing is handled by moving a "data bus" containing the index and working space through the array.
So for instance a 3-wide bus of `|i|data|0|A0|A1|A2`, will become `|A0|i-1|data|0|A1|A2` after shifting by one. The partitioning is performed by keeping the bus between the high and low elements.
Here's the full version:
```
Get input
>>>>>>>> ,[>,] |A0|A1|```|An|@0|
Count items
<[ [>>>+<<<-]>[<+>-]<+ <] |@0|n|0|0|A0|A1|```
Make 8wide data bus w/ stack on left
>[<<<<<<<<+>>>>>>>>-] ```|K1=n|K0=0|Z=0|a|b|c|d|e|@f|g|X=0|A0|A1|```
K1 and K0 represent the first index to process (I) and one past the last (J)
Check if still partitions to process
<<<<<<<<[
Copy K1 to a&c via Z
[>>+>+>>+<<<<<-]>>[<<+>>-] ```|K1=J|K0=I|@Z=0|a=J|b|c=J|d|e|f|g|X=0|A0|A1|```
Copy K0 to b&d via Z
<[>+>>+>>+<<<<<-]>[<+>-] ```|K1|K0|@Z=0|a=J|b=I|c=J|d=I|e|f|g|X=0|A0|A1|```
Check if J minus I LE 1 : Subtract d from c
>>>>[-<->] |a=J|b=I|c=JminusI|@d=0|e|f|g|
d= c==0; e = c==1
+<[>- >+<<-[>>-<<[-]]] |a=J|b=I|@c=0|d=c==0|e=c==1|f|g|
if d or e is 1 then J minus I LE 1: partition empty
>[<+>-]>[<<+>>-]<+< |a=J|b=I|@c=isEmpty|d=1|e=0|f|g|
If Partition Empty;
[->- |a=J|b=I|@c=0|d=0|c=0|f|g|
pop K0: Zero it and copy the remaining stack right one; inc new K0
<<[-]<[-]<<[-]<[[>+<-]<]>>[>]<+ ``|K1|@Z=0|a=J|b=I|c=0|d=0|e|f|g|
Else:
>>>>]>[- Z|a=J|b=I|c=isEmpty=0|@d=0|e|f|g|X|A0|A1
Move Bus right I plus 1 frames; leaving first element to left
<<+[ -[>+<-]<-[>+<-]>>>>>>>> (dec J as we move)
[<<<<<<<<+>>>>>>>>-]<<<<<< ] Z|Ai|a=J|@b=0|c=0|d|e|f|g|X|Aq
first element becomes pivot Ap; store in b
<<[>>+<<-] Z|@0|a=J|b=Ap|c=0|d|e|f|g|X|Aq
While there are more elements (J GT 0);
>[ Z|0|@a=J|b=Ap|c=0|d|e|f|g|X|Aq
copy Ap to e via c
>[>+>>+<<<-]>[<+>-] Z|0|a=J|b=Ap|@c=0|d=0|e=Ap|f|g|X=0|Aq
copy Aq to g via X
>>>>>>[<+<+>>-]<[>+<-] |c|d=0|e=Ap|f|g=Aq|@X=0|Aq
Test Aq LT Ap: while e; mark f; clear it if g
<<<[ >+>[<-]<[<] |@d=0|e|f=gLTe|g|
if f: set d and e to 1; dec e and g
>>[<<+>[-]+>-]>-<<-]
set g to 1; if d: set f
>>[-]+<<< [->>+<<]
If Aq LT Ap move Aq across Bus
>>[->- <<<<<[>+<-] <[>+<-] >>>>>>>>
[<<<<<<<<+>>>>>>>>-] <<] Z|0|Aq|a=J|b=Ap|c|d|e|@f=0|g=0|X=0|Ar
Else Swap AQ w/ Aj: Build a 3wide shuttle holding J and Aq
>[[-] <<<<<<[>>+>>>>>+<<<<<<<-]>>[<<+>>-] |@c=0|d|e|f=0|g=0|X=J|Aq|Ar|```
If J then dec J
>>>>>[-
& While J shuttle right
[>>[<<<+>>>-]<[>+<-]<-[>+<-]>] |a=J|b=Ap|c|d|e|f|Ar|```|Aj|g=0|@X=0|Aq|
Leave Aq out there and bring Aj back
<<[ [>>+<<-] < ] |a=J|b=Ap|c|d|e|@f=0|g|X=0|Ar|```|Aj|Aq|
]>]
Either bus moved or last element swapped; reduce J in either case
<<<<<<-] |Aq|@a=0|b=Ap|c|d|e|f|g|X|Ar|```|
Insert Ap To right of bus
>[>>>>>>+<<<<<<-] |Aq|a=0|@b=0|c|d|e|f|g|Ap|Ar|```|
Move the bus back to original location tracking pivot location
<<[ [>>>>>>>+<<<<<<<-]>[<+>-]<+ <]
<[ [>>>>>>>>+<<<<<<<<-]>>[<+>-]<+ <<] |K1|K0|@Z=0|a=0|b=p|c|d|e|f|g|X|Ar|```
if p is not 0: put new partition on stack between K0 and K1:
>+>[<- |K1|K0|Z=0|@a=pEQ0|b=p|
move K0 to Z; search for last K
<<[>+<-] <[<] |@0|Kn|```|K1|0|Z=K0|a=0|b=p|
shift left until return to 0 at K0;
>[ [<+>-] >] |Kn|```|K1|0|@0|Z=K0|a=0|b=p|
put p one left of there making it K1; restore K0 from Z;
>>>[<<<<+>>>>-]<<[<+>-] |Kn|```|K2|K1=p|K0|@Z=0|a=0|b=0|
else increment K0 (special case when first partition empty)
>>]<[- <<+>>]
>>>] End if !empty
<<<<<<] End If Partitions remaining @K1=0|K0=0|Z=0|a|b|c|d|e|f|g|X=0|A0|A1|```
Print the Results
>>>>>>>>>>>[.>]
```
[Answer]
**brainfuck** *(178 bytes)*
Even if brainfuck is cumbersome, it helps to work with the grain of the language. Ask yourself "Do I have to store this value explicitly in a cell?" You can often gain speed and concision by doing something more subtle. And when the value is an array index (or an arbitrary natural number), it may not *fit* in a cell. Of course, you could just accept that as a limit of your program. But designing your program to handle large values will often make it better in other ways.
As usual, my first working version was twice as long as it needed to be—392 bytes. Numerous modifications and two or three major rewrites produced this comparatively graceful 178-byte version. (Though amusingly [a linear-time sort](https://codegolf.stackexchange.com/a/15308/10650) is only 40 bytes.)
```
>+>>>>>,[>+>>,]>+[--[+<<<-]<[[<+>-]<[<[->[<<<+>>>>+<-]<<[>>+>[->]<<[<]
<-]>]>>>+<[[-]<[>+<-]<]>[[>>>]+<<<-<[<<[<<<]>>+>[>>>]<-]<<[<<<]>[>>[>>
>]<+<<[<<<]>-]]+<<<]]+[->>>]>>]>[brainfuck.org>>>]
```
The input values are spaced every three cells: for every (V)alue cell, there is a (L)abel cell (used for navigation) and one more cell for (S)cratch space. The overall layout of the array is
0 1 0 0 0 S V L S V L ... S V L 0 0 0 0 0 0 ...
Initially all the L cells are set to 1, to mark portions of the array that still need sorting. When we're done partitioning a subarray, we divide it into smaller subarrays by setting its pivot's L cell to 0, then locate the rightmost L cell that's still 1 and partition that subarray next. Oddly, this is all the bookkeeping we need to properly handle the recursive processing of subarrays. When all L cells have been zeroed, the whole array is sorted.
To partition a subarray, we pull its rightmost value into an S cell to act as pivot, and bring it (and the corresponding empty V cell) left, comparing it to each other value in the subarray and swapping as needed. At the end the pivot gets swapped back in, using the same swap code (which saves 50 bytes or so). During partitioning, two extra L cells are kept set to 0, to mark the two cells that may need to be swapped with each other; at the end of partitioning, the left 0 will fuse with the 0 to the left of the subarray, and the right 0 will end up marking its pivot. This process also leaves an extra 1 in the L cell to the right of the subarray; the main loop begins and ends at this cell.
```
>+>>>>>,[>+>>,]>+[ set up; for each subarray:
--[+<<<-]<[ find the subarray; if it exists:
[<+>-]<[ S=pivot; while pivot is in S:
<[ if not at end of subarray
->[<<<+>>>>+<-] move pivot left (and copy it)
<<[>>+>[->]<<[<]<-]> move value to S and compare with pivot
]>>>+<[[-]<[>+<-]<]>[ if pivot greater then set V=S; else:
[>>>]+<<<-<[<<[<<<]>>+>[>>>]<-] swap smaller value into V
<<[<<<]>[>>[>>>]<+<<[<<<]>-] swap S into its place
]+<<< end else and set S=1 for return path
] subarray done (pivot was swapped in)
]+[->>>]>> end "if subarray exists"; go to right
]>[brainfuck.org>>>] done sorting whole array; output it
```
] |
[Question]
[
Write a function that takes 4 points on the plane as input and returns true iff the 4 points form a square. The points will have integral coordinates with absolute values < 1000.
You may use any reasonable representation of the 4 points as input. The points are not provided in any particular order.
Shortest code wins.
Example squares:
```
(0,0),(0,1),(1,1),(1,0) # standard square
(0,0),(2,1),(3,-1),(1,-2) # non-axis-aligned square
(0,0),(1,1),(0,1),(1,0) # different order
```
Example non-squares:
```
(0,0),(0,2),(3,2),(3,0) # rectangle
(0,0),(3,4),(8,4),(5,0) # rhombus
(0,0),(0,0),(1,1),(0,0) # only 2 distinct points
(0,0),(0,0),(1,0),(0,1) # only 3 distinct points
```
You may return either true or false for the degenerate square `(0,0),(0,0),(0,0),(0,0)`
[Answer]
# Python ~~176~~ ~~90~~ 79 bytes
```
def S(A):c=sum(A)/4.0;return set(A)==set((A[0]-c)\*1j\*\*i+c for i in range(4))
```
Function S takes a list of complex numbers as its input (A). If we know both the centre and one corner of a square, we can reconstruct the square by rotating the corner 90,180 and 270 degrees around the centre point (c). On the complex plane rotation by 90 degrees about the origin is done by multiplying the point by *i*. If our original shape and the reconstructed square have the same points then it must have been a square.
[Answer]
## J, 28 ~~17~~ ~~25~~ ~~27~~
J doesn't really have functions, but here's a monadic verb that takes a vector of points from the complex plane:
```
4 8 4-:#/.~&(/:~&:|&,&(-/~))
```
Method is a mix of [Michael Spencer](https://codegolf.stackexchange.com/questions/1487/determine-if-4-points-form-a-square/1501#1501) (work solely on inter-vertex lengths; but he's currently failing my rhombus2) and [Eelvex's](https://codegolf.stackexchange.com/questions/1487/determine-if-4-points-form-a-square/1504#1504) (check the sets' sizes) works. Reading right to left:
* `-/~` compute all point differences
* `,` flatten
* `|` extract magnitude
* `/:~` sort up
* `#/.~` nub and count
* `4 8 4 -:` must have exactly 4 equidistant (at 0), 8 a bit bigger (length 1, sides), 4 bigger yet (length `sqrt 2`, diagonals)
Demonstration:
```
NB. give the verb a name for easier use
f =: 4 8 4-:#/.~&(/:~&:|&,&(-/~))
NB. standard square
f 0 0j1 1j1 1
1
NB. non-axis-aligned square
f 0 2j1 3j_1 1j_2
1
NB. different order
f 0 1j1 0j1 1
1
NB. rectangle
f 0 0j2 3j2 3
0
NB. rhombus 1
f 0 3j4 8j4 5
0
NB. rhombus 2
f 0 1ad_60 1ad0 1ad60
0
```
For memory's sake, my previous method (required ordered vertices, but could detect regular polygons of any order):
```
*./&(={.)&(%1&|.)&(-1&|.)
```
See history for explanation and demo. The current method could probably be expanded to other polygons, that `4 8 4` does look a lot like a binomial distribution.
[Answer]
# Python, 71 ~~42~~
```
lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3
```
Update 1) to require 4 different points (would previously give false positives for repeated points - are there others?) 2) to define a function per spec
For a square, the vector between any two points must be 0 (the same point), a side, or a diagonal. So, the set of the magnitude of these vectors must have length 3.
```
# Accepts co-ordinates as sequences of complex numbers
SQUARES=[
(0+0j,0+1j,1+1j,1+0j), # standard square
(0+0j,2+1j,3-1j,1-2j), # non-axis-aligned square
(0+0j,1+1j,0+1j,1+0j) # different order
]
NONSQUARES=[
(0+0j,0+2j,3+2j,3+0j), # rectangle
(0+0j,3+4j,8+4j,5+0j), # rhombus
(0+0j,0+1j,1+1j,0+0j), # duplicated point
(0+0j,1+60j,1+0j,1-60j) # rhombus 2 (J B)
]
test = "lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3"
assert len(test)==71
is_square=lambda A: len(set(A))==4 and len(set(abs(i-j)for i in A for j in A))==3
for A in SQUARES:
assert is_square(A)
for A in NONSQUARES:
assert not is_square(A)
```
[Answer]
## Haskell, 100 characters
Here's how I'd write the JB's J solution in Haskell. With no attempt made to damage readability by removing nonessential characters, it's about 132 characters:
```
import Data.List
d (x,y) (x',y') = (x-x')^2 + (y-y')^2
square xs = (== [4,8,4]) . map length . group . sort $ [d x y | x<-xs, y<-xs]
```
You can scrape it down a bit to 100 by removing excess spaces and renaming some things
```
import Data.List
d(x,y)(a,b)=(x-a)^2+(y-b)^2
s l=(==[4,8,4]).map length.group.sort$[d x y|x<-l,y<-l]
```
Let's use QuickCheck to ensure that it accepts arbitrary squares, with one vertex at (x,y) and edge vector (a,b):
```
prop_square (x,y) (a,b) = square [(x,y),(x+a,y+b),(x-b,y+a),(x+a-b,y+b+a)]
```
Trying it in ghci:
```
ghci> quickCheck prop_square
*** Failed! Falsifiable (after 1 test):
(0,0)
(0,0)
```
Oh right, the empty square isn't considered a square here, so we'll revise our test:
```
prop_square (x,y) (a,b) =
(a,b) /= (0,0) ==> square [(x,y),(x+a,y+b),(x-b,y+a),(x+a-b,y+b+a)]
```
And trying it again:
```
ghci> quickCheck prop_square
+++ OK, passed 100 tests.
```
[Answer]
## Factor
An implementation in the [Factor](http://www.factorcode.org) programming language:
```
USING: kernel math math.combinatorics math.vectors sequences sets ;
: square? ( seq -- ? )
members [ length 4 = ] [
2 [ first2 distance ] map-combinations
{ 0 } diff length 2 =
] bi and ;
```
And some unit tests:
```
[ t ] [
{
{ { 0 0 } { 0 1 } { 1 1 } { 1 0 } } ! standard square
{ { 0 0 } { 2 1 } { 3 -1 } { 1 -2 } } ! non-axis-aligned square
{ { 0 0 } { 1 1 } { 0 1 } { 1 0 } } ! different order
{ { 0 0 } { 0 4 } { 2 2 } { -2 2 } } ! rotated square
} [ square? ] all?
] unit-test
[ f ] [
{
{ { 0 0 } { 0 2 } { 3 2 } { 3 0 } } ! rectangle
{ { 0 0 } { 3 4 } { 8 4 } { 5 0 } } ! rhombus
{ { 0 0 } { 0 0 } { 1 1 } { 0 0 } } ! only 2 distinct points
{ { 0 0 } { 0 0 } { 1 0 } { 0 1 } } ! only 3 distinct points
} [ square? ] any?
] unit-test
```
[Answer]
**OCaml, 145 164**
```
let(%)(a,b)(c,d)=(c-a)*(c-a)+(d-b)*(d-b)
let t a b c d=a%b+a%c=b%c&&d%c+d%b=b%c&&a%b=a%c&&d%c=d%b
let q(a,b,c,d)=t a b c d||t a c d b||t a b d c
```
Run like this:
```
q ((0,0),(2,1),(3,-1),(1,-2))
```
Let's deobfuscate and explain a bit.
First we define a norm:
```
let norm (ax,ay) (bx,by) = (bx-ax)*(bx-ax)+(by-ay)*(by-ay)
```
You'll notice that there is no call to sqrt, it's not needed here.
```
let is_square_with_fixed_layout a b c d =
(norm a b) + (norm a c) = norm b c
&& (norm d c) + (norm d b) = norm b c
&& norm a b = norm a c
&& norm d c = norm d b
```
Here a, b, c and d are points.
We assume that these points are layed out like this:
```
a - b
| / |
c - d
```
If we have a square then all these conditions must hold:
* a b c is a right triangle
* b c d is a right triangle
* the smaller sides of each right triangle have the same norms
Observe that the following always holds:
```
is_square_with_fixed_layout r s t u = is_square_with_fixed_layout r t s u
```
We will use that to simplify our test function below.
Since our input is not ordered, we also have to check all permutations. Without loss of generality we can avoid permuting the first point:
```
let is_square (a,b,c,d) =
is_square_with_fixed_layout a b c d
|| is_square_with_fixed_layout a c b d
|| is_square_with_fixed_layout a c d b
|| is_square_with_fixed_layout a b d c
|| is_square_with_fixed_layout a d b c
|| is_square_with_fixed_layout a d c b
```
After simplification:
```
let is_square (a,b,c,d) =
is_square_with_fixed_layout a b c d
|| is_square_with_fixed_layout a c d b
|| is_square_with_fixed_layout a b d c
```
Edit: followed M.Giovannini's advice.
[Answer]
## Python (105)
Points are represented by `(x,y)` tuples. Points can be in any order and only accepts squares. Creates a list, `s`, of pairwise (non-zero) distances between the points. There should be 12 distances in total, in two unique groups.
```
def f(p):s=filter(None,[(x-z)**2+(y-w)**2for x,y in p for z,w in p]);return len(s)==12and len(set(s))==2
```
[Answer]
## Python - 42 chars
Looks like its an improvement to use complex numbers for the points
```
len(set(abs(x-y)for x in A for y in A))==3
```
where
A = [(11+13j), (14+12j), (13+9j), (10+10j)]
old answer:
```
from itertools import*
len(set((a-c)**2+(b-d)**2 for(a,b),(c,d)in combinations(A,2)))==2
```
Points are specified in any order as a list, eg
```
A = [(11, 13), (14, 12), (13, 9), (10, 10)]
```
[Answer]
C# -- not exactly short. Abusing LINQ. Selects distinct two-combinations of points in the input, calculates their distances, then verifies that exactly four of them are equal and that there is only one other distinct distance value. Point is a class with two double members, X and Y. Could easily be a Tuple, but meh.
```
var points = new List<Point>
{
new Point( 0, 0 ),
new Point( 3, 4 ),
new Point( 8, 4 ),
new Point( 5, 0 )
};
var distances = points.SelectMany(
(value, index) => points.Skip(index + 1),
(first, second) => new Tuple<Point, Point>(first, second)).Select(
pointPair =>
Math.Sqrt(Math.Pow(pointPair.Item2.X - pointPair.Item1.X, 2) +
Math.Pow(pointPair.Item2.Y - pointPair.Item1.Y, 2)));
return
distances.Any(
d => distances.Where( p => p == d ).Count() == 4 &&
distances.Where( p => p != d ).Distinct().Count() == 1 );
```
[Answer]
**PHP, 82 characters**
---
```
//$x=array of x coordinates
//$y=array of respective y coordinates
/* bounding box of a square is also a square - check if Xmax-Xmin equals Ymax-Ymin */
function S($x,$y){sort($x);sort($y);return ($x[3]-$x[0]==$y[3]-$y[0])?true:false};
//Or even better (81 chars):
//$a=array of points - ((x1,y1), (x2,y2), (x3,y3), (x4,y4))
function S($a){sort($a);return (bool)($a[3][0]-$a[0][0]-abs($a[2][1]-$a[3][1]))};
```
[Answer]
## [K](https://github.com/kevinlawler/kona) - 33
Translation of the [J solution by J B](https://codegolf.stackexchange.com/questions/1487/determine-if-4-points-form-a-square/1491#1491):
```
{4 8 4~#:'=_sqrt+/'_sqr,/x-/:\:x}
```
K suffers here from its reserved words(`_sqr` and `_sqrt`).
Testing:
```
f:{4 8 4~#:'=_sqrt+/'_sqr,/x-/:\:x}
f (0 0;0 1;1 1;1 0)
1
f 4 2#0 0 1 1 0 1 1 0
1
f 4 2#0 0 3 4 8 4 5 0
0
```
[Answer]
# OCaml + Batteries, 132 characters
```
let q l=match List.group(-)[?List:(x-z)*(x-z)+(y-t)*(y-t)|x,y<-List:l;z,t<-List:l;(x,y)<(z,t)?]with[[s;_;_;_];[d;_]]->2*s=d|_->false
```
(look, Ma, no spaces!) The list comprehension in `q` forms the list of squared norms for each distinct unordered pair of points. A square has four equal sides and two equal diagonals, the squared lengths of the latter being twice the squared lengths of the former. Since there aren't equilateral triangles in the integer lattice the test isn't really necessary, but I include it for completeness.
Tests:
```
q [(0,0);(0,1);(1,1);(1,0)] ;;
- : bool = true
q [(0,0);(2,1);(3,-1);(1,-2)] ;;
- : bool = true
q [(0,0);(1,1);(0,1);(1,0)] ;;
- : bool = true
q [(0,0);(0,2);(3,2);(3,0)] ;;
- : bool = false
q [(0,0);(3,4);(8,4);(5,0)] ;;
- : bool = false
q [(0,0);(0,0);(1,1);(0,0)] ;;
- : bool = false
q [(0,0);(0,0);(1,0);(0,1)] ;;
- : bool = false
```
[Answer]
# Mathematica 65 80 69 66
Checks that the number of distinct inter-point distances (not including distance from a point to itself) is 2 and the shorter of the two is not 0.
```
h = Length@# == 2 \[And] Min@# != 0 &[Union[EuclideanDistance @@@ Subsets[#, {2}]]] &;
```
**Usage**
```
h@{{0, 0}, {0, 1}, {1, 1}, {1, 0}} (*standard square *)
h@{{0, 0}, {2, 1}, {3, -1}, {1, -2}} (*non-axis aligned square *)
h@{{0, 0}, {1, 1}, {0, 1}, {1, 0}} (*a different order *)
h@{{0, 0}, {0, 2}, {3, 2}, {3, 0}} (* rectangle *)
h@{{0, 0}, {3, 4}, {8, 4}, {5, 0}} (* rhombus *)
h@{{0, 0}, {0, 0}, {1, 1}, {0, 0}} (* only 2 distinct points *)
h@{{0, 0}, {0, 1}, {1, 1}, {0, 1}} (* only 3 distinct points *)
```
>
> True
>
> True
>
> True
>
> False
>
> False
>
> False
>
> False
>
>
>
N.B.: `\[And]` is a single character in Mathematica.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
_Æm×ıḟƊṆ
```
[Try it online!](https://tio.run/##y0rNyan8/z/@cFvu4elHNj7cMf9Y18Odbf8Ptz9qWhP5/390tEGWjoIhEGsYahtmaYJpgyzNWB0FsIyGEVTUWBcqq2uEJAvVA9WPpM8IJGKsbQTRi2KisbYJWNQCSpsiyyKbapCFJmoAsSs2FgA "Jelly – Try It Online")
Takes a list of complex numbers as a command line argument. Prints `1` or `0`.
```
_Æm Subtract mean of points from each point (i.e. center on 0)
×ıḟƊ Rotate 90°, then compute set difference with original.
Ṇ Logical negation: if empty (i.e. sets are equal) then 1 else 0.
```
This seems like an enjoyable challenge to revive!
[Answer]
## Haskell (212)
```
import Data.List;j=any f.permutations where f x=(all g(t x)&&s(map m(t x)));t x=zip3 x(drop 1$z x)(drop 2$z x);g(a,b,c)=l a c==sqrt 2*l a b;m(a,b,_)=l a b;s(x:y)=all(==x)y;l(m,n)(o,p)=sqrt$(o-m)^2+(n-p)^2;z=cycle
```
Naive first attempt. Checks the following two conditions for all permutations of the input list of points (where a given permutation represents, say, a clockwise ordering of the points):
* all angles are 90 degrees
* all sides are the same length
Deobfuscated code and tests
```
j' = any satisfyBothConditions . permutations
--f
where satisfyBothConditions xs = all angleIs90 (transform xs) &&
same (map findLength' (transform xs))
--t
transform xs = zip3 xs (drop 1 $ cycle xs) (drop 2 $ cycle xs)
--g
angleIs90 (a,b,c) = findLength a c == sqrt 2 * findLength a b
--m
findLength' (a,b,_) = findLength a b
--s
same (x:xs) = all (== x) xs
--l
findLength (x1,y1) (x2,y2) = sqrt $ (x2 - x1)^2 + (y2 - y1)^2
main = do print $ "These should be true"
print $ j [(0,0),(0,1),(1,1),(1,0)]
print $ j [(0,0),(2,1),(3,-1),(1,-2)]
print $ j [(0,0),(1,1),(0,1),(1,0)]
print $ "These should not"
print $ j [(0,0),(0,2),(3,2),(3,0)]
print $ j [(0,0),(3,4),(8,4),(5,0)]
print $ "also testing j' just in case"
print $ j' [(0,0),(0,1),(1,1),(1,0)]
print $ j' [(0,0),(2,1),(3,-1),(1,-2)]
print $ j' [(0,0),(1,1),(0,1),(1,0)]
print $ j' [(0,0),(0,2),(3,2),(3,0)]
print $ j' [(0,0),(3,4),(8,4),(5,0)]
```
[Answer]
## Scala (146 characters)
```
def s(l:List[List[Int]]){var r=Set(0.0);l map(a=>l map(b=>r+=(math.pow((b.head-a.head),2)+math.pow((b.last-a.last),2))));print(((r-0.0).size)==2)}
```
[Answer]
# JavaScript 144 characters
Mathematically equal to J Bs answer. It generates the 6 lengths and assert that the 2 greatest are equal and that the 4 smallest are equal. Input must be an array of arrays.
```
function F(a){d=[];g=0;for(b=4;--b;)for(c=b;c--;d[g++]=(e*e+f*f)/1e6)e=a[c][0]-a[b][0],f=a[c][1]-a[b][1];d.sort();return d[0]==d[3]&&d[4]==d[5]} //Compact function
testcases=[
[[0,0],[1,1],[1,0],[0,1]],
[[0,0],[999,999],[999,0],[0,999]],
[[0,0],[2,1],[3,-1],[1,-2]],
[[0,0],[0,2],[3,2],[3,0]],
[[0,0],[3,4],[8,4],[5,0]],
[[0,0],[0,0],[1,1],[0,0]],
[[0,0],[0,0],[1,0],[0,1]]
]
for(v=0;v<7;v++){
document.write(F(testcases[v])+"<br>")
}
function G(a){ //Readable version
d=[]
g=0
for(b=4;--b;){
for(c=b;c--;){
e=a[c][0]-a[b][0]
f=a[c][1]-a[b][1]
d[g++]=(e*e+f*f)/1e6 //The division tricks the sort algorithm to sort correctly by default method.
}
}
d.sort()
return (d[0]==d[3]&&d[4]==d[5])
}
```
[Answer]
## PHP, ~~161~~ 158 characters
```
function S($a){for($b=4;--$b;)for($c=$b;$c--;){$e=$a[$c][0]-$a[$b][0];$f=$a[$c][1]-$a[$b][1];$d[$g++]=$e*$e+$f*$f;}sort($d);return$d[0]==$d[3]&&$d[4]==$d[5];}
```
Proof (1x1): <http://codepad.viper-7.com/ZlBpOB>
This is based off of [eBuisness's JavaScript answer](https://codegolf.stackexchange.com/questions/1487/determine-if-4-points-form-a-square/1513#1513).
[Answer]
## JavaScript 1.8, 112 characters
Update: saved 2 characters by folding the array comprehensions together.
```
function i(s)(p=[],[(e=x-a,f=y-b,d=e*e+f*f,p[d]=~~p[d]+1)for each([a,b]in s)for each([x,y]in s)],/8,+4/.test(p))
```
Another reimplementation of J B's answer. Exploits JavaScript 1.7/1.8 features (expression closures, array comprehensions, destructuring assignment). Also abuses `~~` (double bitwise not operator) to coerce `undefined` to numeric, with array-to-string coercion and a regexp to check that the length counts are `[4, 8, 4]` (it assumes that exactly 4 points are passed). The abuse of the comma operator is an old obfuscated C trick.
Tests:
```
function assert(cond, x) { if (!cond) throw ["Assertion failure", x]; }
let text = "function i(s)(p=[],[(e=x-a,f=y-b,d=e*e+f*f,p[d]=~~p[d]+1)for each([a,b]in s)for each([x,y]in s)],/8,+4/.test(p))"
assert(text.length == 112);
assert(let (source = i.toSource()) (eval(text), source == i.toSource()));
// Example squares:
assert(i([[0,0],[0,1],[1,1],[1,0]])) // standard square
assert(i([[0,0],[2,1],[3,-1],[1,-2]])) // non-axis-aligned square
assert(i([[0,0],[1,1],[0,1],[1,0]])) // different order
// Example non-squares:
assert(!i([[0,0],[0,2],[3,2],[3,0]])) // rectangle
assert(!i([[0,0],[3,4],[8,4],[5,0]])) // rhombus
assert(!i([[0,0],[0,0],[1,1],[0,0]])) // only 2 distinct points
assert(!i([[0,0],[0,0],[1,0],[0,1]])) // only 3 distinct points
// Degenerate square:
assert(!i([[0,0],[0,0],[0,0],[0,0]])) // we reject this case
```
[Answer]
## GoRuby - 66 characters
```
f=->a{z=12;a.pe(2).m{|k,l|(k-l).a}.so.go{|k|k}.a{|k,l|l.sz==z-=4}}
```
expanded:
```
f=->a{z=12;a.permutation(2).map{|k,l|(k-l).abs}.sort.group_by{|k|k}.all?{|k,l|l.size==(z-=4)}}
```
Same algorithm as [J B's answer](https://codegolf.stackexchange.com/questions/1487/determine-if-4-points-form-a-square/1491#1491).
Test like:
```
p f[[Complex(0,0), Complex(0,1), Complex(1,1), Complex(1,0)]]
```
Outputs `true` for true and blank for false
[Answer]
**Python 97 (without complex points)**
```
def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))
```
This will take lists of point tuples in [(x,y),(x,y),(x,y),(x,y)] in any order, and can handle duplicates, or the wrong number of points. It does NOT require complex points like the other python answers.
You can test it like this:
```
S1 = [(0,0),(1,0),(1,1),(0,1)] # standard square
S2 = [(0,0),(2,1),(3,-1),(1,-2)] # non-axis-aligned square
S3 = [(0,0),(1,1),(0,1),(1,0)] # different order
S4 = [(0,0),(2,2),(0,2),(2,0)] #
S5 = [(0,0),(2,2),(0,2),(2,0),(0,0)] #Redundant points
B1 = [(0,0),(0,2),(3,2),(3,0)] # rectangle
B2 = [(0,0),(3,4),(8,4),(5,0)] # rhombus
B3 = [(0,0),(0,0),(1,1),(0,0)] # only 2 distinct points
B4 = [(0,0),(0,0),(1,0),(0,1)] # only 3 distinct points
B5 = [(1,1),(2,2),(3,3),(4,4)] # Points on the same line
B6 = [(0,0),(2,2),(0,2)] # Not enough points
def tests(f):
assert(f(S1) == True)
assert(f(S2) == True)
assert(f(S3) == True)
assert(f(S4) == True)
assert(f(S5) == True)
assert(f(B1) == False)
assert(f(B2) == False)
assert(f(B3) == False)
assert(f(B4) == False)
assert(f(B5) == False)
assert(f(B6) == False)
def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))
tests(t)
```
This will take a little explaining, but the overall idea is that there are only three distances between the points in a square (Side, Diagonal, Zero(point compared to itself)):
```
def t(p):return len(set(p))-1==len(set([pow(pow(a-c,2)+pow(b-d,2),.5)for a,b in p for c,d in p]))
```
* for a list p of tuples (x,y)
* Remove duplicates using set(p) and then test the length
* Get every combination of points (a,b in p for c,d in p)
* Get list of the distance from every point to every other point
* Use set to check there are only three unique distances
-- Zero (point compared to itself)
-- Side length
-- Diagonal length
To save code characters I am:
* using a 1 char function name
* using a 1 line function definition
* Instead of checking the number of unique points is 4, I check that it is -1 the different point lengths (saves ==3==)
* use list and tuple unpacking to get a,b in p for c,d in p, instead of using a[0],a[1]
* uses pow(x,.5) instead of including math to get sqrt(x)
* not putting spaces after the )
* not putting a leading zero on the float
I fear someone can find a test case that breaks this. So please do and Ill correct. For instance the fact I just check for three distances, instead of doing an abs() and checking for side length and hypotenuse, seems like an error.
First time I've tried code golf. Be kind if I've broken any house rules.
[Answer]
Clojure, 159 chars.
```
user=> (def squares
[[[0,0] [0,1] [1,1] [1,0]] ; standard square
[[0,0] [2,1] [3,-1] [1,-2]] ; non-axis-aligned square
[[0,0] [1,1] [0,1] [1,0]]]) ; different order
#'user/squares
user=> (def non-squares
[[[0,0] [0,2] [3,2] [3,0]] ; rectangle
[[0,0] [3,4] [8,4] [5,0]]]) ; rhombus
#'user/non-squares
user=> (defn norm
[x y]
(reduce + (map (comp #(* % %) -) x y)))
#'user/norm
user=> (defn square?
[[a b c d]]
(let [[x y z] (sort (map #(norm a %) [b c d]))]
(and (= x y) (= z (* 2 x)))))
#'user/square?
user=> (every? square? squares)
true
user=> (not-any? square? non-squares)
true
```
Edit: To also explain a little bit.
* First define a norm which basically gives the distance between two given points.
* Then calculate the distance of the first point to the other three points.
* Sort the three distances. (This allows any order of the points.)
* The two shortest distances must be equal to be a square.
* The third (longest) distance must be equal to the square root of the sum of the squares of the short distances by the theorem of Pythagoras.
(Note: the square rooting is not needed and hence in the code saved above.)
[Answer]
### C#, 107 characters
```
return p.Distinct().Count()==4&&
(from a in p from b in p select (a-b).LengthSquared).Distinct().Count()==3;
```
Where points is List of Vector3D containing the points.
Computes all distances squared between all points, and if there are exactly three distinct types (must be 0, some value a, and 2\*a) and 4 distinct points then the points form a square.
[Answer]
# Python, 66
Improving [paperhorse's answer](https://codegolf.stackexchange.com/a/1554/7971) from 76 to 66:
```
def U(A):c=sum(A)/4;d=A[0]-c;return{d+c,c-d,d*1j+c,c-d*1j}==set(A)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda l:all(1j*z+(1-1j)*sum(l)/4in l for z in l)
```
[Try it online!](https://tio.run/##ZZDBboMwEETv@YqVerFTo2JIpCpVvqTtwWATHC02tY0K@XnqAKEV3cNoD/NmVtsOobYmG6vzx4iiKaQAPAlEwq/72zPhCb/Sve8agvTloA0gVNbBDe4rHb9rjQr4SbCClUyetWm7QOhb67QJUJH30jYtqp70bKATOW@RJgtDP@lIUpZSFpVH5YumFOI8gQ/CSOEk@K9OOLVbzNlky1kyu5OM3s3GmkT02icC9cWoLTRnp5sGqatKORUvtk4qt1vPyaaGWdMp36kynnPBNTFnh6ivkx4fpto2Red/c/5WzxZrcIAsNvugTRmgtfFh/4jHU1Yi3xI/ "Python 2 – Try It Online")
Takes a list of four complex numbers as input. Rotates each point 90 degrees around the average, and checks that each resulting point is in the original list.
Same length (though shorter in Python 3 using `{*l}`).
```
lambda l:{1j*z+(1-1j)*sum(l)/4for z in l}==set(l)
```
[Try it online!](https://tio.run/##ZZBRb4MgFIXf@ytushfoMANtk6WLv2TbAwpWGgQHmGmX/XZH1brF8XBCbs75zs1th1Bbk45V/jZq3hSCgz59scv@@ohYwi5477sGafx0qKyDKygD@jvPvQxxOH7WSktgJ04KUhKRK9N2AeGX1ikToEKvpW1aLXvUkwHDjTD/IgUtGfyOR0QJxSQqi8oWpRjiewAfuBHcCfAfHXdyt5jTyZaRZHYnKb6ZjTUJ75VPuFZnI7ehmU03DUJVlXQybmydkG63rpNODbPSie9kGdc565WYkUPU50mPd1Ntm6Lzv5y/1bPFGj1AGpt9UKYM0Np4sH@J@1HWRLZN/AA "Python 2 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~32~~ 31 bytes
```
Tr[#^2]==Tr[#^3]==0&[#-Mean@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H6xg@z@kKFo5zijW1hbMMAYyDNSilXV9UxPzHJRj1f4HFGXmlQAF7IKjlfWqDXU8a2Nj1RT0Hbiqq6sNdBQManUUQLQhiDZE0Aa1tTpcCgglRlApYx0FXZgaXSM0RTD9BrjNAdJGUHNgNLoSoJAJiLaA0qbISmCGoNuHxR4DuBNgTqqt/Q8A "Wolfram Language (Mathematica) – Try It Online")
Takes a list of points represented by complex numbers, calculates the second and third central moment, and checks that both are zero.
Un-golfed:
```
S[p_] := Total[(p - Mean[p])^2] == Total[(p - Mean[p])^3] == 0
```
or
```
S[p_] := CentralMoment[p, 2] == CentralMoment[p, 3] == 0
```
# proof
This criterion works on the entire complex plane, not just on the [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer).
1. First, we note that the [central moments](https://en.wikipedia.org/wiki/Central_moment) do not change when the points are translated together. For a set of points
```
P = Table[c + x[i] + I*y[i], {i, 4}]
```
the central moments are all independent of `c` (that's why they are called *central*):
```
{FreeQ[FullSimplify[CentralMoment[P, 2]], c], FreeQ[FullSimplify[CentralMoment[P, 3]], c]}
(* {True, True} *)
```
2. Second, the central moments have a simple dependence on overall complex scaling (scaling and rotation) of the set of points:
```
P = Table[f * (x[i] + I*y[i]), {i, 4}];
FullSimplify[CentralMoment[P, 2]]
(* f^2 * (...) *)
FullSimplify[CentralMoment[P, 3]]
(* f^3 * (...) *)
```
This means that if a central moment is zero, then scaling and/or rotating the set of points will keep the central moment equal to zero.
3. Third, let's prove the criterion for a list of points where the first two points are fixed:
```
P = {0, 1, x[3] + I*y[3], x[4] + I*y[4]};
```
Under what conditions are the real and imaginary parts of the second and third central moments zero?
```
C2 = CentralMoment[P, 2] // ReIm // ComplexExpand // FullSimplify;
C3 = CentralMoment[P, 3] // ReIm // ComplexExpand // FullSimplify;
Solve[Thread[Join[C2, C3] == 0], {x[3], y[3], x[4], y[4]}, Reals] // FullSimplify
(* {{x[3] -> 0, y[3] -> -1, x[4] -> 1, y[4] -> -1},
{x[3] -> 0, y[3] -> 1, x[4] -> 1, y[4] -> 1},
{x[3] -> 1/2, y[3] -> -1/2, x[4] -> 1/2, y[4] -> 1/2},
{x[3] -> 1/2, y[3] -> 1/2, x[4] -> 1/2, y[4] -> -1/2},
{x[3] -> 1, y[3] -> -1, x[4] -> 0, y[4] -> -1},
{x[3] -> 1, y[3] -> 1, x[4] -> 0, y[4] -> 1}} *)
```
All of these six solutions represent squares:
[![enter image description here](https://i.stack.imgur.com/N5ZPS.png)](https://i.stack.imgur.com/N5ZPS.png)
Therefore, the only way that a list of points of the form `{0, 1, x[3] + I*y[3], x[4] + I*y[4]}` can have zero second and third central moments is when the four points form a square.
Due to the translation, rotation, and scaling properties demonstrated in points 1 and 2, this means that any time the second and third central moments are zero, we have a square in some translation/rotation/scaling state. ∎
# generalization
The k-th central moment of a regular n-gon is zero if k is not divisible by n. Enough of these conditions must be combined to make up a sufficient criterion for detecting n-gons. For the case n=4 it was enough to detect zeros in k=2 and k=3; for detecting, e.g., hexagons (n=6) it may be necessary to check k=2,3,4,5 for zeros. I haven't proved the following, but suspect that it will detect any regular n-gon:
```
isregularngon[p_List] :=
And @@ Table[PossibleZeroQ[CentralMoment[p, k]], {k, 2, Length[p] - 1}]
```
The code challenge is essentially this code specialized for length-4 lists.
[Answer]
## J, 31 29 27 26
```
3=[:#[:~.[:,([:+/*:@-)"1/~
```
checks if the 8 smallest distances between the points are the same.
checks if there are exactly three kinds of distances between the points (zero, side length and diagonal length).
```
f 4 2 $ 0 0 2 1 3 _1 1 _2
1
f 4 2 $ 0 0 0 2 3 2 3 0
0
```
`4 2 $` is a way of writing an array in J.
[Answer]
## Smalltalk for 106 characters
```
s:=Set new.
p permutationsDo:[:e|s add:((e first - e second) dotProduct:(e first - e third))].
s size = 2
```
where p is a collection of points, e.g.
```
p := { 0@0. 2@1. 3@ -1. 1@ -2}. "twisted square"
```
I think the math is sound...
[Answer]
## Mathematica, 123 characters (but you can do better):
```
Flatten[Table[x-y,{x,a},{y,a}],1]
Sort[DeleteDuplicates[Abs[Flatten[Table[c.d,{c,%},{d,%}]]]]]
%[[1]]==0&&%[[3]]/%[[2]]==2
```
Where 'a' is the input in Mathematica list form, eg: `a={{0,0},{3,4},{8,4},{5,0}}`
The key is to look at the *dot* products between all the vectors and note that they must have exactly three values: 0, x, and 2\*x for some value of x. The dot product checks both perpendicularity AND length in one swell foop.
I know there are Mathematica shortcuts that can make this shorter, but I don't know what they are.
[Answer]
Haskell, "wc -c" reports 110 characters. Does not check that the input has 4 elements.
```
import Data.List
k [a,b]=2*a==b
k _=0<1
h ((a,b):t)=map (\(c,d)->(a-c)^2+(b-d)^2) t++h t
h _=[]
j=k.nub.sort.h
```
I tested on
```
test1 = [(0,0),(3,4),(-4,3),(-1,7)] -- j test1 is True
test2 = [(0,0),(3,4),(-3,4),(0,8)] -- j test2 is False
```
] |
[Question]
[
*Inspired by [this video](https://www.youtube.com/watch?v=wdgULBpRoXk) by Ben Eater. This challenge forms a pair with [Encode USB packets](https://codegolf.stackexchange.com/q/229504).*
The USB 2.0 protocol uses, at a low level, a line code called [**non-return-to-zero**](https://en.wikipedia.org/wiki/Non-return-to-zero) encoding (specifically, a variant called [NRZI](https://en.wikipedia.org/wiki/Non-return-to-zero#Non-return-to-zero_inverted)), in which a stream of bits is encoded into a stream of two electrical level states `J` and `K`. Decoding works as follows:
* Start with some initial state, which is either `J` or `K`
* For each state to be decoded:
+ If the state is different to the previous state, write a 0.
+ If the state is the same as the previous state, write a 1.
For this challenge, we will assume the encoding starts in state `J`.
However, it's not that simple: an additional process called [**bit stuffing**](https://en.wikipedia.org/wiki/Bit_stuffing) takes place, which is designed to make it easier to detect if the signal has dropped out. After 6 consecutive 1 bits are written, a meaningless 0 bit is written to ensure the signal never stays in the same state (`J` or `K`) for too long. When decoding, you need to take this into account and remove the 0 bit that necessarily occurs after 6 consecutive 1s.
The full USB specification is available [here](https://usb.org/document-library/usb-20-specification) on the USB website, or mirrored (and easier to access) [here](https://eater.net/downloads/usb_20.pdf), but I'd caution you before reading it because it's extremely long and the pertinent information is hard to pin down.
## Task
Given a non-empty list of `J`s or `K` states as input, decode the string using the USB implementation of NRZI described above, and output a binary string.
You may assume the input will never contain invalid data with incorrect bit stuffing (i.e., it will never contain 7 consecutive 1s).
## Test-cases
```
Input Output
=====================================
J 1
K 0
JKJKKJJ 1000101
KJKJKJKJ 00000000
JJJJJJKKK 11111111
KJJJJJJKJ 001111100
KJJJJJJJKJK 0011111100
KJJJJJJJKKJK 00111111100
KJJJJJJJKKKKKKKJKJ 0011111111111100
KJJJJJJJJKJ (incorrect bit stuffing; does not need to be handled)
KJJJKKKJKJJJJKJJ 0011011000111001
KKKJJKJKJJJJKKJKJJJJKKJKJJJJKJKJKKKKJKKKJKKKKJJKJKKJJJJJKJJKKKKKJJJJKKKKJJJJKKKKJJJJKKKKJKKJJJJKJJJJJKJJKKKJJJJJKKKKJJKKJJJJKKJKJJJJKKJJKKKJKJJKJJJKJJKKJKKJJJJKJJJKJKKKJJJKKKKKJJJKKKJJKJJKKKKKJJJJKKKKJJJKJKJJKKKKJJKJKKKJKJJJKKKJJKJKJKKKKKKKJKKKKJJJKJKKKKKJJKKKJKKJKJJKKJKJJKKKKJJJJKJJJKKJKJJJJKKKKJKKKKJKKJJKKJJJJKKKJKKKKJJKKKJKJKKKJKJJJKKJJKJKK 01101000011101000111010001110000011100110011101000101111001011110111011101110111011101110010111001111001011011110111010101110100011101010110001001100101001011100110001101101111011011010010111101110111011000010111010001100011011010000011111101110110001111010110010001010001011101110011010001110111001110010101011101100111010110000110001101010001
```
## Rules
* The input should be a string or array, with the two states `J` and `K` being represented by two distinct values of your choice ([within reason](https://codegolf.meta.stackexchange.com/a/14110))
* The output should be a string or array of `1`s and `0`s or of `true`s and `false`s
* You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447)
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
[Answer]
# [convey](http://xn--wxa.land/convey/), 31 25 bytes
Takes `JK` as `01`.
```
>="*>0
",v+<"(6
{0>">>!`}
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiPj1cIio+MFxuXCIsdis8XCIoNlxuezA+XCI+PiFgfSIsInYiOjEsImkiOiIxIDAgMCAwIDAgMCAwIDAgMSAxIDEgMSAxIDEgMSAwIDEgMCJ9)
Compares `=` the string with itself with a `J` prepended `,0`. The middle loop just adds the comparisons to a counter (starting with 0) that gets reset on a 0. Only take `!` elements where the previous counter was less than 6 `(6`.
[![enter image description here](https://i.stack.imgur.com/nUF0L.gif)](https://i.stack.imgur.com/nUF0L.gif)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
σḋ126ḋ63Ẋ=Θ
```
[Try it online!](https://tio.run/##yygtzv6fq/FwZ2Pxo6bGIs1D2/6fb364o9vQyAxImhk/3NVle27G////ow1iuaINgdhAx1AHhEEkWEwHJgLGYBUICFJnCFWFLGqAIQY1Aas4PhkExGUuujiSaiSbISqg/sKQJ8RHhIohEgtZBCXckO1F8QGqvwjzDdF9gcVkA6zmGBL0H3pIGWKYjd1@QzSb0f2HGiKE/W@IoRLdFuwmG2JNIZgmo4eKIVqIGOJwgQGazQY4Ywg1rDB9aoDDDdh9iOTyWC4A "Husk – Try It Online")
Takes an array of bits(0=J, 1=K), outputs an array of bits(formatted as string for convenience)
## Explanation
```
σḋ126ḋ63Ẋ=Θ
Θ Prepend 0
Ẋ= map overlapping pairs by equality
σḋ126ḋ63 replace binary digits of 126 with binary digits of 63 (stolen from Luis Mendo)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes
```
0ihd~126B63BZt
```
Input is an array with `0` for `'J'` and `1` for `'K'`.
[Try it online!](https://tio.run/##y00syfn/3yAzI6XO0MjMyczYKark//9oAwUENATBWAA) Or [verify all test cases](https://tio.run/##hVJLCsIwFNx7ihzhjUIPUDyCC7EUFF0o6K5rrx5NTMn7xRBeaSbDTGba12V5xnOkx/32xnYYh914WiJdj/tDnGjeTPgOBYQ06ZmxsCJ5MqOuxENhcZQMVhRc/N9JXS1djTM2c/4xSi5z3tvXVsDeOCJ6474igczV30OncJTJ1UE3n24KRtv3h3LW@WQj/fwwTO3iK8P9Q6yybgWqETRuQMqZml9IdmWTUuMOfkJ28/kD).
### Explanation
```
0 % Push 0
i % Input: string
h % Concatenate
d % Consecutive differences
~ % Negate: converts nonzero to 0, and zero to 1. Gives a numeric vector (*)
126B % Push 126, convert to binary. Gives [1 1 1 1 1 1 0]
63B % Push 63, convert to binary. Gives [1 1 1 1 1 1]
Zt % String replace (works for numeric vectors too). Replaces [1 1 1 1 1 1 0]
% by [1 1 1 1 1 1] in (*)
% Implicit display
```
[Answer]
# JavaScript (ES6), 54 bytes
```
s=>s.replace(/./g,a=>s^(s=a>"J")?i=i>5?'':0:++i/i,i=0)
```
[Try it online!](https://tio.run/##dVRNb8IwDL33V1RcSARr3cMuQymnXeLjjmMTVVdYpkIrUk1I034764edhlYzVIa8Z79nB/GVfWc2v5i6eThXH8XtoG5WpTa6FHWZ5YWIo/i4ztqTd2FVli70Qm6NMunjdrl8gqfVysRmbRTIW1PYJs9sYUMV7gMdziIJcH4IgUaNqO/4CQAk0PL18PL5FIHuA9HrmVC0dQOo/boeagsJ7BpPwDt0hBm9h/voJBzscwasV9HUonv3XOgm60ZmyjT3G0HU9AxMJNODNHuYZWRVR9YjB6d67BOZ7dUjFbMeGZnpIx9yiUfGcVGOzFaQjKDXgJSdQcRxKieqvQ6e4NC8W3a3a6BdJ5MM7g4SD4Dh6ij/9wAn98XjQzLR4wsnKfDrgX8QVE@WZ/rA5qjvWMeD3HETUu5bkSb4/j1/PD943t1KSJn1hqpgHzUXcxIysnVpGrHcnZcyOmW1uIYqDa/txyb/FPHuZRUfpdwE7h8hOlSX56zFxKtZF29SpT9BXp1tVRZRWR3FQRipVLHusgx@5eb2Bw "JavaScript (Node.js) – Try It Online")
Take input as a string of "J" / "K". Output a string with "0" and "1".
And `f=J=>J.replace(/./g,a=>J^(J=a>f)?i=i>5?'':0:++i/i,i=0)` is 54 bytes too.
---
# JavaScript (ES6), 44 bytes
```
s=>s.flatMap(a=>s^(s=a)?i=i>5&&[]:++i>0,i=0)
```
[Try it online!](https://tio.run/##dVTBbuMgFLz7K3yqQcnS50MvrXBPe@FpT3tMs6rldVqq1ETBiiqt9tuzYB6Y2FoSh9gz82Z4WHy0l9Z2Z30avw3md389yKuVjRWHYzv@aE@sdTe/mJUtf9ZSNw93d7v942ajG9hqCfw69nbsWtvbUpavhSpXoy5w/RAKhQpR3fBrAKjB8VX45HwahZoGYlazpuF0AVS5boKckEBfeAHeoDMc0Vt4Gt4iwTknYJOLohL@O3HBr8wvOVKW89QRREVXYCKFDtYxw2rG6JrIaubg0i/mxMjO9Eji6EdBVv4YH0ZJRsa5UYkcoyAFwawAOaeAiPOqkqnKKmSGobhvtu81UK/rxQxpD@oMgLB1NP/vgjilm4wP9cIvbjhZQa6H@EKQniKv/CGGo7qzLi7khluT81SKPCHPn@WL64cse2oJOUe/oCpexXjWn4wLezrqkVUvQ8XFpzsavkrZlF/u79i9s/uXn5v7N86finQiiIM5f28dxnZ62@@5bP4UF3dM7IQQej@V6HwJ9yPLCiunNQ4@sEuoP3hwM3DxYfTAKo93ZrDm2IujeWNGyn5rePGXP13/AQ "JavaScript (Node.js) – Try It Online")
Take input as an array of false (for "J") and true (for "K"). Output an array of false and true.
[Answer]
# [R](https://www.r-project.org/), ~~83~~ ~~76~~ 62 bytes
```
function(x)gsub('(1{6})0','\\1',Reduce(paste0,+!diff(c(0,x))))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjO9uDRJQ13DsNqsVtNAXUc9JsZQXScoNaU0OVWjILG4JNVAR1sxJTMtTSNZw0CnQhMI/qdplJakWYTke@aVaKh7qWvqmptocqEIemMT9PL28vb2wq7eCwKxagMDb29v7Bohsl54JEEm45WGADyGQGTBJkHV/AcA "R – Try It Online")
Takes input as `0`(`J`) and `1`(`K`).
Outputs string of `1`s and `0`s.
Change of approach after looking at [@Luis Mendo's answer](https://codegolf.stackexchange.com/a/229385/55372).
```
function(x) # function taking x as input
gsub( # replace all occurences of
'(1{6})0', # 6 ones and a zero
'\\1', # with just 6 ones (first capturing group)
Reduce(paste0, # in a following vector collapsed to string
+!diff(c(0,x)) # negated differences of x with 0 prepended
# converted from logical to numeric with unary +
# this would be the output without bit stuffing
))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~79~~ 76 bytes
-3 thanks to @ceilingcat
```
x;c;a(char*p){x=74;for(c=1;c*=*p==x,x=*p++;c=c>5?x=*p++,1:c+1)putchar(!!c);}
```
[Try it online!](https://tio.run/##dVLrasIwFP7fp8gKY23tMIGNwUq3/zmvIGwlq1OGtWiEgvjsLpdzaow1Wk6afrckRz3/KnU@D5Wqmkytml3R58ehfnuplttdpmpRqaIu@roeysHU2axStfp4/fQvpXhXM5H3B22p2cODyqvTed1pptu99npse9Al89N1lyfHhJnRZGZeuWm/M4Rlli66x/2iW3RpaRjm2ylJrNKmWXcZ0eYF081fu2d61TKTcNNo9u282qFvlW5/vgy5t47rzpT8iRVzx3SgVKQlS2WKzn6N2zW4XhOcc8E9GiSAjDk4HFX6X6SAw0m4AQCxiEOQigfJScw1yNpNw2LcfeAk2o3JDPbvuNyfCni8BB8nZlgCR4KIKh@FRPCB@zxY7z2cyvgS4LmI/Cg1WvGQz2lXyMfIN/6cwqHuhUcbucIKdHZS6MnD/EE@2j8Pso9Hgs7k51nu5G030sHH1TUrgMTHIwF7xl8w3fRNBbrLESwvGIj96PaB0AEfkEx@GOTGH2iRKAEYLu04gikKYBAIBNB5DAhw2dVoKgOFwNCL2xY@nf8B "C (gcc) – Try It Online") Takes input as `J` and `K`, outputs with bytes `0x00` and `0x01` for `0` and `1`.
For output as numeric `0` and `1`,
[Try it online!](https://tio.run/##dVLrasIwFP7vU2SFsbZWTMAxttLtf84rCFvJ6izDWjRCQXx2l8s5NUYXLSdNv1uSo2Y/Sp3PQ6nKOlXrepf32XGoXhblartLVSVKlVd5X1VDMZg6nZaqUu/PH/6lEG9qKrL@oC01XbzOHlRWns5tp5lu9torsu1BF8xP2y6bHCfMjDo189JN@50hrNJk2T3ul92ySwrDMN9Ok4lV2tRtlxJtnjNd/zZ7ptcNMxk3tWZfzqsZ@kbp5vvTkHvr2HamZE8snzumAyUiKVgiE3T2a9yuwfWa4JwL7tEgAWTMweGo0v8iBRxOwg0AiEUcglQ8SN7FXIOs3X1YjPsfeBftxt0M9u@43J8KeLwEHydmWAJHgogqH4VE8IH7PFj/eziV8SXAcxH5UWq04iGf066Qj5Fv/DmFQ90LjzZyhRXo7KTQk4f5g3y0fx5kH48EncnPs9zJ226kg4@ra1YAiY9HAvaMv2C66ZsKdJcjWF4wEPvR7QOhAz4gmfwwyI0/0CJRAjBc2nEEUxTAIBAIoPMYEOCyq9FUBgqBoRe3LXw6/wE "C (gcc) – Try It Online") for 78 bytes.
[Encoder](https://codegolf.stackexchange.com/a/229567/80050)
[Answer]
# [J](http://jsoftware.com/), 26 bytes
Takes in `JK` as `0 1`.
```
t#~0=_6|.(6$1)E.t=:2=/\0,]
```
[Try it online!](https://tio.run/##lVQ9T8QwDN37KyJAylXqFYfhhqJOCIaYiRVODOiuwMJyI@Kvl7aJm8ROOJGotdz6veePtJ/jRauPqu@UVo0C1U3XtlV3T48P4@nyB/rX3Xe72V2Z@r499d1Nf/0CzX6sq6Hvnrujtqg/2n11eHv/UpvN7VArjdYtdMui1bUPGJSeHLXtlFyNCUFYDIKIaaKetGSomWqY92xjUuu2AEC6IwWqg0NMumMNBxEiLh/aicraL8t0UkwJxWEcVcSF6SxoifuDwSGXpEOpxED3wAhsEvPciIDbZayI1l8uEn2HXNqUv7BIOa3BNsQg16MqkKIjPHow6flEhD7SQ4JEwRiavAZTKugTwYjAK68JIoaqVlEbMUSCjjwaBQ0C2CDMGR/k4CKbIiA@IMz/rwXhyTd5fhA@FN6HvIFx5/VBHOlUP@3y@fpBdA6YCmSZIfMrMIVPjdebTiunn1Ys@8fnD4W@m0zf0/MHTGd9Uo2/ "J – Try It Online")
```
t#~0=_6|.(6$1)E.t=:2=/\0,]
0,] prepend a J
2=/\ pair-wise equal
t=: store as t
(6$1)E. bitmask of places where 6 ones starts
_6|. shifted by 6 bits
0= negate
t#~ take only truthy bits from t
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes
```
1p-Ṫv¬ṅ\16*:0+$V
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=1p-%E1%B9%AAv%C2%AC%E1%B9%85%5C16*%3A0%2B%24V&inputs=%5B1%2C1%2C1%2C1%2C1%2C1%2C0%2C0%2C0%5D&header=&footer=)
```
1p # Prepend a 1
- # Differences - truthy if unchanged, falsy if changed
Ṫ # Get rid of last
v¬ # Vectorised not
ṅ # Joined
\16* # Six ones
: # Duplicate
0+ # Append a 0 to the first
$ # Swap
V # Replace
```
Takes the difference of the list with a 1 prepended and the list itself, NOTted, to get the values. Then spend the remaining 10 bytes on doing the bit stuffing.
[Answer]
# [PHP](https://php.net/) -F, 96 bytes
```
for($s=$r=$argn;$s[++$i]!='';)$r[$i]=+!abs($s[$i]-$s[$i-1]);echo str_replace(1111110,111111,$r);
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNFSKbVWKbFUSi9LzrFWKo7W1VTJjFW3V1a01VYqigWxbbcXEpGKgMhBHF0zpGsZqWqcmZ@QrFJcUxRelFuQkJqdqGIKBgQ6E1lEp0rT@/x8qaGDwL7@gJDM/r/i/rhsA "PHP – Try It Online")
Well, I.. tried.. to make it short.. hum!
takes a string of 0 (J) and 1 (K) as input
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
```
lambda s:''.join((`+(x==y)`for x,y in zip('J'+s,s))).replace('1'*6+'0','1'*6)
```
[Try it online!](https://tio.run/##TcYxDsIgFAbgq7D97wlpqIODSS8AV@hQ1BIxlRLoULw8Jnbxm75Ut@caz80PY1vc@/ZwolyB7rWGSDRJ2oeh8uTXLHZVRYjiExLBQBZVmLnLc1rcfSb0OF0kNNRv3FIOcSNPsOZgD8YasILW/R@twe0L "Python 2 – Try It Online")
-2 bytes thanks to @ovs
[Answer]
# [Red](http://www.red-lang.org), 79 bytes
```
func[x][p: s: 0 collect[foreach i x[s: any[all[s < 6 keep p = i s + 1]0]p: i]]]
```
[Try it online!](https://tio.run/##jZHBaoQwEIbveYoh16WQQNmCti9gbr0Oc5BsZENFRbOwfXo7Gd1WbQ/9lRz8v29GyBgu83u4IKmmmJtb5/FOOBQwFWDA920bfMKmH0PtrxDhjlzU3SfWbYsTvMIZPkIYYIA3bic4gSVD7EcimmMBj5HHUZ5Hifn08syWZ1z1/8BDTNcwgkdLaChbDyQBKl1p@JXSKu3@@m6Yd5Vz1d4qrTHGmmxVy6N31hqWJc5th5d2TbaXfquzLW3W1z5v0Md@D2yIb@BASGTXD7HDllrWyQ8Jll/B@VB872PsEvTQ8F0mmr8A "Red – Try It Online")
Takes input as a block of \$1\$s and \$0\$s, outputs a block of booleans.
Test suite on TIO uses two additional transformation functions that allow reading inputs from JK-strings as in task specification and convert output to numbers for nicer visualization.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
*-1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
0ìüQJƵPbD¨.:
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f4PCaw3sCvY5tDUhyObRCz@r/f0NDQwMDQyAEAkN0GgRBCqAYohIsBVJgCBEyMMBKQ5lIig0QagzR7YNYAVEPkUfoN4RqhtkHdQiG/YYwQZgWJMUQ9yP8AROAWmwIsxTJEygONDRE@ApuqQGSCUgWQgwHAA "05AB1E – Try It Online") Uses `0` for `J` and `1` for `K`.
```
0ìüQJƵPbD¨.: # full program
.: # replace all instances of...
ƵP # 126...
b # in binary...
.: # in...
J # joined...
ü # are all digits of each element in...
0 # literal...
ì # concatenated with...
# implicit input...
Q # equal...
.: # with...
ƵP # 126...
bD # in binary...
¨ # excluding the last digit
# implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
⪫⪪⭆θ⁼ι§⁺Jθκ⁺×1⁶0×1⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPI7ggJ7NEI7gEKJLum1igUaij4FpYmphTrJGpo@BY4pmXklqhEZBTWqyh5KWko1CoqaOQrakJJMFiIZm5qUAZQ6CMGVBMyUAJJIUiqqlp/f@/txcEeEOAl7fXf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
⭆ Map over characters and join
J Literal string `J`
⁺ Concatenated with
θ Input string
§ Indexed by
κ Current index
⁼ Equals
ι Current character
⪪ Split on
1 Literal string `1`
× Repeated
⁶ Literal `6`
⁺ Concatenated with
0 Literal string `0`
⪫ Join with
1 Literal string `1`
× Repeated
⁶ Literal `6`
Implicitly print
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Å3≈àE∩◄σ←π<δô╝ìà
```
[Run and debug it](https://staxlang.xyz/#p=8f33f78545ef11e51be33ceb93bc8d85&i=%5B0%5D%0A%5B1%5D%0A%5B0,+1,+0,+1,+1,+0,+0%5D%0A%5B1,+0,+1,+0,+1,+0,+1,+0%5D%0A%5B0,+0,+0,+0,+0,+0,+1,+1,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+0,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+1,+0,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+1,+1,+1,+1,+1,+1,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+1,+1,+1,+0,+1,+0,+0,+0,+0,+1,+0,+0%5D%0A%5B1,+1,+1,+0,+0,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+0,+1,+0,+1,+1,+1,+1,+0,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+1,+0,+1,+1,+0,+0,+0,+0,+0,+1,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+0,+0,+1,+0,+0,+1,+1,+1,+0,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+1,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+0,+1,+1,+1,+0,+1,+0,+0,+1,+0,+0,+0,+1,+0,+0,+1,+1,+0,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+1,+0,+1,+1,+1,+0,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+1,+1,+1,+0,+0,+1,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+1,+0,+1,+0,+0,+1,+1,+1,+1,+0,+0,+1,+0,+1,+1,+1,+0,+1,+0,+0,+0,+1,+1,+1,+0,+0,+1,+0,+1,+0,+1,+1,+1,+1,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+0,+1,+0,+1,+1,+1,+1,+1,+0,+0,+1,+1,+1,+0,+1,+1,+0,+1,+0,+0,+1,+1,+0,+1,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+1,+1,+1,+1,+0,+1,+1,+0,+0,+1,+1,+0,+0,+0,+0,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+1,+1,+1,+0,+1,+0,+1,+1,+1,+0,+1,+0,+0,+0,+1,+1,+0,+0,+1,+0,+1,+1%5D%0A&m=2)
takes in a string/array of bytes `0x00` for J and `0x01` for K.
Outputs a string, same as the given testcases.
Sadly, [this 14 byte program](https://staxlang.xyz/#c=Z%2B2B%7BE%3Dm1%5D6*c0%2BsRJ&i=%5B0%5D%0A%5B1%5D%0A%5B0,+1,+0,+1,+1,+0,+0%5D%0A%5B1,+0,+1,+0,+1,+0,+1,+0%5D%0A%5B0,+0,+0,+0,+0,+0,+1,+1,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+0,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+1,+0,+1%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+1,+1,+1,+1,+1,+1,+1,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+0,+0,+0,+0,+0,+1,+0%5D%0A%5B1,+0,+0,+0,+1,+1,+1,+0,+1,+0,+0,+0,+0,+1,+0,+0%5D%0A%5B1,+1,+1,+0,+0,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+0,+1,+0,+1,+1,+1,+1,+0,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+1,+0,+1,+1,+0,+0,+0,+0,+0,+1,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+0,+0,+1,+0,+0,+1,+1,+1,+0,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+1,+1,+0,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+0,+0,+1,+1,+1,+0,+1,+0,+0,+1,+0,+0,+0,+1,+0,+0,+1,+1,+0,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+1,+0,+1,+1,+1,+0,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+1,+1,+1,+0,+0,+1,+0,+0,+1,+1,+1,+1,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+0,+0,+1,+0,+1,+0,+0,+1,+1,+1,+1,+0,+0,+1,+0,+1,+1,+1,+0,+1,+0,+0,+0,+1,+1,+1,+0,+0,+1,+0,+1,+0,+1,+1,+1,+1,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+0,+1,+0,+1,+1,+1,+1,+1,+0,+0,+1,+1,+1,+0,+1,+1,+0,+1,+0,+0,+1,+1,+0,+1,+0,+0,+1,+1,+1,+1,+0,+0,+0,+0,+1,+0,+0,+0,+1,+1,+0,+1,+0,+0,+0,+0,+1,+1,+1,+1,+0,+1,+1,+1,+1,+0,+1,+1,+0,+0,+1,+1,+0,+0,+0,+0,+1,+1,+1,+0,+1,+1,+1,+1,+0,+0,+1,+1,+1,+0,+1,+0,+1,+1,+1,+0,+1,+0,+0,+0,+1,+1,+0,+0,+1,+0,+1,+1%5D%0A&m=2) doesn't work since stax auto-replaces null bytes with spaces.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 25 bytes
```
*|+(126=2/')_7':(&6),0=':
```
[Try it online!](https://ngn.bitbucket.io/k#eJyVU8tOxDAMvPcrohxoC5Vw9rBIlVZwznwEtz3tJyC+nTaO87BbEIlay8mMx3br+/r89TKFy/V2eR3nz7dxnZ6u80K3cR2Gx+oj/PswLWH+vrvHx+Kj3zwSD34IjtLebdiPN0oE4gYk1+10ich7J3abqWkBYHK9rnRGRA0wkF3Fgg5gJ7jfGGl1Sci7xqHSDzAngrNKLOGQ4ugYNqbRaGzPqBVZ/7+WjGdvjuOT8XW2unt9VeTO9Mnp7vf6fZf/rp+c7hwpFaunv8h53NDFbOvr69T6fcW2f/r7tz21eRzlcFxfo8V/8T7T8hNrm0YeiPlhJPIY8sDI5BgLmYsCjhUDrSeTBEE3fGSy6OVEjD7kUCgNGHW8C1hSQU4ETYCsXBIEalVFNDYRGkEO7n8ANZIiBQ==)
Takes `J` as `0`, and `K` as `1`. Returns a list of `0`s and `1`s.
* `0=':` run an equals-each-prior, seeded with `0` on the (implicit) input, handling the non-return-to-zero part
* `7':(&6),` prepend 6 `0`s to the input, then slice into length-7 sliding windows. the first 6 slices will contain some dummy `0`s
* `(126=2/')_` drop chunks of `1 1 1 1 1 1 0`, i.e. where the last value in the chunk is a dummy `0` inserted for bit stuffing purposes
* `*|+` return the last value of each chunk (saves a byte over `*'|'`)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
n=>n.replace(/./g,(e,i)=>1-e^n[i-1]).replace(/1{6}0/g,111111)
```
[Try it online!](https://tio.run/##dVTBboMwDL3zFbkVtLY4l10m@gHxJzCmoi6rOjFALdpl2rczktjBgGZAUfKe/V4c4LP@rh@X@60fDm33bsePYmyLU3u8276pLzbNj/l1n9r9LStO@mDf2vJ20FU24/rn@RcmjvaRjZeufQxqUIU6G7UJneB2ERKDBtEs@BoANEx8Ey7Jp0iMD0RRU1NMeQE0Ms9DUyKBrvAKXKAzzOgS9uEkIiw5AfMqhkq423PB7cxtmSnr0XcE0dATmEimgzR72IzIqpFsZg6u9dgnMlvkIyWzHhnZ6CMvcoog49yoSGYrSEZQFCDlaBBx3lUUNaKCEAzFXbNdr4F6rVcjxDPQAoBwdDT@9wAPcSL4oFd6fOAkBTIf@IWgfLK80Qc2R3XnPN7IgqtJ2ZciTZD@hT/ePwjvsSWkzHoh65yo@dM302cPmVxB9yNwK4@@uQ3p7rXdudlX3ae2UcVJ2YagXD3lWfaSuN9F19hj013TQRBL25S62quPaV5ClVUTefwD "JavaScript (Node.js) – Try It Online")
I have tried to make sure it outputs numbers.
-10 bytes by pxeger
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Ż⁼Ɲ0ȯ1בʋ7Ƒ?ɼƇ
```
[Try it online!](https://tio.run/##ZVAxDoIwFN05C4NMju7/ncAYRxfDBdjQhcFJFxnkBkZj4mJgIxD1FvQitbT9pUKb5r/@vP/ea7ebOE6kbEqxq9pi9r5H9Vmk@fcwb4@LT9VmsiufIr0QRFqEq1kYrRPxuNWZ2F@bU/fKVV1KSQECAgGkEJkdkF4AVMtAYtQTBvx/0Yu5BuoB1ej1@T6u2h4gewwT1szIsv6kgi0cmQYOxn4cCsz25mGH2c8GmfiDmzzikTF8giNzFNgg8ASsswsIDK9ypuQpeIZG/Ac "Jelly – Try It Online")
Takes `J` and `K` as `0` and `1`.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
(.)(?<=(\1.|^J)?)
$#2
1{6}0
6$*
```
[Try it online!](https://tio.run/##ZZCxDsIwDER3/wZFShgqytAJ1BHJ9wsIwcDAwoDYgG8PbWwnpk1V5Wyd/a593l73xzWtw/GSQhvDsD@EU9d@zhyHSM1qR927/26pbzYpMYEYDPCoWB7ifACMLZFsajJU/V/k472mpZ3rsTGxrJ7fOQrA@ooTuksQxlrcMEQxc/VgzrNQMLebhw4bT4Ms@LCmjTgz6g8pZosCDQK3QMklIFC/qkDZbXBAWf4D "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(.)(?<=(\1.|^J)?)
```
For each letter, look behind for a possible duplicate or a leading `J`.
```
$#2
```
If it was then replace it with a `1` otherwise replace it with a `0`.
```
1{6}0
6$*
```
Remove the `0` that appears after a run of six `1`s.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
ŻI¬“~?‘B¤œṣjƭƒ
```
[Try it online!](https://tio.run/##y0rNyan8///obs9Dax41zKmzf9Qww@nQkqOTH@5cnHVs7bFJ//3jzU0Ot///7@0FAd4Q4OXtBQA "Jelly – Try It Online")
A monadic link taking the argument as a vector of 0 (=J) and 1 (=K) and returning a vector of 0 and 1.
] |
[Question]
[
Figuring out whether a given number is prime, while not very complicated, is kind of hard. But making a guess doesn't need to be.
Seeing whether a number is a multiple of 2 or 5 is easy - you can just look at the last digit. Multiples of 3 isn't much harder, just add up the digits and see if you end up with a multiple of 3. Multiples of 11 are also easy enough, at least as long as they're fairly small. Any other number might not *be* prime, but at least they look like they *might* be prime. Or at least, that's how it works in base ten. As a person who frequently uses base ten, you can probably also identify the single-digit primes, and know that 11 is a prime as well.
We can generalize this to other bases. In some base \$b \ge 2\$, you can find fairly simple divisibility rules for any factor of \$b, b-1 \text{ or }b+1\$. You also presumably know all the prime numbers up to and including \$b+1\$.
But in any base, you eventually start running into numbers that *look* prime, but *aren't*. And I want to know when that happens. I know that in base 10, the first such number is 49 (not divisible by 2, 3, 5 or 11, but also not prime), in base 12 it's 25 (not divisible by 2, 3, 11 or 13), and in base 27, it's 55 (not divisible by 2, 3, 7 or 13, and unlike 25 it's also big enough to require two digits!). But for other bases? That's where you come in!
## Rules
Your task is to write a program or function which takes as input some integer \$b\ge2\$ and outputs the first integer which, when written in base \$b\$ *looks* like it might be prime, but *isn't*. That is to say, the smallest integer that
* Is a composite number and
* Is greater than \$b\$ and
* Is coprime with (does not share any prime factors with) \$b-1\$, \$b\$ and \$b+1\$
This is related to [OEIS A090092](https://oeis.org/A090092), but starts to diverge at \$b=27\$
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so save those bytes!
## Test cases
```
Base -> Smallest pseudo-prime
2 -> 25
5 -> 49
6 -> 121
10 -> 49
12 -> 25
27 -> 55
32 -> 35
34 -> 169
37 -> 49
87 -> 91
88 -> 91
89 -> 91
121 -> 133
123 -> 125
209 -> 289
```
[Answer]
# [Haskell](https://www.haskell.org/), 53 bytes
```
f b=[x|x<-[b..],k<-[2..x-1],mod x k+gcd(b^3-b)x<2]!!0
```
[Try it online!](https://tio.run/##DYxLDoIwFEW38phBvG3aVxVIwB24gloTKqKEj0QddODea5N7kpMzuM/uM93nOcaBfGvDLzTCeikdpiQsZRDaYXn1FGjaPW597q9G@CI07LJMxaUbV2pp6bYz5RcvTtt7XL@5R7orCrKMA47QCprBJQzD7GFKVGkVqjp1nTBgVbv4Bw "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), ~~91 83 79~~ 76 bytes
```
f=(b,n=b,k=n)=>(g=d=>k<2?d<n:k%d?g(d+1):b*~-b*~b%d&&g(d,k/=d))(2)?n:f(b,n+1)
```
[Try it online!](https://tio.run/##ddBLDoMgEAbgfU/hRgOtVgEfYETPIqKm1UBTmy57dWsj3UhYsOFjZv7h3r7bpXveHq9Iadmv68CBCBUX4cQV5DUYueT1VOFGVqqcfNmMQF4QLMX5E21H@DIItqtwirmEEGDYqHL4tdgerZ1Wi57766xHMADPwxB6cezh7HSUbJeUWZLvgjA6EkpcRcg5CBe7ZJYQU0NsSU2E3BpEClcEaoRZsSl1CnPItryJQIhF5P9Bx@A4Mf0wZesX "JavaScript (Node.js) – Try It Online")
### How?
Given the base \$b\$, we look for the smallest integer \$n\ge b\$ with a prime divisor \$d\$ which is neither \$n\$ itself nor a divisor of \$b-1\$, \$b\$ or \$b+1\$.
### Commented
```
f = ( // f is a recursive function taking:
b, // b = input base
n = b, // n = candidate number, starting at b
k = n // k = copy of n
) => ( //
g = d => // g is a recursive function taking a divisor d
k < 2 ? // if k = 1:
d < n // successful if d is smaller than n
: // else:
k % d ? // if d is not a divisor of k:
g(d + 1) // do recursive calls with d + 1 until it is
: // else:
b * ~-b * ~b // if b(b - 1)(b + 1) ...
% d && // ... is not divisible by d:
g(d, k /= d) // do a recursive call with k divided by d
)(2) // initial call to g with d = 2
? // if successful:
n // return n
: // else:
f(b, n + 1) // try again with n + 1
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~21~~ ~~20~~ 18 bytes
```
1⟨+:ṗ!¤@3*@⁻S&⟩#e+
```
[Try it online!](https://tio.run/##ASYA2f9nYWlh//8x4p@oKzrhuZchwqRAMypA4oG7Uybin6kjZSv//zIwOQ "Gaia – Try It Online")
-2 thanks to Arnauld!
```
1⟨ ⟩# % Find the first 1 positive integers n where:
+: % b + n
ṗ! % is not prime
S& % and is coprime with
¤@3*@⁻ % b^3 - b, the product of b-1,b,b+1
e+ % and return b + n
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
ḟȯ≥3Λ`%-¹^3¹p
```
[Try it online!](https://tio.run/##AR8A4P9odXNr///huJ/Ir@KJpTPOm2AlLcK5XjPCuXD///82 "Husk – Try It Online")
## Explanation
```
ḟȯ≥3Λ`%-¹^3¹p Input is a number b.
ḟ Find first number ≥b that satisfies:
ȯ Composition of 3 functions:
Argument is a number n.
p 1) Prime factors of n (with repetitions).
Λ 2) All of them satisfy this:
¹ b
^3 cubed
-¹ minus b
`% modulo the prime (is nonzero).
Λ returns either 0 or length+1.
≥3 3) Is at least 3.
This means n has at least 2 prime factors and none of them divide b^3-b = b*(b+1)*(b-1).
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
’r‘Ɗg’;Ẓ}E
ç@1#
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8yiRw0zjnWlA1nWD3dNqnXlOrzcwVD5////RgaWAA "Jelly – Try It Online")
## How it works
```
’r‘Ɗg’;Ẓ}E - Helper link. Takes b on the left and n on the right
Ɗ - Run the previous 3 commands over b:
’ - Yield b-1
‘ - Yield b+1
r - Yield [b-1, b, b+1]
g - Take the GCD between each of these and n
’ - Decrement, yielding 0 for co-primes
Ẓ} - Is n prime?
; - Concatenate to the list of decremented GCDs
E - Are they all equal i.e. do they all equal 0?
ç@1# - Main link. Takes b on the left
1# - Count up from b and return the first integer, n, which is true when:
ç@ - run through the helper link with b on the left and n on the right
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~97~~ ~~96~~ 91 bytes
```
b=>{def g(i:Int):Int=if(BigInt(b*b*b-b).gcd(i)>1|2.to(i-1).forall(i%_>0))g(i+1)else i
g(b)}
```
[Try it online!](https://tio.run/##Xc7NCsIwDADg@56iFyFRNtbNf9hAbx58Bmm3dkRKN1wRQX32OfEgGYUmX5M27Svl1NDqq6mCOCvywjyC8XUvDl33jO7KCbsXJx9EUf7CoIvyWRsrGqD9eILfrSALR2rGDPR8XLHGpKlqICzlK0tCCxRLTGx7U84BzS5lijg@sJBoXG8ERQ1ofA/djXxwHixkiNFfK6Y1k0w5@c1sw5jzar7k5M3bCbecu8lcOXHOP5J@@6P38AE "Scala – Try It Online")
* Thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) for -1!
* Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for -5!
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~18~~ 17 bytes
```
ḟ(EM⌋m+¹ṡ1)fo¬ṗ↓N
```
[Try it online!](https://tio.run/##AScA2P9odXNr///huJ8oRU3ijIttK8K54bmhMSlmb8Ks4bmX4oaTTv///zI "Husk – Try It Online") or [Verify all test cases](https://tio.run/##yygtzv6f@6ip8f/DHfM1XH0f9XTnah/a@XDnQkPNtPxDax7unP6obbLf////o410THXMdAwNdAyNdIzMdYyNdIxNdIzNdSyAyELHwhIobgjExjpGBpaxAA "Husk – Try It Online")
-1 byte after rearranging stuff.
## Explanation
```
ḟ(EM⌋m+¹ṡ1)fo¬ṗ↓N
↓N drop first b elements from natural numbers.
fo¬ṗ filter out primes
ḟ get first element which satisfies the following:
( ) co-prime check
ṡ1 range -1..1
m+¹ add each to b
M⌋ GCD of each and b
E are all equal?
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 22 16 bytes
*-6 thanks to Zgarb*
```
^₃;?-ḋF&<.ḋṀ;Fx×
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3wP@5RU7O1ve7DHd1uajZ6QOrhzgZrt4rD0///jzbSMdUx0zE00DE00jEy1zE20jE20TE217EAIgsdC0uguCEQG@sYGVjGAgA "Brachylog – Try It Online")
* `^₃;?-ḋF`: all the prime factors of `B^3-B`
* `&<.`: the output `N` is greater than `B`
* `ḋṀ`: `N`'s prime factors are at least 2
* `;Fx×`: and the product of the prime factors without the ones in `F` unifies with the output `N`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
’r‘²Pg€ƊỤẒÞḊḢ
```
A monadic Link accepting an integer, \$b\$, which yields the first integer that "looks prime but isn't".
**[Try it online!](https://tio.run/##ASoA1f9qZWxsef//4oCZcuKAmMKyUGfigqzGiuG7pOG6ksOe4biK4bii////MTA "Jelly – Try It Online")** (Too inefficient for even quite small inputs due to golfing.)
### How?
This is really just a golfed version of this 15 byter which is not so ridiculously inefficient: `’r‘ṀÆn²g€ƲỤẒÞḊḢ`.
```
’r‘²Pg€ƊỤẒÞḊḢ - Link: b
’ - decrement -> b-1
‘ - increment -> b+1
r - inclusive range -> [b-1, b, b+1]
Ɗ - last three links as a monad:
² - square -> [(b-1)², b², (b+1)²]
P - product -> (b(b-1)(b+1))²
(this is always greater than ṀÆn²
- the square of the next prime above b+1
and saves us two precious bytes)
€ - for each (v in [1..(b(b-1)(b+1))²]:
g - greatest-common-divisor (between v and each of [b-1, b, b+1])
Ụ - grade-up -> 1-based indices sorted by the values at those positions
Þ - sort by:
Ẓ - is prime?
Ḋ - dequeue (since 1 gets GCDs [1,1,1] so it also looks prime and isn't prime)
Ḣ - head -> the smallest number that looks prime and isn't prime
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~115~~ ~~98~~ 89 bytes
Saved a whopping 17 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
f=lambda b,m=9:(m>b)*(perm(m-1)**2%m!=1)*m*(gcd(b**3-b,m)<2)or f(b,m+1)
from math import*
```
[Try it online!](https://tio.run/##NU7LboQwDLzzFe6hIkmNtElggVXZH2l74BF2kRqIQiq1RXw7NbS1bHnG9sjjvsJ9GnXh/Lb11Xttm66GBm1VXpi9NlwwZ7xlNpFcCPVoHyoCVrBb27FGCJ3QLX9WfPLQM8JPkke9nyzYOtxhsG7yQWzBzGGGCpjCDM8oTygVqhy1Qp2izrGgLLAoaS6pNKpTySPz6UwbTHcoM0x/19SIZBnqDOW53Hkp/1JqTTcZqoLkftfFrx8qT9sYDiB1TP7IbEADwwjfg2OHOfz/xS8RUOxuexb4QZwfxsD6eAkrJFdY5hUW/2Kqan5bY779AA "Python 3.8 (pre-release) – Try It Online")
### Explanation
```
f=lambda b # recursive function taking b
,m=9 # init possible answer to largest single
# digit (of which none of them can be
# the solution because they're either
# prime or divisible by 2 or 3)
: # the start of a chain of logical
# tests, if any of them are False the
# chain will be 0 invoking recursion
(m>b)* # first one makes sure m is >= b + 1
(perm(m-1)**2%m!=1)* # second tests that m isn't prime using
# one of xnor's tricks
*(math.gcd(b**3-b,m)<2) # third tests that m is coprime with
# (b - 1)*b*(b + 1) == b**3 - b
*m # if all this is True return m
or f(b,m+1) # otherwise try m + 1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@Jõ+U ejX «Xj}aU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QEr1K1UgZWpYIKtYan1hVQ&input=MjA5) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QEr1K1UgZWpYIKtYan1hVQ&footer=V2dWIHMg%2bTMgKyIgPSAiK1VzIPkz&input=WzIgNSA2IDEwIDEyIDI3IDMyIDM0IDM3IDg3IDg4IDg5IDEyMSAxMjMgMjA5XS1tUg)
```
@Jõ+U ejX «Xj}aU :Implicit input of integer U
@ :Function taking an integer X as argument
J : -1
õ : Range [-1,1]
+U : Add U to each
e : All
jX : Co-prime with X
« : Logical AND with the boolean negation of
Xj : Is X prime?
} :End function
aU :Starting from U, get the first X that returns true
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 58 bytes
```
.+
$*11¶$&$*
+`^(11+)\1*1?1?¶\1+$|¶(?!(11+)\2+$)
$&1
r`1\G
```
[Try it online!](https://tio.run/##JcixCcMwFEXR/m0R@DayBMbvK4nlSqWXEEEpUqRJYVJ6Lg2gxRRB4N7mHK/v@/Nsg9lzmx3EkrXIKBYuPwzppkTLyFhLopOzFhMvf1cnE2Qkjsy0t6a44Q4uoEJXeIW/wq8IvYCwdWffQ5ftBw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*11¶$&$*
```
Convert `b` to unary, and make a copy as `b+1`, which will be used for GCD testing.
```
+`^(11+)\1*1?1?¶\1+$|¶(?!(11+)\2+$)
$&1
```
Keep incrementing the result while it's prime or shares a common factor with either `b+1`, `b` or `b-1`.
```
r`1\G
```
Convert the result back to decimal.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
öα•○¼¿¼╓♫├û•
```
[Run and debug it](https://staxlang.xyz/#p=94e00709aca8acd60ec39607&i=2%0A5%0A6%0A10%0A12%0A27%0A32%0A34%0A37%0A87%0A88%0A89%0A121%0A123%0A209&a=1&m=2)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~87~~ ~~86~~ 84 bytes
Saved a byte thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
i;q;p;m;f(b){for(p=m=b;p|!q;++m)for(q=p=i=1;++i<m;)q=m%i<1?p=0,q&&b*~-b*~b%i:q;--m;}
```
[Try it online!](https://tio.run/##bVFdb4IwFH33V3QkGKqXjFKrsNrtYdmvUB8EYWuyIl9ZyBz76@wiqFuypjfl3J5z2h5i9zWOu07LQubSyNSJ6Ck9lk6ujIpk/nVXyPnc0L5VqFxpxRDrtZG0UMbWa/aUKw@K6TSafbtYka0fCum6Rradzmpi9jpz6OQ0ITj6Rp1UdbXZEUVOPghYAvOA@eCvgPvAF8BXEOAMIAixz7A4@F7YyqtD0uRJXCeH0UTAYmDigkAI4ALYMuxxyMbJOEeOAD@4OMVv@3JGysHE2jYv/rYJn7GEBeQ35taowAyI019AZ4ekQZknx881qfRnckyd8@Po/YhmA5QEE@t5lAwxXB5CIjQZ8jjv7@R1Oy@RkDqWfSDuI8EbRVT@0ZZJ/bF/R33/x/7V2dU2Q@FAxHVzkahbgsOxu9GgnbTdDw "C (gcc) – Try It Online")
Port of my [Python answer](https://codegolf.stackexchange.com/a/213463/9481).
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
f=lambda b,k=1,p=1:(k<b)|p%k|math.gcd(b**3-b,k)-1and f(b,k+1,p*k)or k
import math
```
[Try it online!](https://tio.run/##FY3PDoMgDIfP8yl6WQKsLiL7o2Y@ybIDjDgJE4nhssR3Z@Xwtb@2X9L4S/MaVM7T@NWLsRoM@lFiHOXA/MPwPR79vug0nz9vy4wQqiaD11IHCxOjfCJbeL5u4Cu3xHVLUPw80caAC/BsEa4INwTZEDS1dwRFXV0Iyl2hI/pyl6Uospr@NVSHuLmQGL3iPP8B "Python 3 – Try It Online")
---
Uses [xnor's corollary to Wilson's theorem](https://codegolf.stackexchange.com/a/27022/48931). I still find it unbelievable that the shortest way to test for coprimality is `import math;math.gcd(x,y)<2`, but I couldn't find a shorter way.
-2 due to xnor, since we only need the regular factorial here (instead of factorial squared). The special case `k=4` is taken care of by the other conditions.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞+.ΔαD3mαy¿yp+
```
Inspired by [*@Giuseppe*'s Gaia answer](https://codegolf.stackexchange.com/a/213469/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8bb1zU85tdDHOPbex8tD@ygLt//@NAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8fdczT1js35dC6cxtdjHPPbaw8tL@yQPt/rc7/aCMdUx0zHUMDHUMjHSNzHWMjHWMTHWNzHQsgstCxsASKGwKxsY6RgWUsAA).
**Explanation:**
```
∞ # Push an infinite positive list: [1,2,3,...]
+ # Add the (implicit) input `n` to each: [n+1,n+2,n+3,...]
.Δ # Find the first `n+b` which is truthy for:
α # Take the absolute difference with the (implicit) input: [1,2,3,...]
D # Duplicate this `b`
3m # Cube it: b³
α # Take the absolute difference with the `b` we've duplicated: |b-b³|
y¿ # Get the greatest common divisor with the current `b+n`: gcd(|b-b³|,b+n)
yp # Check whether `b+n` is a prime number (1 if prime; 0 if not)
+ # Add them together: gcd(|b-b³|,b+n)+isPrime(b+n)
# (NOTE: only 1 is truthy in 05AB1E)
# (after which the result is output implicitly as result)
```
[Answer]
# [R](https://www.r-project.org/), ~~100~~ ~~81~~ ~~73~~ 72 bytes
*Edit1: -19 bytes by abandoning the nice all-in-one check-for-primality-and-shared-divisors, and instead using clunkier but shorter separate checks*
*Edit2: -8 bytes, and then -1 more byte thanks to Giuseppe*
```
f=function(b,n=b)`if`(sum(a<-!n%%2:n)>1&all(!a|(b^3-b)%%2:n),n,f(b,n+1))
```
[Try it online!](https://tio.run/##hdDLCoMwEAXQfb9CKZaEKpjER1Kqn1IfrQFBoxjd9d@tpaYrh2zDmTs3M626r7qu0XMx6mZ5DcU4tX2TrTKTi3rO7aBQ7ausxmUrS6SXHlX3wFWeR28K5@SyDSO3eqP6wYIa/5595cvv1JVgfJyPKHbOTpA7ND4dg3gHkQBAsgNCCSBIaMsg1ho03UUMCWYyGCgiUzWBirDUVpUbIaDvcm4Vwia2Y5qujIGG/U8Pni00qygX6wc "R – Try It Online")
Sadly, although checking for primality by counting divisors and checking for **co**-primality by counting **shared** divisors could be elegantly combined, the ugly code below is actually (quite a bit) shorter...
Thanks to Giuseppe for ruthlessly pruning all the unneccessary variables, parentheses, square-brackets and so on...
**How?** (code before golfing by Giuseppe)
```
f=function(b, # f is recursive function taking argument b (=base)
n=b, # n is number to test for pseudo-primeness; start at b
a=!n%%2:n, # a is zero-values of n MOD 2..n = divisors (excluding 1)
c=!(b^3-b)%%2:n # c is zero-values of (b-1).b.(b+1) MOD 2..n = divisors of b-1, b or b+1
)
`if`( # Now, check whether:
(sum(a)>1) # a is not prime (if it has >1 divisor including itself)
&!sum(c[a]), # and it has no shared divisors with b-1, b or b+1
n, # If both are Ok, then n is a pseudo-prime: return it
f(b,n+1) # otherwise, do recursive call with n+1
)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
Nθ≔X²⁻Xθ³θηW∨﹪Π…¹θθ﹪÷Xηθ⊖η⊖X²θ≦⊕θIθ
```
[Try it online!](https://tio.run/##XU@7DoMwDNz5ioyORIfSoQNTVRYGWtQ/SENEIgWHvODz01SNGGrJtnx3Op25ZI4bplPqcY3hEZe3cGBpW928VzPCaPYMNDUZFEZfTluTC62JpXnIrN2l0oLA08FgpqgNjC5vHuDFcBZwLlKbuwh6DJ3a1CSKo/yxneBOLAKDmEDSP@CIks1ykYGtJWSPh@rLttXoFAa4Mx/yL7RNqbmm06Y/ "Charcoal – Try It Online") Link is to verbose version of code. Uses @xnor's formulas (see @Sisyphus's answer), so slow for large inputs (seems to be OK up to \$ b = 27 \$ at least). Explanation:
```
Nθ
```
Input \$ n \$, which is initially equal to \$ b \$.
```
≔X²⁻Xθ³θη
```
Calculate \$ 2 ^ { b (b - 1) (b + 1) } \$ which is used in @xnor's GCD calculation.
```
W∨
```
While either...
```
﹪Π…¹θθ
```
... \$ n \$ does not divide \$ (n - 1)! \$, meaning that \$ n \$ is 4 or prime, or...
```
﹪÷Xηθ⊖η⊖X²θ
```
... \$ 2 ^ n - 1 \$ does not divide \$ \left \lfloor \frac { 2 ^ { n b (b - 1) (b + 1) } } { 2 ^ { b (b - 1) (b + 1) } - 1 } \right \rfloor \$, meaning that \$ n \$ is not coprime to all of \$ b - 1 \$, \$ b \$ and \$ b + 1 \$, ...
```
≦⊕θ
```
... increment \$ n \$.
```
Iθ
```
Output the final value of \$ n \$.
Much faster 38-byte version which performs separate coprimaility testing on \$ b - 1 \$, \$ b \$ and \$ b + 1 \$:
```
Nθ≔E³X²⊖⁺θιηW∨﹪Π…¹θθ⊙η﹪÷Xκθ⊖κ⊖X²θ≦⊕θIθ
```
[Try it online!](https://tio.run/##XY/PCoMwDMbve4oeU@hgc6fhSebFg5vsDbpatFhb@0dlT9/VKTIWCCHJL3xfWEst01SGUKhh9Pexf3ELBqeHzDnRKCjpABeCKj3HeUJQzpnlPVee11DJ0YEhSOAYBLXxam6F5AgeFkpdj1JDZWNlHp5UNRzOBJkFNTEz9YaWoI0rlM/FJGoOq1S3Qr9y3V@/ezL4Gyh63VwXaseWdXqorFAebtT5@BxOQ0hO13Cc5Ac "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~145~~ ~~143~~ 137 bytes
```
from math import*
p=lambda b,h=2,c=inf:h>c and c or p(b,h+1,([h*i for i in range(2,h+1)if 2>gcd(h*i,b**3-b)and h*i<c and b<h*i]or[c])[0])
```
[Try it online!](https://tio.run/##XZDLbsMgEEXX9VeMvAKXVgbysKM4P@Kiyq8EpBgjh0iNony7O8RtWmVxYebM1UWDu3g9WDlNpnfD6KGvvI5ccaz6uq2gZroQrCnSjd41UNkWGhhGcAQHr5yRUicG9kgMGAtjZQ8dEWFEzR7ELoS9H5qWoI3VSSLfahpCsN2Se5JOEn1H9RahGsayUbRMFZ2MdWd/ggJKwWDJYMWApyjsxJqBxFsuUFhnQRkqD3MeDomuNFdR9@W6xnft53D2jzxMW/xaQxHAEiVRfJXPMOd/4lIGO45FhqGnS18Px3tW/HEWa57FDOZqEasoevqQY2fJvA2lm@jFjcZ6so@vMyuNum3g6sijpTe4/jxR/sdQFPC8D3J1i@n0DQ "Python 3 – Try It Online")
* -2 bytes by reformatting the condition in the list comprehension and removing an unnecessary space.
* -6 bytes from removing a special case when `c` is `0` by making it default to `math.inf` instead
Wanted to test how a solution that doesn't involve prime checking might fare, just out of curiosity. Worse than the competition, it seems. Oh well, at least I had fun.
Works by generating all composite numbers. On each pass, we generate some numbers that are definitely composite, then update our best guess (which we'll call \$x\$) to be the smallest number we find that's between \$b\$ and \$x\$ and also coprime with \$b^3 - b\$ - if we didn't end up generating a number like that, we keep our existing \$x\$. Eventually we reach a point where we know we'll no longer generate any numbers that are below our current \$x\$, which means \$x\$ must be the correct answer.
## Ungolfed
```
from math import gcd, inf
def pseudoprime(base, high=2, candidate=inf):
if high > candidate:
# We can no longer find anything that's small enough to care about
return candidate
else:
valid_multiples = [high * i for i in range(2, high+1) if # Generate all multiples of "high", then filter them
base < high * i and # Exclude single-digit numbers
math.gcd(high * i, base ** 3 - base) < 2 and # Check for coprimality
high * i < candidate # Make sure it's not bigger than our best guess, assuming we've found one
]
if valid_multiples:
return pseudoprime(base, high + 1, valid_multiples[0])
else:
return pseudoprime(base, high + 1, candidate)
```
[Answer]
# Java 8, ~~106~~ ~~105~~ ~~104~~ 100 bytes
```
n->{for(int b=0,p,g,i;;){for(g=p=++n;n%--p>0;);for(i=++b*b*b-b;i>0;)i=g%(g=i);if(p>1&g<2)return n;}}
```
-1 byte thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##PZDNboMwEITveYpVpFS4LIiftiFx4dJzc8kxzcEQg5ySBYFJVSGenRqSVF6vtJ9GO2OfxVU459P3mJWibeFTKOoXAIq0bHKRSdhN4wwgs6ZOjBsyLExrtdAqgx0QxDCSk/R51cyiNPawxgIV52yGRVzHtk2cVo5TJx5nfJYalj6b46RcTVTFxcpoFeMqt@rEfyreA9ZI3TUExIdh5JNv3aWl8b3bXyt1gosJbu11o6g4HEGwW@pHHC1b/SFaCVsg@TM95nDsA3zFN/Q99AMM1hgGGL5guMbIVITRxnDf3BADbzOweR/A/rfV8uJWnXZrY6ZLsh7L7eX2Sy9tcrN/xO5/NYx/)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
for(int b=0, // Start integer `b` at 0
p, // Temp-integer to check for primes
g,i; // Temp-integers to check for the gcd
;){ // Loop indefinitely:
for(g=p=++n; // Increase n by 1 first with `++n`
// And then set both g and p to this new n
n%--p>0;); // Decrease p by 1 before every iteration with `--p`
// and continue looping as long as n is NOT divisible by p
for(i=++b*b*b-b; // Then increase b by 1 first with `++b`
// And set i to b³-b
i>0;) // Loop as long as i is still positive:
i=g%(g=i); // First set g to i
// And then set i to old_g modulo-new_g
if(p>1 // If `p` is larger than 1 (this means it's NOT a prime)
&g<2) // and the greatest common divisor is 1:
return n;}} // Return the modified n as result
```
] |
[Question]
[
I was messing around with infinite resistor networks (long story) when I came across the following interesting recursive pattern:
```
|-||
|---
```
Each instance of this pattern is twice as wide as it is tall. To go from one level of the pattern to the next, you break up this rectangle into two sub-blocks (each of which is a NxN square):
```
AB =
|-||
|---
so A =
|-
|-
and B =
||
--
```
These halves are then duplicated and rearranged according to the following pattern:
```
ABAA
ABBB
giving
|-|||-|-
|---|-|-
|-||||||
|-------
```
**Challenge**
Write a program/function which, given a number `N`, outputs the `N`th iteration of this recursive design. This is golf.
I/O format is relatively lenient: you may return a single string, a list of strings, a 2D array of characters, etc. Arbitrary trailing whitespace is allowed. You may also use either 0 or 1 indexing.
**Examples**
The first several iterations of the pattern are as follows:
```
N = 0
|-
N = 1
|-||
|---
N = 2
|-|||-|-
|---|-|-
|-||||||
|-------
N = 3
|-|||-|-|-|||-||
|---|-|-|---|---
|-|||||||-|||-||
|-------|---|---
|-|||-|-|-|-|-|-
|---|-|-|-|-|-|-
|-||||||||||||||
|---------------
N = 4
|-|||-|-|-|||-|||-|||-|-|-|||-|-
|---|-|-|---|---|---|-|-|---|-|-
|-|||||||-|||-|||-|||||||-||||||
|-------|---|---|-------|-------
|-|||-|-|-|-|-|-|-|||-|-|-|||-|-
|---|-|-|-|-|-|-|---|-|-|---|-|-
|-|||||||||||||||-|||||||-||||||
|---------------|-------|-------
|-|||-|-|-|||-|||-|||-|||-|||-||
|---|-|-|---|---|---|---|---|---
|-|||||||-|||-|||-|||-|||-|||-||
|-------|---|---|---|---|---|---
|-|||-|-|-|-|-|-|-|-|-|-|-|-|-|-
|---|-|-|-|-|-|-|-|-|-|-|-|-|-|-
|-||||||||||||||||||||||||||||||
|-------------------------------
```
I wonder if there is some short algebraic way to compute this structure.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~29~~ 25 bytes
```
'|-'[{a,⊖⌽⍉~a←⍪⍨⍵}⍣⎕⍉⍪⍳2]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/6r1@iqR1cn6jzqmvaoZ@@j3s66RKDko95Vj3pXPOrdWvuodzFQB1AcLLTZKPY/UNv/NC4TAA "APL (Dyalog Classic) – Try It Online")
`‚ç≥2` is the vector `0 1`
`‚ç™` turns it into a 2x1 matrix
`‚çâ` transposes it, so it becomes 1x2
`‚éï` evaluated input
`{` `}⍣⎕` apply a function that many times
`⍪⍨⍵` concatenate the argument on top of itself - a 2x2 matrix
`a‚Üê` remember as `a`
`~` negate
`‚çâ` transpose
`‚åΩ` reverse horizontally
`‚äñ` reverse vertically
`a,` concatenate with `a` on the left
`'|-'[` `]` use the matrix as indices in the string `'|-'`, i.e. turn 0 into `|` and 1 into `-`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~130~~ ... ~~106~~ ~~94~~ 92 bytes
Golfed from my alternative method and fixing the characters, -14 bytes Thanks @Shaggy
```
f=n=>n?f(n-1).replace(/.+/g,x=>(g=i=>x.replace(/./g,p=>p<i?s[i]+s[i]:s))`0`+`
`+g`1`):s="|-"
```
[Try it online!](https://tio.run/##TcmxDsIgEIDh3cfodBeE2sSp8eiDNCZHEAiGACnGdOi7o24u//D9T/M2zW6xvmQuD9e7p0w6Lx6ynFBtriZjHYxKjOG8k4ZAkfT@N75eSddbXNoa7@KXuSHyhQWfWASeGOdGwyGHbktuJTmVSgAPV8T@AQ "JavaScript (Node.js) – Try It Online")
**My original approach (~~106~~ 102 bytes)**
```
f=n=>n?[0,1].map(j=>f(n-1).split`
`.map(x=>x+x.substr((i=x.length/2)*j,i).repeat(2)).join`
`).join`
`:"|-"
```
-4 bytes Thanks @Shaggy
```
f=n=>n?[0,1].map(j=>f(n-1).split`
`.map(x=>x+(y=x.substr((i=x.length/2)*j,i))+y).join`
`).join`
`:"|-"
```
[Try it online!](https://tio.run/##PctBDsIgEEDRvcfoasYWtLozAQ9iTIoVKgQHUtDQxLtj48Ldy0@@U2@VxtnGzCjcda1GkJB0vuy7/sqfKoIT0gCxHnmK3uZhM/xyEbK0sIjC0@uW8gxgV3tNU37sDrh1nUVsF@QuWFqnP07NhzV1DJSC19yHCQwcEesX "JavaScript (Node.js) – Try It Online")
Explanation & Ungolfed:
```
function f(n) { // Main Function
if (n != 0) { // If n != 0: (i.e. not the base case)
return [0, 1].map( // Separate the pattern into 2 parts
function(j) { // For each part:
return f(n - 1).split("\n") // Split the next depth into lines
.map(function(x) { // For each line in the result:
return x // The common part: "AB"
+ x.substr(
(i = x.length / 2) * j // Take A if j == 0, B if j == 1
, i // Take half the original length
).repeat(2); // Double this part
}).join("\n"); // Join all lines together
}).join("\n"); // Join the two parts together
}
else return "|-"; // If not (base case): return "|-";
}
```
**My original alternative method, if `"|"->"2", "-"->"1"` is allowed, ~~105~~ 104 bytes:**
```
f=n=>n?f(n-1).replace(/[12]+/g,x=>(g=(y,i)=>y.replace(/1|2/g,p=>[,i?11:22,21][p]))(x,0)+`
`+g(x,1)):"21"
```
[Try it online!](https://tio.run/##RcnRCoMgFADQ931GT/ei1a7sqdA@JITEqThCpcYo2L@73vZ24LzMx@x2i@Xdpvx0tXqZpEqTh9QSdpsrq7EO@pmEZn3gh1QQJJw8olTn/@krri1SzTxORIMQXJCei0aEg9@RLbeFhYuEODSCmjranPa8um7NATw8EMf6Aw "JavaScript (Node.js) – Try It Online")
**Just figured out some algebraic method towards this problem.**
```
x=>y=>"|-||--"[(f=(x,y,t=0,m=2**30,i=!(y&m)*2+!(x&m)<<1)=>m?f(x^m,y^m,([18,0,90][t]&3<<i)>>i,m>>1):t)(x>>1,y)*2+x%2]
```
[Try it online!](https://tio.run/##PYzhaoMwFIX/5ynSwMqNxhEVxjpzswdxDqStEmlMUSkJc8/uIoX9uHznng/O0D7a@TyZ@5KN7nLdetw86oCardm6ZhmroUPwIogFpbBYJEkphcEDhKPlSZEewMegVM5R288O/LcVIR7U@buQ4iSbemmOpVKGa22E1TrnHwsHH4MI@4J/KZrt0U50pkgZq0jnJgp7McRCVhGK5m@RacrpD6H/3jy9ib4sIndPaNxJkfZgOAy8Is@XfY1x@Zec3Ti72/X15nqYebX9AQ "JavaScript (Node.js) – Try It Online")
(finally a function which length's comparable to my original answer)
`f(n, x, y)` calculates the block type at (x, y) block at `n`th iteration of the following substitution:
```
0 => 0 1 1 => 0 0 2 => 1 1
0 2 0 0 2 2
```
where `0 = "|-", 1 = "||", 2 = "--"`, starting from `f(0, 0, 0) = 0`.
Then, `g(x)(y)` calculates the symbol at (x, y) of the original pattern.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 ~~17~~ 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╛ä├¼àz[{╧↑;ε╖>╠
```
[Run and debug it](https://staxlang.xyz/#p=be84c3ac857a5b7bcf183beeb73ecc&i=3%0A5&a=1&m=2)
Here's the ascii representation of the same program.
```
'|'-{b\2*aa+c\}N\m
```
The basic idea is start with the 0-generation grid, and then repeat a block that expands the grid.
```
'|'- Push "|" and "-"
{ }N Get input and repeat block that many times.
b Copy two top stack values
\2* Zip two parts, and double the height
aa Roll the top of the stack down to 3rd position.
+ Concatenate two grids vertically
c\ Copy result and zip horizontally
\ Zip the two parts horizontally
m Output each row
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~17~~ 16 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
|∙-╶[∔αω+:∔;:+}+
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTdDJXUyMjE5LSV1MjU3NiV1RkYzQiV1MjIxNCV1MDNCMSV1MDNDOSV1RkYwQiV1RkYxQSV1MjIxNCV1RkYxQiV1RkYxQSV1RkYwQiV1RkY1RCV1RkYwQg__,i=Mg__,v=1)
Explanation, showing the stack for the input of 1:
```
|‚àô- push "|" and "-" - the initial halves "|", "-"
‚ï∂[ } repeat input times
∔ add the two parts vertically "|¶-"
αω get the original arguments to that "|¶-", "|", "-"
+ and add those horizontally "|¶-", "|-"
:∔ and add to itself vertically "|¶-", "|-¶|-"
; get the vertically added parts "|-¶|-", "|¶-"
:+ and add to itself horizontally "|-¶|-", "||¶--"
+ finally, add the halves together "|-||¶|---"
```
Updated to 16 bytes by fixing a bug where the values set for `α`/`ω` to work weren't copied properly (Canvas is supposed to be fully immutable, but, alas, it wasn't).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ 77 bytes
-11 bytes thansk to Lynn
```
f=lambda x:x<1and['|-']or[n+2*n[i:i+2**x/2]for i in(0,2**x/2)for n in f(x-1)]
```
[Try it online!](https://tio.run/##NcxBDsIgEAXQq8xuoNJqSdwQewUvgCwwFR1jh4Z0QRPvjlTjZn7@y8/M6/KIrEsJw8tP19FDNvnUex4tvlt0MVne6YYtGarZ5L12ISYgIBYH9RO5CVeBIHLbS1f@E0ie7zdxlGZOxAvgGQZUpPDC@D3dM9ZHQZCUW69SPg "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
```
@1='|-';$l=@1,map{/.{$l}/;push@1,$_.$' x2;$_.=$&x2}@1for 1..<>;say for@1
```
[Try it online!](https://tio.run/##K0gtyjH9/9/B0Fa9RlfdWiXH1sFQJzexoFpfr1olp1bfuqC0OAMopBKvp6KuUGFkDWTYqqhVGNU6GKblFykY6unZ2FkXJ1YqAHkOhv//m/zLLyjJzM8r/q/ra6pnYGgAAA "Perl 5 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
!¡§z+DȯṁmDTm½;"|-
```
1-indexed.
[Try it online!](https://tio.run/##ASEA3v9odXNr//8hwqHCp3orRMiv4bmBbURUbcK9OyJ8Lf///zU "Husk – Try It Online")
## Explanation
```
!¡§z+DȯṁmDTm½;"|- Implicit input: a number n.
"|- The string "|-".
; Wrap in a list: ["|-"]
¬° Iterate this function on it:
Argument is a list of lines, e.g. L = ["|-||","|---"]
m¬Ω Break each line into two: [["|-","||"],["|-","--"]]
T Transpose: [["|-","|-"],["||","--"]]
ȯṁ Map and concatenate:
mD Map self-concatenation.
Result: ["|-|-","|-|-","||||","----"]
z+ Zip using concatenation
§ D with L concatenated to itself: ["|-|||-|-","|---|-|-","|-||||||","|-------"]
Result is the infinite list [["|-"],["|-||","|---"],["|-|||-|-","|---|-|-","|-||||||","|-------"],...
! Take n'th element, implicitly display separated by newlines.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 19 bytes
```
;"/;`,Ẏ;`€$
⁾|-Ç¡ZY
```
[Try it online!](https://tio.run/##y0rNyan8/99aSd86Qefhrj7rhEdNa1S4HjXuq9E93H5oYVTk///GAA "Jelly – Try It Online")
---
Explanation:
Initially, the value is `‚Åæ|-`, that is `["|","-"]`.
The last link (`Ç`), given `[A, B]`, will return
```
AB AA
[ AB , BB ]
```
. The `¬°` repeatedly apply the last link (input) number of times, and `ZY` formats it.
Explanation for last link:
```
-----------------
;"/;`,Ẏ;`€$ Monadic link. Value = [A, B]
;"/ Accumulate vectorized concatenate. Calculates (A ;" B).
Represented as a matrix, it's |AB| (concatenated horizontally)
;` Concatenate with self. |AB|
Value = |AB| (concatenate vertically)
, $ Pair with ...
Ẏ Tighten. |A| (concatenate vertically)
Value = |B|
;`€ Concatenate each with self. |AA|
Value = |BB| (duplicate horizontally)
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~121~~ 106 bytes
```
import StdEnv
$0=[['|-']]
$n#z=map(splitAt(2^n/2))($(n-1))
=[u++v++u++u\\(u,v)<-z]++[u++v++v++v\\(u,v)<-z]
```
[Try it online!](https://tio.run/##TY6xCsIwFEX3fkXAQBNiUIujGQQdhG4d2wpprRJIXotNCha/3WdEB@Fy4J7l3tZ2GtD1l2A74rQBNG7o754U/nKEKaFrVZbpU6Z1nVBYzMrpgY2DNX7vWXaGVcY5owzkhvNElUGISYjIUFUsLCe@k3MtxM9/8uex8DouKXK12lsD3cgIJVvC8dVGdRtRnnI8PEA7035LfJWbBmXzBg "Clean – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 86 bytes
```
(%)=zipWith(++)
f 0=["|-"]
f n|(a,b)<-unzip$splitAt(2^(n-1))<$>f(n-1)=a%b%a%a++a%b%b%b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/X0NV07YqsyA8syRDQ1tbkytNwcA2WqlGVykWyMyr0UjUSdK00S3NA6pRKS7IySxxLNEwitPI0zXU1LRRsUsDs2wTVZNUE1UTtbVBDCD8n5uYmadgq5CbWOAbr1BQWhJcUuSTp6CikKZg8h8A "Haskell – Try It Online")
Pretty simple. Output is a list of strings. We take the previous version and split each line in half then collect those into two new lists using `unzip`. Then it's simply a matter of combining the arrays together the right way
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
f=.3 :'''|-''{~((,.[:|.[:|."1[:|:-.)@,~)^:y,:0 1'
```
A clumsy translation of ngn's APL solution. I had problems making it tacit - I'll apreciate any advice.
[Try it online!](https://tio.run/##y/r/P81Wz1jBSl1dvUZXXb26TkNDRy/aqgaMlQyBpJWunqaDTp1mnFWljpWBgqH6/9TkjHyFNAUDLjBDXV2BCypiCBOBCRihCxijC5igC5j@BwA "J – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~47~~ 46 bytes
```
M²↖|-¶¶FENX²ι«F²C±ι⁰C⁰ιC⊗ι±ιC׳ι±ι≦⊗ιM±ι±ιT⊗ιι
```
[Try it online!](https://tio.run/##XY69DoIwFIVneIqGqU0gIRgXnYwuGiEMuLEAFmxCf1JajFGfvRYiRNzuvec759zqVsiKF60xMe8xjHywuYgzrhXauqkkTEHvFeQsZ5491FwCGBcCHpnQKtG0xBIiH6T8bgfrJQgh8HSdEYwQ2HPxgAluCoUhsWBoQ5zxGA7wtBy4Llt8HZGZntWMUNzB1WD4k@0ru64jDZsSvqEnTcVv7cKUSUIXjYPlbczaBH37AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
M²↖|-¶¶
```
In order to get a consistent cursor position for the following loop, I have to print step 0 at position (-2, -2) and leave the cursor at (-2, 0). (This might be due to a bug in Charcoal.)
```
FENX²ι«
```
Loop over the first `N` powers of 2.
```
F²C±ι⁰C⁰ιC⊗ι±ιC׳ι±ι
```
Make copies of the previous output with various offsets resulting in a canvas that contains the desired next step in a rectangle within it.
```
≦⊗ιM±ι±ιT⊗ιι
```
Move to the position of that rectangle and trim the canvas.
Alternative solution, also 46 bytes:
```
M²→|-FENX²ι«F432C×Iκι׳ιF245C×Iκι⊗ι≦⊗ιJ⊗ιιT⊗ιι
```
[Try it online!](https://tio.run/##fY69DoIwFEZneYqG6TaBhZ9FJoOLJhhieIGCVRopJS3FGPXZa/kxDiZu9zs5J7lVTWQlSGNMJgYKgYfWR3ape5w4uWRtD@7Td@04C4kgIx3s2k73B81LKgF7KBc3e9iMYYzRw1lNohuFgYtRKro7FIxTBSlRPVzx6HloRuEUJZ8kiOI/yVbosqEnmAv7yEYpdmlh4aNk@V7zrhDwlRdeSMZ/6MuY2PhD8wY "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
M²→|-
```
This time step 0 has to be printed at position (2, 0), but at least the cursor position doesn't matter.
```
FENX²ι«
```
Loop over the first `N` powers of 2.
```
F432C×Iκι׳ιF245C×Iκι⊗ι
```
Make copies of the previous output with various offsets resulting in a canvas that contains the desired next step in a rectangle within it.
```
≦⊗ιJ⊗ιιT⊗ιι
```
Move to the position of that rectangle and trim the canvas.
[Answer]
# [R](https://www.r-project.org/), 126 bytes
```
function(n,k=cbind){o=matrix(c("|","-"),1,2)
if(n>0)for(i in 1:n)o=rbind(k(a<-o[,x<-1:(2^(i-1))],b<-o[,-x],a,a),k(a,b,b,b))
o}
```
[Try it online!](https://tio.run/##HY7BCsMgEETv@QrxtFtWqB5D0h8pCWhaYQldQSwV2n67NWUuw/BmmNyimkyLT9kKJwGhfd4Cyw3faX74krnCBvqjSRuNZMnhwBHkcsaYMrBiUXYUTHM@WrCDn0y6Up2MHcGtwMYiLhT@qakLefJIHaNwCHFI3yb9g3LDK3O5Q4G@j0hakzu5Vag7bD8 "R – Try It Online")
Returns a `matrix`. There's a bit of code in the TIO link to get it to print nicely for ease of verification.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 25 bytes
```
{"|-"x{x,'|+|~x:x,x}/,!2}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlqpRleporpCR71Gu6auwqpCp6JWX0fRqPa/gZ@iepq6oqn1fwA "K (ngn/k) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~67~~ 65 bytes
```
SubstitutionSystem[{"|"->{i={"|","-"},i},"-"->{i,i}Ôèá},{i},{#}]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0qbgks6S0JDM/L7iyuCQ1N7paqUZJ16460xbE0FHSVarVyawF0SBBIPN9f3utTjVQqFq5Nlbtf0BRZl6Jg4ODspq@Q5qDa3JGPpgZlJiXnhptoGMS@x8A "Wolfram Language (Mathematica) – Try It Online")
Straightforward implementation of the recursion. Returns an array of characters wrapped in a list.
] |
[Question]
[
[Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)) is a puzzle game where mines are hidden around a board of nondescript tiles with the goal of identifying the location of all mines. Clicking on a mine loses the game, but clicking on any other tile will reveal a number from 0-8 which signifies how many mines directly surround it.
Given a number, you must display a random\* possible combination of empty tiles and mines surrounding it. This should be in the form of a 3x3 array. The center tile should be the number of mines taken as input.
\*Must have a non-zero chance for all combinations to occur.
---
## Examples
```
_ = blank square
X = mine
0
___
_0_
___
1
_X_
_1_
___
1
___
_1_
X__
___
_1_
__X
4
_X_
X4X
_X_
4
X_X
_4_
X_X
4
___
X4X
X_X
8
XXX
X8X
XXX
```
---
### Input
* The number of mines surrounding the center tile (0-8)
---
### Output
* Any reasonable form of output that displays the 3x3 array of tiles
---
## Other rules
* Each combination does not have to have an equal chance of happening. There just must be a non-zero chance of each combination to occur when executing your program.
* Any 2 characters can be chosen for the mine and empty tile.
* This is code golf, the program with fewest bytes wins.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 15 bytes
-13 bytes thanks to ngn!
```
{3 3⍴5⌽⍵,⍵≥8?8}
```
## Explanation:
`{...}` A direct function (D-Fn), `⍵` is its right argument.
`8?8` deal 8 random numbers from the list 1..8:
```
8?8
7 2 1 8 4 6 5 3
```
`⍵≥` is the argument greater or equal to each of them?:
```
5 ≥ 7 2 1 8 4 6 5 3
0 1 1 0 1 0 1 1
```
`⍵,` prepend the argument to the boolean list:
```
5 , 0 1 1 0 1 0 1 1
5 0 1 1 0 1 0 1 1
```
`5⌽` rotate the list 5 positions to the left, so that the argument is in the center:
```
5 ⌽ 5 0 1 1 0 1 0 1 1
1 0 1 1 5 0 1 1 0
```
`3 3⍴` reshape the list to a 3x3 matrix:
```
3 3 ⍴ 1 0 1 1 5 0 1 1 0
1 0 1
1 5 0
1 1 0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqYwXjR71bTB/17H3Uu1UHiB91LrWwt6gFSisYc6nrKgChOleagikS2xwA "APL (Dyalog Unicode) – Try It Online")
# [J](http://jsoftware.com/), 15 bytes
Also many bytes thanks to ngn!
```
3 3$5|.],]>8?8:
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9YwVjFtEYvVifWzsLewuq/JpeSnoJ6mq2euoKOQq2VQloxF1dqcka@QpqCEYShrqsAhOowUROsoub/AQ "J – Try It Online")
[Answer]
# JavaScript (ES6), 67 bytes
*Shorter version suggested by @tsh*
Empty slots are `0`, mines are `1`.
```
n=>`___
_${t=9,n}_
___`.replace(/_/g,_=>n-(n-=Math.random()<n/--t))
```
[Try it online!](https://tio.run/##DcpBDoIwEEDRPaeYhUnblIJLFYYbeAOToYGCEpyS0rghnL129d/iL/Zn9yF8tmjYjy5NmBi7nogKuhwR7yWfmUR9Fdy22sHJmuq5JOzYSDb4tPFdBcuj/0rVcm1MVCpNPkgGhGsDDC3CLVdrBUcBMHje/eqq1c/50SAeLxa5k2SlRbZqijP9AQ "JavaScript (Node.js) – Try It Online")
---
# Original trial-and-error version, 78 bytes
Empty slots are `_`, mines are `7`.
```
f=(n,o=`___
_${k=n}_
___`.replace(/_/g,c=>Math.random()<.5?--k|7:c))=>k?f(n):o
```
[Try it online!](https://tio.run/##FYtBDoIwEADvvGIPJrQpFC9GAxRe4A9MalMKKrhLCvGCvL3W08xh5mU@ZrH@Oa85UudC6BXDjNRda53owzYq3KNofZfezZOxjhW6GDKrmqtZH9Ib7OjNeC1PbZ6P33NpOVfN2PYMeUmhJ88QFBwrQKgVXCKF4LAlAJZwocnJiYbYCEjLG6aR/1Wk0XmV7OEH "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function
n, // n = input
o = `___\n_${k = n}_\n___` // o = minesweeper field / k = backup of n
.replace(/_/g, c => // for each underscore character c in o:
Math.random() < .5 ? // random action:
--k | 7 // either decrement k and yield 7
: // or:
c // let the underscore unchanged
) // end of replace()
) => //
k ? // if k is not equal to 0:
f(n) // try again
: // else:
o // stop recursion and return o
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
8Ẉ>RẊs4js3
```
The returned list of lists has the displayed integer in the centre surrounded by 0s and 1s representing mines and blanks respectively.
**[Try it online!](https://tio.run/##y0rNyan8/9/i4a4Ou6CHu7qKTbKKjf8fbo/8/98YAA "Jelly – Try It Online")** (footer pretty prints the array)
### How?
```
8Ẉ>RẊs4js3 - Link: integer, n e.g. 3
8 - eight 8
Ẉ - length of each (implicit range of eight) [1,1,1,1,1,1,1,1]
R - range of n [1,2,3]
> - greater than? (vectorises) [0,0,0,1,1,1,1,1]
Ẋ - shuffle [1,1,1,0,0,1,1,0]
s4 - split into chunks of 4 [[1,1,1,0],[0,1,1,0]]
j - join (with n) [1,1,1,0,3,0,1,1,0]
s3 - split into chunks of 3 [[1,1,1],[0,3,0],[1,1,0]]
```
[Answer]
# Pyth, ~~16~~ 14 bytes
```
c3jQc2.S.[d8*N
```
Saved 2 bytes thanks to isaacg.
Uses spaces for safe spots and quotes for mines.
[Try it here](https://pyth.herokuapp.com/?code=c3jQc2.S.%5Bd8%2aN&input=2&debug=0)
### Explanation
```
c3jQc2.S.[d8*N
*NQ Get (implicit) input number of quotes...
.[d8 ... and pad to length 8 with spaces.
.S Shuffle.
jQc2 Stick the input in the middle.
c3 Split into three.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
<Ɱ8Ẋs4js3
```
[Try it online!](https://tio.run/##y0rNyan8/9/m0cZ1Fg93dRWbZBUb/z/c7v7/vzEA "Jelly – Try It Online")
empty = `1`
mine = `0`
Note that `1` and `0` are integers.
Another note: this is somewhat similar to Jonathan Allan's 10-byte answer, but it's not really influenced by it in any way, and the mechanism, if you pay close attention, is actually more different than at first glance.
[Answer]
# Oracle 18 SQL, 230 bytes
Not a golfing language but...
```
WITH v(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1))SELECT v.v||b.v||c.v||'
'||d.v||n||e.v||'
'||f.v||g.v||h.v
FROM n,v,v b,v c,v d,v e,v f,v g,v h
WHERE v.v+b.v+c.v+d.v+e.v+f.v+g.v+h.v=n
ORDER BY DBMS_RANDOM.VALUE
FETCH NEXT ROW ONLY
```
The input value is in a table `n` with column `n`:
```
CREATE TABLE n(n) AS
SELECT 7 FROM DUAL;
```
Try it online - log onto <https://livesql.oracle.com> and paste it into a worksheet.
Output:
```
V.V||B.V||C.V||''||D.V||N||E.V||''||F.V||G.V||H.V
-------------------------------------------------
101
171
111
```
To get all possible combinations (183 Bytes):
```
WITH v(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1))SELECT v.v||b.v||c.v||'
'||d.v||n||e.v||'
'||f.v||g.v||h.v
FROM n,v,v b,v c,v d,v e,v f,v g,v h
WHERE v.v+b.v+c.v+d.v+e.v+f.v+g.v+h.v=n
```
Output:
```
V.V||B.V||C.V||''||D.V||N||E.V||''||F.V||G.V||H.V
-------------------------------------------------
111
171
110
111
171
101
111
171
011
111
170
111
111
071
111
110
171
111
101
171
111
011
171
111
```
[Answer]
# Japt, 13 bytes
```
çÊú8 öÊi4U ò3
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=58r6OCD2ymk0VSDyMw==&input=NAotUg==)
---
## Explanation
```
:Implicit input of integer U
Ê :"l"
ç :Repeat U times
ú8 :Pad right to length 8
öÊ :Random permutation
i4U :Insert U at index 4
ò3 :Split at every 3rd character
```
[Answer]
# [QBasic 1.1](http://www.qbasic.net/), ~~206~~ 186 bytes
```
RANDOMIZE TIMER
INPUT N
O=N
Z=8-N
FOR I=0TO 7
IF O*Z THEN
R=RND<.5
O=O+R
Z=Z-1-R
A(I)=-R
ELSEIF O THEN
O=O-1
A(I)=1
ELSE
Z=Z-1
A(I)=0
ENDIF
NEXT I
?A(0)A(1)A(2)
?A(3)N;A(4)
?A(5)A(6)A(7)
```
-20 thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) (newly-posted golfing trick).
Empty = `0`
Mine = `1`
Note that `0` and `1` are integers, but I'm using STDOUT anyway, so...
Output appears like this:
```
A B C
D x E
F G H
```
Where A-H are 0/1 and x is the input.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
W¬⁼ΣIKA⁸«E³⭆³‽²↑↗↖θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDL79Ew7WwNDGnWCO4NFfDObG4RCMgNTXbMSdHQ1NTU0fBAkgqVHNxBhRl5pVo@CYWaBjrKASXAHnpUE5QYl5Kfq6GEVChpjUXp29@WaqGVWgBMjsoMz2jBCQAMQUo4pOaVqKjUAgUq/3/3@S/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Uses `0` for a mine, `1` for an empty space. Explanation:
```
KA Peek the entire canvas
I Cast to integer
Σ Take the sum
⁸ Literal 8
⁼ Equals
¬ Logical Not
W « While
³ ³ Literal 3
E Map over implicit range
⭆ Map over implicit range and join
² Literal 2
‽ Random element of implicit range
Implicitly print on separate lines
↑↗↖θ Print the original input in the middle
```
* `Peek` returns an array of strings, which `Sum` simply concatenates, which is why we have to cast to integer first. (`Sum(Sum(PeekAll()))` also works.)
* `Sum` returns `None` for an empty array (first loop), so the only safe comparison is `Not(Equals(...))`.
* Nilary `Random` always returns `0`, although its documentation says otherwise.
Alternative solution, was 19 bytes, now 17 bytes after a Charcoal bugfix:
```
θ←9W⁻ΣIKA⁸UMKMI‽²
```
[Try it online!](https://tio.run/##HcoxDsIwDEDRnVN4tKWwIAZEJ9Q5UgUniEqkRjhxmyZwfGN1/f/NS6izBFb1nVtaayoN7w9mBxP3HTcHG9Fw@i2JI6BPxeKrZxzD3nCK8WMWicjBjQh8WEfJOZT38bxIjWjv0E/LkvFielC96vnLfw "Charcoal – Try It Online") Link is to verbose version of code. Uses `0` for a mine, `1` for an empty space. Explanation:
```
θ
```
Print the original input.
```
←9
```
Print a `9` leftwards. This moves the cursor back over the original input, and also forces at least one iteration of the while loop (otherwise an input of `8` would do nothing).
```
W⁻ΣIKA⁸
```
Repeat while the difference between the sum of all the digits on the canvas and 8 is nonzero:
```
UMKMI‽²
```
Replace each of the surrounding characters randomly with `0` or `1`.
[Answer]
# [R](https://www.r-project.org/), ~~67 63 62~~ 59 bytes
```
matrix(c(sample(rep(1:0,c(n<-scan(),8-n))),n),6,5)[2:4,1:3]
```
[Try it online!](https://tio.run/##K/r/PzexpCizQiNZozgxtyAnVaMotUDD0MpAJ1kjz0a3ODkxT0NTx0I3T1NTUydPU8dMx1Qz2sjKRMfQyjj2v@l/AA "R – Try It Online")
Uses `1` and `0`. Build a `n* 1 +(8-n)* 0` vector, shuffles it, appends `n`, builds the bigger matrix shown below(where `a...i` stand for the elements of the original vector) and extracts the proper sub-matrix shown in uppercase:
```
[,1] [,2] [,3] [,4] [,5]
[1,] "a" "g" "d" "a" "g"
[2,] "B" "H" "E" "b" "h"
[3,] "C" "I" "F" "c" "i"
[4,] "D" "A" "G" "d" "a"
[5,] "e" "b" "h" "e" "b"
[6,] "f" "c" "i" "f" "c"
```
[Answer]
# [Python 2](https://docs.python.org/2/), 93 bytes
```
from random import*
def f(n):a=[1]*n+[0]*(8-n);shuffle(a);a[4:4]=[n];return zip(*[iter(a)]*3)
```
[Try it online!](https://tio.run/##FY27DgIhEAB7v2JLFmPi4wqF3JcQCpJjvU28haxcoT@PWE0xyUz9tLXItXfSsoEmWQZ4q0WbPSyZgIygS3O4RCvHcI7W3E@C/r3uRK9sEvoUJjfFOUj0mtuuAl@uxgZuWYeP9oadigIDy//wzOaBDqqytJFn7D8 "Python 2 – Try It Online")
`0` for empty; `1` for a mine; and `n` for one's self.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 51 bytes
```
{[3,3]&Rotate[Sample[{Sum@_=_2}&_\BinBelow@8]'_,4]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fZmX7vzraWMc4Vi0ovySxJDU6ODG3ICc1ujq4NNch3jbeqFYtPsYpM88pNSe/3MEiVj1exyS29n9JcnRerIKVrYJGQFFmXkl0no6Ckq6dUqyCtbWCS2ZxQU5iZXQaUAlYAKIkVpOrJFnB1k7BwMriPwA "Attache – Try It Online")
## Explanation
Similar to [Galen's J/APL answer](https://codegolf.stackexchange.com/a/166070/31957), the basic technique is to generate an array of 1s and 0s with the correct number of mines, inserting the input by appending it to the end, rotating the array such that the input lies in the center, then reshaping into a 3x3 matrix.
### Part 1: generating the binary array
There are many ways to go about doing this, but I mainly happened across two types: brute force and selection.
The primary brute force method looks like this:
```
NestWhile[{Random[8&2]},0,{Sum@_/=_2}&_]
```
This generates random arrays of 8 binary digits (`Random[8&2]`) while their sums do not equal the input `{Sum@_/=_2}&_`. This is a bit verbose, as the following emphasized portions of the code are there "just to make it work":
```
NestWhile[{Random[8&2]},0,{Sum@_/=_2}&_]
^ ^^^^^ ^^^^
```
And I discarded the idea.
Selection is more interesting. The main concept is to use the `BaseBelow[b, n]` builtin, which generates a list of all base-`b` integers of width `n` (as digit arrays), from `0` to `b^n-1`. For example, `BaseBelow[3, 2]` generates all ternary integers of width 2:
```
A> BaseBelow[3, 2]
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
```
We specifically use `BaseBelow[2, 8]` for all binary integers of width 8. These represent all possible minefields of all lengths. This is the first step.
The second step is selecting all such arrays with only `N` 1s, where `N` is the input. My first idea was to translate this English statement directly into Attache:
```
Chunk[SortBy[Sum,BaseBelow[2,8]],Sum]@N@1
```
However, not only did this come out to be 1 byte longer than the aforementioned approach, it's also highly repetitive—and it isn't even randomized yet!. Sure, I could probably save 1 byte by reorganizing how `BaseBelow` is called, but it simply isn't worth using the approach.
So I decided to kill two birds with one stone and use a `Shuffle` based approach. The following gives all valid minefields of length `N` in random order:
```
{Sum@_=_2}&N\Shuffle[BaseBelow&8!2]
```
Then, all that needs to be done is to select the first. But I can do better—surely it'd be better to simply `Sample` the filtered array? This approach comes out to be something like this:
```
Sample[{Sum@_=_2}&_\BaseBelow[2,8]]
```
I had to revert the `BaseBelow&8!2` golf because `\`s precedence is too high. Otherwise satisfied, I proceeded to chop a byte off of that:
```
Sample[{Sum@_=_2}&_\2&BaseBelow@8]
```
(I discovered another way to succinctly call a dyadic function here: `x&f@y` is a high-precedence expression which evaluates to `f[x, y]`.)
However, despite this, I remembered that, all along, an alias for `2&BaseBelow` existed: `BinBelow`. So I used that:
```
Sample[{Sum@_=_2}&_\BinBelow@8]
```
This generates the desired minefield. I'm convinced this is near optimal.
### Part 2: Forming the array
As said earlier, the forming technique I used is similar to the J/APL answer, so I won't go into too much detail. Suppose `MINEFIELD` is the result from the last section. The function then becomes:
```
{[3,3]&Rotate[MINEFIELD'_,4]}
```
`MINEFIELD'_` concatenates the minefield with the original input `_`, giving us something like this:
```
[1, 0, 0, 0, 1, 0, 0, 1, 3]
```
Then, `Rotate[MINEFIELD'_,4]` rotates this list `4` times to the left, placing the center:
```
[1, 0, 0, 1, 3, 1, 0, 0, 0]
```
The last step is using `[3,3]&` to reshape the list into a 3x3 matrix:
```
1 0 0
1 3 1
0 0 0
```
[Answer]
# Java 10, ~~165~~ ~~157~~ 141 bytes
```
n->{var r="___\n_"+n+"_\n___";for(int i;n>0;r=r.charAt(i*=Math.random())>58?r.substring(0*n--,i)+(i>9?0:0+r.substring(i+1)):r)i=11;return r;}
```
Empty tiles are `_` (any character with a unicode value above 58 is fine) and mines are `0`.
[Try it online.](https://tio.run/##TZBBbsIwEEX3PcUoKxs3UbJAorgO6gFgw7JUkQmhDIUJjB2kCnH21CRpqWRbHn/rz/uztxcb7zdfbXmwzsHcIl2fAJB8xVtbVrC4lwBLz0ifUIqgAEkdHm9hh@W89VjCAggMtBTn14tlYBMVRbGiIlKkovulKCK9rbkzQE15qtlwUu4sv3mBIzO3fpewpU19FFLm48mME9esXddYpCOK42eUSmD@MkunqfqvosqknLJEk2WaK98wAetbq3vEU7M@BMSB9FLjBo4hqOhDvX@AlX1KXzkv0i4dwB@syTTg6yQcSslOeohnM9ZwjuMQB361wQcHn66YDCN7DKzD6D/emwwEy2/nq2NSNz45BTh/IEFJmLpU0YqiweTW/gA)
**Explanation:**
```
n->{ // Method with integer parameter and String return-type
var r="___\n_"+n+"_\n___"; // Result-String, starting at:
// "___
// _n_
// ___"
for(int i;n>0 // Loop as long as `n` isn't 0 yet:
; // After every iteration:
r=r.charAt(i*=Math.random())
// Select a random integer in the range [0,11)
>58? // And if the character at this random index is a '_':
r.substring(0*n--,i) // Set `r` to the first part excluding character `i`,
// (and decrease `n` by 1 in the process)
+(i>9?0:0+ // appended with a '0',
r.substring(i+1)) // appended with the second part
: // Else:
r) // Leave `r` unchanged
i=11; // Set `i` to 11 so a new random integer can be chosen
return r;} // Return the result
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 77 bytes
```
param($n)-join(0..7|random -c 8|%{'X_'[$_-ge$n]
$n[++$i-ne4]
'
'*($i-in3,5)})
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9vyCxKDFXQyVPUzcrPzNPw0BPz7ymKDEvJT9XQTdZwaJGtVo9Il49WiVeNz1VJS@WSyUvWltbJVM3L9UklkudS11LA8jJzDPWMdWs1fxfy8UFNAGki0sBCNSAlqjEg5nq6ly1/wE "PowerShell – Try It Online")
[Answer]
# [PHP](https://php.net/), ~~135~~ ~~134~~ ~~123~~ ~~117~~ ~~122~~ 121 bytes
Looping over str to print instead saves 1 byte
str\_split and implode to insert the centre number saves 11 bytes
~~Don't need to assign the string to $s anymore saving 6 bytes~~
Yes you do. Otherwise the string is shuffled after every echo...
Removing whitespace after echo saves 1 byte
Replacing "\n" with an ctual line break saves 1 byte
```
$n=$argv[1];$s=implode($n,str_split(str_shuffle(str_pad(str_repeat(m,$n),8,n)),4));for(;$i<9;)echo$s[$i].(++$i%3?"":"
");
```
[Try it online!](https://tio.run/##HcZBCsIwEEDRvccII2RoFKQu1LT0CB6glBJs2gTazJBEj2@Ubv5/7Lg0Hf8LoQUTl09/GTSk1m@80mQlBJVyHBOvPstd7j3Pq93NZtofLVuT5aYgoLqpgKiuiHqmKDX45q7RvhxB6sEPZ1lV4I91J8RDHATqUkr9Jc6eQiqnKTmKeSS2YcxmaZ/hBw "PHP – Try It Online")
[Answer]
# [Alice](https://github.com/m-ender/alice), 24 bytes
```
a8E/be?SZ!@
~E-\ita*.o/a
```
[Try it online!](https://tio.run/##S8zJTE79/z/RwlU/KdU@OErRgavOVTcmsyRRSy9fP/H/f2MA "Alice – Try It Online")
Empty slots are `9`, and mines are `0`.
I also made a 27-byte program with `1` for mines and `0` for empty slots:
```
a8Ea8/be?SZ!@
-E-9:\ita*.o/
```
[Try it online!](https://tio.run/##S8zJTE79/z/RwjXRQj8p1T44StGBS9dV19IqJrMkUUsvX///f2MA "Alice – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 81 bytes
```
f(n,i,j,k){for(j=i=8,k=n;--i+5;putchar(i%4?i-2?rand()%j--<k?k--,88:95:48+n:10));}
```
[Try it online!](https://tio.run/##VcxBCoMwEADAu68IgrBLsmCLQjQG3yIptpvQWFJ7Et@e5lToeWAc3Z3LeYWoWHkV8Fi3BN6y1SrYaIhY9ub12d1jScBNNzNd57TEG2DjiaYwByKl9Tj0Y6dlHC8tojnzc@EIeFSlE8BxF2xbw9NgWEpVvjfUNWIlfu6L@@L@38UKjKY68xc "C (gcc) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~91~~ 86 bytes
-5 bytes thanks to mazzy
```
param($n)$x=,'X'*$n+,'_'*(8-$n)|random -c 8
-join$x[0..2]
$x[3,4]-join$n
-join$x[5..7]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0MlT1OlwlZHPUJdSyVPW0c9Xl1Lw0IXKFpTlJiXkp@roJusYMGlm5WfmadSEW2gp2cUywVkGOuYxEIE8@CSpnp65rH/a7m4gKosalSruTjVVNIUVOK5OJWUuDhr/wMA "PowerShell – Try It Online")
Shuffles a generated string ranging from `________` to `XXXXXXXX` (replacing from the left). It then slices through it multiple times, inserting `$n` in the middle, to build the output string. This last part can probably be greatly optimized because each index costs a minimum of 5 bytes.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 59 bytes
Returns a list of strings (one for each line).
```
->n{a=([0]*(8-n)+[1]*n).shuffle;a[4,0]=n;a.join.scan /.../}
```
[Try it online!](https://tio.run/##BcFNCoUgFAbQrTTUfr4MGgRhGzEH90WSEbfIHES1dt85Z/zdyekxVQM/pIVRNhddxbIwjc1ZIizRuW3uybSlspp7wrp7RpiIsxpA/SWhgE5ipml5Xv8e8QqZM96Wx5f@ "Ruby – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, ~~105~~ 101 bytes
```
@o=grep!/^....1/&&y/1//=="@F",map{sprintf"%09b",$_}0..2**9-1;$_=$o[rand@o];s/....\K./@F/;s/...\K/\n/g
```
[Try it online!](https://tio.run/##K0gtyjH9/98h3za9KLVAUT9ODwgM9dXUKvUN9fVtbZUc3JR0chMLqosLijLzStKUVA0sk5R0VOJrDfT0jLS0LHUNrVXibVXyo4sS81Ic8mOti/VBRsR46@k7uOlDeDHe@jF5@un//5v8yy8oyczPK/6v62uqZ2Bo8F@3IBEA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$×8j.r2äIý3ô
```
Uses `0` for mines, spaces for blank squares. Outputs a list of lines, which is pretty printed in the TIOs below by joining with newline delimiter (`»`).
[Try it online](https://tio.run/##yy9OTMpM/f9f5fB0iyy9IqPDSzwP7zU@vOX/od3/TQA) or [verify a few more test cases at once](https://tio.run/##ATAAz/9vc2FiaWX/N0w10Lh7MMWhOMKqdnn/MHnDlzhqLnIyw6R5w70zw7T/PcK7LMK2P/8).
**Explanation:**
```
$ # Push 0 and the input-digit
× # Repeat the 0 the input-digit amount of times as string
# i.e. 4 → "0000"
8j # Prepend spaces to make the size 8
# → " 0000"
.r # Randomly shuffle the characters in this string
# i.e. " 0000" → " 00 0 0"
2ä # Split it into two equal halves (of 4 characters)
# → [" 00 ","0 0"]
Iý # Join it with the input-digit
# → " 00 40 0"
3ô # And then split it into (three) parts of 3 characters
# → [" 00"," 40"," 0"]
# (which is output implicitly as result)
```
**12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
[[email protected]](/cdn-cgi/l/email-protection)š5._3ô
```
Uses `1` for mines, `0` for blank squares. Outputs a matrix of digits, which is pretty printed in the TIOs below by joining each row, and then these rows with newline delimiter (`J»`).
[Try it online](https://tio.run/##yy9OTMpM/f/fwsdBr@hRw6zTc0z14o0Pb/n/3xgA) or [verify a few more test cases at once](https://tio.run/##ATIAzf9vc2FiaWX/N0w10Lh7MMWhOMKqdnnDkP84TEAucuKAmsucNS5fM8O0/z1KwrsswrY//w).
**Explanation:**
```
8L # Push the list [1,2,3,4,5,6,7,8]
@ # Check for each if the (implicit) input-integer is >= it
# (1 if truthy; 0 if falsey)
# i.e. 4 → [1,1,1,1,0,0,0,0]
.r # Randomly shuffle this list
# i.e. [1,1,1,1,0,0,0,0] → [0,1,1,0,1,0,0,1]
Iš # Prepend the input-digit to the list
# → [4,0,1,1,0,1,0,0,1]
5._ # Rotate the list five times towards the left
# → [1,0,0,1,4,0,1,1,0]
3ô # And then split it into (three) parts of 3 digits each
# → [[1,0,0],[1,4,0],[1,1,0]]
# (which is output implicitly as result)
```
] |
[Question]
[
There's a minigame in Super Mario 3D World known as the *Lucky House*. It consists of a slot machine with 4 blocks.
[![Lucky House](https://i.stack.imgur.com/dKGVQ.jpg)](https://i.stack.imgur.com/dKGVQ.jpg)
Each block may be one of 5 different icons (Flower, Leaf, Bell, Cherry or Boomerang) and the goal of the player is to get as many identical icons as possible ([see a video](https://youtu.be/5YZ52pWn9Ms?t=8)).
The player is rewarded with coins, which in turn may be converted into extra lives. **Your task is to compute the number of extra lives won.**
Depending on the number of icons that match, the amount of coins rewarded are as follows:
* No matches - 10 coins
* One pair - 100 coins
* Two pairs - 200 coins
* Three-of-a-kind - 300 coins
* Four-of-a-kind - 777 coins
**You win one extra life (1UP) every 100 coins**. Therefore, you're guaranteed to win exactly 1UP with *one pair*, 2UP with *two pairs* and 3UP with *3-of-a-kind*. However, the number of lives won with *no matches* or *4-of-a-kind* depends on your initial coin stock.
*Source: [Super Mario Wiki](https://www.mariowiki.com/Lucky_House)*
## Input
You're given the initial coin stock \$0 \le c < 100\$ and a list of four values \$[v\_1,v\_2,v\_3,v\_4]\$ representing the final icons on the slot machine.
## Output
The number of extra lives won: \$0\$, \$1\$, \$2\$, \$3\$, \$7\$ or \$8\$.
## Rules
* You may take the icons in any reasonable format: e.g. as a list, as a string or as 4 distinct parameters.
* Each icon may be represented by either a **single-digit integer** or a **single character**. Please specify the set of icons used in your answer. (But you don't have to explain how they're mapped to Flower, Leaf, Bell, etc., because it doesn't matter at all.)
* You are not allowed to remap the output values.
* This is üé∞[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")üé∞.
## Test cases
In the following examples, we use a list of integers in \$[1..5]\$ to represent the icons.
```
coins icons output explanation
-------------------------------------------------------------------------
0 [1,4,2,5] 0 no matches -> 0 + 10 = 10 coins -> nothing
95 [3,1,2,4] 1 no matches -> 95 + 10 = 105 coins -> 1UP
25 [2,3,4,3] 1 one pair -> 25 + 100 = 125 coins -> 1UP
25 [4,5,5,4] 2 two pairs -> 25 + 200 = 225 coins -> 2UP
0 [2,5,2,2] 3 3-of-a-kind -> 0 + 300 = 300 coins -> 3UP
22 [1,1,1,1] 7 4-of-a-kind -> 22 + 777 = 799 coins -> 7UP
23 [3,3,3,3] 8 4-of-a-kind -> 23 + 777 = 800 coins -> 8UP
99 [3,3,3,3] 8 4-of-a-kind -> 99 + 777 = 876 coins -> 8UP
```
[Answer]
# x86-16 Assembly, ~~56~~ ~~41~~ 39 bytes
**Binary:**
```
00000000: b103 33ed ac8b fe51 f2ae 7503 45eb f983 ..3....Q..u.E...
00000010: fd03 7504 80c2 4d43 03dd 59e2 e592 7502 ..u...MC..Y...u.
00000020: 040a 3c64 7201 43 ..<dr.C
```
**Unassembled:**
```
B1 03 MOV CL, 3 ; set up loop counter for 3 digits
DIGIT_LOOP:
33 ED XOR BP, BP ; clear digit matches counter in BP
AC LODSB ; load next digit char into AL
8B FE MOV DI, SI ; start searching at next char
51 PUSH CX ; save outer digit loop counter
MATCH_LOOP:
F2/ AE REPNZ SCASB ; search until digit in AL is found
75 03 JNZ CHECK_FOUR ; is end of search?
45 INC BP ; if not, a match was found, increment count
EB F9 JMP MATCH_LOOP ; continue looping
CHECK_FOUR:
83 FD 03 CMP BP, 3 ; is four of a kind?
75 04 JNE SCORE_DIGIT ; if not, add number of matches to 1UP's
80 C2 4D ADD DL, 77 ; add 77 to coin count
43 INC BX ; +1 1UP extra for four-of-a-kind
SCORE_DIGIT:
03 DD ADD BX, BP ; Add number of matches to total, set ZF if 0
59 POP CX ; restore outer digit loop position
E2 E5 LOOP DIGIT_LOOP ; keep looping
92 XCHG DX, AX ; coin count to AX for shorter compare
75 02 JNZ FINAL_SCORE ; if 1UPs > 0, no consolation prize
04 0A ADD AL, 10 ; award 10 coins
FINAL_SCORE:
3C 64 CMP AL, 100 ; is coin score over 100?
72 01 JB DONE ; if not, no extra 1UP
43 INC BX ; otherwise, increment 1UP
DONE:
```
Input starting coin count in `DX`, `SI` pointing to start of "icon" bytes (which can be `'1'`-`'5'`, or any byte value). Output the number of 1UP's in `BX`.
**Explanation:**
The input of four bytes is iterated and compared to the remaining bytes to the right, counting the number of matches. The scores for each type of match are awarded and add up to the total. Since a four-of-a-kind is also three-of-a-kind and also a one-pair, the value of each score type can be decomposed as follows:
* 3 matches = 4 1UP's + 77 coins
* 2 matches = 2 1UP's
* 1 match = 1 1UP
***Examples:***
`[2, 2, 2, 2]` (four-of-a-kind) = 7 1UP's + 77 coins
```
2 [2, 2, 2] = 3 matches = 4 1UP's + 77 coins
2 [2, 2] = 2 matches = 2 1UP's
2 [2] = 1 match = 1 1UP
```
`[2, 5, 2, 2]` (three-of-a-kind) = 3 1UP's
```
2 [5, 2, 2] = 2 matches = 2 1UP's
5 [2, 2] = 0 matches
2 [2] = 1 match = 1 1UP
```
`[4, 5, 5, 4]` (two pair) = 2 1UP's
```
4 [5, 5, 4] = 1 match = 1 1UP
5 [5, 4] = 1 match = 1 1UP
5 [4] = 0 matches
```
`[2, 3, 4, 3]` (one pair) = 1 1UP
```
2 [3, 4, 3] = 0 matches
3 [4, 3] = 1 match = 1 1UP
4 [3] = 0 matches
```
If number of earned 1UP's is 0 at the end, 10 coins are awarded. If total coins are greater than 100, an additional 1UP is awarded.
Here is a test program for PC DOS that includes extra routines to handle the integer value I/O:
[![enter image description here](https://i.stack.imgur.com/0XZfJ.png)](https://i.stack.imgur.com/0XZfJ.png)
Download and test [LUCKY.COM](https://stage.stonedrop.com/ppcg/LUCKY.COM) for DOS.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23 22 20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (use `³` in place of `ȷ2`) also used in newer version twice
-1 thanks to [Grimy](https://codegolf.stackexchange.com/users/6484/grimy) (subtract one before summing instead of subtracting four afterwards)
Maybe beatable?
```
ċⱮ`’SṚḌH׳«777»⁵+:³
```
A dyadic Link accepting a list and an integer which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8//9I96ON6xKC400e7pz1cEePx@HphzYfWm1ubn5o96PGrdpWhzb/Pzb58PJjk/9Hm@iAYSyXpSUA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9I96ON6xKC400e7pz1cEePx@HphzYfWm1ubn5o96PGrdpWhzb/Pzb56J7Dy/UfNa05OunhzhlAGoi8gTjyf3R0tKGOgomOgpGOgmmsjoIBEEdHG@soGIKFTIBcS1OwGJBnDFZpDOQaQcSAPFMwMkGIGYEFgKQR3DhDsHEgBFJmBLMCikBixphilpaxsQA "Jelly – Try It Online").
### How?
```
ċⱮ`’SṚḌH׳«777»⁵+:³ - Link: list a, integer n e.g. [x,x,x,x], 22
Ɱ` - map across a with:
ċ - count occurrences in a [4,4,4,4]
’ - decrement [3,3,3,3]
S - sum (call this s) 12
·πö - reverse (implicit toDigits) [2,1]
Ḍ - un-decimal 21
H - halve 10.5
³ - 100 100
√ó - multiply 1050
777 - 777 777
¬´ - minimum 777
⁵ - 10 10
» - maximum 777 (handles 0 -> 10)
+ - add (n) 799
³ - 100 100
: - integer division 7
```
How the hand evaluation works for each type of hand:
```
Hand: no-pair pair 2-pair trips 4-of-a-kind
(sorted) counts: [1,1,1,1] [1,1,2,2] [2,2,2,2] [1,3,3,3] [4,4,4,4]
decrement: [0,0,0,0] [0,0,1,1] [1,1,1,1] [0,2,2,2] [3,3,3,3]
sum: 0 2 4 6 12
reversed: [0] [2] [4] [6] [2,1]
un-decimal: 0 2 4 6 21
halved: 0 1 2 3 10.5
times 100: 0 100 200 300 1050
min(x, 777): 0 100 200 300 777
max(x, 10): 10 100 200 300 777
```
---
Alternative 20: `ĠẈị“¡ıKĖ‘S×4+E{»⁵+:³`
[Answer]
# [Zsh](https://www.zsh.org/), ~~117 ...~~ 60 bytes
***-13** by using a different criterion for differentiation, **-9** by combining cases, **-28** by changing the `case` statement to a nested arithmetic ternary, **-4** thanks to @JonathanAllan, **-1** by optimizing the ternaries, **-2** because I accidentally used `echo` when adding Jonathan's optimization.*
Takes coin count on stdin, and block inputs as arguments. Arguments can be numbers, characters, or even strings: `./foo.zsh flower leaf flower boomerang`
```
read c
for i;for j;((a+=i<j))
<<<$[!a?7+(c>22):a-6?6-a:c>89]
```
Try it online:
~~[117](https://tio.run/##PY5BasMwEEX3c4oP1cJKCVQjmdaRE3qPkoWQVWwwNlRJCg06uzt2S/gIvXn6A/rJ/fLdD2PCVwodxmFKHt1M6RZG5HTBfg@1WorzMOWjMpT74fNC1bItRArHSt2rSb8XTTHkBHV/EnHVoZQHHsyBS8EwkWPdtq36iKe35uy93a2j8Z43zwJmBev97q/4@lzFk7yeKeUQFw2xUNtvqJuntLwABg6MmpoaVgaGI67lsuLtig61xJF0pSeHiVmaW4gt/kNN88Bf "Zsh – Try It Online")
[104](https://tio.run/##PY5Ra8MwDITf9SsO6od4pdDISddMadn/GH0wjkoMIYG6bLDS35452RiHuNPxCfSd@vmrj4Pipr7DEEcVdBPppx@Q9I7dDmZpKUxxTCdTUurj9U7FvB4Euk43qBSF357MY2Me728bo8@ntRR8UhiPONLetm1rPl63RTgz24vIYWmcyHFxFilXpBR5@UXD@dhcSJMPs0VuYNYHqJtGnfdAiQqMmpoaLi@MirjO5nLvllihzqoos5nLw8ScyVXEDn@ipvmPPw "Zsh – Try It Online")
[95](https://tio.run/##PY1Ri8JADITf8ysG3IfuSTmbtmptlfsfhw/LNqULpQVXFE787b1Yj2MImfmYkJ/Yz/c@DIKLuBZDGKVGO5Hc3IAoV6QpzIuSn8IYjyaj2IfuSsm8HHjqpgukThK3PprHyjy@Disjz6e15F0UGIcw0sY2TWO@d@vEn5jtua4zfiN/2lcaP95pm7pPPpNE52cLRTDLX2qnUeYNkKEAo6SqRK6BURCXunLl@csWKFUFaVd7OkzM2lxEnONPVFX/9hc "Zsh – Try It Online")
[67](https://tio.run/##PYzdCoJAEIXv5ykOuBe7iJSjVv708x7RxaIbCqKQUpD47DZJxGGYM4fvzHuol1fdtA4PZyu0TedyVD25p20xuBFBAPVNqeybbjiqkIa6uY@kl7VQ0r1/wOVaW/@oJk9Nl8xTbp6NoaIo1NWetQ1CPu8Cu@GsPB1Sk@19XZ6YzW0xEAhq/U1V37llC4SIwUgoTRDJwYiJE1mR5NHXxkhEMQkrnAwTs5CriCP8RGn6tx8 "Zsh – Try It Online")
[63](https://tio.run/##PYzNCoNADITveYo5eNhFhBp/Wv8fpPSwrFtcERdUWujL21VKGZJMhi/5rMP@HuxksBjVY7KzqdA7Mi81YTUbogjBkZJ2dl6bIKZ1sM@NxH4eaHq6BbY6@lgJocLG1qOUZPTgENxVJ1SUd3mkSt3eClleQ6FbZvnYJeq6RnD@pd7NZr8AMVIwMioyJH5hpMSZH4nPk8OmyLxS8qznfDExe/IUcYKfqCj@9gs "Zsh – Try It Online")
[62](https://tio.run/##PYzbCoNADETf8xVT8EERocZL6/1DSh@WdWVXxAWVFvrzdpVShiST4SSfVe9vbSaFRYkek5lVhd6SeokJq9oQRfCOlKQ189p4Ma3aDBv5@3kgabALTHX0sfJ9ETamHoOAlNQW3uMiulvoy5Y5KEWUd3kkStnei@ceoK5reOdb6u2s9isQIwUjoyJD4hZGSpy5kbg8OWyKzCklxzrOFROzI08RJ/iJiuJvvw "Zsh – Try It Online")~~
**[60](https://tio.run/##PYzbCoNADETf8xVT8EGRhRovrfcPKX1YdMUVUVBpoT9vo5QyJJkMJ/ms/f7u7WiwGN1itJPJ0c5kXnrEajYoBedIqZnttJZOQGtvu43c/TxoqJsX2PzoQ@662i9tMXgeFUXhPC66vvluUzF7mVZJnSidNdU9fe4eBIBzPqV2nsx@BQJEYMSUxghlYUTEsYxQ8vCwEWJRRMIKJ8XELOQp4hA/UZr@7Rc "Zsh – Try It Online")**
Here's the magic from the 67 byte answer:
```
read coins
for block # for each element
(( a+=${#${@:#$block}} ))
# ${@:#$block} remove all elements which don't match
# ${# } count the remaining elements
# (( a+= )) add that number to the total
<<<$[a?(a-12?6-a/2:coins>89):7+(coins>22)]
# a? :7+(coins>22) 4*0 (all elements match all elements)
# (a-12? :coins>89) 4*3 (all elements match exactly one)
# (a-12?6-a/2 ) 3*1 + 1*3 -> 6, 6 - 6/2 -> 3
# 2*2 + 2*2 -> 8, 6 - 8/2 -> 2
# 2*3 + 2*2 -> 10, 6 - 10/2 -> 1
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~123~~ ~~106~~ 90 bytes
```
a=>b=>(a+("Ĭ̉Èd\n"[(b=b.GroupBy(x=>x,(o,p)=>p.Count())).Count()*(b.Max()==3?0:1)]))/100
```
A port of my python answer, which is derived from @Dat's answer.
[Try it online!](https://tio.run/##bY7PSsNAEMbvfYrS04wdY7KbHGrdFSwqhfbsofawG1MI2E3IH0j7BPouvoU99p3SSVGQRoYZvpkfM9/E5XVcpu1T7eK71FV0FvNHV2@Twtj3pBtq6oreq9YobZUGM4bR4ev4@f3x9upGK7DKes9FVucPO2iUbggyylHp3JtltasAEX/VFVhvaRpApeS9fxvgGvEm8P12OmCT4Qa6aig3hdmWQ25Wa8uX9mAQLE4HL0VaJYvUJbABnwIKSVCEF2ASkWQmKLwkIuKp5C35Lwm7e9izYQvOHhCCTc7RI5J@ovfa5A9pTw "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
lambda x,l:int([3,1,7.77,2,.1][sum(map(l.count,l))%14%5]+x/1e2)
```
[Try it online!](https://tio.run/##jZLdasQgEIWv41PMzUKkQzZqQpqFXPUxrBdpm9CFJIbowu7Tp675wUKglUHOjN8ZFR0f9lsPfG6r97mr@4@vGu7YXa6DjaVAhkVSFMgxYUqaWx/39Rh3yae@DRY7Sk8sO@Xq5X5mDaezbYx9q01joAJJwI1l9ipFkAwhQ@AIuVK4L6VerYXAUebOIhCYt2Shha2WKMD5E3eg8JuIf@EOzH386s4P8HRpnvuz8JAWR835cts1Qrw4wsVy0zVC/PUAL8s/caIIafUE25PAddi1uZBIuydq460iU@UCIcyZoiSaHLYXmesZjdPza2i6qWlXuqr2ZP4B "Python 2 – Try It Online")
I had the same idea as [GammaFunction](https://codegolf.stackexchange.com/a/190180/20260) to use `sum(map(l.count,l))` as a "fingerprint". But, instead of using an arithmetic formula on the result, I use a lookup table, first squishing the value to 0 through 4 using a mod chain `%14%5`. Dividing all the point values by 100 saved a few bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
def f(c,a):x=sum(map(a.count,a))//2;return[c//90,x-2,7+(c>22)][x//3]
```
[Try it online!](https://tio.run/##jZHbasQgEIav41PMpVJbTxu22SW96WOIFyFN6F5sDMZA9ulTaw61EGhlkH/G7x8d7B/@03Zqnj@aFlpc04pcpnIY7/he9bh6qe3Y@VAkjMmra/zoOl0zVnA6PUt6fsL1m5TE6IkxZWbfDP69GpoBStAIwlr2qDgFLSicKEgKuTF0P@JRrYXEUeTBoiiIaDmlFrFasgSX33gAVbxE/QsPYB7jV3d5gPOleR7fIlNaHTWXy7RrpPj5CFfLpGuk@OsBXhR/4sgg1FoH25fArdv1cEGZDV/U4q2iuQlBIc2FIShzAduLIvTMenfrPLZkU25Xtix/EjJ/AQ "Python 3 – Try It Online")
A Python port of my C port of my Bash port of my Zsh answer, re-golfed with help from the "Tips for golfing in Python" page.
Last port, I swear... I'm running out of languages I'm comfortable golfing in. I was curious how this strategy compared to the other Python answers. Again, there's probably some way to beat this.
This one turned out surprisingly good, so I added a table below summarizing what's happening so others can port or improve this.
```
Type Example map(a.count,a) sum(__) x=__//2 x//3 array lookup
----------------------------------------------------------------------------
none [1,2,3,4] [1,1,1,1] 4 2 0 c//90
pair [1,1,2,3] [2,2,1,1] 6 3 1 x-2 -> 1
two pair [1,3,1,3] [2,2,2,2] 8 4 1 x-2 -> 2
3-of-a-kind [1,3,1,1] [3,1,3,3] 10 5 1 x-2 -> 3
4-of-a-kind [3,3,3,3] [4,4,4,4] 16 8 2 7+(c>22)
```
## [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 63 bytes
Praise the `:=` walrus!
```
lambda c,a:[2+c//90,x:=sum(map(a.count,a))//2,9+(c>22)][x//3]-2
```
[Try it online!](https://tio.run/##jZHdasQgEIWv41PMpbLTmuiGbgL2po9hvbDphl1oYkiysH361JqfWgi0MsiZ8Tujg93neHGtPHX9VKvX6cM2b@8WKrSlFoeK8yLFe6mGW0Mb21H7WLlbO6JljHOBxYFWz0Iwo@@cS/MgpvE8jC92OA@gQBPwa96DShF0hnBEEAi5MbgdpUEthchR5N4iEbJgOcaWbLEkES6@cQ/KcIn8F@7BPMSv7mIHT@fmeXiLiGm511zM0y4R4097uJwnXSLGTzt4UfyJE0NI7XpYvwSu7aaHkiTOf1FN14pOjQ@EOM8MI0nvsa2Y@Z5J11/bkTq2qn5TTqmfhE1f "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~48~~ 44 bytes
```
{*/100+((0,0,1,3,7.77)[.Bag{*}].sum||.1)+|0}
```
[Try it online!](https://tio.run/##jdDPa8IwFAfw8/pXvNO0Ns3yozXKUNhgtx12cZfSQ9FWyzSRxiGi/u1dkrpawcH6IKSPx4eX7zav1sN6c4DHAib1cfBECQn6fYIIoogjgYXwE/yaLY@Dc4r19@Z0wtQPTuRcF6qCdSlzPZ3ivaoWGo7eg84OUPRxQlP89vny7psrSX0EPeghwAlLn71zDUDAfAlFEWIoTu2P6wBIBZtsN1/lGiCc2nYAQAlM3DlXpdS2L9VuVcqlB@PYSdxsy1DkJHpXMoO/EiXxVaKzDw9YozDz4gjxrqJkDtusrOzdTDOrmIiswv5QIhSbanZhjbLbK6fojsKcwroKs8olG5OLeRFzCm8UHqoizMKvUi7abLhT7Nkq3O3CLgm7copolOhWMYMBCCGMIsbjqyKcwi/punLK6L7CW2XU3WVkFcP@TzGDrSKGN8oP "Perl 6 – Try It Online")
Curried function `f(icons)(coins)`.
[Answer]
# [Python 2](https://docs.python.org/2/), 96 91 89 bytes
*-2 bytes thanks to @Kevin Cruijssen*
```
lambda x,a,b,c,d:(x+(100*sum((a==b,a==c,a==d,b==c,b==d,c==d))or 10)+177*(a==b==c==d))/100
```
[Try it online!](https://tio.run/##Xc3LCsIwEAXQvV/RZdJeME9Khf6Jm6SlKNgHtUL9@jgJiqEMcxlOwszy3m7zpMLQXsPDjb53xQ4Hjw79he0Vk0KUz9fImGtbD4ouRg8fJx@njoLzeS2k4JWs6zJ9pefkZ1oQlvU@bWxgAhIGCpbz088aC02sYI6oD6gsgaYF@ogmbs1QxBvUuSlFV1LlqPGt/Hjzx/AB "Python 2 – Try It Online")
[Answer]
# PHP, ~~153~~ 127 bytes
*@640KB* made some really clever changes to shorten it further:
```
function($c,$s){for(;++$x<6;$n+=$m>3?777:($m>2?300:($m>1)*100))for($m=!$y=-1;++$y<5;$m+=$s[$y]==$x);return($c+($n?:10))/100|0;}
```
[Try it online!](https://tio.run/##dY5da4MwFIbv/RVZOTAz05kPM2lj5g/pelHEYmlNxA@odPvtLgYGg2W8uTjhyXPydk23FGXXdFGUpugyPg/IXk8zGi2ahhqdjDvWzK2dBnSeTDVerIngppefSwwVgQE/zraPVZLAvXhTYBIN7bso8zzfx27ipaDUTwy/MEoxXp9Dq59g1lu2enMhFbTOGw4wH7WGO1Z9PU79@kMSgyn3zHmpsz@p@lpUFCFUV41FcIspQQdGMsKJPOLXzYfZqF90Jx0WhDmcBTBfMSfC@eI/nBHpErKpl6XbzUMy9818Qlj4Zj6h4ru/ePkG "PHP – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~126~~ ~~111~~ ~~108~~ 103 bytes
```
def f(c,a):x=sorted([a.count(i)for i in set(a)]);return([300,777,200,100,10][len(x)*(x[-1]!=3)]+c)//100
```
[Try it online!](https://tio.run/##jZLbboQgEIav5Smmd9DSLoc11m286mMQLoyLqUkjG2QT@/QW8VCamLRm1GH4/gHyc/vyH7aX03Q1LbS4oTW5jNVgnTdXrOqXxt57jzvSWgcddD0MxuOaaPLmjL@7HivJGC2Kgorw5/HV6tP0eCSPeFTPXD9UkuinhpxOYXryZvDv9WAGqEAhCM/yjRmjoDiFMwVBIdea7lMsZmshUZR5kEgKPErOqYSvkizBxYwHUMZF5L/wAOYxfnUXBzhbmudxLyKl5VFzsZx2jRQvjnC5nHSNFH89wMvyTxxphGZfN0tme3d7LiizwaIWbxUVfGWaQjrmmqDMBWwv8tAzu7kuXBpLtsztma2qnwGZvgE "Python 3 – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 78 bytes
```
lambda c,a:(ord("Ĭ̉Èd\n"[len(x:=[*map(a.count,{*a})])*(max(x)!=3)])+c)//100
```
Dat's answer, but golfed more.
[Try it online!](https://tio.run/##jZHPTsQgEMbP5SlwT1CJC2Ubt004@RjdHrDbxk220NCa1Bjv@i6@hR59p4r0z2LSRMmEfDP8voEJzVP3oBXfN2aoxGE4y/r@KGFBZIq0OaLN5/vX28fr8aA22blUqE9FFtayQfKm0I@qI8@hfME5DlEte9TjK8Ftdl3g7ZZROnRl293JtmyhgBmAdo27U5TAjBG4IzAiMM5zshxRp6aC50hia@EEMmfZ@RY2WQIPj35wC3J3Cf8XbsHYxa/u0QpOx@axe0vk03yteTROO4WP367hfJx0Ch/fr@BJ8icOcgAqbeD8JfCkFt2mIND2iyo0VzKa2yDQz1mOQWAsthSZ7Rk05qQ6pPGszKK0EJcED98 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 46 bytes
```
map$q+=$$_++,@F;$_=0|<>/100+($q>5?7.77:$q||.1)
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUClUNtWRSVeW1vHwc1aJd7WoMbGTt/QwEBbQ6XQztTeXM/c3EqlsKZGz1Dz//8kIOCytPiXX1CSmZ9X/F@3wA0A "Perl 5 – Try It Online")
First of input is the spin result, using any 5 unique ASCII letters, except `q` (I suggest `abcde`). The second line of input is the current coin count.
## How?
```
-F # CLI option splits the input into individual characters in @F
map
$q+= # $q holds the result of the calculation here
# possible values are 0,1,2,3,6
$$_ # This interprets $_ as a variable reference, thus if $_ is 'a', this variable is $a
++ # increment after adding it to $q
,@F; # iterate over the elements of @F
$_=0| # force the result to be an integer
<>/100 # divide the current coin count by 100
+($q>5?7.77 # if $q is over 5, then there must have been 4 of a kind
:$q||.1) # otherwise, use $q, unless it is 0, then use .1
-p # CLI option implicitly outputs $_
```
All of the numbers involved are divided by 100, so the program is counting the number of lives (including partial ones) currently earned. The trick to this solution is in the `map`. If the possible entries are `abcde`, then each of `$a`, `$b`, `$c`, `$d`, and `$e` hold the count of the number of times this character had previously been seen. That gets added to a running total (`$q`) each time a character is seen. The running total is bumped up if there is a four of a kind (effectively a 177 coin bonus).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 64 bytes
```
c=>a=>[,7.77,a.sort()[1]-a[2]?2:3,1,.1][new Set(a).size]+c*.01|0
```
[Try it online!](https://tio.run/##XY9NboMwEEb3nGIWXUA7QWBANImcHqJLy1Isx7RUFEfg/qgpZ6djB6QqmoVHz988e97Upxr10J7dprcnMzd81vyg@EFgndY1qnS0g4sTkcuNEkw@sV2BOaa5FL35gmfjYpWkY/tj5IO@T7P8N5s748CZ0Y3AQUQAAiBDEDmWyLCSCJnEgLcVYa9jWBLOF8w8ZlhQvrjFJVZUPs0WHNzkJQkhKNY0C0@GIlyvuAhPhiL8uP5ke4MjuY@ixg4Q@22Etm0/IrTa@sN8n4125iTBNtdNE7iQx0eVdh@qo82bOAwlcRhK9nTvG9uZtLMv8XGV7ODusvYTLvMeXjtC78rp1/8x4JwvwelI5mn@Aw "JavaScript (Node.js) – Try It Online")
I figured there had to be at least one JavaScript answer to an Arnauld challenge!
The concept here is mainly to use the number of distinct elements as a lookup key.
* 1 unique => 4 of a kind
* 2 unique => 2 pair or 3 of a kind
* 3 unique => 1 pair
* 4 unique => no matches
In order to distinguish between 2 pair and 3 of a kind, the input array is sorted and the middle 2 elements are compared.
[Answer]
# [PHP](https://php.net/), ~~89~~ 84 bytes
```
foreach(count_chars($argv[2])as$a)$b+=[2=>1,3,7.77][$a];echo$argv[1]/100+($b?:.1)|0;
```
[Try it online!](https://tio.run/##jdLBjtowEADQe75iFOVAhFliBxqyKaA9tGqllYq06imNkEkNSQs2is320Pbb07GXBDggFUtWYnvejIccq2P7fnmsjp4XGKGNhjnkHuQQEYCckglhZFoQiAAnGI8BQCo4cFNWQgOMFoBbQwAaYaCdS1VLbdelMlUtd9ZKpwTymFC0JsjQu1Y67S0aTS8W/bqyDrMOIzFWFd86Sgo48rrBR3ueWYdGzmF3nAmZ4rD1sItjfinn6CuHOYddO@zNcT3C/uC9GBLxxYlHajvio5@1/N73KHaOnXsnPtfDiO21G0gkF2dy6zCGTpIk6CRpenGSsxO7PruBxOy@E/fO7Lqe2ZuTpv/pYA29k7y7dYrM87aqEbysBnD@trjGJwjht@c5UNeH054bgZGHA0dzX@MfiVHgzuOhgDe715wWmCEweYRot8bs2g/MOMANWoSZNUVZqT6GgP/N@KQ/795hvgDfKmqz1oY3ZhBmbVdnqU7SrMuKN3rQRYVcBzwMNsN5zuYLij1JHpKkyANeZDZdl22M39twEGyWjw80/BNlrS0US8Q8O2HW2/1JV5irK7IrDebuZnibJfirp5cXHx7B//j0@Rm3V59W6w9fnrNzuxqhhQEhX@tGyYOQBpdPEtewWCefXza2GX/bNk3bGH//AA "PHP – Try It Online")
Input from command line, output to `STDOUT`:
```
$ php lucky.php 99 3333
8
$ php lucky.php 0 2522
3
$ php lucky.php 0 abaa
3
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
¿^∩û:¶á☺ⁿ£z⌐└≤♂EM¥t(,5╓
```
[Run and debug it](https://staxlang.xyz/#p=a85eef963a14a001fc9c7aa9c0f30b454d9d74282c35d6&i=++0++++[1,4,2,5]%0A+95++++[3,1,2,4]%0A+25++++[2,3,4,3]%0A+25++++[4,5,5,4]%0A++0++++[2,5,2,2]%0A+22++++[1,1,1,1]%0A+23++++[3,3,3,3]%0A+99++++[3,3,3,3]&a=1&m=2)
This program uses any arbitrary set of 5 integers for icons.
### Procedure:
1. Add up the number of occurrences of each element.
2. Divide by 2 and then mod 7.
3. The result is a number from 1..5. Use this to look up the coin prize in a fixed array.
4. Add to the initial coin count.
5. Divide by 100.
Here's the output from an experimental stack state visualizer I've been working on for the next release of stax. This is an unpacked version of the same code with the stack state added to comments.
```
c input:[2, 3, 4, 3] 25 main:[2, 3, 4, 3]
{[#m input:[2, 3, 4, 3] 25 main:[1, 2, 1, 2]
|+ input:[2, 3, 4, 3] 25 main:6
h7% input:[2, 3, 4, 3] 25 main:3
":QctI*12A"! input:[2, 3, 4, 3] 25 main:[300, 777, 10, 100, 200] 3
@ input:[2, 3, 4, 3] 25 main:100
a+ main:125 [2, 3, 4, 3]
AJ/ main:1 [2, 3, 4, 3]
```
[Run this one](https://staxlang.xyz/#c=c+++++++++++%09input%3A[2,+3,+4,+3]+25+main%3A[2,+3,+4,+3]+%0A%7B[%23m++++++++%09input%3A[2,+3,+4,+3]+25+main%3A[1,+2,+1,+2]+%0A%7C%2B++++++++++%09input%3A[2,+3,+4,+3]+25+main%3A6+%0Ah7%25+++++++++%09input%3A[2,+3,+4,+3]+25+main%3A3+%0A%22%3AQctI*12A%22%21%09input%3A[2,+3,+4,+3]+25+main%3A[300,+777,+10,+100,+200]+3+%0A%40+++++++++++%09input%3A[2,+3,+4,+3]+25+main%3A100+%0Aa%2B++++++++++%09main%3A125+[2,+3,+4,+3]+%0AAJ%2F+++++++++%09main%3A1+[2,+3,+4,+3]+&i=++0++++[1,4,2,5]%0A+95++++[3,1,2,4]%0A+25++++[2,3,4,3]%0A+25++++[4,5,5,4]%0A++0++++[2,5,2,2]%0A+22++++[1,1,1,1]%0A+23++++[3,3,3,3]%0A+99++++[3,3,3,3]&m=2)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 72 bytes
```
O`\D
(\D)\1{3}
777¶
(\D)\1\1
300¶
(\D)\1
100¶
\D{4}
10¶
\d+\D*
$*
1{100}
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3z8hxoVLI8ZFM8aw2riWy9zc/NA2KD/GkMvYwADO5TIEc2Jcqk1qgWwQM0U7xkWLS0WLy7AaKFn7/7@bs0@IAZeTm4@zpSmXj5Ozk5Epl3NIiDOQ8gnx8THgcgMCIyMuJyAwMgZTlpYA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as 4 printable ASCII non-digits followed by the initial number of coins in digits. Explanation:
```
O`\D
```
Sort the non-digits so that identical symbols are grouped together.
```
(\D)\1{3}
777¶
```
Four-of-a-kind scores 777.
```
(\D)\1\1
300¶
```
Three-of-a-kind scores 300.
```
(\D)\1
100¶
```
Each pair scores 100, so two pairs will score 200.
```
\D{4}
10¶
```
If there were no matches then you still win!
```
\d+\D*
$*
```
Convert the values to unary and take the sum.
```
1{100}
```
Integer divide the sum by 100 and convert back to decimal.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes
```
(\D)\1{3}
777¶
w`(\D).*\1
100¶
\D{4}
10¶
\d+\D*
*
_{100}
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8jxkUzxrDauJbL3Nz80Dau8gSQiJ5WjCGXoYEBUCDGpdqkFsgGMVO0Y1y0uLS44quBcrX//7s5@4QYcDm5@ThbmnL5ODk7GZlyOYeEOAMpnxAfHwMuNyAwMuJyAgIjYzBlaQkA "Retina – Try It Online") Link includes test cases. Takes input as 4 printable ASCII non-digits followed by the initial number of coins in digits. Explanation:
```
(\D)\1{3}
777¶
```
Four-of-a-kind scores 777.
```
w`(\D).*\1
100¶
```
Each pair scores 100. The `w` takes all pairs into consideration, so that they can be interleaved, plus three-of-a-kind can be decomposed into three pairs, thus automagically scoring 300.
```
\D{4}
10¶
```
If there were no matches then you still win!
```
\d+\D*
*
```
Convert the values to unary and take the sum.
```
_{100}
```
Integer divide the sum by 100 and convert back to decimal.
[Answer]
# APL+WIN, 42 bytes
Prompts for icons followed by coin stock.
```
‚åä(.01√ó‚éï)+.1‚åà+/1 3 7.77√ó+‚åø(+‚åø‚éï‚àò.=‚ç≥5)‚àò.=1‚Üì‚ç≥4
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##TYxNCsJADIX3OUWWLaVjMz@ULryBHqJUKkJBoSsv0BapIojUe3gAF71JLjKm40YehPclea88NenuXDbHfVo1ZdseKs@353bD3d0AD33tebxEKqN5kn2cKOJxSFaEBnOV5/OU8PiJliFnHl5qzde3i4Mj7h5C1kuPr4HQokYHGdRgkMRbKJyAljKLBvQCFp3I/kDe5U2HCGEQaB3yQaDNHxTFFw "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~76 75 71~~ 70 bytes
***-4** thanks to @JonathanAllan, **-1** by rearranging the ternary.*
```
read c
for i;{ for j;{ ((a+=i<j));};}
echo $[!a?7+(c>22):a-6?6-a:c>89]
```
Bash port of my Zsh answer.
~~[Try it online!](https://tio.run/##PY3BioNAEETv/RV1kDCDDImtJjG6yYcse5gdRxwRB2JIDku@3W1lWYqmqovX9Led@@XVh9Hj7m2LMUy@RhvJP@2I2T9gDJK1JRfDNH8kGc196B6klu3AURfvCPUPVh/ElQpm2O1smmpdv@s3eddHJJ/2pqzJ@HY0ds8Xdz1X@nJKlbsy669Fo2kaJNsTauPklwOQoQCjpKpELgujIC7FcunzNRYoRQUJK5wME7OQm4hz/Imq6j/@Ag "Bash – Try It Online")
[Try it online!](https://tio.run/##PY1RC4JAEITf91dM4MMdIeWqlan1Q6KH67zwQjzIqIfot9sqEcMys8O37MUM7fhqfedwd6ZB53tXognknqbD4B6IY0RTSzb4fqijhIbWXx@kxvnA0jXc4cs3Jr@JK2WWtV/UN63LT/khZ9uA6GSOysQJHzexWfHeHnaF3m@Xyh6Y9XnUqKoK0fyDmtC7cQ0kyMDIqciRysLIiHOxVPp0ihlyUUbCCifDxCzkLOIUP1FR/OMX "Bash – Try It Online")
[Try it online!](https://tio.run/##PYzNCsJADITveYo59LCLFDRt1f5YH0Q8rNuVbildsKIH6bPXtIgMYSbDl9zM2M7v1vcOD2ca9H5wJZpA7mV6jO6JOEa0tGSDH8ZTtKOx9fcnqXk9sHQPD/jyg8U7caXM5uSrTutyKidytg2ILuasTLw/72NT2PqY6@KwUbZm1tdZo6oqROt/asLg5i2wQwpGRnmGRBZGSpyJJdInS0yRiVISVjgZJmYhVxEn@Iny/B@/ "Bash – Try It Online")~~
[Try it online!](https://tio.run/##PYxRC4JAEITf91dM4IMiQq5amZo/JHq4zhNPxAONeoh@u60SMSwzO3y7dzV3y6uzg8FkVIPBjqZA48g81YDZPBBF8NaWtLPjXHkxzZ1tH@Qv24Gm1k2wxRur9@K@r8LKln0QFJ/iQ0Z3Dt51p@pj6OsLc3BW0aE@ROqsL6f8tgQoyxLe9p4aN5plD8RIwcgoz5DIwkiJM7FE@mSNKTJRSsIKJ8PELOQm4gQ/UZ7/4xc "Bash – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~92 84 82 81 79~~ 78 bytes
***-1** by `x+=(..!=..)` **-5** by [returning via assignment](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c/106067#106067), **-4** thanks to Jonathan Allan by replacing `!=` with `<`, which saves bytes elsewhere, **-1** by rearranging the ternary.*
*From @ceilingcat: **-2** by declaring `i` and `x` outside the function, **-1** by setting `x=i` and decrementing `x` instead.*
```
i,x;f(c,a)int*a;{for(i=x=16;i--;)x-=a[i/4]>=a[i%4];c=x?x-6?6-x:c>89:7+(c>22);}
```
Another port of my Zsh answer. I'm unfamiliar with C golfing, there's probably another trick somewhere in here to reduce it further.
~~[92](https://tio.run/##VVDRaoQwEHzWr0ivHCR15UyM1/NS7/7AH7B5sDktoW0s9gqC@O12o@1B2cAw7DCzGRO/GjPPLTVQM@uuD7UaEYgt@B6GIlFt11Nl41ixISrqyu6kvvO4lVr1zfW7d2Q40yHm4ryPh504mtMhZ8fHiJqTEExN80dtHWXhGAb3l6a1riElOYSBT3l578zbV1XqSmpSEJQEIwcJArIJPEmBI5ErEZDiLl2JhAzntslQJlbCYZk/g2X@kzCY1HqA6azz@T48gRxdlpeAQLsU8twLfQVLJ6hKFMITKRGiiKHpZ4@rlm62l2e3AYJFLpZWw@/nrGZMhdP8Aw "C (gcc) – Try It Online")
[84](https://tio.run/##VVBBboMwEDzjVzipItllUbAxaYhL8gM@QH2gToistlClPVhCvJ2uoa0UjaXRaEcz3rXJ1dppapmFhrvu@7HRAxJ1pdiBL1Pd9jemXZJo7uOyqd1WmVXgjTLalv7EfCLkaZf4rTzY477gh6eY2aOUXI/TR@M6xslAoofzpXXdhVZ0T6JQ8Pre27evujK1MrSkaIkGAQok5CMEkYFAoRYhIcNZtggFOeJ/kqNNLkLAjL@AGfeCRKNePmB714X@UJ5CgSnzS0FiXAZFEYxh@/kc6Eo10jOtkOKYY@jnDUctW2/OL90aKN5wjnQGfpdzhnNNxukH "C (gcc) – Try It Online")
[82](https://tio.run/##VVDRaoMwFH3WrwgdhWRemcboatO0f@APuDy4tI7QLo5uDwHx292NboNxAofDOZybe036Zsw899RAx6z7euzkiESsyivwKpP9cKfSpqlkPlFda5@EPiBthZZG@RP1aXWqUr83x13N9s8JNUfOmZzm9846yuIxjh7Ol966C2nILo5C@ettMNfPttGt0EQRjERjDgI4lBMEUUCOQqyCQ4FesQoBJeLPKTHGV5HDgt@CBf9FHE1y/YAZrAvzw/AMamxZXgYc6wqo6xAMmy@nwFQmkQ6kQUoShqUfd7R6utmeX9wGCN5vqbQafpazmjEZT/M3 "C (gcc) – Try It Online")
[81](https://tio.run/##VVBBboMwEDzjV7ipItllUcEYGuKQ/IAPUB@oEyqrLVRpD5YQb6dr01aKxtJoNKNZ75rk1Zhl6ZmBjtvh@6FTExK1dVaCq1PVj1embJIo7uK6a@2j1AekrdTK1Hfu9BQzcxSC711SnsrE7c1xV6l5@ejswDiZSHR/vvR2uNCG7kjku1/eR/P21Ta6lZrWFCPRlIEEAcUMXuSQoZCrEJCjl69CQoH4dwqMiVVkEPBXEHArSDSr9QNmtIOf74enUGFLeCkIrMuhqnzQLx4ugalUIR1ogxTHHEs/r2j1bLM9Pw8boHi@UGk1/C5nNeeKzMsP "C (gcc) – Try It Online")
[79](https://tio.run/##VVBBboMwEDzDK6xUkXBZVDCGhjgkP@AD1AfqhGqV1FRpD5YQb6draCtVY2k0mtHsrk3yZsw8IzjVRwY6jvbrsVMj1lmp@uEeuTpVmCSKu7juWnyS@kC0lVqZ2p1cUp7KxO3NcVftn@PIHIXgaprfO7QRD8cweDhferQX1rBdGFA5e70N5vrZNrqVmtWMIsGYgQQBxQRe5JCRkKsQkJOXr0JCQfhzCoqJVWSw4LdgwX8RBpNaFzADWj/fD0@hopblpSCoLoeq8kF/ug8jpVJFdGANURxzKv24k9VHm@35xW6A0cctlajh5zjUnKtwmr8B "C (gcc) – Try It Online")~~
[Try it online!](https://tio.run/##VVDRaoQwEHzWrwhXDkzdUI3RnpfG@wN/wMuDzZ1laavl2oeA@O121bZQJjAMM8zuxokX5@YZwesuctBy7L/uWz12wy1C401aaBRCcy9M2@CDstXCe2W1M/7kRXEqhD@66lAeH@PIVVJyPc3vLfYRD8cwuLtcO@yvrGaHMKBu9vw2uNfPpraNsswwigRjCgok5BMsIoOUhNqEhIy8bBMKcsKfk1NMbiKFFb8FK/6LMJj0toAbsF/mL8MTKKllfQlIqsugLJfgej6FkVKJJnpiNVEccyr9uJHVRbv95dzvgNG/rZVo4ec4tJzrcJq/AQ "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~19~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
D¢<OR;т*777T)Åm+т÷
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/190171/52210), so make sure to upvote him!!
-2 bytes thanks to *@Grimy*.
Takes the list of icons as first input (being `[1,2,3,4,5]`), and the amount of coins as second input.
[Try it online](https://tio.run/##yy9OTMpM/f/f5dAiG/8g64tNWubm5iGah1tztS82Hd7@/3@0oQ4YxnIZGQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCceh/l0OLbPyDrC82aZmbm4doHm7NjdC@2HR4@3@d/9HRBjrRhjomOkY6prGxOgrRlqY60cY6hkC@CZhvBOQb6RgDVRjD@SY6pkAIkTcASZsClRtBpI1AxoEhhG8MMg4MIcZbIvFjAQ). (The test suite uses `T‚à+` instead of `TMI+`, which is an equal bytes alternative.)
**Explanation:**
```
D # Duplicate the first (implicit) input-list
¢ # Count the amount of occurrences in itself
< # Decrease each count by 1
O # Sum these
R # Reverse it
; # Halve it
—Ç* # Multiply by 100
777 # Push 777
T # Push 10
) # Wrap all three values into a list
√Öm # Get the median of these three values
+ # Add the second (implicit) input to it
т÷ # And integer-divide it by 100
# (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 88 bytes
```
(c,v)=>(Seq(777,300,200,100,0,10)((v.groupBy(x=>x).map(_._2.size+1).product-5)/2)+c)/100
```
[Try it online!](https://tio.run/##TY/RasMwDEXf/RWmTxJ13ViJCR2ksL0N9tYPCJmblows8RI3ZBv7dk/ZwphAQofLvUijq9oq9s8vtQvSyXoOdXce5b338lOIqWrl5Q4eu6BOYWi6KxZHhiKCUxPvcKrfIM9zlSaJIm7DvUwEmPR16G/@4R3m4jijfq08lLokPTYf9dag9kN/vrmws7gn3Drcszk@NWMAAVImSm5MRnaDQoE8WMbUUPaLtCClWfoPM2tX9cdLlmhVaYniWjFdorjW5MMfohbLkXyu519D28EFZl0aJXkSIoqvGL8B "Scala – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
≔⊘ΣEη№ηιηI⌊⁺∕θ¹⁰⁰∨⁻η∕²∨›⁸η⁹∕¹χ
```
[Try it online!](https://tio.run/##bUw9D4IwFNz9FQ3TI3kmgIuGSTHqQiRxJAwNNLTJs9UW@Pu1JYzecpf76iW3veHk/dk5NWp4cFrEAK/5DTX/gERWmVlPUag0AJlMy11jVfAq7ia4kTEWGpodXNWiBgFfZHmWhebTQq10CMJ4y4rVvVvBJ2HhGN@QneLtVsjjOF1Ret8WB2RtchFECbL/3HV@v9AP "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the number of coins and an array of any Python comparable values as icons. Explanation:
```
≔⊘ΣEη№ηιη
```
Shamelessly steal @GammaFunction's trick of computing half the sum of counts.
```
⁻η∕²∨›⁸η⁹
```
Subtract `2` from the sum, thus resulting in the values `0, 1, 2, 3` appropriately, but for 4-of-a-kind, divide the `2` by `9` first, resulting in `7.777...`.
```
∨...∕¹χ
```
But if the result is 0, then there were no matches, so replace it with `0.1` instead. (Using a literal doesn't help me here because I would need a separator.)
```
I⌊⁺∕θ¹⁰⁰...
```
Divide the initial coins by 100 and add on the winnings, then floor the result and cast to string for implicit output.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 32 bytes
```
AQ-@[+K2/G90J/sm/HdH2+9>G22)/J3K
```
[Try it online!](https://tio.run/##K6gsyfj/3zFQ1yFa29tI393SwEu/OFffI8XDSNvSzt3ISFPfy9j7//9oI1OdaBMdUyA0iY0FAA "Pyth – Try It Online")
Inspired by GammaFunction's solution. Takes input as `[coins, [icons]]`.
```
AQ # Q is the input. Set G := Q[0], H := Q[1]
[ ) # Construct a list from the following entries:
+K2/G90 # [0] (K:=2) + G/90 (/ is integer division)
J # [1] J:=
s # reduce on + (
m H # map entries of H as d on (
/Hd # number of occurences of d in H ) )
/ 2 # / 2
+9>G22 # [2] 9 + (G > 22)
@ /J3 # Take element at position J/3
- K # Subtract K (=2)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 bytes
```
param($n,$l)$r=@{2=100;3=300;4=777}[($l|group|% c*t)]|?{$_;$n+=$_}
+(($n+10*!$r)-replace'..$')
```
[Try it online!](https://tio.run/##bY7xToMwEIf/5ynqcnPtKAu0EMTZuPcwhhDs1KQCFlAT4NnxZIxpYi9tk6/f765V@alt/aKNGeGourHKbPZGoeBgGFh16IQKfH8vlcQzVHEcDw8UTP9sy7bq1yTfNuyxv@8g3UPhKkgHx6WYdwN/ewWWeVZXJsv1ZreDDRsHxzlQh@Di1OeE4KYBD7ngEWMX7ot/eMBJEiGXPEAe/ubihwsuMSEXLmYe8gjr4st5LvbGPmLhMfqnuVMt/Aa5nHzxx0eeJNN/pkLOSE/WpJveQX9VOm/0EyeQl69FjfdHZlpdE0UgPTlW161pEFzDcdbO1iSsgM6Ol@v3pSW7XaJ33jlH5yBbOcP4DQ "PowerShell – Try It Online")
Unrolled:
```
param($nowCoins,$values)
$groupCounts=$values|group|% count
$rewardedCoins=@{2=100;3=300;4=777}[$groupCounts]|?{
$_ # output matched only
$nowCoins+=$_ # and accumulate
}
$nowCoins+=10*!$rewardedCoins # add 10 coins if no rewarded conis
+($nowCoins-replace'..$') # truncate last two digits
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~114~~ 107 bytes
-7 bytes thanks to mazzy
```
param($n,$l)((((0,.1,1)[+($x=($l|group|% c*t|sort))[2]],2,3)[$x[1]-1],7.77)[$x[0]-eq4]+".$n")-replace'\..*'
```
[Try it online!](https://tio.run/##RY1BDoIwEEX3nIKYKi0MDS0QwoKTYBeEFF1UwIKRRDw7DkjC/NW8vPnTd29th7s2ZiFN8Vn6ylYPSloghlGcCLgAwcqAkqmgxMw32736@ezW/jgPnR0ZK6VSICFmJZlKoUKhIONZtq2RCvUzUcGJk/bEQqt7U9Xau3Lue8vXcS6kcaPIpQISrEjZBvLUpTEIBMkfSAT4AJ34AAmkmN1YO/AeT@RuyLV0yw7i1ZCHkefrly1s@QE "PowerShell – Try It Online")
A big ol' PowerShell-flavored ternary operation built upon grouping and sorting the counts of the input list. The sort is needed because we leverage the fact that the grouped list gets shorter the more repeats there are. In fact, here's all the possible values:
```
(1,1,1,1)
(1,1,2)
(2,2)
(1,3)
(4)
```
Truncating to an int is still expensive.
Unrolled:
```
param($n,$l)
$x=$l|group|% c*t|sort
((( #Start building a list...
(0,.1,1)[+$x[2]], #where spot 0 holds dummy data or handles no match and 1 pair
2,3)[$x[1]-1], #Overwrite the dummy data with 2-pair or 3-o-k
7.77)[$x[0]-eq4] #OR ignore all that and use spot 1 because it's a 4-o-k
+".$n" #Use that value and add CoinCnt via int-to-string-to-decimal
)-replace'\..*' #Snip off the decimal part
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
‚åä{,.1,1,2,3,,,7.77}[[Total[Counts@#2^2]/2]]+.01#‚åã&
```
[Try it online!](https://tio.run/##TY1LCsIwFEXnXUUh0InPfl5aSgdKwA04cBYiBLFYsC1oHIVsQLvKbiTmAyJ3dLiXc0epbtdRquEibb@z6/LWkFdQAQIFgDZvW8P5aVbyzg/za1JPRvCMokAhNnlZkXX5ZPb4GCbFyXbfM0ZEVjCd6DIF7TU1NMZAorsGNA3iOjA69ic10B@7rUvsS0hd37g9xh69LyQy9b6Q6O/@ODH2Cw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# R, ~~102~~, ~~91~~, 81 bytes
```
f=function(b,v,s=table(v))(477*any(s>3)+b+10*all(s<2))%/%100+sum(s==2)+3*any(s>2)
```
Managed to drop 11 bytes (and fix a bug) thanks to @Giuseppe.
Managed a further 10 inspired by by @Giuseppe's /10 idea.
Ungolfed
```
f=function(b,v){
s = table(v) #included in fn inputs
a = b+10*all(s<2) #covers all different case
a = a+477*any(s>3) #Covers 4 of a kind
d = sum(s==2)+3*any(s>2) #covers 1 and 2 pair, 3 of a kind.
a%/%100+d #sum appropriate values
}
```
[Try it online!](https://tio.run/##TY1RCsMgEAX/e4/AblyorkoI1N4lCRUK1kJNAjm9tVpomb9h9u0rZ@/8Fpf1/oww007JrdMcbrAjghmGfooHpKtGMQsl@ykESBdG7M6dklKk7QHJOUahvyVj9iBpAUWGmCziycNoi9CkijBV8Ecw6dLonzBkC62QNbDlglvAdbPShK6blfZk/Bf5DQ)
[Answer]
# 8051 Assembly (compiles to 158 bytes)
This is a VEEEEEEEEEERRY naive approch, this is yet untested and ungolfed but im pretty confident that works. Things to consider are:
1) the 8051 is an accumulator machine ie. it needs mov instructions that other architectures may not need at all.
2) the 8051 is an 8bit machine therefor there has to be done some trickery for the numbers >255 which makes for more code and is therefor a disadvantage of the platform over the others.
```
CSEG AT 0000H
coinStackOnes equ 0xf3
coinStackTens equ 0xf4
coinStackHundreds equ 0xf5 ; leave one byte as guard so that if that gets corrupted it doesnt really matter
values1 equ 0xf7
values2 equ 0xf8
values3 equ 0xf9
values4 equ 0xfa
numOfFlowers equ 0xfb
numOfLeaf equ 0xfc
numOfBell equ 0xfd
numOfCherry equ 0xfe
numOfBoomerang equ 0xff
flower equ 1
leaf equ 2
bell equ 3
cherry equ 4
boomerang equ 5
numOfHeartsReceived equ 0xf1
mov r1, #4
mov r0, numOfFlowers
clearNumOfRegs: mov @r0, #0d
inc r0
djnz r1, clearNumOfRegs
;if you reach this all numOfXXXX registers are zeroed
mov r0, #values1
mov r1, #flower
mov a, #6 ; innercounter
mov b, #5 ; outercounter
checkfornextpossibleitem: mov r2, a; backup countervar
mov a, @r0 ; store given value in a
xrl a, @r1 ; xor a with item
jnz nextItem ; if value!=item -> nextitem
mov a, #numOfFlowers ;if you end up here a=0 (ie value == item) --> generate addr for numOfReg <-- load a with addr for numOfFlowers
add a, r1 ; since items are only numbers you can add the item to get the addr for numOfReg a=addr(numOfReg)
xch a, r1 ; change the item with the addr as r1 is indirect register
inc @r1 ; increment numOfRegister
xch a, r1; r1 = item
;next item
nextItem: inc r1 ; increment item
mov a, r2 ; restore counter
dec a; decrement counter
cjne a, #0, checkfornextpossibleitem
;if you reach this you have successfully tested one value against all items and therefor the next value must be tested
mov a, #6; reset the innercounter
dec b; decrement the outercounter
inc r0; increment the register that points to the value-under-test
xch a,b; cjne works with a but not with b therefor exchange them
cjne a, #0, here ; do the comparison; if you dont jump here you have tested all values
jmp howManyPairsDoIHave; if you didnt jump above you have the now the number of flowers and so on
here: xch a,b ; and change back
jmp checkfornextpossibleitem ; check the next value
howManyPairsDoIHave: mov r0,#0; store numOfPairsHere initialize with zeros
mov r1, numOfFlowers;
mov b, #6; use as counter to know when you went through all numOfRegisters
analyseNumOfRegister: mov a, @r1 ; load the numOfregister for some math
xrl a, #2; a will contain zero if numOfXXX = 2
jnz numOfXXXWasNot2; if you do not jump here you have 2 XXX therefor
inc r0; increment the number of pairs
jmp nextNumOfRegister; continiue with the next one
numOfXXXWasNot2: mov a, @r1; restore the number of XXX and try the next magic value
xrl a, #3; will contain zero if you have a three of a kind
jnz no3XXX; if you dont jump here however you have a three of a kind
jz add300Coins
no3XXX: mov a, @r1; restore number of XXX
xrl a, #4; a will contain zero if 4 of a kind
jnz nextNumOfRegister; if you numOfXXX!=4 you can only continiue trying to find something in the next numof register
jz add777Coins; if you didnt jump above how ever you will have to add the 777 coins as you detected a 4 of a kind
nextNumOfRegister: inc r0; move pointer to the next numofregister
djnz b, analyseNumOfRegister; if you havent already analysed all numofregisters then continue
; if you have however you end up here so you will have to take a look at the numOfPairs
cjne r0, #1, tryIf2Pairs; test if you have 1 pair if not try if you have 2
jmp add100Coins; if you have 1 pair however add the 100 coins
tryIf2Pairs: cjne r0, #2, youMustHave0Pairs; test if you have 2 pairs if not you can be sure to have 0 of them
jmp add200Coins; if you have 2 pairs however add them
youMustHave0Pairs: ; add 10 coins
inc coinStackTens
mov a, coinStackTens
cjne a, #10d, howManyHearts ; if your tens digit isnt outta range continue with the calculation of the number of hearts
inc coinStackHundreds; if it is outta range do correct that
mov coinStackTens, #0
jmp howManyHearts;
add100Coins: inc coinStackHundreds; here the digit can not possibly have an invalid value...
jmp howManyHearts
add200Coins: mov a, coinStackHundreds
add a, #2
mov coinStackHundreds, a
jmp howManyHearts ; also here no invalid values possible
add300Coins: mov a, coinStackHundreds
add a, #3
mov coinStackHundreds, a
jmp howManyHearts ; same again
add777Coins: mov r0, #coinStackOnes
mov r2, #3
add7: mov a, r0
mov r1, a
mov a, @r0
add a, #7
mov b, a; b contains the possibly invalid version of the ones digit
da a; if you have an invalid value its lower nibble gets corrected this way
anl a, 0x0f; and the higher one gets corrected this way
xch a,b; a and b must be swapped in order to make subb work ie b contains now the corrected value and a has the maybe faulty value
subb a,b; returns zero if all the corrections had no effect therefor the next digit can be increased by 7
jz nextDigit
inc r1
inc @r1
nextDigit: inc r0
djnz r2, add7;
howManyHearts: mov numOfHeartsReceived, coinStackHundreds
loop_forever: sjmp loop_forever
END
```
] |
[Question]
[
The matrix tornado is just like any other tornado: it consists of things rotating around a center. In this case, elements of the matrix instead of air.
Here is an example of a matrix tornado:
[![Matrix tornado in action](https://i.stack.imgur.com/e7ymY.jpg)](https://i.stack.imgur.com/e7ymY.jpg)
First we start by sectioning the matrix into square rings, each section consists of elements that are farther away from the border by the same distance. These sections will be rotated clockwise around the center. In real tornadoes, the severity increases towards the center, and so does the rotation step in a matrix tornado: the outermost section (the red one) is rotated by 1 step, the next (the yellow) one is rotated by 2, and so on. A rotation step is a 90° rotation around the center.
### Task:
Your task, should you accept it, is to write a function or program that takes as input a square matrix, apply the tornado effect to it and then output the resulting matrix.
### Input:
The input should be a square matrix of order `n` where `n >= 1`. No assumption is to be made about the elements of the matrix, they could be anything.
### Output:
A square matrix of the same order which would be the result of applying the tronado effect to the input matrix.
### Examples:
A matrix of order `n = 1`:
```
[['Hello']] ===> [['Hello']]
```
A matrix of order `n = 2`:
```
[[1 , 2], ===> [[5 , 1],
[5 , 0]] [0 , 2]]
```
A matrix of order `n = 5`:
```
[[A , B , C , D , E], [[+ , 6 , 1 , F , A],
[F , G , H , I , J], [- , 9 , 8 , 7 , B],
[1 , 2 , 3 , 4 , 5], ===> [/ , 4 , 3 , 2 , C],
[6 , 7 , 8 , 9 , 0], [* , I , H , G , D],
[+ , - , / , * , %]] [% , 0 , 5 , J , E]]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~100~~ ~~97~~ 96 bytes
-3 bytes thanks to [Graipher](https://codegolf.stackexchange.com/users/55479/graipher) by changing `rot90(a,axes=(1,0))` to `rot90(a,1,(1,0))`
-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) by removing a space
```
import numpy
def f(a):
if len(a):a=numpy.rot90(a,1,(1,0));a[1:-1,1:-1]=f(a[1:-1,1:-1]);return a
```
[Try it online!](https://tio.run/##jY9LU4MwFIX3@RXZOCGaKrRWLZ0ufNf3@8mwQAsWCwEj6PTX47ltFl246OL75t455M6hnFbjQneaJs3LwlRc13k5ZaM44YkTSZ/xNOFZrGmOBrNw3RRVz3Ui5SnHU66U/Sjw/JanSOEAzxZW2TdxVRvNoyYpDM94qnE4CMQwzrJChKH0S5Pqyskkmw@SsYUvWRB4irdDxXjQVdxd5oHYFYqLPdI@6YB0KGY3xBEtx6Qh6YR0ajOPljapQ9okdW22Rcs2aYfUI7k2W6OlRdogrZJWxLJVqSkVpZ6oqagiGs5PoyR1REUlzsA5uACXNr/CfA1uwC24A/fgweaPmJ/AM3gBryACbzZ/xzwCMUjABxiD1OafmCcgAznQoAClzb8wG/ANKlCDH/D77@83fw "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
≔EθSθWθ«≔Eθ⮌⭆觧θνλθθM¹⁻¹Lθ≔E✂θ¹±¹¦¹✂κ¹±¹¦¹θ
```
[Try it online!](https://tio.run/##ZU/JbsIwED3jr/DRlsKBc08pa0pCgbDf3GRwXFxnsROQEN8eHBYJ1MNoRm/VRAkropTJuna1FlyRgGUkd7CnstKEphCKE0odnNMPdEyEBExyis@o9S6fQwWFBnJ3PEDXeCqGE3luCykbJSl9JramVm7I7QzSCkjHwYFQpW4OHxQ3iSVpQ7/0hVJE0KRZ0QQ4M9ZnA5u5U4f/1KPwYv/87Pb6gyEaeV9jP5ig7@lsHi6WaLXebHfsB0Ux7Hki0O9B/qk0Q3mhTVkd63Ylrw "Charcoal – Try It Online") Link is to verbose version of code. Only works on character squares because Charcoal's default I/O doesn't do normal arrays justice. Explanation:
```
≔EθSθ
```
Read the character square.
```
Wθ«
```
Loop until it's empty.
```
≔Eθ⮌⭆觧θνλθ
```
Rotate it.
```
θM¹⁻¹Lθ
```
Print it, but then move the cursor to one square diagonally in from the original corner.
```
≔E✂θ¹±¹¦¹✂κ¹±¹¦¹θ
```
Trim the outside from the array.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes
```
J«þ`UṚ«Ɗ‘ịZU$LСŒĖḢŒHEƊƇṁµG
```
[Try it online!](https://tio.run/##y0rNyan8/9/r0OrD@xJCH@6cdWj1sa5HDTMe7u6OClXxOTzh0MKjk45Me7hj0dFJHq7Huo61P9zZeGir@////5UcnZxdXJV0lNzcPTy9gLShkbGJKZA2M7ewNADS2rr6WqpKAA "Jelly – Try It Online")
I think this could be far shorter.
```
Input: n×n matrix A.
J Get [1..n].
«þ` Table of min(x, y).
UṚ«Ɗ min with its 180° rotation.
Now we have a matrix like: 1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
‘ị Increment all, and use as indices into...
LС List of [A, f(A), f(f(A)), …, f^n(A)]
ZU$ where f = rotate 90°
Now we have a 4D array (a 2D array of 2D arrays).
We wish to extract the [i,j]th element from the [i,j]th array.
ŒĖ Multidimensional enumerate
This gives us: [[[1,1,1,1],X],
[[1,1,1,2],Y],
...,
[[n,n,n,n],Z]]
ḢŒHEƊƇ Keep elements whose Ḣead (the index) split into equal halves (ŒH)
has the halves Equal to one another. i.e. indices of form [i,j,i,j]
(Also, the head is POPPED from each pair, so now only [X] [Y] etc remain.)
ṁµG Shape this like the input and format it in a grid.
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~78 73~~ 72 bytes
*Thanks to nwellnhof for -5 bytes!*
```
$!={my@a;{(@a=[RZ] rotor @_: sqrt @_)[1..*-2;1..@a-2].=$!}if @_;@a[*;*]}
```
[Try it online!](https://tio.run/##Tc7JCsIwFAXQfb8ihUrSmMY2WqdQiPOwdGkpkoWCoKjVjUi/vYZLBTfn5XLD492P5aVf14Gffa5vY/WHGZvlu31BytvrVhJzGJPno3y5R5gnUvJIaTeMjVQhs8CvzidXaWNzrnlRuUUsEUqkIg4lNjAVyqu9My6f9h1qz8nccP/ohBJB6BTO4BwuqPAIIXSJtIJruIHbpk@QFOzCHkybvo80gEM4gnHTt5Ei2IEctujv9vT/9voL "Perl 6 – Try It Online")
Recursive code block that takes a flattened 2D array and returns a similarly flattened array.
### Explanation:
```
$!={ # Assign code block to pre-declared variable $!
my@a; # Create local array variable a
{
(@a=[RZ] # Transpose:
rotor @_: sqrt @_; # The input array converted to a square matrix
)[1..*-2;1..@a-2].=$! # And recursively call the function on the inside of the array
}if @_; # But only do all this if the input matrix is not empty
@a[*;*] # Return the flattened array
}
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~86~~ 81 bytes
```
f(f=@(g)@(M,v=length(M))rot90({@(){M(z,z)=g(g)(M(z=2:v-1,z)),M}{2},M}{1+~v}(),3))
```
[Try it online!](https://tio.run/##FY5BCoMwFET3PcUs/6ep@H@0akPAC@QEpYtS1C5KxSIuFHv1NN0Mw2MezPiY70sXJ59lWeyp9y0N3FIwi39172F@UmD@jHOT09YSb4FWs7If0opS93pZTpIIm7Bvuv9Tjt9lJzaWOQZ/FSgsCpTujAo1GkjuRCAKsZACUjo5QypIDWmgudPkKNRCC2h5O0zpRPwB "Octave – Try It Online")
I'm aware that recursive anonymous functions are not the shortest method to do things in Octave, but they're the most *fun* method by far. This is the shortest anonymous function I could come up with, but I'd love to be outgolfed.
### Explanation
The recursive function is defined according to [this](https://codegolf.stackexchange.com/a/164483/32352) [tips](/questions/tagged/tips "show questions tagged 'tips'") answer by ceilingcat. `q=f(f=@(g)@(M) ... g(g)(M) ...` is the basic structure of such an anonymous function, with `g(g)(M)` the recursive call. Since this would recurse indefinitely, we wrap the recursive call in a conditional cell array: `{@()g(g)(M),M}{condition}()`. The anonymous function with empty argument list delays evaluation to after the condition has been selected (although later, we see that we can use that argument list to define `z`). So far it has just been basic bookkeeping.
Now for the actual work. We want the function to return `rot90(P,-1)` with P a matrix on which `g(g)` has been recursively called on the central part of M. We start by setting `z=2:end-1` which we can hide in the indexing of M. This way, `M(z,z)` selects the central part of the matrix that needs to be tornadoed further by a recursive call. The `,3` part ensures that the rotations are clockwise. If you live on the southern hemisphere, you may remove this bit for -2 bytes.
We then do `M(z,z)=g(g)M(z,z)`. However, the result value of this operation is only the modified central part rather than the entire `P` matrix. Hence, we do `{M(z,z)=g(g)M(z,z),M}{2}` which is basically stolen from [this](https://codegolf.stackexchange.com/a/163110/32352) [tips](/questions/tagged/tips "show questions tagged 'tips'") answer by Stewie Griffin.
Finally, the `condition` is just that the recursion stops when the input is empty.
[Answer]
# [Python 2](https://docs.python.org/2/), 98 bytes
```
def f(a):
if a:a=zip(*a[::-1]);b=zip(*a[1:-1]);b[-2:0:-1]=f(b[-2:0:-1]);a[1:-1]=zip(*b)
return a
```
[Try it online!](https://tio.run/##hY/LTsMwEEX3/orZIMdpIpJAC3GVBe/SL6hkeeGKGFxFTmSFBfx84BZDqYTE5mjOzLU9Ht7Gl95X0/TUWrKJEZKRs2Skad7dkKRGSZmXWiy3315GV3klC9SNTQ4iljHxFd8KRqEdX4MnM9k@UEfOf76jFF@1XddzrYUcgvMjdYztC3YUKzOqdMZIzTMq/gvzK54RvwZugFvgju/P83vIA7ACHoF1nJWQCjgDzoF5nC0gF8AlUANFnM0gOXAKpMDJX39im0YpN9ulNWFjh42D8c9tUguNzu6o8/tbm5/Lpg8 "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 87 bytes
```
function(m,n=nrow(m)){for(i in seq(l=n%/%2))m[j,j]=t(apply(m[j<-i:(n-i+1),j],2,rev));m}
```
[Try it online!](https://tio.run/##jdDLTsMwEAXQvb/CEoo8Qx3aBMo7C94F5Q@ARXCTypVjF9cEEOLbQzo8lOyYxZF8fW1Z9m2VtdWLVUE7C7W0mfXuFWrEj8p50Fxbvi6fwWQ2GkcpYn2/lMvHLECxWpl36JansT4GG@tRgt2OTKUvG8ST@rPd4r838@C4crYpfeBGrwN3FW9KFZxfb7bqInj9xhbZ30tynLsdVRgD/knbucyRMZZnm7OgQMxKY5xAZBUsui4yVQQQ8c88WIG9dsIlT1Ey/j0Kpl0w@edhcSa6tjgnL8hL8kr0rxTXFN6QM/KWvBvWEgpTcpfcI6fD2j6FB@QheUROhrURhTE5JrfJqP81LdvMFw "R – Try It Online")
* credits to this [StackOverFlow answer](https://stackoverflow.com/a/16497058/316644) for the rotation code
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~25 24 23~~ 22
```
t"tX@Jyq-ht3$)3X!7Mt&(
```
[Try it online!](https://tio.run/##DcuxCsJAEEXRX7mKSCyEvJndbMI2qQP2AbGwS5EUwjR@/erpz/GOvbU4xzov3899C7/cfD2VR1y71p7CcBK5DhRGJtRXCRlylFCuGlBBI5qwvtr/GOZYwvLrBw "MATL – Try It Online")
Indexing in MATL is never easy, but with some golfing it actually beats the current best Jelly answer...
```
t % Take input implicitly, duplicate.
" % Loop over the columns of the input*
X@ % Push iteration index, starting with 0. Indicates the start of the indexing range.
Jyq- % Push 1i-k+1 with k the iteration index. Indicates the end of the indexing range
t % Duplicate for 2-dimensional indexing.
t 3$) % Index into a copy of the matrix. In each loop, the indexing range gets smaller
3X! % Rotate by 270 degrees anti-clockwise
7Mt&( % Paste the result back into the original matrix.
```
\*For an `n x n` matrix, this program does `n` iterations, while you really only need `n/2` rotations. However, the indexing in MATL(AB) is sufficiently flexible that indexing impossible ranges is just a no-op. This way, there's no need to waste bytes on getting the number of iterations just right.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~41~~ ~~39~~ 38 bytes
```
{s#(+,/'4(+|:)\x)@'4!1+i&|i:&/!s:2##x}
```
[Try it online!](https://tio.run/##PY/ZjoIwAEXf/YoKo4JooIgbvIwb4L7vY@KKIggKqBh1fp1RS@ap9@S2zT1a3NganqfwdxsnqBgd4QjqwZM/Lvkd4YKQUsMPlQ/TQZtncdx9eg5//5refi1eAa4wNzWBmCsLVRdc4SZY5OwZcKYElssXiiVRwgIAAEwuV6q1egNBs9XudHt9BIPhaDxZLBGs1htlu1MR7DX9YJhHBCfLds6XK0a@iMBO@9WgKedQZZnGQdfyCOxdd7JdFxA4i85YGRYRnHvt0aZVQnCp16qVsojgelSX/YaEkbPX8FgMkze6br6r//wuCAjY9/UkYD4jkgC@kQHs550vjH4UpZcwipBNcEkUU@lMlkGRitPRkC9DpaDoq8SzmbQvQnMJ1teIlmXJlwgxyUoJDYUQQIinBf@ceX8 "K (ngn/k) – Try It Online")
`{` `}` function with argument `x`
`#x` length of `x` - the height of the matrix
`2##x` two copies - height and width (assumed to be the same)
`s:` assign to `s` for "shape"
`!s` all indices of a matrix with shape `s`, e.g. `!5 5` is
```
(0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4)
```
This is a 2-row matrix (list of lists) and its columns correspond to the indices in a 5x5 matrix.
`&/` minimum over the two rows:
```
0 0 0 0 0 0 1 1 1 1 0 1 2 2 2 0 1 2 3 3 0 1 2 3 4
```
`i&|i:` assign to `i`, reverse (`|`), and take minima (`&`) with `i`
```
0 0 0 0 0 0 1 1 1 0 0 1 2 1 0 0 1 1 1 0 0 0 0 0 0
```
These are the flattened ring numbers of a 5x5 matrix:
`4!1+` add 1 and take remainders modulo 4
`(+|:)` is a function that rotates by reversing (`|` - we need the `:` to force it to be monadic) and then transposing (`+` - since it's not the rightmost verb in the "train", we don't need a `:`)
`4(+|:)\x` apply it 4 times on `x`, preserving intermediate results
`,/'` flatten each
`+` transpose
`(` `)@'` index each value on the left with each value on the right
`s#` reshape to `s`
[Answer]
# JavaScript (ES6), 99 bytes
```
f=(a,k=m=~-a.length/2)=>~k?f(a.map((r,y)=>r.map(v=>y-m>k|m-y>k|--x*x>k*k?v:a[m+x][y],x=m+1)),k-1):a
```
[Try it online!](https://tio.run/##ddHZboJAGAXge55ibsywzIiouDVg3NFXmHAxsWhbNqPGQNL46nhAbWhsJ/lIgHP4J8OXvMjT9vh5OPMkfQ@KYueokoVO7Fy5bEZBsj9/mG3Nca/heKfKZiwPqnpkOZ4cq5uL4@Y8dsPvmOe4cp7pmRvq4fgykiI2Ml/kPsuc2LA0jYXc0kay2KbJKY2CZpTu1Z2qECIE9YIoSqnvk9/LNOsvFU17U/5oW4y0fUZeFtp4axNGLJ8hSYTNSOtlyCNJRIuUH/p3DJ1QRqcwgzksaDW12qSBbq@cBEuYPCbSJYIr8GANm58SERzBIQygD9NnyUKwDR3ogl0rmQh2oVPuFmbPUg/BPgxgCK1aSUdwDR6sYP4sGQhyMEGHxv0nVKUGguWZlCe4gcX9bIob "JavaScript (Node.js) – Try It Online")
### How?
Given a square matrix of width \$W\$, we define:
$$m=\frac{W-1}{2}\\
t\_{x,y}=\max(|y-m|,|x-m|)$$
Example output of \$t\_{x,y}\$ for a 5x5 matrix (\$W=5\$, \$m=2\$):
$$\begin{pmatrix}
2 & 2 & 2 & 2 & 2 \\
2 & 1 & 1 & 1 & 2 \\
2 & 1 & 0 & 1 & 2 \\
2 & 1 & 1 & 1 & 2 \\
2 & 2 & 2 & 2 & 2
\end{pmatrix}$$
We start with \$k=m\$ and perform a 90° clockwise rotation of all cells \$(x,y)\$ satisfying:
$$t\_{x,y}\le k$$
while the other ones are left unchanged.
This is equivalent to say that a cell is ***not*** rotated if we have:
$$(y-m>k) \text{ OR } (m-y>k) \text{ OR } (X^2>k^2)\text{ with }X=m-x$$
which is the test used in the code:
```
a.map((r, y) =>
r.map(v =>
y - m > k | m - y > k | --x * x > k * k ?
v
:
a[m + x][y],
x = m + 1
)
)
```
Then we decrement \$k\$ and start again, until \$k=-1\$ or \$k=-3/2\$ (depending on the parity of \$W\$). Either way, it triggers our halting condition:
```
~k === 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
ṙ⁹ṙ€
ḊṖ$⁺€ßḷ""ç1$ç-ZUµḊ¡
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmPGneCyKY1XA93dD3cOU3lUeMuIO/w/Ic7tispHV5uqHJ4uW5U6KGtQOlDC/8fbnf//z9a3dHJ2cVVXUdB3c3dw9MLxDA0MjYxBTHMzC0sDUAMbV19LVX1WAA "Jelly – Try It Online")
>
> I think this could be far shorter.
>
>
>
*– [Lynn](https://codegolf.stackexchange.com/a/169682/41024)*
[Answer]
# [Haskell](https://www.haskell.org/), 108 bytes
```
e=[]:e
r=foldl(flip$zipWith(:))e
g!(h:t)=h:g(init t)++[last t]
f[x,y]=r[x,y]
f[x]=[x]
f x=r$(r.r.r.(f!).r)!x
```
[Try it online!](https://tio.run/##fY5LT8MwEITv/hWbKEg2KQUKtBDJB14thfIsUCDKIRA7MXWd4Dg08OeDW3quVqtv9jAzm8XllEnZNIyGUcCQpjyXicRcisL7FcVEmAwHhDCUOjgLDKFZkGKhhAFDfD@UcWlVhHhYt34iqpdYXBG1izjUVHtYtxeDuUPamjh1M4uFAgpJjgCKyoyNHinwoFJSKFZaxSF0j09Oz87dltsfXAwvLXc7e/sHlt3e4dGOpb@1vbnhRusjVgnLgG5v5Vtv82Ce66SE/wf6A7D1V6PrG7i9u38YPz7B8@Tl9S1@h4@E8TQT8DmVM5UX8KVLU33P3eYP "Haskell – Try It Online")
I used [Laikoni's transpose](https://codegolf.stackexchange.com/a/111362/3852) and modified it a little, to rotate an array 90°:
```
e=[]:e;foldr(zipWith(:))e.reverse
≡ e=[]:e;foldl(flip$zipWith(:))e
```
# Explanation
`r` rotates an array by 90°.
`(!)` is a higher-level function: “apply to center”. `g![1,2,3,4,5]` is `[1] ++ g[2,3,4] ++ [5]`.
`f` is the tornado function: the base cases are size 1 and 2 (somehow 0 doesn't work).
The last line is where the magic happens: we apply `r.r.r.(f!).r` on the middle rows of `x` and then rotate the result. Let's call those middle rows **M**. We want to recurse on the middle *columns* of **M**, and to get at those, we can rotate **M** and then use `(f!)`. Then we use `r.r.r` to rotate **M** back into its original orientation.
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
<./~@g`(|:@|.^:(1<@+>./@g=.#\.<.#\))}
```
[Try it online!](https://tio.run/##JYnBCoJAFEX3fsW1FqOUz9wkThpDRato0boiy1Enwgm1QrB@3aQW95wD99oFJvcOU5MHjBkDYikiDoYxJuD9HMJyt1l3IbkfkZ2slouWjtzyQjGakyuyiIZ7CnvY9ruzje2CsFLV/RY3MkGlEolz8/dL1TkehVPrsogT3d9PWVZKF4a85BqWIh@@jRlS/LL7Ag "J – Try It Online")
Independently solved, but this approach is very similar to Lynn's.
It is also one of the most perfect problems for J's little used "composite item" `}` (in gerund form) that I have come across.
[Answer]
# Java 10, ~~198~~ ~~192~~ ~~181~~ ~~174~~ 173 bytes
```
m->{int d=m.length,b=-1,i,j;var r=new Object[d][d];for(;b<d/2;){for(i=b++;++i<d-b;)for(j=b;j<d-b;)r[j][d+~i]=m[i][j++];for(i=d;i-->0;)m[i]=r[i].clone();}return r;}
```
-25 bytes thanks to *@ceilingcat*
[Try it online.](https://tio.run/##ndRrb5swFAbg7/sVR5WmwLg0ydbdXCp167bu0nRbdo/ywYCTmoLJjJOuithfz14ClVIJpKkSD5I5HNsc@ZDwFfeS@HITpbwo6IxLtb5HJJUResYjQaNqSHQeJiIyk@lkSpG1M8hshngJuArDjYxoRIoC2mTe0RrzUBxkfirU3Fy4YeANXOkmbMU16UCJq5uJ4ykuNsu1xcLDeH/I7HU1kEHoOMxx5GHshcyuHiVByJJ6qCcJ0py/chpkEzmdJI5TzyGDmEnPO@ozuwoEGjc/SnMlLJuVWpilVqRZuWH1xhfLMMXGm/2vchlThkpYY6OlmuMzuV2XwYjCWDvbRgnqANHu03XvuOf2XsBLOIFX8Bre9Eq3NeEUwbfwDt7DBziDUVfCOYIf4RN8hjF8ga9dCd8Q/A4/4Cf8Ag5hV0KEYAwCZjCHC5BdCQmCl5BCBgpyWHQl/EZQQwEGlrCCq165fb/cnq7/L/veqUjTfO9uyQN32L7NA7d/txlbTkFHIeqj4e6cgvYXiQYu0RAewiM46HrxMYJP4Ck8g37H0g6W82AfHsD9W7W/3dnbzth@/e4vgKNL/jQNUnXfTYw/V35kNWG7WXx8XRiR@fnS@As0l0mVleAf5C@NTP1jrfl14Zu8bjyL203FW7Ka7ZWbfw)
**Explanation:**
```
m->{ // Method with Object-matrix as both parameter & return-type
int d=m.length, // Dimensions of the matrix
b=-1, // Boundaries-integer, starting at -1
i,j; // Index-integers
var r=new Object[d][d]; // Result-matrix of size `d` by `d`
for(;b<d/2;){ // Loop `b` in the range (-1,`d/2`]:
for(i=b++;++i<d-b;) // Inner loop `i` in the range [`b`,`d-b`):
for(j=b;j<d-b;) // Inner loop `j` in the range [`b`,`d-b`):
r[j][d+~i]= // Set the `j,d-i-1`'th result-cell to:
m[i][j++]; // The `i,j`'th cell-value of the input-matrix
for(i=d;i-->0;) // Inner loop `i` in the range (`d`,0]:
m[i] // Change the `i`'th row of the input-matrix
=r[i].clone();} // to a copy of the `i`'th row of the result-matrix
return r;} // Return the result-matrix
```
`b` is basically used to indicate which ring we're at. And it will then rotate this ring (including everything inside it) once clockwise during every iteration.
The replacement of the input-matrix is done because Java is pass-by-reference, so simply setting `r=m` would mean both matrices are modified when copying from cells, causing incorrect results. We therefore instead have to copy the values in every cell one row at a time, without copying their reference (by using `.clone()`).
[Answer]
# MATLAB, 93 bytes
```
function m=t(m),for i=0:nnz(m),m(1+i:end-i,1+i:end-i)=(rot90(m(1+i:end-i,1+i:end-i),3));end;end
```
I'm sure this can be golfed some more somehow.
**Explanation**
```
function m=t(m), end % Function definition
for i=0:nnz(m), end; % Loop from 0 to n^2 (too large a number but matlab indexing doesn't care)
m(1+i:end-i,1+i:end-i) % Take the whole matrix to start, and then smaller matrices on each iteration
rot90( ,3) % Rotate 90deg clockwise (anti-clockwise 3 times)
m(1+i:end-i,1+i:end-i)= % Replace the old section of the matrix with the rotated one
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 128 118 115 bytes
-15 bytes from @ceilingcat
```
j,i;f(a,b,w,s)int*a,*b;{for(j=s;j<w-s;j++)for(i=s;i<w-s;)b[~i++-~j*w]=a[i*w+j];wmemcpy(a,b,w*w);++s<w&&f(a,b,w,s);}
```
[Try it online!](https://tio.run/##dVLbrpswEHyGr7CQesRlI@Hl0lYkX0J5wLRpQUoahVQkQpxfT8eGgzm9SN5E3p3ZmXHS7L43zfPZUVsc/ZoUDdQH7fkW1hSqYjz@vPrdoS@6/bDDZxQFutOi05pOoMrXNop2r104VIe6bMMh6qpiOH07NZfHvDAcgiKK@v3w8mIliul5wWVVK5of9TXsC3d0ncsVraPvfegPX86eBruOkT3fxEMcRFzgay@GQkTRI3AdUNb5fZ7f3@Z3zA3AbuWvwiMR@nX0gNt7oNc7E@ry69b7nqfvuNrb5Lqnuj37gTanRWpZygoHWuMopJgmUBBHkiSvlmaDxqkFp/3rqdKAmOLAwM3NUwa@7OWSK5xlLwkWE2nvo0hIpKsOE0OHrc7Cm3WYlAZYHQNXvNFJy7TCmXW0kGAUNLQICdcRWlNkaOSoj6hPxsrc/0xCxigQJdu@xAKZosCT@eo2pRRuU@t2UZ/dpqQ0wLo1cJVu3GZlVuH8yy0q2zpe3dLicuPOuKWNy80MPAmeBE@Cxxse698BPAaPwePMJDPRMsoQLbPRFqtztIyUBthoBq6yTbS8zCuc/0XT7z/HM@neJXv3/n8//1sgOza56I8865jBYrAYLIYIA57E9v8HVgJWAlYCkQTwxP7GOeV4iNw@xBJsfoiclAbYhzBwZeDT8zc "C (gcc) – Try It Online")
[Answer]
# Haskell, 274 bytes
`w` is the main function, which has the type `[[a]] -> [[a]]` that you would expect.
I'm sure a more experienced Haskell golfer could improve on this.
```
w m|t m==1=m|0<1=let m'=p m in(\a b->[h a]++x(\(o,i)->[h o]++i++[f o])(zip(tail a)b)++[f a])m'(w(g m'))
p m|t m==1=m|0<1=z(:)(f m)(z(\l->(l++).(:[]))(r(x h(i m)):(p(g m))++[r(x f(i m))])(h m))
t[]=1
t[[_]]=1
t _=0
h=head
f=last
x=map
i=tail.init
g=x i.i
z=zipWith
r=reverse
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 93 bytes
```
f=(a,k=0,L=a.length+~k)=>L?f(a.map((b,x)=>b.map((c,y)=>x<k|y<k|x>L|y>L?c:a[k+L-y][x])),k+1):a
```
[Try it online!](https://tio.run/##ddHbboIwHAbwe56iN6YgRUDF04aL50N4g6YXlaHbYGCmWSAxe3X2AbK4uJH8Lkq/j39T3uSnPPkfr8ezESfPQZ7vXVWy0LWY58pWFMSH84v@FWru2Hvaq7L1Lo@qumMpXuyqhc8yLNLH8JJBOvYuGbL@SPJQ94xM8FRoGgt1WxvJ3E/iUxIFrSg5qHtVIYRzug6iKKFCkN@Pad5uKpr2oPzRthlpC0buHrSx6xBGbMGQJNxhxLobck0SbpHiQ/@OoRPK6BRmMIcFLaeWh9TR7RWTYAmT60S6RHAFa9jA9qdEuIHgEAbQh2ldshFsQwe64NyUTAS70ClOC7O61EOwDwMYgnVTaiK4gTWsYF6XdAQNMKEJjeonlKUGgsWdFDe4hUV1N/k3 "JavaScript (Node.js) – Try It Online")
```
f=(
a, // Input
k=0, // Range Left
L=a.length+~k // Range Right
)=>L? // More than enough
f(
a.map((b,x)=>b.map((c,y)=>x<k|y<k|x>L|y>L?c:
a[k+L-y][x]// k+L=a.length-1
)),k+1)
:a
```
[Answer]
# [Haskell](https://www.haskell.org/), 144 bytes
```
import Data.List
k=transpose
v=init.tail
t[[o]]=[[o]]
t m=k.reverse.(head m:).(++[last m]).
k.((v.head$k m):).(++[v.last$k m]).
k.t.map(v).v$m
```
[Try it online!](https://tio.run/##LcpJTsQwEIXhvU9RamXhqKU6AJIXQDM3MzRDlEVBDDEesQv38QNBvXmL938jFaudmybjU8wMK2LCtSksrOJMoaRYtKjKBMPIZJzgrot9r/5XMHhlMeuqc9EoR00D@L0W5XLZOSp/uW9RgEUpK861seDbHag4k/nZIUZPSdYWa@MnTyaolE3ghpttzENZ7B8cro6OT@D07PxifXkF1ze3d/cPj7B5en55pTd4H/TH52jgyzofYoLvXPinbhfTLw "Haskell – Try It Online")
`v` cuts out center (rows). `map v` cuts out center columns.
`t` recurses into the tornado. `k` exposes columns as rows.
`(++[v.last$k m])` appends center of last column.
`((v.head$k m):)` prepends center of first column.
`k` flips rows out again.
`(++[last m])` appends last row unprocessed.
`(head m:)` prepends last row unprocessed.
`k.reverse` rotates matrix.
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 25 bytes
```
∧(⍜(↘⊙↻|≡⇌⍉)ׯ2.⊟.)⇡⌈÷2⧻.
```
[Try it!](https://uiua.org/pad?src=0_9_0__ZiDihpAg4oinKOKNnCjihpjiipnihrt84omh4oeM4o2JKcOXwq8yLuKKny4p4oeh4oyIw7cy4qe7LgoKZiBbWzFdXQoKZiBbWzEgMl0KICAgWzUgMF1dCgpmIFsiQUJDREUiCiAgICJGR0hJSiIKICAgIjEyMzQ1IgogICAiNjc4OTAiCiAgICIrLS8qJSJdCg==)
Fun problem.
```
∧(⍜(↘⊙↻|≡⇌⍉)ׯ2.⊟.)⇡⌈÷2⧻.
⇡⌈÷2⧻. # create range for each ring
∧( ) # fold over range and matrix, using matrix as accumulator
⊟. # create pair indicating how much to rotate matrix on each axis
ׯ2. # and another pair indicating how much to drop from each axis
⍜( | ) # call the left part, then the right, then the inverse of left
≡⇌⍉ # rotate matrix clockwise
↘⊙↻ # but only the interior
```
] |
[Question]
[
## Input:
A list of integers
## Output:
Put each digit (and the minus sign) in its own lane, in the order `-0123456789`, ignoring any duplicated digits.
## Example:
Input: `[1,729,4728510,-3832,748129321,89842,-938744,0,11111]`
Output:
```
-0123456789 <- Added as clarification only, it's not part of the output
1
2 7 9
012 45 78
- 23 8
1234 789
2 4 89
- 34 789
0
1
```
## Challenge rules:
* Any duplicated digits in the number are ignored.
* I/O can be in any reasonable format. Input can be as a list/array of strings or character-array. Output can be as a list of strings, characters, character-matrix, etc.
* Trailing spaces are optional.
* Any amount of leading or trailing new-lines are optional (but not in between lines).
* Input will always contain at least one integer
* You'll have to support an integer range of at least `-2,147,483,648` though `2,147,483,647` (32-bit).
* The input-list will never contain `-0`, `00` (or more than two zeroes), or integers with leading zeroes (i.e. `012`).
* If you language uses a different symbol for negative numbers (like an upper `¯`), you are also allowed to use that instead, as long as it's consistent.
* You are allowed to have a space delimiter between digits (so a line without 5 or 8 can be `- 0 1 2 3 4 6 7 9` instead of `-01234 67 9`), as long as it's consistent (and therefore there should also be a space between `-` and `0`).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
Input: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]
Output:
1
2 7 9
012 45 78
- 23 8
1234 789
2 4 89
- 34 789
0
1
Input: [4,534,4,4,53,26,71,835044,-3559534,-1027849356,-9,-99,-3459,-3459,-94593,-10234567859]
Output:
4
345
4
4
3 5
2 6
1 7
0 345 8
- 345 9
-0123456789
- 9
- 9
- 345 9
- 345 9
- 345 9
-0123456789
Input: [112,379,-3,409817,239087123,-96,0,895127308,-97140,923,-748]
Output:
12
3 7 9
- 3
01 4 789
0123 789
- 6 9
0
123 5 789
-01 4 7 9
23 9
- 4 78
Input: [-15,-14,-13,-12,-11,10,-9,-8,-7,-5,-4,-3,-1,0,9,100,101,102,1103,104,105,106,116,-12345690]
Output:
- 1 5
- 1 4
- 1 3
- 12
- 1
-01
- 9
- 8
- 7
- 5
- 4
- 3
- 1
0
9
01
01
012
01 3
01 4
01 5
01 6
1 6
-0123456 9
Input: [99,88,77,66,55,44,33,22,11,10,0,0,0,-941]
Output:
9
8
7
6
5
4
3
2
1
01
0
0
0
- 1 4 9
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
### Code:
```
v'-žh«DyмSð:,
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f@/TF336L6MQ6tdKi/sCT68wUrn//9oEx0FU2MgAUGmxjoKRmY6CuaGOgoWxqYGJkAxXWMLU0uwGl1DAyNzCxNLY1OgEl1LEAYRxiamSJQlkDKGqAWKmJkDNccCAA "05AB1E – Try It Online")
### Explanation:
```
v # For each element in the input..
'-žh« # Push -0123456789
D # Duplicate this string
yм # String subtraction with the current element
e.g. "-0123456789" "456" м → "-0123789"
Sð: # Replace all remaining elements with spaces
e.g. "-0123456789" "-0123789" Sð: → " 456 "
, # Pop and print with a newline
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
║V≡u╝─é╢
```
[Run and debug it](https://staxlang.xyz/#p=ba56f075bcc482b6&i=4%0A534%0A4%0A4%0A53%0A26%0A71%0A835044%0A-3559534%0A-1027849356%0A-9%0A-99%0A-3459%0A-3459%0A-94593%0A-10234567859&a=1)
It takes one number per line on standard input. It works by finding the target index of each character and assigning it into that index of the result. If the index is out of bounds, the array is expanded with zeroes until it fits. During output, `0` becomes a space. The rest are character codes.
Unpacked, ungolfed, and commented, this is what it looks like.
```
m for each line of input, execute the rest of the program and print the result
zs put an empty array under the line of input
F for each character code in the line of input, run the rest of the program
Vd "0123456789"
I^ get the index of the character in this string and increment
_& assign this character to that index in the original string
```
[Run this one](https://staxlang.xyz/#c=m++++++%09for+each+line+of+input,+execute+the+rest+of+the+program+and+print+the+result%0A+zs++++%09put+an+empty+array+under+the+line+of+input%0A+F+++++%09for+each+character+code+in+the+line+of+input,+run+the+rest+of+the+program%0A++Vd%09%220123456789%22%0A++I%5E+%09get+the+index+of+the+character+in+this+string+and+increment%0A++_%26+++%09assign+this+character+to+that+index+in+the+original+string&i=4%0A534%0A4%0A4%0A53%0A26%0A71%0A835044%0A-3559534%0A-1027849356%0A-9%0A-99%0A-3459%0A-3459%0A-94593%0A-10234567859&a=1)
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
*-1 byte thanks to [Laikoni](/u/56433).*
```
f l=[[last$' ':[n|n`elem`i]|n<-"-0123456789"]|i<-l]
```
[Try it online!](https://tio.run/##PY7BCoMwEER/ZRHBywbUJJoU/YoeQ8AcIobGVBqlF/89jS2U3TcszMLMYuLDep/SDH5Uypu4lxVUNxXOMFlv18npMwykIHXTUsa7XshCn24gXqfVuAAjbMd@319QwhG8Czbma86sZoO4PN@gGHLK8BpOse2wb1BQXjOGhAouL5M0ddsLJinvkMi8mRz3V5mVfr9@JbjU6QM "Haskell – Try It Online")
This challenge is digitist. D:
[Answer]
# JavaScript, ~~59~~ 58 bytes
Input & output as an array of strings.
```
a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))
```
---
## Try it
```
o.innerText=(g=s=>(f=
a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))
)(s.split`,`).join`\n`)(i.value="1,729,4728510,-3832,748129321,89842,-938744,0,11111");oninput=_=>o.innerText=g(i.value)
```
```
input{width:100%;}
```
```
<input id=i><pre id=o></pre>
```
---
## Original
Takes input as an array of strings and outputs an array of character arrays
```
a=>a.map(x=>[...`-0123456789`].map(y=>-~x.search(y)?y:` `))
```
```
o.innerText=(g=s=>(f=
a=>a.map(x=>[...`-0123456789`].map(y=>-~x.search(y)?y:` `))
)(s.split`,`).map(x=>x.join``).join`\n`)(i.value="1,729,4728510,-3832,748129321,89842,-938744,0,11111");oninput=_=>o.innerText=g(i.value)
```
```
input{width:100%;}
```
```
<input id=i><pre id=o></pre>
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~32~~ 12 bytes
*28 bytes saved thanks to @Adám and @ngn*
```
⊃¨⎕∘.∩'¯',⎕d
```
[Try it online!](https://tio.run/##ZVA7TgNBDO1zCnfbABr/xnbBYSJFoYkELTUFERJ0kThCqPYOe5S9SLAnQkLKjDze9ec9P29fDve71@3h@emyHt/3l/XjbTmvX6f1@P2wHn@mZZ7u8ndX2ct@s36eljMgGAWIkSs2WGZ2JjBxpGBC8HChDAe7iUADrLOZHutMmz8UAWUBGR6og2Una8uORFSNyi4zNjKXYO2FWFYPi/5zkY6vtRnp5ho3bIgEbKMJpIWjAXE0N6RqjZ5zeiiScfMKGEqDGMmUdoOXbFrPmHGQl2REGBspnkKxtCobmiqfLJEluZNWpZRzNc4PSdO0noE@0EpJtBvelO8OZtA7qEJui3N7hVPM11sbwV8 "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 13 bytes
Saved 4 bytes thanks to *Adnan*
```
vðTúyvyÐd+ǝ},
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/7PCGkMO7KssqD09I0T4@t1bn//9oQx1zI0sdE3MjC1NDAx1dYwtjIx1zEwtDI0tjI0MdC0sLEyMdXUtjC3MTEx0DHUMQiAUA "05AB1E – Try It Online")
**Explanation**
```
v # loop over elements y in input
ðTú # push a space prepended by 10 spaces
yv # for each element y in the outer y
y # push y
Ðd+ # push y+isdigit(y)
ǝ # insert y at this position in the space-string
} # end inner loop
, # print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
Anonymous lambda processing the array of numbers:
```
->a{a.map{|n|"-0123456789".tr"^#{n}",?\s}}
```
[Try it online!](https://tio.run/##FcFLDoIwEADQq5i6nZLOB2e6UA8CmNQFOwnhsyClZ6/hvWX/HnV8Vv9KOTW/NOdzOp0PSCztQy26Zlvc556n4uDdr6XUed/W29h1CEoRRMlaDODZmEDFkCITgkUTAh/ZVAQC4GUY6h8 "Ruby – Try It Online")
Alternatively, a completely Perl-like full program is much shorter. I'd say `-pl` switches look quite funny in this context:
# [Ruby](https://www.ruby-lang.org/) `-pl`, 29 bytes
```
$_="-0123456789".tr"^#$_"," "
```
[Try it online!](https://tio.run/##FcE5DoNADADA3q@IDCUbrQ@wXfAVkNJFigLiKPJ5HDGzna9fZjuPWCqxaD@YBz6PDaemnbHDB2YSGAeosfdUoYgLg6kThzCBhytDCXFThQp0u5b1eC/fPcv6@QM "Ruby – Try It Online")
Finally, the following is possible if it is acceptable for the output strings to be quoted:
# [Ruby](https://www.ruby-lang.org/) `-n`, 27 bytes
```
p"-0123456789".tr ?^+$_,?\s
```
[Try it online!](https://tio.run/##FcE7DoMwDADQ3adAiA1SxR9qe8pFUCt1YwmI0KGXx6jvHd/PL2LvU0ZimZ9q3j/OoyuvcXhPZWkRCEoOomQzZkhsTKBiSM6EYG5CkJxNRSAD/l3bfq5bbZHqDQ "Ruby – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
* Thank to @Andrew Taylor for reducing the join (8 chars)
* Thank to @Yair Rand for X.match (8 chars)
```
a=>a.map(X=>"-0123456789".replace(/./g,x=>X.match(x)?x:" "))
```
[Try it online!](https://tio.run/##PY7NCsMgEIRfpXhSquZHN4kF09cIlB7E2rQljSEJxbe3JoUyO3PZgW9e5mMWOz@nlY3@5uJdR6Nbw99mwp1uEcuLUkio6kYhPrtpMNbhjGc9DbrtUm21DxzIOZzQARESrR8XPzg@@B7f8UVSEJJuAkHLitYFbQTkUlImANT2ZEVe1o1UAirKVLrkRPynSin21m8HqOu@LvHDESUmiV8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
Input & output as an array of strings.
```
£Ao ¬i- ®iS gXøZ
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=o0FvIKxpLSCuaVMgZ1j4Wg==&input=WyIxIiwiNzI5IiwiNDcyODUxMCIsIi0zODMyIiwiNzQ4MTI5MzIxIiwiODk4NDIiLCItOTM4NzQ0IiwiMCIsIjExMTExIl0KLVI=)
---
## Explanation
```
£ :Map over each element X
Ao : Range [0,10)
¬ : Join to a string
i- : Prepend "-"
® : Map over each character Z
iS : Prepend a space
g : Get the character at index
XøZ : X contains Z? (true=1, false=0)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~77~~ 64 bytes
*-12 bytes thanks to @Rod*
```
lambda x:[[[" ",z][z in str(y)]for z in"-0123456789"]for y in x]
```
[Try it online!](https://tio.run/##PVHJbsIwEL3zFVYuJNK48r4g8SUmhyBaNQgMghwCP5@@AVQ7YyV@29i5PqbfS7XLsN0tp@G8Pwxi3pRSGtHQsy9PMVZxn27to@t/LjfB341U2ljnQ0y5ee0@mDX3SxVbUYojbx3x9JZMoKgpWa@cI2m9zwxKrUxMLlsfSGY8KDj@rxmrfbHeOT73tCqaosnkokleK1CTNRRd0iZbg4ycnIHUpogoRZoHy2CeEsVIIZD3BNCiLwMCweY9kfjiSu0Ryw1yPOzeJO4xkYwkAfM5AECVgSFIMYf9lMWLQ3lUwEZgEz5CVn2/WvFdzXxXdSOut7FO7XpX11/Hy1jb03if2vNwbT9/Yb9Zf5B9R2Jo5w6DvuthCw1U3fIH "Python 3 – Try It Online")
My first proper attempt at golfing in Python. Advice welcome!
Returns a 2D array of characters.
[Answer]
# [Perl 5](https://www.perl.org/) `-pl`, 33 bytes
```
$_=eval"'-0123456789'=~y/$_/ /cr"
```
[Try it online!](https://tio.run/##PU3LCsIwELzvV0gp9LTmsdkke@gn@A1FpAch2FCL4MVPd00VZB6XGWbqvBZW7adxfpxLN6B1ngLHlGUYX0/TT@ZgLmunGoApwA4m8BGSg0xsQwAkZtlDdNanHIQ4AkpjUxv7uzSnb@t3wfJe6nZdbnfFEx@ts4q1fAA "Perl 5 – Try It Online")
Takes input as line separated.
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
map(\s->do d<-"-0123456789";max" "[d|elem d s])
```
[Try it online!](https://tio.run/##PU5BCoMwEPzKEnpoIQE1iSa09hM9qodgYpVGDY3SHvr2prGFsjPDwgyz2yt/M9aGrqzDqNy@9uSsZ9AngkiSZpTxvBASHUf1RIAq/TLWjKDBN4eYHyYowa3LZbnDDtbJDpPxcesiYxv4fn5AxTCnDG/DKc5yXKRYUJ4whgkVXG4mSZOsEExSnmMiIyLj7b/KqPSb@n3EZRPebWfV1QfSOvcB "Haskell – Try It Online")
Uses `max` to insert a space where no element exist, since a space is smaller than any digit or minus sign.
If an ungodly number of trailing spaces is OK, two bytes can be saved:
**45 bytes**
```
map(\s->do d<-'-':['0'..];max" "[d|elem d s])
```
[Try it online!](https://tio.run/##PUzLDoIwEPyVDTFBk5YAbXmo@BMegUNDQYgFGgvRg99uXTyYnZnMZme2l/beau26onKjNPvK0ouaQZ2pT/1j6Yd@ENSnUb488Er1bnU7ggJbHzA9TFCAWZfr8oAdrJMeptai65D4C2w/P6HkRDBOthGMxAlJI5IxEXJOKMtEvh1pFMZpxnMmEkJzBJJx8dcclf1SuCcptmr3aTotb9bRxpgv "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
"45KY2ht@gm*c
```
Input is a cell array of strings. [Try it online!](https://tio.run/##y00syfn/X8nE1DvSKKPEIT1XK/n//2p1Q3UddXMjSyBpYm5kYWpoAGTpGlsYG4HETSwMjSyNjUBqLCwtTEBiupbGFuYmJkAWSKUhCKjXAgA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##VVG7TsQwEOz5DBpLCEvel73bUdDRUkCBBLoCCq677sS3B@84kSCSx85kdmc9OX9cvrf37Vbt6ZW/Lg@f57vT9kbt9PL4vF0LlfsyOCbqYDdq81TFhZNXJw7h1Hi4JldDfKjOUyopn/Jzcy3JmCQey2QC9@yDBmINdVXMYkkrNR6uIdbRGgAUtX97zF32isn14ZNPX6KcSsZSp3ULp5HWEs0HMcqi7xN7GPGQ5mAHaZKxRPO@6FnJYLVGXLa4O@VFVkTwQ5P0qijQY4ZKu1tAj6TaqmWk1gQvCjRgx4e@zPKK0TAM8vB0GunUU2FZgjAFIa@mx2x/1wxu/p9f).
### Explanation
```
% Implicit input: cell array of strings, for example {'1','729',...,'11111'}
" % For each cell
45 % Push 45 (ASCII code of '-')
KY2 % Push predefined literal '0123456789'
h % Concatenate horizontally: gives '-0123456789'
t % Duplicate
@ % Push current cell, for example {'729'}
g % Convert cell to matrix. This effectively gives the cell's contents, '729'
m % Ismember: gives an array of zeros and ones indicating membership of each
% char from '-0123456789' in '729'. The result in the example is
% [0 0 0 1 0 0 0 0 1 0 1]
* % Multiply, element-wise. Chars are implicity converted to ASCII
% Gives the array [0 0 0 50 0 0 0 0 55 0 57]
c % Convert ASCII codes to chars. 0 is displayed as space. Gives the string
% ' 2 7 9'
% Implicit end
% Implicilly display each string on a different line
```
[Answer]
# [J](http://jsoftware.com/), 32 27 bytes
-5 bytes thanks to FrownyFrog!
```
10|.":(10<."."0@[)}11$' '"0
```
[Try it online!](https://tio.run/##XU7LSgQxELzPVxSDGBd06E53XoOKIHjy5NVDDouL7GV/QL99rKywgiHVeVRXdR23eQkHPKwIuIVgJe4WPL@9vmwqX8u83qjcL/Myy9P77lv1KiDMsu0mTB/7zxMO148oscFLrEkF3apFFK8am0VFbdUjerNa3GmuY/1KQ/izcCRz@PlEzChUWhJKuqXUBtlVYqneLGX6cRPm6VIbq527@M6lpvZvDDinayKG2WhlMFWM1NRX9IJOeswkwbCNHCPL6ImMLsaLE4nI/MjDZIxrgsuath8 "J – Try It Online")
## Original solution:
# [J](http://jsoftware.com/), 32 bytes
```
(('_0123456789'i.[)}11$' '"0)@":
```
## Explanation:
`@":` convert to characters and
`}11$' '"0` change the content of an array of 11 spaces to these characters
`'_0123456789'i.[` at the places, indicated by the indices of the characters in this list
[Try it online!](https://tio.run/##XU7LSgQxELzPVxSDmB3QIZ3uPHpAEQRPnrx6yEFc1Itf4LePlV1YwSbVCamurvra5zUccbch4AYRG3G74vHl@Wk/HEKPktRyqc3D5/q6/IhcBYQ5Lg/zti8Tpve3j28cr@8hqMlhNbUsEV2bJlRrklyToHmzhO7aqhk9ZNRZHMLfEkNWg51upIJKpeZISdecfZBdYqrNXHPhPh6CES/d2fU0dQ6e/Z8N6NMlE2PZGGUwEYzU1Df0ik56eJJgWCfHyHHMJEaPyocRmSj8KGPJsPOIS037Lw "J – Try It Online")
[Answer]
# [Google Sheets](https://sheets.google.com), 124 bytes
```
=Transpose(ArrayFormula(If(IsError(Find(Mid("-0123456789",Row($1:$11),1),Split(A1,",")))," ",Mid("-0123456789",Row($1:$11),1
```
Input is a comma-separated list in cell `A1`. Output is in the range `B1:L?` where `?` is however many entries were input. (You can put the formula wherever you want, I just chose `B1` for convenience.) Note that Sheets will automatically add four closing parentheses to the end of the formula, saving us those four bytes.
[![Screenshot](https://i.stack.imgur.com/1M76F.png)](https://i.stack.imgur.com/1M76F.png)
Another [test case](https://i.stack.imgur.com/kZwXa.png) and another [test case](https://i.stack.imgur.com/XP6a9.png)
Explanation:
* `Mid("-0123456789",Row($1:$11),1)` picks out each of the 11 characters in turn.
* `Find(Mid(~),Split(A1,","))` looks for those characters in each of the input elements. This either returns a numeric value or, if it's not found, an error.
* `If(IsError(Find(~)," ",Mid(~))` will return a space if the character wasn't found or the character if it was. (I wish there was a way to avoid duplicating the `Mid(~)` portion but I don't know of one.)
* `ArrayFormula(If(~))` is what makes the multi-cell references in `Mid(~)` and `Find(~)` work. It's also what makes a formula in one cell return values in multiple cells.
* `Transpose(ArrayFormula(~))` transpose the returned array because it starts off sideways.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ØD”-;¹⁶e?€Ʋ€
```
[Try it online!](https://tio.run/##y0rNyan8///wDJdHDXN1rQ/tfNS4LdX@UdOaY5uAxP@HO/cBqcPtkf//R5vomBqb6ICgqbGOkZmOuaGOhbGpgYmJjq6xqaklSFLX0MDI3MLE0tjUTEfXEoiA2NjEFE5aAkljsCog38zcwtQyFgA "Jelly – Try It Online")
-2 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) reading a rule I didn't.
Note that the I/O format used in the TIO link is not the actual one, which is input as a list of string representations and output as a list of lines.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
{.map:{map {m/$^a/||' '},'-',|^10}}
```
[Try it online!](https://tio.run/##PVBdb8IwDHzefkWF0AqSA3GcxPGk8Uc2mHgY0qbxIfaEgN/enTtpTe02vfPlrqeP83cd9pfuade9DNfFfnt6vqJ11/1yutkub7e@6@/Uh55uG473@/CzvXS72fR9vlotvo6fh7HNJm@HyZw6f3S74/nx4ZVJk1HW1ApHCtIkkebGySQxNWs5UTBpmjNFYr/WhLlMRTL5KkKpkoIsJYIVpBRzMHBM2rJJqZDAjZJc/ruhy8jCvmorNiozJxJ1FuVojZWSWGzKCWSrcNGscFKJDXvlHMkcgutxPnCBqB/v4nDPTB4NihhQCoDdJQBoGTDkis5JyBcFLxlVUBUfqou4QYujPFK0RqpUK5VCCCz4AT7qp/wtROP18As "Perl 6 – Try It Online")
Output is a character matrix containing either regex matches or space characters.
[Answer]
# Java 8, 53 bytes
```
a->a.map(i->"-0123456789".replaceAll("[^"+i+"]"," "))
```
My own challenge is easier than I thought it would be when I made it..
Input and output both as a `java.util.stream.Stream<String>`.
**Explanation:**
[Try it online.](https://tio.run/##lVLBatwwEL3nK4RONqmEZUmW1LQL@YCmhxxDCsrGG7z12outDYSy376dGXnbLrSUGDSypZn33jzPNr5GsX3@flr3cZ7Zl9gNP64Y64bUTpu4btkdfjK2hTx5SF0v5zS1cSfvafsEWze8rNi6@F9GLG8A6XgFYU4xdWt2xwb2mZ2iWEW5i/uiEysuKlVrYxvnA5dTu@9Bw23fF/zhG7/urvkj/8AZL8vTDQLtD089AC14r2P3zHbQQZE5Hx6BNMtP7ZwKrqDY1QGicbW3qoI3ob2u8dx4VQddY44P3uCZCNo7Y@ANMxU@nLo4A@KV1RjPy2oIdYOAhKRtRQBCWxtyqlBV7bwJ2jbEQYEiNH6xB9j1UqENeALHF/xKoUztchVKqIJXDiXoUHkHXhJOs7Tgg1W105WnU6cMHoacBAZcggtliTtrzjrIFYWdZfOImNCQVFCBOYsRaqENlE8eVrm2Jj8rTR@GoqXY0EWTyXAQQnWpipzySOmQssFUi7Vksyb7M/pZ5J8LLF1@4RHW71Gk0SGCPDpSyl@zsxmn4uvTtl0nNrKPbJD/nHU5bopYljKNt9MU34qyJADG7t/m1ML1Ick9wKd@KMalq79ccfHu59zT8fQT)
```
a-> // Method with String-Stream as both input and return-type
a.map(i-> // For every String in the input:
"-0123456789" // Replace it with "-0123456789",
.replaceAll("[^"+i+"]"," ")) // with every character not in `i` replaced with a space
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 159 bytes
```
f(A,l,j,k,b)long*A,k;{char*s,S[99];for(j=~0;++j<l;puts(""))for(sprintf(S,"%ld",k=A[j]),putchar(k<0?45:32),k=47;++k<58;putchar(b?32:k))for(b=s=S;*s;b*=*s++-k);}
```
[Try it online!](https://tio.run/##dZHdbuIwEIWvt4@BtFIcJpLH47@piSqegUvERaGiW0JpRbpXKPvq7PFWW6kXxLEV@4y/mTnZdc@73fW6b5Z0pAMNtDXHt9Nzu6ShXHa/Hs/tSKu16qbs387Nof9jy3x@WBzL@@@PsZnNjKnn4/v55fSxb1Y0@3l8mtHQL9eHjSEEVUYzLOyDD/fiDCSfgBgWIZf/8vZB3P3widr2Y78q7Vi2bd@O83k3mDJdXx9fTo253P3YN02tb70xF6bklHxyObClTrI4Sj6zU3FMWbN31Knk5D1Z4vpMpOar8vKN5imIpzqCkIuUgJBgcbeTELSKHVuXslcJEWC8mOLD16pY5V8U9jHloBNxvJWQ2ZGkepm81cyJnKjNiR0YGlFy1sAuic3YJ/aWtEpoEVi@he04oIRabC0FDjBTtQeJwEnUQa49QUAKhQZvbI1xoFrBh8cMmBEHsUJqO2oncv5WVliRM6VEMVIIBNcELlZiTf454A9@AH9jTNe/ "C (gcc) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~96~~ 75 bytes
```
for(i in scan())cat(paste(gsub(paste0("[^",i,"]")," ","-0123456789"),"\n"))
```
[Try it online!](https://tio.run/##JchNCgMhDEDhfU4hWSkomJip8Sz9ATu0xY0t4/T8lqFv9fG2OZ/vzTbTuhlr7da5te72U8f@sK/xvf8ZLZ5v6JvHKzqPBj2GSJxkOWUtx7p0dG4SZC4gmXWhCCFpYsiixCUxgRYVhlCSZhGIQEfzBw "R – Try It Online")
Thanks to Kevin Cruijssen for suggesting this regex approach!
Takes input from stdin as whitespace separated integers, and prints the ascii-art to stdout.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~14~~ 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
{ø,{²²⁴WI1ž}P
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTdCJUY4JTJDJTdCJUIyJUIyJXUyMDc0V0kxJXUwMTdFJTdEUA__,inputs=MTYlMEE0JTBBNTM0JTBBNCUwQTQlMEE1MyUwQTI2JTBBNzElMEE4MzUwNDQlMEEtMzU1OTUzNCUwQS0xMDI3ODQ5MzU2JTBBLTklMEEtOTklMEEtMzQ1OSUwQS0zNDU5JTBBLTk0NTkzJTBBLTEwMjM0NTY3ODU5,v=0.12)
Explanation:
```
{ø,{²²⁴WI1ž}P
{ repeat input times
ø, push an empty string and the next input above that
{ } for each character in the input
²² push "0123456789"
⁴ copy the character on top
W and get it's index in that string (1-indexed, 0 for the non-existent "-")
I increment that (SOGL is 1-indexed, so this is required)
1ž at coordinates (index; 1) in the string pushed earlier, insert that original copy of the character
P print the current line
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 85 bytes
```
I X =INPUT :F(END)
S ='-0123456789'
R S NOTANY(X ' ') =' ' :S(R)
OUTPUT =S :(I)
END
```
[Try it online!](https://tio.run/##PY67CsMwDEVn6yu82RkMcSQldiBDoS14cUoekK6dSzP0/3GVFoqkO0jnSnq/9sf@pFKS2vSQ8m1dVH@1l3yuQM16MK72DRK3XYgGJmnlcTnlu9200aYSQBvVz3YSfFwXsethVr1NFciOUggYCY5ghKaFzkNAronAIXM8hs7XTRcoIrfgoqSUXPxrFMUv9fuD4wc "SNOBOL4 (CSNOBOL4) – Try It Online")
```
I X =INPUT :F(END) ;* read input, if none, goto end
S ='-0123456789' ;* set the string
R S NOTANY(X ' ') =' ' :S(R) ;* replace characters of S not in X + space with space
OUTPUT =S :(I) ;* print S, goto I
END
```
[Answer]
# Pyth, 14 bytes
```
VQm*d}dNs+\-UT
```
Takes input as list of strings and outputs a list of strings for each line.
[Try it here](http://pyth.herokuapp.com/?code=VQm%2Ad%7DdNs%2B%5C-UT&input=%5B%224%22%2C%20%22534%22%2C%20%224%22%2C%20%224%22%2C%20%2253%22%2C%20%2226%22%2C%20%2271%22%2C%20%22835044%22%2C%20%22-3559534%22%2C%20%22-1027849356%22%2C%20%22-9%22%2C%20%22-99%22%2C%20%22-3459%22%2C%20%22-3459%22%2C%20%22-94593%22%2C%20%22-10234567859%22%5D&debug=0)
### Explanation
```
VQm*d}dNs+\-UT
VQ For each string in the input...
m s+\-UT ... and each character in "-0123456789"...
}dN ... check if the character is in the string...
*d ... and get that character or an empty string.
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 26 bytes
```
%"-0123456789"~`.+
[^$&]¶
```
[Try it online!](https://tio.run/##K0otycxLNPz/X1VJ18DQyNjE1MzcwlKpLkFPmys6TkUt9tA2hf//TbhMjU24QNDUmMvIjMvckMvC2NTAxIRL19jC1BIkqWtoYGRuYWJpbGrGpWsJREAMNA1OWgJJY7AqiB2mlgA "Retina – Try It Online") Note: Trailing space. Explanation: `%` executes its child stage `~` once for each line of input. `~` first executes its child stage, which wraps the line in `[^` and `]<CR><SP>`, producing a program that replaces characters not in the line with spaces. The `"-0123456789"` specifies that the input to that program is the given string (`$` substitutions are allowed but I don't need them).
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 30 bytes
Wouldn't work if `-` could appear anywhere else than in the first position
```
#!/usr/bin/perl -n
say"-0123456789"=~s/[^$_]/ /gr
```
[Try it online!](https://tio.run/##PU27CsJAEOz3KyTYrvfY3bvbIp/gF4iKhYggScjZ2Pjpbi4KMo9mhpnpOj/ErF5eHfoQiSXlol3/ru5w2p6PbuNusxmDEMMKIYgJcoBC4pkBSUTXEIOPubCSJEBtbGpzf9fm9G39TkQ/4/S8j0M13MvOB284LA "Perl 5 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 94 bytes
```
func[b][foreach a b[s: copy" "foreach c a[s/(index? find"-0123456789"c): c]print s]]
```
Takes input as a block of strings
[Try it online!](https://tio.run/##TU4xDsIwDNz7CssTDBWNnZCEhT@wRhlK2giWFrUgweuLQ4XAin3S@XyXqe@WU99BiFU@LPkxpHCOIY9T36YLtHAO8wHSeHsh/Aq/@wRtmHeb69D1zyNkQawbRazN3jqPaSu38TZdhzvMMS4ZAmpEwzLWZxiR9ohWITo2jRauZmP8R1OrhqzTno1Ial@6DLH/Ay/Aq3bNFTZWayhiVTLF3JJotSVnVFNuHZOQ2inyTCXcO03FjZ0tnxCRKoVxeQM "Red – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
qS%{'-10,+s_@-SerN}/
```
[Try it online!](https://tio.run/##FcE9DkBgDADQq3QRA42vP9J2cwKLA4iIRWLAKM5e8d66L0fmOVVPjVTa5p4HnLZrfLtMAuMANfaeCqC4MJg6cQgTeLgyYIibKhSg3wc "CJam – Try It Online")
Accepts input as space separated list of integers. Pretty much the same approach as @adnans answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~95~~ 94 bytes
```
c,d;f(l,n)char**l;{for(;n--;l++)for(c=0;c<12;)putchar(strchr(*l,d=c++?c+46:45)?d:d^58?32:10);}
```
[Try it online!](https://tio.run/##VVLbbsMgDH1uvgLlKWlAwhgCNKv6IbtIE9G6Slk2td1eqn57h02qaZFisDk@PjYktU/pdktyHN6aSc5ten89rtfTcHn7PDbDrNQwdV1LTtrqIT2AGdqv7zPBmtP5mN6PzXqS4zZ13S51tt9Y1@7Gzfjiwg7NBnQ7XG8/n4dR7BtKEplcisN8FnNbXaoVVc3boVpl1lNTP@WSStU5cK0qgn28HuaGoSV9OpzOj89iKy411LL2JmZrvQkOdN4pDGgobgOYiIYwIQZLMRUxeGvzjpBAX32VzGgWSjp0SPb@O8zG9ETJXOg0Uyh0LhaoAm18sBFdz1XYsEXr/q0xr7hk5FjvQ44vEvDeFZBW9CWRVOgYwJMKjDp4MMwQ@6WPEB0Yjzpw1IOlYCygPIU7vV3oFTgWUIQXMTwcoPbKDLk081FZxQn2LkfBUjgynkepS67hsWpkx7J1bHs@6Esxajzq@prvvFrtGxInRaQnUBwjBfR/LmYX/lwrhbH0PG6/ "C (gcc) – Try It Online")
Input in the form of a list of strings. Output to STDOUT.
[Answer]
# [K4](http://kx.com/download/), ~~30~~ 27 bytes
**Solution:**
```
{?[a in$x;a:"-",.Q.n;" "]}'
```
**Example:**
```
q)k){?[a in$x;a:"-",.Q.n;" "]}'1 729 4728510 -3832 748129321 89842 -938744 0 11111
" 1 "
" 2 7 9"
" 012 45 78 "
"- 23 8 "
" 1234 789"
" 2 4 89"
"- 34 789"
" 0 "
" 1 "
```
**Explanation:**
Return "-0123..." or " " based on the input. Interpreted right-to-left. No competition for the APL answer :(
```
{?[a in$x;a:"-",.Q.n;" "]}' / the solution
{ }' / lambda for each
?[ ; ; ] / if[cond;true;false]
.Q.n / string "0123456789"
"-", / join with "-"
a: / save as a
$x / convert input to string
a in / return boolean list where each a in x
" " / whitespace (return when false)
```
[Answer]
# APL+WIN, 33 bytes
Prompts for screen input as a string
```
n←11⍴' '⋄n['-0123456789'⍳s]←s←⎕⋄n
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 9 years ago.
[Improve this question](/posts/13/edit)
You are provided with a function Rand5(). This function returns perfectly random (equal distribution) integers between 1 and 5.
Provide the function Rand7(), which uses Rand5() to produce perfectly random integers between 1 and 7.
[Answer]
Java - 61 chars
```
int rand7(){int s=0,c=7;while(c-->0)s+=rand5();return s%7+1;}
```
Test driver for validation:
```
class Rand {
public static void main(String[] args) {
int[] nums = new int[7];
// get a lot of numbers
for(int i = 0; i < 10000000; i++) nums[rand7()-1]++;
// print the results
for(int i = 0; i < 7; i++) System.out.println((i+1) + ": " + nums[i]);
}
// just for rand5()
static java.util.Random r = new java.util.Random();
static int rand5() {
return r.nextInt(5)+1; // Random.nextInt(n) returns 0..n-1, so add 1
}
static int rand7(){int s=0,c=7;while(c-->0)s+=rand5();return s%7+1;}
}
```
Results
```
C:\Documents and Settings\glowcoder\My Documents>java Rand
1: 1429828
2: 1429347
3: 1428328
4: 1426486
5: 1426784
6: 1429853
7: 1429374
C:\Documents and Settings\glowcoder\My Documents>
```
[Answer]
## Perl - 47 (was 52) chars
```
sub rand7{($x=5*&rand5+&rand5-3)<24?int($x/3):&rand7}
```
Plus I get to use the ternary operator AND recursion. Best... day... ever!
OK, 47 chars if you use mod instead of div:
```
sub rand7{($x=5*&rand5+&rand5)<27?$x%7+1:&rand7}
```
[Answer]
## JavaScript, 42
```
Rand7=f=_=>(x=Rand5()+Rand5()*5-5)>7?f():x
```
Bonus ES5 thing:
```
Rand7=eval.bind(0,'for(;x=Rand5()+Rand5()*5-5,x>7;);x')
```
[Answer]
In Python:
```
def Rand7():
while True:
x = (Rand5() - 1) * 5 + (Rand5() - 1)
if x < 21: return x/3 + 1
```
[Answer]
Ruby - 54 chars (based on Dan McGrath solution, using loop)
```
def rand7;x=8;while x>7 do x=rand5+5*rand5-5 end;x;end
```
Ruby - 45 chars (same solution, using recursion)
```
def rand7;x=rand5+5*rand5-5;x>7 ?rand7: x;end
```
[Answer]
In Common Lisp 70 characters:
```
(defun rand7()(let((n(-(+(rand5)(* 5(rand5)))5)))(if(> n 7)(rand7)n)))
```
The parenthesis take up more space than I would like.
[Answer]
In c/c++ using [rejection sampling](http://en.wikipedia.org/wiki/Rejection_sampling)
```
int rand7(){int x=8;while(x>7)x=rand5()+5*rand5()-5;return x;}
```
62 characters.
[Answer]
Translation to PHP, from the answer posted ny Dan McGrath.
```
function Rand7(){$x=8;while($x>7)$x=rand5()+5*rand5()-5;return $x;}
```
67 characters.
[Answer]
# R, 34 characters
In R (a language built for statistical computation), a deliberately cheaterish solution:
```
# Construct a Rand5 function
Rand5 <- function() sample(seq(5),1)
# And the golf
Rand7=function(r=Rand5())sample(1:(r/r+6),1)
# Or (same character count)
Rand7=function(r=Rand5())sample.int(r/r+6,1)
# Or even shorter(thanks to @Spacedman)
Rand7=function()sample(7)[Rand5()]
```
Thanks to lazy evaluation of arguments, I eliminated the semicolon and braces.
Output over 10^6 replicates:
```
> test <- replicate(10^6,Rand7())
> table(test)
test
1 2 3 4 5 6 7
142987 142547 143133 142719 142897 142869 142848
library(ggplot2)
qplot(test)
```
![histogram of results](https://i.stack.imgur.com/KDWwz.png)
[Answer]
## scala, 47, 40 59 chars:
```
def rand7:Int={val r=5*(rand5-1)+rand5
if(r<8)r else rand7}
```
with 2 inputs from rand5:
```
\ 1 2 3 4 5
1 1 2 3 4 5
2 6 7 8 ..
3 11 ..
4 ..
5
```
I multiply the first-1 by 5, and add the second. Most results are ignored, and lead to a new calculation. The result should be an equal distribution of values from 1-25, from which I only pick the first 7 ones. I could accept the first 21 with building a modulo, but this would lead to longer code.
historic code which failed, but not very obviously. Thanks to Ilmari Karonen for pointing it out:
```
def rand7=(1 to 7).map(_=>rand5).sum%7+1
```
Thanks to Yoshiteru Takeshita, for this scala-2.8.0-approach which made 'sum' so easy. My solution before:
```
def rand7=((0/:(1 to 7))((a,_)=>a+rand5-1))%7+1
```
rand5:
```
val rnd = util.Random
def rand5 = rnd.nextInt (5) + 1
```
[Answer]
## C++
```
int Rand4()
{
int r = Rand5();
return r > 4 ? Rand4() : r;
}
inline int Rand8()
{
return (Rand4() - 1) << 2 + Rand4();
}
int Rand7()
{
int r = Rand8();
return r > 7 ? Rand7() : r;
}
```
---
## C++ (109)
### Golfed
```
int Rand4(){int r=Rand5();return r>4?Rand4():r;}int Rand7(){int r=Rand4()-1<<2+Rand4();return r>7?Rand7():r;}
```
[Answer]
Translation to Javascript, from the answer posted by Dan McGrath.
```
function Rand7(){x=8;while(x>7)x=rand5()+5*rand5()-5;return x}
```
**62 chars**
[Answer]
## JavaScript, 85
```
function Rand7(){for(x=0,i=1;i<8;x^=i*((k=Rand5())%2),i*=1+(k<5));return x?x:Rand7()}
```
I know there's shorter answer, but I wanted to show the [test](http://jsfiddle.net/JIminP/KPLkT/) of this puzzle. It turns out that only Clyde Lobo's answer using Dan McGrath's rejection sampling is correct (between JS answers).
[Answer]
## С++
```
int Rand7()
{
int r = Rand5();
int n = 5;
do {
r = (r - 1) * 5 + Rand5();
int m = n * 5 / 7 * 7;
if (r <= m) {
return r % 7 + 1;
}
r -= m;
n = n * 5 - m;
} while (1);
}
```
Numbers distribution (1000000 integers):
```
142935 142751 142652 143299 142969 142691 142703
```
Average number of calls to Rand5() per every generated integer is about 2.2 (2 to 10+).
```
1 2 3 4 5 6 7 8 9 10
0 840180 112222 44433 2212 886 0 60 6 1
```
[Answer]
In Java (or C/C++ I suppose)
* using generation formula by Alexandru, in 65 characters:
```
int rand7(){int x=rand5()*5+rand5()-6;return x>20?rand7():x/3+1;}
```
* using generation formula by Dan McGrath, in 60 characters
```
int rand7(){int x=rand5()+5*rand5()-5;return x>7?rand7():x;}
```
[Answer]
# Clojure - 58 chars
```
(defn rand7[](#(if(<% 8)%(rand7))(+(rand5)(*(rand5)5)-5)))
```
[Answer]
# Python, 56 37 chars
Another solution that may be wrong, in Python:
```
rand7 = lambda: sum(rand5() for i in range(7)) % 7 + 1
```
This seems to be too simple, but when I try:
```
counter = [0] * 7
for i in range(100000):
counter[rand7()] += 1
```
I get a reasonably even distribution (all between 14000 and 14500).
Okay, now as somebody voted for this post: Is this solution indeed correct? I more posted this here to make people criticize it. Well, if it is correct, my golfed version would be:
```
rand7=lambda:eval("+rand5()"*7)%7+1
```
which comes out to 37 chars.
[Answer]
Java, 65 chars:
```
int rand7(){int r;do{r=rand5()+5*rand5()-5;}while(r>7);return r;}
```
[Answer]
# Python, 70 chars
```
def rand7():
while True:
n=5*(rand5()-1)+(rand5()-1)
if n<21:return n%7+1
```
but completely correct based on the reasoning [here](https://stackoverflow.com/questions/137783/expand-a-random-range-from-1-5-to-1-7).
[Answer]
## Perl, 43 chars, iterative rejection sampling
```
sub rand7{1while($_=5*&rand5-rand5)>6;$_+1}
```
This gives a warning about `Ambiguous use of -rand5 resolved as -&rand5()`, but works correctly. Prepending an `&` also to the second `rand5` call fixes it at the cost of one stroke. (Conversely, the other `&` can also be removed *if* `rand5` has been defined with a `()` prototype.)
Ps. The following 46-char version is about three times faster:
```
sub rand7{1while($_=5*&rand5-rand5)>20;$_%7+1}
```
[Answer]
## Java - 66 chars
```
int rand7(){int s;while((s=rand5()*5+rand5())<10);return(s%7+1);}
```
Longer than previous routine, but I think this one returns uniformly distributed numbers in less time.
[Answer]
**PostScript (46)**
This uses binary token encoding, therefore, here is a hexdump:
```
00000000 2f 72 61 6e 64 37 7b 38 7b 92 38 37 92 61 7b 92 |/rand7{8{.87.a{.|
00000010 40 7d 69 66 92 75 32 7b 72 61 6e 64 35 7d 92 83 |@}if.u2{rand5}..|
00000020 35 92 6c 92 01 35 92 a9 7d 92 65 7d 92 33 |5.l..5..}.e}.3|
0000002e
```
To try it out, you can also [download it](http://www.mediafire.com/?ceas14shso7e97x).
Here is the ungolfed and commented code, together with testing code.
```
% This is the actual rand7 procedure.
/rand7{
8{ % potentialResult
% only if the random number is less than or equal to 7, we're done
dup 7 le{ % result
exit % result
}if % potentialResult
pop % -/-
2{rand5}repeat % randomNumber1 randomNumber2
5 mul add 5 sub % randomNumber1 + 5*randomNumber2 - 5 = potentialResult
}loop
}def
%Now, some testing code.
% For testing, we use the built-in rand operator;
% Doesn't really give a 100% even distribution as it returns numbers
% from 0 to 2^31-1, which is of course not divisible by 5.
/rand5 {
rand 5 mod 1 add
}def
% For testing, we initialize a dict that counts the number of times any number
% has been returned. Of course, we start the count at 0 for every number.
<<1 1 7{0}for>>begin
% Now we're calling the function quite a number of times
% and increment the counters accordingly.
1000000 {
rand7 dup load 1 add def
}repeat
% Print the results
currentdict{
2 array astore ==
}forall
```
[Answer]
```
int result = 0;
for (int i = 0; i++; i<7)
if (((rand(5) + rand(5)) % 2) //check if odd
result += 1;
return result + 1;
```
[Answer]
# R (30 characters)
Define rand7:
```
rand7=function(n)sample(7,n,T)
```
Because R was written with statistical analysis in mind, this task is trivial, and I use the built-in function `sample` with replacement set to TRUE.
Sample output:
```
> rand7(20)
[1] 4 3 6 1 2 4 3 2 3 2 5 1 4 6 4 2 4 6 6 1
> rand7(20)
[1] 1 2 5 2 6 4 6 1 7 1 1 3 7 6 4 7 4 2 1 2
> rand7(20)
[1] 6 7 1 3 3 1 5 4 3 4 2 1 5 4 4 4 7 7 1 5
```
[Answer]
# Groovy
```
rand7={if(b==null)b=rand5();(b=(rand5()+b)%7+1)}
```
example distribution over 35,000 iterations:
```
[1:5030, 2:4909, 3:5017, 4:4942, 5:5118, 6:4956, 7:5028]
```
Is it bad that it's stateful?
[Answer]
## Mathematica, 30
```
Rand7=Rand5[]~Sum~{7}~Mod~7+1&
```
[Answer]
How about this?
```
int Rand7()
{
return Rand5()+ Rand5()/2;
}
```
[Answer]
## Java - 54
```
int m=0;int rand7(){return(m=m*5&-1>>>1|rand5())%7+1;}
```
Distribution test:
`[1000915, 999689, 999169, 998227, 1001653, 1000419, 999928]`
Algorithm:
* Keep a global variable
* multiply by 5, so there get 5 places free at the least significant end
* Truncate the sign bit to make it positive (not necessary if unsigned numbers were supported)
* Modulo 7 is the answer
> The numbers are not mutually uncorrelated anymore, but individually perfectly random.
[Answer]
# Ruby (43 bytes)
```
def rand7;(0..7).reduce{|i|i+rand5}%7+1;end
```
cemper93's solution ported to Ruby is three bytes shorter ;) (34 bytes)
```
def rand7;eval("+rand5"*7)%7+1;end
```
[Answer]
**C/C++ code** the core code has one line only!
```
static unsigned int gi = 0;
int rand7()
{
return (((rand() % 5 + 1) + (gi++ % 7)) % 7) + 1;
}
//call this seed before rand7
//maybe it's not best seed, if yo have any good idea tell me please
//and thanks JiminP again, he remind me to do this
void srand7()
{
int i, n = time(0);
for (i = 0; i < n % 7; i++)
rand7();
}
```
The srand7() is the seed of rand7, must call this function before rand7, just like call srand before rand in C.
This is a very good one, because it call rand() only one time, and no loop thing, no expends extra memories.
Let me explain it: consider a integer array with size of 5:
```
1st get one number from 1 2 3 4 5 by rand5
2nd get one number from 2 3 4 5 6
3rd get one number from 3 4 5 6 7
4th get one number from 4 5 6 7 1
5th get one number from 5 6 7 1 2
5th get one number from 6 7 1 2 3
7th get one number from 7 1 2 3 4
```
So we got the TABLE, each one of 1-7 appears 5 times in it, and has all 35 numbers, so the probability of each number is 5/35=1/7. And next time,
```
8th get one number from 1 2 3 4 5
9th get one number from 2 3 4 5 6
......
```
After enough times, we can get the uniform distribution of 1-7.
So, we can allocate a array to restore the five elements of 1-7 by loop-left-shift, and get one number from array each time by rand5. Instead, we can generate the all seven arrays before, and using them circularly. The code is simple also, has many short codes can do this.
But, we can using the properties of % operation, so the table 1-7 rows is equivalent with (rand5 + i) % 7, that is :
a = rand() % 5 + 1 is rand5 in C language,
b = gi++ % 7 generates all permutations in table above, and 0 - 6 replace 1 - 7
c = (a + b) % 7 + 1, generates 1 - 7 uniformly.
Finally, we got this code:
```
(((rand() % 5 + 1) + (gi++ % 7)) % 7) + 1
```
But, we can not get 6 and 7 at first call, so we need a seed, some like srand for rand in C/C++, to disarrange the permutation for first formal call.
Here is the full code to testing:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static unsigned int gi = 0;
//a = rand() % 5 + 1 is rand5 in C language,
//b = gi++ % 7 generates all permutations,
//c = (a + b) % 7 + 1, generates 1 - 7 uniformly.
//Dont forget call srand7 before rand7
int rand7()
{
return (((rand() % 5 + 1) + (gi++ % 7)) % 7) + 1;
}
//call this seed before rand7
//maybe it's not best seed, if yo have any good idea tell me please
//and thanks JiminP again, he remind me to do this
void srand7()
{
int i, n = time(0);
for (i = 0; i < n % 7; i++)
rand7();
}
void main(void)
{
unsigned int result[10] = {0};
int k;
srand((unsigned int)time(0)); //initialize the seed for rand
srand7() //initialize the rand7
for (k = 0; k < 100000; k++)
result[rand7() - 1]++;
for (k = 0; k < 7; k++)
printf("%d : %.05f\n", k + 1, (float)result[k]/100000);
}
```
] |
[Question]
[
Write an \$n\$-bytes program \$AB\$ such that:
* it outputs an integer \$x,\ 0\lt x\lt n\$;
* both its \$x\$-byte prefix \$A\$ and \$(n-x)\$-byte suffix \$B\$, when run as programs, output \$AB\$.
\$A, B\$ and \$AB\$ should:
* run in the same language
* not take any input
* use the same output method
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins (i.e., your score is \$ n \$).
## Program example (in a dummy 'lizard language')
With \$x = 2\$ bytes, the whole program is `lizard` the first-part program is `li`, and the second-part program is `zard`, then the following behaviour would be expected:
```
source | output |
--------+--------+
lizard | 2 |
li | lizard |
zard | lizard |
```
[Answer]
# [Python 2](https://docs.python.org/2/), 123 bytes
```
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u'input(56)'
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u
```
[Try it online!](https://tio.run/##nY7BCsMgEETvfsWyEGxJe0jBHDb4JYkQsJZ6UREF8/XGpJTeexl2Hrs7E7b09u5RtX8aGRGxsiyxSL4sLssuTqYYDZl3eQrRugSlX7l1IaeLGK987Qt@V3703xe15c8D3QfF2MtH0GAdHM1uh8wkRvWZxEiKGECKG8F5q5szRZuQCM4UxEbqDg "Python 2 – Try It Online")
outputs 56 and crash.
Both
```
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u
```
and
```
'input(56)'
u="x='\\nu=%r;exec u'%u;print x+`'input(56)'`+x";exec u
```
return the original code.
---
Here is another version without any crashing of the program:
# [Python 2](https://docs.python.org/2/), 141 bytes
```
u="x='\\nu=%r;exec u'%u;print x+`'print 62;exit()'`+x";exec u'print 62;exit()'
u="x='\\nu=%r;exec u'%u;print x+`'print 62;exit()'`+x";exec u
```
[Try it online!](https://tio.run/##pU69CsMgGNx9ig8h2JJ2iIPDF3ySREixlrqoGAXz9MY0dOna5bjjfriwpbd3vGr/NDJSSivJkhbJ5tll2cXRFKMhsy6PIVqXoPQLO5ngzbTpcmVLX@g3@Ov9N1fbo2nA@6AIefkIGqyD4@vtgAkFVycTHBUSgBQ3hE9XN2WKNiEhhMe61h0 "Python 2 – Try It Online")
---
Thanks to @ovs who helped me to improve my solution.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 52 bytes
```
"/+:zQash|2ss}a' 0'rlKH
0"/+:zQash|2ss}a' 0'rlKH
0
```
[Try it online!](https://tio.run/##S8/PScsszvj/X0lf26oqMLE4o8aouLg2UV3BQL0ox9uDS8EAt8z//wA "Gol><> – Try It Online") Outputs 26.
The two halves (identical, 26 bytes):
```
"/+:zQash|2ss}a' 0'rlKH
0
```
[Try it online!](https://tio.run/##S8/PScsszvj/X0lf26oqMLE4o8aouLg2UV3BQL0ox9uDS8Hg/38A "Gol><> – Try It Online") Outputs the original program.
The program path for half and full programs is identical. The only difference is that one more 0 is pushed while going through the 2nd column. If the sum of the top two values is 0, it prints 26 and halts (`ash`). Otherwise:
```
2ss} Push 34 and place it at the bottom of the stack
a' 0' Push a newline and ' 0' on the stack
rlK Reverse the entire stack and push a copy of the entire stack
H Print each char from top to bottom and halt
```
[Answer]
# Scala 3 `-language:postfixOps`, ~~940~~ 748 bytes
This is a chonky lizard.
```
@main def m:Unit=
val s="""@main def m:Unit=
val s=Q%sQ;var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
return
new main()dval
x=0
@main def n={val s=Q%sQ;printf(s.replace(""+81.toChar,"\""*3),s,s)}""";var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
return
new main()dval
x=0
@main def n={val s="""@main def m:Unit=
val s=Q%sQ;var x=0;class main extends annotation.Annotation{def dval=print(420);def d=printf(s.replace(""+81.toChar,"\""*3),s,s)}
return
new main()dval
x=0
@main def n={val s=Q%sQ;printf(s.replace(""+81.toChar,"\""*3),s,s)}""";printf(s.replace(""+81.toChar,"\""*3),s,s)}
```
`x` is 420.
[Try it online!](https://scastie.scala-lang.org/tiNK6ypJRZyjXGzaxjB5Aw)
[Try the first x bytes online!](https://scastie.scala-lang.org/BbMmaTVXSPOuDmF1hybT7A)
[Try the last (n-x) bytes online!](https://scastie.scala-lang.org/J8lgZcC1TLOKHYxdLMhCsQ)
I'm sure I've done something silly here and can make it smaller, but it's really hard editing quines and seeing what's wrong, so I'll try golfing it more later.
First x bytes, prettified (`...` contains the entire program):
```
@main def m: Unit =
val s = """..."""
var x = 0
class main extends annotation.Annotation {
def dval = print(420)
def d = printf(s.replace("" + 81.toChar, "\"" * 3), s, s)
}
return new main().d
```
Last (n-x) bytes, prettified (`...` contains the entire program):
```
val x = 0
@main def n = {
val s = """..."""
printf(s.replace("" + 81.toChar, "\"" * 3), s, s)
}
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 44 bytes
```
`:qpd4NẎ[20|`:qpd4NẎ[20|`:qpd4NẎ[20|`:qpd4NẎ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%3Aqpd4N%E1%BA%8E%5B20%7C%60%3Aqpd4N%E1%BA%8E%5B20%7C%60%3Aqpd4N%E1%BA%8E%5B20%7C%60%3Aqpd4N%E1%BA%8E&inputs=&header=&footer=) Outputs 20.
**Left Side:**
```
`:qpd4NẎ[20|`:qpd4NẎ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%3Aqpd4N%E1%BA%8E%5B20%7C%60%3Aqpd4N%E1%BA%8E&inputs=&header=&footer=)
**Right Side:**
```
[20|`:qpd4NẎ[20|`:qpd4NẎ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%5B20%7C%60%3Aqpd4N%E1%BA%8E%5B20%7C%60%3Aqpd4N%E1%BA%8E&inputs=&header=&footer=)
```
`...`:qpd4NẎ[20|`...`:qpd4NẎ
`...`:qp `...`:qp Standard Vyxal quine (of the first 24 bytes)
d d Double ^
4NẎ 4NẎ Remove the last 4 characters of ^ to make it a quine
[20| If the top of stack is true, push 20, otherwise the second quine.
```
The `D` flag allows the character `Ẏ` to be used in string literals
[Answer]
# [Haskell](https://www.haskell.org/), 303 bytes
```
k="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
x="k="++show k++k++show k
main=putStr x where x="153";main=putStr$"k="++show q++q++show q
q="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P9tWKSavwjZGKRuItbWLM/LLFbK1tbNhzJi83MTMPNuC0pLgkiKFCoXyjNSiVAWQBkNT4xglayRZFRRDCrW1C2HMmLxCWyWuClugPDY7uLBbAbIB1QIk/cjGcxXSzRP//wMA "Haskell – Try It Online")
Prints 153.
```
k="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
x="k="++show k++k++show k
main=putStr x where
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P9tWKSavwjZGKRuItbWLM/LLFbK1tbNhzJi83MTMPNuC0pLgkiKFCoXyjNSiVAWQBkNT4xglayRZFRRDCrW1C2HMmLxCWyWuClugPDY7uLBZ8f8/AA "Haskell – Try It Online")
```
x="153";main=putStr$"k="++show q++q++show q
q="\nx=\"k=\"++show k++k++show k\nmain=putStr x where x=\"153\";main=putStr$\"k=\"++show q++q++show q\nq="
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8JWydDUWMk6NzEzz7agtCS4pEhFKdtWSVu7OCO/XKFQW7sQxuQqtFWKyauwjQHKx8AUZGtrZ8OYMXlIpihUKJRnpBalKoA0AK2IQbUDxRBkW2LygNb8/w8A "Haskell – Try It Online")
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 34 bytes
```
'r2sslK5+:l)?H1sh"r2sslK5+:l)?H1sh
```
[Try it online!](https://tio.run/##S8/PScsszvj/X73IqLg4x9tU2ypH097DsDhDCV3g/38A "Gol><> – Try It Online")
This is composed of two identical sections of code, except one uses `'` and the other uses `"`. The combined program outputs 17 (which is only one byte away from being able to use a single instruction to push the number), which splits them into practically identical programs.
[Try the first half online!](https://tio.run/##S8/PScsszvj/X73IqLg4x9tU2ypH097DECQEAA "Gol><> – Try It Online") [And the second half!](https://tio.run/##S8/PScsszvj/X6nIqLg4x9tU2ypH097DECQEAA "Gol><> – Try It Online")
### Explanation:
```
'r2ss Push the code on the first line and add a " to the start
lK Push a copy of the stack
5+ Add 5 to the top " making it a '
:l)? If the length of the stack is less than 39
H Halt and output the stack contents
1sh Otherwise print 17
```
[Answer]
## [Ruby](https://www.ruby-lang.org/en/), 143 bytes
```
$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$ab='puts 63;exit';$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a
```
Outputs «63» and exits. First 63 bytes
```
$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a
```
and the rest
```
b='puts 63;exit';$a=%q[a="$a=%q[#$a];eval$a";$><<a+"b='puts 63;exit';"+a];eval$a
```
output the whole quine. I feel like when golfing it inevitably converged towards the existing python solution in the answers. Other approaches seem to all be bigger.
] |
[Question]
[
## Background
Entombed is an Atari 2600 game released in 1982, with the goal of navigating through a continuous mirrored maze as it scrolls upwards. In recent times, the game [has been subject to research](https://programming-journal.org/2019/3/4/) — despite the strict hardware limitations of the Atari 2600, it somehow manages to create solvable mazes every time. By disassembling the game's ROM, researchers discovered that this is done with the help of a mysterious lookup table.
When a tile **X** is to be generated, the game first looks at the states of 5 tiles **A**, **B**, **C**, **D**, and **E** which are around it:
$$
\bbox[5px, border: 1px solid white]{\color{white}{\mathsf{x}}}
\bbox[6px, border: 1px solid black]{\mathtt{C}}\,
\bbox[6px, border: 1px solid black]{\mathtt{D}}\,
\bbox[6px, border: 1px solid black]{\mathtt{E}}\\
\;
\bbox[6px, border: 1px solid black]{\mathtt{A}}\,
\bbox[6px, border: 1px solid black]{\mathtt{B}}\,
\bbox[6px, border: 1px solid white]{{\mathtt{X}}}\,
\bbox[10px, border: 1px solid white]{\color{white}{\mathsf{x}}}\,
$$
These five values then index into the following 32-byte lookup table to determine what should appear at **X** — a wall, an empty space, or either a wall **or** an empty space, chosen at random:
```
A B C D E X
0 0 0 0 0 1
0 0 0 0 1 1
0 0 0 1 0 1
0 0 0 1 1 R
0 0 1 0 0 0
0 0 1 0 1 0
0 0 1 1 0 R
0 0 1 1 1 R
0 1 0 0 0 1
0 1 0 0 1 1
0 1 0 1 0 1
0 1 0 1 1 1
0 1 1 0 0 R
0 1 1 0 1 0
0 1 1 1 0 0
0 1 1 1 1 0
1 0 0 0 0 1
1 0 0 0 1 1
1 0 0 1 0 1
1 0 0 1 1 R
1 0 1 0 0 0
1 0 1 0 1 0
1 0 1 1 0 0
1 0 1 1 1 0
1 1 0 0 0 R
1 1 0 0 1 0
1 1 0 1 0 1
1 1 0 1 1 R
1 1 1 0 0 R
1 1 1 0 1 0
1 1 1 1 0 0
1 1 1 1 1 0
```
Here **R** represents a value to be chosen randomly.
## Task
Given values for **A**, **B**, **C**, **D**, and **E** as input, your program or function should output the correct value for **X** (either 0 or 1, depending on which row of the table the input corresponds to). **However**, if the input corresponds to a row in the table with an **X** value of **R**, your program should output either 0 or 1 uniformly randomly.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* Your input can be given in any reasonable format, e.g. a list of values, a string with the values in it, an integer in the range [0..31], etc.
* When receiving input that corresponds to an **X** value of **R** in the table, your output has to be non-deterministic.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~19~~ 15 bytes
```
ị“£ṅ@kṃżF’b3¤BX
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//4buL4oCcwqPhuYVAa@G5g8W8RuKAmWIzwqRY////MTU "Jelly – Try It Online")
-4 bytes after inspiration from @Neil's Charcoal Answer (binary!).
[Try all testcases](https://tio.run/##y0rNyan8///h7u5HDXMOLX64s9Uh@@HO5qN73B41zEwyPrTEKeJ/@MNd3UYGx7oeNa053A4kgIjL2Ojhjm06h9tVoo5OerhzBkQ0C2iGgq2dwqOGuSpAbuR/AA "Jelly – Try It Online") listed out in a grid (each row is one input tested multiple times).
### How?
```
ị“£ṅ@kṃżF’b3¤BX # Main link
“©½B.ọṅc’ # The integer 1719989029560350
b3 # to base 3: [1,1,2,0,0,2,2,1,1,1,1,2,0,0,0,1,1,1,2,0,0,0,0,2,0,1,2,2,0,0,0,1]
# (2 => R; 1 => 1; 0 => 0)
ị ¤ # Index the input into the base 3 list above
# (1-indexed, and 0 gives the last element)
B # convert to binary: 2 => [0,1], 1 => [1], 0 => [0]
X # Pick a random element from that list
```
---
## 19 byte version
(I personally like this one more because it uses special properties of `ị` and `X`)
[Try it online!](https://tio.run/##AScA2P9qZWxsef//4buL4oCcwqPhuYVAa@G5g8W8RuKAmWIzwqRY////MTU "Jelly – Try It Online")
[Try all testcases](https://tio.run/##y0rNyan8///h7u5HDXMOrTy010nv4e7ehztbkx81zEwyPrTEAyhlqGMQ8T/84a5uI4NjXY@a1hxuBxJAxGVs9HDHNp3D7SpRRyc93DkDIpoFNEnB1k7hUcNcFSA38j8A "Jelly – Try It Online").
```
ị“©½B.ọṅc’b3¤Hị1,0X # Main link
“©½B.ọṅc’ # The integer 1719989029560350
b3 # to base 3: [2,2,1,0,0,1,1,2,2,2,2,1,0,0,0,2,2,2,1,0,0,0,0,1,0,2,1,1,0,0,0,2]
# (2 => 1; 1 => R; 0 => 0)
ị ¤ # Index the input into the base 3 list above
# (1-indexed, and 0 gives the last element)
H # Halve: [2,1,0] => [1,0.5,0]
ị1,0 # Index into 1,0 (again 1-indexed)
# 1 gives 1, and 0 gives 0
# 0.5 gives [0,1]; since it is a fractional index, it gives both the element corresponding to floor(0.5) and ceil(0.5)
X # Random; 3 different functions
# 0 => 0
# 1 => random integer from 1 to 1 => 1
# [0,1] => random element of [0,1]
```
[Answer]
# JavaScript (ES6), 47 bytes
Expects an integer in \$[0..31]\$ as input.
Similar to [@histocrat's Ruby answer](https://codegolf.stackexchange.com/a/206379/58563), except that the \$\text{R}\$-mask is left-shifted by 1 position so that we can directly get \$0\$ or \$2\$.
```
n=>Math.random()*(975060894>>n&2)|67571463>>n&1
```
[Try it online!](https://tio.run/##TczBasJAEAbgu08xp@5MU5fZaBKtTaAP0Mt6FJHFGBvR2bAuhdL22dOk9iBz@P@Bj//kPtx1H9ouTsXXh74peymrNxffdXBS@wvSIy6LjHNeLOdVJQ8pfedFVph5Phtf0zc@oEAJvAKBF5ilQyYJwdcEYO/l6s8HffZHFB39OoZWjki6c/U6uhAxJUhADZfAHUjvRPYEitWN4eiUMcYyW2tuhf@DLRs7FrWR7egInv@GN1rr1xDcJxqmrb64DndQVtCgEOmTb2XYVUSryU//Cw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~58 56~~ 49 bytes
Expects an integer in \$[0..31]\$ as input.
```
n=>(Math.random(k=n*5%62%46%18)*2|k<11)&253553>>k
```
[Try it online!](https://tio.run/##TczBTsMwEATQe79iL8G7DVi2QypE60h8ABf3WFXIapqSpl1HroWEgG8PCeVQzWHm8DRH/@Evu9j26YFDvR8aO7Ct8NWndxk91@GMneV5mS1M9rjI9BPNzXe30pruTFmUZVFV3dCEiAwW1BIYVlCYsfOc4GsGsAt8Cae9PIUDskxhnWLLByTZ@3qdfExoCHIQY3K4AeZGlPcglLgynJzQWjulnNPXof5LOaXdNMSGt5MjeP473kgpX2L0n6gVbeXZ9/gGtoIGmUgeQ8vjryBazn6GXw "JavaScript (Node.js) – Try It Online")
### How?
The input \$n\$ is turned into an index \$k \in[0..17]\$ with the following formula:
$$\big(((n\times 5)\bmod 62)\bmod 46\big)\bmod 18$$
In addition to reducing the size of the lookup table, it isolates all \$\text{R}\$ values at the end of the table, with an index greater than \$10\$.
As a string, the lookup table looks as follows:
```
10001110011RR0RRRR
```
Therefore, we can use a bitmask to determine if the answer is either \$0\$ or something else, and the test \$k<11\$ to decide between \$1\$ and \$\text{R}\$.
```
n | * 5 | mod 62 | mod 46 | mod 18 | output
----+-----+--------+--------+--------+--------
0 | 0 | 0 | 0 | 0 | 1
1 | 5 | 5 | 5 | 5 | 1
2 | 10 | 10 | 10 | 10 | 1
3 | 15 | 15 | 15 | 15 | R
4 | 20 | 20 | 20 | 2 | 0
5 | 25 | 25 | 25 | 7 | 0
6 | 30 | 30 | 30 | 12 | R
7 | 35 | 35 | 35 | 17 | R
8 | 40 | 40 | 40 | 4 | 1
9 | 45 | 45 | 45 | 9 | 1
10 | 50 | 50 | 4 | 4 | 1
11 | 55 | 55 | 9 | 9 | 1
12 | 60 | 60 | 14 | 14 | R
13 | 65 | 3 | 3 | 3 | 0
14 | 70 | 8 | 8 | 8 | 0
15 | 75 | 13 | 13 | 13 | 0
16 | 80 | 18 | 18 | 0 | 1
17 | 85 | 23 | 23 | 5 | 1
18 | 90 | 28 | 28 | 10 | 1
19 | 95 | 33 | 33 | 15 | R
20 | 100 | 38 | 38 | 2 | 0
21 | 105 | 43 | 43 | 7 | 0
22 | 110 | 48 | 2 | 2 | 0
23 | 115 | 53 | 7 | 7 | 0
24 | 120 | 58 | 12 | 12 | R
25 | 125 | 1 | 1 | 1 | 0
26 | 130 | 6 | 6 | 6 | 1
27 | 135 | 11 | 11 | 11 | R
28 | 140 | 16 | 16 | 16 | R
29 | 145 | 21 | 21 | 3 | 0
30 | 150 | 26 | 26 | 8 | 0
31 | 155 | 31 | 31 | 13 | 0
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 35 bytes
```
->i{[67571463,487530447].sample[i]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6zOtrM3NTc0MTMWMfEwtzU2MDExDxWrzgxtyAnNToztva/hoGenrGhpl5uYkF1TWaNQkFpSbGGkmqmgmqBkmp0pk60gY5hrFq0FlCZpWWsXlpmTk51GkhnrKZC7X8A "Ruby – Try It Online")
There are 128 different pairs of numbers such that the nth bit is 0 for both when the table's value is 0, 1 for both when the table's value is 1, and different when the table's value is R. So we just choose one of the two at random and take the nth bit.
It seems very likely there's a way to compress this array since we have 128 pairs to choose from, but some quick searching didn't turn it up.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 19 bytes
```
‽⍘I§”)∨‴)C]!P"”↨²S²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMoMS8lP1fDKbE4NbgEKJKu4ZxYXKLhWOKZl5JaoaFkaGhoZGBgZGQIYRhAKQMjA0MjEENJRwGkV8NIR8Ezr6C0BGqIJhDoKBgBSev//w0Ngdr@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of five bits. Explanation:
```
”...” Compressed string
§ Indexed by
S Input string
↨² Converted from base 2
I Cast to integer
⍘ ² Converted to base 2
‽ Random element
Implicitly print
```
The compressed string contains `2` where either `0` or `1` is allowed. This converts to base two as `10` thus giving the randomisation operator a choice.
[Answer]
# [J](http://jsoftware.com/), ~~30~~ 28 bytes
Takes in an integer.
```
>.@?@{&(36bkmh2k8esv#:~32#3)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7fQc7B2q1TSMzZKyczOMsi1Si8uUreqMjZSNNf9r/tewTtNUMlDI1FMwNgIA "J – Try It Online") Apparently TIO resets J's random seed every session. If you run it locally, the results of **R** will change.
### How it works
```
>.@?@{&(36bkmh2k8esv#:~32#3)
36bkmh2k8esv base 36 representation of the table
with 0 and 1 swapped
#:~32#3 back to base 3 (there is usually the
shorter 3#.inv, but that would drop the
leading 0's.)
{ get the corresponding entry
? roll: 1 -> 0
2 -> 0 or 1
0 -> open interval (0,1)
>. round up the floats from 0.… to 1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 66 bytes
```
lambda n:randint(67571463>>n&1,487530447>>n&1)
from random import*
```
[Try it online!](https://tio.run/##HYzBCsMgEAXv@Yo9NVpaSKrGIsQv6cWQ2i7UVcRLCfl2U3t6zDC89C3vSKL6@VE/LiyrAzLZ0YpU2KSVHuUkrKXTeJF3rcQgpf4j73yOAVr6Gwwp5nKuPmZAQGr@9WTixk0HkHJ78/2GZlDLDlcLm2fI957XAw "Python 3 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 55 bytes
```
~`.+
K`111R00RR1111R000111R0000R01RR000¶$&L`.
R
10
@L`.
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8L8uQU@byzvB0NAwyMAgKMgQwjCAUgZBBoZBIMahbSpqPgl6XEFchgZcDkDW//9GplxGZlxG5gA "Retina – Try It Online") Link includes test cases. Explanation:
```
.+
K`111R00RR1111R000111R0000R01RR000¶$&L`.
```
Replace the input by Retina code that takes the `n`th character of the lookup table.
```
~`
```
Evaluate that code.
```
R
10
```
Change `R` to `10`.
```
@L`.
```
Output a random character.
[Answer]
# Excel, ~~63 56~~ 55 bytes
Cell `A1` (33 bytes):
```
=MID(BASE(940349744638137,3),A2,1
```
Cell `B1` (Output Cell, 22 bytes):
```
=--IF(A1-2,A1,.5<RAND(
```
*-8 thanks to @Calculuswhiz*
Input goes into cell `A2`. Input is 1 indexed rather than 0 indexed, and needs to be in the range \$[1, 32]\$
## But How?
Well, lets first look at cell `A1`. This is where the row lookup is performed.
```
BASE(940349744638137,3) | Produces the number 11120022111120001112000020122000
=MID( ,A2,1 | Indexes that number at the position in A2 (input)
```
Then, we go to cell `B1` (the output cell). This is where we check if we need to pick a random number.
```
IF(A1-2, | Coerce A1 to Number and subtract 2 from it.
A1, | If A1 isn't 2, condition is nonzero->TRUE. Set to A1.
.5<RAND( | Otherwise, pick FALSE or TRUE at random
=-- | Coerce Boolean to Number, or do nothing to Number
```
## Where's the Closing Brackets?!?
[Not needed](https://codegolf.meta.stackexchange.com/a/19037/78850). That's where. ;P
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•3-aáδÜ[•3вbIèΩ
```
Input as an integer in the range \$[0,31]\$.
[Try it online](https://tio.run/##yy9OTMpM/f//UcMiY93EwwvPbTk8JxrEubApyfPwinMr//83BgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9seGySn72SwqO2SQpK9v8fNSwy1k08vPDclsNzokGcC5uS/A6vOLfyv85/YwA).
**Explanation:**
```
•3-aáδÜ[• # Push compressed integer 940349744638137
3в # Convert it to base-3 as list:
# [1,1,1,2,0,0,2,2,1,1,1,1,2,0,0,0,1,1,1,2,0,0,0,0,2,0,1,2,2,0,0,0]
b # Take the binary string of each, converting the 2s to 10s:
# [1,1,1,10,0,0,10,10,1,1,1,1,10,0,0,0,1,1,1,10,0,0,0,0,10,0,1,10,10,0,0,0]
Iè # Index the input-integer into this list
Ω # And pop and push a random digit of this integer
# (after which it is output implicitly as result)
```
[See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•3-aáδÜ[•` is `940349744638137` and `•3-aáδÜ[•3в` is `[1,1,1,2,0,0,2,2,1,1,1,1,2,0,0,0,1,1,1,2,0,0,0,0,2,0,1,2,2,0,0,0]`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input as `0-31`.
```
g`qn77sq5p`nH ì3)¤ö
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z2BxbjeMN3NxNXBgbkgg7DMppPY&input=MzIKLW0) - includes all test cases
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~81~~ \$\cdots\$ ~~66~~ 52 bytes
Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
Saved a whopping 14 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!!
```
f(n){n=(n=0x29200950255a095l>>n*2&3)<2?n:time(0)&1;}
```
[Try it online!](https://tio.run/##dVDBboMwDL33KyykVqFNpWDEgaVhh2lfMXpgFNZINK0AaUiIb2cOkJbLLCeOX/L8HOfHnzwfx5IZvzeKGSU6jFGIOBIYRRnFKknMHnehf8J389bqW8GEvwvkMN4ybZgP/QbI8mtW76H@OoOC3ku7T0y7@INW5HFY56E3yImhTQtt9l0VMyfgMDtyEJPj5MHKn1fiH1C4NHD0BV80y3sNzAprkhSSwglClHA4aPcR11pDL0qmfflCS2Bzw5o6VoBrirXfq64KYJalVLNiWrP18AUNz9OjJrmSedsLHBOgfdukhoamOTScJtpYLad7XqoOm2H8Aw "C (gcc) – Try It Online")
Inputs an integer in the range \$[0,31]\$ and returns either \$0\$, \$1\$, or one of them randomly.
Uses the bits of a `long int` to map each return value to 2-bits.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 14 bytes
```
3»∧l%≥D⋎v»τiB℅
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=3%C2%BB%E2%88%A7l%25%E2%89%A5D%E2%8B%8Ev%C2%BB%CF%84iB%E2%84%85&inputs=31&header=&footer=)
Takes input as a number.
] |
[Question]
[
## Objective
*From [Wikipedia](http://en.wikipedia.org/wiki/Recursive_acronym) :*
>
> A recursive acronym is an acronym that refers to itself in the expression for which it stands.
>
>
>
Your goal is to check if a string is a recursive acronym.
* The acronym is the first word
* Words are not case sensitive, separated with a single space.
* The given string does not contain any punctuation nor apostrophe.
* Only the first letter of each word can be part of the acronym.
You must also give the [function words](http://en.wikipedia.org/wiki/Function_word). For simplicity, every word can be considered as a function word.
## Example
```
f("RPM Package Manager") => { true, [] }
f("Wine is not an emulator") => { true, ["an"] }
f("GNU is not Unix") => { true, ["is"] }
f("Golf is not an acronym") => { false }
f("X is a valid acronym") => { true, ["is","a","valid","acronym"] }
```
You can give a full program or a function.
The input string can be taken from STDIN or as a function argument.
Output result can be true/false, 0/1, yes/no...
The function words list (any format of list is valid) must be given *if and only if* this is a recursive acronym (even if the list is empty). You do not have to preserve capitalization of the function words.
## Winning criteria
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins.
[Answer]
## Regex, .NET flavour, 62 bytes
```
(?i)(?<=^\w(?<c>\w)*)( \k<c>(?<-c>)\w+| (?<w>\w+))*$(?(c)(?!))
```
[You can test it here](http://regexhero.net/tester/). If the input is a recursive acronym, this will yield a match, and capturing group `w` will contain all function words. If it isn't, then there will be no match.
This *does* preserve capitalisation of the function words (but matches case-insensitively).
Unfortunately, the tester doesn't display the entire stack of a named capturing group, but if you used it anywhere in .NET, the `w` group *would* contain all function words in order.
Here is a C# snippet to prove that:
```
var pattern = @"(?i)(?<=^\w(?<c>\w)*)( \k<c>(?<-c>)\w+| (?<w>\w+))*$(?(c)(?!))";
var input = new string[] {
"RPM Package Manager",
"Wine is not an emulator",
"GNU is not Unix",
"Golf is not an acronym",
"X is a valid acronym"
};
var r = new Regex(pattern);
foreach (var str in input)
{
var m = r.Match(str);
Console.WriteLine(m.Success);
for (int i = 0; i < m.Groups["w"].Captures.Count; ++i)
Console.WriteLine(m.Groups["w"].Captures[i].Value);
}
```
Here is a quick explanation. I'm using .NET's [balancing groups](https://stackoverflow.com/questions/17003799/what-are-regular-expression-balancing-groups/17004406#17004406) to build a stack of the acronym letters in the named group `c`, with this snippet
```
^\w(?<c>\w)*
```
The trick is that I need the second letter on top of the stack and the last one at the bottom. So I put all of this in a lookbehind that matches the position *after* the acronym. This helps, because .NET matches lookbehinds from right to left, so it encounters the last letter first.
Once I got that stack, I match the rest of the string word for word. Either the word begins with the letter on top of the acronym stack. In that case I pop that letter from the stack:
```
\k<c>(?<-c>)\w+
```
Otherwise, I match the word anyway and push onto the `w` stack which will then contain all function words:
```
(?<w>\w+)
```
At the end I make sure I reached the end of the string with `$` and also make sure that I've used up all letters from the acronym, by checking that the stack is empty:
```
(?(c)(?!))
```
[Test it on ideone.](http://ideone.com/gwZXYg)
[Answer]
# Python (158, without regex)
It's not that I don't like regexes. It's that I don't know them.
```
def f(x):
s=x.lower().split();w=list(s[0][1:]);s=s[1:];o=[]
if not w:return 1,s
[w.pop(0)if i[0]==w[0]else o.append(i)for i in s]
return(0,)if w else(1,o)
```
Oh, I also had an ungolfed version:
```
def acronym(string):
scentence = string.lower().split()
word = scentence[0][1:]
scentence = scentence[1:]
over = []
if not word: return 1, scentence
for item in scentence:
if item[0] == word[0]:
word = word[1:]
else:
over.append(item)
if word:
return 0,
return 1,over
```
[Answer]
## GolfScript, ~~51~~ 50 chars
```
{32|}%" "/(1>\{.1<2$1<={;1>}{\}if}/{]!}{]`1" "@}if
```
It probably can be golfed further. Takes input on STDIN. The boolean is 0/1.
[Test online](http://golfscript.apphb.com/?c=O1siUlBNIFBhY2thZ2UgTWFuYWdlciIgIldpbmUgaXMgbm90IGFuIGVtdWxhdG9yIiAiR05VIGlzIG5vdCBVbml4IiAiR29sZiBpcyBub3QgYW4gYWNyb255bSIgIlggaXMgYSB2YWxpZCBhY3JvbnltIl17CnszMnx9JSIgIi8oMT5cey4xPDIkMTw9ezsxPn17XH1pZn0ve10hfXtdYDEiICJAfWlmCiJcbiJ9JQ%3D%3D)
---
Explanation:
```
{32|}% # change everything to lower-case
" "/ # splits the string by spaces
(1> # takes the first word out and removes the first letter
\ # moves the list of remaining words in front of the acronym word
{ # for every word:
.1<2$1<= # compares the first letter of the word with
# the next unmatched letter of the acronym
{;1>} # if they are the same, discard the word and the now-matched letter
{\} # otherwise store the word in the stack
if # NB. if all letters have been matched, the comparison comes out as false
}/
{]!} # if there are still unmatched letters, return 0 (`!` non-empty list)
{]`1" "@} # otherwise, return 1, and display the list of function words
if
```
[Answer]
# Python 2.7 - ~~131~~ 126 bytes
```
def f(s):
s=s.lower().split();a,f=list(s[0]),[]
for w in s:f+=0*a.pop(0)if a and w[0]==a[0]else[w]
return(0,)if a else(1,f)
```
Makes a list of letters in the first word of the acronym. Then, for each word in the full string, get rid of the first element of that list we made if it is the same as the first letter of that word. Otherwise, add that word to the list of function words. To output, return `not a` (In python, any list other than the empty list is `True`-y, and the list is empty if it's a recursive acronym) and the list if `not a`.
Thanks to @ace for helping me fix an error/save some bytes.
[Answer]
# Python - 154 characters
First ever code golf attempt. I'm thinking python isn't the best language for it, given all the long keywords. Also, I don't think this function is foolproof. It works for the OP's input, but I'm sure I could think up exceptions.
```
def f(s):
w=s.lower().split();r=list(w[0]);return(True,[x for x in w if x[0]not in r])if len(r)==1 or[x for x in[y[0]for y in w]if x in r]==r else False
```
[Answer]
# ECMAScript 6 (105 bytes):
```
f=s=>(r=(a=s.toUpperCase(i=1).split(' ')).map((w,c)=>c?a[0][i]==w[0]?(i++,''):w:''),a[0].length==i?1+r:0)
```
Enter the function in Firefox's browser console, and then just call the function, like this:
```
f('ABC Black Cats') // 1,,
f('ABC is Black Cats') // 1,IS,,
f('ABC Clapping Cats') // 0
```
[Answer]
# Haskell - 287 bytes
Not the shortest entry (hey this is Haskell, what did you expect?), but still a lot a fun to write.
```
import Data.Char
import Data.List
f""w=map((,)False)w
f _[]=[]
f(a:as)(cs@(c:_):w)
|toLower a==toLower c=(True,cs):f as w
|True=(False,cs):f(a:as)w
g s=if(length$filter(fst)d)==length v
then Just$map(snd)$snd$partition(fst)d
else Nothing
where
w=words s
v=head w
d=f v w
```
Tested with
```
map (g) ["RPM Package Manager","Wine is not an emulator","GNU is not Unix","Golf is not an acronym","X is a valid acronym"]
```
Expected output
```
[Just [],Just ["an"],Just ["is"],Nothing,Just ["is","a","valid","acronym"]]
```
# Ungolfed
```
import Data.Char
import Data.List
f :: String -> [String] -> [(Bool, String)]
f "" w = map ((,) False) w
f _ [] = []
f (a:as) ((c:cs):w) | toLower a == toLower c = (True, c:cs) : f as w
| otherwise = (False, c:cs) : f (a:as) w
g :: String -> Maybe [String]
g s = if (length $ filter (fst) d) == (length v)
then Just $ map (snd) $ snd $ partition (fst) d
else Nothing
where w = words s
v = head w
d = f v w
```
[Answer]
# JavaScript (ECMAScript 6) - 97 Characters
```
f=x=>(r=(a=x.toLowerCase(i=0).split(' ')).filter(y=>y[0]!=a[0][i]||i-i++),i==a[0].length?[1,r]:0)
```
**Tests:**
```
f("RPM Package Manager")
[1, []]
f("GNU is not Unix")
[1, ["is"]]
f("X is an acronym")
[1, ["is", "an", "acronym"]]
f("Golf is not an acronym")
0
f("Wine is not an emulator")
[1, ["an"]]
```
[Answer]
# Rebol - 133
```
f: func[s][w: next take s: split s" "y: collect[foreach n s[either n/1 = w/1[take w][keep n]]]reduce either/only w: empty? w[w y][w]]
```
Ungolfed:
```
f: func [s] [
w: next take s: split s " "
y: collect [
foreach n s [
either n/1 = w/1 [take w][keep n]
]
]
reduce either/only w: empty? w [w y][w]
]
```
Tested with:
```
foreach t [
"RPM Package Manager" "Wine is not an emulator"
"GNU is not Unix" "Golf is not an acronym"
"X is a valid acronym"
][probe f t]
```
Output:
```
[true []]
[true ["an"]]
[true ["is"]]
[false]
[true ["is" "a" "valid" "acronym"]]
```
[Answer]
# Julia - 116 bytes
```
f(w)=(a=split(lowercase(w));L=1;A=a[];while a!=[];a[][1]==A[1]?A=A[2:]:(L=[L,a[]]);a=a[2:];A>""||return [L,a];end;0)
```
Less Golfed:
```
f(w)=(
a=split(lowercase(w))
L=1
A=a[]
while a!=[]
if a[][1]==A[1]
A=A[2:]
else
L=[L,a[]]
end
a=a[2:]
if !(A>"")
return [L,a]
end
end
0)
```
The `0` on the end makes it output 0. Otherwise, it outputs an array containing `1` followed by the function words. For example:
```
julia> f("RPM Package Manager")
1-element Array{Any,1}:
1
julia> f("Golf is not an acronym")
0
julia> f("GNU is not Unix")
2-element Array{Any,1}:
1
"is"
julia> f("X is a valid acronym")
5-element Array{Any,1}:
1
"is"
"a"
"valid"
"acronym"
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 29 bytes
```
ḷṇ₁XhY∧X;0zpᵐz{ċ₂ˢ}ᵐZhhᵐcY∧Zt
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcL/hzu2P9zZ/qipMSIjEigfYW1QVQAUr6o@0v2oqen0IpCiqIwMIJkMko8q@f8/WikowFchIDE5OzE9VcE3MQ9IFSnpKIVn5qUqZBYr5OWXKCTmKaTmluYkluSDZNz9QmESoXmZFSCR/Jw0JLWJyUX5eZW5QIkIkGiiQlliTmYKXDgWAA "Brachylog – Try It Online")
Outputs the function words through the output variable if the input is a recursive acronym, and fails if it is not.
```
X X is
ḷ the input lowercased
ṇ₁ and split on spaces,
hY the first element of which is Y
∧ (which is not X).
X z X zipped
;0 with zero,
pᵐ with all pairs permuted (creating a choicepoint),
z zipped back,
{ }ᵐ and with both resulting lists
ċ₂ˢ losing all non-string elements,
Z is Z.
hᵐ The first elements of the elements of
Zh the first element of Z
cY concatenated are Y
∧ (which is not Z).
Zt The last element of Z is the output.
```
Without having to output the function words (treating this as a pure [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")), it comes out to just 12 bytes, because `∧Zt` can be dropped for -3, `Y` can be replaced with `.` for -1, and most importantly `;0zpᵐz{ċ₂ˢ}ᵐZh` can be replaced with `⊇` for a whopping -13: [`ḷṇ₁Xh.∧X⊇hᵐc`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f7hj@8Od7Y@aGiMy9IDyEY@62jOA4sn//0crBQX4KgQkJmcnpqcq@CbmAakiJR2l8My8VIXMYoW8/BKFxDyF1NzSnMSSfJCMu18oTCI0L7MCJJKfk4akNjG5KD@vMhcoEQESTVQoS8zJTIELxwIA)
[Answer]
# Cobra - 187
```
def f(s as String)
l=List<of String>(s.split)
a=l[0]
l.reverse
o=0
for c in a,for w in l.reversed
if c==w[0]
l.pop
o+=1
break
x=o==a.length
print x,if(x,l,'')
```
[Answer]
# Ruby - 173
Could be better...
```
f=->s{a=[];o={};s=s.split;r=true;s[0].each_char{|c|s.each{|w| w[0]=~/#{c}/i?(o[c]=1;a<<w if o[c]):(o[c]=0 if !o[c])}};r,a=false,s if o.values&[0]==[0];!r ?[r]:[r,(s-(a&a))]}
```
Calling the func :
```
p f.call('RPM Package Manager')
p f.call('Wine is not an emulator')
p f.call("GNU is not Unix")
p f.call("Golf is not an acronym")
p f.call("X is a valid acronym")
```
Output :
```
[true, []]
[true, ["an"]]
[true, ["is"]]
[false]
[true, ["is", "a", "valid", "acronym"]]
```
[Answer]
## Java - 195
Unfortunately, Java does not have built in tuple support.
So, this is a class that stores the boolean in 'b' and the function word list in 'x'.
Here, the function is the constructor of the class.
```
static class R{boolean b;String[]x;R(String s){String v=" ",i="(?i)",f=s.split(v)[0],r=i+f.replaceAll("(?<=.)",".* ");if(b=(s+=v).matches(r))x=(s.replaceAll(i+"\\b["+f+"]\\S* ","")+v).split(v);}}
```
Test
```
public class RecursiveAcronyms {
public static void main(String args[]) {
String[] tests = {
"RPM Package Manager",
"Wine is not an emulator",
"GNU is not Unix",
"Golf is not an acronym",
"X is a valid acronym"
};
for (String test:tests) {
R r = new R(test);
System.out.print(r.b);
if (r.b) for (String s:r.x) System.out.print(" "+s);
System.out.print("\n");
}
}
static class R{boolean b;String[]x;R(String s){String v=" ",i="(?i)",f=s.split(v)[0],r=i+f.replaceAll("(?<=.)",".* ");if(b=(s+=v).matches(r))x=(s.replaceAll(i+"\\b["+f+"]\\S* ","")+v).split(v);}}}
```
[Answer]
# Awk - 145
```
awk -v RS=' ' '{c=tolower($0)};NR==1{w=c};{t=substr(c,1,1)!=substr(w,NR-s,1);if(t){f=f" "c;s++};a=a||t};END{print a&&(s>NR-length(w))?"N":"Y|"f}'
```
Test:
```
$ cat gcp.sh
#!/bin/sh
f() {
echo "$1:"
echo "$1"|awk -v RS=' ' '{c=tolower($0)};NR==1{w=c};{t=substr(c,1,1)!=substr(w,NR-s,1);if(t){f=f" "c;s++};a=a||t};END{print a&&(s>NR-length(w))?"N":"Y|"f}'
}
f "RPM Package Manager"
f "Wine is not an emulator"
f "Wine is not an appropriate emulator"
f "GNU is not Unix"
f "Golf is not an acronym"
f "Go is not an acronym"
f "Go is a valid acronym OK"
f "X is a valid acronym"
f "YAML Ain't Markup Language"
$ ./gcp.sh
RPM Package Manager:
Y|
Wine is not an emulator:
Y| an
Wine is not an appropriate emulator:
Y| an appropriate
GNU is not Unix:
Y| is
Golf is not an acronym:
N
Go is not an acronym:
N
Go is a valid acronym OK:
Y| is a valid acronym
X is a valid acronym:
Y| is a valid acronym
YAML Ain't Markup Language:
Y|
```
[Answer]
# Coffeescript - 144
```
z=(a)->g=" ";b=a.split g;c=b[0];d=[];(d.push(e);g++)for e,f in b when e[0].toLowerCase()!=c[f-g].toLowerCase();if(g+c.length==f)then{1,d}else{0}
```
Call it with, for instance: `z "GNU is not Unix"`
The compiled JS:
```
var z;
z = function(a) {
var b, c, d, e, f, g, _i, _len;
g = " ";
b = a.split(g);
c = b[0];
d = [];
for (f = _i = 0, _len = b.length; _i < _len; f = ++_i) {
e = b[f];
if (e[0].toLowerCase() !== c[f - g].toLowerCase()) {
d.push(e);
g++;
}
}
if (g + c.length === f) {
return {
1: 1,
d: d
};
} else {
return {
0: 0
};
}
};
```
It splits the string into words and then loops through each word. If the first character of the word doesn't match the next in the acronym, the word is stored. A counter (`g`) is used to track how many words have been skipped. If the number of skipped words plus the length of the acronym matches the length of the phrase, it matched, so return 1 and the skipped words. If not, it was not valid, so return 0.
[Answer]
# C# - 234
```
Tuple<bool,string[]> f(string w) {var l=w.ToLower().Split(' ');var o=new List<string>();int n=0;var a=l[0];foreach(var t in l){if(n>=a.Length||a[n]!=t[0])o.Add(t);else n++;}var r=n>=a.Length;return Tuple.Create(r,r?o.ToArray():null);}
```
[Answer]
# Python (108)
```
l=raw_input().lower().split()
a=l[0]
e=[]
for w in l:d=w[0]!=a[0];a=a[1-d:];e+=[w]*d
b=a==''
print b,b*`e`
```
] |
[Question]
[
Lets define the process of crushing an array of numbers. In a crush we read the array left to right. If at a point we encounter two of the same element in a row we remove the first one and double the second one. For example here is the process of crushing the following array
```
[5,2,2,3]
^
[5,2,2,3]
^
[5,2,2,3]
^
[5,4,3]
^
[5,4,3]
^
```
The same element can be collapsed multiple times, for example `[1,1,2]` becomes `[4]` when crushed.
We will call an array uncrushable when the process of crushing that array does not change it. For example `[1,2,3]` is still `[1,2,3]` after being crushed.
Your task is to take an array and determine the number of crushes required to make it uncrushable. You need only support integers on the range of **0** to **232-1**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
## Test Cases
```
[1] -> 0
[1,1] -> 1
[2,1,1] -> 2
[4,2,1,1] -> 3
[2,2,2,1,1] -> 3
[0,0,0,0] -> 1
[4,0,0,0,4] -> 1
[4,0,0,0,0,4] -> 1
[] -> 0
```
[Answer]
# x86 assembly (64-bit), 66 65 bytes
```
31 c0 57 59 56 51 56 5f 4d 31 c0 48 83 c6 08 48
83 e9 01 76 1b fc f2 48 a7 75 15 48 d1 67 f8 51
56 57 f3 48 a5 5f 5e 59 fd 48 a7 49 ff c0 eb e5
59 5e 4c 29 c1 48 ff c2 4d 85 c0 75 c7 48 ff c8
c3
```
String instructions were helpful. Having to correct for off-by-one errors in a 64-bit environment was not.
Fully commentated source code:
```
.globl crush
crush:
/* return value */
xor %eax, %eax
/* save our length in rcx */
push %rdi
pop %rcx
pass:
/* save the start of the string and the length */
push %rsi
push %rcx
/* this is the loop */
/* first copy source to dest */
push %rsi
pop %rdi
/* and zero a variable to record the number of squashes we make this pass */
xor %r8, %r8
/* increment source, and decrement ecx */
add $8,%rsi
sub $1,%rcx
/* if ecx is zero or -1, we're done (we can't depend on the code to take care of this
automatically since dec will leave the zero flag set and cmpsq won't change it) */
jbe endpass
compare:
/* make sure we're going forward */
cld
/* compare our two values until we find two that are the same */
repne cmpsq
/* if we reach here, we either found the end of the string, or
we found two values that are the same. check the zero flag to
find out which */
jne endpass
/* okay, so we found two values that are the same. what we need
to do is double the previous value of the destination, and then
shift everything leftwards once */
shlq $1, -8(%rdi)
/* easiest way to shift leftwards is rep movsq, especially since
our ecx is already right. we just need to save it and the rsi/rdi */
push %rcx
push %rsi
push %rdi
rep movsq
pop %rdi
pop %rsi
pop %rcx
/* problem: edi and esi are now one farther than they should be,
since we can squash this dest with a different source. consequently
we need to put them back where they were. */
std
cmpsq
/* we don't need to put ecx back since the list is now one shorter
than it was. */
/* finally, mark that we made a squash */
inc %r8
/* okay, once we've reached this point, we should have:
edi and esi: next two values to compare
ecx: number of comparisons left
so we just jump back to our comparison operation */
jmp compare
endpass:
/* we reached the end of the string. retrieve our old ecx and esi */
pop %rcx
pop %rsi
/* rsi is accurate, but rcx is not. we need to subtract the number of squashes
that we made this pass. */
sub %r8, %rcx
/* record that we performed a pass */
inc %rax
/* if we did make any squashes, we need to perform another pass */
test %r8, %r8
jnz pass
/* we reached the end; we've made as many passes as we can.
decrement our pass counter since we counted one too many */
dec %rax
/* and finally return it */
ret
```
I may try doing this in 32-bit, if only for fun, since those REX prefixes really killed me.
Edit: shaved one byte off by replacing lodsq with add, %rdx with %rax, and collapsing two cld's into one.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 22 bytes
```
tl.uu?&GqeGH+PGyH+GHN[
```
[Verify all testcases.](http://pyth.herokuapp.com/?code=tl.uu%3F%26GqeGH%2BPGyH%2BGHN%5B&test_suite=1&test_suite_input=%5B1%5D%0A%5B1%2C1%5D%0A%5B2%2C1%2C1%5D%0A%5B4%2C2%2C1%2C1%5D%0A%5B2%2C2%2C2%2C1%2C1%5D%0A%5B0%2C0%2C0%2C0%5D%0A%5B4%2C0%2C0%2C0%2C4%5D%0A%5B%5D&debug=0)
[Answer]
# [Haskell](https://www.haskell.org/), 66 bytes
```
f(a:b:x)|a==b=f$a+a:x|1>0=a:f(b:x)
f x=x
g x|f x==x=0|1>0=1+g(f x)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SrJqkKzJtHWNsk2TSVRO9GqosbQzsA20SpNAyTDlaZQYVvBla5QUQNi2VbYGoDlDbXTNYACmv9zEzPzbAuKMvNKVNKjDXTAMPY/AA "Haskell – Try It Online")
## Explanation
`f` is a function that crushes a list. It performs the crush as desribed in the question. `g` is a function that counts the number of crushes. If `f x==x`, `g x=0` otherwise `g x=1+g(f x)`.
[Answer]
# [Paradoc](https://github.com/betaveros/paradoc) (v0.2.10), 16 bytes (CP-1252)
```
{—1\ε=k+x}]»}IL(
```
[Try it online!](https://tio.run/##K0gsSkzJT/4fbahgqGCkYKJgoQBnxf6vftQwxTDm3FbbbO2K2thDu2s9fTT@/wcA "Paradoc – Try It Online") / with header/footer that check all [test cases](https://tio.run/##K0gsSkzJT/4fHW0YqxBtqAAijRQgtIkCjGWkYARnGyiAIVgewjZBYkN4EKOAWkwULGJjuaqtEvyVFHTtFJT8/1c/aphiGHNuq222dkVt7KHdtZ4@Gv8DalP/AwA)
Takes a list on the stack, and results in a number on the stack.
Pretty straightforward implementation, to be quite honest. Crushes a list by starting with a sentinel -1, looping through the list, pushing each element and adding it to the element beneath it iff they're equal. At the end we cut off the -1. We only crush equal numbers together and all the problem's numbers are nonnegative, so the -1 sentinel won't affect the crushing process. With crushing implemented, it's only a matter of counting iterations to its fixed point.
Explanation:
```
{ }I .. Iterate this block: repeatedly apply it until a fixed
.. point is reached, and collect all intermediate results
—1 .. Push -1 (note that that's an em dash)
\ .. Swap it under the current list of numbers
ε } .. Execute this block for each element in the list:
= .. Check if it's equal to the next element on the stack...
k .. ... while keeping (i.e. not popping either of) them
+ .. Add the top two elements of the stack...
x .. ... that many times (so, do add them if they were
.. equal, and don't add them if they weren't)
] .. Collect all elements pushed inside the block that
.. we're iterating into a list
» .. Tail: take all but the first element (gets rid of the -1)
L .. Compute the length of the number of intermediate results
( .. Subtract 1
```
If we could assume the input were nonempty, we wouldn't need the sentinel and could shave 2 bytes: `{(\ε=k+x}]}IL(`
Another fun fact: we only lose 2 bytes if we force ourselves to only use ASCII: `{1m\{=k+x}e]1>}IL(`
[Answer]
# JavaScript (ES6), 86 bytes
```
f=a=>a.length>eval("for(i=0;a[i]>-1;)a[i]==a[++i]&&a.splice(--i,2,a[i]*2);i")?1+f(a):0
```
## Ungolfed and Explained
```
f=a=> // function taking array a
a.length > eval(" // if a.length > the result of the following...
for(i=0; a[i]>-1;) // loop from 0 until the current value is undefined (which is not > -1)
a[i] == a[++i] && // if the current value equals the next one...
a.splice(--i, // splice the array at the first index of the pair...
2, // by replacing 2 items...
a[i]*2); // with the current item * 2
// this also decrements the counter, which means the current value is now the next
i") // return the counter, which is new a.length
? 1+f(a) // if that was true, the array was crushed. add 1 and recur with the new array
: 0 // otherwise just return 0
```
## Tests
```
f=a=>a.length>eval("for(i=0;a[i]>-1;)a[i]==a[++i]&&a.splice(--i,2,a[i]*2);i")?1+f(a):0
;[ [1], [1,1], [2,1,1], [4,2,1,1], [2,2,2,1,1], [0,0,0,0], [4,0,0,0,4], [4,0,0,0,0,4], []
].forEach(x=>console.log( JSON.stringify(x) + " -> " + f(x) ))
```
```
.as-console-wrapper{max-height:100%!important}
```
[Answer]
# JavaScript, 67 bytes
```
f=a=>a.map(a=>k[k[d-1]!=a?d++:(a*=z=2,d-1)]=a,k=d=[z=0])&&z&&f(k)+1
```
[Try it online!](https://tio.run/##Tc7BCoMwDAbgV9kupZ1RbPG0ke1BSsFgdWi1lTl2kL175xTHCCRfksvf0Yum6tGOz9QHW8fYIOGVsoFGvsBpp20qzRHpZpPkzOmEMypYbsIggUOLesbcCMZmxhruRCJjFfwU@jrrw51rLQ1oCd@uYJsF7FKgfs5hrfW/ufjzthmzJ2s4iXcusi60vjyU4hI/)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 144 bytes
```
([])({<{}>(<(([][()]){[{}]<({}[({})]<(())>){({}<{}>({})<>)((<>))}>{}{{}(<(({}){})>)}{}([][()])})>{()(<{}>)}{}{}<><([]){{}({}<>)<>([])}>{}<>)}<>)
```
[Try it online!](https://tio.run/##LY2xCgMxDEN/5UZp6HCdjX8kZLgbCqWlQ1fhb8/JpSQyecJSzu/x/Nwe7@O1FsYkFKpEwDDASQ3VDKiGRb9AJmX4LdqLJODBSpVUHbbtmyzjv8goEJ1q2/mM/rETDe5p7BJDa6371mff9gs "Brain-Flak – Try It Online")
### Explanation
```
([]) Push stack height (starts main loop if list nonempty)
{ } Do while the last iteration involved at least one crush:
<{}> Remove crush indicator
<(...)> Do a crush iteration
{()(<{}>)} Evaluate to 1 if list was changed
{}{} Remove zeroes
<> <> On other stack:
<([]){{} ([])}>{} Do while stack is nonempty:
({}<>)<> Move to first stack
( ) Push 1 if crush worked, 0 otherwise
( <>) Push sum of results on other stack and implicitly print
```
The crush function evaluates to the number of pairs of items that were crushed together:
```
([][()]){[{}] ([][()])} Do while stack height isn't 1:
({}[({})] ) Calculate difference between top two elements
<(())> Push a 1 below difference
{ } If difference was nonzero (don't crush this pair)
({} ({})<>) Reconstruct top element and place on other stack
<{}> ((<>)) Push zeros to exit this conditional and skip next
< >{} Evaluate as zero
{ }{} If difference was zero (crush this pair):
{} Evaluate as previously pushed 1
(<(({}){})>) Double top of stack
```
[Answer]
# Java 8, 120 bytes
A lambda from `List<Long>` to `Integer`. Input list must implement `remove(int)` (e.g. `ArrayList`). Assign to `Function<List<Long>, Integer>`.
```
l->{int c=-1,i,f=1;for(;f>0;c++)for(f=i=0;++i<l.size();)if(l.get(i)-l.get(i-1)==0)l.set(i-=f=1,2*l.remove(i));return c;}
```
[Try It Online](https://tio.run/##jZNNa@MwEIbPzq@Yo7SxRRJ6sqNACRQK2VOPpQetKrtKZclIcpZs8G/PjuJAQkk/jA0j5plB7zvjrdiJwnXKbl/fj13/x2gJ0ogQ4LfQFg6TrPN6J6KCEEXEZK2tMLDFMtZHbVjdWxm1s@zhHCwvuY0Ocblxtlnl8GijapRfgfR9eFu73kbgR1OsDhojyYt5rvOaz6vaeVLVq1klp1OaDjXXfFZNp3ppWND/FKEV1TUxrFGRaFqcg2JOOZ9RZE4njr3yxS/DvGrdTiFIK69i7y3Iajhm1QSljXrPynZOv0KLqslT9No2zy8gfBNoMiH7IOqWRpQmggrAr9y5917sAwvRK9ESq/5CQp9fsHfqmh3mZsgn8MmD2Ry@JhYn4jvqDomfkYsz@TN6hsTl@@4G1/Tdl/SA3gw0GcRa0ZGPfpalCMn3T4nLUMoSTR856YxRMl6x41jYekw4H1h0qZTQVJE2JMMFBHJr2iDWOG0ox6GPS5I97UNULXN9ZPjb2Ggsuaw7E11n9uRUh8uYJE7wHY7/AQ)
## Ungolfed lambda
```
l -> {
int
c = -1,
i,
f = 1
;
for (; f > 0; c++)
for (f = i = 0; ++i < l.size(); )
if (l.get(i) - l.get(i - 1) == 0)
l.set(i -= f = 1, 2 * l.remove(i));
return c;
}
```
`c` counts the number of crushes so far, `i` is the index into the list, and `f` indicates whether to continue crushing the list when an iteration finishes. Inside the loops, each adjacent pair is compared. `i` is incremented unconditionally, so if an element is removed by crushing, `i` is decremented first to cancel out the increment. The former element is removed from the list.
## Acknowledgments
* Bugfix thanks to Olivier Grégoire: boxed equality test
[Answer]
# [Perl 5](https://www.perl.org/), 96 bytes
94 code, 2 for `-pa`
```
do{$\++;$l=@F;for($i=0;++$i<@F;){$F[$i]==$F[$i-1]&&splice@F,$i,2,$F[$i--]*2}}while$l!=@F}{$\--
```
[Try it online!](https://tio.run/##JYzBCgIhFAB/ZYPHUukLFfZkwp689QXlIcrogaTsBh0Wf72XFXMYmMOUOKWB@ZoXOAlhIbnR21ue1kBOWSGA9i1sFvBHoODcz6hD388l0SWOXgJJI/8dw9bU@rpTipBWbVXbFpHZdF90p9@5PCk/ZsbDsFNaMZbzBw "Perl 5 – Try It Online")
[Answer]
# JavaScript (ES6), 70 bytes
```
f=(a,j=m=0,t=[])=>a.map(e=>t[e==t[j-1]?(e*=m=2,j-1):j++]=e)&&m&&1+f(t)
```
**Explanation:**
```
f=(
a, //the input
j=m=0, //j is the index into t; m starts out falsey
t=[] //t will hold the crushed array
)=>
a.map(e=> //for each element in the array
t[e==t[j-1] ? //if the element repeats:
(e*=m=2, //... multiply it by two, set m to truthy,
j-1) : //... and index the previous element of t.
j++ //else append to t, and increment its index.
]=e //set this index of t to the current value of e
) && //map is always truthy
m && //if m is falsey, return 0
1+f(t) //else return 1 plus the recurse on t
```
**Test Cases:**
```
f=(a,j=m=0,t=[])=>a.map(e=>t[e==t[j-1]?(e*=m=2,j-1):j++]=e)&&m&&1+f(t)
console.log(f([1])) // 0
console.log(f([1,1])) // 1
console.log(f([2,1,1])) // 2
console.log(f([4,2,1,1])) // 3
console.log(f([2,2,2,1,1])) // 3
console.log(f([0,0,0,0])) // 1
console.log(f([4,0,0,0,4])) // 1
console.log(f([4,0,0,0,0,4])) // 1
console.log(f([])) // 0
```
[Answer]
# [Python 2](https://docs.python.org/2/), 112 110 108 107 105 100 bytes
**Edit:** saved 2 bytes by removing `or` in return statement
**Edit:** saved 2 bytes by having `i` as the index of the second of the two elements to be accessed
**Edit:** saved 1 byte thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
**Edit:** saved 7 bytes thanks to [@jferard](https://codegolf.stackexchange.com/users/72753/jferard)
```
def f(x):
i=e=1
while x[i:]:
if x[~-i]==x[i]:del x[i];i-=1;x[i]*=2;e=2
i+=1
return~-e and-~f(x)
```
[Try it online!](https://tio.run/##VY9NCoMwEIXXzSlmqW0ETV0pOYmEInWCAYliIrUbr24nai1lFvO9Nz/JDG/f9lasa4MadDTHBQMjUWYMXq3pEObKFKpgF6MJl8QoKclSRYNdqKnSJDIrA12lKFEKar2F8RH9NNolQahtkyxh9@rR@cezduhAQhVVmeJpzClzoiyQ4BuLwDk/1H2viD@d8i2OuXxXPD90WKyY7kc43@T0JTd1Hoz9mY5OG0ZjPR1/mvG3df0A)
[Answer]
## JavaScript (ES6), 83 bytes
```
f=([x,y,...a],b=[],c)=>1/x?x==y?f([x+y,...a],b,1):f([y,...a],[...b,x],c):c?1+f(b):0
```
Explanation: The elements are recursively extracted from the original array and unique values are appended to `b` while `c` is a flag to indicate whether the array had been successfully crushed.
[Answer]
# J, 54 bytes
```
[:<:@#[:".@":@(,`(+:@[,}.@])@.({.@]=[))/^:a:@".@":_,|.
```
[Try it online!](https://tio.run/##y/r/P03BVk8h2srGykE52kpJz0HJykFDJ0FD28ohWqdWzyFW00FPoxpI20ZraurHWSVaOYAVxevU6HGlJmfkK6QpaBgoqCgYaCr4OekppOYWlFQqFKeWwCRNFIwUDBUMYVwDCPz/HwA)
Not my best golf by any means. Surely there has to be a better way of converting a list with one item to an atom.
# Explanation
```
crush =. ,`(+:@[ , }.@])@.({.@] = [)/
times =. <:@# [: ".@":@crush^:a:@".@": _ , |.
```
### crush
This crushes an array once. It needs to be given the array in *reverse* since J's insert works right-to-left (something I learned today). This doesn't particularly matter, since all we need to output is the number of times we can crush the array.
```
,`(+:@[ , }.@])@.({.@] = [)/
/ Fold/reduce from the right
{.@] = [ Head of the running array equals the left argument?
+:@[ , If so, prepend double the argument to
}.@] the array minus its head
, Else, prepend the left argument.
```
### times
This is fairly straightforward: apply crush to the array until our result converges, but there are a few issues I had to deal with that result in much more code than I anticipated.
First, when crushing reduces to a single element, that element is actually in a one item list (i.e. it is nonatomic), so the function is applied *again* resulting in overcounting. To fix this, I used a hack I came up with to reduce a single element list to an atom which is `".@":` (convert to string and then evaluate).
Second, `crush` errors on the empty list. I *think* you can define how a function should behave on receiving empty input with insert (`/`), but I couldn't find anything after a cursory look, so I'm using another workaround. This workaround is to prepend `_` (infinity) to the list since it will never affect the number of times the array is crushed (`_ > 2^64`). *However*, this results in a single element list consisting of `_` when given the empty list, so we need to convert to an atom *again* before crushing.
```
<:@# [: ".@":@crush^:a:@".@": _ , |.
|. Reverse input
_ , Prepend infinity
".@": Convert single-element list to atom
crush Crush the list and after
".@": Convert single-element list to atom
^:a: until it converges, storing each
iteration in an array
<:@# Length of the resulting list minus 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ṪḤ,⁼?⁹⁸;µ/Ḋ$¹L’$?ÐĿL’
```
[Try it online!](https://tio.run/##y0rNyan8///hzlUPdyzRedS4x/5R485HjTusD23Vf7ijS@XQTp9HDTNV7A9POLIfxPr//3@0kQ4IGuoYxgIA "Jelly – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~142~~ 75 bytes
```
function(l){while(any(z<-which(!diff(l)))){l[z]=l[z]*2
l=l[-z-1]
F=F+1}
+F}
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jR7O6PCMzJ1UjMa9So8pGF8hJztBQTMlMSwPKAUF1TnRVrC2I0DLiygEydKt0DWO53GzdtA1rubTdav@naSRrGGpqcoFpHRjLSAfBNtFB5hnpGKHwDXTAEK4WwjdB48NEMvNKUtNTizSA6v8DAA "R – Try It Online")
] |
[Question]
[
Earlier this week, we learned about how to [format esoteric languages](https://codegolf.stackexchange.com/questions/92776/esolang-comment-template-generator) for commenting. Today, we're going to do the inverse of that. I need you to write a program or function that parses some well-commented esoteric code and parses the comments out, returning just the code. Using some examples from the previous challenge, here is what well-commented code looks like:
```
a #Explanation of what 'a' does
bc #Bc
d #d
e #Explanation of e
fgh #foobar
ij #hello world
k #etc.
l #so on
mn #and
op #so forth
```
Here is what you need to do to extract the code out. First, remove the comment character (`#`), the space before it, and everything after the comment character.
```
a
bc
d
e
fgh
ij
k
l
mn
op
```
Then, collapse each line upwards into a single line. For example, since `b` is in the second column on line two, once we collapse it up, it will be in the second column on line *one*. Similarly, `c` will be put in the third column of line one, and `d` will be put on the fourth. Repeat this for every character, and you get this:
```
abcdefghijklmnop
```
Important note: It seems like the trivial solution is to just remove the comments, remove every space, and join every line. This is *not* a valid approach! Because the original code might have spaces in it, these will get stripped out with this approach. For example, this is a perfectly valid input:
```
hello #Line one
#Line two
world! #Line three
```
And the corresponding output should be:
```
hello world!
```
# The Challenge:
Write a program or function that takes commented code as input, and outputs or returns the code with all the comments parsed out of it. You should output the code *without* any trailing spaces, although one trailing newline is permissible. The comment character will always be `#`, and there will always be one extra space before the comments start. `#` will *not* appear in the comment section of the input. In order to keep the challenge simpler, here are some inputs you do *not* have to handle:
* You can assume that the code will not have two characters in the same column. For example, this is an input that violates this rule:
```
a #A character in column one
bc #Characters in columns one and two
```
* You can also assume that all comment characters appear in the same column. For example, this input:
```
short #this is a short line
long #This is a long line
```
violates this rule. This also means that `#` will not be in the code section.
* And lastly, you do not have to handle code sections with leading or trailing spaces. For example,
```
Hello, #
World! #
```
You may also assume that the input only contains printable ASCII characters.
# Examples:
```
Input:
hello #Line one
#Line two
world! #Line three
Output:
hello world!
Input:
E #This comment intentionally left blank
ac #
h s #
ecti #
on is #
one c #
haracte #
r longer #
than the #
last! #
Output:
Each section is one character longer than the last!
Input:
4 #This number is 7
8 #
15 #That last comment is wrong.
16 #
23 #
42 #
Output:
4815162342
Input:
Hello #Comment 1
world #Comment 2
, #Comment 3
how #Comment 4
are #Comment 5
you? #Comment 6
Output:
Hello world, how are you?
Input:
Prepare #
for... #
extra spaces! #
Output:
Prepare for... extra spaces!
```
You may take input in whatever reasonable format you like, for example, a list of strings, a single string with newlines, a 2d list of characters, etc. The shortest answer in bytes wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
»/ṣ”#ḢṖ
```
[Try it online!](http://jelly.tryitonline.net/#code=wrsv4bmj4oCdI-G4ouG5lgrhu7TDhyAgICAgIOG4t-KAnCBTcGxpdCBhdCBuZXdsaW5lcyBhbmQgY2FsbCB0aGUgbGluayBhYm92ZS4&input=&args=SGVsbG8gICAgICAgICAgICAgICAgICAgICAjQ29tbWVudCAxCiAgICAgIHdvcmxkICAgICAgICAgICAgICAgI0NvbW1lbnQgMgogICAgICAgICAgICwgICAgICAgICAgICAgICNDb21tZW50IDMKICAgICAgICAgICAgIGhvdyAgICAgICAgICAjQ29tbWVudCA0CiAgICAgICAgICAgICAgICAgYXJlICAgICAgI0NvbW1lbnQgNQogICAgICAgICAgICAgICAgICAgICB5b3U_ICNDb21tZW50IDY)
### How it works
```
»/ṣ”#ḢṖ Main link. Argument: A (array of strings)
»/ Reduce the columns of A by maximum.
Since the space is the lowest printable ASCII characters, this returns the
non-space character (if any) of each column.
ṣ”# Split the result at occurrences of '#'.
Ḣ Head; extract the first chunk, i.e., everything before the (first) '#'.
Ṗ Pop; remove the trailing space.
```
[Answer]
# Python 2, ~~48~~ 43 bytes
```
lambda x:`map(max,*x)`[2::5].split(' #')[0]
```
*Thanks to @xnor for golfing off 5 bytes!*
Test it on [Ideone](http://ideone.com/UslRUT).
[Answer]
# JavaScript (ES6), ~~97~~ ~~75~~ 60 bytes
Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for helping golf off 22 bytes
```
a=>a.reduce((p,c)=>p.replace(/ /g,(m,o)=>c[o])).split` #`[0]
```
Input is an array of lines.
* `a` is array input
* `p` is previous item
* `c` is current item
* `m` is match string
* `o` is offset
[Answer]
# Perl, ~~35~~ ~~34~~ 32 bytes
Includes +1 for `-p`
Give input on STDIN
`eso.pl`
```
#!/usr/bin/perl -p
y/ /\0/;/.#/;$\|=$`}{$\=~y;\0;
```
Notice that there is a space after the final `;`. The code works as shown, but replace `\0` by the literal character to get the claimed score.
[Answer]
## Python 2, 187 bytes
```
def f(x,o=""):
l=[i[:i.index("#")-1]for i in x]
for n in range(len(l[0])):
c=[x[n]for x in l]
if sum([1for x in c if x!=" "])<1:o+=" "
else:o+=[x for x in c if x!=" "][0]
print o
```
I'm gonna golf this more tomorrow I have school ;)
[Answer]
# Ruby, 63 bytes
Basically a port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/93068/11261). Takes input as an array of strings.
```
->a{l,=a
l.gsub(/./){a.map{|m|m[$`.size]||$/}.max}[/(.+) #/,1]}
```
See it on eval.in: <https://eval.in/640757>
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 12 bytes
*Thanks to Sp3000 for saving 2 bytes.*
```
{:.e>_'##(<}
```
An unnamed block that takes a list of strings (one for each line) and replaces it with a single string.
[Try it online!](http://cjam.tryitonline.net/#code=WyJoZWxsbyAgICAgICAgICNMaW5lIG9uZSIKICIgICAgICAgICAgICAgICNMaW5lIHR3byIKICIgICAgICAgd29ybGQhICNMaW5lIHRocmVlIl0KCns6LmU-XycjIyg8fQoKfg&input=aGVsbG8gICAgICAgICAjTGluZSBvbmUKICAgICAgICAgICAgICAjTGluZSB0d28KICAgICAgIHdvcmxkISAjTGluZSB0aHJlZQ)
### Explanation
```
:.e> e# Reduce the list of strings by elementwise maximum. This keeps non-spaces in
e# favour of spaces. It'll also wreak havoc with the comments, but we'll discard
e# those anyway.
_'## e# Duplicate and find the index of '#'.
(< e# Decrement that index and truncate the string to this length.
```
[Answer]
# J, 30 bytes
```
(#~[:<./\'#'~:])@(>./&.(3&u:))
```
Takes a list of strings as input. Basically uses the same approach as Dennis in his Jelly answer.
## Commented and explained
```
ord =: 3 & u:
under =: &.
max =: >./
over =: @
maxes =: max under ord
neq =: ~:
arg =: ]
runningMin =: <./\
magic =: #~ [: runningMin ('#' neq arg)
f =: magic over maxes
```
Intermediate steps:
```
p
Hello #Comment 1
world #Comment 2
, #Comment 3
how #Comment 4
are #Comment 5
you? #Comment 6
maxes p
Hello world, how are you? #Comment 6
magic
#~ ([: runningMin '#' neq arg)
3 neq 4
1
'#' neq '~'
1
'#' neq '#'
0
'#' neq maxes p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
runningMin 5 4 2 5 9 0 _3 4 _10
5 4 2 2 2 0 _3 _3 _10
runningMin '#' neq maxes p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
0 1 0 1 1 0 # 'abcdef'
bde
'abcdef' #~ 0 1 0 1 1 0
bde
(maxes p) #~ runningMin '#' neq maxes p
Hello world, how are you?
(#~ [: runningMin '#' neq arg) maxes p
Hello world, how are you?
((#~ [: runningMin '#' neq arg) over maxes) p
Hello world, how are you?
(magic over maxes) p
Hello world, how are you?
```
## Test case
```
f =: (#~[:<./\'#'~:])@(>./&.(3&u:))
a
Hello #Comment 1
world #Comment 2
, #Comment 3
how #Comment 4
are #Comment 5
you? #Comment 6
$a
6 36
f a
Hello world, how are you?
```
[Answer]
# Javascript (ES6), 63 bytes
```
a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')
```
Takes input as an array of strings.
```
F=a=>a.reduce((p,c)=>p+/(.+?)\s+#/.exec(c)[1].slice(p.length),'')
input.oninput = update;
update();
function update() {
try {
output.innerHTML = F(input.value.trim().split`
`);
} catch(e) {
output.innerHTML = 'ERROR: INVALID INPUT';
}
}
```
```
textarea {
width: 100%;
box-sizing: border-box;
font-family: monospace;
}
```
```
<h2>Input:</h2>
<textarea id="input" rows="8">
a #Explanation of what 'a' does
bc #Bc
d #d
e #Explanation of e
fgh #foobar
ij #hello world
k #etc.
l #so on
mn #and
op #so forth
</textarea>
<hr />
<h2>Output:</h2>
<pre id="output">
</pre>
```
[Answer]
# [Retina](http://github.com/mbuettner/retina), 32 bytes
Byte count assumes ISO 8859-1 encoding.
```
Rmr` #.+|(?<=^(?<-1>.)+).+?¶( )+
```
[Try it online!](http://retina.tryitonline.net/#code=Um1yYCAjLit8KD88PV4oPzwtMT4uKSspLis_wrYoICkr&input=YSAgICAgICAgICAgICAgICAjRXhwbGFuYXRpb24gb2Ygd2hhdCAnYScgZG9lcwogYmMgICAgICAgICAgICAgICNCYwogICBkICAgICAgICAgICAgICNkCiAgICBlICAgICAgICAgICAgI0V4cGxhbmF0aW9uIG9mIGUKICAgICAgICAgICAgICAgICAjZm9vYmFyCiAgICAgICAgaWogICAgICAgI2hlbGxvIHdvcmxkCiAgICAgICAgICAgICAgICAgI2V0Yy4KICAgICAgICAgICBsICAgICAjc28gb24KICAgICAgICAgICAgbW4gICAjYW5kCiAgICAgICAgICAgICAgb3AgI3NvIGZvcnRo)
[Answer]
## Pyke, ~~15~~ 10 bytes
```
,FSe)s\#ch
```
[Try it here!](http://pyke.catbus.co.uk/?code=%2CFSe%29s%5C%23ch&input=%22Prepare+++++++++++++++++++++++++++++++%23+comment+1%22%2C%22++++++++for...++++++++++++++++++++++++%23+comment+2%22%2C%22++++++++++++++++++++++++extra+spaces%21+%23+comment+3%22)
Port of the Jelly answer
```
, - transpose()
FSe) - map(min, ^)
s - sum(^)
\#c - ^.split("#")
h - ^[0]
```
[Answer]
# C# 157 122 Bytes
Golfed 35 bytes thanks to @milk -- though I swear I tried that earlier.
Takes input as a 2-d array of characters.
```
string f(char[][]s){int i=0;foreach(var x in s)for(i=0;x[i]!=35;i++)if(x[i]!=32)s[0][i]=x[i];return new string(s[0],0,i);}
```
157 bytes:
```
string g(char[][]s){var o=new char[s[0].Length];foreach(var x in s)for(int i=0;x[i]!=35;i++)if(x[i]!=32|o[i]<1)o[i]=x[i];return new string(o).TrimEnd('\0');}
```
[Answer]
# Pyth, 11 bytes
```
PhceCSMCQ\#
```
A program that takes input of a list of strings on STDIN and prints a string.
[Try it online](https://pyth.herokuapp.com/?code=PhceCSMCQ%5C%23&test_suite=1&test_suite_input=%5B%27hello+++++++++%23Line+one%27%2C+%27++++++++++++++%23Line+two%27%2C+%27+++++++world%21+%23Line+three%27%5D%0A%5B%27E+++++++++++++++++++++++++++++++++++++++++++++++++++%23This+comment+intentionally+left+blank%27%2C+%27+ac+++++++++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27+++h+s++++++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++ecti++++++++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++++++on+is+++++++++++++++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++one+c+++++++++++++++++++++++++++++++%23%27%2C+%27+++++++++++++++++++++haracte++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++++++++++++++r+longer++++++++++++++++%23%27%2C+%27+++++++++++++++++++++++++++++++++++++than+the+++++++%23%27%2C+%27++++++++++++++++++++++++++++++++++++++++++++++last%21+%23%27%5D%0A%5B%274++++++++++%23This+number+is+7%27%2C+%27+8+++++++++%23%27%2C+%27++15+++++++%23That+last+comment+is+wrong.%27%2C+%27++++16+++++%23%27%2C+%27++++++23+++%23%27%2C+%27++++++++42+%23%27%5D%0A%5B%27Hello+++++++++++++++++++++%23Comment+1%27%2C+%27++++++world+++++++++++++++%23Comment+2%27%2C+%27+++++++++++%2C++++++++++++++%23Comment+3%27%2C+%27+++++++++++++how++++++++++%23Comment+4%27%2C+%27+++++++++++++++++are++++++%23Comment+5%27%2C+%27+++++++++++++++++++++you%3F+%23Comment+6%27%5D%0A%5B%27Prepare+++++++++++++++++++++++++++++++%23%27%2C+%27++++++++for...++++++++++++++++++++++++%23%27%2C+%27++++++++++++++++++++++++extra+spaces%21+%23%27%5D&debug=0)
**How it works**
```
PhceCSMCQ\# Program. Input: Q
CQ Transpose Q
SM Sort each element of that lexicographically
C Transpose that
e Yield the last element of that, giving the program ending with ' #' and some
parts of the comments
c \# Split that on the character '#'
h Yield the first element of that, giving the program with a trailing space
P All but the last element of that, removing the trailing space
Implicitly print
```
[Answer]
# sed, 126 bytes
```
:a;N;$!ba;s,#[^\n]*\n,#,g;s,^,#,;:;/#[^ ]/{/^# /s,^# *,,;t;H;s,#.,#,g}
t;/#[^ ]/!{H;s,#.,#,g};t;g;s,\n#(.)[^\n]*,\1,g;s,...$,,
```
Requires a newline at the end of the input.
I'm sure I can golf this a little more, but I'm just happy it works for now.
[Answer]
# [Perl 6](http://perl6.org/), 39 bytes
```
{[Zmax](@_».comb).join.split(' #')[0]}
```
Translation of the [Python solution by Dennis](https://codegolf.stackexchange.com/a/93072/14880).
Takes input as a list of strings, and returns a string.
([try it online](https://glot.io/snippets/eifhpqhiu3))
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
żḟ€” ;€” Ḣ€
i€”#’©ḣ@"ç/ḣ®ṪṖ
```
Test it at **[TryItOnline](http://jelly.tryitonline.net/#code=xbzhuJ_igqzigJ0gO-KCrOKAnSDhuKLigqwKaeKCrOKAnSPigJnCqeG4o0Aiw6cv4bijwq7huarhuZY&input=&args=IlByZXBhcmUgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIyBjb21tZW50IDEiLCIgICAgICAgIGZvci4uLiAgICAgICAgICAgICAgICAgICAgICAgICMgY29tbWVudCAyIiwiICAgICAgICAgICAgICAgICAgICAgICAgZXh0cmEgc3BhY2VzISAjIGNvbW1lbnQgMyI)**
Uses the strictest spec - the extra space before the comment character is removed at the cost of a byte.
Input is a list of strings.
[Answer]
## Ruby, 77 bytes
```
puts File.readlines("stack.txt").join('').gsub(/\s{1}#.*\n/,'').gsub(/\s/,'')
```
[Answer]
# TSQL, ~~216~~ 175 bytes
**Golfed:**
```
DECLARE @ varchar(max)=
'hello #Line one
#Line two
world! #Line three'
DECLARE @i INT=1,@j INT=0WHILE @i<LEN(@)SELECT @=stuff(@,@j+1,len(x),x),@j=iif(x=char(10),0,@j+1),@i+=1FROM(SELECT ltrim(substring(@,@i,1))x)x PRINT LEFT(@,patindex('%_#%',@))
```
**Ungolfed:**
```
DECLARE @ varchar(max)=
'hello #Line one
#Line two
world! #Line three'
DECLARE @i INT=1,@j INT=0
WHILE @i<LEN(@)
SELECT @=stuff(@,@j+1,len(x),x),@j=iif(x=char(10),0,@j+1),@i+=1
FROM(SELECT ltrim(substring(@,@i,1))x)x
PRINT LEFT(@,patindex('%_#%',@))
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/539127/parse-the-comments-out-of-my-esoteric-code)**
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
[Inspiration](https://codegolf.stackexchange.com/a/93068/43319).
```
(⎕UCS¯2↓⍳∘35↑⊢)⌈⌿∘⎕UCS
```
`(`
`⎕UCS` character representation of
`¯2↓` all but the last two of
`⍳∘35↑` up until the position of the first 35 ("#"), in that which is outside the parenthesis, taken from
`⊢` that which is outside the parenthesis
`)` namely...
`⌈⌿` the columnar maximums
`∘` of
`⎕UCS` the Unicode values
[TryAPL online!](http://tryapl.org/?a=f%u2190%28%u2395UCS%AF2%u2193%u2373%u221835%u2191%u22A2%29%u2308%u233F%u2218%u2395UCS%20%u22C4%20%u22A2Input%u2190%u2191%27hello%20%20%20%20%20%20%20%20%20%23Line%20one%27%20%27%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23Line%20two%27%20%27%20%20%20%20%20%20%20world%21%20%23Line%20three%27%20%u22C4%20f%20Input&run)
] |
[Question]
[
A [Flow Snake, also known as a Gosper curve](https://en.wikipedia.org/wiki/Gosper_curve), is a fractal curve, growing exponentially in size with each order/iteration of a simple process. Below are the details about the construction and a few examples for various orders:
*Order 1 Flow Snake*:
```
____
\__ \
__/
```
*Order 2 Flow Snake*:
```
____
____ \__ \
\__ \__/ / __
__/ ____ \ \ \
/ __ \__ \ \/
\ \ \__/ / __
\/ ____ \/ /
\__ \__/
__/
```
*Order 3 Flow Snake*:
```
____
____ \__ \
\__ \__/ / __
__/ ____ \ \ \ ____
/ __ \__ \ \/ / __ \__ \
____ \ \ \__/ / __ \/ / __/ / __
____ \__ \ \/ ____ \/ / __/ / __ \ \ \
\__ \__/ / __ \__ \__/ / __ \ \ \ \/
__/ ____ \ \ \__/ ____ \ \ \ \/ / __
/ __ \__ \ \/ ____ \__ \ \/ / __ \/ /
\ \ \__/ / __ \__ \__/ / __ \ \ \__/
\/ ____ \/ / __/ ____ \ \ \ \/ ____
\__ \__/ / __ \__ \ \/ / __ \__ \
__/ ____ \ \ \__/ / __ \/ / __/ / __
/ __ \__ \ \/ ____ \/ / __/ / __ \/ /
\/ / __/ / __ \__ \__/ / __ \/ / __/
__/ / __ \ \ \__/ ____ \ \ \__/ / __
/ __ \ \ \ \/ ____ \__ \ \/ ____ \/ /
\ \ \ \/ / __ \__ \__/ / __ \__ \__/
\/ / __ \/ / __/ ____ \ \ \__/
\ \ \__/ / __ \__ \ \/
\/ \ \ \__/ / __
\/ ____ \/ /
\__ \__/
__/
```
# Construction
Consider the order 1 Flow Snake to be built of a path containing 7 edges and 8 vertices (labelled below. Enlarged for feasibility):
```
4____5____6
\ \
3\____2 7\
/
0____1/
```
Now for each next order, you simply replace the edges with a rotated version of this original order 1 pattern. Use the following 3 rules for replacing the edges:
**1** For a horizontal edge, replace it with the original shape as is:
```
________
\ \
\____ \
/
____/
```
**2** For a `/` edge (`12` in the above construction), replace it with the following rotated version:
```
/
/ ____
\ / /
\/ /
/
____/
```
**3** For a `\` edge (`34`and `67` above), replace it with the following rotated version:
```
/
/ ____
\ \ \
\ \ \
\ /
\/
```
So for example, order 2 with vertices from order 1 labelled will look like
```
________
\ \
________ \____ \6
\ \ / /
\____ \5___/ / ____
/ \ \ \
4___/ ________ \ \ \7
/ \ \ \ /
/ ____ \____ \2 \/
\ \ \ / /
\ \ \3___/ / ____
\ / \ / /
\/ ________ \/ /
\ \ /
\____ \1___/
/
0___/
```
Now for any higher order, you simply break up the current level into edges of lengths 1 `/`, 1 `\` or 2 `_` and repeat the process. Do note that even after replacing, the common vertices between any two consecutive edges are still coinciding.
# Challenge
* You have to write a function of a full program that receives a single integer `N` via STDIN/ARGV/function argument or the closest equivalent and prints the order `N` Flow Snake on STDOUT.
* The input integer is always greater than `0`.
* There should not be any leading spaces which are not part of the pattern.
* There should be either no trailing spaces or enough trailing spaces to pad the pattern to fill the minimum bounding rectangle completely.
* Trailing newline is optional.
# Fun Facts
* Flow Snakes is a word play of Snow Flakes, which this pattern resembles for order 2 and above
* The Flow and Snakes actually play a part in the pattern as the pattern is made up of a single path flowing throughout.
* If you notice carefully, the order 2 (and higher as well) pattern comprises of rotations of order 1 pattern pivoted on the common vertex of the current and the previous edge.
* There is a Non ASCII variant of Flow Snakes which can be found [here](http://80386.nl/projects/flowsnake/) and at several other locations.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes win!
---
# Leaderboard
**[The first post of the series generates a leaderboard.](https://codegolf.stackexchange.com/q/50484/31414)**
To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
[Answer]
# Python 2, ~~428~~ ~~411~~ 388 bytes
This one was pretty tricky. The patterns don't retain their ratios after each step meaning its very difficult to procedurally produce an image from its predecessor. What this code does, though its pretty unreadable after some intense math golfing, is actually draw the line from start to finish using the recursively defined `D` function.
The size was also an issue, and I ended up just starting in the middle of a `5*3**n` sided square and cropping things afterward, though if I can think of better way to calculate the size I might change it.
```
n=input();s=5*3**n
r=[s*[" "]for i in[0]*s]
def D(n,x,y,t=0):
if n<1:
x-=t%2<1;y+=t%3>1;r[y][x]='_/\\'[t/2]
if t<2:r[y][x+2*t-1]='_'
return[-1,2,0,1,0,1][t]+x,y-(2<t<5)
for c in[int(i)^t%2for i in"424050035512124224003"[t/2::3]][::(t^1)-t]:x,y=D(n-1,x,y,c)
return x,y
D(n,s/2,s/2)
S=[''.join(c).rstrip()for c in r]
for l in[c[min(c.find('\\')%s for c in S):]for c in S if c]:print l
```
[Answer]
# JavaScript (*ES6*), 356 ~~362 370~~
That's a difficult one ...
Each shape is stored as a path. There are 6 basic building blocks (3 + 3 backward)
* `0` diagonal up left to bottom right (`4` backward)
* `1` diagonal bottom left to up right (`5` backward)
* `2` horizontal left to right (`6` backward)
For each one, there is a replacing step to be applied when increasing order:
* `0` --> `0645001` (backward `4` --> `5441024`)
* `1` --> `2116501` (backward `5` --> `5412556`)
* `2` --> `2160224` (backward `6` --> `0664256`)
values prefilled in the`h` array, even if the elements 4..6 can be obtained from 0..2 using
```
;[...h[n]].reverse().map(x=>x^4).join('')
```
To obtain the shape for the given order, the path is built in the p variable applying the substitutions repeatedly. Then the main loop iterates on the p variable and draw the shape inside the g[] array, where each element is a row.
Starting at position (0,0), each index can become negative (y index at high orders). I avoid negative y indexes shifting all the g array whenever I find a negative y value. I don't care if the x index becomes negative, as in JS negative indexes are allowed, just a little more difficult to manage.
In the last step, I scan the main array using .map, but for each row I need to use an explicit for(;;) loop using the `b` variable that holds the least x index reached (that will be < 0).
In the `console.log` version there is a handy leading newline, that can be easily made a trailing newline swapping 2 rows, as in the snippet version.
```
f=o=>{
g=[],x=y=b=0,
h='064500192116501921602249954410249541255690664256'.split(9);
for(p=h[2];--o;)p=p.replace(/./g,c=>h[c]);
for(t of p)
z='\\/_'[s=t&3],
d=s-(s<1),
t>3&&(x-=d,y+=s<2),
y<0&&(y++,g=[,...g]),r=g[y]=g[y]||[],
s?s>1?r[x]=r[x+1]=z:r[x]=z:r[x-1]=z,
t<3&&(x+=d,y-=s<2),
x<b?b=x:0;
g.map(r=>
{
o+='\n';
for(x=b;x<r.length;)o+=r[x++]||' '
},o='');
console.log(o)
}
```
Handy snippet to test (in Firefox) :
```
f=o=>{
g=[],x=y=b=0,
h='064500192116501921602249954410249541255690664256'.split(9);
for(p=h[2];--o;)p=p.replace(/./g,c=>h[c]);
for(t of p)
z='\\/_'[s=t&3],
d=s-(s<1),
t>3&&(x-=d,y+=s<2),
y<0&&(y++,g=[,...g]),r=g[y]=g[y]||[],
s?s>1?r[x]=r[x+1]=z:r[x]=z:r[x-1]=z,
t<3&&(x+=d,y-=s<2),
x<b?b=x:0;
g.map(r=>
{
for(x=b;x<r.length;)o+=r[x++]||' ';
o+='\n'
},o='');
return o
}
// TEST
fs=9;
O.style.fontSize=fs+'px'
function zoom(d) {
d += fs;
if (d > 1 && d < 40)
fs=d, O.style.fontSize=d+'px'
}
```
```
#O {
font-size: 9px;
line-height: 1em;
}
```
```
<input id=I value=3><button onclick='O.innerHTML=f(I.value)'>-></button>
<button onclick="zoom(2)">Zoom +</button><button onclick="zoom(-2)">Zoom -</button>
<br>
<pre id=O></pre>
```
[Answer]
# Haskell, 265 bytes
```
(?)=div
(%)=mod
t[a,b]=[3*a+b,2*b-a]
_#[0,0]=0
0#_=3
n#p=[352,6497,2466,-1]!!((n-1)#t[(s+3)?7|s<-p])?(4^p!!0%7)%4
0&_=0
n&p=(n-1)&t p+maximum(abs<$>sum p:p)
n!b=n&[1,-b]
f n=putStr$unlines[["__ \\/ "!!(2*n#t[a?2,-b]+a%2)|a<-[b-n!2+1..b+n!2+0^n?3]]|b<-[-n!0..n!0]]
```
(Note: on GHC before 7.10, you will need to add `import Control.Applicative` or replace `abs<$>` with `map abs$`.)
[Run online at Ideone.com](http://ideone.com/mx5CR1)
`f n :: Int -> IO ()` draws the level `n` flowsnake. The drawing is computed in bitmap order rather than along the curve, which allows the algorithm to run in O(n) space (that is, logarithmic in the drawing size). Nearly half of my bytes are spent computing which rectangle to draw!
[Answer]
# Perl, ~~334 316~~ 309
```
$_=2;eval's/./(map{($_,"\1"x7^reverse)}2003140,2034225,4351440)[$&]/ge;'x($s=<>);
s/2|3/$&$&/g;$x=$y=3**$s-1;s!.!'$r{'.qw($y--,$x++ ++$y,--$x $y,$x++ $y,--$x
$y--,--$x ++$y,$x++)[$&]."}=$&+1"!eeg;y!1-6!//__\\!,s/^$x//,s/ *$/
/,print for
grep{/^ */;$x&=$&;$'}map{/^/;$x=join'',map$r{$',$_}||$",@f}@f=0..3**$s*2
```
Parameter taken on the standard input.
Test [me](http://ideone.com/iB5taR).
[Answer]
# Haskell, ~~469~~ ~~419~~ ~~390~~ ~~385~~ 365 bytes
the function f::Int->IO() takes an integer as input and print the flow snake
```
e 0=[0,0];e 5=[5,5];e x=[x]
f n=putStr.t$e=<<g n[0]
k=map$(53-).fromEnum
g 0=id
g n=g(n-1).(=<<)(k.(words"5402553 5440124 1334253 2031224 1345110 2003510"!!))
x=s$k"444666555666"
y=s$k"564645554545"
r l=[minimum l..maximum l]
s _[]=[];s w(x:y)=w!!(x+6):map(+w!!x)(s w y)
t w=unlines[["_/\\\\/_ "!!(last$6:[z|(c,d,z)<-zip3(x w)(y w)w,c==i&&d==j])|i<-r.x$w]|j<-r.y$w]
```
[Answer]
# CJam, 144 bytes
```
0_]0a{{_[0X3Y0_5]f+W@#%~}%}ri*{_[YXW0WW]3/If=WI6%2>#f*.+}fI]2ew{$_0=\1f=~-
"__1a /L \2,"S/=(@\+\~.+}%_2f<_:.e>\:.e<:M.-:)~S*a*\{M.-~3$3$=\tt}/zN*
```
Newline added to avoid scrolling. [Try it online](http://cjam.aditsu.net/#code=0_%5D0a%7B%7B_%5B0X3Y0_5%5Df%2BW%40%23%25~%7D%25%7Dri*%7B_%5BYXW0WW%5D3%2FIf%3DWI6%252%3E%23f*.%2B%7DfI%5D2ew%7B%24_0%3D%5C1f%3D~-%22__1a%20%2FL%20%5C2%2C%22S%2F%3D(%40%5C%2B%5C~.%2B%7D%25_2f%3C_%3A.e%3E%5C%3A.e%3C%3AM.-%3A)~S*a*%5C%7BM.-~3%243%24%3D%5Ctt%7D%2FzN*&input=3)
The program works in several steps:
1. The initial fractal (order 1) is encoded as a sequence of 7 angles (conceptually, multiples of 60°) representing the direction of movement
2. The fractal is "applied" to a horizontal segment (order 0 fractal) N times to generate all the "movements" in the order N fractal
3. Starting from [0 0], the movements are translated into a sequence of points with [x y] coordinates
4. Each segment (pair of points) is converted to 1 or 2 [x y c] triplets, representing the character c at coordinates x, y
5. The bounding rectangle is determined, the coordinates are adjusted and a matrix of spaces is generated
6. For each triplet, the character c is placed at position x, y in the matrix, and the final matrix is adjusted for output
[Answer]
# C, ~~479~~ ~~474~~ ~~468~~ 427 bytes
There's no beating the Perl and Haskell guys I guess, but since there's no C submission here yet:
```
#define C char
C *q="053400121154012150223433102343124450553245";X,Y,K,L,M,N,i,c,x,y,o;F(C*p,
int l,C d){if(d){l*=7;C s[l];for(i=0;i<l;i++)s[i]=q[(p[i/7]%8)*7+i%7];return F
(s,l,d-1);}x=0;y=0;o=32;while(l--){c=*p++%8;for(i=!(c%3)+1;i--;) {K=x<K?x:K;L=
y<L?y:L;M=x>M?x:M;N=y>N?y:N;y+=c&&c<3;x-=c%5>1;if(x==X&y==Y)o="_\\/"[c%3];y-=c
>3;x+=c%5<2;}}return X<M?o:10;}main(l){F(q,7,l);for(Y=L;Y<N;Y++)for(X=K;X<=M;X
++)putchar(F(q,7,l));}
```
To save space on a atoi() call, the *number* of arguments passed to the program is used for the level.
The program runs in O(n^3) or worse; first the path is calculated once to find the min/max coordinates, then for each (x,y) pair it is calculated once to find the character on that specific location. Terribly slow, but saves on memory administration.
Example run at <http://codepad.org/ZGc648Xi>
[Answer]
# Python 2, ~~523~~ ~~502~~ ~~475~~ ~~473~~ ~~467~~ ~~450~~ 437 bytes
```
l=[0]
for _ in l*input():l=sum([map(int,'004545112323312312531204045045050445212331'[t::6])for t in l],[])
p=[]
x=y=q=w=Q=W=0
for t in l:T=t|4==5;c=t in{2,4};C=t<3;q=min(q,x);Q=max(Q,x+C);w=min(w,y);W=max(W,y);a=C*2-1;a*=2-(t%3!=0);b=(1-T&c,-1)[T&1-c];x+=(a,0)[C];y+=(0,b)[c];p+=[(x,y)];x+=(0,a)[C];y+=(b,0)[c]
s=[[' ']*(Q-q)for _ in[0]*(W-w+1)]
for t,(x,y)in zip(l,p):x-=q;s[y-w][x:x+1+(t%3<1)]='_/\_'[t%3::3]
for S in s:print''.join(S)
```
Pffft, costed me a like 3 hours, but was fun to do!
The idea is to split the task in multiple steps:
1. Calculate all the edges (encoded as 0-5) in order of appearence (so from the beginning of the snake to the end)
2. Calculate the position for each of the edges (and save the min and max values for x and y)
3. Build the strings it consists of (and use the min values to offset, so that we don't get negative indices)
4. Print the strings
Here is the code in ungolfed form:
```
# The input
n = int(input())
# The idea:
# Use a series of types (_, /, \, %), and positions (x, y)
# Forwards: 0: __ 1: / 2: \
# Backwards: 3: __ 4: / 5: \
# The parts
pieces = [
"0135002",
"0113451",
"4221502",
"5332043",
"4210443",
"5324551"
]
# The final types list
types = [0]
for _ in range(n):
old = types
types = []
for t in old:
types.extend(map(int,pieces[t]))
# Calculate the list of positions (and store the mins and max')
pos = []
top = False
x = 0
y = 0
minX = 0
minY = 0
maxX = 0
maxY = 0
for t in types:
# Calculate dx
dx = 1 if t < 3 else -1
if t%3==0:
dx *= 2 # If it's an underscore, double the horizontal size
# Calculate dy
top = t in {1, 5}
dy = 0
if top and t in {0, 3, 1, 5}:
dy = -1
if not top and t in {2, 4}:
dy = 1
# If backwards, add dx before adding the position to the list
if t>2:
x += dx
# If top to bottom, add dy before adding the position to the list
if t in {2,4}:
y += dy
# Add the current position to the list
pos += [(x, y)]
# In the normal cases (going forward and up) modify the x and y after changing the position
if t<3:
x += dx
if t not in {2, 4}:
y += dy
# Store the max and min vars
minX = min(minX, x)
maxX = max(maxX, x + (t<3)) # For forward chars, add one to the length (we never end with __'s)
minY = min(minY, y)
maxY = max(maxY, y)
# Create the string (a grid of charachters)
s = [[' '] * (maxX - minX) for _ in range(maxY - minY + 1)]
for k, (x, y) in enumerate(pos):
x -= minX
y -= minY
t = types[k]
char = '/'
if t % 3 == 0:
char = '__'
if t % 3 == 2:
char = '\\'
s[y][x : x + len(char)] = char
# Print the string
for printString in s:
print("".join(printString))
```
**Edit:** I changed the language to python 2, to be compatible with [my answer for #3](https://codegolf.stackexchange.com/a/50652/40620) (and it also saves 6 more bytes)
[Answer]
# Pari/GP, 395
Looping over x,y character positions and calculating what char to print. Moderate attempts at minimizing, scored with whitespace and comments stripped.
```
k=3;
{
S = quadgen(-12); \\ sqrt(-3)
w = (1 + S)/2; \\ sixth root of unity
b = 2 + w; \\ base
\\ base b low digit position under 2*Re+4*Im mod 7 index
P = [0, w^2, 1, w, w^4, w^3, w^5];
\\ rotation state table
T = 7*[0,0,1,0,0,1,2, 1,2,1,0,1,1,2, 2,2,2,0,0,1,2];
C = ["_","_", " ","\\", "/"," "];
\\ extents
X = 2*sum(i=0,k-1, vecmax(real(b^i*P)));
Y = 2*sum(i=0,k-1, vecmax(imag(b^i*P)));
for(y = -Y, Y,
for(x = -X+!!k, X+(k<3), \\ adjusted when endpoint is X limit
z = (x- (o = (x+y)%2) - y*S)/2;
v = vector(k,i,
z = (z - P[ d = (2*real(z) + 4*imag(z)) % 7 + 1 ])/b;
d);
print1( C[if(z,3,
r = 0;
forstep(i=#v,1, -1, r = T[r+v[i]];);
r%5 + o + 1)]) ); \\ r=0,7,14 mod 5 is 0,2,4
print())
}
```
Each char is the first or second of a hexagon cell. A cell location is a complex number z split into base b=2+w with digits 0, 1, w^2, ..., w^5, where w=e^(2pi/6) sixth root of unity. Those digits are kept just as a distinguishing 1 to 7 then taken high to low through a state table for net rotation. This is in the style of [flowsnake code by Ed Shouten](http://80386.nl/projects/flowsnake/) (`xytoi`) but only for net rotation, not making digits into an "N" index along the path. The extents are relative to an origin 0 at the centre of the shape. As long as the limit is not an endpoint these are the middle of a 2-character hexagon and only 1 of those chars is needed. But when the snake start and/or end are the X limit 2 chars are needed, which is k=0 start and k<3 end. Pari has "quads" like sqrt(-3) builtin but the same can be done with real and imaginary parts separately.
] |
[Question]
[
Write a program which calculates if an inputted monetary value, as an integer, can be represented by a unique combination of coins and/or notes, that meaning the same coin/note cannot be used more than once.
Your program should take a value as input, and can take a list of coin/note values either via input or via your language's equivalent of an array. The list of coins/notes should be able to change, so make sure it's clear where this is defined if you're using a constant.
Your program should output any truthy/falsy value respectively.
Please note that outputting the list of coins/notes that make up the value is **not** required.
# **EXAMPLE**
Using the UK pound, (£1.00 = 100 and £420.69 = 42069)
```
coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000]
```
The following will output true:
```
6 (1, 5)
15 (10, 5)
88 (1, 2, 5, 10, 20, 50)
512 (500, 10, 2)
7003 (5000, 2000, 2, 1)
```
The following will output false:
```
4
209
8889
4242424242
[ANYTHING ABOVE 8888]
```
# **ALTERNATIVE TEST DATA (US Dollar)**
```
coins = [1, 5, 10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000]
```
Good luck!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2 (TIO Nexus), 2 bytes
```
⊇+
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oq137//9oQx0FIx0FUx0FQwMgC4hNDUBsMAfMg3AhfIiAQex/U0MTAA "Brachylog – TIO Nexus")
Takes the list of coins either via standard input or via prepending it to the start of the program as an array literal (either will work, so it's up to you as to which you feel is "more legitimate"; the former is allowed by default PPCG rules, the latter specifically allowed by the question); and takes the value to produce as a command-line argument.
## Explanation
This program makes use of implementation details of the way TIO Nexus's wrapper for Brachylog functions; specifically, it lets you give a command-line argument to give input via the Output. (This wasn't envisaged in the original design for Brachylog; however, languages are defined by their implementation on PPCG, and if an implementation comes along that happens to do what I need, I can therefore take advantage of it.) That means the program looks like this:
```
⊇+
⊇ Some subset of {standard input}
+ sums to {the first command-line argument}
```
As a full program, it returns a boolean value; `true.` if all the assertions in the program can be simultaneously satisfied, or `false.` if they can't be.
(A reminder, or for people who don't already know: Brachylog 2 uses its own character encoding in which `⊇` is a single byte long.)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
æOså
```
Explanation:
```
æ Calculate the powerset of the first input
O Sum each element
s Put the second input at the top of the stack
å Check whether the input is in the powerset sum.
```
[Try it online!](https://tio.run/nexus/05ab1e#@394mX/x4aX//0cb6igY6SiY6igYGgBZQGxqAGKDOWAehAvhQwQMYrnMDQyMAQ "05AB1E – TIO Nexus")
[Answer]
# Mathematica, 25 bytes
```
!FreeQ[Tr/@Subsets@#,#2]&
```
Pure function taking an array of coin-values as the first argument and the target integer as the second argument, and returning `True` or `False`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ŒPS€e@
```
[Try it online!](https://tio.run/##y0rNyan8///opIDgR01rUh3@//8fbaijYKSjYKqjYGgAZAGxqQGIDeaAeRAuhA8RMIj9b2EBAA "Jelly – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
The operator function `(#)` takes an integer and a list of integers (or, more generally, any `Traversable` container of numbers) and returns a `Bool`.
Use as `6#[1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000]`.
```
c#l=elem c$sum<$>mapM(:[0])l
```
[Try it online!](https://tio.run/nexus/haskell#NYxNCoMwEEb3c4qgLpKqIbHaqqh7oaUHEBeioRWSWPyhx7dR2xkGvveYGdX0Ou8GJDN/FE1302laPqpSz@IpxhrQr3ojxqadnUXLXouJquaN8fQaPlN2KrCF/AJZrkvopii2JSF0@0fovr62tsyFFAq1zrSozCnM/R2nFauJXNeKeyjwUOQhzkwyE7Et77DTgQcfgtVwAR5BHEPEA7gydoYQApYYEycQBv8@@As "Haskell – TIO Nexus")
# How it works
* `c` is the desired value and `l` the list of coin values.
* `mapM(:[0])l` maps `(:[0])` over `l`, pairing each value with 0, and then constructs the cartesian product, giving lists where each element is either its corresponding value in `l`, or 0.
* `sum<$>` sums each combination, and `elem c$` checks if `c` is in the resulting list.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~52~~ 31 bytes
```
\d+
$*
^((1+) |1+ )+(?<-2>\2)+$
```
[Try it online!](https://tio.run/nexus/retina#lc8xCoAwDIXhvafIUKE1CEm02oLo6CWKOHgM715tT2C2/8G3vM4dV8k3Gtub0zlGDw8jeHT7OsiWxaMthUEgABMIQaAvatVs3UZbBLP5bzkocIwKHFgUeiEaFXxSWKGk@hjTCw "Retina – TIO Nexus") Takes input as a space-separated list of coins and notes followed by the desired value. Edit: Saved 18 bytes thanks to @Kobi who debugged my code. Explanation: The first two lines simply convert from decimal to unary. The third line then captures the list of coins and notes. The alternation allows the engine to backtrack and choose not to capture specific coins/notes. The balancing group then matches the value against all suffixes of the the capture list (unnecessary but golfier.)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
tT&h⊇+T
```
[Try it online!](https://tio.run/nexus/brachylog2#@18SopbxqKtdO@T//@hoQx0jHVMdQwMdIwMdUwMgA8QCMcFsMAfMM4jVMTcwMI4FAA)
## How it works
```
tT&h⊇+T
tT the second input is T
& and
h the first input
⊇ is a superset of a set
+ that sums up to
T T
```
## Including the combination, 9 bytes
```
tT&h⊇.+T∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@18SopbxqKtdTzvkUcfy//@jow11jHRMdQwNdIwMdEwNgAwQC8QEs8EcMM8gVsfcwMA49n8UAA)
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 125 bytes
```
boolean f(int[]c,int n){int l=c.length;if(l<1)return n==0;int[]a=java.util.Arrays.copyOf(c,l-1);return f(a,n-c[l-1])|f(a,n);}
```
[Try it online!](https://tio.run/nexus/java-openjdk#lZBNbsMgEIXX8SlmCRJB4MatK9eLHqDqIssoC0Jtl4qAZXAqy/XZU7B7gCKE3rzRNz/QjxetJEgtnIM3ocx8v1irG2GgRcr401mSIGDwHEXXkurGdP6zUi3SLxwPjR8HA6auWbXyov4SN0FHrzR9HQYxOSptP723SBK957j6q2iRIGYvTyF3xj@rw9Vy77eFnBc@yM2qD7iGtdDRD8p0of3QOTxnu3UWSKuMgxpM8w1rZuYEcgIFAc5CFG7BYrya1W1281uCLVW2O07ON1dqR0/7MMlrg2LT@CUI07B8nEQeMf43y4sEuCwT4ILnCfQTYw8J@CGBzdlz0hvLFPyQbyeWLNly/wU "Java (OpenJDK 8) – TIO Nexus")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 46 bytes
```
a([],0).
a([H|T],X):-Y is X-H,(a(T,Y);a(T,X)).
```
[Try it online!](https://tio.run/nexus/prolog-swi#@5@oER2rY6CpxwVkeNSExOpEaFrpRipkFitE6HroaCRqhOhEalqDqAhNTb3//4HKDHUUjHQUTHUUDA2ALCA2NQCxwRwwD8KF8CECBrE6CuYGBsaaegA "Prolog (SWI) – TIO Nexus")
Fork of [my Python answer](https://codegolf.stackexchange.com/a/119627/48934).
[Answer]
## JavaScript (ES6), ~~81~~ ~~69~~ ~~67~~ 64 bytes
Takes the list of coins `c` and the target amount `a` in currying syntax `(c)(a)`. Returns `0` or `true`.
```
c=>g=(a,m=1)=>c.map((c,i)=>x-=c*(m>>i&1),x=a)&&!x||x-a&&g(a,m+1)
```
### Test cases
```
let f =
c=>g=(a,m=1)=>c.map((c,i)=>x-=c*(m>>i&1),x=a)&&!x||x-a&&g(a,m+1)
const pound = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000];
console.log(f(pound)(6))
console.log(f(pound)(15))
console.log(f(pound)(88))
console.log(f(pound)(512))
console.log(f(pound)(7003))
console.log(f(pound)(4))
console.log(f(pound)(209))
console.log(f(pound)(8889))
console.log(f(pound)(4242424242))
```
[Answer]
# R, ~~88~~ 83 bytes
*-5 bytes thanks to @Jarko Dubbeldam*
returns an anonymous function. It generates all the possible combinations of coins (using `expand.grid` on pairs of `T,F`) and checks if the value(s) are present. `k` is coins since `c` is a reserved word in R. Can check multiple values at once.
```
function(k,v)v%in%apply(expand.grid(Map(function(x)!0:1,k)),1,function(x)sum(k[x]))
```
[Try it online!](https://tio.run/nexus/r#TY1dCsIwEITfe4r4UMjCKElsNYoewROID6E/ElrTYG2pp6@1UZFll/mGnd3yOJadyx62cbxCT31sXWy8r5@8GLxx@ep6tzk/Gc9/ewMtxF6iIoLEn9t2N16dhwvRmDXWteywZBmXYAosBZNiUlOn4q1nmClg4GAIinpTd8XnwgYyhdZIpcJWiDUSKLED01pPM1Hfoqjk82OwEKfxBQ)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ŒP§i
```
[Try it online!](https://tio.run/##y0rNyan8///opIBDyzP///9vqKNgpKNgqqNgaABkAbGpAYgN5oB5EC6EDxEw@G9uYGAMAA "Jelly – Try It Online")
Powerset, vector sum, index.
Powerset gets all subsets, sum all the subsets, and check for the occurrence of the second argument
Returns 0 as the falsy value, and anything else otherwise.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 bytes
```
à mx èN
```
[Try it online!](https://tio.run/nexus/japt#@394gUJuhcLhFX7//0cb6igY6SiY6igYGgBZQGxqAGKDOWAehAvhQwQMYrksgAAA "Japt – TIO Nexus") Outputs `0` for falsy, a positive integer for truthy.
### Explanation
```
à mx èN
// Implicit: U = input array, V = input integer, N = array of all inputs
à // Take all combinations of U.
mx // Map each combination to its sum.
è // Count the number of items in the result which also exist in
N // the array of inputs.
// This returns 0 if no combination sums to V, a positive integer otherwise.
// Implicit: output result of last expression
```
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
5 bytes thanks to ovs.
```
f=lambda c,n:c and f(c[1:],n-c[0])|f(c[1:],n)or n==0
```
[Try it online!](https://tio.run/nexus/python3#PY5BCoMwEEX3OcWnKwNjSWxTUyG9SMgijQiBGot1Zz27jQpdzPDfMDz@2pmX75@tR6DUBPjUoiuClY2jVAYrHP/@mQ8jkjFiDUNMHxhYSagIiiBFTnmU2PIOOx148HEQjnXZExET7I2kIq1JyayphbgQrtvvnaC1zlvKWsvKNQzvMaapOM0Lygfm5XTOlt5PRaTcb@tDkXPO2PoD "Python 3 – TIO Nexus")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
Returns `nil` as the falsy value, and the smallest coin value in the list that makes up the number as truthy (all numbers are truthy in Ruby).
```
f=->c,n{n!=0?c.find{|i|f[c-[i],n-i]}:1}
```
Do beware, however, that this algorithm is insanely slow, with `O(C!)` time complexity, where `C` is the length of the coin list. It eventually finishes, but most test cases will time out on most online interpreters, even `f(UK_POUND, 5)`.
Here is a 41-byte version that finishes much faster by adding an extra ending condition, and is much harder to actually time out
```
f=->c,n{n>0?c.find{|i|f[c-[i],n-i]}:n==0}
```
[Try it online!](https://tio.run/nexus/ruby#@59mq2uXrJNXnWdnYJ@sl5aZl1Jdk1mTFp2sG50Zq5Onmxlba5Vna2tQ@79AIU0vOTEnRyG1LDFHIz21pFhTB4n9P9pQR8FIR8FUR8HQAMgCYlMDEBvMAfMgXAgfImAQy2VuYGAMAA "Ruby – TIO Nexus")
[Answer]
# Bash + GNU utilities, 56 39
```
printf %$2s|egrep "^ {${1//,/\}? {}}?$"
```
Input denomination list (unsorted) is given as a comma-separated list. Input list and value are given as a command-line parameters.
Output given in the form of the shell return code. Inspect with `echo $?` after running the script. `0` means truthy, `1` means falsy.
[Try it online](https://tio.run/nexus/bash#ndTRCoIwFAbg@57isNZNTDxbrtZF@SIRRK0SSkOlG/PZTSfFDCo2vTnH@en0HztmOZS6KPe7QkOSwmYE7UE4E0wyjkwgk9gWXdWVpjaN6RDm5G2wR/8NlxbCj1d9Q0rZCH9M0EKSC@L@TQvEmQeLPIzApYdSSvmwSLxOC/dU/qamHYTt5OzAnaAduhMcBu8iP8J3oZGnGy4Ct/@jfKm1GEaHzDzhvrusaPXaDsZTqM3lg06zqzUwgWk/UOgSggCouQFoy5tbnqTlESZUFA99yvUNyBYqWvEwZOGmjqGq65iSpuN6f86A0Pf2E6yBxt1kUt08AQ).
* `printf %$2s` outputs a string of `value` spaces
* `"^ {${1//,/\}? {}}?$"` is a shell expansion that expands the denomination list to a regex like `^ {1}? {2}? {5}? {10}? ... $`. It turns out that the `egrep` regex engine is smart enough to correctly match with this, regardless of what order the denominations are in
* `egrep` checks if the string of spaces matches the regex
[Answer]
## C, 66 bytes
```
m;v;f(n){for(m=1e5;m/=10;)for(v=5;n-=n<v*m?0:v*m,v/=2;);return!n;}
```
See it [work here](https://tio.run/nexus/c-gcc#VU/RasMwDHzPV2iFQby2xE6bNp1r9iFdGSFxmB8sjzQ1YyGfvedMdtqxyfgkztydNVnpZZsiG1rXpVYJXUibKcElC4RXhcS1wqN/si/8mXDlM5VLJjvdXzt8QDlOBnuwlcEUvDMNsGRIgCrQTdVXpzMoGGAHKxAFQVkSFCIn3HO@obalm/NDfCtD2@bzofHAuYARZLSsHV76X@O32l1pVHAxX9q1aSSBQfaPOPEzcbM@Qtgrehhs9CfJOcjbfPzreyOXS9oo6OatQn10JCf7xWPzigv65D0qCkLcPXBMxukb3bqu6nf9Aw).
## C, 53 bytes
```
g(c,w,n)int*c;{for(;n-=n<c[--w]?0:c[w],w;);return!n;}
```
This variant takes the coin array, which defeats the purpose of this problem, because it comes down to simple subtraction.
The first argument is the coin array, the second is the coin count, and the third is the value.
## C, 48 bytes
```
g(c,n)int*c;{for(;n-=n<*c?0:*c,*++c;);return!n;}
```
An alternative to the previous variant. It assumes that the coin array can be reversed and zero terminated.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
/sMtyE
```
[Test suite.](http://pyth.herokuapp.com/?code=%2FsMtyE&test_suite=1&test_suite_input=6%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A15%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A88%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A512%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A7003%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A4%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A209%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A8889%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D%0A4242424242%0A%5B1%2C+2%2C+5%2C+10%2C+20%2C+50%2C+100%2C+200%2C+500%2C+1000%2C+2000%2C+5000%5D&debug=0&input_size=2)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~18~~ 17 bytes
```
q~_,2\m*\f.*::+#)
```
[Try it online!](https://tio.run/nexus/cjam#@19YF69jFJOrFZOmp2Vlpa2s@f@/oalCtKGCkYKpgqGBgpGBgqkBkAFigZhgNpgD5hnEAgA "CJam – TIO Nexus")
**Explanation**
```
q~ e# Read and eval input.
_, e# Duplicate the money list and take its length.
2\m* e# Take the (length)th Cartesian power of [0 1].
\f.* e# Element-wise multiplication of each set of 0's and 1's with the money
e# list. This is essentially the powerset, but with 0s instead of
e# missing elements.
::+ e# Sum each set.
# e# Find the index of the desired amount in the list. (-1 if not found)
) e# Increment. -1 => 0 (falsy), anything else => nonzero (truthy)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 91 bytes
```
i,j,c[]={1,2,5};f(n){for(i=1000;i;i/=10)for(j=2;j>=0;j--)n-=n<i*c[j]?0:i*c[j];return n==0;}
```
[Try it online!](https://tio.run/nexus/c-gcc#fc3BDoIwDAbgO09BSEw2s8WxgEHn9EGQA5lMt0AxE0@Ex/bqhBhvYHv5069NvSGWqLyQfUw4SQehEeBetw4ZGTPGhBFmMyY8jazkwh4lE5ZSDFTCwaxVbosT23@DcFX3dBCCHJcG35QGEA76IBzr7gx0GkWryxkiEmq0xVjMS5wuUpYtUhrzyeYxWTzjbPfnW7aMCf/1tDIE/q10XV4fntbNC1qqSnWrPg "C (gcc) – TIO Nexus")
[Answer]
# PHP, 70 Bytes
prints 1 for true and nothing for false
```
<?foreach($_GET[1]as$v)$i-=$v*$r[]=($i=&$_GET[0])/$v^0;echo max($r)<2;
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjTY1NNKJNjUwMNAxAhGGIMIUwgNxgGwgE8jSMdUx0jGMjbX@n5ZflJqYnKEBNiDaMDaxWKVMUyVT11alTEulKDrWVkMl01YNImsQq6mvUhZnYJ2anJGvkJtYoaFSpGljZP3/PwA "PHP – TIO Nexus")
[Answer]
# Octave, 39 bytes
```
@(L,n)any(cellfun(@sum,powerset(L))==n)
```
An anonymous function that takes an array of coin-values as the first argument and the target integer as the second argument, and returns true or false.
[Try it online!](https://tio.run/nexus/octave#dY4xC4MwEIX3/IqHUwIZom00IoJTJ8duxUE0gmCjeErpr7dR6ejBwfsO7uNtBS@lE7X78sYOQ7c6XtD6ltP4sTPZhZdC5LkTW5ejdpSxZuwdIccrlIgktESofPKr1Z4POOjEk8@DqjLG2p4mHjzn1WKxtKCpyVIgGOvGGW43xwg1YAygwwiJUreKwc/x2fGjge8smHXt3/eoB7oU3n2F1AtNijjWsTHJtXD7AQ "Octave – TIO Nexus")
[Answer]
# Mathematica, 42 bytes
```
ListQ@NumberDecompose[#,Sort[#2,Greater]]&
```
**input**
>
> [15,{10,5}]
>
>
>
] |
[Question]
[
Let's use the four basic operations, addition `+`, multiplication `*`, subtraction `-` and division `/` (float, not integer).
***Stewie's sequence*** is defined as follows:
```
x = [x(1), x(2)] // Two initial numbers (one indexed)
x(3) = x(1) + x(2)
x(4) = x(2) * x(3)
x(5) = x(3) - x(4)
x(6) = x(4) / x(5)
x(7) = x(5) + x(6)
... and so on.
```
**Challenge:**
Take two non-negative integers (`x(1), x(2)`), and one positive integer `N` as input.
`x(1)` and `x(2)` will be the two first numbers of your sequence, and `N` will be the length of the sequence you must output. (You can choose to have the list 0-based, in which case `N` will be one less than the length).
* You can not assume that `x(2) >= x(1)`.
* `N` will always be `>2` if 1-based, (`>1` if 0-based).
* You do not have to handle division by zero errors.
+ Note the 2nd test case. You will not get `0, 1`, and `N=6` as input, since that will result in division by zero, but you must support `0, 1` and `N=5`.
* Assume only valid input will be given.
* The input and output can be on any convenient format, but you must support at least 3 digits after the decimal points if the output is non-integer.
**Test cases:**
```
1 3
8
1, 3, 4, 12, -8, -1.5, -9.5, 14.25
0 1
5
0, 1, 1, 1, 0 // N=6 would give division by zero error. You don't need to handle that case.
1 0
9
1, 0, 1, 0, 1, 0, 1, 0, 1
6 3
25
6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96, -0.375, -79.335, 29.7506, -109.086, -0.272727, -109.358, 29.825, -139.183, -0.214286, -139.398, 29.8709, -169.269
```
[Answer]
## Haskell, ~~69~~ ~~68~~ 64 bytes
```
x#n=take n$x++zipWith3 id(cycle[(+),(*),(-),(/)])(x#n)(tail$x#n)
```
`x1` and `x2` are taken as a list. Usage example: `[1,3] # 8` -> `[1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]`.
Laziness makes it possible to define an infinite recursive list where we take the first n elements.
### Haskell, 66 bytes
```
(h%g)y x=x:g(h x y)y
a=(+)%b
b=(*)%c
c=(-)%d
d=(/)%a
(.a).(.).take
```
Different approach, slightly longer. Argument order is `N`, `x2`, `x1`. Usage example: `( (.a).(.).take ) 8 3 1` -> `[1.0,3.0,4.0,12.0,-8.0,-1.5,-9.5,14.25]`.
Defines 4 functions `a`, `b`, `c` and `d` which take two arguments `y`, `x` and make a list by putting `x` in front of a call to the next function with `y` as the second argument and `x op y` as the first. For example `a` is: `a y x = x : (b (x+y) y)`, `b` does multiplication: `b y x = x : (c (x*y) y)`, etc.
Edit: @Michael Klein saved a byte in the 1st variant (`#`). Luckily I also found one byte for the second variant, so both have the same length again.
Edit II: @Zgarb found 2 bytes in the second version to save, and I 4 in the first, so they are no longer of the same length.
[Answer]
# ES6 (Javascript), ~~79~~, ~~67~~, 65 bytes
UPDATE
* minus 2 bytes, by starting with i=2, as suggested by @ETHProductions
* Saved 3 bytes, thanks to excellent advice from @Neil !
**Golfed**
```
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a
```
**Test**
```
S=(n,a,i=2)=>i<n?S(n,a,a.push(eval(a[i-2]+"-/+*"[i%4]+a[i-1]))):a
>S(8,[1,3])
Array [ 1, 3, 4, 12, -8, -1.5, -9.5, 14.25 ]
>S(5,[0,1])
Array [ 0, 1, 1, 1, 0 ]
>S(9,[1,0])
Array [ 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
>S(25,[6,3])
Array [ 6, 3, 9, 27, -18, -1.5, -19.5, 29.25, -48.75, -0.6, ...]
```
[Answer]
# Python 3, ~~90~~ ~~80~~ 74 bytes
xnor's probably going to come and destroy this solution...
```
def F(s,n,i=2):
while i<n:s+=eval('%s'*3%(s[-2],'-/+*'[i%4],s[-1])),;i+=1
```
The function modifies the list passed to it. Use like this:
```
s = [1,3]
F(s,8)
```
[**Try on repl.it!**](https://repl.it/E8Lu/1)
*-6 bytes thanks to Copper*
[Answer]
# [Perl 6](https://perl6.org), ~~75 71~~ 61 bytes
```
->\a,\b,\c{$_=[|(&[+],&[*],&[-],&[/])xx*];(a,b,{.shift.($^a,$^b)}...*)[^c]}
```
[Test it](https://tio.run/##ZVHbbtpAEH3frxhFLrZhvXht8KWIhA@oeOpLxU2@TIIlsF1fICnhy/rWH6OzhiRSIsyxZ87xmbPjEqudd2lrhIMnkgnbv0CvbvCYYW3V@LvFPEGYXqz7ZcSXMV8mJ20zXbwavcVgxXuLvgJLwXBlPj/3VxMj4jE/iXqbPTbC0NYR19axeRZC9M3FOlmdLzRi1mDdwBR2WY61eKqwNB76pthH5fcTA9gP14QAiw5fwVimAxP6fXDhG@igv7VBt/QHIBIWutDVw@oBzIES8ZtqRTicEMzsf3/FvN1jlSXiR1Y37MyYOvdPijJh5S7Kb7GG4EwYq9sYKkzbBK2ywiSrsyKnibMNmKAyzjbkVxVtnhq2sG1pUplHVVUc390fi@pmad3DDAyNdhFzbW5ymOFziUmDaeeV1VaKWO5evkw0Pn@LDxNy@aJ@tyXyTotAi0Gb37HzRdLqAiY5uBxGHKTDwQroL8WYMFQoR8IZM2aDhDGzqX67bLVHGA5hPvXgWLS7FJ6yA0KaHa5biV/gD1YFIJ2@EvCraCEtcr2BHOmATQHbKE93CM02aiCJahSMSbINVaDrpM/ImEeJKY/XRQ45OL6K@5FZdqGdkEJTNQqEr@628FQVCvdKeuRn@YEIvY50O5FP9I33x7ZipB0KO7hqHF/9bk13HHS6oJsi3VDIwL3K5Mjp3lBNN7zJfDtULY9ieeF/ "Perl 6 – Try It Online")
```
{$_=[|(&[+],&[*],&[-],&[/])xx*];($^a,$^b,{.shift.($^a,$^b)}...*)[^$^c]}
```
[Test it](https://tio.run/##ZVHbkppAEH2fr@jaInIRRgaUSyyjH5DyKS8poxZC70oVAuHiJa5flrf8mOlB3a3aLfFA9zmcPtOUWGXeta0R9h6Px2x3gl7d4CHF2qrxd4t5jDC5npX1ZPGq9Rb9pdlbGBIsCYOlfjway7GmrCJTWW3MM6@36XPDHw39wjk39MVKWcXLy5XsZw3WDUwgS3Os@UuFpTY1dL6Lyq9nBrAbrAgBFh2@gvYr6etgGODCF1BBfbRBtdQpEAkLlavyYTkFvS9F5l21JByMCWb2v7983u6wSmP@Pa0bdmFMnvkHRRmzMovye6wBOGPG6nYDFSZtjFZZYZzWaZHTxNkadJAZZ2vyq4o2TzSb27bQqcyjqioOb@7PRXW3tL7BDDSFtrExlbluwgyPJcYNJp1XWlsJYpmdPk3UPn6HdxNy@aR@syXySYlA2YAyf2KXq6DVBUyY4JowNEE4JlgB/QUfEYYSxZA7I8ZsEDBiNtWPy5Z7hMEA5hMPDkWbJfCS7hGSdH/byuYEf7AqAOn0FYefRQtJkasN5EgHbArYRnmSITTbqIE4qpEzJsg2lIFukz4iYx4lpjxeFzk0wfFl3PfMogvthBSaqmHAfXm3uSerkLs30iM/yw946HWk24l8ou@8P7IlI@yQ28FN4/jyd2@6o6DTBd0U4YZcBO5NJoZO94ZsuuFd5tuhbHkUywv/Aw "Perl 6 – Try It Online")
```
{($^a,$^b,{(&[+],&[*],&[-],&[/])[$++%4]($^a,$^b)}...*)[^$^c]}
```
[Test it](https://tio.run/##ZVDbkppAEH2fr@jaYgUUBgaUSywjH5DyKS8pg1sInV2qEAgXjTF@Wd7yY6YHdbdqt4AD3edw@kzX2BTepW8R9h5P52x3hFHb4SHH1mzxZ49lirC4nDRlkxjKZmuctNF6Ehuj9ViCKcGK9bUymTxO47tKP3POx/p6o2zS@Hwh06jDtoMFFHmJLX9usNaWY53vkvrTiQHsrA0hwHrAP6B9zyY6jMfgwiOooN7boJrqEoiEtcpV@REvQZ9IkXFTxYTWnCCy//3lq36HTZ7yL3nbsTNj8qRfKcqc1UVS3mJZ4MwZa/stNJj1KZp1g2ne5lVJE6Mn0EFmjJ7Ir6n6MtNsbttCp7JMmqY6vLr/qJqbpfkZItAU2sbWUFa6ARH@qjHtMBu88tbMEOvi@GGi9n77bybk8kH9akvkg5KAsgVl9cDOF0GrC5gwwDVgaoBwDDADegSfEYYSxZQ7M8ZsEDBjNtX325Z7BMuC1cKDQ9UXGTzne4Qs31@3sj3Cb2wqQDp9w@Fb1UNWlWoHJdIBuwpekjIrELqXpIM0aZEzJsg2lIGuk94jYx4lpjzeEDk0wPFl3LfMYgjthBSaqmnAffm2uSerkLtX0iM/0w946A2kO4h8om@8P7MlI@yQ28FV4/jyujXdWTDogmGKcEMuAvcqE1Nn@EM23fAm8@1QtjyK5YX/AQ "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$a」 「$b」 「$c」
# generate sequence
(
# initialize sequence
$^a, # declare and use first argument
$^b, # second argument
{ # bare block lambda with two placeholder parameters 「$a」 「$b」
(
&[+], &[*], &[-], &[/] # the four operators
)[ # index into the list of operators
$++ # increment (++) an anonymous state variable ($)
% 4 # modulo 4
]( $^a, $^b ) # and use it on the previous two values in sequence
}
... # repeat that until
* # indefinitely
)[ # take only
^ # upto and excluding: ( Range object )
$^c # third argument
]
}
```
[Answer]
# Mathematica, 68 bytes
```
(±1=#;±2=#2;±n_:=1##[#-#2,#/#2,+##][[n~Mod~4]]&[±(n-2),±(n-1)];±#3)&
```
Barely snuck into 3rd place! Unnamed function of three arguments, which uses a helper unary operator `±` such that `±n` is exactly the nth element x(n) of the Stewie sequence. The first two arguments are x(1) and x(2), and the third argument is the N indicating which x(N) we output.
Direct implementation, using a mod-4 calculation to choose which binary function to apply to the previous two terms. Picking the correct binary function, which is what `1##[#-#2,#/#2,+##]` helps with, uses a few of [these fun Mathematica golfing tricks](https://codegolf.stackexchange.com/a/45188/56178).
[Answer]
# x86-64 machine code, 34 bytes
Calling convention = x86-64 System V [x32 ABI](https://en.wikipedia.org/wiki/X32_ABI) (register args with 32-bit pointers in long mode).
The function signature is `void stewie_x87_1reg(float *seq_buf, unsigned Nterms);`. The function receives the x0 and x1 seed values in the first two elements of the array, and extends the sequence out to at least N more elements. The buffer must be padded out to 2 + N-rounded-up-to-next-multiple-of-4. (i.e. `2 + ((N+3)&~3)`, or just N+5).
Requiring padded buffers is normal in assembly for high-performance or SIMD-vectorized functions, and this unrolled loop is similar, so I don't think it's bending the rules too far. The caller can easily (and should) ignore all the padding elements.
Passing x0 and x1 as a function arg not already in the buffer would cost us only 3 bytes (for a [`movlps [rdi], xmm0`](http://www.felixcloutier.com/x86/MOVLPS.html) or `movups [rdi], xmm0`), although this would be a non-standard calling convention since System V passes `struct{ float x,y; };` in two separate XMM registers.
This is `objdump -drw -Mintel` output with a bit of formatting to add comments
```
0000000000000100 <stewie_x87_1reg>:
;; load inside the loop to match FSTP at the end of every iteration
;; x[i-1] is always in ST0
;; x[i-2] is re-loaded from memory
100: d9 47 04 fld DWORD PTR [rdi+0x4]
103: d8 07 fadd DWORD PTR [rdi]
105: d9 57 08 fst DWORD PTR [rdi+0x8]
108: 83 c7 10 add edi,0x10 ; 32-bit pointers save a REX prefix here
10b: d8 4f f4 fmul DWORD PTR [rdi-0xc]
10e: d9 57 fc fst DWORD PTR [rdi-0x4]
111: d8 6f f8 fsubr DWORD PTR [rdi-0x8]
114: d9 17 fst DWORD PTR [rdi]
116: d8 7f fc fdivr DWORD PTR [rdi-0x4]
119: d9 5f 04 fstp DWORD PTR [rdi+0x4]
11c: 83 ee 04 sub esi,0x4
11f: 7f df jg 100 <stewie_x87_1reg>
121: c3 ret
0000000000000122 <stewie_x87_1reg.end>:
## 0x22 = 34 bytes
```
This C reference implementation compiles (with `gcc -Os`) to somewhat similar code. gcc picks the same strategy I did, of keeping just one previous value in a register.
```
void stewie_ref(float *seq, unsigned Nterms)
{
for(unsigned i = 2 ; i<Nterms ; ) {
seq[i] = seq[i-2] + seq[i-1]; i++;
seq[i] = seq[i-2] * seq[i-1]; i++;
seq[i] = seq[i-2] - seq[i-1]; i++;
seq[i] = seq[i-2] / seq[i-1]; i++;
}
}
```
I did experiment with other ways, including a two-register x87 version that has code like:
```
; part of loop body from untested 2-register version. faster but slightly larger :/
; x87 FPU register stack ; x1, x2 (1-based notation)
fadd st0, st1 ; x87 = x3, x2
fst dword [rdi+8 - 16] ; x87 = x3, x2
fmul st1, st0 ; x87 = x3, x4
fld st1 ; x87 = x4, x3, x4
fstp dword [rdi+12 - 16] ; x87 = x3, x4
; and similar for the fsubr and fdivr, needing one fld st1
```
You'd do it this way if you were going for speed (and SSE wasn't available)
Putting the loads from memory inside the loop instead of once on entry might have helped, since we could just store the sub and div results out of order, but still it needs two FLD instructions to set up the stack on entry.
I also tried using SSE/AVX scalar math (starting with values in xmm0 and xmm1), but the larger instruction size is killer. Using `addps` (since that's 1B shorter than `addss`) helps a tiny bit. I used AVX VEX-prefixes for non-commutative instructions, since VSUBSS is only one byte longer than SUBPS (and the same length as SUBSS).
```
; untested. Bigger than x87 version, and can spuriously raise FP exceptions from garbage in high elements
addps xmm0, xmm1 ; x3
movups [rdi+8 - 16], xmm0
mulps xmm1, xmm0 ; xmm1 = x4, xmm0 = x3
movups [rdi+12 - 16], xmm1
vsubss xmm0, xmm1, xmm0 ; not commutative. Could use a value from memory
movups [rdi+16 - 16], xmm0
vdivss xmm1, xmm0, xmm1 ; not commutative
movups [rdi+20 - 16], xmm1
```
---
Tested with this test-harness:
```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char**argv)
{
unsigned seqlen = 100;
if (argc>1)
seqlen = atoi(argv[1]);
float first = 1.0f, second = 2.1f;
if (argc>2)
first = atof(argv[2]);
if (argc>3)
second = atof(argv[3]);
float *seqbuf = malloc(seqlen+8); // not on the stack, needs to be in the low32
seqbuf[0] = first;
seqbuf[1] = second;
for(unsigned i=seqlen ; i<seqlen+8; ++i)
seqbuf[i] = NAN;
stewie_x87_1reg(seqbuf, seqlen);
// stewie_ref(seqbuf, seqlen);
for (unsigned i=0 ; i< (2 + ((seqlen+3)&~3) + 4) ; i++) {
printf("%4d: %g\n", i, seqbuf[i]);
}
return 0;
}
```
Compile with `nasm -felfx32 -Worphan-labels -gdwarf2 golf-stewie-sequence.asm &&`
`gcc -mx32 -o stewie -Og -g golf-stewie-sequence.c golf-stewie-sequence.o`
Run the first test-case with `./stewie 8 1 3`
If you don't have x32 libraries installed, use `nasm -felf64` and leave gcc using the default `-m64`. I used `malloc` instead of `float seqbuf[seqlen+8]` (on the stack) to get a low address without having to actually build as x32.
---
Fun fact: YASM has a bug: it uses a rel32 jcc for the loop branch, when the branch target has the same address as a global symbol.
```
global stewie_x87_1reg
stewie_x87_1reg:
;; ended up moving all prologue code into the loop, so there's nothing here
.loop:
...
sub esi, 4
jg .loop
```
assembles to ... `11f: 0f 8f db ff ff ff jg 100 <stewie_x87_1reg>`
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~19~~ ~~18~~ 17 bytes
```
q:"y'+*-/'@)hyhUV
```
Input is in the format: `N` (0-based), `x(1)`, `x(2)` (as strings); all separated by newlines.
[Try it online!](http://matl.tryitonline.net/#code=cToieScrKi0vJ0ApaHloVVY&input=NwonMScKJzMnCg) Or [verify all test cases](http://matl.tryitonline.net/#code=YApxOiJ5JysqLS8nQCloeWhVVgpdMTBYaFpjRFQ&input=NwonMScKJzMnCjQKJzAnCicxJwo4CicxJwonMCcKMjQKJzYnCiczJw) (slightly modified code; output sequences separated by a blank line).
### Explanation
MATL doesn't have a proper `eval` function, but `U` (`str2num`) can evaluate numeric expressions with infix operators.
Each new term is computed and pushed onto the stack, keeping the previous terms. The entire stack is printed at the end.
```
q % Implicitly input N (0-based). Subtract 1
:" % Repeat that many times
y % Duplicate x(n-1), where n is the number of already computed terms
% In the first iteration, which corresponds to n=2, this implicitly
% inputs x(1) and x(2) as strings (and then duplicates x(1))
'+*-/' % Push this string
@) % Push iteration number and apply as modular index into the string.
% So this gives '+' in the first iteration, '*' in the second etc
h % Concatenate horizontally. This gives a string of the form
% '*x(n-1)+', where '+' is the appropriate operator
&y % Duplicate x(n)
hh % Concatenate horizontally. This gives a string of the form
% 'x(n-1)+x(n)'
U % Convert to number. This evaluates the string
V % Convert back to string. This is the new term, x(n+1)
% Implicitly end loop and display stack
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~21~~ ~~19~~ 18 bytes
Input is taken in the order **N**(0-based), **x(2)**, **x(1)**.
Saved 1 byte thanks to *carusocomputing*.
```
GUDXsX"/+*-"Nè.V})
```
[Try it online!](http://05ab1e.tryitonline.net/#code=R1VEWHNYIi8rKi0iTsOoLlZ9KQ&input=MjQKMwo2)
**Explanation**
```
G # for N in [0 ... n-1] do:
U # save top element of stack in X
D # duplicate top of stack
X # push X
s # swap top 2 elements on stack
X # push X
"/+*-"Nè # index into the string with the current iteration number
.V # evaluate
} # end loop
) # wrap stack in list
```
We iteratively build the stack with the latest element in the sequence on top, while keeping all previous elements in order.
Then we wrap the stack in a list at the end to display all values at once.
[Answer]
# [Haskell](https://www.haskell.org/), 60 bytes
```
g(o:z)a b=a:g z b(o a b)
p=(+):(*):(-):(/):p
(.g p).(.).take
```
[Try it online!](https://tio.run/##LYxBDoIwFETX9BSzcPGrsYIGo016mBJLIRTaQBOVy9eqLCZ58zKZTi@DcS4lS16uXKNRWlqsaMgjN86CogOXtM855py4DKxVJCwCFyS4iHowadT9BIWHZ0U0S8QNFS4b1yhRbXzPvtz4XOP6HRXPzswGP@fwwjsfhbmfInZo/yZ9AA "Haskell – Try It Online")
Ungolfed:
```
ungolfed :: Int -> Double -> Double -> [Double]
ungolfed len x1 x2 = take len $ go (cycle [(+),(*),(-),(/)]) x1 x2
where go (f:fs) x y = x : go fs y (f x y)
```
Knowing `\x -> f x == f`, `\x -> f $ g x == f . g`, and some other patterns, you can transform a normal (point-full) function into a point-free one:
```
f0 len x1 x2 = take len $ go p x1 x2
f1 len = \x1 x2 -> take len $ go p x1 x2
f2 len = \x1 -> take len . go p x1
f3 len = (take len .) . go p
f4 = \len -> (. go p) (take len .)
f5 = \len -> (. go p) ((.) (take len))
f6 = \len -> (. go p) . (.) $ take len
f7 = \len -> ((. go p) . (.) . take) len
f8 = (. go p) . (.) . take
```
`\x y -> f $ g x y == (f.) . g` is also a common pattern.
You could also read this backwards for adding back arguments to a point-free function.
[Answer]
## Common Lisp, 158
```
(lambda(x y n)(loop repeat n for a = x then b for b = y then r for o in '#1=(+ * - / . #1#)for r =(ignore-errors(funcall o a b))collect(coerce a'long-float)))
```
Not really competitive, but I like how it is is expressed quite naturally:
```
(lambda (x y n)
(loop
repeat n
for a = x then b
for b = y then r
for o in '#1=(+ * - / . #1#)
for r = (ignore-errors (funcall o a b))
collect (coerce a 'long-float)))
```
We ignore errors when computing R, which makes R (and then B) possibly take the NIL value. That allows to output the current result even if the next value is undefined. Then, eventually the loop will fail, but that's within the rules.
## Tests
We name the function `F` and verify that the expected values are approximately equal to the tested one.
```
(loop
for (args expected)
in
'(((1 3 8)
(1 3 4 12 -8 -1.5 -9.5 14.25))
((0 1 5)
(0 1 1 1 0))
((1 0 9)
(1 0 1 0 1 0 1 0 1))
((6 3 25)
(6 3 9 27 -18 -1.5 -19.5 29.25 -48.75 -0.6 -49.35 29.61 -78.96 -0.375 -79.335 29.7506 -109.086 -0.272727 -109.358 29.825 -139.183 -0.214286 -139.398 29.8709 -169.269)))
for result = (apply #'f args)
always (every (lambda (u v) (< (abs (- u v)) 0.001)) result expected))
=> T
```
The reason for the approximate test is because the computed values are a little more precise than required; here, for `(f 6 3 25)`:
```
(6.0d0 3.0d0 9.0d0 27.0d0 -18.0d0 -1.5d0 -19.5d0 29.25d0 -48.75d0 -0.6d0
-49.35d0 29.61d0 -78.96d0 -0.375d0 -79.335d0 29.750625d0 -109.085625d0
-0.2727272727272727d0 -109.35835227272727d0 29.825005165289255d0
-139.18335743801654d0 -0.21428571428571427d0 -139.39764315230224d0
29.870923532636194d0 -169.26856668493843d0)
```
[Answer]
# dc, ~~112~~ ~~110~~ 108 bytes
```
5k?sarfsmsn[pSnla1-Sa]sh[lmlndSm]sv[lvx/lhx]sb[lvx+lhx]sc[lvx*lhx]sd[lvx-lhx]se[lcx2la>d2la>e2la>b2la>j]dsjx
```
Sometimes `dc` answers can be super long, and sometimes they can be super short. It all just depends on the challenge at hand as is the case with many other languages. Anyways, this prompts for a space-separated one-indexed command line input of 3 integers, `x(1), x(2), N`, upon invocation, and outputs each element of the sequence on separate lines with non-integer outputs containing 5 digits after the decimal point.
For example, the input `6 3 25` results in the following output:
```
6
3
9
27
-18
-1.50000
-19.50000
29.25000
-48.75000
-.60000
-49.35000
29.61000
-78.96000
-.37500
-79.33500
29.75062
-109.08562
-.27272
-109.35834
29.82420
-139.18254
-.21428
-139.39682
29.86995
-169.26677
```
[Answer]
# Perl, 62 + 3 (`-pla` flag) = 65 bytes
```
push@F,eval$F[-2].qw(* - / +)[$_%4].$F[-1]for 3..pop@F;$_="@F"
```
Using:
```
perl -plae 'push@F,eval$F[-2].qw(* - / +)[$_%4].$F[-1]for 3..pop@F;$_="@F"' <<< '1 3 8'
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
λ£"-/+*"Nè.V
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3O5Di5V09bW1lPwOr9AL@/8/2lBHwTiWywIA "05AB1E – Try It Online")
[Answer]
# Bash, 224 bytes (NO CONTEST)
A tremendously large implementation in *BASH*.
Takes the task quite literally, and does everything in one continuous pipe,
w/o any unholy control flow structures or recursion.
**Input**
>
> $1,$2 - initial elements
>
>
> $3 - target sequence size
>
>
>
**Golfed**
```
{ echo "a[0]=$1;a[1]=$2;a[0];a[1]";paste <() <(seq 2 $[$3-1]) <(seq 0 $[$3-3]) <(printf '%.0s+*-/' `seq $[$3/4]`|fold -1|head -$[$3-2]) <(seq 1 $[$3-2]);}|sed -r '1 ! s/(.+)\s(.+)\s(.+)\s(.)/a[\1]=a[\2]\3a[\4];a[\1];/'|bc -l
```
**Less Golfed**
```
{
echo "a[0]=$1;a[1]=$2;a[0];a[1]";
paste <() <(seq 2 $[$3-1]) <(seq 0 $[$3-3]) <(printf '%.0s+*-/' `seq $[$3/4]`|fold -1|head -$[$3-2]) <(seq 1 $[$3-2]);
}\
|sed -r '1 ! s/(.+)\s(.+)\s(.+)\s(.)/a[\1]=a[\2]\3a[\4];a[\1];/' \
|bc -l
```
**Test**
```
>./stewie.sh 1 3 8
1
3
4
12
-8
-1.50000000000000000000
-9.50000000000000000000
14.25000000000000000000
```
**Pipeline Stages**
Generate a table of element indices + op, for an each output sequence element (one per line):
```
...
2 0 + 1
3 1 * 2
4 2 - 3
5 3 / 4
6 4 + 5
7 5 * 6
...
```
Use *sed* to convert this into a linear *bc* program:
```
...
a[2]=a[0]+a[1];a[2];
a[3]=a[1]*a[2];a[3];
a[4]=a[2]-a[3];a[4];
a[5]=a[3]/a[4];a[5];
a[6]=a[4]+a[5];a[6];
a[7]=a[5]*a[6];a[7];
...
```
feed this to *bc* and let it do all the job
[Answer]
# Ruby, 79 bytes
```
->(b,c,d){a=[b,c];(d-2).times{|i|a<<a[i].send(%i{+ * - /}[i%4],a[i+1]).to_f};a}
```
I suspect this is very far off from optimal (and I haven't looked at the other answers yet), but it's fun nonetheless.
I wanted to have some fun with `Enumerable#cycle`, but sadly, it's 4 fewer characters to just use `%4`.
[Answer]
# C++14, 118 bytes
```
[](auto&v,int N){for(int i=0;++i<N-1;){auto p=v.rbegin(),q=p+1;v.push_back(i%4?i%4<2?*q+*p:i%4<3?*q**p:*q-*p:*q/ *p);}
```
As unnamed lambda modifying its input. Requires `v` to be a `vector<double>` or `vector<float>`.
Ungolfed and usage:
```
#include<iostream>
#include<vector>
auto f=
[](auto&v,int N){
for(int i=0; ++i<N-1;){
auto p=v.rbegin(),q=p+1;
v.push_back(
i%4 ?
i%4<2 ? *q+*p :
i%4<3 ? *q**p : *q-*p
: *q/ *p
);
}
};
int main(){
std::vector<double> v={1,3};
f(v,8);
for (auto x:v) std::cout << x << ", ";
std::cout << "\n";
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@OxVs2n)q"-/+*"gY}hV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QE94VnMybilxIi0vKyoiZ1l9aFY&input=MjUKWzYsM10)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ ~~60~~ 58 bytes
-8 bytes thanks to mazzy
```
param($a,$b)3..$a|%{$b+=$b[-2,-1]-join"*-/+"[$_%4]|iex}
$b
```
[Try it online!](https://tio.run/##JYzdCoIwGEDv9xRjfMa3/GZOKyrwSWTEBkqGqdhFgvrsy5@7w@FwuvZX9N9XUdceymz0ne3tB8ESOJlGEdgpGMGFGbhcJaS0Ue@2asRRnUKRwzM4m6kqhpmB8zNjyPBGqCmVkhheCGPSG95XG2@YLPq6FkwubzFkgPDMtZHEm51jIx9c8JDjAUq@Cb4ns/8D "PowerShell – Try It Online")
Builds `x(n)` in place by making a string out of `x(n-2)` and `x(n-1)`, joined by the operator we need (determined by modulo math using the index we get for free from iterating up), and feeds it into `i`nvoke`Ex`pression. We then spit out the final array.
[Answer]
# [J](http://jsoftware.com/), ~~49~~ ~~33~~ 29 bytes
```
[$_2&(],(-,%,+,*)/@{.{~4|#@])
```
[Try it online!](https://tio.run/##bU7LTsMwELznK0a82hTH9SMPO1JRBRInxIFrVUVRm0JQSaom5dKKXw/rJOKEbI/XM7Pr@eyu@GSHRYoJGARSOgHH09vLc7e6ydTddM2mAbtl92zmz5dnfv4JL9fLtd/53usjx6kp0Nb74phXLTb11yE/lk1dEYf8uy632O3rvC2rdxzqkizH@lRt3bNsmlPReG3RtAuOVYrZHIILIfGAyzLwvGLzUWNqsIOE9uGMkAyaIWSQiiEzdCSPCK1DGXIVjW0RtQnIsU0w1zlsgdFi@8nCR5D2PPsPR69y8@K/GFTBQiX0vekjEFAEKEsJkIWGJ3QJHlNtue6FWCJLDLexE7TTE5IGLYkE0VJYLkyvq8StgdKRcR7jJkttuTS6t8hQObOjtB0sibBExJQitt0v "J – Try It Online")
*-4 bytes thanks to FrownFrog*
[Answer]
# Pyth - 20 bytes
Outputting all `n` costs me.
```
u+Gvj@"+*-/"H>2GttEQ
```
Doesn't work online cuz of eval.
[Answer]
# Ceylon, 195 bytes
```
Float[]s(Integer a,Integer b,Integer n)=>loop([a.float,b.float,[Float.divided,Float.plus,Float.times,Float.minus].cycled.rest])(([x,y,o])=>[y,(o.first else nothing)(x)(y),o.rest]).take(n)*.first;
```
Formatted and commented:
```
// Print the first n entries of the Stewies sequence with given starting entries.
//
// Question: http://codegolf.stackexchange.com/q/101145/2338
// My answer: http://codegolf.stackexchange.com/a/101251/2338
// Declare a function `s` which takes three integers, and returns a tuple
// of floats. (The more common syntax for the return value is [Float*],
// but Float[] is shorter.)
Float[] s(Integer a, Integer b, Integer n)
// it is implemented by evaluating the following expression for each call.
=>
// start a loop with ...
loop([
// ... float versions of the integers, and ...
a.float, b.float,
// ... an infinite sequence of the four operators, ever repeating.
// I needed the `.rest` here so the whole thing gets a {...*} type
// instead of {...+}, which doesn't fit to what o.rest returns.
// Each operator has the type Float(Float)(Float), i.e. you apply
// it twice to one float each to get a Float result.
[Float.divided, Float.plus, Float.times, Float.minus].cycled.rest])
// in each iteration of the loop, map the triple of two numbers
// and a sequence of operators to a triple of ...
(([x, y, o]) => [
// the second number,
y,
//the result of the first operator with both numbers
// (using this "else nothing" here to convince the
// compiler that o.first is not null),
(o.first else nothing)(x)(y),
// and the sequence of operators without its first element.
// (that one unfortunately has a {...*} type, i.e. a possibly
// empty sequence.)
o.rest])
// now we got an infinite sequence of those triples.
// We just want the first n of them ...
.take(n)
// and of each triple just the first element.
// (The *. syntax produces a tuple, non-lazily.
// We could also have used .map((z) => z.first)
// or .map(Iterable.first) or .map((z) => z[0]), each of
// which would return a (lazy) sequence, but they all would be
// longer.)
*.first;
```
Example usage:
```
shared void run() {
print(s(1, 3, 8));
print(s(0,1,11));
print(s(1,0,9));
print(s(6, 3, 29));
}
```
Example output:
```
[1.0, 3.0, 4.0, 12.0, -8.0, -1.5, -9.5, 14.25]
[0.0, 1.0, 1.0, 1.0, 0.0, Infinity, Infinity, Infinity, NaN, NaN, NaN]
[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
[6.0, 3.0, 9.0, 27.0, -18.0, -1.5, -19.5, 29.25, -48.75, -0.6, -49.35, 29.61, -78.96000000000001, -0.37499999999999994, -79.33500000000001, 29.750625, -109.08562500000001, -0.2727272727272727, -109.35835227272727, 29.825005165289255, -139.18335743801651, -0.2142857142857143, -139.39764315230224, 29.870923532636194, -169.26856668493843, -0.17647058823529413, -169.44503727317374, 29.90206540114831, -199.34710267432206]
```
The second example shows how this would handle division by zero.
The last example shows that the results deviate a bit depending on which kind of arithmetic (and rounding) one is using ... I think Ceylon's 64 bit floating point arithmetic is a bit nearer to what it should be than what was posted in the question.
[Answer]
**Clojure, 99 bytes**
```
#(let[ops[+ * - /]](take %3(map first(iterate(fn[[a b i]][b((ops i)a b)(mod(inc i)4)])[%1 %2 0]))))
```
This version is nicer to use in practice but has 110 bytes:
```
(defn f[a b n](let[ops[+ * - /]](take n(map first(iterate(fn[[a b i]][b((ops i)a b)(mod(inc i)4)])[a b 0])))))
```
I had trouble fuzing iterated function and a cyclical sequence of operations so I had to use a counter instead. Also tried using a FSM transition table like `{+ * * - - / / +}` but I couldn't squeeze it to less code.
Could be expressed as an anonymous function
Un-golfed:
```
(defn f [a b n]
(let [ops [+ * - /]]
(->> [a b 0]
(iterate (fn [[a b i]]
[b
((ops i) a b)
(mod (inc i) 4)]))
(map first)
(take n))))
```
Must be called with floats like `(f 6.0 3.0 25)` as otherwise you get rational numbers out. Alternatively the iteration could be started from `[a (float b) 0]` which brings some extra characters.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 91 bytes
```
@(x,n)eval 'for i=3:n,x(i)=eval([(n=@num2str)(x(i-2)),"*-/+"(mod(i,4)+1),n(x(i-1))]);end,x'
```
[Try it online!](https://tio.run/##HclNCoMwEAbQq4gb56tjSrQLUQLeQ1xITSBQJ@AfuX1su30vvI/5sskZpVQaKLLAXvMnK1zYMm@aTjiSh/khjSRmkHOt92MDfb2qAc4f1bPMaQ0LeX6h1GD5pwYm9FYWjkVyNGpuJm6Rbg "Octave – Try It Online")
Some golfs:
* No parentheses for the first `eval` call
* No concatenations for the first `eval` call
* Inline assignment of `*-/+` (not possible in MATLAB)
* Combined `'` and `"` to avoid escaping the apostrophes (not possible in MATLAB)
* Storing `n=@num2str` since it's used twice (not possible in MATLAB)
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 19 bytes
```
=A,B&Y+Z,YZ,Y-Z,Y/Z
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/39ZRx0ktUjtKJxKIdIFYP@r/fzMFYwUjUwA "cQuents – Try It Online")
# Explanation
Receives three inputs, `A B n`
```
=A,B first two terms in sequence are A and B
& output first n terms of sequence
Y+Z,YZ,Y-Z,Y/Z next terms are Y+Z, then Y*Z, ..., cycling back to beginning after 4th
Y and Z are the previous two terms in the sequence
```
] |
[Question]
[
*Disclaimer: ModTen is a fictional card game which was created for the sole purpose of this challenge.*
## The rules of ModTen
*ModTen* is played with a standard 52-card deck. Because the full rules are yet to be invented, we're going to focus on the hand ranking exclusively.
[![Jack & Three, suited](https://i.stack.imgur.com/4xgGc.png)](https://i.stack.imgur.com/4xgGc.png)
*A winning hand in ModTen. Graphics from [Wikipedia](https://en.wikipedia.org/wiki/Standard_52-card_deck#Rank_and_color).*
### Card values
The cards have the following values:
* **2** to **9**: worth their face value
* **Ten**: 0 point
* **Jack**: 3 points
* **Queen** or **King**: 8 points
* **Ace**: 9 points
### Hand values
* A *ModTen* hand is made of **two cards**. The base value of a hand is obtained by multiplying the value of both cards together and keeping the last digit only (i.e. applying a modulo 10).
For instance, the value of **7**♥ - **Q**♣ is "\$6\$", because \$(7\times8)\bmod 10=6\$.
* The only other rule in *ModTen* is that **suited cards** are worth more than unsuited ones. By convention, we are going to append a **"s"** to the value if both cards are of the same suit.
For instance, the value of **9**♠ - **5**♠ will be noted as "\$5\text{s}\$", because \$(9\times5)\bmod 10=5\$ and the cards are suited.
### Hand ranking and winner
The above rules result in 18 distinct hand ranks which are summarized in the following table, from strongest to lowest (or rarest to most common). The probabilities are given for information only.
Given two hands, the hand with the lowest rank wins. If both hands are of the same rank, then it's a draw (there's no tie breaker).
```
hand rank | hand value(s) | deal probability
-----------+---------------+------------------
1 | 9s | 0.30%
2 | 3s | 0.60%
3 | 1s | 0.90%
4 | 7s | 1.21%
5 | 5s | 1.51%
6 | 3 | 1.81%
7 | 9 | 2.26%
8 | 8s | 2.71%
9 | 6s | 3.02%
10 | 1 or 7 | 3.62% each
11 | 2s or 4s | 3.92% each
12 | 5 | 4.98%
13 | 0s | 5.43%
14 | 8 | 8.14%
15 | 6 | 9.95%
16 | 2 | 11.76%
17 | 4 | 13.57%
18 | 0 | 16.74%
```
## The challenge
Given two *ModTen* hands, output one of **three consistent values** of your choice to tell whether:
* the first player wins
* the second player wins
* it's a draw
The following rules apply:
* A card must be described by its rank in upper case (`2`, `3`, ..., `9`, `T`, `J`, `Q`, `K` or `A`) followed by its suit in lower case (`c`, `d`, `h` or `s`, for clubs, diamonds, hearts and spades).
* You may use `"10"` instead of `"T"` but any other substitution is prohibited.
* As long as the above rules are followed, you may take the hands in any reasonable and unambiguous format. You are allowed to take the rank and the suit as two distinct characters rather than a single string.
Some valid input formats are:
+ `"7c Qh 8s Ks"`
+ `[["7c","Qh"], ["8s","Ks"]]`
+ `[[['7','c'], ['Q','h']], [['8','s'], ['K','s']]]`
+ etc.
* Instead of using 3 consistent distinct values, your output may also be **negative**, **positive** or **zero**. Please specify the output format used in your answer.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
Player 1 wins
```
["Js","3s"], ["Ks","Kh"]
["7h","9h"], ["9s","7c"]
["Ah","5s"], ["Ts","8s"]
["Ts","8s"], ["Jh","2s"]
["4h","8s"], ["Qh","Ks"]
```
Player 2 wins
```
["Th","8d"], ["6s","Kd"]
["Jc","5c"], ["3s","9s"]
["Jc","Jd"], ["9h","Ah"]
["2d","4d"], ["3h","3s"]
["5c","4c"], ["3c","2c"]
```
Draw
```
["Js","3s"], ["3d","Jd"]
["Ah","Ac"], ["3d","9s"]
["Qc","Kc"], ["6d","4d"]
["2d","3d"], ["3s","2s"]
["Ts","9c"], ["4h","5d"]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~114~~ 110 bytes
```
lambda m,n:p(*n)-p(*m)
R=b"T 2J45UNK9RL<3SLM;QAK:O>=/678"
v=R.find
p=lambda i,s,j,t:R[s==t::2][v(j)*v(i)%10+3]
```
[Try it online!](https://tio.run/##fZFba4MwGIbv/RVBGGrnDk20rW4OhF1pd6hzV06GmkosrZN@0tJf76yRRbp1N4E8vCeS6lCzr5I0ufPRrJNNShO00Uu7UkeldtWeG00KnFQOEfYM8/3Zt4L5PXmbP90tXN9@eXBuJtOZLO2c4DovSipVTh9S6KCv9NoOInCc2rZxHO3UlTbaqYV2Mb69JHFTL6H@zBJYwhg5KJIQilLFAwKKjlLFB58psc7plFmsoxZMs5Yijl1mcnEIMxC4ux2xx/AAG6zHC@a3WIolsQCLBSGb0U42AZ/@LPAyM@soAQsG1ONai7liLaYGp4QRoTUzo0/IcHZST/94AEI9Ue8ytzfTQf0i8zmdHBtFPenrAQttCBbXGsykXb1UbYuyVuXXdXJYbtEY7YsSbFmT8q8tqlFRosEP2W0K1@fqqNa0Uzf@z43Puh@3yf6Mif4yNd8 "Python 3 – Try It Online")
@Arnauld proposed the idea of merging the card value and rank table strings. After some attempts I managed to craft a merged string `R="T 2J45UNK9RL<3SLM;QAK:O>=/678"`, which has the same length as the original card value string. The substring `R[6:25]="UNK9RL<3SLM;QAK:O>=/"` serves as the rank table as well as a card value lookup table for `3`, `9`, `A`, `K`, and `Q`. The ASCII-value decoding of the new rank table has the same ranking effect as the previous rank table.
Using byte strings as input saves 4 bytes.
Using `cmp` in Python 2 can reduce the solution to 102 bytes, as shown by [@xnor's solution](https://tio.run/##fZFda4MwGIXv/RVBGH5MtjXRtro5EHal3YfOXTkZLqnE0triKy399U4j09HSXebhnDwJZ3es@bbETe5@Nuts880yPXboZqfqSZSA69aOg9Nkr640fa8W2tXk7pqk@bZChQHGyqhRUaI41aTIlWOEfdP6eAnsaPFA3hfP96EXOK@P7u10NpelvRvd5EXJmnoJ9RfNYAkT5KJEQihRfCCgGEgJIOBKagg24zbvmA0z2jIkoMctEYxhDgMUhxb6HI/Q5D0MedBCKZVGLx68MZ@zLjSFgP16fWrRjhGwYWS@yNncG96HmSkY4WTIWdTsuxTTEyk7@yxh/iD1uNcX2SgNaSDYtBMNUtJLAQ@5GGyRM7nFhFTaVUVZq/LbOjsuKzRBh6IER9akbjgx2Z8NnPaOPp@req1pp238XxtfbD9V2eFCiZ2Vmh8).
---
# [Python 3](https://docs.python.org/3/), ~~165~~ ~~142~~ ~~130~~ 129 bytes
```
lambda m,n:p(*n)-p(*m)
v="T 23456789 J QA K".find
p=lambda i,s,j,t:ord("HC92FA51GAB4E893D760"[s==t::2][v(j)*v(i)%10])
```
[Try it online!](https://tio.run/##fZFba4MwGIbv/RUfwlCLG22i9QBeuHUH9GaF3nUyXFKJpbXFL7Ts13caOx0tXSCBPLxvnoTsv6XYVfRURB@nTb794jls7Srcm6PKum/WraUdIn0BhDru1PMDAEiaCfMYziPVH4qy4to@OvdLG@21LcNdzU397SkgL7E7eY0fnWc/oDNvOtaXGEUyDEm2PJhra3QwS@tuMs6sk1yh/GQ5rnACESw1gKWRIEXDBiPFVBiZrZgnAtGyAD3WMFAwFq4KLtDHHqpNAxNBBuiIDs5F2kAt0wYv6b0L4fM2NMWU/3oT5rKWUQxwYInKBSLu70e4oxgVtM@5zOm6jLALKb96LOVJL41F3BX5IJ2zVLFpK@qltJMi6XMLDFTOES5XUm1fl5U09fdN/r2qYQLHssJQt7RiV4OEsoI/fxA2Z3T5whxJy7psk//a5GZ7VufHGyV@VTr9AA "Python 3 – Try It Online")
*-23 bytes thanks to @Jonathan Allan*
*-2 bytes thanks to @ovs*
*-1 byte thanks to @mypetlion*
### Ungolfed:
```
f = lambda hand1, hand2: get_rank(*hand2) - get_rank(*hand1)
def get_rank(v1, suit1, v2, suit2):
get_card_value = "T 23456789 J QA K".find
# rank_table = [[17,9,15,5,16,11,14,9,13,6],[12,2,10,1,10,4,8,3,7,0]]
# rank_table = ("H9F5GBE9D6","C2A1A48370") # Base-18 encoding of ranks
rank_table = "HC92FA51GAB4E893D760" # Interleaved base-18 encoding
# ASCII-value decoding has the same ranking effect as base-18 decoding
return ord(rank_table[suit1 == suit2::2][get_card_value(v2) * get_card_value(v1) % 10])
```
The function `f` takes two arguments representing the hand of player 1 and player 2. It returns a positive, negative, or zero value in the case of a player 1 win, a player 2 win, or a draw, correspondingly. Each hand is encoded as a single string, e.g. "7cQh".
[Answer]
# x86-16 machine code, ~~87~~ 83 bytes
**Binary:**
```
00000000: e807 0050 e803 005a 3ac2 ad2c 3092 ad2c ...P...Z:..,0..,
00000010: 30bb 3501 3af4 7503 bb3f 01e8 0a00 92e8 0.5.:.u..?......
00000020: 0600 f6e2 d40a d7c3 b106 bf49 01f2 aee3 ...........I....
00000030: 038a 4504 c312 0a10 0611 0c0f 0a0e 070d ..E.............
00000040: 030b 020b 0509 0408 0124 1a21 1b11 0003 .........$.!....
00000050: 0808 09 ...
```
**Unassembled:**
```
E8 010A CALL GET_HAND ; score first hand, ranked score into AL
50 PUSH AX ; save score
E8 010A CALL GET_HAND ; score second hand
5A POP DX ; restore first hand into DL
3A C2 CMP AL, DL ; compare scores - result in CF, OF and ZF
GET_HAND: ; 4 char string to ranked score ("9s7c" -> 6)
AD LODSW ; load first card string
2C 30 SUB AL, '0' ; ASCII convert
92 XCHG DX, AX ; store in DX
AD LODSW ; load second card string
2C 30 SUB AL, '0' ; ASCII convert
BB 0139 MOV BX, OFFSET R ; first, point to non-suited table
3A F4 CMP DH, AH ; is it suited?
75 03 JNZ NO_SUIT
BB 0143 MOV BX, OFFSET RS ; point to suited table
NO_SUIT:
E8 012C CALL GET_VALUE ; get face card value in AL
92 XCHG DX, AX ; swap first and second cards
E8 012C CALL GET_VALUE ; get face card value in AL
F6 E2 MUL DL ; multiply values of two cards
D4 A0 AAM ; AL = AL mod 10
D7 XLAT ; lookup value in rank score table
C3 RET ; return to caller
GET_VALUE: ; get value of a card (2 -> 2, J -> 3, A -> 9)
B1 06 MOV CL, 6 ; loop counter for scan
BF 014D MOV DI, OFFSET V ; load lookup table
F2/ AE REPNZ SCASB ; scan until match is found
E3 03 JCXZ NOT_FOUND ; if not found, keep original numeric value
8A 45 04 MOV AL, BYTE PTR[DI+4] ; if found, get corresponding value
NOT_FOUND:
C3 RET ; return to program
R DB 18, 10, 16, 6, 17, 12, 15, 10, 14, 7 ; unsuited score table
RS DB 13, 3, 11, 2, 11, 5, 9, 4, 8, 1 ; suited score table
V DB 'J'-'0','Q'-'0','K'-'0','A'-'0','T'-'0' ; face card score table
DB 3, 8, 8, 9, 0
```
Input is as a string such as `Js3sKsKh`, at pointer in `SI`. Output is `ZF = 0 and SF = OF` (test with `JG`) if player 1 wins, `SF ≠ OF` (test with `JL`) if player 2 wins or `ZF` (test with `JE`) if a draw.
**Output using DOS test program:**
[![enter image description here](https://i.stack.imgur.com/sIXAP.png)](https://i.stack.imgur.com/sIXAP.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~41~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•V›{₆Ÿ&∊WÍj¸•19вyεø`Ës‘ߌQ‘ŽćS‡Pθ«}èÆ
```
-4 bytes thanks to *@Grimy*.
Input as a list of list of list of characters, like the third example input format in the challenge description. I.e. P1 `7c Qh` & P2 `8s Ks` would be input as `[[["7","c"],["Q","h"]],[["8","s"],["K","s"]]]`. (And uses `"10"` for `10`.)
Outputs a negative integer if player 1 wins; a positive integer if player 2 wins; or 0 if it's a draw.
[Try it online](https://tio.run/##yy9OTMpM/f//UcOisEcNu6ofNbUd3aH2qKMr/HBv1qEdQGFDywubPM9tPbwj4XB38aOGGYfnH50UCKSP7j3SHvyoYWHAuR2HVtceXnG47f//6OhoJXMlHaVkpVidaKVAICtDKRbIjFayALKLwaLeEFZsLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw2Lwh417Kp@1NR2dIfao46u8MO9WYd2AIUNLS9sqjy39fCOhMPdxY8aZhyef3RSIJA@uvdIe/CjhoUB53YcWl17eMXhtv86fnamh6dlHtpmX/s/GgiUvJR0lIqVYnWilYwhLCAzWskbLgpiZQBFY3UUQMrNIVyghCVUAqTcEq4cJJ@MUO4IV26KZLqhAVy9BVQYqh6LjA7UkRBjjFDVm8AlkJUHwkW9sRiPUJ8CVW@G4tsUhHoviG@gzk@GKjeGK7dENR6h3AvJdEu4nY6oYWkEUaQD8UYKkukZKBECVW4KN90EzTHJ8KBJRnUMZsQaw@30QvWqI4orkzGUo3k1EG6tN5JyMwwfYXjVGM2rxdiiFSkZWCIZb4KSmlJQUyXENYFIqdICJVrBxscCAA).
**Explanation:**
```
•V›{₆Ÿ&∊WÍj¸• # Push compressed integer 36742512464916394906012008
19в # Convert it to base-19 as list:
# [18,10,16,6,17,12,15,10,14,7,13,3,11,2,11,5,9,4,8,1]
Iε # Push the input, and map each of its hands to:
ø # Zip/transpose the hand; swapping rows/columns
# i.e. [["8","s"],["K","s"]] → [[["8","K"],["s","s"]]
` # Push them separated to the stack
Ë # Check if the two suits in the top list are equal (1/0 for truthy/falsey)
s # Swap to get the list with the two values
‘ߌQ‘ # Push dictionary string "JAKEQ"
ŽćS # Push compressed integer 39808
‡ # Transliterate these characters to these digits
P # Now take the product of the two values in the list
θ # Only leave the last digit (basically modulo-10)
« # And merge it to the 1/0
# (now we have the hand values of both players,
# where instead of a trailing "s" we have a leading 1)
}è # After the map: index each value into the earlier created integer-list
# (now we have the hand rank of both players)
Æ # And then reduce the resulting integers by subtracting
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (sections *How to use the dictionary?* *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•V›{₆Ÿ&∊WÍj¸•` is `36742512464916394906012008`, `•V›{₆Ÿ&∊WÍj¸•19в` is `[18,10,16,6,17,12,15,10,14,7,13,3,11,2,11,5,9,4,8,1]`, `‘ߌQ‘` is `"JAKEQ"`, and `ŽćS` is `39808`.
[Answer]
# [Nibbles](http://golfscript.com/nibbles), 31 27 bytes
```
`/.$=+*`*.`'$`r:`#$10$~,`$$`D22-859ff1e2379fa8205a46a3
```
Thats 32 nibbles of code followed by a number that is stored as 22 hex digits. Making 54 half byte instructions in the binary form. (Nibbles isn't on TIO yet).
I found this to be a pretty cool problem. My first instinct was rather than hardcode the hand orders, calculate it! By finding how common each is, but this turned out to be longer surprisingly.
It works by converting each hand to an integer 1-20 and then looking it up it up in a table to find its relative goodness. Finally those goodnesses are subtracted so that equal hands are 0, player 1 wins positive, and player 2 wins negative.
Let's break down the code:
```
`D 22 859ff1e2379fa8205a46a3
```
becomes that data in base 22, which is
```
[5,0,18,8,7,2,19,12,7,1,14,6,9,3,15,8,10,4,20,11]
```
This code just maps on each hand and does a fold on the result
```
`/ special fold
.$ map on input (for each hand)
...
- subtract (the type of special fold)
```
Now for the code that converts hand to a unique number for that suitedness and mod10. Multiply the product by 2 to make space for the suitedness value of 1 or 2 without conflict (this is similar to other solutions).
```
+
* [product mod 10]
~ 2
, `$ $ length of the unique suites
```
To calculate the hand value mod 10:
```
`* product
. map
`' $ transpose of input hand [("J",'c'), ("10",'d')] becomes
(["J","10"],"cd") and since this is a tuple, it returns
the first value, setting $ to be "cd" (used later)
`r read a number from a string in base 10
: list concat of
`# $ 10 hash of the hand value mod 10 (this is to convert JQKA)
$ the hand value string
```
Finally this is looked up in the table by just looking up the value at an index with `=`
There's a couple of cool tricks here. One is how the hash value becomes the right answer mod 10. It uses the data as salt, but the data is also being used to extract our table. This is why the table was in base 22 when we only needed base 20. It gave us some degrees of freedom to brute for search for different representations that will still give the right answer. On average we need about 10000 degrees of freedom. Since JQKA all have to go to the correct number (1/10 chance each).
This was found with brute force search using this code:
```
.| . | `*.,4`,21 ==\$`<@ # n-b=18
`@ 22
..%"13,18,3,10,11,16,2,6,11,17,5,12,9,15,4,10,8,14,1,7" ',' - 18`r$
+- 5 ?:@0~ +-@$1 $
==."JQKA"
`#~ : o$ @ 10
:3:8:8 9
hex$
```
Another cool trick is how the card value is parsed. Essentially what we want to do is say if it is an integer than use its value, otherwise the hash value. But it is shorter to just always put the hash in front of the value and parse the result. Like so: "J" -> "3J", "5" becomes "[something]5". In the first case the J is ignored because it isn't a digit. In the second case the [something] doesn't matter because the complete value is still 5 mod 10.
Also note that we don't actually ever need to do mod 10 on the product because the size of the table we are looking is size 20 and wraps (and we've multiplied by 2).
To invoke it pass the hands as command line args. List of List of tuple of Str, Char.
For example:
```
nibbles hardcode.nbl "[[(\"7\",'c'),(\"Q\",'h')],[(\"8\",'s'),(\"K\",'s')]]"
```
This problem shows off the power of a deterministic hash function already, but there's a cool idea that could improve it further but it would be computationally intractable unless the hash function can be reversed without using brute force!
The idea is rather than look up the hand in a list of goodnesses, take the hash of it. You just need to find salt that happens to give the right ordering (it doesn't have to use values 0-17).
This would be shorter because the current encoding takes
log(18)\*20=83 bits but the new one would be
```
log(18!)+log(n)*2+log2(n^18*(n-18)!/n!)
```
Where n is the base to use in the hash mod. The higher it is the less likely you'll have collisions, but also the less likely you'll manage to get those two hands that are equivalent to map to the same value. This value is maximized by n being 117, giving 68 bits (but really n is another degree of freedom in the search so it could be fewer bits).
This would lead to a 2 byte savings on average! (In data alone, not counting the degrees of freedom for n, you also wouldn't need the \* ~ and = instructions).
The ultimate reason less information is needed is because a list stores exact values but all we really need is an order.
This problem has inspired me to try to design a hash function that can be reversed so that a solution like this (and others for other problems) can be realized without brute force. It has gotten pretty mathy, especially when the base we are talking about isn't a prime number, but it is something I intend to revisit and hopefully write a paper and add it into nibbles!
[Answer]
# [PHP](https://php.net/), ~~212~~ ~~185~~ ~~178~~ 149 bytes
```
while($p=$argv[++$x])$$x=ord(rjpfqlojngmckbkeidha[(($v=[J=>3,Q=>8,K=>8,A=>9])[$p[0]]?:$p[0])*($v[$p[2]]?:$p[2])%10+($p[1]==$p[3])*10]);echo${1}-${2};
```
[Try it online!](https://tio.run/##dZJvb5swEMZfx5/ihDwFFqYW6D@WkSovKk3JpCVS3zGrYtitSRNgmCaZonz27AxORjrtDebu57vn7pFLWR6@3JeyJITWQtUKIogJAbi4gHKZ/BYVeLDJcoWpmPRiiK2JslwrUBZzMZjqYCotBsxt8a3ETChbHGp8m3bwWONrU/2o8Z3q4FNG44m@63fxlezguQ6mBkP7@Tu2/27sx6aUt6U3zdi803mS6rnSFgcah@o9npjqULcad5f2OWauDA6kMeh8Ll4lm/@4GHDT/dymcdrBZ@PM9ThTg2@O4ufjBLyzjP@PyaGpbiy95qdpCWFDQp6LSiSptMG8ikQBraIRrYQCB3aE9EQqC5h9nT09fP/mgjVrXbewZb99MX237x9/9O59FtMKJU815gfVekYOUE8raLXa6LRCC1XkTyJPCy5sWjso@KO2dGUPnVXZ6m2Z1ALSYrVKcg7LLBeQVC8KsDE0G@BNipl17DF84osiy7FPfMmc4Yn4XeJpctjIbImCZdTeGAzoljmUbqOi4na1KJ9/LYtF/rJKX3@@iozLJLZtuo7iSTQK3Hk0unOn@jOORiFzYlqiILv/3JzOR7ypU75J@cz54F0OUA3FowiPAC95ekRtAd15@0905@@Hh96Z@UcX0DhRg8jXWVXkK5HXmH7LMWfTotnSBOtusHV0@Z4Qsj/8AQ "PHP – Try It Online")
* -7 bytes thanks to @Night2!
* -29 bytes by ASCII encoding the table instead of array
Input is via command line. Output to `STDOUT` is **negative** if player 1 wins, **positive** if player 2 wins, `0` if tie. Example:
```
$ php modten.php Js3s KsKh
-1
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~101~~ ~~100~~ ~~94~~ 88 bytes
*-1 byte thanks to Jo King*
```
{[-] .map:{'HC92FA51GAB4E893D76'.ords[[*](.[*;0]>>.&{TR/JQKA/3889/})%10*2+[eq] .[*;1]]}}
```
[Try it online!](https://tio.run/##ZZK9boMwFIX3PoWXJkApfwaCW4rk/stMVN0QQ6QmU6OkZIoQD9ItEmoerC9CMe6NDWzm@OOce7jsVuVn2G4OaLZGd22VXxfI2ix3N9X89YF4zzRwX@i9/xQR/LgI59a2/NjnuVFoVm7cOkWSWLPq/c1mWUptHEXErvVL1zG8q3z11Tl1kFsUdd3ulwdkdRHrbXmhaTFDv9/HxEQx7g@6ibQ4BY0ffhJdNzm56B86lQiVkwRIftkASYEMpKfrABoJUaATmbMM3vdU1AdVITPQ0onpGT0JNFRLnQBl/dz/ozaCxEAS1fRMMulJIIeqH8rrgU71JYmBxKpnAJ7@ML2B8o2aPl4ThhymNqLqTM2IHDTKICmVZDiafdQIDxsdJ0uS@yTS1Ff/B27a/gE "Perl 6 – Try It Online")
Takes input as `f(((<J ♠>, <3 ♠>), (<10 ♠>, <K ♥>)))` using `10` for Ten. Returns a value < 0 if player 1 wins, > 0 if player 2 wins, 0 if it's a draw.
### Explanation
```
{
[-] # subtract values
.map:{ # map both hands
'HC92FA51GAB4E893D76'.ords[ # lookup rank in code point array
[*]( # multiply
.[*;0] # card ranks
>>.&{TR/JQKA/3889/} # translate J,Q,K,A to 3,8,8,9
)
%10*2 # mod 10 times 2
+[eq] .[*;1] # plus 1 if suited
]
}
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~172~~ ~~167~~ ~~165~~ ~~164~~ 162 bytes
```
char*v="T 23456789 J QA K";p(char*l){return"A<92?:51@:;4>893=760"[(l[1]==l[3])+(index(v,l[2])-v)*(index(v,*l)-v)%10*2];}f(char*s){return p(s+5)-p(s);}
```
[Try it online!](https://tio.run/##XY1Lr5swEIXX8a84chUJ8qiCgSSEkFu2sIqUHWWBbFIjURoxebS6ym9Ph7S5Umv5MT5nzjd6/k3rx6em0@3F1NjS2TQ/PtvdQ9uqn1wTeYDyg3C5WkcAMj7Yp/i7chmfnGdj67739fnSdzLdRuptE3pfNnGwW0d@slouZOG0hVcmSVv4pTt1ms7UP53rrC1U6c6v7uRDYRD/x95iosr4fvwDpxccJ4emoTvnx43vj6Y743vVdI6LdzEaWkGFtyhjMbrZpq0d0lV3dOSYMKavnZyBeGOK0EWSQD1jo4HS13Rpz0hwHMgsnnqWh2jA2YA2/wNmr8gOC7xBntrqV93Dw63pSGLzsrf/2OrDlqavbnIYdRf3R0Y@IafcipWNLCJaaYjUhoQDrQnieWdWcRlYLvc2J3Gwa4Ml5UZkOtTwKSKuMoPIplYoExj41icR6oBdrbR4jvFNZpidsmY4sde5xpKbOeFzghSTKdIIbGh@Aw "C (gcc) – Try It Online")
4 bytes shaved off thanks to the amazing @ceilingcat!
Basically a port of @Joel's Python3 solution, but without the base18 encoding. Expects the input as one string with a space separating the hands of the two players, and outputs an integer that is positive, negative or zero to indicate player 1 wins, player 2 wins or if it's a draw.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 46 bytes
```
“T0J3Q8K8A9”yⱮZV€P$Eƭ€)%⁵UḌị“©N¿!Æßvṅ?żṀ’b18¤I
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5wQAy/jQAtvC0fLRw1zKx9tXBcV9qhpTYCK67G1QFpT9VHj1tCHO3oe7u4GKj600u/QfsXDbYfnlz3c2Wp/dM/DnQ2PGmYmGVocWuL5////aCXzDCUdJe9ipVidaCWTYiDbEcgGAA "Jelly – Try It Online")
A full program taking as its argument for example `["7h","Ks"],["4s","Ts"]` and printing zero if both players draw, positive if player 1 wins and negative if player 2 wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 97 bytes
```
≔”)¶&sNψU↓”ζF¹³F¹³F⁻⁴⁼ικ⊞υ⁺÷λ³⊗﹪Π⁺§ζι§ζκχ≔”A↘τ[⁵PkxτG”ε≔⁰δF⟦θη⟧≦⁻№υ⁺⁼§ι¹§ι³⊗﹪Π⁺§ζ⌕ε§ι⁰§ζ⌕ε§ι²χδIδ
```
[Try it online!](https://tio.run/##jZBBS8MwGIbv/oqPnb7AJ7RrnR2eyqYwZ6EDb8NDbTIbDIlrkiH78zVd3dw8iKcv4X2TPE/qpmprU6muy62VbxpH4yS9mdxm0yjJsumIYM/urjamBYwTBpeLQmpvMSW43/pKWZQE74wxKL1t0BOUKsQL7eZyJ7lARZAwgrnxr0pwLAz3ymDZhlk7PJRzt9BcfOKeQIbq2ba/mCCOwghAv2GfH1fLPMCKnywi4Ef09ZageWFQVB9D@iQ2bsAnmBmv3Qn3W@X4clCKz0Bkr/B/hwepOYqL49HB4@/OuJc82Q4eZSsD5ayyDnn4ga5b1csaJjzl3fVOfQE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two strings of 4 characters e.g. `QcKc` `6d4d` and outputs a signed integer. Explanation:
```
≔”)¶&sNψU↓”ζ
```
Compressed string `2345678903889` represents the card values.
```
F¹³F¹³
```
Loop over each possible pair of values.
```
F⁻⁴⁼ικ
```
Loop over each possible second card suit. Without loss of generality we can assume that the first card has suit 3, so the second card suit can range from 0 to 3 unless the values are the same in which case it can only range from 0 to 2.
```
⊞υ⁺÷λ³⊗﹪Π⁺§ζι§ζκχ
```
Compute the modified score of the hand, which is the value of the hand doubled, plus 1 if the suits are the same (i.e. the second card has suit 3).
```
≔”A↘τ[⁵PkxτG”ε
```
Compressed string `23456789TJQKA` represents the card characters. The input cards are looked up in this string and then the position is used to index into the first string to get the card's value.
```
≔⁰δ
```
Initialise the result to 0.
```
F⟦θη⟧
```
Loop over the two hands.
```
≦⁻№υ⁺⁼§ι¹§ι³⊗﹪Π⁺§ζ⌕ε§ι⁰§ζ⌕ε§ι²χδ
```
Calculate the modified score of the hand, and thus its frequency, and subtract the result from this.
```
Iδ
```
Output the frequency difference.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 139 bytes
```
x=>x.Sum(n=>(i++%2*2-1)*(n[1]==n[3]?"":"
")[n.Aggregate(1,(a,b)=>a*(b>85?1:b>83?0:b>74?8:b>73?3:b>64?9:b-48))%10]);int i
```
[Try it online!](https://tio.run/##jZJba9swGIbvfbPz1u4oBAUpdUpt2Ymd1DaGbTD7pmW5C2EoshIZWg38OUvH6G/PZHvQOe0OV5/Qw/vy6CBgKKDcfdxocfbpg95cyYovL@UZ1FWp17Fd6jpeRbvrKL4@@by5IjqKSXl8fOQO3KFDB0TPnUUU6TlbJPjVo8OHh09ePH7@AE8wOnj79N3LNwevn2E61yfpel3JNa8lcWzC7SWNYj4gyzjwE2diBktOzRh7SdAMljAzRl4STpZDL6D0yDld0KmRQeVuan3jFaol1F8EBwkOipCW2/nih4V@LXAGDLCNcA65wjf2LRirUDUghLEwAN2SVPltZAYB9Em7Y0im3D3iqY5cqNwQ62Zfzb1HbaaCosmMIC96apnwRQMYhLAHsjYRqrR/GLfwWsAU6yd84XVVwhX3eRV/uTJWZH2vVKVdWbHndSHyFowajb4X67zA7SdmELYJT/lF52Wdm39WE3x@yb/LCjloW2qYYDq1Vl8ryYUirTkq9e8vTk1lF1yRmtI7Ne5/1bh/rHlf8e2/0sWd9O4n "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 107 bytes
```
$a=A;y/ATJQK/90388/;${$a++}=substr"IAG6HCFAE7D3B2B59481",($1eq$3).$&*$2%10,1while/.(.) (.)(.)/g;$_=$A cmp$B
```
[Try it online!](https://tio.run/##JcjLCoJAGEDhvU8xyF9oXsZxshRxMXYfaRG0D1NJwdIcIyJ69SYhON/mtEVXe1JCGrHwhdmRHxIcONT3cQhvSA3jE4nHWfSdumOb2XaxZqv5ksZu7AVTn6imBqS4A9VtGE/AHRHHJM@yqgtsa7aOBkP4EsIpAoayawuxlFwgKsxEoKRUeIa8zKQCBUL5f5ojnn@btq@am5DW3rMd4kirrX8 "Perl 5 – Try It Online")
### Input:
```
As 4d,Th 8c
```
(Actually, the comma can be any character.)
### Output:
```
-1 Player one wins
0 Draw
1 Player two wins
```
] |
[Question]
[
J. E. Maxfield proved following theorem (see [DOI: 10.2307/2688966](http://www.jstor.org/stable/2688966)):
>
> If \$A\$ is any positive integer having \$m\$ digits, there exists a positive integer \$N\$ such that the first \$m\$ digits of \$N!\$ constitute the integer \$A\$.
>
>
>
### Challenge
Your challenge is given some \$A \geqslant 1\$ find a corresponding \$N \geqslant 1\$.
### Details
* \$N!\$ represents the factorial \$N! = 1\cdot 2 \cdot 3\cdot \ldots \cdot N\$ of \$N\$.
* The digits of \$A\$ in our case are understood to be in base \$10\$.
* Your submission should work for arbitrary \$A\geqslant 1\$ given enough time and memory. Just using e.g. 32-bit types to represent integers is not sufficient.
* You don't necessarily need to output the *least* possible \$N\$.
### Examples
```
A N
1 1
2 2
3 9
4 8
5 7
6 3
7 6
9 96
12 5
16 89
17 69
18 76
19 63
24 4
72 6
841 12745
206591378 314
```
The least possible \$N\$ for each \$A\$ can be found in <https://oeis.org/A076219>
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
```
f=lambda a,n=2,p=1:(`p`.find(a)and f(a,n+1,p*n))+1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVEnz9ZIp8DW0EojoSBBLy0zL0UjUTMxL0UhTQMop22oU6CVp6mpbfi/oCgzrwQoqm6orsmF4Jih8MxReBYoPEt1zf8gMQA "Python 2 – Try It Online")
This is a variation of the 47-byte solution explained below, adjusted to return `1` for input `'1'`. (Namely, we add `1` to the full expression rather than the recursive call, and start counting from `n==2` to remove one layer of depth, balancing the result out for all non-`'1'` inputs.)
## [Python 2](https://docs.python.org/2/), 45 bytes (maps 1 to `True`)
```
f=lambda a,n=2,p=1:`-a`in`-p`or-~f(a,n+1,p*n)
```
This is another variation, by @Jo King and @xnor, which takes input as a number and returns `True` for input `1`. [Some people think](https://codegolf.meta.stackexchange.com/a/9067/3852) this is fair game, but I personally find it a little weird.
But it costs only 3 bytes to wrap the icky Boolean result in `+()`, giving us a shorter "nice" solution:
## [Python 2](https://docs.python.org/2/), 48 bytes
```
f=lambda a,n=2,p=1:+(`-a`in`-p`)or-~f(a,n+1,p*n)
```
>
> This is my previous solution, which returns `0` for input `'1'`. It would have been valid if the question concerned a *non-negative `N`*.
>
>
> ## [Python 2](https://docs.python.org/2/), 47 bytes (invalid)
>
>
>
> ```
> f=lambda a,n=1,p=1:`p`.find(a)and-~f(a,n+1,p*n)
>
> ```
>
> [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVEnz9ZQp8DW0CqhIEEvLTMvRSNRMzEvRbcuTQMopw2U08rT/F9QlJlXopCmoW5opq7JheCZo/AsUHiW6pr/QWIA "Python 2 – Try It Online")
>
>
> Takes a string as input, like `f('18')`.
>
>
> The trick here is that `x.find(y) == 0` precisely when `x.startswith(y)`.
>
>
> The `and`-expression will short circuit at ``p`.find(a)` with result `0` as soon as ``p`` starts with `a`; otherwise, it will evaluate to `-~f(a,n+1,p*n)`, id est `1 + f(a,n+1,p*n)`.
>
>
> The end result is `1 + (1 + (1 + (... + 0)))`, `n` layers deep, so `n`.
>
>
>
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~3~~ 5 bytes
```
ℕ₁ḟa₀
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/eobcOjpqaHuzprH26d8P9Ry9RHTY0Pd8xPfNTU8P9/tKGOkY6xjomOqY6ZjrmOpY6hkY6hmY6huY6hhY6hpY6RiY65kY6FCVCZgZmppaGxuUUsAA "Brachylog – Try It Online")
Takes input through its output variable, and outputs through its input variable. (The other way around, it just finds arbitrary prefixes of the input's factorial, which isn't quite as interesting.) Times out on the second-to-last test case on TIO, but [does fine on the last one](https://tio.run/##SypKTM6ozMlPN/r//@GO@YmPmhr@/4/6b2RgZmppaGxuAQA). I've been running it on 841 on my laptop for several minutes at the time of writing this, and it hasn't actually spit out an answer yet, but I have faith in it.
```
The (implicit) output variable
a₀ is a prefix of
ḟ the factorial of
the (implicit) input variable
ℕ₁ which is a positive integer.
```
Since the only input `ḟa₀` doesn't work for is 1, and 1 is a positive prefix of 1! = 1, `1|ḟa₀` works just as well.
Also, as of this edit, 841 has been running for nearly three hours and it still hasn't produced an output. I guess computing the factorial of every integer from 1 to 12745 isn't exactly fast.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~107~~ 95 bytes, using `-lgmp` and `-lgmpxx`
Thanks to the people in the comments for pointing out some silly mishaps.
```
#import<gmpxx.h>
auto f(auto A){mpz_class n,x=1,z;for(;z!=A;)for(z=x*=++n;z>A;z/=10);return n;}
```
[Try it online!](https://tio.run/##LY7bioMwGISvm6fIsjdm1a122ZO/EXySEuJhhZxIIispffWmans1Mwx8M9yYfOQ8xtdJGm19PUqzLO9/DWKz13hIdmnJRZpw5oI5h1W20DILMGibQHihLZDNBrq80TRVEJoWwpGWBQHb@9kqrOC68hUXc9fjetLO257JBqFJeSzZpBKCL@jgfFdVXM8e1/W6fCq@Pn/Lj@8fsuW97FUnAB2e2ALQNd74INjoYi725w@N@f8d "C++ (gcc) – Try It Online")
Computes \$n!\$ by multiplying \$(n-1)!\$ by \$n\$, then repeatedly divides it by \$10\$ until it is no longer greater than the passed integer. At this point, the loop terminates if the factorial equals the passed integer, or proceeds to the next \$n\$ otherwise.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1!w⁼1ʋ1#
```
[Try it online!](https://tio.run/##y0rNyan8/99QsfxR4x7DU92Gyv///zc3AgA "Jelly – Try It Online")
Takes an integer and returns a singleton.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞.Δ!IÅ?
```
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8vXNTFD0Pt9r//29kYGZqaWhsbgEA) or [verify -almost- all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXo/0cd8/TOTVGMONxq/79W53@0oY6RjrGOiY6pjpmOuY6ljqGRjqGZjqG5jqGFjqGljpGJjrmRjpGBmamlobG5RSwA) (`841` times out, so is excluded).
**Explanation:**
```
∞.Δ # Find the first positive integer which is truthy for:
! # Get the factorial of the current integer
IÅ? # And check if it starts with the input
# (after which the result is output implicitly)
```
[Answer]
# Pyth - 8 bytes
```
f!x`.!Tz
f filter. With no second arg, it searches 1.. for first truthy
! logical not, here it checks for zero
x z indexof. z is input as string
` string repr
.!T Factorial of lambda var
```
[Try it online](http://pyth.herokuapp.com/?code=f%21x%60.%21Tz&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9&debug=0).
[Answer]
# JavaScript, ~~47~~ 43 bytes
Output as a BigInt.
```
n=>(g=x=>`${x}`.search(n)?g(x*++i):i)(i=1n)
```
[Try It Online!](https://tio.run/##Rc1LDsIgFADAvafowgXYJ/HRD8WEegiXagLpT5oKTdsYEuPZcelcYEbzNmuz2Hk7Ot92sVfRqZoMKqha7z/hq9namaV5EkcvAwmHNLX0bCmxCh2NjXernzo2@YHcdggcMsihgBIESEAOWAIKwApQAs9BcOCnspCYiWr3YC8zk380m/a6mWUjkqY6UYlOexIoZaO3Tt@dpvEH)
Saved a few bytes by taking Lynn's approach of "building" the factorial rather than calculating it on each iteration so please upvote her solution as well if you're upvoting this one.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 69 + 22 = 91 bytes
```
a=>{var n=a/a;for(var b=n;!(b+"").StartsWith(a+"");b*=++n);return n;}
```
[Try it online!](https://tio.run/##hY1BS8NAEIXv@RVrT7tGU2tpVdbtoYIgqAg99DxZN3GgnYWZSUFKfns0oHizt/fe9x4vymXMnIZOkFqz@RRN@@q12yfGKL6IOxAxb@ZYiIJiNIeM7@YFkKz7Dn/6jx3F@zW2T6SpTXzxJ1dNGCCsjgdgQwGm4JvMdnR1IH9m63IycdVGgVW2qB8WxsDX56EsyXlO2jEZ8v3gf88eMknepWrLqOkZKdnGzpz7l1@f4PNT@6vl4m42v7kde33RD18 "C# (.NET Core) – Try It Online")
Uses `System.Numerics.BigInteger` which requires a `using` statement.
-1 byte thanks to @ExpiredData!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
‘ɼ!³;D®ß⁼Lḣ@¥¥/?
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//4oCYybwhwrM7RMKuw5/igbxM4bijQMKlwqUvP////zIwNjU5MTM3OA "Jelly – Try It Online")
### Explanation
```
‘ɼ | Increment the register (initially 0)
! | Factorial
³; | Prepend the input
D | Convert to decimal digits
⁼ ¥¥/? | If the input diguts are equal to...
Lḣ@ | The same number of diguts from the head of the factorial
® | Return the register
ß | Otherwise run the link again
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes
```
{+([\*](1..*).../^$_/)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlsjOkYrVsNQT09LU09PTz9OJV5fs/Z/cWKlgkq8jrqCrZ2Cuo4eUG1afpECUJWRgfV/AA "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous code block
[\*](1..*) # From the infinite list of factorials
... # Take up to the first element
/^$_/ # That starts with the input
+( ) # And return the length of the sequence
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
⊞υ¹W⌕IΠυθ⊞υLυI⊟υ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1RHwVDTmqs8IzMnVUHDLTMvRcM5sbhEI6AoP6U0uUSjVFNTR6FQU1MBptonNS@9JAMkbs0VUJSZVwJVn18AEtO0/v/f/L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ¹
```
Push `1` to the empty list so that it starts off with a defined product.
```
W⌕IΠυθ
```
Repeat while the input cannot be found at the beginning of the product of the list...
```
⊞υLυ
```
... push the length of the list to itself.
```
I⊟υ
```
Print the last value pushed to the list.
[Answer]
# [Perl 5](https://www.perl.org/) `-Mbigint -p`, 25 bytes
```
1while($.*=++$\)!~/^$_/}{
```
[Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1VDRU/LVltbJUZTsU4/TiVev7b6/3/Lf/kFJZn5ecX/dX2TMtMz80r@6xYAAA "Perl 5 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~28~~ 22 bytes
*-6 bytes thanks to FrownyFrog*
```
(]+1-0{(E.&":!))^:_&1x
```
[Try it online!](https://tio.run/##bdFNC8IwDAbge3/Fqwd1qGPZunUreFH0JB68q6BM/GSgEwV//NRGEYOB9vBQkpd0V9X95ho9iyY6CGCfp@tjMB2PqtasTd3g3hr6jbqted7cLhp0qzwFVypfbQoQelg/70@xhk5DoZnTSGjqVAs1TmOhkdNEaOLUyGnMmeCYA4ciBGejRHR@sxHhuDWl4jXHo@yXNS9D/w39zTHp@7huDwdci9Mey0uJcnvMzygupQXvOjSa46eafvdC7yFBEmcUmRTuk16XUqp6AA "J – Try It Online")
# original answer [J](http://jsoftware.com/), 28 bytes
```
>:@]^:(-.@{.@E.&":!)^:_ x:@1
```
[Try it online!](https://tio.run/##bdHLCsIwEAXQfb7i6sIHaDBt2rQBpSi6EhfuraC0@KSgFQU/vmpGEQcHksUhzFwmu6oumzn6Fk100IN9nq7EaD6dVAObLFLb6srkLpOxbNRtrZ3aJW42UVVbwJXI1psCCn3kz/tTpJ5Tj2ns1GcaOdVMjdOAqe80ZBo6NXwaccw4oMAeC0HZVMg6v9mwcNRaRew1xVPxL2tahv4b@ptjNpS4bg8HXIvTHqtLiXJ7zM4oLqUF7dozmuJHWv3uRb2H9MIgVr6J4D7pdQkhqgc "J – Try It Online")
* `>:@] ... x:@1` starting with an extended precision `1`, keep incrementing it while...
* `-.@` its not the case that...
* `{.@` the first elm is a starting match of...
* `E.&":` all the substring matches (after stringfying both arguments `&":`) of searching for the original input in...
* `!` the factorial of the number we're incrementing
[Answer]
# [C (gcc)](https://gcc.gnu.org/) -lgmp, 161 bytes
```
#include"gmp.h"
f(a,n,_,b)char*a,*b;mpz_t n,_;{for(mpz_init_set_si(n,1),mpz_init_set(_,n);b=mpz_get_str(0,10,_),strstr(b,a)-b;mpz_add_ui(n,n,1),mpz_mul(_,_,n));}
```
[Try it online!](https://tio.run/##VZDRasQgEEXf8xVDSkHDpGzoo/RL2kWMia5g3GBMH7rsr9fOdJfSFYQ7d2YOV23vra31KSQb92lu/bK@nNrGCYMJNY7SnkzuDHajWtYvXYBcdXHnLLgMKRS9zXSDSDhI/G8KjUmq8Y09zzMliwMOB9QSSXM5opH9jWymSe9M@eMseyQEQ6S61pAKLCYkwcJkbxE4GnSkP9@PEi4N0LmFzPO2x4LgjC2q@W3Qi3hwOOJDV97bayauE@3z9pFahMfMQKHvW5Sludb6@m1dNH6rfaQf@wE "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
f=lambda x,a=2,b=1:str(b).find(str(x))==0and a-1or f(x,a+1,b*a)
```
[Try it online!](https://tio.run/##FYpBCoQwDAC/0mOiXbGKrgp5TEopFnZjqRX09VXnMMxh4pXXTfpSPP34bx2rUzN12pJZ9pzAYuODOHj7RCRqWZzij9mS8vC8tdG2YiwxBcng4XWQeGTAh9K14zCb/jvd "Python 3 – Try It Online")
-24 bytes thanks to Jo King
-3 bytes thanks to Chas Brown
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
‘ɼµ®!Dw³’µ¿
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yTew5tPbRO0aX80OZHDTOB7P3///@PNtIx0DHTMdWx1DHUMdYx17GIBQA "Jelly – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 88 bytes
```
import StdEnv,Data.Integer,Text
$a=hd[n\\n<-[a/a..]|startsWith(""<+a)(""<+prod[one..n])]
```
[Try it online!](https://tio.run/##LY3NbsIwEITvfYot4pCIYOIUCFThRg9IPVSiUg8hhy0xYGGvI2cDReqz101/Dp9GMxrN7I1CCtbVnVFgUVPQtnGeYcv1E12SNTKKDbE6Kp@8qg@@G@LqVJe021ExLnGCQlSfLaPn9k3zKRoMihHGv9J4V5eOlBBUxVXY/pRg1b80ELHbstd0BAfDHnb/HzFEpRRiWcFoBKXMEpDznrxn0bNMIJsmkPd5ls5nS/mQL6r4bjKBqzYG1EURd2jMDa7On@HgPCymMoH3jkEzMJ5VC21nI7p/lAUVMsunsxhcozyydtSGr/3B4LEN481zWN8Ird7/mReD3O/ZMD4Fmaap/QY "Clean – Try It Online")
Defines `$ :: Integer -> Integer`.
Uses `Data.Integer`'s arbitrary size integers for IO.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 62 bytes
```
(b=1;While[⌊b!/10^((i=IntegerLength)[b!]-i@#)⌋!=#,b++];b)&
```
[Try it online!](https://tio.run/##DcrBCoIwHAfgV0mEUPzF/M/pFBl4DTp06yAGLsYcpAfZLXqB8il9kdV3/ubRT2YevXuMwaqQaEXtbXJP0@/bR0eM8nuSOHVevLFmvZjF@intdTScXBen@/aNVAydZUOr02O4rm7xB9ZZ1r0IHAUESlSQaEAcVIEkqAY14AKSoxb/lldlQ4Ws3yH8AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->n{a=b=1;a*=b+=1until"%d"%a=~/^#{n}/;b}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE2ydbQOlHLNknb1rA0ryQzR0k1RUk10bZOP065Oq9W3zqp9r@GoZ6ekYGmXm5iQXVNRY1CQWlJsQJQnYKunQJIdXSFTlp0RWxs7X91Qwt1AA "Ruby – Try It Online")
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~65~~ 63 bytes
```
procedure f(a);p:=1;every n:=seq()&1=find(a,p*:=n)&return n;end
```
[Try it online!](https://tio.run/##TY3NDoIwEAbvPMXKgbTmM3HLf0l9EeOBQEk4uGAFjU@Pmnhw7jMzdpNs2xymzvdr8DSoVjezddz4hw8vEuvu/qZ0wm4YpVct5r11opPglzUISeOl//Ov7ShKR/ThFyDraHdmGKTIkKNAiRpswAW4BFfgGiZDaWCORV5zWlYX6id6hnHxShAfThRjUKJ19J29AQ "Icon – Try It Online")
[Answer]
# Haskell, 89 bytes
```
import Data.List
a x=head$filter(isPrefixOf$show x)$((show.product.(\x->[1..x]))<$>[1..])
```
If anyone knows how to bypass the required import, let me know.
] |
[Question]
[
The goal of this code golf is to create an interpreter for the programming language [HQ9+](http://esolangs.org/wiki/HQ9%2B)
There are 4 commands in this programming language:
* **H** - prints "Hello, world!"
* **Q** - prints the source code of the program
* **9** - prints the lyrics of the song ["99 bottles of beer"](http://esolangs.org/wiki/99_bottles_of_beer)
* **+** - increments the accumulator
The rules:
1. Because the accumulator isn't defined, you can ignore the command **+**
2. Your program should prompt for input (this input will be the source code) or the source code is read from a file
3. You are not allowed to put the lyrics of "99 bottles of beer" in a file, and read the text from the file
4. You are not allowed to use a compression algorithm such as GZip or BZip to compress the song text: you have to create your own compression algorithm. This doesn't have to be a complex algorithm, but try to compress the text as much as possible (remember: this is a code-golf, the code with the fewest bytes wins)
5. If the source code contains a char that isn't **H**, **Q**, **9** or **+**, then output "Source code contains invalid characters" **before running any commands!** This means that, if the source code is `H1` for example, then don't output `Hello, world!` before you output `Source code contains invalid characters`. No, immediately output `Source code contains invalid characters`
6. If your interpreter accepts both uppercase and lowercase characters, then you get **-8** to your character count
Good luck!
[Answer]
## APL (Dyalog) (326 - 8 = 318)
Paste it in an editor window and call `H`. Input is taken from the keyboard.
```
H
⎕←'Source code contains invalid characters'/⍨~∧/'HhQq9+'∊⍨V←⍞
B←' of beer'
W←' on the wall'
L←⎕TC[2]
Z←{k←' bottle','s'/⍨⍵≠1⋄⍵<0:'99',k⋄⍵=0:'No',k⋄k,⍨⍕⍵}
{⍵∊'Hh':⎕←'Hello, world!'
⍵∊'Qq':⎕←V
⍵∊'9':{⎕←G,K,(G←Z⍵),B,L,(⊃'Go to the store and buy some more' 'Take one down and pass it around'[1+×⍵]),L,(Z⍵-1),K←B,W,L}¨1-⍨⌽⍳100}¨V
```
[Answer]
# C, 599 587 487 481 467 characters
I'm sure this can be beaten. I'm using C after all. There's a reason you don't see a lot of winning golf entries written in C. This is now 467 characters thanks to criminal abuse of `#define`.
Specify the HQ9+ source file as a command line argument.
EDIT: Now accepts the source from stdin, not a file. Start the program, start typing the code, `CTRL`‑`C` when done to run it.
It compiles at least in MinGW/GCC with: `gcc -o hq9+.exe hq9+.c`
Should work in MSVC, but I didn't feel like creating a whole solution just for this. :)
```
#define B "bottles of beer"
#define C case
#define P printf
#define R break
a,i,j,s;
main(){
char p[9999],c;
for(;;) {
switch(c=getch()){
C 'H':C 'Q':C '9':C '+': C 3: R;
default:P("Source code contains invalid characters\n");
}
if (c==3) R;
p[s++]=c;
}
for(i=0;i<s;i++){
c = p[i];
switch(c){
C 'H':
P("Hello world!");
R;
C 'Q':
for(j=0;j<s;j++)putchar(p[j]);
R;
C '9':
j=99;
while(j){
P("%d "B" on the wall,\n%d "B".\nTake one down, pass it around,\n%d "B".\n",j,j,j-1);
j--;
}
R;
C '+':
a++;
}
}
}
```
Or:
```
#define B "bottles of beer"
#define C case
#define P printf
#define R break
a,i,j,s;main(){char p[9999],c;for(;;){switch(c=getch()){C 'H':C 'Q':C '9':C '+': C 3: R;default:P("Source code contains invalid characters\n");}if (c==3) R;p[s++]=c;}for(i=0;i<s;i++){c = p[i];switch(c){C 'H':P("Hello world!");R;C 'Q':for(j=0;j<s;j++)putchar(p[j]);R;C '9':j=99;while(j){P("%d "B" on the wall,\n%d "B".\nTake one down, pass it around,\n%d "B".\n",j,j,j-1);j--;}R;C '+':a++;}}}
```
[Answer]
# Mathematica, ~~349 346~~ 341 chars
```
h = If[StringMatchQ[#, ("H" | "Q" | "9" | "+") ...],
b = If[# > 0, ToString@#, "No"] <> " bottle" <>
If[# == 1, "", "s"] <> " of beer" &;
w = b@# <> " on the wall" &;
Print /@
StringCases[#, {"H" -> "Hello, world!", "Q" -> #,
"9" -> "" <>
Table[w@n <> ",\n" <> b@n <>
".\ntake one down, pass it around,\n" <> w[n - 1] <>
If[n == 1, ".", ".\n\n"], {n, 99, 1, -1}]}];,
"Source code contains invalid characters"] &
```
[Answer]
# J - 444 bytes
I liked the number, so stopped golfing. Here 'ya go, single expression function!
```
f=:'Source code contains invalid characters'"_`('Hello, world!'"_`[`((((s=:(<:@[s],L,(v,LF,'Take one down and pass it around, '"_,b@<:,' of beer on the wall.'"_)@[,''"_)`(],(L=:LF,LF),(v=:1&b,' of beer on the wall, '"_,b,' of beer.'"_)@[)@.([<1:))''"_),LF,'Go to the store and buy some more, '"_,(b=:({&'Nn'@([=0:),'o more'"_)`(":@])@.(]>0:),{.&' bottles'@(8:-=&1@])),' of beer on the wall.'"_)@(99"_))`]@.('HQ9+'&i.@])"0 1 0])@.(*./@e.&'HQ9+')
```
Examples:
```
hq9 '9QHHQ+'
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.
...
3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.
No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
9QHHQ+
Hello, world!
Hello, world!
9QHHQ+
+
hq9 '9QHHaQ'
Source code contains invalid characters
```
[Answer]
# Fortran 528 ~~470~~ ~~481~~
~~It requires compiling with `-fpp` flag (+3 to score)1 to use preprocessing directives (which saves way more than 3 chars, so I'm totally okay with that). It is also case insensitive, so there's -8 :D. *Saved 5 chars by not preprocessing the `endif` as that is used once anyway*.~~
Requires the file to have a `.F90` extension (makes sense to call it `hq9+.F90`) so that the compiler forces preprocessing. The code is case-sensitive; making it case-insensitive adds something like 16 characters, so it's not really worth it to save 8 characters. My previous answer did not account for the changing plurals in `bottles` for `9`; this version corrects it (and sadly adds a lot more characters).
```
#define P print*,
#define W " of beer on the wall"
#define N print'(x,i0,a,a)',
#define e enddo
#define S case
#define J len(trim(c))
character(len=99)::c,b=" bottles";read*,c;do i=1,J;if(all(c(i:i)/=["H","Q",'9',"+"])) then;P"Source code contains invalid characters";exit;endif;e;do i=1,J;select S(c(i:i));S("H");P"Hello, world!";S("Q");P c;S("9");l=8;do k=99,1,-1;N k,b(1:l),W;N k,b(1:l)," of beer";P "Take one down, pass it around";if(k==2)l=l-1;if(k==1)exit;N k-1,b(1:l),W;P"";e;P"No more",trim(b),W;S default;endselect;e;end
```
Looks a lot better ungolfed & non-preprocessed (probably because you can see what's going on):
```
program hq9
character(len=99)::c,b=" bottles"
read*,c
do i=1,len(trim(c))
! change the below to ["H","h","Q","q","9","+"] to be case-insensitive
if(all(c(i:i)/=["H","Q","9","+"]))then
print*,"Source code contains invalid characters"
exit
endif
enddo
do i=1,len(trim(c))
select case(c(i:i))
case("H") ! change to case("H","h") for case-insensitive
print*,"Hello, world!"
case("Q") ! change to case("Q","q") for case-insensitive
print*, c
case("9")
l=8
do k=99,1,-1
print'(x,i0,a,a)', k,b(1:l)," of beer on the wall"
print'(x,i0,a)', k,b(1:l)," of beer"
print*,"Take one down, pass it around"
if(k==2) l=l-1
if(k==1) exit
print'(x,i0,a)', k-1,b(1:l)," of beer on the wall"
print*,""
enddo
print*,"No more",trim(b)," of beer on the wall"
case default
! do nothing
endselect
enddo
end program hq9
```
[Answer]
# Perl, 325 - 8 = 317
```
sub p{print@_}$_=<>;$a=' on the wall';$b=' bottle';$e=' of beer';$c='Take one down, pass it around';if(!/^[hqHQ9+]+$/){p"Source code contains invalid characters";exit}$k=$_;for(/./g){/H|h/&&p"Hello, World!";if(/9/){$i=99;$d=$b."s$e";while($i>0){p"$i$d$a
$i$d
$c
";$q=--$i==1?'':'s';$d="$b$q$e";$i||=No;p"$i$d$a
"}}/Q|q/&&p$k}
```
Expanded:
```
sub p{print@_}
$_=<>;
$a=' on the wall';
$b=' bottle';
$e=' of beer';
$c='Take one down, pass it around';
if(!/^[hqHQ9+]+$/){
p"Source code contains invalid characters";
exit
}
$k=$_;
for(/./g){
/H|h/&&p"Hello, World!";
if(/9/){
$i=99;
$d=$b."s$e";
while($i>0){
p"$i$d$a
$i$d
$c
";
$q=--$i==1?'':'s';
$d="$b$q$e";
$i||=No;
p"$i$d$a
"
}
}
/Q|q/&&p$k
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~452~~ ~~453~~ 443 bytes
```
q=raw_input()
if set(q)-set('HQ9+'):print'Source code contains invalid characters'
b=' bottles of beer'
b=[b,b.replace('s','')]
w=[a+' on the wall'for a in b]
t='Take one down, pass it around,\n'
c={'H':'Hello, world!','Q':q,'9':''.join(`i`+w[i<2]+',\n'+`i`+b[i<2]+'.\n'+t+(`i`if i>1 else'No')+w[0]+'.\n'for i in range(1,100)[::-1])+'No'+w[0]+',\nNo'+b[0]+'.\n'+'Go to the store, buy some more,\n99'+w[0]+'.'}
for d in q:
if d in c:print c[d]
```
[Try it online!](https://tio.run/##PVHBTsMwDL33K8zJrdpN626rKFd2Qprg1lUsaT0WyOIuSakmxLePZAwucfz83rMTD2d/YLO8XE61FdOrMsPo0yxRe3Dk01M2iwHXm1WOWTVYZTw@82g7go77eBgvlHGgzKfQqofuIKzoPFmHiawRJHuvyQHvQRLZCDaykHNLgxYdpeiwQMzaZKobkSOwAX8gmITWuGcLIjiDbBNf44v4oFAn6HkyBQzChbYehOXR9MXWYNLVX7jGCtekNRcwsdX9XfDfYHUqcBUqOH9nZdKd2uVTo@6XbY5RmUdA3oB5BHweSeEb1EMJpB3hE2MWRIsbIw6n4nBWmDdKy6JcLLKmqmZlm@WRfOMG@5jIf2GOjwyer890ni0VIMczOD4SHGO6NavVn3qO30ns1MdOpyqBMNH13v0uA7qmby@XuJ/1Dw "Python 2 – Try It Online")
Bleh. It was already bleh, but then I discovered a bug that cost me a byte to fix. Bleh.
Saved some characters by not exiting on invalid input like I thought you were supposed to.
~~Explained version coming shortly.~~ I gave up. I barely even understand how this monstrosity works any more. If there's demand I'll give it another go but until then it's not happening.
[Answer]
# Ruby, ~~364~~ 360 - 8 = 352
Still has *lots* of room for improvement. 99 bottles code stolen from [here](http://www.99-bottles-of-beer.net/language-ruby-673.html).
```
p=gets.upcase
if p=~/[^HQ9+
]/
puts"Source code contains invalid characters"else
p.each_char{|x|case x
when ?H
puts"Hello, world!"
when ?Q
puts p
when ?9
def c;"#{$n} bottle#{'s'if$n>1} of beer on the wall"end
($n=99).times{puts"#{c}, #{c[0..-13]}.
#{$n<2?"Go to the store and buy some more":"Take one down and pass it around"}, #{$n=($n-2)%99+1;c}.
"}end}end
```
[Answer]
# Haskell, 298
```
main=interact g
g s|all(`elem`"HQ9+")s=s>>=(%s)|0<1="Source code contains invalid characters"
'H'%_="hello World!"
'Q'%s=s
'9'%_=drop 32$d 99
_%_=""
k=" bottles of beer on the wall"
d 0="No more"++k++"."
d n|a<-shows n k=[a,".\n\n",a,",\n",take 18a,".\ntake one down, pass it around\n",d$n-1]>>=id
```
this is quite straightforward. `%` returns a command's output (given the source cod for use on `Q`). `d` returns the 99 bottles song with a junk line at the start for golfing reasons.
everything is wrapped in an interact (you might want to use `g` instead of `main` when testing)
[Answer]
# Python 2, 340 - 8 = 332
```
s,o=raw_input(),''
for z in s:
if z in'Hh':o+='Hello World!'
elif z in'Qq':o+=s
elif'9'==z:
i=298
while~-i:print i/3or 99,'bottle'+'s of beer on the wall.\n'[2<i<6:9+i%3*12]+'..\nGToa kteo otnhee dsotwonr,e ,p absusy isto maer omuonrde,,'[(i>3)+i%3*68::2];i-=1
elif'+'!=z:o='Source code contains invalid characters';break
print o
```
[Answer]
## Java, 546 bytes
This is my first code golf submission. I am sure we could do more with it. It reads the input as the command line argument.
Beer code "borrowed" from ["99 Bottles of Beer"](https://codegolf.stackexchange.com/questions/64198/99-bottles-of-beer?rq=1) java answer (creative commons)
```
class a{public static void main(String[] a){if(a[0].matches("^[HQ9\\Q+\\E]+$")){for(char c:a[0].toCharArray()){if(c=='H')p("Hello, world!");if(c=='Q')p(a[0]);if(c=='9')b();}}else{System.out.println("Source code contains invalid characters");}}static void p(String s){System.out.println(s);}static void b(){String b=" of beer",c=" on the wall",n=".\n",s;for(int i=100;i-->1;){s=" bottle"+(i>1?"s":"");p(i+s+b+c+", "+i+s+b+n+(i<2?"Go to the store and buy some more, 99":"Take one down and pass it around, "+(i-1))+" bottle"+(i!=2?"s":"")+b+c+n);}}}
```
Let me know if command line args is not acceptable.
This was a lot of fun!
[Answer]
# Lua 443 - 8 = 435 ~~464 - 8 = 456~~
I managed to save 21 characters by using multiple `if-end`s instead of `if-elseif-end`. I also had some extra white spaces floating around after a few `)`.
```
p=print o=" of beer"t=" on the wall"B=" bottle"b=" bottles"l=io.read("*l");g=l:lower()if g:match"[^hq9+]"then p("Source code contains invalid characters")end for i=1,#g do s=g:sub(i,i)if s=='h'then p("Hello, world")end if s=='q'then p(l)end if s=='9'then n=99 repeat p(n..b..o..t..", "..n..b..o)n=n-1 p("Take one down, pass it around, "..n..b..o..t..".")p()until n==1 p("1"..B..o..t..", 1"..B..o)p("No more"..b..o..t..", no more"..b..o)end end
```
I'm fairly happy with this one, even though it's not much shorter than [my Fortran answer](https://codegolf.stackexchange.com/a/32043/11376). The 99 bottles of beer code has been modified from [this answer by Alessandro](https://codegolf.stackexchange.com/questions/31506/99-bottles-of-beer-99-languages/31816#31816). Ungolfed, we have
```
-- reuse stuff
p=print
o=" of beer"
t=" on the wall"
B=" bottle"
b=" bottles"
-- read the line & then lowercase it for case insensitivity
l=io.read("*l");g=l:lower()
if g:match"[^hq9+]" then -- horray for basic regex
p("Source code contains invalid characters")
end
for i=1,#g do
s=g:sub(i,i) -- take substring
if s=='h' then p("Hello, world") end
if s=='q' then p(l) end
if s=='9' then
n=99
repeat
p(n..b..o..t..", "..n..b..o)
n=n-1
p("Take one down, pass it around, "..n..b..o..t..".")
p()
until n==1
p("1"..B..o..t..", 1"..B..o)
p("No more"..b..o..t..", no more"..b..o)
end
end
```
[Answer]
# Julia, 362
```
s = chomp(readline(STDIN))
l=""
z=" of beer"
q,r,w,t=" bottles$z"," bottle$z"," on the wall.\n","take one down, pass it around,\n"
for j=99:-1:2
b="$j$q"
l*="$b$w$b.\n$t"
end
l*="1$r$(w)1$r.\n$(t)No$q$w"
p=println
all(c->c in "HQ9+", s)||p("Source code contains invalid characters")
for c in s
c=='Q'&&p(s)
c=='H'&&p("Hello, world!")
c=='9'&&p(l)
end
```
[Answer]
# Tcl, 515
```
set d [read stdin]
if {![regexp {^[hq9\+HQ]*$} $d]} {puts "Source code contains invalid characters"}
lmap c [split $d {}] {set b { bottles of beer}
switch -- $c H {puts "Hello, world"} Q {puts $d} 9 {for {set i 99} {$i>2} {incr i -1} {puts "$i$b on the wall,
$i$b.
Take one down, pass it around,
[expr $i-1]$b on the wall.
"}
puts "2$b on the wall,
2$b.
Take one down, pass it around,
1 bottle of beer on the wall.
1 bottle of beer on the wall,
1 bottle of beer.
Take one down, pass it around,
No$b on the wall."}}
```
Just a bit golfed, still smaller than C and the correct 99 Bottles of beer end verse.
[Answer]
## JavaScript (ES6), 385
```
s=>{n=99,b=' bottle',j=' of beer',d=' on the wall',e='Take one down, pass it around',k='Go to the store, buy some more',l='No',o='s',f=', ';for(i=s.split(m=v='');~n;)v+=[n||l,b,n-1?o:m,j,d,f,n||l,b,n-1?o:m,j,f,n?e:k,f,--n<1?99:n,b,n-1?o:m,j,d,'! '].join(m);return s.match(/[^HQ9\+]/,r='')?'Source code contains invalid characters':[...s].map(c=>({H:'Hello World!',9:v,Q:s})[c]).join``}
```
Didn't opt for the case-insensitive, would have cost too many characters. Not even close to some of the other entries, but was fun nonetheless!
## JavaScript, 344
I made a version with a less complete version of the song:
```
(function(i){if(s.match(/[^HQ9\+]/)){m='Source code contains invalid characters'}else{n=99,b=' bottles of beer ',d='on the wall',e='take one down, pass it around',f=', ';for(;n;)v+=[n,b,d,f,n,b,f,e,f,--n||'no more',b,d,'! '].join(m);h={H:'Hello World!',Q:arguments.callee+m,9:v};for(;c=i[n++];)m+=h[c]||''}alert(m)})((s=prompt()).split(m=v=''))
```
but after seeing the other entries (and looking at the actual lyrics, who knew!), I thought it was a bit of a cop out!
[Answer]
# C, 562 bytes
```
char*c="%1d %3$s of %4$s on the %5$s, %1d %3$s of %4$s.\n\0Take one down and pass it around, %2d %3$s of %4$s on the %5$s.\n\0Go to the store and buy some more, %1d %3$s of %4$s on the %5$s.\n";main(int a,char**b){int x=0;for(int i=0;i<strlen(b[1]);i++){if(b[1][i]=='+')x++;else if(b[1][i]=='9'){int k=99;while(1){printf(&c[0],k,k,k==1?"bottle":"bottles","beer","wall");if(k!=1){printf(&c[49],k,k,"bottles","beer","wall");k--;}else{k=99;printf(&c[114],k,k,"bottles","beer","wall");break;}}}else printf("%s",b[1][i]=='H'?"Hello, world!":(b[1][i]=='Q'?b[1]:""));}}
```
As a full program. First argument is the HQ9+ program. With an actual accumulator. I challanged myself not to use define statements.
Ungolfed version:
```
char* c = "%1d %3$s of %4$s on the %5$s, %1d %3$s of %4$s.\n\0Take one down and pass it around, %2d %3$s of %4$s on the %5$s.\n\0Go to the store and buy some more, %1d %3$s of %4$s on the %5$s.\n";
main (int a, char** b) {
int x = 0;
for (int i = 0; i < strlen(b[1]); i++) {
if (b[1][i] == '+')
x++;
else if (b[1][i] == '9') {
int k = 99;
while (1) {
printf(&c[0], k, k, k == 1 ? "bottle" : "bottles", "beer", "wall");
if (k != 1) {
printf(&c[49], k, k, "bottles", "beer", "wall");
k--;
} else {
k=99;
printf(&c[114], k, k, "bottles", "beer", "wall");
break;
}
}
} else
printf("%s",b[1][i] == 'H' ? "Hello, world!" : (b[1][i] == 'Q' ? b[1] : ""));
}
}
```
[Answer]
## GNU C, ~~429~~ 423 bytes
Compiles and runs correctly on GCC-8.3, without any compiler flags. No other configuration was tested.
It considers a file to be a stream of text up to the first `'\n'` that it encounters (this just makes testing easier, can be fixed by replacing the `10` in `(c=getchar())!=10` with a `-1`). However, keep in mind that newlines will not be considered valid.
```
char*b="bottles of beer\0on the wall\0Take one down, pass it around",s[4096];n;Q(){puts(s);}W(){puts("Hello, world!");}B(){for(n=100;--n;){printf("%d %s %s,\n%d %s.\n%s,\n%d %s %s.\n\n",n,b,b+16,n,b,b+28,n-1,b,b+16);}}N(){}l=0,c,i,(*t[])()={[43]=N,[57]=B,[72]=W,[81]=Q};main(){while((c=getchar())!=10){if(c!=43&&c!=57&&c!=72&&c!=81){exit(puts("Source code contains invalid characters"));}s[l++]=c;}for(;i<l;++i)t[s[i]]();}
```
## Degolfed
```
// we stick all the strings in a single string, null separated.
// We will later index into the right indices to print the right pieces.
char*b="bottles of beer\0on the wall\0Take one down, pass it around";
// Here we store the source code. I chose 4kiB, but this was rather arbitrary.
char s[4096];
// n is the counter for the B function
n;
Q() { // Q for quine
// puts is shorter than printf and it prints a newline for free
puts(s);
}
W() { // W for world
puts("Hello, world!");
}
B() { // B for bottles
// n is the current count
for (n = 100; --n;) {
printf("%d %s %s,\n" // n bottles of beer on the wall,
"%d %s.\n" // n bottles of beer.
"%s,\n" // Take one down, pass it around,
"%d %s %s.\n\n", // n-1 bottles of beer on the wall
n, b, b + 16, // Index into the right positions
n, b, // in the string.
b + 28, n - 1, b, b + 16);
}
}
N() {} // N for nothing, we need it for the table
// l is the length of source code
// c is the currently read character
// i is an index
l = 0, c, i;
// This array of function pointers is a bit like a jump table.
// This table tells us which function to call depending on the current char.
// It is essentially a hand-rolled switch statement, but shorter.
// NOTE: the [index]=value syntax is a GNU extension
int(*t[])()={
[43/* ASCII + */] = N, // do nothing
[57/* ASCII 9 */] = B, // print 99 bottles
[72/* ASCII H */] = W, // print hello world
[81/* ASCII Q */] = Q // print source
};
main() {
// consume input until we hit \n. this
while ((c = getchar()) != 10) {
// if we find a character not in "HQ9+", we log and exit
if (c != 43 && c != 57 && c != 72 && c != 81) {
exit(puts("Source code contains invalid characters"));
}
// populate the source code
s[l++] = c;
}
// go over the source code (at this point validated)
// and call the function that is set in the table
// We can skip initializing i because it is a static, and statics
// get implicitly initialized to 0. this saves 3 bytes
for (; i < l; ++i)
t[s[i]]();
}
```
I will admit I cheated a bit with the 99 bottles.
[Answer]
# Excel VBA, 489 Bytes
Unindented:
```
Sub h(s)
For c=1 To Len(s)
Select Case Mid(s,c,1)
Case "H"
Debug.? "Hello,World!"
Case "Q"
Set v=ActiveWorkbook.VBProject.VBComponents("M").CodeModule:For n=1 To v.countoflines:Debug.? v.Lines(n,1):Next
Case "+"
a=a+1
Case "9"
s=" Bottles of Beer":o=" Bottle of Beer":w=" on the wall":t=". Take 1 down pass it around,":p=",":d=".":For n=99 To 3 Step -1:Debug.? n;s;w;p;n;s;t;n-1;s;w;d:Next:Debug.? 2;s;w;p;2;s;t;1;o;w;d:Debug.? 1;o;w;p;1;o;t;"No";s;w;d
End Select
Next
End Sub
```
---
(indented for readability)
```
Sub h(s)
For c=1 To Len(s)
Select Case Mid(s,c,1)
Case "H"
Debug.? "Hello,World!"
Case "Q"
Set v=ActiveWorkbook.VBProject.VBComponents("M").CodeModule
For n=1 To v.countoflines
Debug.? v.Lines(n,1)
Next
Case "+"
a=a+1
Case "9"
s=" Bottles of Beer"
o=" Bottle of Beer"
w=" on the wall"
t=". Take 1 down pass it around,"
p=","
d="."
For n=99 To 3 Step -1
Debug.? n;s;w;p;n;s;t;n-1;s;w;d
Next
Debug.? 2;s;w;p;2;s;t;1;o;w;d
Debug.? 1;o;w;p;1;o;t;"No";s;w;d
End Select
Next
End Sub
```
Rename default *Module1* to *M*
call with `h "+++++++++Your Code"`
] |
[Question]
[
The goal of this challenge is to generalise the bitwise XOR function to other bases. Given two non-negative integers \$ x \$ and \$ y \$, and another integer \$ b \$ such that \$ b \geq 2 \$, write a program/function which computes the generalised XOR, described the following algorithm:
1. First, find the base \$ b \$ representation of \$ x \$ and \$ y \$. For example, if \$ b = 30 \$ and \$ x = 2712 \$, then the digits for \$ x \$ would be \$ [3, 0, 12] \$. If \$ y = 403 \$, then the digits for \$ y \$ would be \$ [13, 13] \$.
2. Next, pairwise match each digit in \$ x \$ with its corresponding digit in \$ y \$. Following on from the previous example, for \$ b^0 \$ we have \$ 12 \$ and \$ 13 \$, for \$ b^1 \$ we have \$ 0 \$ and \$ 13 \$, and for \$ b^2 \$ we have \$ 3 \$ and \$ 0 \$.
3. Let \$ p \$ and \$ q \$ be one of the pairs of digits. The corresponding digit in the output will be equal to \$ -(p + q) \bmod b \$, where \$ \bmod \$ is the modulo function in the usual sense (so \$ -1 \bmod 4 = 3 \$). Accordingly, the output digit for \$ b^0 \$ is \$ 5 \$, the next digit is \$ 17 \$, and the final is \$ 27 \$. Combining the output digits and converting that back to an integer, the required output is \$ 5 \cdot 30^0 + 17 \cdot 30^1 + 27 \cdot 30^2 = 24815 \$.
This definition retains many of the familiar properties of XOR, including that \$ x \oplus\_b y = y \oplus\_b x \$ and \$ x \oplus\_b y \oplus\_b x = y \$, and when \$ b = 2 \$ the function behaves identically to the usual bitwise XOR.
This challenge is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. You may not accept/output digit arrays of base \$ b \$, and your code should work in theory for all bases, and not be limited by builtin base conversion which limit your program/function from working for say \$ b > 36 \$. However, assuming that your integer data type width is sufficiently large is fine.
## Test cases
Formatted as `x, y, b => output`
```
2712, 403, 30 => 24815
24815, 2712, 30 => 403
27, 14, 2 => 21
415, 555, 10 => 140
0, 10, 10 => 90
10, 0, 10 => 90
52, 52, 10 => 6
42, 68, 10 => 0
1146, 660, 42 => 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
bUSN%Uḅ
```
[Try it online!](https://tio.run/##y0rNyan8/z8pNNhPNfThjtb/D3euOrzcQfP//2gjc0MjHQUTA2MdBWODWB2FaCMTC0NTHQWIOFTIXEfB0AQoBuKYgGRNTYGEIVjSAMSAcUAsOMcUaAAIQ3gmQJaZBVyhoYkZkG8GVGxiFAsA "Jelly – Try It Online")
-3 byte thanks to Unrelated String
```
bUSN%Uḅ Main link; take [x, y] on the left and b on the right
b Convert x and y to base b
U Upend; reverse each of x and y's digits
S Sum; vectorizes
N Negate
% Modulo with b
U Upend; reverse the digits
ḅ Convert from base b
```
The double reverse is necessary such that the digits line up on the correct side should one digit list be shorter than the other.
Almost all ASCII!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~14~~ ~~13~~ 11 bytes
```
vτR÷+N⁰%Ṙ⁰β
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=v%CF%84R%C3%B7%2BN%E2%81%B0%25%E1%B9%98%E2%81%B0%CE%B2&inputs=%5B2712%2C%20403%5D%0A30&header=&footer=)
Takes `[x, y]` and `b` and outputs the result.
*-1 thanks to the power of vectorisation*
*and -2 thanks to porting Jelly*
## Explained (old)
```
vτR÷Zv∑N⁰%Ṙ⁰β
vτ # Convert x and y to base b
R # reverse each result
÷Z # zip the digits
# to each pair of digits ([p, q]):
v∑N # -(p + q)
⁰% # % b
Ṙ # reverse the result of the above map and
⁰β # convert it from base b to base 10
```
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
f=lambda b,x,y:x+y and-(x+y)%b+f(b,x/b,y/b)*b
```
[Try it online!](https://tio.run/##ZdDRaoMwGAXg@zzFQRhN1n9tYqPrCvZJdmOosoCzYsMwT@/@VL0YCxjid06UZIjh697n89xWXf3tbjUcTRQv0z6i7m9vkhfqxe1byX50FI9Ovbo5oEKWZSJ/NznB6hPhpAFUV@T2bArxnAlLzhEH3OI@wVh2LCP1jbCpWhQ8Gb2qsVro9L7Zwh9aJPqvBf8mPRuzlsIylOc/yPuNLZlL/obNN@SzHB5h9INUh8fQ@SB3n/1OifY@ooPvES4C8ISGD96tlay6Zop5IkSC46T5qTvpkw2j74N83hpFhWrNGkXYUM2/ "Python 2 – Try It Online")
The \$\text{div}\$ and \$\text{mod}\$ operator in Python 2 work much better than JavaScript in this challenge...
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
[#.[|[:-@+/#.inv
```
[Try it online!](https://tio.run/##XY0/C8IwEMV3P8XDDkW0MZdeYg0UBMHJyTWjWKqDbk5@93hpagvC/eP33t094lKVHVqPEhtoeMlK4Xg5n2IoVPgEXx3W20Ldn@@4Wtyu/QuGG7JoUWt0MDsyYF1nSYZJGFxJHrdIFDNsgDgzYi2Qkp3FbK3NfD9hLe2fSRmZ@yFrJDKbLxq4ZmacfhOxg3M6fgE "J – Try It Online")
Just a straight translation of the algorithm:
* `#.inv` Convert to base `b`
* `[:-@+/` Negative of elementwise sum
* `[|` Mod by `b`
* `[#.` Convert back to decimal
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~65~~ ~~47~~ 45 bytes
No bytes added or saved but thanks for a bug fix by [Chris Bouchard](https://codegolf.stackexchange.com/users/45870/chris-bouchard)!!!
```
f(x,y,b){x=x+y?~-b*(x+y)%b+b*f(x/b,y/b,b):0;}
```
[Try it online!](https://tio.run/##bZJtb4IwEMff@ykuJCY8HJGHgjrG9mLZp5hmsVgc2YYLkKzMsI8@dpVi1EjyL6X/@90dbTN3l2V9n5sSW@TWQabSaR9/XW6bNLGm3OE2mTOOLYlbd17S9UXZwOemKE1rcpgAPWqhEXXzKl/WkMIhxGDuBwgBW/gRveYITE08BJ8UkcVIvs/iLrnM0I4ZmBcqUqXxGTFRNMCajxek2LvG@YAzDClOKRioa7HgjBTyS2SN2A5sgLrtoQNf1SdiqRUfWxgLZ2@byqZRZO@iIh5UBmMln4OVXD6RIgPh/Ds0NJnvKzBV9aLcCkmYl@jpPdTFj9jn5tiXNdML9mklAcc5RlswHMH4LyqTPoqjv04u7Ha025s2H21@067JHq/KpSPIOW3jNfpVUUhuGtMtwiBwH9Q4rVcl7Y9EaBE4Qo2nrazTVKx1kW7S9X9Z/rHZ1b37/Q8 "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
f=->x,y,b{x+y<1?0:(-x-y)%b+b*f[x/b,y/b,b]}
```
[Try it online!](https://tio.run/##Zc3NCsIwDAfw83yKgAjqMmy6tJvix4PILj3sLILQIj57TdrhxUNK@f3z8XyFlPN86a4RE4Z3bNOZbua07WKXdpvQhv18j4eASSpMn/yA@W4HsghseoTeTNCswfJIblUy/SHUFkkllMYaDQjEkk2NjlBB1m7n5KHSTGyKG4WKoseKKn/o5JDWor6uFfDjD5dxYi/sZQVbPWbyFw "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~57~~ 53 bytes
```
f=function(x,b)"if"(any(x),-sum(x)%%b+f(x%/%b,b)*b,0)
```
[Try it online!](https://tio.run/##fc/BDsIgDAbgu0/RaEhAMQIDNg/zXWQJyQ5uyXQJPv0sG6jz4AnC97e0wxT6oZ587ceuebR9RwN3bNv6Lb12TxoYP97HG56EuIOngZyIw8DeccFiKW2oKqXioEXBOBSC7QCgvoDSlTSblIh3DjGYM5jAiuwlB6mR1FwNqYNMrGOxMQYDcukfWWqRXMzvH1z8nFmi/2GDwxu1cmSb/0a11a@@W0tt0W1sr1Ve/WsusVpq0ekF "R – Try It Online")
Using [@tsh's recursive approach](https://codegolf.stackexchange.com/a/226617/55372), taking input as `[x, y], b`.
---
Straightforward, taking input as `[x, y], b`:
### [R](https://www.r-project.org/), ~~69~~ ~~65~~ 64 bytes
```
function(x,b,n=b^(0:max(0,log(x,b))))-(x[1]%/%n+x[2]%/%n)%%b%*%n
```
[Try it online!](https://tio.run/##fc/RCsIgFAbg@57iQAiujDymbgXrRUZBGxRBORgFvv06blqti7wSv//8atf7tiv789M1j2vruBe1cGV95HJ3P3kuxa29hMOM1or7Cg9szdzSV2rYZIzVbMFcaOENVzkqAVpuMgEbmc0BoNyD0gWaWUyEvYAQTBlK0ETyXABqIjVMQ2zAyDoMG2MogGN/YNQyuhzOPzj6NjGS/2FDjzdq4sQ23U1qi199V6O25DbUa5W@/vUuOfnUqP0L "R – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 bytes
Basically a translation of [Jonah's J solution](https://codegolf.stackexchange.com/a/226613/43319).
Tacit infix function. Takes \$b\$ as left argument and \$\{x,y\}\$ as right argument.
```
⊣⊥⊣|∘-+/⍤⊤
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HX4kddS4FkzaOOGbra@o96lzzqWvI/7VHbhEe9fY@6mh/1rnnUu@XQeuNHbRMf9U0NDnIGkiEensH/jQ0U0hSMzA2NFEwMjLkgPBMLQ1OwGJcRWFLB0ITLECRjAhQ3NTWFcAwUDA0gLCABZZkaARFUrZGCmQWXCcgEQ0MTMwUzMwMA "APL (Dyalog Extended) – Try It Online")
`⍤⊤` convert \$\{x,y\}\$ to base \$b\$, one digit-value per row, padding with leading zeros if needed, then:
`+/` sum each row
`∘-` negate those sums, then:
`⊣|` find the remainder when dividing by \$b\$
`⊣⊥` evaluate in base \$b\$
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
Last 5 bytes very similar to the [Vyxal answer](https://codegolf.stackexchange.com/a/226610/64121) ;)
```
вí0ζO(¹%R¹β
```
[Try it online!](https://tio.run/##ASkA1v9vc2FiaWX//9Cyw60wzrZPKMK5JVLCuc6y//8zMApbMjcxMiwgNDAzXQ "05AB1E – Try It Online")
```
в # convert [x, y] to base b; this results in a list of two lists of digits
í # reverse each digit list
0ζ # zip with 0 as filler
O # sum each pair of digits
( # negate all sums
¹% # modulo b
R # reverse the resulting base-b digits
¹β # convert from base b
```
[Answer]
# [Red](http://www.red-lang.org), 78 bytes
```
f: func[x y b][either x + y = 0[0][(b * f x / b y / b b)-(x + y % b - b % b)]]
```
[Try it online!](https://tio.run/##LU7RCsIwDHzvV9yLsCnDtmu7IfgTvoY@2K1jvkwpE@bXz7QKyV3uEpKkOO63OJLfpwum9zLQhg@Cp/hY55iw4cT6CknSUxVwxMTeGYHdjKFuqt/MgVXDyVx7XvdM8T7M@O8DCd0pDSNbtFJo0yuL4mTVQRloYdiz1kJJIRkyMxa2GhxcGA3Xl44yDs5JGC28oFd6LGt5Lp/bvw "Red – Try It Online")
My first humble attempt at golfing in Red. This is is the common recursive approach to the problem, but involves a few extra steps in the calculation of the output "digit" because the operators behave quite inconveniently for this task: `%` is remainder, not modulus, while unary minus seems to work only in literals. So, we would need to use verbose function names `negate` and `modulo`, but the shown approach saves a few bytes over that.
[Answer]
# JavaScript (ES6), 44 bytes
* -1 byte by applying a crazy bit-wise expression as suggested by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
```
b=>g=(x,y)=>(s=~-x-~y)&&s*~-b%b+g(x/b,y/b)*b
```
[Try it online!](https://tio.run/##ZZBRb4IwEIDf@yvuZdpqgRYLczHlbb9CSQRFdKlApBrMMv86uw55MGvSy/W77@6SfmW3rN1dTo31qnpf9Afd5zopNe34nemEtvrhdd7jziaTdvbw8rd8XtIuyPk9yNks7y1o2JLwXYYclFhwWAgA0AmEaikj8hc5DHUsYQEt9DlIhRyG43xJlFOjCIMUTyqVIMK9RzbgD0Ec@k8jXOPuiJHGRCGIly8Q@6WKEcc4Q4Uj3Pr2cjpT5reNOVk63VRT5p@zhnY66TCxuyMNNvt5UA745trmN8ZWxPqH@vKZoWAc/CYAprBQX21zdZ90oGYdpgyjSLlZy5ShsaurtjaFb@qSjqYGsza@KarSHj2Z8ucIXPHDVv0v "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Ouch!
```
®ìV ÔÃÕ®xn uVÃÔìV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ruxWINTD1a54biB1VsPU7FY&input=WzI3MTIsNDAzXQozMA)
```
®ìV ÔÃÕ®xn uVÃÔìV :Implicit input of array U=[x,y] and integer V=b
® :Map U
ìV : Convert to base V digit array
Ô : Reverse
à :End map
Õ :Transpose
® :Map
x : Reduce by addition
n : After negating each
uV : Mod V
à :End map
ìV :Convert from base V digit array
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
I↨⮌E↨Σθη﹪±Σ÷θXηκηη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFUjKLUstQhI@yYWQASCS3M1CjV1FDKA2Dc/pTQnX8MvNT2xBCLjmVfiklmWmZKqUaijEJBfnlqkkaGjkK0JBCAtMNL6///oaCNzQyMdBRMD41gdBWOD2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the form `[[x, y], b]`. Explanation:
```
θ List `[x, y]`
Σ Take the sum
↨ η Convert to base `b`
E Map over digits
θ List `[x, y]`
÷ Vectorised integer divide by
η `b`
X Raised to power
κ Current index
Σ Summed
± Negated
﹪ η Reduced modulo `b`
⮌ Reversed
↨ η Convert from base `b`
I Cast to string
Implicitly print
```
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 155 bytes
```
mod X is pr INT . vars B X Y : Nat . op f : Nat Nat Nat -> Nat . eq f(0,0,B)=
0 . eq f(X,Y,B)= B * f(X quo B,Y quo B,B)+((B - 1)*(X + Y))rem B[owise]. endm
```
The answer is obtained by reducing the function `f`, which takes x, y, and b.
### Example Session
```
\||||||||||||||||||/
--- Welcome to Maude ---
/||||||||||||||||||\
Maude 3.1 built: Oct 12 2020 20:12:31
Copyright 1997-2020 SRI International
Tue Jun 1 20:59:00 2021
Maude> mod X is pr INT . vars B X Y : Nat . op f : Nat Nat Nat -> Nat . eq f(0,0,B)=
> 0 . eq f(X,Y,B)= B * f(X quo B,Y quo B,B)+((B - 1)*(X + Y))rem B[owise]. endm
Maude> red f(2712, 403, 30) .
reduce in X : f(2712, 403, 30) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 24815
Maude> red f(24815, 2712, 30) .
reduce in X : f(24815, 2712, 30) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 403
Maude> red f(27, 14, 2) .
reduce in X : f(27, 14, 2) .
rewrites: 46 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 21
Maude> red f(415, 555, 10) .
reduce in X : f(415, 555, 10) .
rewrites: 28 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 140
Maude> red f(0, 10, 10) .
reduce in X : f(0, 10, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 90
Maude> red f(10, 0, 10) .
reduce in X : f(10, 0, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 90
Maude> red f(52, 52, 10) .
reduce in X : f(52, 52, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 6
Maude> red f(42, 68, 10) .
reduce in X : f(42, 68, 10) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0
Maude> red f(1146, 660, 42) .
reduce in X : f(1146, 660, 42) .
rewrites: 19 in 0ms cpu (0ms real) (~ rewrites/second)
result Zero: 0
```
### Ungolfed
```
mod X is
pr INT .
vars B X Y : Nat .
op f : Nat Nat Nat -> Nat .
eq f(0, 0, B) = 0 .
eq f(X, Y, B) =
B * f(X quo B, Y quo B, B)
+ ((B - 1) * (X + Y)) rem B [owise] .
endm
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~29~~ 23 bytes
```
{Y-$+ay&y%b+b*(fa//bb)}
```
Stretching the input format a bit, this submission is function that takes two arguments: a two-element list containing \$x\$ and \$y\$, and an integer \$b\$. [Try it online!](https://tio.run/##RYyxDoJAEER7v2IKNSoh3C67B/ED6KSzMJcruMLExIKWGL79ODB63bw3kxlfY@z6a/w8yn0xTMfpEIpwOT2HqgrhPEe3g3PcEENM7VEbvwlpSbHqrBqQePAGklpV9aBvadbwAzLIoAzlPwnDtnlIYmFtGku69bjd0fUxlu8F "Pip – Try It Online")
### Explanation
Recursive function idea borrowed from [tsh's Python answer](https://codegolf.stackexchange.com/a/226617/16766).
```
{ } A function:
-$+a Negated sum of the first argument (the list of two numbers)
Y Yank that value into y
y& If y is 0 (falsey), return 0; otherwise, return:
y%b Negated sum modulo the second argument (the base)
+ Plus
b* The base, times
(f ) A recursive call
a//b with the two numbers int-divided by the base
b and the same base as before
```
] |
[Question]
[
The leaders of the world have met and have finally admitted that the best (and only) way of resolving global economic woes is to take stock of how much they owe each other and just pay each other off with huge cheques. They have hired you (ironically, at the lowest contract rate possible) to work out the best means of doing so.
After much deliberation, and asking someone to draw a simple example they've come up with the following spec.
Each country is represented by their [ISO 3166-1 alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) code: `US` for the USA, `AU` for Australia, `JP` for Japan, `CN` for China and so on...
1. A ledger is drawn up as a series of country entries and the amounts
owing to each country.
2. Each country's entry starts off with their domain ID a colon, and how much they have in surplus/deficit (in billions of Euro), followed by a semicolon, then a coloned
comma-separated list of the countries and how much (in billions of
Euro) they owe.
3. If a country owes nothing to another country, no mention of that country is entered after that semicolon separator.
4. Deficits are indicated as negative numbers, surplus is indicated as a positive number.
5. Values can also be floats.
6. The ledger must be taken from STDIN. The end of the ledger is indicated by a carriage return on a blank line. The tally must be delivered to STDOUT.
An example of a ledger:
```
Input:
AU:8;US:10,CN:15,JP:3
US:14;AU:12,CN:27,JP:14
CN:12;AU:8,US:17,JP:4
JP:10;AU:6,US:7,CN:10
```
The system then works out how much each country owes and is owed and determines their surplus/deficit, for example, for AU:
AU = 8 (current surplus) -10 (to US) -15 (to CN) -3 (to JP) +12 (from US) +8 (from CN) +6 (from JP) = 6
When all the computing is done, a tally must be shown:
```
Output:
AU:6
US:-5
CN:35
JP:8
```
Your job is to create this system, capable of taking any number of ledger entries for any number of countries and capable of determining how much each country has in deficit/surplus when everything is paid out.
The ultimate test is for you to use your code to resolve the debt owed between the following countries in the test case below. These figures were taken from BBC News as of June 2011. (<http://www.bbc.com/news/business-15748696>)
For the purposes of the exercise, I have used their respective GDP as their current surplus... Please bear in mind that this is strictly an exercise in code quality assurance... there will be no talk of global economic resolution here in this question... If you want to talk economics I'm sure there's another subdomain in SE that handles it...
```
US:10800;FR:440.2,ES:170.5,JP:835.2,DE:414.5,UK:834.5
FR:1800;IT:37.6,JP:79.8,DE:123.5,UK:227,US:202.1
ES:700;PT:19.7,IT:22.3,JP:20,DE:131.7,UK:74.9,US:49.6,FR:112
PT:200;IT:2.9,DE:26.6,UK:18.9,US:3.9,FR:19.1,ES:65.7
IT:1200;JP:32.8,DE:120,UK:54.7,US:34.8,FR:309,ES:29.5
IE:200;JP:15.4,DE:82,UK:104.5,US:39.8,FR:23.8
GR:200;DE:15.9,UK:9.4,US:6.2,FR:41.4,PT:7.5,IT:2.8
JP:4100;DE:42.5,UK:101.8,US:244.8,FR:107.7
DE:2400;UK:141.1,US:174.4,FR:205.8,IT:202.7,JP:108.3
UK:1700;US:578.6,FR:209.9,ES:316.6,IE:113.5,JP:122.7,DE:379.3
```
Now, be the economic savior of the world!
Rules:
1. Shortest code wins... this is code-golf after all...
2. Please provide your output of the major test case with your code answer...
[Answer]
# K, 66
```
{(((!)."SF"$+":"\:'*+a)-+/'d)+/d:"F"$(!).'"S:,"0:/:last'a:";"\:'x}
```
.
```
k)input:0:`:ledg.txt
k){(((!)."SF"$+":"\:'*+a)-+/'d)+/d:"F"$(!).'"S:,"0:/:last'a:";"\:'x} input
US| 9439.3
FR| 2598.9
ES| 852.1
PT| 90.1
IT| 887.5
IE| 48
GR| 116.8
JP| 4817.4
DE| 2903.7
UK| 1546.2
```
[Answer]
# Perl, 139 137 134 119 112
Here's another working piece of code... I will document it later.
**Golfed code**
With dictionary (112):
```
for(<>){~/:(.+);/g;$d{$c=$`}+=$1;$l=$';$d{$1}+=$2,$d{$c}-=$2while$l=~/(..):([^,]+)/g}print"$_:$d{$_}
"for keys%d
```
Without dictionary (137):
```
for($T=$t.=$_ for<>;$t=~/(..:)(.+);(.+)/g;print"$c$s\n"){$c=$1;$l=$3;$s=$2;$s-=$&while$l=~/[\d.]+/g;$s+=$1while$T=~/$c([\d.]+)(?!;|\d)/g}
```
**Output**
```
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2
```
**See it in action!**
<http://ideone.com/4iwyEP>
[Answer]
# Python, 211 185 183
```
import sys,re;t,R,F=sys.stdin.read(),re.findall,float;S=lambda e,s:sum(map(F,R(e,s)))
for m in R('(..:)(.+);(.+)',t):print m[0]+`F(m[1])+S(m[0]+'([\d.]+)(?!;|\d)',t)-S('[\d.]+',m[2])`
```
Output with major test case:
```
US:9439.300000000001
FR:2598.9
ES:852.0999999999999
PT:90.09999999999997
IT:887.5
IE:48.0
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2000000000003
```
(test it here: <http://ideone.com/CjWG7v>)
[Answer]
# C - ~~257~~ 253 if no CR at end of line
Depends on sizeof(short)==2.
No check for buffer overflow.
```
#define C(c) x[*(short*)c]
main(i){double x[23131]={0},d;char*q,b[99],*(*s)()=strtok;for(;gets(b);)for(s(b,":"),C(b)+=atof(s(0,";"));q=s(0,":");C(b)-=d=(atof(s(0,","))),C(q)+=d);for(i=b[2]=0;i<23131;memcpy(b,&i,2),x[i]?printf("%s:%f\n",b,x[i++]):++i);}
```
## Output:
```
DE:2903.700000
IE:48.000000
UK:1546.200000
JP:4817.400000
FR:2598.900000
GR:116.800000
ES:852.100000
US:9439.300000
IT:887.500000
PT:90.100000
```
## Less golfed:
```
#define C(c) x[*(short*)c]
main(i)
{
double x[23131]={0}, d;
char *q, b[99], *(*s)()=strtok;
for(;gets(b);)
for(s(b, ":"),C(b)+=atof(s(0, ";"));
q=s(0, ":");
C(b)-=d=(atof(s(0, ","))), C(q)+=d) ;
for(i=b[2]=0;
i<23131;
memcpy(b, &i, 2), x[i]?printf("%s:%f\n", b, x[i++]):++i) ;
}
```
[Answer]
## PHP - ~~338~~, 280
Should work with any version of PHP 5.
**Golfed**:
```
while(preg_match("#(..):(.+);(.*)#",fgets(STDIN),$m)){$l[$m[1]][0]=(float)$m[2];foreach(explode(",",$m[3])as$x){$_=explode(":",$x);$l[$m[1]][1][$_[0]]=(float)$_[1];}}foreach($l as$c=>$d)foreach($d[1]as$_=>$o){$l[$_][0]+=$o;$l[$c][0]-=$o;}foreach($l as$c=>$d)echo$c,":",$d[0],"\n";
```
**Un-golfed**:
```
<?php
while( preg_match( "#(..):(\d+);(.*)#", fgets( STDIN ), $m ) )
{
$l[$m[1]][0] = (float)$m[2];
foreach( explode( ",", $m[3] ) as $x )
{
$_ = explode( ":", $x );
$l[$m[1]][1][$_[0]] = (float)$_[1];
}
}
foreach( $l as $c => $d )
foreach( $d[1] as $_ => $o )
{
$l[$_][0] += $o;
$l[$c][0] -= $o;
}
foreach( $l as $c => $d )
echo $c, ":", $d[0], "\n";
```
**Output**:
```
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2
```
[Answer]
## perl (184 characters)
**Code**
```
%c,%d,%e=();while(<>){$_=~/(..):(.+);(.*)/;$n=$1;$c{$1}=$2;for $i(split /,/,$3){$i=~/(..):(.+)/;$d{$1}+=$2;$e{$n}+=$2;}}for $i(keys %c){$c{$i}+=$d{$i}-$e{$i};print $i.":".$c{$i}."\n";}
```
**Output**
```
UK:1546.2
DE:2903.7
IT:887.5
FR:2598.9
PT:90.1
US:9439.3
JP:4817.4
ES:852.1
IE:48
GR:116.8
```
[Answer]
# Perl - ~~116~~ ~~114~~ 112
```
for(<>){($n,$m,@l)=split/[:;,]/;$h{$n}+=$m;$h{$n}-=$p,$h{$o}+=$p while($o,$p,@l)=@l}print"$_:$h{$_}\n"for keys%h
```
## Output:
```
GR:116.8
UK:1546.2
DE:2903.7
IE:48
IT:887.5
US:9439.3
PT:90.1
ES:852.1
FR:2598.9
JP:4817.4
```
## Ungolfed:
```
for(<>) {
($n, $m, @l)=split(/[:;,]/);
$h{$n}+=$m;
$h{$n}-=$p, $h{$o}+=$p while ($o,$p,@l)=@l
}
print "$_:$h{$_}\n" for keys%h
```
[Answer]
# C++ - 1254
```
#include<iostream>
#include<cstring>
#include<vector>
#include<sstream>
#include<cstdlib>
using namespace std;int main(){vector<string>input,countries,output;vector<double>results;string last_val;int j,k,i=0;cout<<"Input\n";do{getline(cin,last_val);if(last_val!=""){input.push_back(last_val);countries.push_back(last_val.substr(0,2));}}while(last_val!="");for(j=0;j<countries.size();j++){results.push_back(0);for(k=0;k<input.size();k++)input[k].substr(0, 2)==countries[j]?results[j]+=atof(input[k].substr((input[k].find(countries[j])+3),(input[k].find(',',input[k].find(countries[j]))-input[k].find(countries[j]))).c_str()):results[j]+=atof(input[k].substr((input[k].find(countries[j],3)+3),(input[k].find(',',input[k].find(countries[j]))-input[k].find(countries[j]))).c_str());}for(j=0;j<input.size();j++){for(k=0;k<countries.size();k++){if(input[j].substr(0,2)!=countries[k]){results[j]-=atof(input[j].substr((input[j].find(countries[k])+ 3),(input[j].find(',',input[k].find(countries[k]))-input[j].find(countries[j]))).c_str());}}}for(i=0;i<countries.size();i++){stringstream strstream;strstream<<countries[i]<<":"<<results[i];output.push_back(strstream.str().c_str());}cout<<"Output:\n";for(i=0;i<output.size();i++){cout<<output[i]<<'\n';}return 0;}
```
I realize the code is very long, but enjoyed the good fun. This is my first time code golfing, and I am new to C++, so suggestions for improving my code are much appreciated.
## Final Challenge Results
```
Output:
US:9439.3
FR:2598.9
ES:852.1
PT:90.1
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7
UK:1546.2
```
## Ungolfed Code
```
#include<iostream>
#include<cstring>
#include<vector>
#include<sstream>
#include<cstdlib>
using namespace std;
int main() {
vector<string> input, countries, output;
vector<double> results;
string last_val;
int i, j, k;
cout << "Input\n";
do {
getline(cin, last_val);
if(last_val != "") {
input.push_back(last_val);
countries.push_back(last_val.substr(0, 2));
}
} while(last_val != "");
for(j = 0; j < countries.size(); j++) {
results.push_back(0);
for(k = 0; k < input.size(); k++) {
if(input[k].substr(0, 2) == countries[j]) {
results[j] += atof(input[k].substr((input[k].find(countries[j]) + 3),
(input[k].find(',', input[k].find(countries[j])) -
input[k].find(countries[j]))).c_str());
} else {
results[j] += atof(input[k].substr((input[k].find(countries[j], 3) + 3),
(input[k].find(',', input[k].find(countries[j])) -
input[k].find(countries[j]))).c_str());
}
}
}
for(j = 0; j < input.size(); j++) {
for(k = 0; k < countries.size(); k++) {
if(input[j].substr(0, 2) != countries[k]) {
results[j] -= atof(input[j].substr((input[j].find(countries[k]) + 3),
(input[j].find(',', input[k].find(countries[k])) -
input[j].find(countries[j]))).c_str());
}
}
}
for(i = 0; i < countries.size(); i++) {
stringstream strstream;
strstream << countries[i] << ":" << results[i];
output.push_back(strstream.str().c_str());
}
cout << "Output:\n";
for(i = 0; i < output.size(); i++) {
cout << output[i] << '\n';
}
return 0;
}
```
[Answer]
## AWK - 138 120
```
{l=split($0,h,"[:,;]");t[h[1]]+=h[2];for(i=3;i<l;i+=2){t[h[1]]-=h[i+1];t[h[i]]+=h[i+1]}}END{for(v in t){print v":"t[v]}}
```
And the results
```
$ cat data.withoutInputHeadline |awk -f codegolf.awk
IT:887.5
UK:1546.2
DE:2903.7
PT:90.1
ES:852.1
FR:2598.9
GR:116.8
Input:0
JP:4817.4
IE:48
US:9439.3
```
## Ungolfed
```
{
l=split($0,h,"[:,;]");
t[h[1]]+=h[2];
for(i=3;i<l;i+=2){
t[h[1]]-=h[i+1]
t[h[i]]+=h[i+1]
}
}
END{
for(v in t){
print v":"t[v]
}
}
```
(test it here: <http://ideone.com/pxqc07>)
[Answer]
## Ruby - 225
First try in a challenge like this, sure it could be a lot better...
```
R=Hash.new(0)
def pd(s,o=nil);s.split(':').tap{|c,a|R[c]+=a.to_f;o&&R[o]-=a.to_f};end
STDIN.read.split("\n").each{|l|c,d=l.split(';');pd(c);d.split(',').each{|s|pd(s,c.split(':')[0])}}
puts R.map{|k,v|"#{k}: #{v}"}.join("\n")
```
And the results
```
$ cat data|ruby codegolf.rb
US: 9439.299999999997
FR: 2598.8999999999996
ES: 852.1
JP: 4817.4
DE: 2903.7
UK: 1546.2000000000003
IT: 887.5
PT: 90.09999999999998
IE: 48.0
GR: 116.8
```
[Answer]
# JS, 254 240 245
```
z='replace';r={};p=eval(('[{'+prompt()+'}]')[z](/\n/g,'},{')[z](/;/g,','));for(i in p){l=p[i];c=0;for(k in l){if(!c){c=k;r[c]=0;}else{r[c]-=l[k];}};for(j in p){w=p[j][c];if(w!=null)r[c]+=w}};alert(JSON.stringify(r)[z](/"|{|}/g,'')[z](/,/g,'\n'))
```
Well..I know it is quite long but this is my second code golf.
Suggestions are welcome!
BTW, Interesting Javascript preserves the order of elements in hashmaps,
so, even if p contains an array of dictionaries, I can iterate each dictionary
as an array and I'm sure that the first element of a dict is the first inserted. (the name of the country referred to the current line)
## Ungolfed:
```
z='replace';
r={};
p=eval(('[{'+prompt()+'}]')[z](/\n/g,'},{')[z](/;/g,',')); // make the string JSONable and then evaluate it in a structure
for(i in p){
l=p[i];
c=0;
for(k in l){
if(!c){ // if c is not still defined, this is the country we are parsing.
c=k;
r[c]=0;
}
else r[c]-=l[k];
};
for(j in p){
w=p[j][c];
if(!w) r[c]+=w
}
};
alert(JSON.stringify(r)[z](/"|{|}/g,'')[z](/,/g,'\n')) # Stringify the structure, makes it new-line separated.
```
---
Note: the input is a `prompt()` which should be a single line. But if you copy/paste a multi line text (like the proposed input) in a `prompt()` window then `JS` read it all.
Output:
```
US:9439.3
FR:2598.9
ES:852.1
PT:90.09999999999998
IT:887.5
IE:48
GR:116.8
JP:4817.4
DE:2903.7000000000003
UK:1546.2
```
[Answer]
# JavaScript(ES6) ~~175~~,~~166~~, ~~161~~, ~~156~~, ~~153~~147
**Golfed**
```
R={};prompt().split(/\s/).map(l=>{a=l.split(/[;,:]/);c=b=a[0];a.map(v=>b=!+v?v:(R[b]=(R[b]||0)+ +v c==b?b:R[c]-=+v))});for(x in R)alert(x+':'+R[x])
```
**Ungolfed**
```
R = {};
prompt().split(/\s/).map(l => {
a = l.split(/[;,:]/); // Split them all!!
// Now in a we have big array with Country/Value items
c = b = a[0]; // c - is first country, b - current country
a.map(v =>
b = !+v ? v // If v is country (not a number), simply update b to it's value
: (R[b] = (R[b] ||0) + +v // Safely Add value to current country
c == b ? c : R[c] -= +v) // If current country is not first one, remove debth
)
});
for (x in R) alert(x + ':' + R[x])
```
**Output**
```
US:9439.299999999997
FR:2598.8999999999996
ES:852.1
JP:4817.4
DE:2903.7
UK:1546.2000000000003
IT:887.5
PT:90.09999999999998
IE:48
GR:116.8
```
[Answer]
## Groovy 315
```
def f(i){t=[:];i.eachLine(){l=it.split(/;|,/);s=l[0].split(/:/);if(!z(s[0]))t.put(s[0],0);t.put(s[0],x(z(s[0]))+x(s[1]));(1..<l.size()).each(){n=l[it].split(/:/);t.put(s[0],x(z(s[0]))-x(n[1]));if(!z(n[0]))t.put(n[0],0);t.put(n[0],x(z(n[0]))+x(n[1]))}};t.each(){println it}};def x(j){j.toDouble()};def z(j){t.get(j)}
Output:
US=9439.299999999997
FR=2598.8999999999996
ES=852.1
JP=4817.4
DE=2903.7
UK=1546.2000000000003
IT=887.5
PT=90.09999999999998
IE=48.0
GR=116.8
```
**Ungolfed:**
```
input = """US:10800;FR:440.2,ES:170.5,JP:835.2,DE:414.5,UK:834.5
FR:1800;IT:37.6,JP:79.8,DE:123.5,UK:227,US:202.1
ES:700;PT:19.7,IT:22.3,JP:20,DE:131.7,UK:74.9,US:49.6,FR:112
PT:200;IT:2.9,DE:26.6,UK:18.9,US:3.9,FR:19.1,ES:65.7
IT:1200;JP:32.8,DE:120,UK:54.7,US:34.8,FR:309,ES:29.5
IE:200;JP:15.4,DE:82,UK:104.5,US:39.8,FR:23.8
GR:200;DE:15.9,UK:9.4,US:6.2,FR:41.4,PT:7.5,IT:2.8
JP:4100;DE:42.5,UK:101.8,US:244.8,FR:107.7
DE:2400;UK:141.1,US:174.4,FR:205.8,IT:202.7,JP:108.3
UK:1700;US:578.6,FR:209.9,ES:316.6,IE:113.5,JP:122.7,DE:379.3"""
ungolfed(input)
def ungolfed(i){
def tallyMap = [:]
i.eachLine(){
def lineList = it.split(/;|,/)
def target = lineList[0].split(/:/)
if(!tallyMap.get(target[0])){tallyMap.put(target[0],0)}
tallyMap.put(target[0],tallyMap.get(target[0]).toDouble() + target[1].toDouble())
(1..lineList.size()-1).each(){ e ->
def nextTarget = lineList[e].split(/:/)
//subtract the debt
tallyMap.put(target[0], (tallyMap.get(target[0]).toDouble() - nextTarget[1].toDouble()))
//add the debt
if(!tallyMap.get(nextTarget[0])){ tallyMap.put(nextTarget[0], 0) }
tallyMap.put(nextTarget[0], (tallyMap.get(nextTarget[0]).toDouble() + nextTarget[1].toDouble()))
}
}
tallyMap.each(){
println it
}
}
```
[Answer]
# PHP, 333
```
$a='';while(($l=trim(fgets(STDIN)))!='')$a.=$l.'\n';$a=rtrim($a,'\n');$p=explode('\n',$a);foreach($p as $q){preg_match('/^([A-Z]+)/',$q,$b);preg_match_all('/'.$b[0].':(\d+(?:\.\d+)?)/',$a,$c);$e=ltrim(strstr($q,';'),';');preg_match_all('/([A-Z]+)\:(\d+(?:\.\d+)?)/',$e,$d);echo $b[0].':'.(array_sum($c[1])-array_sum($d[2])).PHP_EOL;}
```
Ungolfed version :
```
$a='';
while(($l=trim(fgets(STDIN)))!='')
$a .= $l.'\n';
$a = rtrim($a,'\n');
$p = explode('\n',$a);
foreach($p as $q){
preg_match('/^([A-Z]+)/',$q,$b);
preg_match_all('/'.$b[0].':(\d+(?:\.\d+)?)/',$a,$c);
$e = ltrim(strstr($q,';'),';');
preg_match_all('/([A-Z]+)\:(\d+(?:\.\d+)?)/', $e, $d);
echo $b[0].':'.(array_sum($c[1])-array_sum($d[2])).PHP_EOL;
}
```
] |
[Question]
[
At the opening scene of the *Dark Knight rises*, there is a rather [awkward dialogue](http://knowyourmeme.com/memes/baneposting) between a CIA agent and the villain Bane.
>
> **CIA agent:** “If I pull that [mask] off, will you die?”
>
>
> **Bane:** “It would be extremely painful…”
>
>
> **CIA agent:** “You’re a big guy.”
>
>
> **Bane:** “…for you.”
>
>
>
It’s unsure if Bane intends to say “painful for you” or “big guy for you”. Let’s settle this problem once for all through code golfing!
## Challenge
Your task is write a program that reorders the above dialogue depending on an integer given as input.
CIA agent dialogue words are:
`If` `I` `pull` `that` `off` `will` `you` `die?` `You're` `a` `big` `guy.`
Bane’s dialogue words are:
`It` `would` `be` `extremely` `painful...` `for` `you!`
Please note that `die?`, `You’re`, `painful...` and `you!` are considered as single words.
1. Given an integer n as input, convert it to binary
2. Reading the binary digits from left to right, output the next word from CIA agent dialogue if the digit is `1`, and the next word from Bane dialogue if the digit is `0`. The words should be separated by a space.
When the speaker changes, add a line feed. Also, prefix each dialogue line with the speaker name (`BANE:` or `CIA:` ).
You can assume that the input always starts with a 1 in binary form, and has 12 ones and 7 zeroes.
## Example
`522300`
1. Converted to binary: `1111111100000111100`
2. The number starts with 8 ones, so we output the 8 first words from CIA’s agent dialogue, and prefix them with CIA:
`CIA: If I pull that off will you die?`
3. Then we got 5 zeroes, so we get the 5 first words from Bane’s dialogue:
`BANE: It would be extremely painful...`
4. Then there are 4 ones, so we output the 4 next CIA words:
`CIA: You’re a big guy.`
5. Then 2 zeroes:
`BANE: for you!`
**Final result:**
```
CIA: If I pull that off will you die?
BANE: It would be extremely painful...
CIA: You’re a big guy.
BANE: for you!
```
## More test cases:
**494542**
```
CIA: If I pull that
BANE: It would be
CIA: off
BANE: extremely
CIA: will you die? You're
BANE: painful... for
CIA: a big guy.
BANE: you!
```
**326711**
```
CIA: If
BANE: It would
CIA: I pull that off will you
BANE: be extremely painful... for
CIA: die? You're
BANE: you!
CIA: a big guy.
```
[Answer]
# Pyth - 138 bytes
I should look into compressing the movie script.
```
K_cc"guy big a You're die? you will off that pull I If you! for painful... extremely be would That"d12jmj;++@c"BANECIA"4ed\:m.)@Kedhdr8jQ2
```
[Test Suite](http://pyth.herokuapp.com/?code=K_cc%22guy+big+a+You%27re+die%3F+you+will+off+that+pull+I+If+you%21+for+painful...+extremely+be+would+That%22d12jmj%3B%2B%2B%40c%22BANECIA%224ed%5C%3Am.%29%40Kedhdr8jQ2&test_suite=1&test_suite_input=522300%0A494542%0A326711&debug=0).
[Answer]
## JavaScript (ES6), ~~203~~ 201 bytes
*Edit: saved 2 bytes by shamelessly borrowing the `trim()` idea from [ETHproductions answer](https://codegolf.stackexchange.com/a/109036/58563)*
```
n=>"If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `.map((_,i,a)=>[`
BANE: `,`
CIA: `,' '][j^(j=n>>18-i&1)?j:2]+a[k[j]++],k=[j=12,0]).join``.trim()
```
### Test cases
```
let f =
n=>"If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `.map((_,i,a)=>[`
BANE: `,`
CIA: `,' '][j^(j=n>>18-i&1)?j:2]+a[k[j]++],k=[j=12,0]).join``.trim()
console.log(f(522300))
console.log(f(494542))
console.log(f(326711))
```
[Answer]
## JavaScript (ES6), ~~209~~ ~~202~~ 201 bytes
```
(n,a="It would be extremely painful... for you! If I pull that off will you die? You're a big guy.".split` `,b=[6,18])=>(F=(s,p=n%2)=>n?F((p^(n>>=1)%2?p?`
CIA: `:`
BANE: `:` `)+a[b[p]--]+s):s.trim())``
```
Old approach:
```
(n,a="If I pull that off will you die? You're a big guy. It would be extremely painful... for you!".split` `,b=[12,0])=>(F=p=>p^n%2?F(n%2)+(p?`
CIA:`:`
BANE:`):n?F(p,n>>=1)+" "+a[b[p]++]:``)(n%2).trim()
```
### Test snippet
```
f=(n,a="It would be extremely painful... for you! If I pull that off will you die? You're a big guy.".split` `,b=[6,18])=>(F=(s,p=n%2)=>n?F((p^(n>>=1)%2?p?`
CIA: `:`
BANE: `:` `)+a[b[p]--]+s):s.trim())``
console.log(f(522300))
console.log(f(494542))
console.log(f(326711))
```
[Answer]
## C++11 (GCC), ~~298~~ 293 bytes
```
#include<sstream>
[](int i){std::stringstream b("It would be extremely painful... for you!"),c("If I pull that off will you die? You're a big guy.");std::string s,w;int n=0,t=i,p;while(t/=2)n++;for(;n>=0;p=t)((t=i>>n&1)?c:b)>>w,s+=p^t?t?"CIA: ":"BANE: ":" ",s+=t^(i>>--n)&1?w+"\n":w;return s;}
```
A lambda function that takes an integer and returns the dialogue as a `std::string`. You can see it in action [here](http://ideone.com/b6uunu).
Ungolfed version (with some explanation):
```
#include<sstream>
[](int i) {
std::stringstream bane("It would be extremely painful... for you!"),
cia("If I pull that off will you die? You're a big guy.");
std::string s, w;
int n = 0, t = i, p;
// Find the position of the most significant bit (n)
while (t/=2) n++;
for (; n>=0; p=t) {
t = i>>n&1; // Current bit
// Append the speaker name if the previous bit was different
if (t != p) s += (t ? "CIA: " : "BANE: ");
else s += " ";
// Read the next word from one of the streams
if (t) cia >> w;
else bane >> w;
s += w;
if (t != ((i>>--n)&1)) // Append a newline if the next bit is different
s += "\n";
}
return s;
}
```
[Answer]
# JavaScript (ES6), ~~252 227~~ 226 bytes
```
n=>[...n.toString(2,b="If I pull that off will you die? You're a big guy.".split` `,c="It would be extremely painful... for you!".split` `)].map((a,i,j)=>(a!=j[i-1]?+a?i?`
CIA: `:`CIA: `:`
BANE: `:``)+(+a?b:c).shift()).join` `
```
# Usage
```
f=n=>[...n.toString(2,b="If I pull that off will you die? You're a big guy.".split` `,c="It would be extremely painful... for you!".split` `)].map((a,i,j)=>(a!=j[i-1]?+a?i?`
CIA: `:`CIA: `:`
BANE: `:``)+(+a?b:c).shift()).join` `
f(522300)
```
# Notes
This is golfing-in-progress, I think I can still shave off some bytes, but feel free to leave suggestions in the comments.
[Answer]
# Python 3.6, 232 bytes
```
from itertools import*
c="you! for painful... extremely be would It".split(),"guy. big a You're die? you will off that pull I If".split()
for n,r in groupby(f'{int(input()):b}',int):
print("BCAINAE::"[n::2],*[c[n].pop()for _ in r])
```
**Edit**, equivalently:
```
from itertools import*
c="It would be extremely painful... for you!".split(),"_ If I pull that off will you die? You're a big guy.".split()
for n,r in groupby(map(int,f'{int(input()):b}')):
print("BCAINAE::"[n::2],*map(c[n].pop,r))
```
[Answer]
# Japt, 121 bytes
```
A=[`It Ùd ¼ extÚ+ pafª... f y!`¸`If I pªl È f Øi y ¹e? Y' a big guy.`¸]¢®^T?["
BANE:""
CIA:"]gT=Z :P +S+AgZ vÃx
```
Contains many unprintables, so you'd just be better off [testing it online](http://ethproductions.github.io/japt/?v=1.4.4&code=QT1bYEl0INkCZCC8IGV4dJzaKyBwYYhmqi4uLiBmjiB5jCFguGBJZiBJIHCqbCDICSCPZiDYaSB5jCC5ZT8gWYwnnCBhIGJpZyBndXkuYLhdoq5eVD9bIgpCQU5FOiIiCkNJQToiXWdUPVogOlAgK1MrQWdaIHbDeA==&input=NTIyMzAw).
[Answer]
# [Perl 6](http://perl6.org/), 211 bytes
```
{.put for map |*,zip map {.[0]X .[1].rotor: .[2..*]},zip <CIA: BANE:>,(<If I pull that off will you die? You're a big guy.>,<It would be extremely painful... for you!>),|(.base(2)~~m:g/(.)$0*/)».chars.rotor(2)}
```
[Answer]
# C#, ~~398~~ ~~390~~ ~~385~~ ~~396~~ 389 bytes
```
class P{static void Main(string[] a){string s="2"+System.Convert.ToString(int.Parse(a[0]),2),e="CIA: ",r="BANE: ",o="";int k=0,l=0,i=1;string[] c="If I pull that off will you die? You're a big guy.".Split(' '),b="It would be extremely painful... for you!".Split(' ');for(;i<s.Length;i++)o+=(s[i-1]==s[i]?" ":(i<2?"":"\n")+(s[i]>'0'?e:r))+(s[i]>'0'?c[k++]:b[l++]);System.Console.Write(o);}}
```
Launch with input number as parameter.
Ungolfed:
```
class P
{
static void Main(string[] a)
{
string s = "2" + System.Convert.ToString(int.Parse(a[0]), 2), e = "CIA: ", r = "BANE: ", o = "";
int k = 0, l = 0, i = 1;
string[] c = "If I pull that off will you die? You're a big guy.".Split(' '), b = "It would be extremely painful... for you!".Split(' ');
for (; i < s.Length; i++)
o += (s[i - 1] == s[i] ? " " : (i<2?"":"\n") + (s[i] > '0' ? e : r))
+ (s[i] > '0' ? c[k++] : b[l++]);
System.Console.Write(o);
}
}
```
Back to 396 bytes because I didn't notice "no newline at the begining" rule.
[Answer]
# Ruby, 204+1 = 205 bytes
Requires the `-n` flag.
```
d=[%w"It would be extremely painful... for you!",%w"If I pull that off will you die? You're a big guy."]
n=%w"BANE CIA"
("%b"%$_).scan(/((.)\2*)/).map{|i,b|puts n[k=b.to_i]+': '+d[k].slice!(0,i.size)*' '}
```
[Answer]
# PHP, 198 bytes
```
while($i++<19)echo($t-$s=1&$argv[1]>>19-$i)?"
"[$i<2].($s?CIA:BANE).": ":" ",explode(0,"It0would0be0extremely0painful...0for0you!0If0I0pull0that0off0will0you0die?0You're0a0big0guy.")[$$s+++7*$t=$s];
```
[Answer]
# Perl, 205 bytes
```
@t=([qw/It would be extremely painful... for you!/],[qw/If I pull that off will you die? You're a big guy./]);$_=sprintf'%b',$0;print$n?'BANE':'CIA',": @{[splice$t[$n=1-$n],0,length$&]}"while s/(.)\1*//;
```
Put that into a file named 494542 and run like this:
```
perl -lX 494542
```
Tested on perl v5.22
[Answer]
## Clojure, 401 bytes
```
(require '[clojure.string :as s])(defn f[n](let[c(map #(-(int %) 48)(Integer/toString n 2))p[(s/split"It would be extremely painful... for you!"#" ")(s/split"If I pull that off will you die? You're a big guy."#" ")]a["BANE" "CIA"]](loop[i[0 0] g"" d c q 2](if(<(count d)1)g(let[b(first d)j(i b)](recur(assoc i b (inc j))(str g(if(= b q)" "(str(when(not= 2 q)"\n")(a b)": "))((p b) j))(rest d) b))))))
```
Invocation:
```
(f 522300)
```
# Ungolfed
```
(require '[clojure.string :as s])
(defn dialogue[num]
(let [dacode (map #(- (int %) 48) (Integer/toString num 2))
phrases [(s/split"It would be extremely painful... for you!"#" ")(s/split"If I pull that off will you die? You're a big guy."#" ")]
actors ["BANE" "CIA"]]
(loop [idxs [0 0] finaldial "" code dacode prevbit 2]
(if (< (count code) 1) finaldial
(let [bit (first code) idx (idxs bit)]
(recur (assoc idxs bit (inc idx)) (str finaldial (if (= bit prevbit) " " (str (when (not= 2 prevbit) "\n") (actors bit) ": ")) ((phrases bit) idx)) (rest code) bit))))))
```
] |
[Question]
[
# Introduction
Some months are **completely symmetric**, meaning they have *central symmetry* as well as *reflection symmetry*, like `February of 2010`:
```
February 2010
┌──┬──┬──┬──┬──┬──┬──┐
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
└──┴──┴──┴──┴──┴──┴──┘
```
Some months have **only** central symmetry, like `February of 1996` or current month, the `April of 2018`:
```
February 1996
┌──┬──┬──┬──┐
│ │ │ │ │
┌──┬──┬──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┴──┴──┘
│ │ │ │ │
└──┴──┴──┴──┘
April 2018 ┌──┐
│ │
┌──┬──┬──┬──┬──┬──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┴──┴──┴──┴──┴──┘
│ │
└──┘
```
And some are **asymmetric**, like the previous month, the `March of 2018`:
```
March 2018
┌──┬──┬──┬──┐
│ │ │ │ │
┌──┬──┬──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┤
│ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┘
│ │ │ │ │ │ │
└──┴──┴──┴──┴──┴──┘
```
# Task
Take an input in form of a **date**, e.g.:
* `2018.04`
* `2018.03`
* `2010.02`
* `1996.02`
Output the corresponding **symmetry**, e.g.
* `2018.04` -> `centrally symmetric`
* `2018.03` -> `asymmetric`
* `2010.02` -> `symmetric`
* `1996.02` -> `centrally symmetric`
# Rules
* This is code golf, so the smallest number of bytes wins.
* Standard loopholes are obviously not allowed.
* Assume that the week starts with [Monday](https://commons.wikimedia.org/wiki/File:First_Day_of_Week_World_Map.svg) (thanks to [Angs](https://codegolf.stackexchange.com/users/60340/angs) and [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for suggestion).
* Consider only years between 1900 and 2100 (**inclusive**).
* The input and output formatting rules are **permissive**, meaning you can use any equivalent format that is native to the language of your choice.
* Base your solution on the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar).
[Answer]
# JavaScript (ES6), 55 bytes
*Saved 6 bytes thanks to @Neil*
Takes input in currying syntax `(year)(month)`. Returns `false` for asymmetric, `true` for centrally symmetric and `0` for completely symmetric.
```
y=>m=>(n=(g=_=>new Date(y,m--,7).getDay())()+g())&&n==7
```
[Try it online!](https://tio.run/##bcixCoMwEADQvV/hJHfUiNpSdbhM/kcJeoYWvYgGJV@flq51evDeZjdbv74Wr8QNHEeKgfRMGoTA0pO08JF0xjOEbFYqqzG37DsTABHwar@kqRDVsXeyuYnzyVkYoSrKBuGOeDn729kXCNXfl237@H38AA "JavaScript (Node.js) – Try It Online")
## How?
We define the function **g()** which returns the weekday of **yyyy/mm/01**, as an integer between **0** = Monday and **6** = Sunday.
```
g = _ => new Date(y, m--, 7).getDay()
```
Because **getDay()** natively returns **0** = Sunday to **6** = Saturday, we shift the result to the expected range by querying for the 7th day instead.
Then we define:
```
n = g() + g()
```
Because the constructor of *Date* expects a 0-indexed month and because **g()** decrements **m** *after* passing it to *Date*, we actually first compute the weekday of the first day of the *next* month and then add that of the current one.
### Completely symmetric months
Completely symmetric months start with a Monday and are followed by a month which also starts with a Monday. This is only possible for February of a non-leap year.
```
- Feb -------------- - Mar --------------
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
-------------------- --------------------
01 02 03 04 05 06 07 01 02 03 04 05 06 07
08 09 10 11 12 13 14 08 09 10 11 12 13 14
15 16 17 18 19 20 21 15 16 17 18 19 20 21
22 23 24 25 26 27 28 22 23 24 25 26 27 28
29 30 31
```
This leads to **n = 0**.
### Centrally symmetric months
Centrally symmetric months are months for which the sum of the weekday of their first day and that of the next month is **7**.
```
- M ---------------- - M+1 --------------
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
-------------------- --------------------
0 1 [2] 3 4 5 6 0 1 2 3 4 [5] 6
-------------------- --------------------
01 02 03 04 05 01 02
06 07 08 09 10 11 12 03 04 05 06 07 07 09
13 14 15 16 17 18 19 ...
20 21 22 23 24 25 26
27 28 29 30 31
```
Hence the second test: **n == 7**.
---
# No built-in, 93 bytes
Uses [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence). Same I/O format as the other version.
```
y=>m=>(n=(g=_=>(Y=y,((m+(m++>2||Y--&&13))*2.6|0)+Y+(Y>>2)-6*~(Y/=100)+(Y>>2))%7)()+g())&&n==7
```
[Try it online!](https://tio.run/##bcjRCoIwFIDh@96jcY5rts3QvDh7j12FmI5Et8gIBOnV16jLhP/i5xuaVzO3j9v9KXy4drGnuJCZyIAncHRJY2k5AEw8xY1eVysEY6pAzHRerhK55WCN0SjK7A32SEom/BHuKwTkDhAZ80RVbIOfw9jlY3DQg5bqjHBC3G15seUSQf@5quvy6/ED "JavaScript (Node.js) – Try It Online")
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 213 bytes (strict I/O rules)
```
SET DATEFIRST 1SELECT CASE WHEN a+b<>8THEN'a'WHEN a=1THEN''ELSE'centrally 'END+'symetric'FROM(SELECT DATEPART(DW,f)a,DATEPART(DW,DATEADD(M,1,f)-1)b FROM (SELECT CONVERT(DATETIME,REPLACE(s,'.','')+'01')f FROM t)y)x
```
The above query considers the strict input/output formatting rules.
The input is taken from the column `s` of a table named `t`:
```
CREATE TABLE t (s CHAR(7))
INSERT INTO t VALUES ('2018.04'),('2018.03'),('2010.02'),('1996.02')
```
Ungolfed:
```
SET DATEFIRST 1
SELECT *, CASE WHEN a+b<>8 THEN 'a' WHEN a=1 AND b=7 THEN '' ELSE 'centrally ' END+'symetric'
FROM (
SELECT *,DATEPART(WEEKDAY,f) a,
DATEPART(WEEKDAY,DATEADD(MONTH,1,f)-1) b
FROM (SELECT *,CONVERT(DATETIME,REPLACE(s,'.','')+'01')f FROM t)y
) x
```
[SQLFiddle 1](http://sqlfiddle.com/#!18/fecbd/1)
# [T-SQL](https://www.microsoft.com/sql-server), 128 bytes (permissive I/O rules)
```
SET DATEFIRST 1SELECT CASE WHEN a+b<>8THEN 1WHEN a=1THEN\END FROM(SELECT DATEPART(DW,d)a,DATEPART(DW,DATEADD(M,1,d)-1)b FROM t)x
```
If the format of the input and of the output can be changed, I would choose to input the first day of the month, in a `datetime` column named `d`:
```
CREATE TABLE t (d DATETIME)
INSERT INTO t VALUES ('20180401'),('20180301'),('20100201'),('19960201')
```
The output would be 1 for asymetric, 0 for symetric, NULL for centrally symetric.
If we can run it on a server (or with a login) configured for BRITISH language, we can remove `SET DATEFIRST 1` saving 15 more bytes.
[SQLFiddle 2](http://sqlfiddle.com/#!18/69377/1)
[Answer]
# Haskell, 170 bytes
```
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
a%b=((\(_,_,a)->a).toWeekDate.fromGregorian a b$1)!gregorianMonthLength a b
1!28=2
4!29=1
7!30=1
3!31=1
_!_=0
```
Returns 2 for centrally symmetric, 1 for symmetric and 0 for asymmetric
[Answer]
# Python 2, ~~118~~ 104 bytes
Thanks to Jonathan Allan and Dead Possum for the improvements!
```
from calendar import*
def f(*d):_=monthcalendar(*d);print all(sum(_,[]))+(_[0].count(0)==_[-1].count(0))
```
---
# Python 3, ~~122~~ 105 bytes
```
from calendar import*
def f(*d):_=monthcalendar(*d);print(all(sum(_,[]))+(_[0].count(0)==_[-1].count(0)))
```
---
### Input
* First is the **year**
* Second is the **month**
---
### Output
* 0 = no symmetry
* 1 = central symmetry
* 2 = complete symmetry
[Answer]
# [Red](http://www.red-lang.org), 199, 168 161 bytes
```
func[d][t: split d"."y: do t/1 m: do t/2 a: to-date[1 m y]b: a + 31
b/day: 1 b: b - 1 if(1 = s: a/weekday)and(7 = e: b/weekday)[return 1]if 8 - e = s[return 2]0]
```
[Try it online!](https://tio.run/##ZczNDoIwEATgO08x6QljgBaMQhNfwmvTQ7FtQlQgUGJ4elzjTzDeJt/O7ODscnJW6cjLxU/tWVmtgsTYX5sAy1I2S9gOIRO4vVMOIxG6xJrgFDFmXUsYbFGIqM6soYkAUY2EQuNjgSNGqmR35y5035jWxgdCR6UvqsGFaWghdONR0tY9Zx/NNddLPzRtgAfLuShTvmPRWoo/4SnPVyKqav8rrz8VWx4 "Red – Try It Online")
0 - asymmetric
1 - symmetric
2 - centrally symmetric
## More readable:
```
f: func[d][ ; Takes the input as a string
t: split d "." ; splits the string at '.'
y: do t/1 ; stores the year in y
m: do t/2 ; stores the month in m
a: to-date[1 m y] ; set date a to the first day of the month
b: a + 31 ; set date b in the next month
b/day: 1 ; and set the day to 1st
b: b - 1 ; find the end day of the month starting on a
s: a/weekday ; find the day of the week of a
e: b/weekday ; find the day of the week of b
if(s = 1) and (e = 7) ; if the month starts at Monday and ends on Sunday
[return 1] ; return 1 fo symmetric
if 8 - e = s ; if the month starts and ends on the same day of the week
[return 2] ; return 2 for centrally symmetric
0 ; else return 0 for assymetric
]
```
[Answer]
# Mathematica, 137 bytes
```
a=#~DateValue~"DayName"&;b=a/@{2}~DateRange~{3};Which[{##}=={0,6},1,+##>5,0,1>0,-1]&@@(Position[b,a@#][[1,1]]~Mod~7&)/@{{##},{#,#2+1,0}}&
```
Pure function. Takes the year and the month as input and returns `-1` for asymmetric months, `0` for centrally symmetric months, and `1` for fully symmetric months. Not sure why this language can't convert from a weekday to a number by default...
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 70
```
date -f- +%u<<<"$1/1+1month-1day
$1/1"|dc -e??sad8*la-55-rla+8-d*64*+p
```
Input is formatted as `YYYY/MM`.
Output is numeric, as follows:
* less than 0: centrally symmetric
* exactly 0: symmetric
* greater than 0: asymmetric
I assume this output format is acceptable for this question.
[Try it online!](https://tio.run/##dVBda8MwDHz3rxDGAyfBJO7aktJk/SnDixUScOwSOw@h7W/P8rHC6JheDunuhE5fyjeTG8J1CJ9WdcijG4G52ho4ZxLKErIoOkNo0K7EUlg1Dqgfuw5D31Z0JdA8PcW/lgpt6JUxI/wxe3zRqhdJ3ZIHqV0PAX3QKiC0FnaZzNNs/4PvC2ZptgN5Oh1nPIN2xGMAIYA9fWSLWzI@rWtELSB5G4qioEymMpGds6ERUquRLAN61xUIvFy80nlslDgcRG9UkgsdH/dxcp0isp08ZxcfwPivfwLbmogS7SxO3w "Bash – Try It Online")
[Answer]
# C, 111 bytes
```
a;g(y,m){y-=a=m<3;return(y/100*21/4+y%100*5/4+(13*m+16*a+8)/5)%7;}f(y,m){a=g(y,m)+g(y,m+1);return(a>0)+(a==7);}
```
Invoke `f(year, month)`, 0 for completely symmetric, 1 for asymmetric, 2 for centrally symmetric.
[Answer]
# [Perl 6](https://perl6.org/), 74 bytes
```
{{{$_==30??2!!$_%7==2}(2*.day-of-week+.days-in-month)}(Date.new("$_-01"))}
```
Bare block, implicitly a function of 1 argument, a string like `"2012-02"`. Returns:
```
2 # Fully symmetric
True # Centrally symmetric
False # Asymmetric
```
When the pattern is symmetric, as .day-of-week increases by 1, .days-in-month would need to move by 2 in order to still match (the month would be starting a day later but need to end a day earlier), so `2 * .day-of-week + .days-in-month` gives us a measure of that gap. Modulo 7 it should be 1 to get symmetry, but we can first cheaply check for the non-leap February by checking that total before modulo (Monday and 28 days per month is the minimum possible combination).
I'm surprised that this takes so many bytes, but fully 36 bytes are needed for just making a date and getting the day of the week and days in that month.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/41600/edit)
This is a challenge of practicing golf optimization in Python -- reusable tricks and shortcuts to shave off a few characters. Many will be familiar to Python golfers and use common ideas from the [Python Tips](https://codegolf.stackexchange.com/q/54/20260). Some of these use Python-specific features that you might not know exist unless you've seen them, so do take a look at the tips if you're stuck.
**Goal:**
There are ten problems, each a reference snippet of Python code for you to optimize and a description of the code does. Your goal is rewrite it to be shorter but still functionally-equivalent.
Your score, which you're trying to minimize, is the total length of your code all the snippets. The length of the reference snippets is 150. Tiebreaker is earliest post.
**Posting answers:** For each problem, post your code and its character count. You can post the reference snippet if you didn't find something shorter. It's intended that you don't look at others' answers when you post yours. Please spoiler-tag each individual problem including the individual character counts. You can leave the total count revealed. Feel free now to unspoiler your solution or post new unspoilered solutions.
**Details on legality:** Functional equivalence means the code can be replaced in a program without affecting its behavior (ignoring things like memory usage and operator precedence as part of an expression). Expressions should produce values that are equivalent by `==`. Note that `1.0==1==True`. Your code should have no side-effects unless otherwise stated. I don't intend the problems to be version-specific, but just in case, you can specify a Python version for each problem.
**Problem 1:** Keep iterating as long as the list `L` has at least 7 elements
```
# 16 chars
while len(L)>=7:
```
**Problem 2**: Check whether two floats `x` and `y` are both positive.
```
# 11 chars
x>0 and y>0
```
**Problem 3**: If Boolean `b` is true, remove the first element of `L`. Otherwise, leave it unchanged.
```
# 12 chars
if b:L=L[1:]
```
**Problem 4**: Check if all elements of a non-empty list `L` of numbers are equal. For this problem, it's OK to modify the list.
```
# 22 chars
all(x==L[0]for x in L)
```
**Problem 5**: Append a number `n` to the end of a list `L` only if `L` already contains that number.
```
# 16 chars
if n in L:L+=[n]
```
**Problem 6**: Express the sign of a float `x`: `+1` for positive, `0` for 0, `-1` for negative.
```
# 20 chars
abs(x)/x if x else 0
```
**Problem 7** Continue a loop as long as the first element of `L`, a list of Booleans, is `True`. Also stop if `L` is empty.
```
# 17 chars
while L and L[0]:
```
**Problem 8**: Continue a loop as long as `n` is greater than 1. The number `n` is guaranteed to be a positive integer.
```
# 10 chars
while n>1:
```
**Problem 9**: Check if an integer represented as a string `s` is negative (i.e, starts with '-').
```
# 9 chars
s[0]=='-'
```
**Problem 10**: Convert a Boolean `b` to `"Win"`/`"Lose"`, with `True`->`"Win"` and `False`->`"Lose"`.
```
# 17 chars
["Lose","Win"][b]
```
---
**Warning:** Spoilers below, don't scroll down if you want to solve these yourself.
If you just want to know the optimal score for a problem:
Problem 1:
>
> 12
>
>
>
Problem 2:
>
> 5
>
>
>
Problem 3:
>
> 7
>
>
>
Problem 4:
>
> 13
>
>
>
Problem 5:
>
> 13
>
>
>
Problem 6:
>
> 8
>
>
>
Problem 7:
>
> 12
>
>
>
Problem 8:
>
> 9
>
>
>
Problem 9:
>
> 5
>
>
>
Problem 10:
>
> 15
>
>
>
[Answer]
# Total: 104 101 99 chars
## Problem 1
>
> 12 chars
>
> `while L[6:]:`
>
>
>
## Problem 2
>
> 5 chars
>
> `x>0<y`
>
>
>
## Problem 3
>
> 7 chars
>
> `L=L[b:]`
>
>
>
## Problem 4
>
> 13 chars
>
> `len(set(L))<2`
>
> `L[1:]==L[:-1]`
>
>
>
## Problem 5
>
> 13 chars
>
> `L+=set(L)&{n}`
>
>
>
## Problem 6
>
> 11 chars
>
> `(x>0)-(x<0)`
>
>
>
> 8 chars (Python 2)
>
> `cmp(x,0)`
>
>
>
## Problem 7
>
> 12 chars
>
> `while[.5]<L:`
>
>
>
## Problem 8
>
> 9 chars
>
> `while~-n:`
>
>
>
## Problem 9
>
> 5 chars
>
> `s<'.'`
>
>
>
## Problem 10
>
> 15 chars
>
> `'LWoisne'[b::2]`
>
>
>
[Answer]
# Total size: ~~128~~ ~~122~~ ~~120~~ ~~117~~ ~~116~~ ~~115~~ ~~111~~ ~~107~~ 104
## Problem 1
Keep iterating as long as the list `L` has at least 7 elements.
>
> 15 chars
>
> `while len(L)>6:`
>
> (Yes, I could save 3 bytes on this, but I accidentally saw the solution Sp3000's answer, so I won't claim those three bytes.)
>
>
>
## Problem 2
Check whether two floats `x` and `y` are both positive.
>
> 5 chars
>
> `x>0<y`
>
>
>
## Problem 3
If Boolean `b` is true, remove the first element of `L`. Otherwise, leave it unchanged.
>
> 7 chars
>
> `L=L[b:]`
>
>
>
## Problem 4
Check if all elements of a non-empty list `L` of numbers are equal. For this problem, it's OK to modify the list.
>
> 13 chars
>
> `L[1:]==L[:-1]`
>
>
>
## Problem 5
Append a number `n` to the end of a list `L` only if `L` already contains that number.
>
> 15 chars
>
> `L+=[n]*(n in L)`
>
> or
>
> `L+=[n][:n in L]`
>
>
>
## Problem 6
Express the sign of a float `x`: `+1` for positive, `0` for 0, `-1` for negative.
>
> 8 chars, **Python 2**
>
> `cmp(x,0)`
>
> According to docs this might return any positive/negative value, but consensus is it always returns -1, 0, 1.
>
>
>
## Problem 7
Continue a loop as long as the first element of `L`, a list of Booleans, is `True`. Also stop if `L` is empty.
>
> 12 chars
>
> `while[1]<=L:`
>
>
>
## Problem 8
Continue a loop as long as `n` is greater than 1. The number `n` is guaranteed to be a positive integer.
>
> 9 chars
>
> `while~-n:`
>
>
>
## Problem 9
Check if an integer represented as a string `s` is negative (i.e, starts with '-').
>
> 5 chars
>
> `s<'.'`
>
>
>
## Problem 10
Convert a Boolean `b` to `"Win"`/`"Lose"`, with `True`->`"Win"` and `False`->`"Lose"`.
>
> 15 chars
>
> `"LWoisne"[b::2]`
>
>
>
[Answer]
# Total: ~~106~~ ~~104~~ 102 chars
## Problem 1
>
> 12 chars
>
> `while L[6:]:`
>
>
>
## Problem 2
>
> 5 chars
>
> `x>0<y`
>
> Huzzah for comparison chaining
>
>
>
## Problem 3
>
> 7 chars
>
> `L=L[b:]`
>
> Good old implicit conversion
>
>
>
## Problem 4
>
> 13
>
> `len(set(L))<2`
>
>
> Alternatively:
>
> `L[1:]==L[:-1]`
>
>
> Stupid way to get the negation of what we want in Python 2:
>
> `","in`set(L)``
>
>
> I'm not sure what the relevance of "it's OK to modify the list" is though, because the best I can think of is 14 chars (and is actually wrong):
>
> `L==[L.pop()]+L`
>
>
>
## Problem 5
>
> 13 chars
>
> `L+={n}&set(L)`
>
> Doing funky things with sets
>
>
>
## Problem 6
>
> 11 chars
>
> `(x>0)-(x<0)`
>
>
>
>
## Problem 7
>
> 12 chars
>
> `while[1]<=L:`
>
> Uses lexicographical order of lists
>
>
>
## Problem 8
>
> 9 chars
>
> `while~-n:`
>
>
>
## Problem 9
>
> 5 chars
>
> `s<"."`
>
> Uses lexicographical ordering of strings
>
>
>
## Problem 10
>
> 15 chars
>
> `"LWoisne"[b::2]`
>
>
> Alternatively:
>
> `b*"Win"or"Lose"`
>
>
>
[Answer]
## Total: 99 bytes
**Problem 1**
>
> *12 bytes*
>
> `while L[6:]:`
>
>
>
**Problem 2**
>
> *5 bytes*
>
> `x>0<y`
>
>
>
**Problem 3**
>
> *7 bytes*
>
> `L=L[b:]`
>
>
>
**Problem 4**
>
> *13 bytes*
>
> `len(set(L))<2`
>
>
>
> *14 byte alternatives*
>
> `min(L)==max(L)`
>
> `set(L)=={L[0]}`
>
>
>
**Problem 5**
>
> *13 bytes*
>
> `L+=set(L)&{n}`
>
>
>
**Problem 6**
>
> *8 bytes*
>
> `cmp(x,0)`
>
>
>
**Problem 7**
>
> *12 bytes*
>
> `while[1]<=L:`
>
>
>
**Problem 8**
>
> *9 bytes*
>
> `while~-n:`
>
>
>
**Problem 9**
>
> *5 bytes*
>
> `s<'.'`
>
>
>
**Problem 10**
>
> *15 bytes*
>
> `b*"Win"or"Lose"`
>
> - or -
>
> `"LWoisne"[b::2]`
>
>
>
[Answer]
>
> 1: 12
>
> `while L[6:]:`
>
> 2: 5
>
> `y>0<x`
>
> 3: 7
>
> `L=L[b:]`
>
> 4: 15
>
> `L==L[:1]*len(L)`
>
> 5: 15
>
> `L+=[n]*(n in L)` or `L+=[n][:n in L]`
>
> 6: 11
>
> This is the only one for which an idiomatic expression did not immediately leap to my mind, but I think I found the right answer. Edit: Nope, it was horrible.
>
> `(x>0)-(x<0)`
>
> 7: 12
>
> `while[1]<=L:`
>
> Or if the program is completed after that, `while L[0]` is nice.
>
> 8: 9
>
> `while~-n:`
>
> 9: 5
>
> Many strings would work here but the "naive method" is funny.
>
> `s<'0'`
>
> 10: 15
>
> `'LWoisne'[b::2]`
>
>
>
>
Total: 106
[Answer]
## Total size: ~~123 121 120~~ 116
**#1**
>
> (12) `while L[6:]:`
>
>
>
**#2**
>
> (10) `min(x,y)>0`
>
>
>
**#3**
>
> (7) `L=L[b:]`
>
>
>
**#4**
>
> (13) `len(set(L))<2` or `L[1:]==L[:-1]`
>
>
>
**#5**
>
> (15) `L+=[n]*(n in L)`
>
>
>
**#6**
>
> (14) `x and abs(x)/x` or (inspired by Claudiu's solution after giving up) `x and(x>0)*2-1`
>
>
>
**#7**
>
> (15) `while[0]<L[:1]:`
>
>
>
**#8**
>
> (9) `while~-n:`
>
>
>
**#9**
>
> (5) `s<'.'`
>
>
>
**#10**
>
> (15) `b*"Win"or"Lose"`
>
>
>
[Answer]
# Total: 121
First attempts:
## Problem 1
>
> 15 chars
>
> `while len(L)>6:`
>
>
>
## Problem 2
>
> 5 chars
>
> `x>0<y`
>
>
>
## Problem 3
>
> 7 chars
>
> `L=L[b:]`
>
>
>
## Problem 4
>
> 13 chars
>
> `len(set(L))<2`
>
>
>
## Problem 5
>
> 16 chars
>
> `if n in L:L+=[n]`
>
>
>
## Problem 6
>
> 16 chars
>
> `x and(1,-1)[x<0]`
>
>
>
## Problem 7
>
> 16 chars
>
> `while(L+[0])[0]:`
>
>
>
## Problem 8
>
> 10 chars
>
> `while n>1:`
>
>
>
## Problem 9
>
> 8 chars
>
> `s[0]<'0'`
>
>
>
## Problem 10
>
> 15 chars
>
> `"LWoisne"[b::2]`
>
>
>
] |
[Question]
[
# The Challenge
A simple "spy versus spy" challenge.
Write a program with the following specifications:
1. The program may be written in any language but must not exceed 512 characters (as represented in a code block on this site).
2. The program must accept 5 signed 32-bit integers as inputs. It can take the form of a function that accepts 5 arguments, a function that accepts a single 5-element array, or a complete program that reads 5 integers from any standard input.
3. The program must output one signed 32-bit integer.
4. The program must return 1 if and only if the five inputs, interpreted as a sequence, match a specific arithmetic sequence of the programmer's choosing, called the "key". The function must return 0 for all other inputs.
An arithmetic sequence has the property that each successive element of the sequence is equal to its predecessor plus some fixed constant `a`.
For example, `25 30 35 40 45` is an arithmetic sequence since each element of the sequence is equal to its predecessor plus 5.
Likewise, `17 10 3 -4 -11` is an arithmetic sequence since each element is equal to its precessor plus -7.
The sequences `1 2 4 8 16` and `3 9 15 6 12` are not arithmetic sequences.
A key may be any arithmetic sequence of your choosing, with the sole restriction that sequences involving integer overflow are not permitted. That is, the sequence *must* be strictly increasing, strictly decreasing, or have all elements equal.
As an example, suppose you choose the key `98021 93880 89739 85598 81457`. Your program must return 1 if the inputs (in sequence) match these five numbers, and 0 otherwise.
**Please note that the means of protecting the key should be of your own novel design. Also, probabilistic solutions that may return false positives with any nonzero probability are not permitted. In particular, please do not use any standard cryptographic hashes, including library functions for standard cryptographic hashes.**
# The Scoring
The shortest non-cracked submission(s) per character count will be declared the winner(s).
If there's any confusion, please feel free to ask or comment.
# The Counter-Challenge
All readers, including those who have submitted their own programs, are encouraged to "crack" submissions. A submission is cracked when its key is posted in the associated comments section. If a submission persists for 72 hours without being modified or cracked, it is considered "safe" and any subsequent success in cracking it will be ignored for sake of the contest.
See "Disclaimer" below for details on the updated cracking score policy.
Cracked submissions are eliminated from contention (provided they are not "safe"). They should not be edited. If a reader wishes to submit a new program, (s)he should do so in a separate answer.
The cracker(s) with the highest score(s) will be declared the winners along with the developers of the winning programs.
*Please do not crack your own submission.*
Best of luck. :)
# Leaderboard
Penultimate standings (pending safety of Dennis' CJam 49 submission).
### Secure Lockers
1. [CJam 49, Dennis](https://codegolf.stackexchange.com/a/36952)
2. [CJam 62, Dennis](https://codegolf.stackexchange.com/a/36874) *safe*
3. [CJam 91, Dennis](https://codegolf.stackexchange.com/a/36790) *safe*
4. [Python 156, Maarten Baert](https://codegolf.stackexchange.com/a/36822) *safe*
5. [Perl 256, chilemagic](https://codegolf.stackexchange.com/a/36825) *safe*
6. [Java 468, Geobits](https://codegolf.stackexchange.com/a/36796) *safe*
### Unstoppable Crackers
1. **Peter Taylor** [Ruby 130, Java 342, Mathematica 146\*, Mathematica 72\*, CJam 37]
2. Dennis [Pyth 13, Python 86\*, Lua 105\*, GolfScript 116, C 239\*]
3. Martin Büttner [Javascript 125, Python 128\*, Ruby 175\*, Ruby 249\*]
4. Tyilo [C 459, Javascript 958\*]
5. freddieknets [Mathematica 67\*]
6. Ilmari Karonen [Python27 182\*]
7. nitrous [C 212\*]
\*non-compliant submission
### Disclaimer (Updated 11:15 PM EST, Aug 26)
With the scoring problems finally reaching critical mass (given two thirds of the cracked submissions are thus far non-compliant), I've ranked the top crackers in terms of number of submissions cracked (primary) and total number of characters in compliant cracked submissions (secondary).
As before, the exact submissions cracked, the length of the submissions, and their compliant/non-compliant status are all marked so that readers may infer their own rankings if they believe the new official rankings are unfair.
My apologies for amending the rules this late in the game.
[Answer]
# CJam, 91 characters
```
q~]KK#bD#"듋ޔ唱୦廽⻎킋뎢凌Ḏ끮冕옷뿹毳슟夫眘藸躦䪕齃噳卤"65533:Bb%"萗縤ᤞ雑燠Ꮖ㈢ꭙ㈶タ敫䙿娲훔쓭벓脿翠❶셭剮쬭玓ୂ쁬䈆﹌⫌稟"Bb=
```
Stack Exchange is prone to mauling unprintable characters, but copying the code from [this paste](http://pastebin.com/ypekEyFR "lock.cjam - Pastebin.com") and pasting it in the [CJam interpreter](http://cjam.aditsu.net/) works fine for me.
### How it works
After replacing the Unicode string with integers (by considering the characters digits of base 65533 numbers), the following code gets executed:
```
" Read the integers from STDIN and collect them in an array. ";
q~]
" Convert it into an integer by considering its elements digits of a base 20**20 number. ";
KK#b
" Elevate it to the 13th power modulus 252 ... 701. ";
D#
25211471039348320335042771975511542429923787152099395215402073753353303876955720415705947365696970054141596580623913538507854517012317194585728620266050701%
" Check if the result is 202 ... 866. ";
20296578126505831855363602947513398780162083699878357763732452715119575942704948999334568239084302792717120612636331880722869443591786121631020625810496866=
```
Since 13 is coprime to the totient of the modulus (the totient is secret, so you'll just have to trust me), different bases will generate different results, i.e., the solution is unique.
Unless someone can exploit the small exponent (13), the most efficient way of breaking this lock is to factorize the modulus (see [RSA problem](http://en.wikipedia.org/wiki/RSA_problem "RSA problem - Wikipedia, the free encyclopedia")). I chose a 512-bit integer for the modulus, which should withstand 72 hours of factorization attempts.
### Example run
```
$ echo $LANG
en_US.UTF-8
$ base64 -d > lock.cjam <<< cX5dS0sjYkQjIgHuiJHhq5bgv7zrk4velOWUse6zjuCtpuW7veK7ju2Ci+uOouWHjOG4ju+Rh+uBruWGleyYt+u/ueavs+6boOyKn+Wkq86i55yY6Je46Lqm5KqV6b2D5Zmz75Wp5Y2kIjY1NTMzOkJiJSIB6JCX57ik4aSe74aS6ZuR54eg4Y+G44ii6q2Z44i244K/5pWr5Jm/5aiy7ZuU7JOt67KT7rO26IS/57+g4p2275+K7IWt5Ymu7Kyt546T4K2C7IGs5IiG77mM4quM56ifIkJiPQ==
$ wc -m lock.cjam
91 lock.cjam
$ cjam lock.cjam < lock.secret; echo
1
$ cjam lock.cjam <<< "1 2 3 4 5"; echo
0
```
[Answer]
# CJam, 62 characters
```
"ḡꬼ쏉壥떨ሤ뭦㪐ꍡ㡩折量ⶌ팭뭲䯬ꀫ郯⛅彨ꄇ벍起ឣ莨ຉᆞ涁呢鲒찜⋙韪鰴ꟓ䘦쥆疭ⶊ凃揭"2G#b129b:c~
```
Stack Exchange is prone to mauling unprintable characters, but copying the code from [this paste](http://pastebin.com/xuuYip2T "block.cjam - Pastebin.com") and pasting it in the [CJam interpreter](http://cjam.aditsu.net/) works fine for me.
### How it works
After replacing the Unicode string with an ASCII string, the following code gets executed:
```
" Push 85, read the integers from STDIN and collect everything in an array. ";
85l~]
" Convert the array of base 4**17 digits into and array of base 2 digits. ";
4H#b2b
" Split into chunks of length 93 and 84. ";
93/~
" Do the following 611 times:
* Rotate array A (93 elements) and B one element to the left.
* B[83] ^= B[14]
* T = B[83]
* B[83] ^= B[0] & B[1] ^ A[23]
* A[92] ^= A[26]
* Rotate T ^ A[92] below the arrays.
* A[92] ^= A[0] & A[1] ^ B[5]. ";
{(X$E=^:T1$2<:&^2$24=^+\(1$26=^_T^@@1$2<:&^3$5=^+@}611*
" Discard the arrays and collects the last 177 generated bits into an array. ";
;;]434>
" Convert the into an integer and check if the result is 922 ... 593. ";
2b9229084211442676863661078230267436345695618217593=
```
This approach uses Bivium-B (see [Algebraic analysis of Trivium-like ciphers](http://eprint.iacr.org/2013/240.pdf)), a weakened version of the stream cipher [Trivium](http://en.wikipedia.org/wiki/Trivium_(cipher) "Trivium (cipher) - Wikipedia, the free encyclopedia").
The program uses the sequence of integers as initial state, updates the state 434 times (354 rounds achieve full diffusion) and generates 177 bit of output, which it compares to those of the correct sequence.
Since the state's size is precisely 177 bits, this *should* suffice to uniquely identify the initial state.
### Example run
```
$ echo $LANG
en_US.UTF-8
$ base64 -d > block.cjam <<< IgThuKHqrLzsj4nlo6XrlqjhiKTrrabjqpDqjaHjoanmipjvpb7itozuoIDtjK3rrbLul7bkr6zqgKvvjafpg6/im4XlvajqhIfrso3uprrotbfvmL/hnqPojqjguonhhp7mtoHujLPuipzlkaLpspLssJzii5npn6rpsLTqn5PkmKbspYbnlq3itorlh4Pmj60iMkcjYjEyOWI6Y34=
$ wc -m block.cjam
62 block.cjam
$ cjam block.cjam < block.secret; echo
1
$ cjam block.cjam <<< "1 2 3 4 5"; echo
0
```
[Answer]
# Python - 128
Let's try this one:
```
i=input()
k=1050809377681880902769L
print'01'[all((i>1,i[0]<i[4],k%i[0]<1,k%i[4]<1,i[4]-i[3]==i[3]-i[2]==i[2]-i[1]==i[1]-i[0]))]
```
(Expects the user to input 5 comma-separated numbers, e.g. `1,2,3,4,5`.)
[Answer]
# Java : 468
Input is given as `k(int[5])`. Bails early if not evenly spaced. Otherwise, it takes a bit figuring out if all ten hashes are correct. For large numbers, "a bit" can mean ten seconds or more, so it might dissuade crackers.
```
//golfed
int k(int[]q){int b=q[1]-q[0],i,x,y,j,h[]=new int[]{280256579,123883276,1771253254,1977914749,449635393,998860524,888446062,1833324980,1391496617,2075731831};for(i=0;i<4;)if(q[i+1]-q[i++]!=b||b<1)return 0;for(i=1;i<6;b=m(b,b/(i++*100),(1<<31)-1));for(i=0;i<5;i++){for(j=1,x=b,y=b/2;j<6;x=m(x,q[i]%100000000,(1<<31)-1),y=m(y,q[i]/(j++*1000),(1<<31)-1));if(x!=h[i*2]||y!=h[i*2+1])return 0;}return 1;}int m(int a,int b,int c){long d=1;for(;b-->0;d=(d*a)%c);return (int)d;}
// line breaks
int k(int[]q){
int b=q[1]-q[0],i,x,y,j,
h[]=new int[]{280256579,123883276,1771253254,1977914749,449635393,
998860524,888446062,1833324980,1391496617,2075731831};
for(i=0;i<4;)
if(q[i+1]-q[i++]!=b||b<1)
return 0;
for(i=1;i<6;b=m(b,b/(i++*100),(1<<31)-1));
for(i=0;i<5;i++){
for(j=1,x=b,y=b/2;j<6;x=m(x,q[i]%100000000,(1<<31)-1),y=m(y,q[i]/(j++*1000),(1<<31)-1));
if(x!=h[i*2]||y!=h[i*2+1])
return 0;
}
return 1;
}
int m(int a,int b,int c){
long d=1;for(;b-->0;d=(d*a)%c);
return (int)d;
}
```
[Answer]
# Java : 342
```
int l(int[]a){String s=""+(a[1]-a[0]);for(int b:a)s+=b;char[]c=new char[11];for(char x:s.toCharArray())c[x<48?10:x-48]++;for(int i=0;i<11;c[i]+=48,c[i]=c[i]>57?57:c[i],i++,s="");for(int b:a)s+=new Long(new String(c))/(double)b;return s.equals("-3083.7767567702776-8563.34366442527211022.4345579010483353.1736981951231977.3560837512646")?1:0;}
```
Here's a string-based locker that depends on both the input character count and the specific input. The sequence *might* be based on obscure pop culture references. Have fun!
A bit ungolfed:
```
int lock(int[]a){
String s=""+(a[1]-a[0]);
for(int b:a)
s+=b;
char[]c=new char[11];
for(char x:s.toCharArray())
c[x<48?10:x-48]++;
for(int i=0;i<11;c[i]+=48,
c[i]=c[i]>57?57:c[i],
i++,
s="");
for(int b:a)
s+=new Long(new String(c))/(double)b;
return s.equals("-3083.7767567702776-8563.34366442527211022.4345579010483353.1736981951231977.3560837512646")?1:0;
}
```
[Answer]
# Python, 147
Edit: shorter version based on Dennis' comment. I updated the sequence too to avoid leaking any information.
```
def a(b):
c=1
for d in b:
c=(c<<32)+d
return pow(7,c,0xf494eca63dcab7b47ac21158799ffcabca8f2c6b3)==0xa3742a4abcb812e0c3664551dd3d6d2207aecb9be
```
Based on the discrete logarithm problem which is believed to be uncrackable, however the prime I'm using is probably too small to be secure (and it may have other issues, I don't know). And you can brute-force it of course, since the only unknowns are two 32-bit integers.
[Answer]
# Javascript 125
This one should be cracked pretty quickly. I'll follow up with something stronger.
```
function unlock(a, b, c, d, e)
{
return (e << a == 15652) && (c >> a == 7826) && (e - b == d) && (d - c - a == b) ? 1 : 0;
}
```
[Answer]
# Ruby, 175
```
a=gets.scan(/\d+/).map(&:to_i)
a.each_cons(2).map{|x,y|x-y}.uniq[1]&&p(0)&&exit
p a[2]*(a[1]^a[2]+3)**7==0x213a81f4518a907c85e9f1b39258723bc70f07388eec6f3274293fa03e4091e1?1:0
```
Unlike using a cryptographic hash or `srand`, this is provably unique (which is a slight clue). Takes five numbers via STDIN, delimited by any non-digit, non-newline character or characters. Outputs to STDOUT.
[Answer]
## GolfScript (116 chars)
Takes input as space-separated integers.
```
~]{2.5??:^(&}%^base 2733?5121107535380437850547394675965451197140470531483%5207278525522834743713290685466222557399=
```
[Answer]
# C 459 bytes
# SOLVED BY Tyilo -- READ EDIT BELOW
```
int c (int* a){
int d[4] = {a[1] - a[0], a[2] - a[1], a[3] - a[2], a[4] - a[3]};
if (d[0] != d[1] || d[0] != d[2] || d[0] != d[3]) return 0;
int b[5] = {a[0], a[1], a[2], a[3], a[4]};
int i, j, k;
for (i = 0; i < 5; i++) {
for (j = 0, k = 2 * i; j < 5; j++, k++) {
k %= i + 1;
b[j] += a[k];
}
}
if (b[0] == 0xC0942 - b[1] &&
b[1] == 0x9785A - b[2] &&
b[2] == 0x6E772 - b[3] &&
b[3] == 0xC0942 - b[4] &&
b[4] == 0xB6508 - b[0]) return 1;
else return 0;
}
```
We need someone to write a C solution, don't we? I'm not impressing anybody with length, I'm no golfer. I hope it's an interesting challenge, though!
I don't think there's an obvious way to crack this one, and I eagerly await all attempts! I know this solution to be unique. Very minimal obfuscation, mostly to meet length requirements. This can be tested simply:
```
int main(){
a[5] = {0, 0, 0, 0, 0} /* your guess */
printf("%d\n", c(a));
return 0;
}
```
P.S. There's a significance to `a[0]` as a number in its own right, and I'd like to see somebody point it out in the comments!
# EDIT:
Solution: `6174, 48216, 90258, 132300, 174342`
A note about cracking:
While this is not the method used (see the comments), I did happen to crack my own cipher with a very easy bruteforce. I understand now it is vitally important to make the numbers large. The following code can crack any cipher where `upper_bound` is a known upper bound for `a[0] + a[1] + a[2] + a[3] + a[4]`. The upper bound in the above cipher is `457464`, which can be derived from the system of equations of `b[]` and some working-through of the algorithm. It can be shown that `b[4] = a[0] + a[1] + a[2] + a[3] + a[4]`.
```
int a[5];
for (a[0] = 0; a[0] <= upper_bound / 5; a[0]++) {
for (a[1] = a[0] + 1; 10 * (a[1] - a[0]) + a[0] <= upper_bound; a[1]++) {
a[2] = a[1] + (a[1] - a[0]);
a[3] = a[2] + (a[1] - a[0]);
a[4] = a[3] + (a[1] - a[0]);
if (c(a)) {
printf("PASSED FOR {%d, %d, %d, %d, %d}\n", a[0], a[1], a[2], a[3], a[4]);
}
}
printf("a[0] = %d Checked\n", a[0]);
}
```
With `a[0] = 6174`, this loop broke my work in a little under a minute.
[Answer]
# Mathematica ~~80~~ 67
```
f=Boole[(p=NextPrime/@#)-#=={18,31,6,9,2}&&BitXor@@#~Join~p==1000]&
```
Running:
```
f[{1,2,3,4,5}] (* => 0 *)
```
Probably pretty easy to crack, might also have multiple solutions.
**Update:** Improved golfing by doing what Martin Büttner suggested. Functionality of the function and the key hasn't changed.
[Answer]
## Python27, ~~283~~ 182
Alright, I am very confident in my locker, however it is quite long as I've added 'difficult to reverse' calculations to the input, to make it well - difficult to reverse.
```
import sys
p=1
for m in map(int,sys.argv[1:6]):m*=3**len(str(m));p*=m<<sum([int(str(m).zfill(9)[-i])for i in[1,3,5,7]])
print'01'[p==0x4cc695e00484947a2cb7133049bfb18c21*3**45<<101]
```
edit: Thanks to colevk for the further golfing. I realized during editing that there was a bug as well as a flaw in my algorithm, maybe I'll have better luck next time.
[Answer]
**Mathematica ~~142~~ 146**
**EDIT**: key wasn't unique, added 4 chars, now it is.
```
n=NextPrime;
f=Boole[
FromDigits /@ (
PartitionsQ[n@(237/Plus@##) {1, ##} + 1] & @@@
IntegerDigits@n@{Plus@##-37*Log[#3],(#1-#5)#4}
) == {1913001154,729783244}
]&
```
(Spaces and newlines added for readability, not counted & not needed).
Usage:
```
f[1,2,3,4,5] (* => 0 *)
```
[Answer]
# CJam, 49 characters
```
"腕옡裃䃬꯳널֚樂律ࡆᓅ㥄뇮┎䔤嬣ꑙ䘿휺ᥰ籃僾쎧諯떆Ἣ餾腎틯"2G#b[1q~]8H#b%!
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
```
" Push a string representing a base 65536 number and convert it to an integer. ";
"腕옡裃䃬꯳널֚樂律ࡆᓅ㥄뇮┎䔤嬣ꑙ䘿휺ᥰ籃僾쎧諯떆Ἣ餾腎틯"2G#b
" Prepend 1 to the integers read from STDIN and collect them into an array. ";
[1q~]
" Convert that array into an integer by considering it a base 2**51 number. ";
8H#b
" Push the logical NOT of the modulus of both computed integers. ";
%!
```
The result will be 1 if and only if the second integer is a factor of the first, which is a product of two primes: the one corresponding to the secret sequence and another that doesn't correspond to any valid sequence. Therefore, the solution is unique.
Factorizing a 512 bit integer isn't *that* difficult, but I hope nobody will be able to in 72 hours. My previous version using a 320 bit integer [has been broken](https://codegolf.stackexchange.com/questions/36768/lockers-vs-crackers-the-five-element-sequence/36887?noredirect=1#comment83347_36889).
### Example run
```
$ echo $LANG
en_US.UTF-8
$ base64 -d > flock512.cjam <<< IuiFleyYoeijg+SDrOqvs+uEkNaa76a/5b6L4KGG4ZOF76Gi46WE64eu4pSO5JSk5ayj6pGZ5Ji/7Zy64aWw57GD5YO+7I6n6Kuv65aG7qK04byr6aS+6IWO7rSn7YuvIjJHI2JbMXF+XThII2IlIQ==
$ wc -m flock512.cjam
49 flock512.cjam
$ cjam flock512.cjam < flock512.secret; echo
1
$ cjam flock512.cjam <<< "1 2 3 4 5"; echo
0
```
[Answer]
# Cracked by @Dennis in 2 hours
---
Just a simple one to get things started - I fully expect this to be quickly cracked.
# [Pyth](https://github.com/isaacg1/pyth), 13
```
h_^ZqU5m-CGdQ
```
Takes comma separated input on STDIN.
Run it like this (-c means take program as command line argument):
```
$ echo '1,2,3,4,5' | python3 pyth.py -c h_^ZqU5m-CGdQ
0
```
Fixed the program - I had not understood the spec.
This language might be too esoteric for this competition - If OP thinks so, I will remove it.
[Answer]
# Lua 105
I suspect it won't be long before it's cracked, but here we go:
```
function f(a,b,c,d,e)
t1=a%b-(e-2*(d-b))
t2=(a+b+c+d+e)%e
t3=(d+e)/2
print(t1==0 and t2==t3 and"1"or"0")
end
```
(spaces added for clarity, but are not part of count)
[Answer]
## Perl - 256
```
sub t{($z,$j,$x,$g,$h)=@_;$t="3"x$z;@n=(7,0,split(//,$g),split(//,$h),4);@r=((2)x6,1,1,(2)x9,4,2,2,2);$u=($j+1)/2;for$n(0..$#r+1){eval{substr($t,$j,1)=$n[$n]};if($@){print 0; return}$j+=$r[$n]*$u}for(1..$x){$t=pack'H*',$t;}eval$t;if($@||$t!~/\D/){print 0}}
```
I had to put in a lot of error handling logic and this can definitely be golfed down a lot more. It will print a `1` when you get the right five numbers. It will **hopefully** print a `0` for everything else (might be errors or nothing, I don't know). If anyone wants to help improve the code or golf it more, feel free to help out!
---
## Call with:
```
t(1,2,3,4,5);
```
[Answer]
## Ruby - 130
Based on Linear Feedback Shift Register. Inputs by command line arguments.
Should be unique based on the nature of LFSRs. Clue: ascending and all positive.
Will give more clues if no one solves it soon.
```
x=($*.map{|i|i.to_i+2**35}*'').to_i
(9**8).times{x=((x/4&1^x&1)<<182)+x/2}
p x.to_s(36)=="qnsjzo1qn9o83oaw0a4av9xgnutn28x17dx"?1:0
```
[Answer]
# Ruby, 249
```
a=gets.scan(/\d+/).map(&:to_i)
a.each_cons(2).map{|x,y|x-y}.uniq[1]&&p(0)&&exit
r=(a[0]*a[1]).to_s(5).tr'234','(+)'
v=a[0]<a[1]&&!r[20]&&(0..3).select{|i|/^#{r}$/=~'%b'%[0xaa74f54ea7aa753a9d534ea7,'101'*32,'010'*32,'100'*32][i]}==[0]?1:0rescue 0
p v
```
Should be fun. Who needs math?
[Answer]
# C 93 bytes
A simple hash. To follow the rule of unique solution, I bruteforced all the candidates, which took quite some core-hours. Of course the solution can be found in the same way.
The function `f` accepts a pointer to the 5 input integers and outputs 1 for the unique solution, 0 otherwise.
```
i=1e5;f(int*x){for(;--i;)x[i&3]+=(x[4]^=x[i&3])*9>>3;return!memcmp(x,"U|]v-W^Scv1(-8V8",16);}
```
For more adventurous hackers, here's a variant with 64-bit security`*` (89 bytes), which I could not verify to have a unique solution due to too big search space (but the chance of it happening is less than 1 in a billion).
```
i=1e5;f(int*x){for(;--i;)x[i&3]+=(x[4]^=x[i&3])*9>>3;return!memcmp(x,"'=P(=31qlite",12);}
```
`*` 64-bit security meaning 2^64 function calls. The number of required bit operations is quite bigger.
[Answer]
# Javascript 958
Converts the inputs to a number of data types and performs some manipulations relevant to each data type along the way. Should be fairly easily reversed for anyone that takes the time.
```
function encrypt(num)
{
var dateval = new Date(num ^ (1024-1) << 10);
dateval.setDate(dateval.getDate() + 365);
var dateString = (dateval.toUTCString() + dateval.getUTCMilliseconds()).split('').reverse().join('');
var result = "";
for(var i = 0; i < dateString.length; i++)
result += dateString.charCodeAt(i);
return result;
}
function unlock(int1, int2, int3, int4, int5)
{
return encrypt(int1) == "5549508477713255485850495848483249555749321109774324948324410511470" && encrypt(int2) == "5756568477713252485848495848483249555749321109774324948324410511470" && encrypt(int3) == "5149538477713248485856485848483249555749321109774324948324410511470" && encrypt(int4) == "5356498477713256535853485848483249555749321109774324948324410511470" && encrypt(int5) == "5748568477713251535851485848483249555749321109774324948324410511470" ? 1 : 0;
}
```
[Answer]
## C, 239 (Cracked by Dennis)
Go [here](https://codegolf.stackexchange.com/a/36810/31002) for my updated submission.
Could probably be golfed a little more thoroughly. Admittedly, I haven't taken the time to prove the key is unique (it probably isn't) but its definitely on the order of a hash collision. If you crack it, please share your method :)
```
p(long long int x){long long int i;x=abs(x);
for (i=2;i<x;i++) {if ((x/i)*i==x) return 0;}return 1;}
f(a,b,c,d,e){char k[99];long long int m;sprintf(k,"%d%d%d%d%d",e,d,c,b,a);
sscanf(k,"%lld",&m);return p(a)&&p(b)&&p(c)&&p(d)&&p(e)&&p(m);}
```
[Answer]
# C, 212 by Orby -- Cracked
<https://codegolf.stackexchange.com/a/36810/31064> by Orby has at least two keys:
```
13 103 193 283 373
113 173 233 293 353
```
Orby asked for the method I used to crack it. Function p checks whether x is prime by checking `x%i==0` for all i between 2 and x (though using `(x/i)*i==x` instead of `x%i==0`), and returns true if x is a prime number. Function f checks that all of a, b, c, d and e are prime. It also checks whether the number m, a concatenation of the decimal representations of e, d, c, b and a (in that order), is prime. The key is such that a,b,c,d,e and m are all prime.
Green and Tao (2004) show that there exist infinitely many arithmetic sequences of primes for any length k, so we just need to look for these sequences that also satisfy m being prime. By taking long long as being bounded by -9.223372037e+18 and 9.223372037e+18, we know that for the concatenated string to fit into long long, the numbers have an upper bound of 9999. So by using a python script to generate all arithmetic sequences within all primes < 10000 and then checking whether their reverse concatenation is a prime, we can find many possible solutions.
For some reason I came up with false positives, but the two above are valid according to the program. In addition there may be solutions where e is negative and the rest are positive (p uses the modulus of x), but I didn't look for those.
The keys I gave are all arithmetic sequences but Orby's script doesn't appear to actually require the inputs to be an arithmetic sequence, so there may be invalid keys too.
[Answer]
# MATLAB: Apparently invalid
Very simple, you just have to generate the right random number.
```
function ans=t(a,b,c,d,e)
rng(a)
r=@(x)rng(rand*x)
r(b)
r(c)
r(d)
r(e)
rand==0.435996843156676
```
It can still error out, but that shouldn't be a problem.
[Answer]
# MATLAB (with Symbolic Toolbox), 173 characters
This isn't an official entry and won't count towards anyone's cracking score, but it will net you mad bragging rights. ;)
```
function b=L(S),c=sprintf('%d8%d',S(1),S(2)-S(1));b=numel(unique(diff(S)))==1&&numel(c)==18&&all(c([8,9])==c([18,17]))&&isequal(c,char(sym(sort(c,'descend'))-sym(sort(c))));
```
The symbolic toolbox is only required to handle subtraction of big integers.
Brute forcing it should be a dog, but if you're familiar with the series it involves, the solution is trivial.
[Answer]
# Python 2 (91)
**Edit:** This isn't allowed because the argument for uniqueness is probabilistic. I give up.
---
```
s=3
for n in input():s+=pow(n,s,7**58)
print s==0x8b5ca8d0cea606d2b32726a79f01adf56f12aeb6e
```
Takes lists of integers as input, like `[1,2,3,4,5]`.
The loop is meant to operate on the inputs in an annoying way, leaving a tower of sums and exponents. The idea is like discrete log, but with messy complication instead of mathematical simplicity. Maybe the compositeness of the of the modulus is a vulnerability, in which case I could make it something like `7**58+8`.
I don't really know how I'd prove that my key is the only one, but the range of outputs is at least 10 times bigger than the range of inputs, so probably? Though maybe only a small fraction of potential outputs are achievable. I could always increase the number of digits at the cost of characters. I'll leave it up to you to decide what's fair.
Happy cracking!
[Answer]
# Mathematica - 72
Version 2 of my script, with the same key as the one intended for my version 1.
This basically removes negative prime numbers for `NextPrime`.
```
f=Boole[(p=Abs[NextPrime/@#])-#=={18,31,6,9,2}&&BitXor@@#~Join~p==1000]&
```
Running:
```
f[{1,2,3,4,5}] (* => 0 *)
```
[Answer]
# Python, 86 characters
```
a,b,c,d,e=input()
print 1if(a*c^b*e)*d==0xd5867e26a96897a2f80 and b^d==48891746 else 0
```
Enter the numbers like `1,2,3,4,5`.
```
> python 36768.py <<< "1,2,3,4,5"
0
> python 36768.py <<< "[REDACTED]"
1
```
[Answer]
# Python, 78
(Cracked by Tyilo in 14 mins)
Fun!
```
def L(a): return 1 if a==[(i-i**6) for i in bytearray(' ','utf-8')] else 0
```
[Okay, it doesn't display properly here :(](http://pastebin.com/CkEN608E)
Expects a list of five numbers, eg. [1,2,3,4,5]
[Answer]
# CJam, 37 characters (broken)
```
"煷➻捬渓类ⶥ땙ዶ꾫㞟姲̷ᐂ㵈禙鰳쥛忩蔃"2G#b[1q~]4G#b%!
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### How it works
[See my new answer.](https://codegolf.stackexchange.com/a/36952/)
### Example run
```
$ echo $LANG
en_US.UTF-8
$ base64 -d > flock.cjam <<< IueFt+Keu+aNrOa4k+exu+K2peuVmeGLtuq+q+Oen+Wnsu6AhMy34ZCC47WI56aZ6bCz7KWb5b+p6JSDIjJHI2JbMXF+XTRHI2IlIQ==
$ wc -m flock.cjam
37 flock.cjam
$ cjam flock.cjam < flock.secret; echo
1
$ cjam flock.cjam <<< "1 2 3 4 5"; echo
0
```
] |
[Question]
[
I need to prepare digits made of cardboard to display some number ([example](https://i.stack.imgur.com/eWidM.jpg)). I don't know beforehand which number I should display - the only thing I know is that it's not greater than `n`.
How many cardboard digits should I prepare?
Example: `n = 50`
To display any number in the range 0...50, I need the following digits:
1. A zero, for displaying the number 0, or any other round number
2. Two copies of digits 1, 2, 3 and 4, for displaying the corresponding numbers
3. One copy of digits 5, 6, 7 and 8, for the case they appear as least significant digit in the number
4. The digit 9 is never needed, because I can use the inverted digit 6 instead
Total: 13 digits
Test cases (each line is a test case in the format "input; output")
```
0 1
1 2
9 9
11 10
50 13
99 17
100 18
135 19
531 22
1000 27
8192 34
32767 38
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
‘ḶDœ|/ḟ9L
```
[Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oCY4bi2RMWTfC/huJ85TP///zMyNzY3 "Jelly – Try It Online")
## How it works
```
‘ḶDœ|/ḟ9L
‘Ḷ [0,1,...,n]
D convert each to list of its digits
œ|/ fold by multiset union
ḟ9 remove 9
L length
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda n:9*len(`n`)-9+(n*9+8)/10**len(`n`)+(n<10)
```
[Try it online!](https://tio.run/##PYrBDoIwEETP7FfssQXUbhuEEvsnJlIiBBKoDWKIX4@rB@cwk7x58b0Oj6D33l33yc/t3WOobTp1QTShkQebiZDarJInUukfM7yQkvs2jFOHVEPi89bNPooxrPnit9sY4msV8viM08grIVlcLzxvXNhBn@OSY8vtXLsrJCDUoNGARQukvkVICgr@GFqkEsgUSBYKw65mSSnUJRhdnks0FVS/YGE@ "Python 2 – Try It Online")
A clumsy arithmetical formula. Assume that `n` fits within an `int` so that an `L` isn't appended.
Thanks to Neil for saving 5 bytes by pointing out that 9's being unused could be handled by doing `n*9+8` instead of `n*9+9`, so that, say, `999*9+8=8999` doesn't roll over to 9000.
[Answer]
# [Haskell](https://www.haskell.org/), ~~117~~ ~~114~~ ~~108~~ ~~95~~ ~~89~~ ~~88~~ ~~87~~ ~~84~~ ~~82~~ 63 bytes
*6 bytes saved thanks to Laikoni*
*~~1~~ ~~4~~ 6 bytes saved thanks to nimi*
```
g x=sum[maximum[sum[1|u<-show y,d==u]|y<-[0..x]]|d<-['0'..'8']]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P12hwra4NDc6N7EiMxdIg9iGNaU2usUZ@eUKlToptralsTWVNrrRBnp6FbGxNSlAprqBup6euoV6bOz/3MTMPCsrT38NTS4Q07agKDOvRCVdwdDI0vg/AA "Haskell – Try It Online")
[Answer]
# Mathematica, 49 bytes
```
Tr@Delete[Max~MapThread~DigitCount@Range[0,#],9]&
```
[Answer]
## Batch, 67 bytes
```
@if %1 geq 10%2 %0 %1 0%2 -~%3
@cmd/cset/a(%1*9+8)/10%2+9*%30+!%30
```
In the standard formulation of this problem, you need separate `6` and `9` digits, but you're not required to display `0`. As the maximum value `n` required increases, the number of required numerals increases every time you reach a repdigit (because you don't quite have enough of that numeral) and every time you reach a power of `10` (when you need an extra zero). In total each power of `10` needs `10` more numerals than the previous one, which can be caluclated as `floor(log10(n))*10`. For values of `n` between powers of 10, the number of intermediate repdigits can then be calculated as `floor(n/((10**floor(log10(n))*10-1)/9))` or alternatively `floor(n*9/(10**floor(log10(n))*10-1))`.
I calculate `floor(log10(n))` by means of the loop on the first line. Each time, `%2` gains an extra `0` and `%3` gains an extra `-~`. This means that `10%2` is `10*10**floor(log10(n))` and `%30` is `floor(log10(n))`.
The duplication of `6` and `9` has two effects: firstly, there are only `9` numerals required for each power of `10`, and secondly the repdigit detection needs to ignore the `9` repdigits. Fortunately as they are one less than a power of 10 this can be achieved by tweaking the formula to result in `floor((n*9+8)/(10**floor(log10(n))*10))`.
Dealing with the zero is reasonably simple: this just requires an extra numeral when `n<10`, i.e. `floor(log10(n))==0`.
[Answer]
## JavaScript (ES6), ~~60~~ 53 bytes
```
f=(n,i=9)=>n>(i%9+1+"e"+(i/9|0))/9-1?1+f(n,-~i):n>9^1
```
A sort of hacky recursive solution. This generates the numbers which require adding a digit:
```
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 22, 33, 44, 55, 66, 77, 88, 100, 111, 222, ...
```
and then counts how many are less than the input. By a happy miracle, removing the digit `9` actually *removes* several bytes from the function, because the sequence can then be generated like so (assuming integer division):
```
1e1 / 9 = 1, 2e1 / 9 = 2, ..., 8e1 / 9 = 8, 9e1 / 9 = 10, 1e2 / 9 = 11, 2e2 / 9 = 22, ...
```
We do have to take into account the fact that numbers under 10 still require the zero, but this is as simple as adding `n > 9 ? 0 : 1` to the result.
### Test cases
```
let f=(n,i=9)=>n>(i%9+1+"e"+(i/9|0))/9-1?1+f(n,i+1):n>9^1;
[0, 1, 9, 11, 50, 99, 100, 135, 531, 1000, 8192, 32767].map(n => console.log(f(n)));
```
[Answer]
# Mathematica, 83 bytes
```
v=DigitCount;s=v@0;(Table[s[[i]]=v[j][[i]]~Max~s[[i]],{i,10},{j,#}];s[[9]]=0;Tr@s)&
```
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes
```
lambda n:sum(max(str(j).count(str(i))for j in range(n+1))for i in range(9))
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqrg0VyM3sUKjuKRII0tTLzm/NK8EzMnU1EzLL1LIUsjMUyhKzEtP1cjTNoSIZSLELDU1/xcUZQL1pGkYaGpywdiGSGxLZHFkCVNkHZYoyoxNkdUZI@syNDBA1mdsZG5mDnQFAA "Python 3 – Try It Online")
[Answer]
# [PHP](https://php.net/), 60 bytes
```
<?=count(preg_grep('#^100+$|^([0-8])\1*$#',range(0,$argn)));
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbGRuZq5kzWVvBxS3Tc4vzSvRKChKTY9PL0ot0FBXjjM0MNBWqYnTiDbQtYjVjDHUUlFW1ylKzEtP1TDQARuiqalp/f8/AA "PHP – Try It Online")
] |
[Question]
[
In [this simple but fun challenge](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform), you were asked to determine if Jimmy would fall of their platform. Jimmy has three body parts `/`, `o`, and `\` arranged like this
```
/o\
```
Platforms are represented with `-`. Jimmy will fall off their platform iff they have two or more body parts that are not directly above a platform.
Some examples:
```
/o\
- -------
```
Jimmy will balance since all their body parts are above a `-`.
```
/o\
------ ---
```
Jimmy will balanced since two body parts are above `-`s.
```
/o\
-- ---- --
```
Jimmy will balance even though they are split between two platforms
```
/o\
-
```
Jimmy will not be balanced since two body parts are not above a platform.
---
Your task is to write a program that takes a platform as a lengthed container containing only `-`s and s (e.g. a string) and outputs the number of Jimmys that can be placed on the platform such that none of them will fall and none of them will overlap. A Jimmy may have one of their body parts to the left of the beginning of the string or the right of the end of the string.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with fewer bytes being the aim.
## Test cases
### Inputs
```
- - -
- -
--
-- --
----
- -- --
------- -
```
### Respective outputs
```
0
0
1
1
2
2
2
3
```
[Answer]
# JavaScript (ES6), ~~45 41~~ 40 bytes
*Saved 4 bytes thanks to @Shaggy*
```
s=>(0+s+0).split(/.--|-.-|--./).length-1
```
[Try it online!](https://tio.run/##fY09CoAwFIN3T1GcWiSvegC9i2j9o7TiK07evSpuUoVk@ZKQpd1b7rZ5DXC@N3GoI9eNLAsuSkW82jlITcABugzSiqxxY5hQxc479taQ9aMcZA4hbuVKZa8kgZAsIg3FB09j8TcAnud4Ag "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 53 bytes
```
lambda s:len(re.findall('.--|-.-|--.',`s`))
import re
```
[Try it online!](https://tio.run/##TYjBCsIwEETv@Yq9bQJuQI8F/0SwkSZ0YZuGbaQI/ntsrQdhZt7MlFcd53xp6XprEqbHEGDpJGar0SfOQxCx6Ine5DeTx1O/9M4ZnsqsFTS2dWSJcO4MFOVcIVkN651zeVbrXEMC2IUGN9G30BHw4wH4P2gf@AE "Python 2 – Try It Online")
Based on [Arnauld's regex](https://codegolf.stackexchange.com/a/187684/20260). Greedily searches for all the non-overlapping length-3 substrings with two or more `-`. A trick is to do ``s`` to enclose the input string in quotes as padding to leave room for Jimmys to hang off on either end like
```
/o\/o\
'----'
```
**[Python 2](https://docs.python.org/2/), 57 bytes**
```
f=lambda s:'--'in s[:3]*2and-~f(s[3:])or s>''and f(s[1:])
```
[Try it online!](https://tio.run/##TYnNCoMwEITvPsXc1hT2oN4C7YuIlBQVA3YNSYr00ldPE@2hMMzPN@4dl03alObrap6P0SBoYiYrCL3uhktrZOTPXIe@04PaPMKNKDMU1GSU9sWuExpdwXkrMR/e7Hcr7hVrpRIxUEQVZfFR@DT88gz8Ay6Dvg "Python 2 – Try It Online")
Requires a cheesy I/O format of the input already in quotes. Outputs `False` for 0.
A recursive function that places each Jimmy on the leftmost position allowed, by either placing Jimmy over the first three characters if they can hold Jimmy, or otherwise deleting the first character. A cute trick is to check if `s[:3]` contains two or more `-` by doing `'--'in s[:3]*2`, which concatenates two copies of `s[:3]` and checks for two adjacent `-`.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 28 bytes
Uses the same method as @Arnauld's JavaScript.
```
$_=@a=" $_ "=~/.--|-.-|--./g
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tYh0VZJQSVeQcm2Tl9PV7dGVw@IdfX00///11VQACEuLl0goQtCCmASRCggOLog5r/8gpLM/Lzi/7q@pnoGhgb/dQtyAA "Perl 5 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
Based on Arnauld's original JS solution. I tried a few different methods to get the necessary padding either side of the input but all came in at the same length - still searching for a shorter way...
```
ûUÊÄÄ è".--|-."ê
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2b1XKxMQg6CIuLS18LS4i6g&input=WwoiLSAgLSAgLSIKIiIKIi0gLSIKIi0tIgoiLS0gLS0iCiItLS0tIgoiLSAtLSAtLSIKIi0tLS0tLS0gLSIKXS1t)
```
ûUÊÄÄ è".--|-."ê :Implicit input of string U
û :Centre pad with spaces to length
UÊ : Length of U
ÄÄ : Add 1, twice
è :Count the occurrences of
".--|-."ê : ".--|-." palindromised, resulting in the RegEx /.--|-.-|--./g
```
[Answer]
# Excel, 96 bytes
`A1` = platform.
Entered as array Formula `Ctrl`+`Shift`+`Enter`
```
=SUM(IF(LEN(TRIM(MID(IF(MOD(LEN(A1),3)=1," ","")&A1,3*ROW(INDIRECT("A1:A"&LEN(A1)))-2,3)))>1,1))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ðì‚ε3ôʒ'-¢2@}g}à
```
Can definitely be golfed.. Sometimes it's annoying to see all these regex answers in a challenge when using 05AB1E, which is lacking regex of any kind. ;)
[Try it online](https://tio.run/##yy9OTMpM/f//8IbDax41zDq31fjwllOT1HUPLTJyqE2vPbzg/39dCFDQBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v8Pbzi85lHDrHNbjQ9vOTVJXffQIiOH2vTawwv@6/zXVVAAIS4FLl0gqQtCCmASRCggOLogJgA).
**Explanation:**
```
ðì # Prepend a space before the (implicit) input
‚ # Pair it with the unmodified (implicit) input
ε # Map both to:
3ô # Split them into parts of size 3
ʒ # Filter these parts by:
'-¢ '# Where the amount of "-"
2@ # Is larger than or equal to 2
}g # After the filter: take the length to get the amount of items left
}à # After the map: get the maximum of the two
# (which is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->s{s.scan(/(^|.)--|-.-|--(.|$)/).size}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivODkxT0NfI65GT1NXt0ZXD4h1NfRqVDT1NfWKM6tSa/9Hq@sqKICQuo46EOmCGboQQgFKQygFZAFdEEc9Vi83saC6pqKmQCEtuiK29j8A "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ƒó±KêyG←à╛Ωô∟
```
[Run and debug it](https://staxlang.xyz/#p=9fa2f14b8879471b85beea931c&i=%22-++-++-%22%0A%22%22%0A%22-+-%22%0A%22--%22%0A%22--+--%22%0A%22----%22%0A%22-+--+--%22%0A%22-------+-%22%0A&a=1&m=2)
[Answer]
# Java 8, 41 bytes
```
s->(0+s+10).split(".--|--.|-.-").length-1
```
[Try it online.](https://tio.run/##TZC9bgIxEIR7nmLkypazFrRESZM6NJQhhWMMMTG@03kBRXDPfvH9SZFWu57Rej5pT/Zq6bT/6Vy0OePdhnRfACGxbw7WeWx6ORhwcstNSEdk9VzMdlFaZsvBYYOEF3SZXuVSZ71aKpPrGFgKQ/QgMg8yJJSJPh35m1ZdH1BfvmL5O0Vcq7DHufAnyscnrBrhh6qZ0ewzv9nssUbyN8yrd0FAX@JJlKLhQWPDNMeB/wb1QrRqoADb38z@bKoLm7rkckxS7ITQM1QXtYbQyTg5e2q6Rdv9AQ)
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/187684/52210), except that `+0` is `+10` to fix test cases like `----`. This is necessary because the [`String#split`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-) builtin in Java will remove trailing empty Strings by default. This can be changed by adding an [additional parameter to the `split` builtin](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-) (which is `0` by default in the `split`-builtin with a single String argument). To quote the usage of this additional parameter from the docs:
>
> The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
>
> If the limit \$n\$ is **greater than zero** then the pattern will be applied at most \$n-1\$ times, the array's length will be no greater than \$n\$, and the array's last entry will contain all input beyond the last matched delimiter.
>
> If \$n\$ is **non-positive** then the pattern will be applied as many times as possible and the array can have any length.
>
> If \$n\$ is **zero** then the pattern will be applied as many times as possible, the array can have any length, **and trailing empty strings will be discarded**.
>
>
>
Because of this, usually `.split("...",-1)` is used to retain *ALL* trailing empty Strings, and I could have used it for this answer as well ([Try it online](https://tio.run/##TZBPbwIhEMXvfooXThAcoleb9tJzvXhse6CIFkV2s4w2je5n37L/kiaTGd4L836Ek71ZOu3PnYs2Z7zZkO4LICT2zcE6j20vBwNO7rgJ6YisnorZLkrLbDk4bJHwjC7Ti1zprFfK5DoGlsIQPYjMgwyJJa2ViT4d@ZvWXR9RX79i2Z5CblXY41JeMHHeP2HViD9UzQxnn/nVZo8Nkv/BfPUuCOhLLEUpGg40NkxzHPhvUC9EqwYKsPvN7C@murKpSy7HJMWHEHqG6qI2EDoZJ2dPTb/Rdn8)). In this case changing the `+0` to `+10` saves two bytes over the `,-1`, though. :)
[Answer]
# Elm 0.19, 108 bytes
```
import Regex as R
f p=List.length<|R.find(Maybe.withDefault R.never<|R.fromString".--|-.-|--.")(" "++p++" ")
```
Based on the regex in [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s JavaScript [answer](https://codegolf.stackexchange.com/a/187684/79343). Verify all test cases [here](https://ellie-app.com/63bn8psYDyxa1).
Alternative solution without regex, significantly longer at **171 bytes**:
```
f p=(String.foldl(\z{x,y,s,c}->let(t,d)=if s<1&&List.length(List.filter((==)'-')[x,y,z])>1 then(2,c+1)else(max 0 s-1,c)in{x=y,y=z,s=t,c=d}){x=' ',y=' ',s=0,c=0}(p++" ")).c
```
Verify all test cases [here](https://ellie-app.com/63qnVmb8V3Ba1).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
n⁶,Ż$s€3§Ẓ§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/z/vUeM2naO7VYofNa0xPrT84a5JQGJnw/9HjfuUlLKsHzXMUdC1U3jUMNf6cDvXw91bDrcDFUb@/6@kpKSroABCXApcukBSF4QUwCSIUEBwdEFMoHoA "Jelly – Try It Online")
Based on [@KevinCrujissen’s 05AB1E answer](https://codegolf.stackexchange.com/a/187711/42248) so be sure to upvote him too.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
Pθ↖Fθ¿›№KM-¹«⊞υωM³→»→⎚ILυ
```
[Try it online!](https://tio.run/##NY7BCoMwDIbP9imCpxT0MHbTo4ddFGSwBygStaxYF1t3GHv2LnOMwE/y8@dLhtnw4I1LqYsu2JXtEvCha9X5nbC6rS2NQcbRM4gPdgS8MJlAjI2PEu6J7p33TKgLyMtc9KQ1vFTWx23GWMBT9rODdy6gutpp/hLfitxG8LvzNxtHhlGa/nikMVvAlpYpCEhrXadUwlEqlbv7AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Pθ↖
```
Print the platform without moving the cursor, then move the cursor up and left as that is the first potential Jimmy position.
```
Fθ
```
Look for as many Jimmies as there are platform positions.
```
¿›№KM-¹
```
Check to see whether there is more than one piece of platform at this position.
```
«⊞υω
```
If so then note a valid Jimmy position...
```
M³→»
```
... and move three characters to the right so that the Jimmies don't overlap.
```
→
```
Otherwise the next potential Jimmy position is one character to the right.
```
⎚ILυ
```
Clear the platform and output the count of discovered positions.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes
Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/187684/52210).
```
(" $args "-split'.--|-.-|--.').count-1
```
[Try it online!](https://tio.run/##XY9hC4IwEIa/71ccYzUH3sj6JgT9kxCbFaxcblKg/vY1NTQ9drD3fd47OFO@VWVvSmvPCjhC4yMKLKuuFihao@@OS8QWZWiUXMi8rJ8OE98RcooIhIqjXcwRoH9czNb0T3qMCzmrfa9gbaw0LCOHMYI4rhXQwgaaATL1MSp36hIDMzpzRVk9bLiLnUdcKVtrF4xtOHdODJCy6MdRvaZFIp2m0r8JSjr/BQ "PowerShell – Try It Online")
] |
[Question]
[
As you probably know, a Fibonacci Number is one which is the sum of the previous two numbers in the series.
A Fibonacci Digit™ is one which is the sum of the two previous *digits*.
For instance, for the series beginning `1,1`, the series would be `1,1,2,3,5,8,13,4,7,11,2...` The change occurs after the `13`, where, instead of adding `8+13`, you add `1+3`. The series loops at the end, where `4+7=11`, and `1+1=2`, same as the series starts.
For another example, the series beginning `2,2`: `2,2,4,6,10,1,1,2,3,5,8,13,4,7,11,2,3...`. This one starts out uniquely, but once the digits sum to `10`, you end up with `1+0=1, 0+1=1`, and the series continues - and loops - the same way the `1,1` series did.
---
# The Challenge
Given an integer input `0≤n≤99`, calculate the loop in the Fibonacci Digit series beginning with those two digits. (You are certainly *allowed* to consider integers out of this range, but it's not required.) If given a one-digit input, your code should interpret it to denote the series beginning `0,n`.
All numbers in the loop that are two-digits *must* be outputted as two digits. So, for instance, the loop for `1,1` would contain `13`, not `1,3`.
The output begins with the first number in the loop. So, based on the above restrictions, the loop for `1,1` begins with `2`, since `1,1` and `11` are counted separately.
Each number of the output may be separated by whatever you want, as long as it's consistent. In all of my examples I use commas, but spaces, line breaks, random letters, etc. are all allowed, as long as you always use the same separation. So `2g3g5g8g13g4g7g11` is a legal output for `1`, but `2j3g5i8s13m4g7sk11` is not. You can use strings, lists, arrays, whatever, provided that you have the correct numbers in the correct order separated by a consistent separator. Bracketing the entire output is also allowed (ex. `(5,9,14)` or `[5,9,14]`, etc.).
**Test Cases:**
```
1 -> 2,3,5,8,13,4,7,11
2 -> 2,3,5,8,13,4,7,11
3 -> 11,2,3,5,8,13,4,7
4 -> 3,5,8,13,4,7,11,2
5 -> 2,3,5,8,13,4,7,11
6 -> 3,5,8,13,4,7,11,2
7 -> 14,5,9
8 -> 13,4,7,11,2,3,5,8
9 -> 11,2,3,5,8,13,4,7
0 -> 0
14 -> 5,9,14
59 -> 5,9,14
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest number of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
DFṫ-SṭḊ
d⁵ÇÐḶZḢ
```
[Try it online!](https://tio.run/##y0rNyan8/9/F7eHO1brBD3eufbijiyvlUePWw@2HJzzcsS3q4Y5F/w@3P2pao@D@/7@hjoKRjoKxjoKJjoKpjoKZjoK5joKFjoKljoKBjoIhSNQSAA "Jelly – Try It Online")
### How it works
```
d⁵ÇÐḶZḢ Main link. Argument: n (integer)
d⁵ Divmod 10; yield [n:10, n%10].
ÇÐḶ Call the helper link until a loop is reached. Return the loop.
Z Zip/transpose the resulting array of pairs.
Ḣ Head; extract the first row.
DFṫ-SṭḊ Helper link. Argument: [a, b] (integer pair)
D Decimal; replace a and b with the digits in base 10.
F Flatten the resulting array of digit arrays.
ṫ- Tail -1; take the last two digits.
S Compute their sum.
Ḋ Dequeue; yield [b].
ṭ Append the sum to [b].
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~96 78~~ 75 bytes
*-3 bytes thanks to nwellnhof*
```
{0,|.comb,((*~*)%100).comb.sum...{my$a=.tail(2);m/(\s$a.*)$a/}o{@_};$_&&$0}
```
[Try it online!](https://tio.run/##bY7NbsIwEITvfooVchM73RpvfoAIEfU9WoQMIlKkuEGYHqIQXj2N0wNqldvON7Ozezlf69VgWwhK2MHQabyrU2OPKET0iOQLaS0noNy3VUp1tuVmp26mqkUst3YpPh03KpLcLPumez/0W34IAq77oWyuIOrq6@xkUSh3qaubWMBbAQsJHQNwpgX1ofcYehhiKV69lAghVG4Eo0t71g/k/RgTzHCDlGCKayRi8TxOPCbCvw5LPf6XxZhl8yWr@fR66k5HnrPNND/N3w6Wz5/XHmtG0xvjOlLKsvwpfgA "Perl 6 – Try It Online")
0 returns 0, and other number return a Match object which stringifies to the numbers separated by a space with a leading a trailing space.
### Explanation:
```
{ } # Anonymous code block
0,|.comb, ... # Start a sequence with 0,input
# Where each element is
.sum # The sum of
( %100).comb # The last two digits
(*~*) # Of the previous two elements joined together
# Until
{ }o{@_} # Pass the list into another function
my$a=.tail(2); # Save the last two elements
m/(\s$a.*)$a/ # The list contains these elements twice?
# And return
;$_ # Input if input is 0
&& # Else
$0 # The looping part, as matched
```
[Answer]
# JavaScript (ES6), ~~111 104~~ 103 bytes
```
f=(n,o=[p=n/10|0,n%10])=>n^o[i=o.lastIndexOf(n=(q=p+[p=n])/10%10+q%10|0)-1]?f(n,[...o,n]):o.slice(i,-1)
```
[Try it online!](https://tio.run/##jc/NCoJAEAfwe0/hJdilcd3xozLYOnfqAcRATMOQHUuJDr27rShUe/I6/9983bJn1uaPqulcTZei70vFNJBKGqU9lG8Jeoky5Wqvz5RUikSdtd1RX4rXqWRasbtqVgNOueGGru7LoY27mB4MgEQIQWDiHYm2rvKCVeAi73PSLdWFqOnKSuYg547nOT4EEMEWMIAQNoC4sJw/0wWjQ4R/artwdNY08G0Xzdy7njlvM90XGhjb4XYKv@3jWtvFM5@Uo5NWHafnzQWAoRVG8W/YfwA "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function taking:
n, // n = last term, initialized to the input
o = [ // o = sequence, initially containing:
p = n / 10 | 0, // p = previous term, initialized to floor(n / 10)
n % 10 ] // n mod 10
) => //
n ^ // we compare n against
o[ // the element in o[] located at
i = o.lastIndexOf( // the index i defined as the last position of
n = // the next term:
(q = p + [p = n]) // q = concatenation of p and n; update p to n
/ 10 % 10 // compute the sum of the last two digits
+ q % 10 // of the resulting string
| 0 // and coerce it back to an integer
) - 1 // minus 1
] ? // if o[i] is not equal to n:
f(n, [...o, n]) // append n to o[] and do a recursive call
: // else:
o.slice(i, -1) // we've found the cycle: return it
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~187~~ ~~176~~ ~~158~~ ~~139~~ ~~138~~ ~~129~~ ~~121~~ ~~120~~ ~~112~~ ~~96~~ ~~95~~ ~~120~~ 116 bytes
```
f=lambda n,m=0,z=[]:(n,m)in zip(z,z[1:])and z[z.index(m)::-1]or f((z and n//10or m%10)+n%10,z and n or n//10,(m,*z))
```
[Try it online!](https://tio.run/##jVJhS8MwEP3eX3EMhETPrXGb2wL94AfxR3RlxDV1hTUrbdQZ8bfXS1cnlQkNtL2@9@5ejrvyw@4OZto0WbRXxXOqwGARheiiOJGMYp4bcHnJHLpYyIQrk4KL3Tg3qT6ygkt5K5JDBRljDjxpJhMRElBciZDfGHpjRwChLYuswGvHeZPqDFRd68pu3nO725RVbix7yd@0QdDHUm@tThHU1r6qPZcB0DnpzyxEUccjjNbmyedKr/v8WpvHTiTbv4dWJjtuNM4OVaH@twsCfz2ra8s6a31URbnXNUQQt4A/LET/cI6/kCDoDmGKMEdYIgiKZggLikRPeDdUSDgTVPaSuCckgF0sR7k94Xyo9f3Qigt/x1mrXPWIpSf6iWfjnnA1tEtv4zugBDHrt7W6wCRB@6GBw59pA633z1jlucqAncxOEKc1Oa1I8w0 "Python 3 – Try It Online")
Edit: As noted by @[Jules](https://codegolf.stackexchange.com/users/81581/jules), shorter solution applies to Python 3.6+. No longer distinct solutions for Python 3 / 3.6+
Edit: Indexing of `z` was too verbose. Without that now there is no gain in using `eval`.
Edit: Simplified finding if last two elements already appeared in the sequence.
Edit: Changed output format from list to tuple + replaced `lambda` with `def`
Edit: Back to `lambda` but embedded `t` into `f`.
Edit: Input `n` can be actually interpreted as head of growing collection `z` which would represent tail in recursive approach. Also beats @[Arbo](https://codegolf.stackexchange.com/users/82577/arbo)'s solution again.
Edit: Actually you can unpack two items from head which cuts another 16 bytes.
Edit: Actually 17 bytes.
Edit: As noted by @[Arbo](https://codegolf.stackexchange.com/users/82577/arbo) solution was giving answers for `14` and `59` cases as they were in initial test cases which were proven later to be wrong. For now this isn't so short but at least it works correctly.
---
Quite an abuse of `f-strings` and `eval`. Original ungolfed code although I suspect it could be done somehow easier:
```
def is_subsequence(l1, l2):
N, n = len(l1), len(l2)
for i in range(N-n):
if l1[i:i+n]==l2:
return True
return False
def generate_sequence(r):
if is_subsequence(r,r[-2:]):
return r
last_two_digits = "".join(map(str,r))[-2:]
new_item = sum(int(digit) for digit in last_two_digits)
return generate_sequence(r + [new_item])
def f(n):
seq = generate_sequence([n,n])[::-1]
second_to_last = seq[1]
first_occurence = seq.index(second_to_last)
second_occurence = seq.index(second_to_last, first_occurence + 1)
return seq[first_occurence + 1 : second_occurence + 1][::-1]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~114~~ ~~112~~ 109 bytes
```
f(n,s){int i[19]={};for(s=n/10,n%=10;i[s]-n;n+=n>9?-9:s%10,s=i[s])i[s]=n;for(;printf("%d ",s),i[s=i[s]]-n;);}
```
[Try it online!](https://tio.run/##XY7PCoMwDMbve4oiCC1GZt3f2nV7EPEwHI4iy8S6k/TZXarDw3JIyJcvya9On3U9ve4WuRg3jMLiwGxZmVFCDjvYwwGOcIIzKMhAUqu8no3Nu2c8uFtmWKapXJjMqSaJYMutEF1PnoZHcf4oWAS2bCuh12nD/4TuMzgeRT/Fb/zUcAQnxoVLKiLzmn5zZ3ArM8DYyEzb0lUpakwMXtUtVYWLaeZM0EVIBuclveI8CMYJ4llMYVtoP01f "C (gcc) – Try It Online")
-3 from [ceilingcat](https://codegolf.stackexchange.com/questions/178588/what-are-the-repeating-fibonacci-digits/178688?noredirect=1#comment430698_178688)
Includes a trailing space.
```
f(n,s){
int i[19]={}; //re-initialize edges for each call
for(s=n/10,n%=10; //initialize from input
i[s]-n; //detect loop when an edge s->n repeats
n+=n>9?-9:s%10,s=i[s])i[s]=n; //step
for(;printf("%d ",s),i[s=i[s]]-n;); //output loop
}
```
[Answer]
# Perl 5, ~~90~~ 76 bytes
```
s/.\K/ /;s/(.?) *(.)\K$/$".($1+$2)/e until/^0|\b(.\B.|. .)\b.*(?= \1)/;$_=$&
```
[TIO](https://tio.run/##DcrBCoJAEADQ@3zFEkPsGs7sWluJiNBV@oOlQPAgLLq0dvPbmzw@eGn8RC@SmULPipvMmjqjCk0m9Mh4II3uhJXhUX3ndYr8slsYNIUHbaT2NVChu1YFZ7jBd4tHEQcVnOECHq5wgzvUYMHtrH9LWqdlzlI@PVlnpUzxDw)
[Answer]
# [Java (JDK)](http://jdk.java.net/), 194 bytes
```
n->"acdfinehlcdfinehfjofj".chars().map(x->x-97).skip((n="abbicbcsfibbbgqifiibbgbbbcsfbiiqcigcibiccisbcqbgcfbffifbicdqcibcbicfsisiibicfsiffbbicfsifiibicfsifii".charAt(n)%97)).limit(n<1?1:n<9?8:3)
```
[Try it online!](https://tio.run/##bZAxb8IwEIV3fsUpUiS7EAvaoQUCiKVSh06MVQfb4cKFxAm2g0AVvz01gXZpF99375387CvkUSZFtu@oamrroQi9aD2V4mE@@KNha7Sn2vxrOm@3srpaupTOwbskA18DgKZVJWlwXvpQjjVlUAWPbbwlk398grS54/0owJvxr/eUNPCmv3QJCIvOJMtI6gzJbHflvWJRYxEJvZPWMS4q2bBTsjwl02cu3J4axswikkqRVtohKaXyAyEFyAMHSREdNOWawogmp/RB5RoVIgVLZ8FTOgA6ckQ3QFR3@FWIbm9Ye2Z4HMK5KKmi0KWT1WRm0unqZfbEu3n/R6wtI@OBYAHjeSgpTMZXGA5/1gCwOTu/rUTdetGEPXlkUfyYzSB2sYlGQCNYWyvPTvj6tkiGQjZNeWbEg9abjHN@i7z05@AKl@4b "Java (JDK) – Try It Online")
Hardcoded seemed the shortest given that Python already had an answer of 187...
[Answer]
## Haskell, 100 bytes
```
d!p@(s,t)|(_,i:h)<-span(/=p)d=fst<$>i:h|q<-d++[p]=q!(t,last$mod s 10+t:[t-9|t>9])
h x=[]!divMod x 10
```
[Try it online!](https://tio.run/##DclLDoMgFEDReVfxTBxAfLbaP0ZMN@AKCDEktIFULRbSOHDvlOG9xyj/fo5jjDpzD@Ix0I0MaBtD29I7NZMDd1Tzlw9t3qW9LW2pi0I4yZeMBByVD/n00eChrorQiFCyLXRM0p2BlQuZafvrk6/J46TsDBwm5foBiPvaOcAeDAVR4xFPeMYLXvGGd2RYYZ2SyfgH "Haskell – Try It Online")
```
d!p@(s,t) -- function '!' recursively calculates the sequence
-- input parameter:
-- 'p': pair (s,t) of the last two numbers of the sequence
-- 'd': a list of all such pairs 'p' seen before
| <-span(/=p)d -- split list 'd' into two lists, just before the first
-- element that is equal to 'p'
(_,i:h) -- if the 2nd part is not empty, i.e. 'p' has been seen
-- before
=fst<$>i:h -- return all first elements of that 2nd part. This is
-- the result.
|q<-d++[p] -- else (p has not been seen) bind 'q' to 'd' followed by 'p'
=q! -- and make a recursive call to '!' with 'q' and
(t, ) -- make the last element 't' the second to last element
-- the new last element is
[t-9|t>9] -- 't'-9 (digit sum of 't'), if 't'>9
mod s 10+t -- last digit of 's' plus 't', otherwise
h x= -- main function
[]!divMod x 10 -- call '!' with and empty list for 'd' and
-- (x/10,x%10) as the pair of last numbers
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ ~~114~~ 113 bytes
```
n=input()
p=b=l=n/10,n%10
while~-(b in p):p+=b,;l+=(b[1]/10or b[0]%10)+b[1]%10,;b=l[-2:]
print l[p.index(b)-2:-2]
```
[Try it online!](https://tio.run/##FYxBCsMgEADvvsJLQVFbtbeEfYl4WRqIIJslWNpe@nW7vQ3DMPwZ@0F5ToJG/BzGKgaEDnRL0dMlRfXaW9@@waBupNku7AD92h0YLKlKdpwaS6zSWvdXAn6VRwl5qYrPRkP3wtdGj@1t0IoOuc55/wE "Python 2 – Try It Online")
The program builds up a tuple `p` of all 2-value pairs that have occurred in the sequence, which is initialised with junk to save some bytes. The sequence itself gets built in the tuple `l`, and the last two elements of this tuple are stored in `b` for easy (and short) reference. As soon as a repeat is found, we can look up the index of `b` in `p` to know where the loop began.
EDIT: Cleaned this up a bit, and shaved off one more byte... My method does seem to be nearing its byte count limit, and I really should stop working on this.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
≔E◧S²ΣιθW¬υ≔ΦE⊖L⊞OθΣ…⮌⪫θω²✂θλLθ¹⁼κ✂θ⊗⁻λLθλ¹υIυ
```
[Try it online!](https://tio.run/##TU/NbsIwDL7zFD06EjvADfU0lSEx8VONJwjBNNHcpE2coj19lhQOWLJkfX/Wp7T0yklK6TME01k4ygFaeTvgnWFvh8gX9sZ2IJbVOu8l9mBEPkZRLx7aEFZwcgxRiOqVsDPE6OegLSqPPVrGGxzQdqyhjUGfB/SSnYfxGdj8KcJGuwF@cEIfEL6dsYV9iPlvmSwlo7CgtKxeaWOGV4X7GqOkAL9vqq2LV8qPj8bGAO@eYqDZmI@Yi7S5IkMjw1ykTmmTPib6Bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔E◧S²Σιθ
```
Input the number, pad it to 2 characters, then take the digital sum of each character, and save the resulting list.
```
W¬υ
```
Repeat while the list of loops is empty.
```
⊞OθΣ…⮌⪫θω²
```
Calculate the sum of the two previous digits and add it to the Fibonacci list.
```
E⊖L...✂θλLθ¹
```
Take all the nontrivial suffixes of the list.
```
≔Φ...⁼κ✂θ⊗⁻λLθλ¹υ
```
Filter out those that don't repeat and save the result in the list of loops.
```
Iυ
```
Cast the list of loops to string and print.
[Answer]
# [Red](http://www.red-lang.org), ~~189~~ ~~178~~ ~~164~~ 137 bytes
```
func[n][b: n % 10 c: reduce[a: n / 10]until[append c e: b
b: a *(pick[0 1]b > 9)+(a: b % 10)+(b / 10)k: find c reduce[e b]]take/last k k]
```
[Try it online!](https://tio.run/##Tc3RCoIwFMbxe5/iQwi0iFxp5S56iG7HLra5gUyGmD6/LSeH7g4/@H9nst36tp2QmeOrW4IRQQrNEXAAq2A4Jtstxgr1s0s0uYS5H4QaRxs6GFgOncVC4ViMvfGiApMaL7TlqYiV3pbirbe89Byu38p92UJLOStvL4P6zPDwch2nPswiZzi/crg4mO1y/YnDleCW4EZQJ6gJmgQNwT3BneCR4EHwTPAkaBO0BFWCioDtf9nf471qWrl@AQ "Red – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~149~~ 139 bytes
```
s=input()
s=[s/10,s%10]
while zip(s,s[1:]).count((s[-2],s[-1]))<2:s+=[(s[-1]/10or s[-2]%10)+s[-1]%10]
print s[-s[::-1].index(s[-2],2)-1:-2]
```
[Try it online!](https://tio.run/##LY7LDoIwEEXXzld0Y2jDQ1qfNPZLGhYGqjTR0jAloj@Phbibe27m5PpP6Hon5qZvDVEkSZIZlXV@DJQBKo07Xma45WUN784@DflaTzFDzWXNiqYfXaAUdS7qyHJeM3YVElOl6Rrjdz@QtY8Olq5wtfnBurA0qKWMsLCuNdNfJVjOZTzmuAfu0WCDeRHryHBzD0O5YBI2ZjINWXbPHATs4QBHOMEZLlBBCTzG6gc "Python 2 – Try It Online")
Expects a non-negative integer as input. Smaller bytecount, but likely will no longer work for integers >99.
**Explanation:**
```
# get the input from STDIN
s=input()
# convert the input into two integers via a divmod operation
s=[s/10,s%10]
# count number of times the last two numbers appear in sequence in list.
# turn list into list of adjacent value pairs Ex: [1,1,2]->[(1,1),(1,2)]
zip(s,s[1:])
# count number of times the last two items in list appear in entire list
.count((s[-2],s[-1]))
# if >1 matches, we have found a repeat.
while .................................<2:
# the first digit of the last number, if it is >9
# else the last digit of the second to last number
(s[-1]/10or s[-2]%10)
# the last digit of the last number
+s[-1]%10
# add the new item to the list
s+=[..............................]
# reverse the list, then find the second occurrence of the second to last item
s[::-1].index(s[-2],2)
# get the section of the list from the second occurrence from the end, discard the final two items of the list
print s[-......................-1:-2]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
UṠ-U_2¡ȯΣ↑_2ṁd;
```
[Try it online!](https://tio.run/##ASgA1/9odXNr/23igoHFgDEw/1XhuaAtVV8ywqHIr86j4oaRXzLhuYFkO/// "Husk – Try It Online")
```
UṠ-U_2¡ȯΣ↑_2ṁd;
U # longest prefix of unique elements from sequence
Ṡ-U_2 # (after removing longest prefix with
# all unique sublists of length 2)
¡ȯΣ↑_2ṁd; # fibonacci digit sequence:
¡ # repeatedly apply function to list
; # (starting with list formed from input):
ȯ # combination of 3 functions -
Σ # sum of
↑_2 # last 2 elements of
ṁd # digits of list
```
] |
[Question]
[
You are given a matrix of forward and back slashes, for instance:
```
//\\
\//\
//\/
```
A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces.
Pieces from adjacent (horizontally or vertically) cells are glued together.
Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them:
[![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png)
Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins.
```
in:
[[0,0,1,1],
[1,0,0,1],
[0,0,1,0]]
out:
8
in:
[[1]]
out:
2
in:
[[1,0],
[1,1],
[0,1],
[0,0]]
out:
6
in:
[[1,0,1,1,0,1,0,0,0,1,1,1],
[1,0,1,0,1,1,1,1,1,1,1,0],
[1,1,1,0,1,1,0,1,1,1,1,0],
[0,1,0,1,0,1,0,0,1,0,1,1],
[1,1,1,1,0,0,1,1,1,0,0,1]]
out:
19
in:
[[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1],
[1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1],
[1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1],
[1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1],
[0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1],
[0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0],
[0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]]
out:
27
in:
[[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0],
[1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0],
[1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1],
[0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0],
[1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0],
[0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0],
[0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]]
out:
32
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 21 bytes
```
3XytPJ*-X*Xj~4&1ZIunq
```
The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`.
[Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf).
With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0).
## Explanation
Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to
```
\/
\\
/\
//
```
`3Xy` creates a 3×3 identity matrix:
```
1 0 0
0 1 0
0 0 1
```
`tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give
```
0 0 j
0 j 0
j 0 0
```
`-` subtracts the two matrices:
```
1 0 -j
0 1-j 0
-j 0 1
```
`X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix:
```
1 0 -j j 0 1
0 1-j 0 0 1+j 0
-j 0 1 1 0 j
1 0 -j 1 0 -j
0 1-j 0 0 1-j 0
-j 0 1 -j 0 1
j 0 1 1 0 -j
0 1+j 0 0 1-j 0
1 0 j -j 0 1
j 0 1 j 0 1
0 1+j 0 0 1+j 0
1 0 j 1 0 j
```
`Xj` takes the real part:
```
1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
1 0 0 1 0 0
0 1 0 0 1 0
0 0 1 0 0 1
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1
0 0 1 0 0 1
0 1 0 0 1 0
1 0 0 1 0 0
```
Note how the above matrix is a "pixelated" version of
```
\/
\\
/\
//
```
`~` applies logical negation, that is, swaps `0` and `1`:
```
0 1 1 1 1 0
1 0 1 1 0 1
1 1 0 0 1 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
1 1 0 0 1 1
1 0 1 1 0 1
0 1 1 1 1 0
1 1 0 1 1 0
1 0 1 1 0 1
0 1 1 0 1 1
```
`4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label:
```
0 3 3 3 3 0
1 0 3 3 0 5
1 1 0 0 5 5
0 1 1 0 5 5
2 0 1 1 0 5
2 2 0 1 1 0
2 2 0 0 1 1
2 0 4 4 0 1
0 4 4 4 4 0
4 4 0 4 4 0
4 0 4 4 0 6
0 4 4 0 6 6
```
`unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
[Answer]
# MSX-BASIC, ~~226~~ 199 bytes
```
1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H
2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y)
3NEXTX,Y:SCREEN0:?R
```
This script draw slashes on a whole screen and use PAINT operator to count closed areas.
[![The MSX-BASIC script in process](https://i.stack.imgur.com/RLYso.png)](https://i.stack.imgur.com/RLYso.png)
[![Result](https://i.stack.imgur.com/jmlri.png)](https://i.stack.imgur.com/jmlri.png)
To test:
* copy to clipboard the script with test cases data (see below)
* open online emulator <https://webmsx.org/>
* press `Alt-V` and `Ctrl+V` to past test script into MSX
* press `Enter` and `F5` to run test script
* wait a some time to see a result (press `Shift-Alt-T` to switch in `CPU Turbo 8X` mode to save your time)
```
1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H
2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y)
3NEXTX,Y:SCREEN0:?R
10 ' this and below lines are not counted
20 ' the script runs first uncommented test case.
30 ' comment unnecessary test cases
100 '
110 'test case 1: expected output=8
120 'DATA 4,3
130 'DATA 0,0,1,1,1,0,0,1,0,0,1,0
200 '
210 'test case 2: expected output=2
220 'DATA 1,1
230 'DATA 1
300 '
310 'test case 3: expected output=6
320 'DATA 2,4
330 'DATA 1,0,1,1,0,1,0,0
400 '
410 'test case 4: expected output=19
420 'DATA 12,5
430 'DATA 1,0,1,1,0,1,0,0,0,1,1,1
440 'DATA 1,0,1,0,1,1,1,1,1,1,1,0
450 'DATA 1,1,1,0,1,1,0,1,1,1,1,0
460 'DATA 0,1,0,1,0,1,0,0,1,0,1,1
470 'DATA 1,1,1,1,0,0,1,1,1,0,0,1
500 '
510 'test case 5: expected output=27
520 DATA 17,7
530 DATA 1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1
540 DATA 1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1
550 DATA 1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1
560 DATA 1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1
570 DATA 0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1
580 DATA 0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0
590 DATA 0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0
600 '
610 'test case 5: expected output=32
620 DATA 17, 7
630 DATA 0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0
640 DATA 1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0
650 DATA 1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1
660 DATA 0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0
670 DATA 1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0
680 DATA 0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0
690 DATA 0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1
```
[Answer]
# JavaScript (ES6), ~~175~~ 174 bytes
This is probably overcomplicated.
```
a=>a.map((r,y)=>r.map((v,x)=>[2,4].map(s=>v&s||(n++,g=(x,y,s,i,v=(r=a[y])&&r[x])=>!(v&(s^=i%2==v%2&&6))/v&&g(x+1-(r[x]|=s,s&2),y++,s^6)|g(x,y-=v%2*2^s&2,s,v))(x,y,s))),n=0)|n
```
[Try it online!](https://tio.run/##fZLvaoMwFMW/@xTuQ0Oy3rY32eg2RvoiYkG6VhydFjOCgu/u/NcmUSeCcM25v3s8N9@RjtQpT26/mzT7OtcXWUfyEG1/ohulOZRMHvK@0FA0RSDgNew@KHnQRFUVTddriCUtoAQFCWhJcxkFZcgIyYMibJqeqCZUHWWyElLqlSBkz9hOExLTYs03tJVVUoEigkHZ4NRxz6q4RW5a/bM4NkcNXTPWz2GMQSqRVWl9ylKVXc/baxbTCw383c5/93w/QEDgwENoCw5d2Rf9CYZeyNin580ARNezINgP0Dv9QTYjFrr5x90Th/6NMNi1Dd8F5jHzwO52DhFMLxqK3cnNtCGXhSjeFryaUS7eNubYdLYxZ3NOxi2JI7R/GB3mgozPSEfx8dFQV/Z/Vi9iTJhScLxEBJykhvau3RAmjsydnlsRTm8OzsT5II/v0HhRgw03q8kfPpLvsqr/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
≔׳Lθη≔׳L§θ⁰ζBζηψFLθ«J¹⊕׳ιF§θι«¿κP\²P/²M³→»»Fη«J⁰ιFζ«⊞υ¬℅KK¤#→»»⎚IΣυ
```
[Try it online!](https://tio.run/##dY5PT8JAFMTP7ad4wctrssZWb3BCEhOMaKPcag9Nu3Q3bLewfwjW8Nlrlw0pHDzOmzfzm5IVqmwL0fdzrXktcc0bqvGJwBuVtWG4jyICLJqF//hzs5QVPeKeQBy53274fW6P2A0xAj@D2rQKcKyD3zB4tc1u3WJCYClLRRsqDa3Gbj40zcLgHLwCcB8O@AZwG8HKCsN3ikuD028Cjy4SUKHpjfNwcVbtgbry6SevmXGnU3jy49j1qNiBLvTOE1OrGVoC763BD1VxWQhMKd1i5JcGL1wInNxNRtItZiFooXBQ6XnVotAGv2yD1uX7PsuymMQkIUlOQoAsIWfphXfiPM/7@4P4Aw "Charcoal – Try It Online") Link is to verbose version of code. Uses the same format as the examples (except Charcoal requires the list of inputs as an outer array). Explanation:
```
≔׳Lθη≔׳L§θ⁰ζ
```
Like @LuisMendo, we're going to be drawing the matrix at 3x scale, so calculate that in advance.
```
Bζηψ
```
Draw an empty rectangle of that size so that we can fill the edge pieces.
```
FLθ«J¹⊕׳ιF§θι«
```
Loop over the rows and columns.
```
¿κP\²P/²M³→»»
```
Draw each slash at triple size and move to the next one.
```
Fη«J⁰ιFζ«
```
Loop over all of the squares.
```
⊞υ¬℅KK
```
Record whether this square was empty.
```
¤#→»»
```
But try filling it anyway before moving on to the next square. (`Fill` does nothing if the current square is not empty.)
```
⎚IΣυ
```
Clear the canvas and output the total number of empty squares found, which equals the number of pieces (because each piece would have been immediately filled in as soon as we counted it).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 292 bytes
```
n=>{var x=n.SelectMany(l=>"\0".Select(g=>l.SelectMany(r=>r.Skip(g).Concat(r.Take(g))).ToList())).ToList();int i=0,j=0,t=0;for(;i<x.Count;i++)for(j=0;j<x[0].Count;k(i,j++))t+=x[i][j]%2;void k(int a,int b){try{if(x[a][b]<50){x[a][b]='2';k(a+1,b);k(a-1,b);k(a,b-1);k(a,b+1);}}catch{}}return t;}
```
The `\0` should be a literal null byte.
`112` for `/`, `211` for `\`
[Try it online!](https://tio.run/##ZZBBS8QwEIXRo7@iFGQTmi1twVOaXERBUBB2b7WHtKY13ZpKmq5dSn57Tdmoq3vI8DHv5Q0zZb8uezHfD7JMH@7k8M4VK1r@h3uthKwpRUJqWpFZEjrtmfJGIsMNb3mpn5g8gJZQ/yW6uPRdE9SEtqcGRagKNzvxAWoY3nayZBqocMt23DYgDLfdo@g1OEVsR3qCRKixT5MIV50CWKSj/T9IjUUQwKVlZdykYxblTtgBgRorQh2QMRN51uTXCd534tWzkg1lyzZeASetDpOowJixPCvy9CaCk2OySlY2iAUxKuAC629AxTp2EFgwxq5Svk3GKK4HJT2NzYyvnu3ZNKiA5J9ZPh2rH8eJj1xN4thV87Mxcr6j9t997jvPW/jXZ07Oiucv "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50~~ 46 bytes
```
®_ż+¥"SƝż€"Jż‘$$ḞṖ
ZJḤ©Żż‘$;€þJ;ÇẎfƇ@Ẏ¥€`Q$ÐLL
```
[Try it online!](https://tio.run/##y0rNyan8///Quvije7QPLVUKPjb36J5HTWuUvIBUwwwVlYc75j3cOY0ryuvhjiWHVh7dDRG2Bio5vM/L@nD7w119acfaHYDUoaVAwYRAlcMTfHz@u1s/aphzaJuCrp3Co4a5QHVcQP2PGmZ6PNyx2ORwO1Bl1qPGfYe2Hdr2/380V3S0gY6BjqGOYawOl0K0oQ6YB2ZDxA1igZzoaEMoBeRD1MHUwNXCFYAMg2jVgRqNZDhMHgHhBuog60WWM9BB6DRAmIGkzxBhE9QD@ByDMA7FCGSrURyCHDLYHIJFlSGSChR1SB4yQDERtypDLCpRA8cQzUZUVeCgwAh1FKUGaLFgoGOAESgGSHGF6kkMS@HJB1vwG2DEuwGWwIKbi5YC0CMB6gaUoMDwGzxYY7liAQ "Jelly – Try It Online")
A full program taking a matrix as its input with `-0.5` as `/` and `0.5` as `\`. Returns an integer with the number of pieces.
Full explanation to follow, but works by generating a list of all the pairs of connected cells, and then merging overlapping sets until there’s no change. The final number of sets is the desired answer.
] |
[Question]
[
# Primes are everywhere...
they hide inside Pi
3.141592653**58979**3238**462643**3832**795028841**971693993751
Let's get those primes!
# The Challenge
Given as input an integer `n>0`, find out how many primes are hidden inside the first `n` digits of `Pi`
# Examples
For `n=3` we should search for primes in `[3,1,4]`. There are 2 Primes `(3,31)`, so your code should output `2`
For `n=10` , the first 10 digits are `[3,1,4,1,5,9,2,6,5,3]` and your code should output `12` because `[2, 3, 5, 31, 41, 53, 59, 653, 4159, 14159, 314159, 1592653]` were hidden (and found!)
# Test Cases
input -> output
```
1->1
3->2
13->14
22->28
42->60
50->93
150->197
250->363
500->895
```
# Rules
Your code must be able to **find all primes at least for `n=50`**
Yes, you can **hardcode the first 50 digits** of `Pi` if you like
**Entries hardcoding the answers are invalid**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").Shortest answer in bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
-2 bytes thanks to Adnan (`p` vectorises)
```
<žsþŒÙpO
```
**[Try it online!](https://tio.run/##MzBNTDJM/f/f5ui@4sP7jk46PLPA//9/Q2MA "05AB1E – Try It Online")** (will work up to n=98413 but will be very slow even for n=50 due to the need to test such large numbers for primality - TIO times out at 60 seconds for n=50.)
### How?
```
<žsþŒÙpO - implicitly push input, n
< - decrement = n-1
žs - pi to that many decimal places (i.e. to n digits)
þ - only the digits (get rid of the decimal point)
Œ - all sublists
Ù - unique values
p - is prime? (vectorises) 1 if so, 0 otherwise
O - sum
- implicitly print the top of the stack
```
[Answer]
# Mathematica, 76 bytes
```
Tr[1^Union@Select[FromDigits/@Subsequences@#&@@RealDigits[Pi,10,#],PrimeQ]]&
```
[Answer]
# Mathematica, ~~104~~ ~~97~~ 90 bytes
```
Length@DeleteDuplicates@Select[FromDigits/@Subsequences@First@RealDigits[Pi,10,#],PrimeQ]&
```
Hahahaha, I managed to make this work. I have no idea how to use Mathematica. XD
Input:
```
[50]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~274~~ ~~237~~ ~~207~~ ~~194~~ 189 bytes
*-37 bytes thanks to Wheat Wizard! -14 bytes thanks to Mr.Xcoder.*
Hardcodes the first 50 digits of *pi* but manually computes everything else.
```
x=int(input());l="31415926535897932384626433832795028841971693993751"[:x]
print(sum(all(i%m for m in range(2,i))for i in{int(i)for w in range(x)for i in[l[j:j-~w]for j in range(x-w)]}-{1}))
```
[Try it online!](https://tio.run/##TY3LCoMwFET3/YogFBKoYHLzuha/RFy46COiUayiReyvp9VF2@WcOcx0z@HeeghhzpwfqPPdOFDGznUWAZdcodAKlEWDIMBKLbQEsCAMqkRYKzkarhEQwSge5elcHLp@W3qMDS3rmrpjQ65tTxriPOlLf7tQcXKMbcx92LLf7nH6KfO3z@u8Sqv4NRUbqf6UeGLFGi98ZSwEnrwB "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~59~~ 32 bytes
*-27 bytes thanks to Erik the Outgolfer.*
```
“!⁶⁷¬,6½ạEC.wʠ€Ẉ!+Ẉfṭ¡’Ṿḣ³ẆVQÆPS
```
[Try it online!](https://tio.run/##AUoAtf9qZWxsef//4oCcIeKBtuKBt8KsLDbCveG6oUVDLnfKoOKCrOG6iCEr4bqIZuG5rcKh4oCZ4bm@4bijwrPhuoZWUcOGUFP///8xMA "Jelly – Try It Online")
## Explanation
```
“...’Ṿḣ³ẆVQÆPS
“...’ compressed string that evaluates to first 50 digits of pi (314159...)
Ṿ uneval; stringify
ḣ³ first n characters of the string where n is the first command-line argument
Ẇ all sublists
V convert all elements to integers
Q deduplicate
ÆP convert all prime elements to 1 and others to 0
S sum
```
[Answer]
# R, ~~156~~ 123 bytes
```
cat(cumsum(c(1,1,0,1,1,4,1,0,0,3,0,0,2,7,3,1,0,3,0,0,0,0,0,0,4,1,0,6,0,3,2,0,0,0,0,0,0,4,3,3,6,0,4,8,2,5,3,6,0,5))[scan()])
```
Super interesting solution. Working on a proper one.
Saved 33 bytes thanks to @Giuseppe.
# R (+ numbers and gmp), 198 bytes
```
function(n,x=unique(gmp::as.bigz(unlist(sapply(1:n,function(x)substring(gsub("[.]","",numbers::dropletPi(50)),x,x:n))))))min(length(x),sum(sapply(sapply(x[x>0&!is.na(x)],gmp::factorize),length)==1))
```
Proper solution. Takes `n` as input.
Uses `numbers::dropletPi(50)` to generate the first 50 decimal places of pi. `gsub` removes the decimal point. `substring` takes every possible substring (surprise surprise) of pi up to `n`.
The returned list is flattened and converted to `gmp`'s `bigz` format. This format is required to store integers of length 50. `unique` takes the unique values of that vector. This result gets stored in `x`.
Then we check for primality. This is tricky, because there are a bunch of edge-cases and annoyances:
* For high `n`, there is a `0` in pi. This leads to substrings with a leading zero. `as.bigz` produces `NA`s with that, which have to be removed.
* On a similar note, the substring `"0"` will crash `gmp::factorize`, so has to be removed as well.
* For `n=1`, `x = 3`. Which in itself is ok, but the `bigz` representation of `3` is iterable, so `sapply` will get confused and report 16 primes. To this end we take the minimum of the length of the vector `x`, and the amount of primes in it.
* `gmp::isprime` can't seem to reliably handle the large numbers reliably. So instead we use `gmp::factorize` and check of the length of the output is 1.
So in all, we remove `0` and `NA` from `x`. We factorize all of `x` and check for the length. We count the number of occurrences of `1` and return the `min(occurences, length(x))`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
#ṗumdQ↑İπ
```
[Try it online!](https://tio.run/##yygtzv7/X/nhzumluSmBj9omHtlwvuH///@GBgA "Husk – Try It Online")
Freezes beyond n=10 on tio. Reverse of the 05AB1E program.
] |
[Question]
[
# Overview
Some of you might be aware of the [Kolakoski Sequence](https://en.wikipedia.org/wiki/Kolakoski_sequence) ([A000002](http://oeis.org/A000002)), a well know self-referential sequence that has the following property:
[![The coolio Kolakoski property, yo.](https://i.stack.imgur.com/KoIk7.jpg)](https://i.stack.imgur.com/KoIk7.jpg)
It is a sequence containing only 1's and 2's, and for each group of 1's and twos, if you add up the length of runs, it equals itself, only half the length. In other words, the Kolakoski sequence describes the length of runs in the sequence itself. It is the only sequence that does this except for the same sequence with the initial 1 deleted. (This is only true if you limit yourself to sequences made up of 1s and 2s - Martin Ender)
---
# The Challenge
The challenge is, given a list of integers:
* Output `-1` if the list is NOT a working prefix of the Kolakoski sequence.
* Output the number of iterations before the sequence becomes `[2]`.
---
# The Worked Out Example
Using the provided image as an example:
```
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1] # Iteration 0 (the input).
[1,2,2,1,1,2,1,2,2,1,2] # Iteration 1.
[1,2,2,1,1,2,1,1] # Iteration 2.
[1,2,2,1,2] # Iteration 3.
[1,2,1,1] # Iteration 4.
[1,1,2] # Iteration 5.
[2,1] # Iteration 6.
[1,1] # Iteration 7.
[2] # Iteration 8.
```
Therefore, the resultant number is `8` for an input of `[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1]`.
`9` is also fine if you are 1-indexing.
---
# The Test Suite (You can test with sub-iterations too)
```
------------------------------------------+---------
Truthy Scenarios | Output
------------------------------------------+---------
[1,1] | 1 or 2
[1,2,2,1,1,2,1,2,2,1] | 6 or 7
[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1] | 8 or 9
[1,2] | 2 or 3
------------------------------------------+---------
Falsy Scenarios | Output
------------------------------------------+---------
[4,2,-2,1,0,3928,102904] | -1 or a unique falsy output.
[1,1,1] | -1
[2,2,1,1,2,1,2] (Results in [2,3] @ i3) | -1 (Trickiest example)
[] | -1
[1] | -1
```
If you're confused:
**Truthy:** It will eventually reach two without any intermediate step having any elements other than `1` and `2`. – `Einkorn Enchanter 20 hours ago`
**Falsy:** Ending value is not `[2]`. Intermediate terms contain something other than something of the set `[1,2]`. A couple other things, see examples.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count will be the victor.
[Answer]
# [Haskell](https://www.haskell.org/), ~~126~~ ~~87~~ ~~79~~ ~~76~~ 75 bytes
*39 bytes saved thanks to Ørjan Johansen*
```
import Data.List
f[2]=0
f y@(_:_:_)|all(`elem`[1,2])y=1+f(length<$>group y)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrLdoo1taAK02h0kEj3goINWsSc3I0ElJzUnMTog11jGI1K20NtdM0clLz0ksybFTs0ovySwsUKjX/5yZm5llZefpraHKBmLYFRZl5JSppCtFGQF3/AQ "Haskell – Try It Online")
This errors on bad input.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
[Dg2‹#γ€gM2›iX]2QJiNë®
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2iXd6FHDTuVzmx81rUn3BbJ3ZUbEGgV6ZfodXn1oHVCBoY6hjhEQGoIxgg3jAclYAA "05AB1E – Try It Online")
**Explanation**
```
[ # start a loop
D # duplicate current list
g2‹# # break if the length is less than 2
γ # group into runs of consecutive equal elements
€g # get length of each run
M2›iX # if the maximum run-length is greater than 2, push 1
] # end loop
2QJi # if the result is a list containing only 2
N # push the iteration counter from the loop
ë® # else, push -1
# implicitly output top of stack
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
ŒgL€$ÐĿµẎḟ1,2ȯL_2
```
[Try it online!](https://tio.run/##y0rNyan8///opHSfR01rVA5POLL/0NaHu/oe7phvqGN0Yr1PvNH///@jgWwgNNQxBJNGSCRExDAWAA "Jelly – Try It Online")
[Answer]
# SCALA, 290(282?) chars, 290(282?) bytes
It took me sooo loong ... But I'm finally done!
with this code :
```
var u=t
var v=Array[Int]()
var c= -1
var b=1
if(!u.isEmpty){while(u.forall(x=>x==1|x==2)){c+=1
if(u.size>1){var p=u.size-1
for(i<-0 to p){if(b==1){var k=u(i)
v:+=(if(i==p)1 else if(u(i+1)==k){b=0
if(p-i>1&&u(i+2)==k)return-1
2}else 1)} else b=1}
u=v
v=v.take(0)}else if(u(0)==2)return c}}
c
```
I don't know if I should count the `var u=t` into the bytes, considering I do not use `t` during the algorithm (the copy is just to get a modifyable `var` instead of the parameter `t` considered as `val` - thanks *ScaLa*).
Please tell me if I should count it.
Hard enough. [Try it online!](https://tio.run/##lZGxboMwEIbn@incDJEtAsJuhibqIWXo0KFPEGVwiKO6ULDA0KSUZ6cGhoSkpKqQDnP3/f@djzwUsWjS7bsMDX4VKsHyYGSyy/FK6wrd7eQeR2ksorTMI0XMcpVl4rh@ScyGLm2EqilFhgswqH2XcKoT2qVCwC7rTltgSO3JfeGp/PlDmyOtPt9ULEnh7dNMxDE5QHAAYN82cEqr0OkVhZerLxkwWrU2Gvpv62plRD25PjYp1rSy6NbKeyyCgig7wtIBYgsKQFOGZZxL3FoS5TAKENFqC37bRLsqYNNpW@BdIZOmyBLbhdeditG6l9t71KiAEpVQekZEkvi0Phn7tJ2@V@OwrlHY1AjpTCUmTshkzTfYDfDEOVtrtzRir0zPODZjY6QtXbJ8nL3y5faxFl3szje0l@ifXoPMf5yHwmGfuU26bd6fPSz444z5fOHPx8x/p6@2e3O/lxMMxh39g@fQUD8maam6@QE)
PS : I was thinking of doing it recursively, but I'll have to pass a counter as a parameter of the true recursive "subfunction" ; this fact makes me declare two functions, and these chars/bytes are nothing but lost.
EDIT : I had to change (?) because we're not sure we should take in count `[1]` case. So [here](https://tio.run/##lZHPjpswEMbP9VO4OUS2EiLs7mE36iDl0EMPfYIoqhyvo/VCAYGhSV0/ezrAShuyJasVkjEzv@@bP9RaZepc7J@NdvSHsjk1R2fyx5puytKTT4/mQNMiU2nR1qllbr2pKnXafs/djq/xBH9uVUUbcKR7t/CaZ7wPaaCR6G97EMQe2OdmZetvv0p34t5VJ@@Y4EErp5@8VrWhPyGpjGuqnCLsWMwBJI@pyTAXiUB@P9nMsGZ1KCqVZewIyRFA/D12GPd6MVRpVrX9YxLBfVe6hOEbO0EZs1@jmLqCltwjukf5gKXQMIttrxfAMGEBSi6Gyp0lswuB3aTc7yHuipSRTcR83iVknxgaxyoy9CqcbJDj7IE00JIW2pVTqcG5wqvxMOTL2DoEos@BkLKyuctyNtuKHY0SOltc/Ip@0bg6zi84OcXJMSeW045Lcc3KafaNr8QHLfqzv9/QXqPveo0iH3EeC8d17jAYdfF4@eVB3i9FLB/iuynz/9Nvtntzv9cdjNqd/IOX0Fg/JemocP4H) is the modified code :
```
var u=t
var v=Array[Int]()
var c= -1
var b=1
if(!u.isEmpty){try{t(1)}catch{case _=>return if(t(0)==2)0 else -1}
while(u.forall(x=>x==1|x==2)){c+=1
if(u.size>1){var p=u.size-1
for(i<-0 to p){if(b==1){var k=u(i)
v:+=(if(i==p)1 else if(u(i+1)==k){b=0
if(p-i>1&&u(i+2)==k)return-1
2}else 1)} else b=1}
u=v
v=v.take(0)}else if(u(0)==2)return c}}
c
```
It's not optimized (I have a duplicate "out" for the same conditions : when I get to `[2]` and when param is `[2]` is treated separatedly).
NEW COST = 342 (I didn't modify the title on purpose)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ ~~25~~ ~~22~~ ~~21~~ 20 bytes
```
FQœ-2R¤
ŒgL€µÐĿṖ-LÇ?
```
[Try it online!](https://tio.run/##y0rNyan8/98t8OhkXaOgQ0u4jk5K93nUtObQ1sMTjux/uHOars/hdvv///9HG@oYAaGhjiGYNEIiISKGsQoKAA "Jelly – Try It Online")
This code actually wasn't working correctly until 20 bytes and I didn't even notice; it was failing on the `[2,2]` test case. Should work perfectly now.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒɠƬµ2Wea’ỊȦƊ
```
[Try it online!](https://tio.run/##y0rNyan8///opJMLjq05tNUoPDXxUcPMh7u7Tiw71vX/cPujpjVHJz3cOeP//2hDHcNYHSBpBIRANpgEs7GLoohA1QBJEyBfFyRkoGNsaWShY2hgZGlgApaGKEMxCMgHScUCAA "Jelly – Try It Online")
## How it works
```
ŒɠƬµ2Wea’ỊȦƊ - Main link. Takes a list L on the left
Ƭ - Until reaching a fixed point, keeping each step:
Œɠ - Get the lengths of consectuively equal groups of elements
µ - Call this list S and use it as the argument
2W - Yield [2]
e - Is [2] in S?
Ɗ - Last 3 links as a monad f(S):
’ - Decrement every integer in S
Ị - Insignificant? Replace 0 and 1 with 1, everything else 0
Ȧ - Any and all? S is non-empty and has no zeros
a - Both are true?
```
[Answer]
# **JavaScript, ~~146~~ 142 bytes**
First try in code golfing, it seems that the "return" in the larger function is quite tedious...
Also, the checking of b=1 and b=2 takes up some bytes...
Here's the code:
```
f=y=>{i=t=!y[0];while(y[1]){r=[];c=j=0;y.map(b=>{t|=b-1&&b-2;if(b-c){if(j>0)r.push(j);c=b;j=0}j++});(y=r).push(j);i++}return t||y[0]-2?-1:0^i}
```
Explanation
```
f=y=>{/*1*/} //function definition
//Inside /*1*/:
i=t=!y[0]; //initialization
//if the first one is 0 or undefined,
//set t=1 so that it will return -1
//eventually, otherwise i=0
while(y[1]){/*2*/} //if there are 2+ items, start the loop
//Inside /*2*/:
r=[];c=j=0; //initialization
y.map(b=>{/*3*/}); //another function definition
//Inside /*3*/:
t|=b-1&&b-2; //if b==1 or b==2, set t=1 so that the
//entire function returns -1
if(b-c){if(j>0)r.push(j);c=b;j=0} //if b!=c, and j!=0, then push the
//count to the array and reset counter
j++ //counting duplicate numbers
(y=r).push(j);i++ //push the remaining count to the array
//and proceed to another stage
return t||y[0]-2?-1:0^i //if the remaining element is not 2, or
//t==1 (means falsy), return -1,
//otherwise return the counter i
```
Test data (using the given test data)
```
l=[[1,1],[1,2,2,1,1,2,1,2,2,1],[1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1],[1,2],[4,2,-2,1,0,3928,102904],[1,1,1],[2,2,1,1,2,1,2],[]];
console.log(l.map(f));
//Output: (8) [1, 6, 8, 2, -1, -1, -1, -1]
```
Edit 1: 146 -> 142: Revoking my edit on reducing bytes, because this affects the output; and some edit on the last statement
[Answer]
## JavaScript (ES6), ~~127~~ ~~126~~ ~~95~~ 80 bytes
```
g=(a,i,p,b=[])=>a.map(x=>3>x&0<x?(x==p?b[0]++:b=[1,...b],p=x):H)==2?i:g(b,~~i+1)
```
0-indexed. Throws `"ReferenceError: X is not defined"` and `"InternalError: too much recursion"` on bad input.
### Test cases
```
g=(a,i,p,b=[])=>a.map(x=>3>x&0<x?(x==p?b[0]++:b=[1,...b],p=x):H)==2?i:g(b,~~i+1)
function wrapper(testcase) {
try {console.log(g(testcase))} catch(e) {
console.log("Error")
}
}
wrapper([1,1])
wrapper([1,2,2,1,1,2,1,2,2,1])
wrapper([1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1])
wrapper([1,2])
wrapper([4,2,-2,1,0,3928,102904])
wrapper([1,1,1])
wrapper([2,2,1,1,2,1,2])
wrapper([])
wrapper([1])
```
[Answer]
# [Scala 3 (compile-time)](https://dotty.epfl.ch/docs/index.html), 460 bytes
This may be the longest answer here, but it's also the fastest one here...because it works at compile time.
```
import compiletime.ops.int._
type r[T,P]=T match{case h*:t=>r[t,h*:P]case E=>P}
type E=EmptyTuple
type F[K,R,L,S,P,I]=K match{case E=>L-S match{case 0=>R match{case E=>0 case _=>F[r[R,E],E,0,0,0,I+1]}case _=>0}case P*:_=>0
case 1*:1*:t=>F[t,2*:R,L+2,S+2,1,I]case 1*:t=>(t,R)match{case(E,E)=>0 case _=>F[t,1*:R,L+1,S+1,1,I]}case 2*:2*:t=>F[t,2*:R,L+2,S+2,2,I]case 2*:t=>(t,R)match{case(E,E)=>I+1 case _=>F[t,1*:R,L+1,S+1,2,I]}case _=>0}
type G[K]=F[K,E,0,0,0,0]
```
[Try it in online!](https://scastie.scala-lang.org/XnwSWKZ7STiR8iE6zsPW5w)
You can invoke it as `G[1 *: 2 *: EmptyTuple]` (actually, just `G[(1, 2)]` *should* also work, but for whatever reason, it's not working right now. I'll fix it later, though). It's 1-indexed, and it returns 0 for falsy inputs.
[Answer]
## Clojure, 110 bytes
```
#(if-not(#{[][1]}%)(loop[c % i 0](if(every? #{1 2}c)(if(=[2]c)i(recur(map count(partition-by + c))(inc i))))))
```
A basic `loop` with a pre-check on edge cases. Returns `nil` for invalid inputs. I did not know `(= [2] '(2))` is `true` :o
[Answer]
# Python 2, 146 bytes (function only)
```
f=lambda l,i=0:i if l==[1]else 0if max(l)>2or min(l)<1else f([len(x)+1for x in"".join(`v!=l[i+1]`[0]for i,v in enumerate(l[:-1])).split("T")],i+1)
```
Returns 0 on falsy input (ok since it's 1-indexed). Simply use it like this:
```
print(f([1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1]))
```
[Answer]
## Mathematica, 82 bytes
```
FixedPointList[#/.{{2}->T,{(1|2)..}:>Length/@Split@#,_->0}&,#]~FirstPosition~T-1&
```
`Function` which repeatedly replaces `{2}` with the undefined symbol `T`, a list of (one or more) `1`s and `2`s with the next iteration, and anything else with `0` until a fixed point is reached, then returns the `FirstPosition` of the symbol `T` in the resulting `FixedPointList` minus `1`. Output is `{n}` where `n` is the (`1`-indexed) number of iterations needed to reach `{2}` for the truthy case and `-1+Missing["NotFound"]` for the falsy case.
If the output must be `n` rather than `{n}`, it costs three more bytes:
```
Position[FixedPointList[#/.{{2}->T,{(1|2)..}:>Length/@Split@#,_->0}&,#],T][[1,1]]-1&
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~184 163~~ 156 bytes
* @Felipe Nardi Batista saved 21 bytes!!!! thanks a lot!!!!
* **Halvard Hummel saved 7 bytes!! thanks**
# [Python 2](https://docs.python.org/2/), 156 bytes
```
a,c=input(),0
t=a==[]
while 1<len(a)and~-t:
r,i=[],0
while i<len(a):
j=i
while[a[j]]==a[i:i+1]:i+=1
r+=[i-j]
a=r;c+=1;t=any(x>2for x in a)
print~c*t+c
```
[Try it online!](https://tio.run/##bY7BasMwDIbP0VP4lmRxIPZ6WNOqT7Gb8cG4HlUoTjAuSy999UxNcykMwY/06Uf6p3u@jFEvfjwHLMtycdIjxemWq1p2kNEhGgu/F7oGoY7XECtXu3h@tLkHkSTxln3iZaDN0EMxIEGxUuPMYC2iM9RToywLKihSg4bawYJwmA6e2YG/xXs1n/TPmMQsKApXw5Qo5of/yI1fOOAW5TvdAgcIc/DVM3u9GCWVBVbNxf2qa/8/fSObh3XHc/tEnfzc6y@pOr3vduv6ZXs7xLP9Aw "Python 2 – Try It Online")
Explanation:
```
a,c=input(),0 #input and initialize main-counter
t=a==[] #set t to 1 if list's empty.
while len(a)>1: #loop until list's length is 1.
r,i=[],0 #Initialize temp. list and
#list-element-pointer
while i<len(a): #loop for the element in list
j=0 #set consecutive-item-counter to 0
while(i+j)<len(a)and a[i]==a[i+j]:j+=1 #increase the consec.-counter
r+=[j];i+=j #add the value to a list, move the
#list-element-pointer
a=r;c+=1;t=any(x>2for x in a) #update the main list, increase t
#the counter, check if any number
if t:break; #exceeds 2 (if yes, exit the loop)
print[c,-1][t] #print -1 if t or else the
#counter's
#value
```
[Answer]
# R, 122 bytes
```
a=scan()
i=0
f=function(x)if(!all(x%in%c(1,2)))stop()
while(length(a)>1){f(a)
a=rle(a)$l
f(a)
i=i+1}
if(a==2)i else stop()
```
Passes all test cases. Throws one or more errors otherwise. I hate validity checks; this code could have been so golfed if the inputs were nice; it would be shorter even in case the input were a sequence of 1’s and 2’s, not necessarily a prefix of the Kolakoski sequence. Here, we have to check both the initial vector (otherwise the test case `[-2,1]`) would have passed) and the resulting vector (otherwise `[1,1,1]` would have passed).
[Answer]
# [Python 2](https://docs.python.org/2/), 122 bytes
```
def f(s,c=2,j=0):
w=[1]
for i in s[1:]:w+=[1]*(i!=s[j]);w[-1]+=i==s[j];j+=1
return(w==[2])*c-({1,2}!=set(s))or f(w,c+1)
```
[Try it online!](https://tio.run/##hU29DoMgEN59CrqBYsJRh6q5JyFMVlIctBEa0jR9dopOxQ7NJZf7fu/@9LdlljFeR0MMdXxAyScUrCtIQAW6IGZZiSV2Jk5Bp7tQbXRJ7QmdmjTrg6pBV2hxx/1UIRRkHf1jnWlAVFKzcqjpC7h8p8zoqWMsdRoa@FABi/fVzp4aqoCDZqz4wjJNYve93//0jPlxZ7hJnnqzCX5u5YWDkK1oDpFjSfYwU/JgQvED "Python 2 – Try It Online")
# [Python 3](https://docs.python.org/3/), 120 bytes
```
def f(s,c=2,j=0):
w=[1]
for i in s[1:]:w+=[1]*(i!=s[j]);w[-1]+=i==s[j];j+=1
return(w==[2])*c-({1,2}!={*s})or f(w,c+1)
```
[Try it online!](https://tio.run/##hU29DoMgEN55CrqBYuKhQ9XckxAmKykOaNSGNMZnt@hU7NBccrnv98b38hxcse@PzlDDZtGiFD3mvCbUowJNqBkmaql1dFZQ69qnB50we8NZ9Zo3XmWgU7R44qZPEQiduuU1OeYRldQ8aTO2gpDbDddk3nhoNMyLNgW@j5N1CzNMgQDNOfnCMkxgz33e//SI@XFHuAye7LDloqjkXUAuq7y8RK4l0cNIiYMB7R8 "Python 3 – Try It Online")
# Explanation
A new sequence (w) is initialized to store the next iteration of the reduction. A counter (c) is initalized to keep track of the number of iterations.
Every item in the original sequence (s) is compared to the previous value. If they are the same, the value of the last item of (w) is increased with 1. If they are different, the sequence (w) is extended with [1].
If w==[2], the counter (c) is returned. Else, if the original sequence (s) contains other items than 1 and 2, a value -1 is returned. If neither is the case, the function is called recursively with the new sequence (w) as (s) and the counter (c) increased by 1.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
äE⌐+É7∩ΦΓyr╔ßΣ·φƒÇe►ef%I»
```
[Run and debug it](https://staxlang.xyz/#p=8445a92b9037efe8e27972c9e1e4faed9f80651065662549af20&i=%5B1,1%5D%0A%5B1,2,2,1,1,2,1,2,2,1%5D%0A%5B1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1%5D%0A%5B1,2%5D%0A%5B4,2,-2,1,0,3928,102904%5D%0A%5B1,1,1%5D%0A%5B2,2,1,1,2,1,2%5D%0A%5B1%5D%0A%5B%5D&m=2)
Tried with a generator, but it seems like a while loop is shorter.
[Answer]
# [R](https://www.r-project.org/), ~~93~~ 92 bytes
*Edit: -1 byte thanks to Giuseppe*
```
f=function(x)`if`(sum(x|1)<2,(-1)^(sum(x)!=2),`if`(!all(x%in%1:2),-1,(y=f(rle(x)$l))+(y>0)))
```
[Try it online!](https://tio.run/##jY7tCoIwFIb/exVGCefQBM8UymhdSviBwkAN/ACF7n1tkyhDIQZj5zzPy7tWyb5o014@mk6oUpRDk5sBRkxkmUA31DA@Ca@cgU94nxe4ExyZFXZpVcHoycaji975xGASJbRVobVDhXiE6RYgokpFDsQI3b3LnU8rpOjMiOujBXvbt1FP/6mLjQ3G60GDwh/kZJpFOuqbdMDCmJ8ZBTwOIqP79O1naHV696zSxf82rGaoi1bmsF2xStQL "R – Try It Online")
Returns 1-based number of iterations for truthy input, and `-1` for all falsy inputs. This needed quite careful input testing, especially for the last two test cases...
**Commented:**
```
f=function(x) # recursive function with argument x
`if`(sum(x|1)<2, # if there's one (or less) element left
(-1)^(sum(x)!=2), # return 1 if it's equal to 2, -1 otherwise
`if`(!all(x%in%1:2), # if any element isn't 1 or 2
-1, # return -1
(y=f( # otherwise recursively call self with
rle(x)$l)) # lengths of groups of digits in x
+(y>0))) # if result is positive, return result +1
# otherwise return result (which must be -1)
```
---
# [R](https://www.r-project.org/), ~~74~~ 66 bytes
```
f=function(x)`if`(sum(x)==2&x==2,1,if(all(x%in%1:2))f(rle(x)$l)+1)
```
[Try it online!](https://tio.run/##lY7tCsIgFIb/7yqEtVAymG5QC7yXfaAgbDqcxrp600XUYkH9ORx9n@ecY7y03DRWajUxL5hwqosPOKNaihpObggtY3Q/h4IJlgI2fQ/nTKqMXChCApqeB2bXowNBvmEdJJggkAKavGbDBiWPiOI4hix16SN6@g1d/SxitS3GqPiIkjZkZVCP0c5xUdEzJjmt8jLiQGmgnR2dffdatGjkuc9w64yaAB9GewNX3lltNvjV5X94EeXGhCwFG1d8j/0d "R – Try It Online")
...but then I read the comments more carefully and realised that it's Ok to output nothing, or rubbish, or to error for falsy inputs. That makes it much easier!
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 30 bytes
```
λĠvL&›Dƛ2>;A$Ḣ∧[x|u£];†h2=[¥|u
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BB%C4%A0vL%26%E2%80%BAD%C6%9B2%3E%3BA%24%E1%B8%A2%E2%88%A7%5Bx%7Cu%C2%A3%5D%3B%E2%80%A0h2%3D%5B%C2%A5%7Cu&inputs=%5B2%2C2%2C1%2C1%2C2%2C1%2C2%5D&header=&footer=)
A big mess.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~81~~ 77 bytes
```
f=->a,i=1{a[1]&&a-[1,2]==[]?f[a.chunk{|x|x}.map{|x,y|y.size},i+1]:a==[2]?i:0}
```
[Try it online!](https://tio.run/##ldHdaoMwFAfw@z3FAaFsLBFPlK0WbF9idyEXWYks9MuqAV312V2i7ebGWqwBCSG/cw7/5Oa97ro0oUtJdIInyVHMZpJyJEwkCRerlEt//WH2m1NTNVXr72Rmd6Ruar/Qn6ol@hnFQtq7TKz0Imi7DFJuPQoBUz4PEA45sIezY3ZZ3f/7/ZU6Hrw493rV/Tr5qeLB3Ln4202ekzkXDm6qci5wDs/ujn7jXG4l8deFzkWDi6yjLoCAhDGbEwxYHET/FfKA9g0lmL0@GgWp3BY1HEyZmdK/pIWTp6A4mvzyLjdtP8HjW67XG62KElQld9lWPQ11Jgc@6o13vBLF7gs "Ruby – Try It Online")
**Edit:** Saved 4 bytes by converting to recursive lambda.
Returns 1-indexed number of iterations or 0 as falsey.
Makes use of Ruby enumerable's chunk method, which does exactly what we need - grouping together consecutive runs of identical numbers. The lengths of the runs constitute the array for the next iteration. Keeps iterating while the array is longer than 1 element and no numbers other than 1 and 2 have been encountered.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 45 bytes
```
L?||qb]1!lb-{b,1 2_1?q]2b1Z.V0IKy~QhMrQ8*KhbB
```
[Try it online!](https://tio.run/##K6gsyfj/38e@pqYwKdZQMSdJtzpJx1DBKN7QvjDWKMkwSi/MwNO7si4ww7co0ELLOyPJ6f//aEMdIyA01DEEk0ZIJETEMBYA "Pyth – Try It Online")
This is probably still golfable.
It's definitely golfable if `.?` worked the way I hoped it would (being an `else` for the innermost structure instead of the outermost)
```
L?||qb]1!lb-{b,1 2_1?q]2b1Z # A lambda function for testing an iteration of the shortening
L # y=lambda b:
? # if
qb]1 # b == [1]
| !lb # or !len(b)
| {b # or b.deduplicate()
- ,1 2 # .difference([1,2]):
_1 # return -1
?q]2b1Z # else: return 1 if [2] == b else Z (=0)
.V0 # for b in range(0,infinity):
IKy~Q # if K:=y(Q := (applies y to old value of Q)
hM # map(_[0],
rQ8 # run_length_encode(Q)):
*Khb # print(K*(b+1))
B # break
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 71 bytes
```
$_.=$";s/(. )\1*/$&=~y|12||.$"/ge&$.++while/^([12] ){2,}$/;$_=/^2 $/*$.
```
[Try it online!](https://tio.run/##BcFbCsIwEAXQrYRyKX3YmUygXyFLcAVq@xW0UGxoBBGjS3c8J8V9HVUxU0DlMzdk2rN0jDp8X0VcKYSKr7EG9f3ztqyRp@Yk7mLatzt8wB5z4MkZcAdSjxysV2fkt6XHst2zDseRrFgd0h8 "Perl 5 – Try It Online")
`1`-indexed. Outputs `0` for falsy.
] |
[Question]
[
# **Balancing Act**
**Overview**
Given an input of 3 single-digit positive integers representing a set of weights, output an ASCII representation of a seesaw with the weights placed on it so that it is in balance around a central pivot, taking lever effects into account.
Each number has a weight equal to its value. The torque of each number is the weight multiplied its the distance from the center in characters. For the seesaw to be in balance, the sum torque of the weights on the left of the seesaw must equal that of those on the right, like [this](https://upload.wikimedia.org/wikipedia/commons/c/c3/Lever_Principle_3D.png).
**Input**
3 integers in the range of 1-9. You can input the integers however is convenient, e.g. a tuple, 3 comma-separated values etc. However your program must be able to handle numbers input in any order (i.e. no assuming the values will be sorted). Duplicate numbers may be input (e.g. 2,3,2).
The inputs will always mathematically allow for a valid output, otherwise the input is not valid.
**Output**
The output should be a 2-line ASCII representation of the seesaw with the weights placed on it. On the first line are the digits, spaced in order to balance them on the seesaw.
Numbers may not be placed in the very center of the scale, where the distance and therefore the torque would be zero. Valid distances from the center range from 1-10 characters inclusive to the left or right of the pivot.
In the spaces unoccupied by the numbers are 18 underscore characters (a center underscore and 10 on each side, minus the 3 positions occupied by the numbers). On the last line is a single caret character aligned with the center of the scale, representing the pivot.
**Examples**
Input:
```
4,7,2
```
Output:
```
________7___42_______
^
```
7\*2 = 4\*2 + 2\*3
Numbers can be output on either side, for example this would also be valid:
```
_______24___7________
^
```
2\*3 + 4\*2 = 7\*2
Numbers can be placed anywhere on the scale as long as they balance, e.g:
Input:
```
3,1,5
```
Output:
```
_____5________1__3___
^
```
5\*5 = 1\*4 + 3\*7
or
```
____5________1_____3_
^
```
5\*6 = 1\*3 + 3\*9
or
```
____5___________1_3__
^
```
5\*6 = 1\*6 + 3\*8
etc
Your program only has to output one of the valid outputs. It does not have to output an error if the input is not valid.
**Notes**
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in bytes wins
* Program may be a stand-alone or a function that accepts the numbers as input and returns a string.
* Trailing newline and white-space on last line is optional
* If you don't know what a [seesaw](https://en.wikipedia.org/wiki/Seesaw) is, it's also known as a teeter-totter or a teeterboard.
[Answer]
# CJam, ~~40~~ ~~39~~ 38 bytes
```
q~21Ue]e!{21,Af-Aest.*:+!}=0'_erNAS*'^
```
[Try it online.](http://cjam.aditsu.net/#code=q~21Ue%5De!%7B21%2CAf-Aest.*%3A%2B!%7D%3D0'_erNAS*'%5E&input=%5B4%207%202%5D)
### How it works
```
q~ e# Read and evaluate the input.
21Ue] e# Append zeroes to achieve a length of 21.
e! e# Push all unique permutations.
{ }= e# Find the first permutation such that:
21, e# Push [0 ... 20].
Af- e# Subtract 10 from each.
Aest e# Replace the element at index 10 with the
e# current time (ms since epoch) to push
e# [-10 ... -1 <big number> 1 ... 10].
.* e# Multiply each number of the permutation
e# by the corresponding distance.
:+ e# Add the products.
e# The timestamp makes sure that this sum
e# is non-zero for a non-zero element in
e# the middle of the permutation.
! e# Push the logical NOT of the sum.
0'_er e# Replace zeroes with underscores.
NAS*'^ e# Push a linefeed, ten spaces and a caret.
```
[Answer]
# CJam, ~~46~~ 44 bytes
```
'_21*q~K,Am3m*{___&=*Afm1$.*:+!}=.{\t}NAS*'^
```
[Test it here.](http://cjam.aditsu.net/#code='_21*q~K%2CAm3m*%7B___%26%3D*Afm1%24.*%3A%2B!%7D%3D.%7B%5Ct%7DNAS*'%5E&input=%5B3%205%201%5D)
## Explanation
First, an observation: we never need to put two digits on the ends of the seesaw. Whenever that's a valid solution, there is at least one other valid solution (according to the pastebin in the comment on the challenge).
```
'_21* e# Push a string of 21 underscores.
q~ e# Read and eval input.
K, e# Push the array [0 1 .. 19 20]
Am e# Remove the 10. This is now an array of all valid positions on the seesaw.
3m* e# Get all 3-tuples of valid positions.
{ e# Select the first tuple for which the following block yields a truthy result.
___ e# Make three copies of the tuple.
&= e# Intersect the last two copies and check for equality with the first one.
e# This yields 1 if all positions are distinct, and 0 otherwise.
* e# Repeat the original tuple that many times. That is, if the positions are
e# distinct, leave the tuple unchanged. Otherwise, replace it with an empty array.
Afm e# Subtract 10 from each position to get its weight.
1$ e# Copy the input digits.
.* e# Take the pairwise product of weights and digits. If the weights are empty
e# (because they were not unique), this will just yield a list of the digits.
:+ e# Sum the weighted digits. If the weights were not unique, this will just sum
e# the digits and will always be positive.
! e# Logical NOT - give 1 if the sum was 0, or 0 otherwise.
}=
.{\t} e# For each pair of digit and position, replace that position in the underscore
e# string with the corresponding digit.
N e# Push a newline.
AS* e# Push ten spaces.
'^ e# Push a caret.
```
[Answer]
# Java, 519 414 321 bytes
```
static int f(int a,int b,int c){int i,j,k;for(i=-10;i<=10;i++)for(j=i+1;j<=10;j++)for(k=j+1;k<=10;k++){if(a*i+b*j+c*k==0&&i!=0&&j!=0&&k!=0){for(int q=0;q<21;q++){if(q==10+i)p(a);else if(q==10+j)p(b);else if(q==10+k)p(c);else p('_');}p("\n ^\n");return 0;}}return 0;}static void p(Object a){System.out.print(a);}}
```
My first attempt at golfing.
You can call it with `f(a,b,c)`.
Try it [here](http://ideone.com/RjpsBd)
**EDIT:** Used izlin method of check `(a*i+b*j+c*k)==0`
**EDIT:** Thanks, J Atkin for the golfing suggestions.
[Answer]
## Pyth, ~~67~~ ~~58~~ ~~53~~ 49 bytes
~~This feels a little on the huge side for Pyth, but I'm not nearly familiar enough with the language to be able to get this much smaller.~~ Sub 50 bytes, I'm finally happy with this!
```
V.c-KrT-011Z3FY.pQIqs*VNYZjkm?}dN@YxNd\_K+*dT\^.q
```
Input is expected as an array of integers, for example `[1,2,3]`. Try it [here.](https://pyth.herokuapp.com/?code=V.cK%2Bm_dJrT0J3FY.pQIqs*VNYZjkm%3F%7DdN%40YxNd%5C_S%2BKZ%2B*dT%5C%5E.q&input=%5B2%2C9%2C5%5D&debug=1)
Explaination:
```
V.c-KrT-011Z3FY.pQIqs*VNYZjkm?}dN@YxNd\_K+*dT\^.q
Implicit: Q = eval(input())
rT-011 Create range from 10 to -10
K Store in K
- Z Drop 0 from the above
V.c 3 For N in (combinations of the above of size 3)
FY.pQ For Y in (permutations of input)
*VNY Multiply each element in N by the corresponding element in Y
s Take the sum
Iq Z If it's equal to zero:
m K For d in K (K = [10, ..., -10])
?}dN Is d in N?
@YxNd If so, get corresponding value from Y
\_ Otherwise, get '_'
jk Join the resulting array into a string (implicit print)
+*dT\^ Join 10 spaces and '^', implicit print
.q Break all loops and exit
```
And finally, some example inputs and outputs:
```
[1,1,1] ->
1__________1_______1_
^
[2,9,5] ->
2____5_________9_____
^
[9,8,5] ->
5____8______________9
^
```
[Answer]
## C - ~~237~~ 228 Bytes
```
i,j,k;f(a,b,c){char o[]="_____________________\n ^";for(i=-10;i<9;i+=i+1?1:2){for(j=i+1;j<11;j+=j+1?1:2){for(k=j+1;k<11;k+=k+1?1:2){if((a*i+b*j+c*k)==0){o[i+10]=a+48;o[j+10]=b+48;o[k+10]=c+48;printf("%s",o);return;}}}}}
```
You can call it with `f(a,b,c)`.
Try it [here](http://ideone.com/eoSRtB).
Example outputs:
```
f(4,7,2):
4_____________7_2____
^
f(3,1,5)
3____1___________5___
^
```
[Answer]
## Python 2.7 ~~235~~ ~~226~~ 219 Bytes
```
def s(n,p=__import__("itertools").permutations):
l=["_"]*21
for p,q in[[(a,x+10),(b,y+10),(c,10-z)]for a,b,c in p(n,3)for x,y,z in p(range(1,11),3)if x!=y and a*x+b*y==c*z][0]:l[q]=`p`
return`l`[2::5]+"\n"+" "*10+"^"
```
[Testing](http://ideone.com/wEZDLI) it with some basic examples- `(1,1,1),(1,2,1),(3,1,5),(4,7,2)` results in- :
```
(1, 1, 1)
_______1___11________
^
(1, 2, 1)
_____1_____12________
^
(3, 1, 5)
________5__3_____1___
^
(4, 7, 2)
_2_________47________
^
```
Outputs for all possible inputs pasted [here](http://pastebin.com/3XwYeVzH)
[Answer]
# PHP, 278 bytes
A brute-force solution that uses a bunch of nested loops and a couple of tests.
```
$p=explode(',',$argv[$i=1]);for(;$i<=10;$i++)for($j=1;$j<=10;$j++)
for($k=1;$k<=10;$k++)if($j-$k)for($l=0;$l<3;$l++){$q=array_shift($p);
if($i*$q==$j*$p[0]+$k*$p[1]){$o=str_repeat('_',21);$o[10-$i]=$q;$o[10+$j]=$p[0];
$o[10+$k]=$p[1];echo($o."\n ^\n");}array_push($p,$q);}
```
As always, put it into a file (let's name it `seesaw.php`), join the lines (split here for readability), put the PHP marker (`<?php`) at the beginning of the file (technically, it is not part of the program) and you're good to go.
An example of execution:
```
$ php seesaw.php 9,2,1
_________9_2_____1___
^
_________9__2__1_____
^
_________9_1__2______
^
________9_____2_____1
^
________9______2__1__
^
________9_____1__2___
^
________9___1_____2__
^
_______9_________1__2
^
____2______9_1_______
^
___2_______9___1_____
^
__2________9_____1___
^
_2_________9_______1_
^
```
It generates and displays all the solutions (without reflections), but it does not strip the duplicates (when the input values contain duplicates).
[Answer]
# Julia, 154 bytes
```
f(a,b,c)=(x=replace(join(first(filter(p->p⋅[-10:-1,1:10]==0,permutations([a,b,c,zeros(Int,17)])))),"0","_");print(x[1:10]*"_"*x[11:20]*"\n"*" "^10*"^"))
```
Ungolfed + explanation:
```
function f(a,b,c)
# Create a 20-element array of the input with 17 zeros
z = [a,b,c,zeros(Int,17)]
# Get the set of all permutations of z such that the dot product
# of the permutation with the distances is 0
d = filter(p -> p ⋅ [-10:-1,1:10] == 0, permutations(z))
# Join the first element of d into a string and replace all of
# the zeros with underscores
x = replace(join(first(d)), "0", "_")
# Print the output
print(x[1:10] * "_" * x[11:20] * "\n" * " "^10 * "^")
end
```
[Answer]
# C, 252 (214) bytes
Call with a,b,c as arguments on command line.
```
e=48;main(_,v,x,y,z,a,b,c)char**v;{char s[]="_____________________\n ^";x=*v[1]-e;y=*v[2]-e;z=*v[3]-e;for(a=-1;a+11;--a)for(b=-10;b-11;++b)_=a*x+b*y,!b|b==a|_%z?0:(c=-_/z,c&c<11&c>-11?s[a+10]=x+e,s[b+10]=y+e,s[c+10]=z+e,puts(s),exit(0):0);}
```
If main can be ommitted, byte count drops to 214 for a function.
```
a,b,c;f(x,y,z){char s[]="_____________________\n ^";for(a=-1;a+11;--a)for(b=-10;b-11;++b)!b|b==a|(a*x+b*y)%z?0:(c=-(a*x+b*y)/z,c&&c<11&&c>-11?s[a+10]=x+48,s[b+10]=y+48,s[c+10]=z+48,puts(s),b=10,a=-b:0);}
```
Both use the same strategy of placing the first weight on the left, then scanning along possible second weight positions and calculating the third weight. This allows the removal of an inner loop.
] |
[Question]
[
In schools across the world, children type a number into their LCD calculator, turn it upside down and erupt into laughter after creating the word 'Boobies'. Of course, this is the most popular word, but there are many other words which can be produced.
All words must be less than 10 letters long, however (the dictionary does contain words long than this however, so you must perform a filter in your program). In this dictionary, there are some uppercase words, so convert the all words the lowercase.
Using, an English language dictionary, create a list of numbers which can be typed into an LCD calculator and makes a word. As with all code golf questions, the shortest program to complete this task wins.
For my tests, I used the UNIX wordlist, gathered by typing:
```
ln -s /usr/dict/words w.txt
```
Or alternatively, get it [here](https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt).
![](https://1.bp.blogspot.com/-gT-gcsMlWmo/Tj4zh0F1_0I/AAAAAAAAB7M/NuQW7C7jz3s/s1600/loose%2Bcalc.jpg)
For example, the image above was created by typing the number `35007` into the calculator and turning it upside down.
The letters and their respective numbers:
* *b*: `8`
* *g*: `6`
* *l*: `7`
* *i*: `1`
* *o*: `0`
* *s*: `5`
* *z*: `2`
* *h*: `4`
* *e*: `3`
Note that if the number starts with a zero, a decimal point is required after that zero. The number must not start with a decimal point.
I think this is MartinBüttner's code, just wanted to credit you for it :)
```
/* Configuration */
var QUESTION_ID = 51871; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
/* App */
var answers = [], page = 1;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
if (data.has_more) getAnswers();
else process();
}
});
}
getAnswers();
var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;
function shouldHaveHeading(a) {
var pass = false;
var lines = a.body_markdown.split("\n");
try {
pass |= /^#/.test(a.body_markdown);
pass |= ["-", "="]
.indexOf(lines[1][0]) > -1;
pass &= LANGUAGE_REG.test(a.body_markdown);
} catch (ex) {}
return pass;
}
function shouldHaveScore(a) {
var pass = false;
try {
pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
} catch (ex) {}
return pass;
}
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
answers = answers.filter(shouldHaveScore)
.filter(shouldHaveHeading);
answers.sort(function (a, b) {
var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
answers.forEach(function (a) {
var headline = a.body_markdown.split("\n")[0];
//console.log(a);
var answer = jQuery("#answer-template").html();
var num = headline.match(NUMBER_REG)[0];
var size = (headline.match(SIZE_REG)||[0])[0];
var language = headline.match(LANGUAGE_REG)[1];
var user = getAuthorName(a);
if (size != lastSize)
lastPlace = place;
lastSize = size;
++place;
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", user)
.replace("{{LANGUAGE}}", language)
.replace("{{SIZE}}", size)
.replace("{{LINK}}", a.share_link);
answer = jQuery(answer)
jQuery("#answers").append(answer);
languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 50%;
float: left;
}
#language-list {
padding: 10px;
width: 50%px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# Bash + coreutils, 54
Again, thanks to @TobySpeight for the golfing help.
```
rev|tr oizehsglb 0-8|sed '/.\{11\}\|[^0-9]/d;s/^0/&./'
```
Input wordlist is taken from STDIN:
```
$ ./5318008.sh < /usr/share/dict/words | head
8
38
338
5338
638
5638
36138
31738
531738
7738
$
```
[Answer]
# CJam, ~~44~~ 42 bytes
```
r{el"oizehsglb"f#W%"0."a.e|N+_,B<*_W&!*r}h
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%7Bel%22oizehsglb%22f%23W%25%220.%22a.e%7CN%2B_%2CB%3C*_W%26!*r%7Dh&input=Bill%0Ahohohohoho%0Ahello%0Abye).
To run the program from the command line, download the [Java interpreter](https://sourceforge.net/p/cjam/wiki/Home/) and execute:
```
java -jar cjam-0.6.5.jar 5318008.cjam < /usr/share/dict/words
```
### How it works
```
r e# Read a whitespace-separated token from STDIN.
{ e# While loop:
el e# Convert to lowercase.
"oizehsglb" e# Push that string.
f# e# Get the index of each character from the input in that string.
e# This pushes -1 for "not found".
W% e# Reverse the resulting array.
"0."a e# Push ["0."].
.e| e# Vectorized logical NOT. This replaces an initial 0 with "0.".
N+ e# Append a linefeed.
_,B<* e# Repeat the array (array.length < 11) times.
_W&!* e# Repeat the array !(array.intersection(-1)) times.
r e# Read a whitespace-separated token from STDIN.
}h e# If the token is not empty, repeat the loop.
```
[Answer]
# Python 2, ~~271~~ ~~216~~ ~~211~~ 205 Bytes
This is the only idea I've had so far.. I will update this once I think of something else! I assumed we needed to read from a file, but if not let me know so I can update :)
*Big thanks to Dennis for saving me 55 bytes :)*
*Also thanks to Sp3000 for saving 6 bytes :)*
```
d,f,g='oizehsglb',[x.lower()for x in open('w.txt').read().split('\n')if len(x)<10],[]
for x in f:
c=x[::-1]
for b in d:c=c.replace(b,`d.find(b)`)
g=[g,g+[['0.'+c[1:],c][c[0]!='0']]][c.isdigit()]
print g
```
[Answer]
# JavaScript (ES7), 73 bytes
This can be done in ES7 a mere 73 bytes:
```
s=>[for(w of s)'oizehsglb'.search(w)].reverse().join``.replace(/^0/,'0.')
```
Ungolfed:
```
var b = function b(s) {
return s.length < 10 && /^[bglioszhe]*$/.test(s) ? s.replace(/./g, function (w) {
return 'oizehsglb'.search(w);
}).reverse().join('').replace(/^0/, '0.') : '';
};
```
Usage:
```
t('hello'); // 0.7734
t('loose'); // 35007
t('impossible'); //
```
Function:
```
t=s=> // Create a function 't' with an argument named 's'
[ // Return this array comprehension
for(i of s) // Loops through each letter in the string
'oizehsglb'.search(w) // Converts it to it's corresponding number
]
.reverse().join`` // Reverse the array and make it a string
.replace(/^0/,'0.') // If the first character is a 0, add a decimal after it
```
---
I ran this on the UNIX wordlist and have put the results in a paste bin:
# [Results](http://pastebin.com/raw.php?i=B8ZaGaDj)
The code used to obtain the results *on Firefox*:
```
document.querySelector('pre').innerHTML.split('\n').map(i => t(i.toLowerCase())).join('\n').replace(/^\s*[\r\n]/gm, '');
```
[Answer]
# Python 2, 121 bytes
```
for s in open("w.txt"):
L=map("oizehsglb".find,s[-2::-1].lower())
if-min(L)<1>len(L)-9:print`L[0]`+"."[L[0]:]+`L`[4::3]
```
Assumes that the dictionary file `w.txt` ends with a trailing newline, and has no empty lines.
[Answer]
# GNU sed, 82
(including 1 for `-r`)
Thanks to @TobySpeight for the golfing help.
```
s/$/:/
:
s/(.)(:.*)/\2\1/
t
s/://
y/oizehsglb/012345678/
/.{11}|[^0-9]/d;s/^0/&./
```
Input wordlist is taken from STDIN:
```
$ sed -rf 5318008.sed /usr/share/dict/words | tail
3705
53705
1705
0.705
50705
5705
505
2
0.02
5002
$
```
[Answer]
# Python 2, ~~147~~ ~~158~~ 156 bytes
I was missing this '0.' requirement. Hope now it works allright.
**edit**: Removed ".readlines()" and it still works ;p
**edit2**: Removed some spaces and move print to the 3rd line
**edit3**: Saved 2 bytes thanks to Sp3000 (removed space after print and changed 'index' to 'find')
```
for x in open("w.txt"):
a="oizehsglb";g=[`a.find(b)`for b in x[::-1].lower()if b in a]
if len(g)==len(x)-1<10:
if g[0]=="0":g[0]="0."
print"".join(g)
```
[Answer]
# Python 2, ~~184~~ 174 bytes
```
for s in open('w.txt'):
try:a=''.join(map(lambda c:dict(zip('bglioszhe','867105243'))[c],s[:-1][::-1]));a=[a,'0.'+a[1:]][a[0]=='0'];print['',''.join(a)][len(s)<11]
except:0
```
[Answer]
# Ruby 2, ~~88~~ 86 bytes
```
x="oizehsglb"
puts$_.tr(x,"0-8").reverse.sub /^0/,"0." if$_.size<11&&$_.delete(x)<?A
```
Byte count includes 2 for the `ln` options on the command line:
```
$ ruby -ln 5318008.rb wordlist.txt
```
[Answer]
# C, 182 172 169/181 172 bytes
```
char*l="oizehsglb",S[99],*s,*t;main(x){for(;t=S+98,gets(S);){for(s=S;*s;s++)if(x=strchr(l,*s|32))*--t=48+x-(int)l;else break;*t==48?*t--=46,*t=48:0;*s||s-S>10?0:puts(t);}}
```
Expanded
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *l="oizehsglb",S[99],*s,*t;
main(int x, char **argv)
{
for (;t=S+98,gets(S);){
for (s=S;*s;s++)
if (x=strchr(l,*s|32))
*--t=48+x-(int)l;
else
break;
if (*t==48) { // '0'
*t--=46; // '.'
*t=48; // '0'
}
if (!*s && s-S <= 10)
puts(t);
}
}
```
using the linked words.txt, with lower case conversion:
```
$ ./a.out < words.txt | tail
2212
0.2
0.802
0.602
7702
37702
0.02
321607002
515002
0.02002
$ ./a.out < words.txt | wc -l
550
```
[Answer]
# Java, 208 200 176 bytes
```
String f(char[] w){String o="",l="oizehsglb";for(int i=w.length;i>0;i--)o+=l.indexOf(w[i-1]|32);if(o.contains("-")||o.length()>8)o=" ";return o.charAt(0)+"."+o.substring(1);}
```
Expanded
```
String f(char[] w)
{
String o = "", l = "oizehsglb";
for(int i = w.length; i > 0; i--)
o+=l.indexOf(w[i-1]|32);
if(o.contains("-")||o.length() > 8)
o = " ";
return o.charAt(0) + "." + o.substring(1);
}
```
It always adds the decimal, and when invalid returns " . ". But otherwise works like it should. :P
Thanks @LegionMammal978!
[Answer]
# Haskell, 175 bytes without imports (229 bytes with imports)
Relevant code (say in File Calc.hs):
```
import Data.Char(toLower)
import Data.Maybe(mapMaybe)
s="oizehsglb\n"
g('0':r)="0."++r
g x=x
main=mapM_(putStrLn.g.reverse.mapMaybe(`lookup`zip s['0'..'8'])).filter(\l->length l<10&&all(`elem`s)l).lines.map toLower=<<getContents
$ cat /usr/share/dict/words | runghc Calc.hs
```
] |
[Question]
[
Until [decimalization in 1971](http://en.wikipedia.org/wiki/Decimal_Day), British money was based on dividing the [pound](http://en.wikipedia.org/wiki/Pound_sterling) into 240 pennies. A shilling was 12 pennies so 20 shillings made a pound. The smallest denomination was the farthing at one fourth of a penny. There were many other denominations and nicknames for coins, [which can get quite confusing](http://resources.woodlands-junior.kent.sch.uk/customs/questions/moneyold.htm) if you're not used to the system.
# Challenge
Write a program or function that can convert (almost) any denomination of old English money to any other. To make it easier for the user you need to support plurals and nicknames.
These are the denominations and their synonymous terms you must support. For convenience their value in farthings leads each line.
```
1: farthing, farthings
2: halfpence, halfpenny, halfpennies
4: penny, pennies, pence, copper, coppers
8: twopenny, twopennies, twopence, tuppence, half groat, half groats
12: threepence, threepenny, threepennies, threepenny bit, threepenny bits, thruppence, thrupenny, thrupennies, thrupenny bit, thrupenny bits
16: groat, groats
24: sixpence, sixpenny, sixpennies, sixpenny bit, sixpenny bits, tanner, tanners
48: shilling, shillings, bob
96: florin, florins, two bob bit, two bob bits
120: half crown, half crowns
240: crown, crowns
480: half sovereign, half sovereigns
504: half guinea, half guineas
960: pound, pounds, pounds sterling, sovereign, sovereigns, quid, quids
1008: guinea, guineas
```
(I am not British, this list is by no means authoritative but it will suffice for the challenge.)
Via stdin or function argument you should take in a string of the form
```
[value to convert] [denomination 1] in [denomination 2]
```
and return or print
```
[value to convert] [denomination 1] is [converted value] [denomination 2]
```
where `[converted value]` is `[value to convert]` units of denomination 1 converted to denomination 2.
The `[value to convert]` and `[converted value]` are positive floats. In the output both should be rounded or truncated to 4 decimal places. If desired you may assume `[value to convert]` always has a decimal point and zero when input (e.g. `1.0` instead of `1`).
Denominations 1 and 2 may be any two terms from the list above. Don't worry about whether they're plural or not, treat all denominations and synonyms the same. You may assume the input format and denominations are always valid.
# Examples
`1 pounds in shilling` → `1 pounds is 20 shilling`
(`1.0000 pounds is 20.0000 shilling` would be fine)
`0.6 tuppence in tanner` → `0.6 tuppence is 0.2 tanner`
`24 two bob bits in pounds sterling` → `24 two bob bits is 2.4 pounds sterling`
`144 threepennies in guineas` → `144 threepennies is 1.7143 guineas`
# Scoring
The shortest code [in bytes](https://mothereff.in/byte-counter) wins.
[Answer]
## Ruby, ~~345~~ ~~306~~ ~~302~~ ~~288~~ ~~287~~ ~~278~~ ~~273~~ ~~253~~ ~~252~~ ~~242~~ ~~232~~ ~~221~~ ~~202~~ 190 bytes
```
f=->s{" !#+/7OďǿȗϟЏ'"[%w{fa fp ^pe|co r..p ^gr x|ta sh|^b fl|b f.c ^c f.s .gu d|v ^g .}.index{|k|s[/#{k}/]}].ord-31}
$><<gets.sub(/ (.+ i)n /){" #{r=$1}s %0.4f ".%$`.to_f/f[$']*f[r]}
```
Takes input from STDIN and prints to STDOUT.
I'm using short regular expressions to match only the desired denominations for each value. There are two arrays, one with regexes and one with values, at corresponding indices. The regex array is a space delimited array literal, and the value array is packed into a string of UTF-8 characters.
I'm selecting the index into the values by searching for a regex that matches each denomination. I'm also defaulting to the tuppence/half-groat case (value 8), because that required the longest regex. Likewise, some of the patterns assume that other values have already been matched by earlier patterns, so each regex only distinguishes the desired value only from the remaining ones. Using this, I could probably shave off another couple of bytes by rearranging the order of the denominations.
Thanks to Ventero for helping me ~~beat Pyth~~ making it shorter!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 146 145
```
K4J24L?*y>b-5>b\t?2>b\t.5}<b2"hatw"@[1K8K12K16J48J1008*JT96*2J960)xc"fapetucothengrsishtagucrflbo"2<b2AGHcz" in"++G%" is %0.4f"*vhcGdcyjdtcGdytHH
```
More readable (newlines and indents must be removed to run):
```
K4J24
L?*y>b-5>b\t?2>b\t.5
}<b2"hatw"
@[1K8K12K16J48J1008*JT96*2J960)
xc"fapetucothengrsishtagucrflbo"2<b2
AGHcz" in"
++G
%" is %0.4f"
*vhcGdcyjdtcGdytH
H
```
Update: Turns out, it's 1 character shorter (no space needed) to chop up the string into a list of 2 character strings before running the string index operation. `/x"string"<b2 2` -> `xc"string"2<b2`. Nothing else needs to be changed.
How it works:
* This uses @xnor's approach of looking up the value of currency using its first two letters, as well as the trick of detecting the initial `half` or `two`, removing it and calling the function again.
* To lookup the value of the first two characters, it finds the location of the first two letters of the currency in a string, then divides by 2 and takes the value at that index in the list. This is much shorter than an dict in pyth.
* Uses the fact that `x` (find within string) returns -1 on failure to avoid putting `po` (pounds) `qu` (quid) or `so` (sovereigns) in the string, and simply return the last element of the list, 960, by default.
* By rearranging the order of currencies in the lookup system and initializing carefully, with `K4` and `J24`, all spaces that would have been needed to separate numbers in the list were removed.
* Uses pyth's dual assignment operator, `A`, on the input split on `in` to get the beginning and end of the input in separate variables.
* Does essentially the same lookup at the end, though pyth has no `.split(_,1)`, so it is somewhat more cumbersome.
Examples:
```
$ pyth programs/currency.pyth <<< '5 florins in half guineas'
5 florins is 0.9524 half guineas
$ pyth programs/currency.pyth <<< '0.4 quid in sixpenny bits'
0.4 quid is 16.0000 sixpenny bits
```
[Answer]
## Python 3: 264 239 chars
```
f=lambda c:c[:2]in"hatw"and f(c[5-(c>'t'):])*2/4**(c<'t')or[1,4,4,4,8,12,16,24,24,48,48,96,240,1008,960]['fapecoentuthgrsitashboflcrgu'.find(c[:2])//2]
a,b=input().split(" in ")
x,c=a.split(" ",1)
print(a,"is %0.4f"%(eval(x)*f(c)/f(b)),b)
```
The function `f` gets the shilling value of the currency-string `c` by fingerprinting the first two letters using the dictionary by finding them in a string. The prefixes "half" and "two" are detected and accounted for by chopping the prefix and the space and applying a multiplier. Since "halfpenny" lacks a space after "half", this results in "enny", but that's handled with a fictional "en" entry.
Thanks to @isaacg and @grc for lots of improvement on the dictionary lookup.
[Answer]
## Python 2 - 345 ~~358~~
```
s=str.startswith
h='half'
u,v=raw_input().split(' in ')
a,b=u.split(' ',1)
C=dict(fa=1,pe=4,twop=8,tu=8,thr=12,gr=16,si=24,ta=24,sh=48,b=48,fl=96,c=240,po=960,so=960,q=960,gu=1008)
C.update({h+'p':2,h+' gr':8,'two ':96,h+' c':120,h+' s':480,h+' gu':504})
for c in iter(C):
if s(b,c):k=C[c]
if s(v,c):f=C[c]
print u+' is %0.4f '%(eval(a)*k/f)+v
```
Requires input number to be a float in python i.e. `144.1`
I think this could be shortened in python 3...
...Confirmed thanks to @xnor. Also confirmed that having a better algorithm matters a lot ;)
[Answer]
# Haskell - 315 bytes
```
w x=f(u x)*v(u x)
f=maybe 1 id.l"ha tw tu th si"[0.5,2,2,3,6]
v x@(_:xs)|Just w<-l"bo cr gr gu so co fa fl pe po qu sh ta"[12,60,4,252,240,1,0.25,24,1,240,240,12,6]x=w|True=v xs
l k v x=take 2 x`lookup`zip(words k)v
u=unwords
i s|(n:x,_:t)<-span(/="in")$words s=u$n:x++["is",show$read n*w x/w t]++t
main=interact i
```
[Answer]
## JavaScript (ES5), 344
```
I=prompt()
n=I.match(/[\d.]+ /)[0]
A=I.slice(n.length).split(" in ")
function m(x){return{fi:1,he:2,p:4,pe:4,cr:4,tn:8,hg:8,tp:12,te:12,g:16,gs:16,sn:24,tr:24,si:48,b:48,fn:96,to:96,hc:120,c:240,cs:240,hs:480,hgtrue:504,ps:960,se:960,q:960,ga:1008}[x[0]+(x[5]||"")+(x[10]=="a"||"")]}
alert(n+A[0]+" is "+(n*m(A[0])/m(A[1])).toFixed(4)+" "+A[1])
```
I went with a hash function approach... I think I underestimated (relatively) how complex the input processing would be (over the regex approach, that wouldn't care about the number).
[Answer]
Based on @FryAmTheEggMan's answer, with a different way of testing `str.startwith`:
# Python 2: 317
```
h='half'
C=dict(fa=1,pe=4,twop=8,tu=8,thr=12,gr=16,si=24,ta=24,sh=48,b=48,fl=96,c=240,po=960,so=960,q=960,gu=1008)
C.update({h+'p':2,h+' gr':8,'two ':96,h+' c':120,h+' s':480,h+' gu':504})
u,v=raw_input().split(' in ')
a,b=u.split(' ',1)
s=lambda x:x and C.get(x, s(x[:-1]))
print u+' is %0.4f '%(eval(a)*s(b)/s(v))+v
```
[Answer]
# JavaScript ES6, 264 273
```
f=t=>{s=t.split(x=' in')
c=d=>{'t0sh|bo0^p|co0f0fp0fl|b b0gu0d|v0wn0gr0f g|t..?p0f s0f gu0f c0x|an'.split(0).map((e,i)=>{v=s[d].match(e)?[12,48,4,1,2,96,1008,960,240,16,8,480,504,120,24][i]:v})
return v}
return s.join(' is '+~~(1e4*t.split(' ')[0]*c(0)/c(1))/1e4)}
```
```
t=prompt()
s=t.split(x=' in')
c=function(d){'t0sh|bo0^p|co0f0fp0fl|b b0gu0d|v0wn0gr0f g|t..?p0f s0f gu0f c0x|an'.split(0).map(function(e,i){v=s[d].match(e)?[12,48,4,1,2,96,1008,960,240,16,8,480,504,120,24][i]:v})
return v}
alert(s.join(' is '+~~(1e4*t.split(' ')[0]*c(0)/c(1))/1e4))
```
This gets the value of each currency by checking it against various regexes, starting with the broadest `/t/`; the value is overwritten if another match is encountered. There might be a way to shave off a couple bytes by reordering the regex string. You can test it using the snippet above (It is formatted only to use dialog boxes and remove ES6 arrow functions so everyone can test the code easily). Thanks to Alconja for the suggestions.
] |
[Question]
[
# Challenge
For this challenge, a mountainous string is one that conforms to the grammar rule `M: x(Mx)*` where at each production, the all x's are the same character. When indented, a mountainous string might look something like this:
```
A
B
C
D
C
E
F
E
C
B
A
```
As you can see, it looks a bit like a mountain from the side.
# Formal Definition
* Any single character `a` is mountainous.
* If `S` is a mountainous string and `a` is a character, then `aSa` is mountainous, where juxtaposition represents string concatenation.
* If `aSa` and `aTa` are mountainous strings, then `aSaTa` is a mountainous string. Note that this rule implies that this pattern holds for any number of repetitions. (i.e. `aSaTaUa`, `aSaTaUaVa`, `aSaTaUaVaWa`... are all mountainous.)
# Examples
All odd-length palindromes are mountainous, for instance:
```
t
a
c
o
c
a
t
```
`qwertytrasdfdgdsarewqjklkjq` is a less trivial example:
```
q
w
e
r
t
y
t
r
a
s
d
f
d
g
d
s
a
r
e
w
q
j
k
l
k
j
q
```
# Example Outputs
```
a ==> true
aaa ==> true
mom ==> true
tacocat ==> true
qwertytrasdfdgdsarewqjklkjq ==> true
wasitacaroraratisaw ==> true
abcbcbcbcba ==> true
aaaaabcbbba ==> true
<empty string> ==> false
aa ==> false
pie ==> false
toohottohoot ==> false
asdfdghgfdsa ==> false
myhovercraftisfullofeels ==> false
```
# Rules
* This is a decision problem, so any representation of true or false is valid output as long as it is correct, consistent, unambiguous, and the program terminates in a finite amount of time. Be sure to state your output convention with your solution.
+ It should be trivial to determine whether the output indicates true or false without having to know what the input string is. Note that this does not mean the truthy or falsy outputs have to be constant, however the convention of "print a mountainous string if the string is mountainous and a non-mountainous string if not mountainous" is a banned loophole for obvious reasons.
+ On the other hand, a convention like "throws an exception for false and exits silently for true" would be fine, as well as "prints a single character for true and anything else for false"
* This is code golf, so the shortest program wins.
* Standard loopholes are banned.
[Answer]
# [Japt v2](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes
```
e/.).\1/_g
¥g
```
[Test it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS8uKS5cMS9fZwqlZw==&input=ImFiY2JjYmNiY2JhIg==)
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~94~~ ~~89~~ ~~87~~ 80 bytes
```
import StdEnv
?[a,b,c:s]=[a: ?if(a==c)s[b,c:s]]
?l=l
$s=limit(iterate?s)==[hd s]
```
[Try it online!](https://tio.run/##Lcu9CsIwFIbhPVcRsNAK9QYKIYsOglvH0OGYpvVAfiTn1OLNGwM6fMvL81nvIJaQ5s07GQBjwfBMmeXI8yW@hDbQ33s70KQMDFLj0oFS9kjmVyehvfKiIeUxIHfILgM7TUelzGOWNJWRIbM4SOKMcZVKmnYHQgYLOWWoHAn2dqpk2aJlTLGiRtT9P@VjFw8rldP1Vs7vCAEtfQE "Clean – Try It Online")
[Answer]
# Perl, 22 bytes
Includes `+` for `p`
```
perl -pe '$_=/^((.)((?1)\2)*)$/' <<< abcbcbcbcba
```
Prints 1 for true, nothing for false
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes
```
({()<<>(([{}]({}))([{}]({}))<>[({}<>)])>{[()()]((<()>))}<{}{}{}<>>}(())){{}}{}
```
[Try it online!](https://tio.run/##RYdBCsMwDAS/s3vID4Q@YnxQcRIah4KdQAhCb3fTU5nDzLy6vT/TslsdAw6KKJA8MjzIf4mmx6LMVE8gmAEBlQzx@CGqAZB0j2fHaNfcz/vsdpSlrOWwPl9tq3vd2pjsCw "Brain-Flak – Try It Online")
Prints 1 for true, nothing for false.
To verify a mountainous word, it is sufficient to assume the word goes "down" the mountain whenever possible.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 29 bytes
```
a-->[X],+X.
+X-->[];a,[X],+X.
```
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1FX1y46IlZHO0KPSzsCxIm1TtSBigClNRIKy1OLSipLihKLU9JS0lOKE4tSywuzsnOyswoTdKJjNfW4uAA "Prolog (SWI) – Try It Online")
This program defines a DCG rule `a//0` that matches any string (list of characters) that is a mountainous string.
## Explanation
For this program I use a slightly different but equivalent definition for mountainous strings than what is described in the challenge: A mountainous string is a character `c` followed by a number (could be zero) of mountainous strings with `c` tacked onto the ends of them. In a more terse regex derived notation, a mountainous string must match the pattern `c(Mc)*` where `M` is a mountainous string and `*` means that the expression in parentheses is repeated zero or more times. Note that while each `c` must be the same character, each `M` does not need to be the same mountainous string.
### Proof of Equivalence
It is clear that rules 1 and 2 from the challenge are equivalent to my rule where `Mc` occurs zero and one times respectively.
In the case that the mountainous string has `Mc` occurring `n` times where `n > 1` then the string can be rewritten as `cMcSc` where `S` is the latter `n - 1` times that `Mc` occurs excluding the last `c` (note that `M` is any mountainous string and not necessarily the same as other `M`). Since `M` is a mountainous string, by rule 2, `cMc` must be a mountainous string. Either `S` is a mountainous string in which case `cSc` is a mountainous string or `S` can be rewritten as `cMcTc` where `T` is the latter `n - 2` times that `Mc` occurs excluding the last `c`. This line of reasoning can keep on being applied until string not guaranteed to be mountainous contains `Mc` once which would mean it would have to be mountainous as well. Thus since `cMc` is mountainous and if `cMc` and `cM'c` are mountainous then `cMcM'c` must be mountainous the whole string must be mountainous.
For the converse, for a string `cScTc` where `cSc` and `cTc` are mountainous then either `cSc` is a mountainous string by rule 2 or by rule 3. If it is a mountainous string by rule 2 then `S` must also be a mountainous string. If it is a mountainous string by rule 3 then `cSc` must be of the form `cUcVc` where `cUc` and `cVc` are mountainous strings. Since the longer of `cUc` and `cVc` must still be at least two characters shorter than `cSc` and rule 3 requires at least 5 character to be applied then after a finite number of applications of rule 3 each string between the `c`s selected by applications of rule 3 must be a mountainous string. The same line of reasoning can be applied to `cTc` thus the string is mountainous by my definition.
Since any string that matches my definition is mountainous and my definition matches all mountainous strings, it is equivalent to the one given in the question.
### Explanation of Code
Overall the `a//0` DCG rule, defined on the first line, matches any mountainous string. The `+//1` DCG rule (like predicates, [DCG rules can be give operator names](https://codegolf.stackexchange.com/a/153160/20059)), defined on line two, matches any string that is made up of a sequence of zero or more mountainous strings with the character passed as its arguments `X` tacked onto the ends of them. Or to borrow the regex-like notation I used above, `a//0` matches `c(Mc)*` but outsources the job of actually matching the `(Mc)*` to `+//1` which takes `c` as its argument `X`.
Line by line the codes behaves as follows:
```
a-->[X],+X.
```
This line defines the DCG rule `a`. The `[X]` states that the first character must be equal to the currently undefined variable `X`. This results in `X` being set equal to the first character. The `+X` then states that the rest of the string must match the DCG rule `+//1` with the character that `X` is set to as its argument.
```
+X-->[];a,[X],+X.
```
This line defines the `+//1` DCG rule. The `;` represents an or in Prolog which means that the string can match either `[]` or `a,[X],+X`. The `[]` represents the empty string so `+//1` is always capable of matching the empty string. If the string is not empty then the start of it must match `a//0` and so must be a mountainous string. This must then be followed by whatever character `X` is set to. Finally the rest of the string must match `+X`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~89~~ 83 bytes
```
f=lambda s:re.search(M,s)and f(re.sub(M,r'\1',s))or len(s)==1
import re;M=r'(.).\1'
```
[Try it online!](https://tio.run/##NY/BbsMgDIbP61NwI5GqSO2xE3uDPkG3g5NAoSU4sWmjPH1mkk1INvx88gfjkj2m87o6E2Foe1B8IduwBep8dT1yDalXrirZq5WA9PdJS1wjqWhTxbUxp0MYRqSsyH5eDemqqRuhVicMq5DUTYM@Kg2wtQGH0jJ02EEu22m2lJdMwL3r7z0D2Xl6POPzMZXrGTgIDYQEBDkwzNu4tvtb/9OhRO1@3KNSx2A3H6LHnKXgJt1l/u7Etz1r8fi21BE4UbhXjOisjax/LoePkULKigUzXwI7@ff6Cw "Python 2 – Try It Online")
Thanks to ovs for 6 bytes.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
εωφΓ§?t·:⁰`(=←t
```
[Try it online!](https://tio.run/##LYw7DsIwEET7PQVluAIS4ipsHDvOx1pib7BShiISHRKHoKUB@hwguUMuYsxHI43mSaOnW1eFlUnccurX4zNMj/k8D9N1vO14fG2W/r5Ptstw4RACAiKCIQOMggQyNF5a7tiiy1SWZw6t9E1Z1VXZgEdXxB9asmiRC4ceMBX/fF344TTuCHAoJDCRJuZYxPCT6lxFL5hO01FaYVFFlWrrmpSUtXsD "Husk – Try It Online")
Type inference takes about 40 seconds, so be patient.
## Explanation
```
εωφΓ§?t·:⁰`(=←t Implicit input, say s = "abacdca"
ω Apply until fixed point is reached
φ this self-referential anonymous function (accessed with ⁰):
Argument is a string x.
Γ Deconstruct x into head h and tail t.
§?t·:⁰`(=←t Call this function on h and t. It is interpreted as §(?t)(·:⁰)(`(=←t)).
§ feeds h to (·:⁰) and (`(=←t)), and calls (?t) on the results.
The semantics of ? cause t to be fed to all three functions.
`(=←t First, check whether h equals the first element (←) of the tail of t.
?t If it does (e.g. if h='a' and t="bacdca"), return tail of t ("acdca").
Otherwise (e.g. if h='b' and t="acdca"),
· ⁰ call the anonymous function recursively on t: "aca"
: and prepend h to the result: "baca".
Final result is "a".
ε Is it a 1-element string? Implicitly print 0 or 1.
```
The idea is to repeatedly replace a substring of the form `aba` with `a` until this is no longer possible.
The input is mountainous if and only if this results in a single-character string (which is what `ε` tests).
The only dangerous situation is when we have a string like this, where `aba` doesn't seem to be a peak:
```
a
b
a
c
a
d
a
b
a
```
Fortunately, we can always transform it into one:
```
a
b
a
c
a
d
a
b
a
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes
```
+`(.).\1
$1
^.$
```
[Try it online!](https://tio.run/##LYxtCoMwEET/7zksWAqCp@glSnGMiUZjt27WBk@fph8MDPNgeGLVP5BP9bXLl65uzs2tpaqle1PlDAJAK6@kMGygtCUreqggDm4YhwixaZuXsMwbJURffhAWCNRHJEJv/vm68OG@7AL09JaUeWLVUqz0k06jK15aj4lfVozAFZXbQ2BnbYhv "Retina 0.8.2 – Try It Online") Trivial port of @ETHproductions' Japt answer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
I suppose this is nearly the most straightforward method to do so?
```
f=s=>(w=s.replace(/(.).\1/,"$1"))==s?w.length==1:f(w)
```
[Try it online!](https://tio.run/##jZLBbsIwDIbvfQqEdmjR1orrtnQvsotJnbaQ1iUxRDx9FwQTTLhliZSD/cWyf/9bOILXrh34racKx2KVwGL6KFUu2B0wAYDnUEfdc4hBkwaeh/YBHZ/Yga9MVVceHIb9dmd32/0NCuDbWA0cOXDArYcgNL7R1wuz08EZ3MxBySd2A58Wnl3b1@UjZcD6c615OS/U0OI/KCZqiDk@xNPURaSmNlGnaao7NXREpx2YKJU5WEsG0fq/1KoYjfKqTIPyucPBgsa0SPMs/14Xr8uX9TLLlPJfIbfY19wotX43acjGj0RT78libqlOTbqESD4GQQxH40jhq1Wk1IxBJFywitjezSwT3f/aRErLX6Ro3L447926xWJ3ixZlnFjxmR1/AA "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 72 bytes
Less trivial one, but much longer.
```
s=>[...s].reduce((a,x)=>(a[a.length-2]==x?a.pop():a.push(x),a),[])==s[0]
```
[Try it online!](https://tio.run/##jZLBbsIwDIbvfQrEqUEQph23pXuQqgeTJm0hrdvEpfD0XRBMMJGWJVIiOV8s@/e/hyM4aauWNg3matyuIlhMLyGSBdleRQDwGqqxfg0RSJRA81A3KEtnsuBynRe5A6uGbn8wh313hwZwlc8GFi1YoMrBECh8J28bZruDC7ibg6IvVbd0XjiyVVMkz5QG4y655uW8Um2l/kERYolE/kCapq4ilYX2Ok1T9bnEo7LSgvZS6d4Y1EoZ95dabaNIi9GJJOWcu4xblfdSxTGsT0wkMaTAjWoKKjfvmRCnb@AttjH78HfvyvjE1sDWacaEcOlbNn5GEhuHRnGDRazjJSwZew5CMOz9FArfHBR6mvFNCA84KFje3UMT1f@6J/Qc/hKKelME@31wQTDZw/yDMk5M/sKOPw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
A well known [song](https://www.youtube.com/watch?v=98W9QuMq-2k) by the Irish rock band [U2](https://en.wikipedia.org/wiki/U2) starts with the singer Bono saying "1, 2, 3, 14" in Spanish ("*uno, dos, tres, catorce*").
There are [various](http://forum.atu2.com/index.php?topic=4695.30) [theories](https://www.quora.com/Why-does-Bono-sing-Uno-Dos-Tres-Catorce-in-Vertigo?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) as to the significance of those numbers. Apparently the [official explanation](https://www.quora.com/Why-does-Bono-sing-Uno-Dos-Tres-Catorce-in-Vertigo/answer/Matias-Petroccello) is "*we drank too much that night*". But there's a more interesting hypothesis: Bono is referring to some integer sequence from OEIS, such as
[**A107083**](https://oeis.org/A107083):
>
> Integers `k` such that `10^k + 31` is prime.
>
> `1`, `2`, `3`, `14`, `18`, `44`, `54`, ...
>
>
>
In an interview, when asked the inevitable question "why 14", Bono admitted he was a bit tired of that number. The journalist suggested "15" instead, and in that night's concert the lyrics were indeed changed into "1, 2, 3, 15". (The story can be read [here](https://www.elconfidencialdigital.com/opinion/tribuna-libre/catorce/20050519000000104195.html), in Spanish). Quite likely the journalist took inspiration from
[**A221860**](https://oeis.org/A221860):
>
> Indices `k` such that `prime(k) - k` is a power of `2`, where `prime(k)` is the `k`-th prime.
>
> `1`, `2`, `3`, `15`, `39`, `2119`, `4189897`, ...
>
>
>
# The challenge
Write two programs in the same language. The first should take an input `n` and output the `n`-th term of [A107083](https://oeis.org/A107083), or the first `n` terms. Similarly, the second should output the `n`-th term of [A221860](https://oeis.org/A221860), or the first `n` terms.
The **score** is the **sum** of **lengths** of the two programs, in bytes, plus the **square** of the [**Levenshtein distance**](https://en.wikipedia.org/wiki/Levenshtein_distance) between the byte representations of the two programs.
If a character encoding is used such that each character corresponds to one byte, [this script](https://planetcalc.com/1721/) can be used to measure Levenshtein distance.
For example, if the two programs are `abcdefgh` and `bcdEEfg`, the score is `8 + 7 + 4^2 = 31`.
Lowest score wins.
# Aditional rules
* The output can be `1`-based or `0`-based, independently for each sequence (so it is allowed if one of the programs is `1`-based and the other is `0`-based).
* Each program can, consistently but independently of the other, either output the `n`-th term or the first `n` terms.
* Programs or functions are allowed, independently for each sequence.
* Input and output means and format are [flexible as usual](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 + 16 + 1² = 33
### A107083
```
⁵*+31ÆḍÆNB>/
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9R41YtbWPDw20Pd/QebvNzstPnMjzcrvz//39TAA "Jelly – Try It Online")
### A221860
```
⁵*+31ÆạÆNB>/
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9R41YtbWPDw20Pdy083ObnZKfPZXi4Xfn///@mAA "Jelly – Try It Online")
### How it works
```
1Ç# Main link. Argument: n
1 Set the return value to 1.
Ç# Call the helper link with arguments k, k + 1, k + 2, ... until n of
them return a truthy value. Return the array of n matches.
⁵*+31ÆḍÆNB>/ Helper link. Argument: k
⁵* Yield 10**k.
+31 Yield 10**k + 31.
Æḍ Count the proper divisors of 10**k + 31.
This yields c = 1 if 10**k + 31 is prime, an integer c > 1 otherwise.
ÆN Yield the c-th prime.
This yields q = 2 if 10**k + 31 is prime, a prime q > 2 otherwise.
B Binary; yield the array of q's digits in base 2.
>/ Reduce by "greater than".
This yields 1 if and only if the binary digits match the regex /10*/,
i.e., iff q is a power of 2, i.e., iff 10**k + 31 is prime.
⁵*+31ÆạÆNB>/ Helper link. Argument: k
Æ Unrecognized token.
The token, as well as all links to its left, are ignored.
ÆN Yield p, the k-th prime.
ạ Take the absolute difference of k and p, i.e., p - k.
B Binary; yield the array of (p - k)'s digits in base 2.
>/ Reduce by "greater than".
This yields 1 if and only if the binary digits match the regex /10*/,
i.e., iff p - k is a power of 2.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 + 11 + 9² = 101 bytes
## 1, 2, 3, 14
```
.fP_+31^T
```
[Try it online!](http://pyth.herokuapp.com/?code=.fP_%2B31%5ET&input=4&debug=0)
## 1, 2, 3, 15
```
.fsIl-e.fP_
```
[Try it online!](http://pyth.herokuapp.com/?code=.fsIl-e.fP_&input=4&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 + 12 + 8² = 88 bytes
## 1, 2, 3, 14
```
ÆN_µæḟ2=
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9wm1/8oa2Hlz3cMd/IlsvwcLvy//8mAA "Jelly – Try It Online")
## 1, 2, 3, 15
```
10*+31ÆP
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8/9/QQEvb2PBwWwCX4eF25f//TQA "Jelly – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11B + 10B + 7B² = 70
## 1, 2, 3, 14
```
⁵*+31ÆP
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9R41YtbWPDw20BXIaH25X///9vAgA "Jelly – Try It Online")
## 1, 2, 3, 15
```
ạÆNBSỊ
1Ç#
```
[Try it online!](https://tio.run/##y0rNyan8///hroWH2/ycgh/u7uIyPNyu/P//fxMA "Jelly – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 17+17+7² = 83
## 1, 2, 3, 14, ... (17 bytes)
```
0G:"`Q11qy^31+Zp~
```
[Try it online!](https://tio.run/##y00syfn/38DdSikh0NCwsDLO2FA7qqDu/38TAA "MATL – Try It Online")
## 1, 2, 3, 15, ... (17 bytes)
```
0G:"`QtYqy-Bzq~p~
```
[Try it online!](https://tio.run/##y00syfn/38DdSikhsCSysFLXqaqwrqDu/38TAA "MATL – Try It Online")
Both employ the similar scheme of `0G:"`Q` to have a counter running up and returning when a condition has been met `n` times. The actual program then is fairly straightforward. The `15` variant has some filler (`~p~`) to minimise the Levenshtein distance, while the `14` program employs an `11qy` rather than `t10w` to match the other program better.
Shared part:
```
0 % Push counter (initially zero)
G:" % Loop `n` times
` % Do .... while true
Q % Increment counter
```
Top program:
```
11q % Push 10
y % Duplicate counter
^ % Power
31+ % Add 31
Zp % isprime
~ % If not, implicitly continue to next iteration.
% Else, implicit display of counter.
```
Bottom program:
```
tYq % Nth prime based on counter
y- % Duplicate counter, subtract from nth prime.
Bzq % Number of ones in binary presentation, minus one (only zero for powers of two).
~p~ % Filler, effectively a NOP.
% If not zero, implicitly continue to next iteration
% Else, implicitl display of counter.
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 + 11 + 62 = ~~84~~ ~~69~~ 57 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
## 1, 2, 3, 14, ... (A107083)
```
ε>а32<+p
```
[Try it online.](https://tio.run/##MzBNTDJM/f//cN@hrXaHJxzaYGxko13w/78JAA)
## 1, 2, 3, 15, ... (A221860)
```
ε>Ð<ØαD<&_
```
[Try it online.](https://tio.run/##MzBNTDJM/f//cN@hrXaHJ9gcnnFuo4uNWvz//yYA)
Both output the 1-based \$n\$th value.
Uses the legacy version of 05AB1E, since it does `½` (*increase `counter_variable` by 1 if the top of the stack is truthy*) implicitly after each iteration of `µ`-loops (*while `counter_variable` is not equal to \$a\$ yet, do ...*).
**Explanation:**
```
Î # Push 0 and the input
µ # While the counter_variable is not equal to the input yet:
> # Increase the top by 1
Ð # Triplicate it (which is our `k`)
°32<+ # Take 10 to the power `k`, and add 31
p # Check if this is a prime
# (implicit: if it is a prime, increase the counter_variable by 1)
# (implicitly output the top of the stack after the while-loop)
Î # Push 0 and the input
µ # While the counter_variable is not equal to the input yet:
> # Increase the top by 1
Ð # Triplicate it (which is out `k`)
<Ø # Get the 0-indexed k'th prime
α # Get the absolute difference of this prime with the copied `k`
D<& # Calculate `k` Bitwise-AND `k-1`
_ # And check if this is 0 (which means it's a power of 2)
# (implicit: if it is 0, increase the counter_variable by 1)
# (implicitly output the top of the stack after the while-loop)
```
] |
[Question]
[
We all know of, or at least have heard of, **[brainfuck](http://esolangs.org/wiki/brainfuck)**, one of the most famous and influential esoteric languages. While these days most implementations use an infinite tape, the original compiler by Urban Müller had a tape of 30000 cells. A little known fact\* is that there is actually a special value at the end of the tape, something that is almost never interacted with in a typical brainfuck program.
While you could print this value with 29999 `>`s and a `.`, brainfuck is known for its short and concise solutions, so your aim is to print this value with the minimum number of characters.
\*fiction
### Rules:
* A refresher on the brainfuck instructions:
+ `+`/`-`: Increment/decrement the current cell, wrapping from 255 to 0 when 255 is incremented and vice-versa
+ `<`/`>`: Move the pointer left/right on the tape
+ `.`: Print the value of the current cell.
+ `[`: Jump to the corresponding `]` if the value at the cell is 0
+ `]`: Jump to the corresponding `[` if the value at the cell is not 0
* In this case `,` (Get input) does nothing, as the original compiler leaves the cell unchanged on EOF, and this program should receive no input.
* The tape is initially filled with all 0s, except for cell 30000, which contains an unknown value
* The pointer starts at cell 1 and should end on cell 30000, having printed it.
* Cells to the left of 1 and to the right of 30000 have undefined behaviour, so solutions should **not** visit these cells.
* Note that the value at 30000 ~~is~~ may be a 0, so simply looping until you hit a non-zero cell will not work.
* You should print *only* the value at cell 30000
* The shortest solution wins!
+ Tie-breaker is the more efficient program (executes in the least steps), followed by the fastest submission time.
**Tip:** Esolanging Fruit suggests using <https://copy.sh/brainfuck> to test your code. The specs are as described in this challenge, and you can select the `abort` option so your program halts if it goes out of bounds.
[Answer]
# 54 Bytes
```
------[>+++<--]>[->----[-[->+<]<[->+<]>>]<]>>>>>>>>>>.
```
119 x 252 = 29988. Straightforward nested loop.
I used [this tool](https://copy.sh/brainfuck/?c=LS0tLS0tWz4rKys8LS1dPlstPi0tLS1bLVstPis8XTxbLT4rPF0-Pl08XT4-Pj4-Pj4-Pj4u) to verify that the pointer stops at 29999.
[Answer]
# 50 bytes
```
>+[>+[<]>->+]>-<<[>>-------[[>]+[<]>-]<<-]>>>[>]>.
```
[Try It Here!](https://copy.sh/brainfuck/?c=PitbPitbPF0-LT4rXT4tPDxbPj4tLS0tLS0tW1s-XStbPF0-LV08PC1dPj4-Wz5dPi4$)
The first section (`>+[>+[<]>->+]>-<<`) sets up the tape as
```
0*12 121' 0 110
```
The next section (`[>>-------[[>]+[<]>-]<<-]`) iterates 121 times, appending 249 `1`s to the end of the tape each time. If you're quick with math, you might realise this 121\*249 results in 30129 `1`s, but the first iteration has the leftover 110 to deal with and only appends (`110-7`) 103 `1`s to the tape, meaning there's only 29983 `1`s. The final tape looks like:
```
0*12 0' 0 0 1*29983 0 ???
```
And a final `>>>[>]>.` to print the value.
Some other algorithms of note:
* 252\*119 = 29988 (also 50 bytes)
* 163\*184 = 29992 (56 bytes)
* 204\*147 = 29988 (60 bytes)
* 153\*196 = 29988 (56 bytes)
* 191\*157 = 29987 (57 bytes)
* 254\*118 = 29972 (56 bytes)
+ This one is the one I consider the next closest to beating 50, since the extra bytes are basically just travelling the extra distance. If I could find an algorithm that generates 118 and travels further than 14 cells, this could beat it.
[Answer]
# 81
```
-[+>+[<]>++]<<+[-->-[-<]>]>-[>[->+[[->+<]<]>>>]<[-<<+>>]<<<-]>-------[[->+<]>-]>.
```
This moves over by 150 cells 200 times.
This is much longer than I'd like it to be, and there's a serious obstacle to golfing:
I no longer know why I works.
This is littered with compensations for off-by-ones to the point where some of them could probably cancel out. I've added and deleted various segments so much that I no longer remember why I put certain things where they are (for example, why does the first part initialize the tape cells to 199 and 151 instead of 200 and 150?).
Here is my commented version of this monstrosity anyways, in the hope that I (or someone else) might find them useful:
```
-[+>+[<]>++]<<+[-->-[-<]>]>-
0 0 0 199' 155
[
n' k 0
>[
n k' j
->+[[->+<]<]>
0' n k-1 j+1 OR
n 0 0' j+1
>>
]
0*k n 0 0 k 0'
<[-<<+>>]<<<-
0*k n-1' k
]
>-------[[->+<]>-]>.
```
] |
[Question]
[
What better problem for PCG.SE than to implement [PCG, A Better Random Number Generator](http://www.pcg-random.org/)? This new [paper](http://www.pcg-random.org/pdf/toms-oneill-pcg-family.pdf) claims to present a fast, hard-to-predict, small, statistically optimal random number generator.
Its minimal C implementation is just about nine lines:
```
// *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill / pcg-random.org
// Licensed under Apache License 2.0 (NO WARRANTY, etc. see website)
typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t;
uint32_t pcg32_random_r(pcg32_random_t* rng)
{
uint64_t oldstate = rng->state;
// Advance internal state
rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1);
// Calculate output function (XSH RR), uses old state for max ILP
uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
uint32_t rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
```
(from: <http://www.pcg-random.org/download.html>)
The question is: can you do better?
# Rules
Write a program or define a function that implements PCG on 32-bit unsigned integers.
This is fairly broad: you could print out an infinite sequence, define a `pcg32_random_r` function and corresponding struct, etc.
You must be able to seed your random number generator equivalently to the following C function:
```
// pcg32_srandom(initstate, initseq)
// pcg32_srandom_r(rng, initstate, initseq):
// Seed the rng. Specified in two parts, state initializer and a
// sequence selection constant (a.k.a. stream id)
void pcg32_srandom_r(pcg32_random_t* rng, uint64_t initstate, uint64_t initseq)
{
rng->state = 0U;
rng->inc = (initseq << 1u) | 1u;
pcg32_random_r(rng);
rng->state += initstate;
pcg32_random_r(rng);
}
```
(from: `pcg_basic.c:37`)
Calling the random number generator without seeding it first is undefined behaviour.
To easily check your submission, verify that, when seeded with `initstate = 42` and `initseq = 52`, the output is `2380307335`:
```
$ tail -n 8 pcg.c
int main()
{
pcg32_random_t pcg;
pcg32_srandom_r(&pcg, 42u, 52u);
printf("%u\n", pcg32_random_r(&pcg));
return 0;
}
$ gcc pcg.c
$ ./a.out
2380307335
```
# Scoring
Standard scoring.
Measured in bytes.
Lowest is best.
In case of tie, earlier submission wins.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
# Sample solution
Compiles under `gcc -W -Wall` cleanly (version 4.8.2).
Compare your submission to this to make sure you get the same sequence.
```
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t;
uint32_t pcg32_random_r(pcg32_random_t* rng)
{
uint64_t oldstate = rng->state;
// Advance internal state
rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1);
// Calculate output function (XSH RR), uses old state for max ILP
uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
uint32_t rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
void pcg32_srandom_r(pcg32_random_t* rng, uint64_t initstate, uint64_t initseq)
{
rng->state = 0U;
rng->inc = (initseq << 1u) | 1u;
pcg32_random_r(rng);
rng->state += initstate;
pcg32_random_r(rng);
}
int main()
{
size_t i;
pcg32_random_t pcg;
pcg32_srandom_r(&pcg, 42u, 52u);
for (i = 0; i < 16; i++)
{
printf("%u\n", pcg32_random_r(&pcg));
}
return 0;
}
```
Sequence:
```
2380307335
948027835
187788573
3952545547
2315139320
3279422313
2401519167
2248674523
3148099331
3383824018
2720691756
2668542805
2457340157
3945009091
1614694131
4292140870
```
[Answer]
# CJam, ~~109~~ ~~107~~ ~~104~~ ~~98~~ 91 bytes
This uses some characters outside the ASCII range, but they are all within extended ASCII, so I'm counting each character as a byte (instead of counting as UTF-8).
```
{[2*0:A)|:B{AA"XQô-L-"256b*B1|+GG#%:A;__Im>^27m>_@59m>_@\m>@@~)31&m<|4G#%}:R~@A+:AR];}:S;
```
This is basically an exact port of the C code.
The seed function is a block stored in `S`, and the random function is a block stored in `R`. `S` expects `initstate` and `initseq` on the stack and seed the PRNG. `R` doesn't expect anything on the stack and leaves the next random number on it.
Since calling `R` before calling `S` is undefined behaviour, I'm actually defining `R` *within* `S`, so until you use the seed block, `R` is just an empty string and useless.
The `state` is stored in variable `A` and the `inc` is stored in `B`.
Explanation:
```
"The seed block S:";
[ "Remember start of an array. This is to clear the stack at the end.";
2* "Multiply initseq by two, which is like a left-shift by one bit.";
0:A "Store a 0 in A.";
)|:B "Increment to get 1, bitwise or, store in B.";
{...}:R "Store this block in R. This is the random function.";
~ "Evaluate the block.";
@A+:A "Pull up initstate, add to A and store in A.";
R "Evaluate R again.";
]; "Wrap everything since [ in an array and discard it.";
"The random block R:";
AA "Push two A's, one of them to remember oldstate.";
"XQô-L-"256b* "Push that string and interpret the character codes as base-256 digits.
Then multiply A by this.";
B1|+ "Take bitwise or of 1 and inc, add to previous result.";
GG#%:A; "Take modulo 16^16 (== 2^64). Store in A. Pop.";
__ "Make two copies of old state.";
Im>^ "Right-shift by 18, bitwise xor.";
27m>_ "Right-shift by 27. Duplicate.";
@59m> "Pull up remaining oldstate. Right-shift by 59.";
_@\m> "Duplicate, pull up xorshifted, swap order, right-shift.";
@@ "Pull up other pair of xorshifted and rot.";
~) "Bitwise negation, increment. This is is like multiplying by -1.";
31& "Bitwise and with 31. This is the reason I can actually use a negative value
in the previous step.";
m<| "Left-shift, bitwise or.";
4G#% "Take modulo 4^16 (== 2^32).";
```
And here is the equivalent of the test harness in the OP:
```
42 52 S
{RN}16*
```
which prints the exact same numbers.
[Test it here.](http://cjam.aditsu.net/) Stack Exchange strips the two unprintable characters, so it won't work if you copy the above snippet. Copy the code from [the character counter](https://mothereff.in/byte-counter#%7B%5B2%2a0%3AA%29%7C%3AB%7BAA%22XQ%C3%B4-L%C2%95%7F-%22256b%2aB1%7C%2BGG%23%25%3AA%3B%5f%5fIm%3E%5E27m%3E%5f%4059m%3E%5f%40%5Cm%3E%40%40~%2931%26m%3C%7C4G%23%25%7D%3AR~%40A%2B%3AAR%5D%3B%7D%3AS%3B) instead.
[Answer]
# C, 195
I figured someone ought to post a more compact C implementation, even if it stands no chance of winning. The third line contains two functions: `r()` (equivalent to `pcg32_random_r()`) and `s()` (equivalent to `pcg32_srandom_r()`). The last line is the `main()` function, which is excluded from the character count.
```
#define U unsigned
#define L long
U r(U L*g){U L o=*g;*g=o*0x5851F42D4C957F2D+(g[1]|1);U x=(o>>18^o)>>27;U t=o>>59;return x>>t|x<<(-t&31);}s(U L*g,U L i,U L q){*g++=0;*g--=q+q+1;r(g);*g+=i;r(g);}
main(){U i=16;U L g[2];s(g,42,52);for(;i;i--)printf("%u\n",r(g));}
```
Although the compiler will complain, this should work properly on a 64-bit machine. On a 32-bit machine you'll have to add another 5 bytes to change `#define L long` to `#define L long long` ([like in this ideone demo](http://ideone.com/4p2wrL)).
[Answer]
# Julia, ~~218~~ ~~199~~ 191 bytes
Renaming data types plus a few other little tricks helped me to cut down the length by additional 19 bytes. Mainly by omitting two **::Int64** type assignments.
```
type R{T} s::T;c::T end
R(s,c)=new(s,c);u=uint32
a(t,q)=(r.s=0x0;r.c=2q|1;b(r);r.s+=t;b(r))
b(r)=(o=uint64(r.s);r.s=o*0x5851f42d4c957f2d+r.c;x=u((o>>>18$o)>>>27);p=u(o>>>59);x>>>p|(x<<-p&31))
```
Explanation of the names (with according names in the ungolfed version below):
```
# R : function Rng
# a : function pcg32srandomr
# b : function pcg32randomr
# type R: type Rng
# r.s : rng.state
# r.c : rng.inc
# o : oldstate
# x : xorshifted
# t : initstate
# q : initseq
# p : rot
# r : rng
# u : uint32
```
Initialize seed with state 42 and sequence 52. Due to the smaller program you need to state the data type explicitely during initialization now (saved 14 bytes of code or so). You can omit the explicit type assignment on 64-bit systems:
```
r=R(42,52) #on 64-bit systems or r=R(42::Int64,52::Int64) on 32 bit systems
a(r.s,r.c)
```
Produce first set of random numbers:
```
b(r)
```
Result:
```
julia> include("pcg32golfed.jl")
Checking sequence...
result round 1: 2380307335
target round 1: 2380307335 pass
result round 2: 948027835
target round 2: 948027835 pass
result round 3: 187788573
target round 3: 187788573 pass
.
.
.
```
I was really surprised, that even my ungolfed Julia version below is so much smaller (543 bytes) than the sample solution in C (958 bytes).
## Ungolfed version, 543 bytes
```
type Rng{T}
state::T
inc::T
end
function Rng(state,inc)
new(state,inc)
end
function pcg32srandomr(initstate::Int64,initseq::Int64)
rng.state =uint32(0)
rng.inc =(initseq<<1|1)
pcg32randomr(rng)
rng.state+=initstate
pcg32randomr(rng)
end
function pcg32randomr(rng)
oldstate =uint64(rng.state)
rng.state =oldstate*uint64(6364136223846793005)+rng.inc
xorshifted=uint32(((oldstate>>>18)$oldstate)>>>27)
rot =uint32(oldstate>>>59)
(xorshifted>>>rot) | (xorshifted<<((-rot)&31))
end
```
You initialize the seed (initial state=42, initial sequence=52) with:
```
rng=Rng(42,52)
pcg32srandomr(rng.state,rng.inc)
```
Then you can create random numbers with:
```
pcg32randomr(rng)
```
Here is the result of a test script:
```
julia> include("pcg32test.jl")
Test PCG
Initialize seed...
Checking sequence...
result round 1: 2380307335
target round 1: 2380307335 pass
result round 2: 948027835
target round 2: 948027835 pass
result round 3: 187788573
target round 3: 187788573 pass
.
.
.
result round 14: 3945009091
target round 14: 3945009091 pass
result round 15: 1614694131
target round 15: 1614694131 pass
result round 16: 4292140870
target round 16: 4292140870 pass
```
As I’m an abysmal programmer, it took me almost a day to get it working. The last time I tried coding something in C (actually C++) was almost 18 years ago, but a lot of google-fu finally helped me to create a working Julia version. I have to say, I have learned a lot during just a few days on codegolf.
Now I can start to work on a Piet version. That’s gonna be a whole lot of work, but I **really, really** want a (good) random number generator for Piet ;)
] |
[Question]
[
### Introduction
Everyone knows the game tic-tac-toe, but in this challenge, we are going to introduce a little twist. We are only going to use **crosses**. The first person who places three crosses in a row loses. An interesting fact is that the maximum amount of crosses before someone loses, is equal to **6**:
```
X X -
X - X
- X X
```
That means that for a 3 x 3 board, the maximum amount is **6**. So for N = 3, we need to output 6.
Another example, for N = 4, or a 4 x 4 board:
```
X X - X
X X - X
- - - -
X X - X
```
This is an optimal solution, you can see that the maximum amount of crosses is equal to **9**. An optimal solution for a 12 x 12 board is:
```
X - X - X - X X - X X -
X X - X X - - - X X - X
- X - X - X X - - - X X
X - - - X X - X X - X -
- X X - - - X - - - - X
X X - X X - X - X X - -
- - X X - X - X X - X X
X - - - - X - - - X X -
- X - X X - X X - - - X
X X - - - X X - X - X -
X - X X - - - X X - X X
- X X - X X - X - X - X
```
This results in **74**.
### The task
The task is simple, given an integer greater than 0, output the *maximum* amount of crosses that can be placed with no three X's adjacent in a line along a row, column or diagonally.
### Test cases
```
N Output
1 1
2 4
3 6
4 9
5 16
6 20
7 26
8 36
9 42
```
More information can be found at <https://oeis.org/A181018>.
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
* You may provide a function or a program.
[Answer]
## CJam (58 56 bytes)
```
2q~:Xm*{7Yb#W=}:F,Xm*{ee{~0a@*\+}%zS*F},_Wf%:z&Mf*1fb:e>
```
This is incredibly slow and uses a lot of memory, but that's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") for you.
### Dissection
```
2q~:Xm* e# Read input into X and find Cartesian product {0,1}^X
{7Yb#W=}:F, e# Filter with a predicate F which rejects arrays with a 111
Xm* e# Take the Cartesian product possible_rows^X to get possible grids
{ e# Filter out grids with an anti-diagonal 111 by...
ee{~0a@*\+}% e# prepending [0]*i to the ith row
zS*F e# transposing, joining on a non-1, and applying F
},
_Wf%:z e# Copy the filtered arrays and map a 90 degree rotation
& e# Intersect. The rotation maps horizontal to vertical and
e# anti-diagonal to diagonal, so this gets down to valid grids
Mf* e# Flatten each grid
1fb e# Count its 1s
:e> e# Select the maximum
```
The number of valid rows is a [tribonacci number](https://oeis.org/A000073) and is \$\Theta(a^X)\$ where \$a\$ is the tribonacci constant, \$1.83928675\ldots\$. The number of grids generated in the Cartesian product is \$\Theta(a^{X^2})\$; the second filter will reduce the number somewhat, but the intersection is still probably \$\Theta(a^{X^4})\$.
---
An "efficient" approach ("merely" \$O(X a^{3X})\$) uses dynamic programming. Ungolfed in Java:
```
public class A181018 {
public static void main(String[] args) {
for (int i = 1; i < 14; i++) {
System.out.format("%d:\t%d\n", i, calc(i));
}
}
private static int calc(int n) {
if (n < 0) throw new IllegalArgumentException("n");
if (n < 3) return n * n;
// Dynamic programming approach: given two rows, we can enumerate the possible third row.
// sc[i + rows.length * j] is the greatest score achievable with a board ending in rows[i], rows[j].
int[] rows = buildRows(n);
byte[] sc = new byte[rows.length * rows.length];
for (int j = 0, k = 0; j < rows.length; j++) {
int qsc = Integer.bitCount(rows[j]);
for (int i = 0; i < rows.length; i++) sc[k++] = (byte)(qsc + Integer.bitCount(rows[i]));
}
int max = 0;
for (int h = 2; h < n; h++) {
byte[] nsc = new byte[rows.length * rows.length];
for (int i = 0; i < rows.length; i++) {
int p = rows[i];
for (int j = 0; j < rows.length; j++) {
int q = rows[j];
// The rows which follow p,q cannot intersect with a certain mask.
int mask = (p & q) | ((p << 2) & (q << 1)) | ((p >> 2) & (q >> 1));
for (int k = 0; k < rows.length; k++) {
int r = rows[k];
if ((r & mask) != 0) continue;
int pqrsc = (sc[i + rows.length * j] & 0xff) + Integer.bitCount(r);
int off = j + rows.length * k;
if (pqrsc > nsc[off]) nsc[off] = (byte)pqrsc;
if (pqrsc > max) max = pqrsc;
}
}
}
sc = nsc;
}
return max;
}
private static int[] buildRows(int n) {
// Array length is a tribonacci number.
int c = 1;
for (int a = 0, b = 1, i = 0; i < n; i++) c = a + (a = b) + (b = c);
int[] rows = new int[c];
int i = 0, j = 1, val;
while ((val = rows[i]) < (1 << (n - 1))) {
if (val > 0) rows[j++] = val * 2;
if ((val & 3) != 3) rows[j++] = val * 2 + 1;
i++;
}
return rows;
}
}
```
[Answer]
## Pyth, ~~57~~ ~~51~~ 49 bytes
```
L.T.e+*]Ykbbsef!s.AMs.:R3ssmyBdsm_BdCBcTQsD^U2^Q2
```
Like @PeterTaylor's CJam solution, this is brute-force, so it runs in O(n22n2) time. The online interpreter doesn't finish within a minute for n=4.
Try it [here](https://pyth.herokuapp.com/?code=L.T.e%2B%2a%5DYkbbsef%21s.AMs.%3AR3ssmyBdsm_BdCBcTQsD%5EU2%5EQ2&input=2&test_suite=1&test_suite_input=1%0A2%0A3&debug=0) for N<4.
Try the [diagonals function](https://pyth.herokuapp.com/?code=L.T.e%2B%2a%5DYkbb%0AJsm_BdCBQ%0A%22%5Cn%22%0AssmyBdJ&input=%5B%5B3%2C1%2C4%5D%2C%5B1%2C5%2C9%5D%2C%5B2%2C6%2C5%5D%5D&debug=0).
```
L.T.e+*]Ykbb y(b): diagonals of b (with some trailing [])
s e sum of the last (with most ones) array such that
f filter lambda T:
! s .AM none of the 3 element sublists are all ones
s .:R3 all 3 element sublists
s s flatten
myBd add the diagonals
sm_B d add the vertically flipped array and transpose
CBcTQ array shaped into Q by Q square, and its transpose
sD ^U2 ^Q2 all binary arrays of length Q^2 sorted by sum
```
[Answer]
# C, ~~460~~ ~~456~~ ~~410~~ ~~407~~ ~~362~~ ~~351~~ 318 bytes
This is a really bad answer. It's an *incredibly* slow brute force approach. ~~I'm trying to golf it a bit more by combining the `for` loops.~~
```
#define r return
#define d(x,y)b[x]*b[x+y]*b[x+2*(y)]
n,*b;s(i){for(;i<n*(n-2);++i)if(d(i%(n-2)+i/(n-2)*n,1)+d(i,n)+(i%n<n-2&&d(i,n+1)+d(i+2,n-1)))r 1;r 0;}t(x,c,l,f){if(s(0))r 0;b[x]++;if(x==n*n-1)r c+!s(0);l=t(x+1,c+1);b[x]--;f=t(x+1,c);r l>f?l:f;}main(c,v)char**v;{n=atol(v[1]);b=calloc(n*n,4);printf("%d",t(0,0));}
```
## Test Cases
```
$ ./a.out 1
1$ ./a.out 2
4$ ./a.out 3
6$ ./a.out 4
9$ ./a.out 5
16$
```
## Ungolfed
```
n,*b; /* board size, board */
s(i) /* Is the board solved? */
{
for(;i<n*(n-2);++i) /* Iterate through the board */
if(b[i%(n-2)+i/(n-2)*n]&&b[i%(n-2)+i/(n-2)*n+1]&&b[i%(n-2)+i/(n-2)*n+2] /* Check for horizontal tic-tac-toe */
|| b[i] && b[i+n] && b[i+2*n] /* Check for vertical tic-tac-toe */
|| (i%n<n-2
&& (b[i] &&b [i+n+1] && b[i+2*n+2] /* Check for diagonal tic-tac-toe */
|| b[i+2*n] && b[i+n+1] && b[i+2]))) /* Check for reverse diagonal tic-tac-toe */
return 1;
return 0;
}
t(x,c,l,f) /* Try a move at the given index */
{
if(s(0)) /* If board is solved, this is not a viable path */
return 0;
b[x]++;
if(x==n*n-1) /* If we've reached the last square, return the count */
return c+!s(0);
/* Try it with the cross */
l=t(x+1,c+1);
/* And try it without */
b[x]--;
f=t(x+1,c);
/* Return the better result of the two */
return l>f?l:f;
}
main(c,v)
char**v;
{
n=atol(v[1]); /* Get the board size */
b=calloc(n*n,4); /* Allocate a board */
printf("%d",t(0,0)); /* Print the result */
}
```
---
Edit: Declare int variables as unused parameters; remove y coordinate, just use index; move variable to parameter list rather than global, fix unnecessary parameters passed to `s()`; combine for loops, remove unnecessary parentheses; replace `&&` with `*`, `||` with `+`; macro-ify the 3-in-a-row check
[Answer]
# C 263 ~~264 283 309~~
**Edit** A few bytes saved thx @Peter Taylor - less than I hoped. Then 2 bytes used to allocate some more memory, now I can try larger size, but it's becoming very time consuming.
**Note** While adding the explanation, I found out that i'm wasting bytes keeping the grid in the R array - so that you can to see the solution found ... it's not requested for this challenge!!
I removed it in the golfed version
A golfed C program that can actually find the answer for n=1..10 in reasonable time.
```
s,k,n,V[9999],B[9999],i,b;K(l,w,u,t,i){for(t=u&t|u*2&t*4|u/2&t/4,--l; i--;)V[i]&t||(b=B[i]+w,l?b+(n+2)/3*2*l>s&&K(l,b,V[i],u,k):b>s?s=b:0);}main(v){for(scanf("%d",&n);(v=V[i]*2)<1<<n;v%8<6?B[V[k]=v+1,k++]=b+1:0)V[k]=v,b=B[k++]=B[i++];K(n,0,0,0,k);printf("%d",s);}
```
My test:
>
> 7 -> 26 in 10 sec
>
> 8 -> 36 in 18 sec
>
> 9 -> 42 in 1162 sec
>
>
>
**Less golfed** and trying to explain
```
#include <stdio.h>
int n, // the grid size
s, // the result
k, // the number of valid rows
V[9999], // the list of valid rows (0..to k-1) as bitmasks
B[9999], // the list of 'weight' for each valid rows (number of set bits)
R[99], // the grid as an array of indices pointing to bitmask in V
b,i; // int globals set to 0, to avoid int declaration inside functions
// recursive function to fill the grid
int K(
int l, // number of rows filled so far == index of row to add
int w, // number of crosses so far
int u, // bit mask of the preceding line (V[r[l-1]])
int t, // bit mask of the preceding preceding line (V[r[l-2]])
int i) // the loop variables, init to k at each call, will go down to 0
{
// build a bit mask to check the next line
// with the limit of 3 crosses we need to check the 2 preceding rows
t = u&t | u*2 & t*4 | u/2 & t/4;
for (; i--; )// loop on the k possibile values in V
{
R[l] = i; // store current row in R
b = B[i] + w; // new number of crosses if this row is accepted
if ((V[i] & t) == 0) // check if there are not 3 adjacent crosses
// then check if the score that we can reach from this point
// adding the missing rows can eventually be greater
// than the current max score stored in s
if (b + (n + 2) / 3 * 2 * (n - l - 1) > s)
if (l > n-2) // if at last row
s = b > s ? b : s; // update the max score
else // not the last row
K(l + 1, b, V[i], u, k); // recursive call, try to add another row
}
}
int main(int j)
{
scanf("%d", &n);
// find all valid rows - not having more than 2 adjacent crosses
// put valid rows in array V
// for each valid row found, store the cross number in array B
// the number of valid rows will be in k
for (; i<1 << n; V[k] = i++, k += !b) // i is global and start at 0
for (b = B[k] = 0, j = i; j; j /= 2)
b = ~(j | -8) ? b : 1, B[k] += j & 1;
K(0,0,0,0,k); // call recursive function to find the max score
printf("%d\n", s);
}
```
[Answer]
# Ruby, 263 bytes
This is also a brute force solution and faces the same problems as the C answer by Cole Cameron, but is even slower since this is ruby and not C. But hey, it's shorter.
```
c=->(b){b.transpose.all?{|a|/111/!~a*''}}
m=->(b,j=0){b[j/N][j%N]=1
x,*o=b.map.with_index,0
c[b]&&c[b.transpose]&&c[x.map{|a,i|o*(N-i)+a+o*i}]&&c[x.map{|a,i|o*i+a+o*(N-i)}]?(((j+1)...N*N).map{|i|m[b.map(&:dup),i]}.max||0)+1:0}
N=$*[0].to_i
p m[N.times.map{[0]*N}]
```
Test cases
```
$ ruby A181018.rb 1
1
$ ruby A181018.rb 2
4
$ ruby A181018.rb 3
6
$ ruby A181018.rb 4
9
$ ruby A181018.rb 5
16
```
Ungolfed
```
def check_columns(board)
board.transpose.all? do |column|
!column.join('').match(/111/)
end
end
def check_if_unsolved(board)
check_columns(board) && # check columns
check_columns(board.transpose) && # check rows
check_columns(board.map.with_index.map { |row, i| [0] * (N - i) + row + [0] * i }) && # check decending diagonals
check_columns(board.map.with_index.map { |row, i| [0] * i + row + [0] * (N - i) }) # check ascending diagonals
end
def maximum_crosses_to_place(board, index=0)
board[index / N][index % N] = 1 # set cross at index
if check_if_unsolved(board)
crosses = ((index + 1)...(N*N)).map do |i|
maximum_crosses_to_place(board.map(&:dup), i)
end
maximum_crosses = crosses.max || 0
maximum_crosses + 1
else
0
end
end
N = ARGV[0].to_i
matrix_of_zeros = N.times.map{ [0]*N }
puts maximum_crosses_to_place(matrix_of_zeros)
```
[Answer]
# Haskell, 143 bytes
In some ways this is not done, but I had fun so here goes:
* Because checking for the horizontal "winning" pattern returns invalid if applied across different rows, input of N<3 returns 0
* The "arrays" are integers unpacked into bits, so easily enumerable
* ((i ! x) y) gives the ith bit of x times y, where negative indices return 0 so the range can be constant (no bounds checking) and fewer parentheses when chained
* Because the bounds are not checked, it checks 81\*4=324 patterns for *every* possible maximum, leading to N=3 taking my laptop 9 seconds and N=5 taking too long for me to let it finish
* Boolean logic on 1/0 is used for T/F to save space, for example (\*) is &&, (1-x) is (not x), etc.
* Because it checks integers instead of arrays, (div p1 L)==(div p2 L) is needed to make sure a pattern isn't checked across different rows, where L is the row length and p1, p2 are positions
* The value of a possible maximum is its Hamming Weight
Here's the code:
```
r=[0..81]
(%)=div
s=sum
i!x|i<0=(*0)|0<1=(*mod(x%(2^i))2)
f l=maximum[s[i!x$1-s[s[1#2,l#(l+l),(l+1)#(l+l+2),(1-l)#(2-l-l)]|p<-r,let a#b=p!x$(p+a)!x$(p+b)!x$s[1|p%l==(p+mod b l)%l]]|i<-r]|x<-[0..2^l^2]]
```
] |
[Question]
[
It is in my humble opinion that standard text is boring. Therefore I propose a new writing standard, walking words!
### Walking words
Walking words are words which will respond to certain characters. For the purpose of this challenge the trigger characters are `[u, d, r, l]` from `up down right left`.
Whenever you encounter such a character when printing text, you will move the direction of the text.
For example, the text `abcdef` will result in:
```
abcd
e
f
```
### Rules
* Both uppercase `UDRL` and lowercase `udrl` should change the direction, but case should be preserved in the output
* Input will only contain printable characters `(0-9, A-Z, a-z, !@#%^&*() etc...)`, no newlines!
* Whenever the text will collide, it will overwrite the old character at that position
* Output should be presented to the user in any fashionable matter, but it should be a single output (no array of lines)
* Trailing and leading newlines are allowed
* Trailing spaces are allowed
* Standard loopholes apply
### Test cases
```
empty input => empty output or a newline
u =>
u
abc =>
abc
abcd =>
abcd
abcde =>
abcd
e
abcdde =>
abcd
d
e
codegolf and programming puzzles =>
cod
e
g
o
dna fl sel
z
p z
rogramming pu
ABCDELFUGHI =>
I
AHCD
G E
UFL
It is in my humble opinion that standard text is boring. Therefore I propose a new writing standard, walking words! =>
dnats taht noinipo el
a b
rd m
It is in my hu
t
e
x
t
i
s
b
o
ring. Therefore I propose a new writing stand
a
rd
,
w
a
rdw gnikl
s
!
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins!
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 63 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
`s@(n+11 9∘○¨+\0j1*⊃¨,⍨\(8∘≠⍴¨⊢)0,'rdluRDLU'⍳¯1↓s)⍴∘'',⍨2×n←≢s←⍞`
uses `⎕IO←0` and features from v16 (`@`)
`n←≢s←⍞` raw input `s` and its length `n`
`⍴∘'',⍨2×n` create a 2n by 2n matrix of spaces
`s@(...)` amend the matrix with the characters of `s` at the specified (pairs of) indices
how the indices are computed:
`¯1↓s` drop the last char of `s`
`'rdluRDLU'⍳'` encode `'r'` as 0, `'d'` as 1, etc; other chars as 8
`0,` prepend a 0
`(8∘≠⍴¨⊢)` turn every 8 into an empty list, all others into a 1-element list
`,⍨\` cumulative swapped concatenations (`abcd` -> `a ba cba dcba`)
`⊃¨` first from each
`0j1*` imaginary constant i to the power of
`+\` cumulative sums
`11 9∘○¨` real and imaginary part from each; get coords in the range `-n`...`n`
`n+` centre them on the big matrix
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ ~~27~~ ~~20~~ 19 bytes
```
FS«F№rdlu↧ι≔ιω✳∨ωrι
```
[Try it online!](https://tio.run/##HY1BCsIwEADP7SuWnDYQX@BJKoggWPAFIU3rQpqVTWKh4ttj8DrMMO5pxbENtc4sgNf4KvmRheKCWsOn7/544BIzKplCUQZuvHlxNnkk3aRTSrREJAObPvbd2OKMZxLvMnHEu@BmQInS2gA141vrKLyIXde2gbHse/AJbJxg4MnDhcPc18M7/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS«
```
Loop over the input characters.
```
F№rdlu↧ι
```
If the current letter is a direction...
```
≔ιω
```
then update the current walking direction.
```
✳∨ωrι
```
Print the character in the current walking direction, defaulting to right if no direction has been set yet.
[Answer]
# Pyth, ~~68~~ 65 bytes
```
KUJ,00ImXH~+VJ=@as_BM_MBU2Kx"rdlu"rd0dzjcsm.x@Hd;*Fm=Z}hdedSMCHlZ
```
[Test suite](https://pyth.herokuapp.com/?code=KUJ%2C00ImXH~%2BVJ%3D%40as_BM_MBU2Kx%22rdlu%22rd0dzjcsm.x%40Hd%3B%2aFm%3DZ%7DhdedSMCHlZ&test_suite=1&test_suite_input=%0Au%0Aabc%0Aabcd%0Aabcde%0Aabcdde%0Acodegolf+and+programming+puzzles%0AABCDELFUGHI%0AIt+is+in+my+humble+opinion+that+standard+text+is+boring.+Therefore+I+propose+a+new+writing+standard%2C+walking+words%21&debug=0)
This uses a dictionary, indexed by a pair of coordinates, that is updated as the input read, then printed at the end. It also uses a ton of clever golfing tricks.
Here's how I wrote it, using the interpreter's `-m` flag to strip the whitespace and comments before running:
```
KUJ,00 ; Initialize J to [0, 0] and K to [0, 1].
; J is the current location, K is the current direction.
I ; If the following is truthy, which will be when the input
; is nonempty,
m ; Map d over z, the input.
XH ; Assign to H (a hash table, initially empty)
~+VJ ; At location J, then update J by adding elementwise
=@ ; K (Next variable is implicit), which is set to
as_BM_MBU2K ; [0, 1], bifurcated on mapped negation, then mapped on
; reversal bifuraction with the old value of K appended.
; e.g. [[0, 1], [1, 0], [0, -1], [-1, 0], K]
x"rdlu"rd0 ; indexed at location equal to the index of the lowercase
; of the current character into "rdlu", -1 if missing.
d ; Insert the current character with that key.
z ; map over z.
jc ; Join on newlines the result of chopping into a rectangle
sm ; the concatenation of the map
.x@Hd; ; Lookup the character at the given location,
; if none then ' '
*Fm ; Locations are the cartesian product of the map
=Z}hded ; Inclusive range from the head of each list to
; the end of each list
; Saved in Z for later
SMCH ; Transpose the list of keys, and sort the x and y values
; separately.
lZ ; Width of the rectangle should equal the number of
; x values, which is the length of the last entry.
```
[Answer]
# C#, 525 474 Bytes
*Edit: Saved 51 Bytes thanks to @steenbergh*
*It's not pretty, but it does work...*
Golfed:
```
string W(string s){var l=s.Length;var a=new char[2*l+1,2*l+1];int x=2*l/2;int y=2*l/2;int d=0;for(int i=0;i<l;i++){switch(char.ToUpper(s[i])){case'U':d=3;break;case'D':d=1;break;case'L':d=2;break;case'R':d=0;break;}a[y,x]=s[i];switch(d){case 0:x+=1;break;case 1:y+=1;break;case 2:x-=1;break;case 3:y-=1;break;}}string o="";for(int i=0;i<2*l+1;i++){string t="";for(int j=0;j<2*l+1;j++)t+=a[i,j]+"";o+=t==string.Join("",Enumerable.Repeat('\0',2*l+1))?"":(t+"\r\n");}return o;}
```
Ungolfed:
```
public string W(string s)
{
var l = s.Length;
var a = new char[2 * l + 1, 2 * l + 1];
int x = 2 * l / 2;
int y = 2 * l / 2;
int d = 0;
for (int i = 0; i < l; i++)
{
switch (char.ToUpper(s[i]))
{
case 'U':
d = 3;
break;
case 'D':
d = 1;
break;
case 'L':
d = 2;
break;
case 'R':
d = 0;
break;
}
a[y, x] = s[i];
switch (d)
{
case 0:
x += 1;
break;
case 1:
y += 1;
break;
case 2:
x -= 1;
break;
case 3:
y -= 1;
break;
}
}
string o = "";
for (int i = 0; i < 2 * l + 1; i++)
{
string t = "";
for (int j = 0; j < 2 * l + 1; j++)
t += a[i, j] + "";
o += t == string.Join("", Enumerable.Repeat('\0', 2 * l + 1)) ? "" : (t + "\r\n");
}
return o;
}
```
Explanation:
Uses a two-dimensional array and the `d` value to increment the position of the array in the correction direction, where d values are:
```
0 => RIGHT
1 => DOWN
2 => LEFT
3 => UP
```
Test:
```
var walkTheWords = new WalkTheWords();
Console.WriteLine(walkTheWords.W("codegolf and programming puzzles"));
cod
e
g
o
dna fl sel
z
p z
rogramming pu
```
[Answer]
# JavaScript (ES6), 218 ~~220 232~~
**Edit** I was using `u` and `t` to keep track of the top and leftmost position, but I realized that `t` is not needed at all
```
w=>[...w].map(c=>u=(((g[y]=g[y]||[])[x]=c,n=parseInt(c,36)|0)-21&&n-27?a=n-13?n-30?a:!(b=-1):!(b=1):(b=0,a=n/3-8),y+=b,x+=a)<u?x:u,a=1,b=0,x=y=u=w.length,g=[])+g.map(r=>[...r.slice(u)].map(c=>z+=c||' ',z+=`
`),z='')&&z
```
*Less golfed*
```
w=>{
a = 1, b = 0;
x = y = u = w.length;
g = [];
[...w].map(c => (
r = g[y]||[],
r[x] = c,
g[y] = r,
n = parseInt(c,36)|0,
n-21 && n-27 ? n-13 && n-30?0 : (a=0, b=n-13?-1:1) : (b=0, a=n/3-8),
x += a, u = x<u? x : u,
y += b
))
z=''
g.map(r=>[...r.slice(u)].map(c=>z += c||' ', z += '\n'))
return z
}
```
**Test**
```
F=
w=>[...w].map(c=>u=(((g[y]=g[y]||[])[x]=c,n=parseInt(c,36)|0)-21&&n-27?a=n-13?n-30?a:!(b=-1):!(b=1):(b=0,a=n/3-8),y+=b,x+=a)<u?x:u,a=1,b=0,x=y=u=w.length,g=[])+g.map(r=>[...r.slice(u)].map(c=>z+=c||' ',z+=`
`),z='')&&z
function update() {
w=I.value
O.textContent=F(w)
}
update()
```
```
#I {width:90%}
```
```
<input id=I value='It is in my humble opinion that standard text is boring. Therefore I propose a new writing standard, walking words!' oninput='update()'>
<pre id=O></pre>
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27 26 25 23~~ 22 bytes
Saved 3 bytes thanks to *Grimy*
```
ā¤‹>Šε’uχ’slkDÈiV}Y}Λ
```
[Try it online!](https://tio.run/##PYsxDoJAFAWv8uyNR7CyoTcmlkv4wg@wn@wuWS1IsLOzNjaaeAULW9GWQ3CRFS3sJpMZsSpmCuG1f96G9jF/X/r70J7q7ji01xFskS@6A6@addOfQ4gc2II1yh2yuowLglSsWTRcphysUzpRJoGj7S@NxbBOZ1hmZGgjhhChMlKJJSho8vCG3Zj81ym8KvKv8WISO/kA "05AB1E – Try It Online")
**Explanation**
```
ā # push [1 ... len(input)]
¤‹ # check each number if its less than the max
> # increment
# results in a list as long as the input where each number is 2
# apart from the last one, this is the lengths to draw
Š # move 2 copies of the input to the top of the stack
# the first one is the string to draw
ε } # for each char in the second copy
’uχ’slk # get the chars index in "ubridal"
D # duplicate
Èi } # if the index is even
V # store it in Y
Y # push Y (initially 2)
# this gives us the list of directions
Λ # draw everything on the canvas
```
[Answer]
## Javascript, 4̶6̶6̶, ~~455~~, 433 Bytes
Edits:
11 Bytes saved, thanks to user 1000000000
10 or so saved, thanks to user2428118
Also removed some unnecessary semi-colons.
I'm pretty sure this can be golfed further, but i couldn't quite manage it.
I'm still new whole thing, so any advice is much appreciated :)
```
z=a=>{b=c=0;j=[[]];d='';a.split``.forEach(g=>{h=g.toLowerCase();if('ruld'.includes(h)){d=h}f=x=>new Array(x[0].length).fill` `;switch(d){case 'l':if(!b){j.forEach(e => e.unshift` `);++b}j[c][b--]=g;break;case 'u':if(!c){j.unshift(f(j));++c}j[c--][b]=g;break;case 'd':if(c == j.length-1){j.push(f(j))}j[c++][b]=g;break;default:if(b==(j[0].length-1)){j.forEach(row=>row.push` `)}j[c][b++] = g;break}});j.forEach(x=>console.log(x.join``))}
```
```
<input id="a"> </input>
<input type="submit" onclick="z(document.getElementById('a').value);"/>
```
Ungolfed:
```
z=a=>{
b=c=0;
j=[[]];
d='';
a.split``.forEach(g=>{
h=g.toLowerCase();
if('ruld'.includes(h)){d=h;}
f=x=>new Array(x[0].length).fill` `;
switch(d){
case 'l':
if(!b){
j.forEach(e => e.unshift` `);
++b;
}
j[c][b--] = g;
break;
case 'u':
if(!c){
j.unshift(f(j));
++c;
}
j[c--][b] = g;
break;
case 'd':
if(c == j.length-1){
j.push(f(j));
}
j[c++][b] = g;
break;
default:
if(b == (j[0].length-1)){
j.forEach(row=>row.push` `);
}
j[c][b++] = g;
break;
}
});
j.forEach(x => console.log(x.join``));
```
}
I more or less took the approach of:
* Have an array to store output
* Calculate the x and y position of next character in the array
* If the co-ordinates were about to be outside of the array, extend the array in that direction. Either by pushing and extra space onto the end of that row or adding another row entirely.
* Make array[y][x] = current character
* print the resulting array
[Answer]
# Python 3, 314 309 290 268 Bytes
```
x=y=0
d,m=(1,0),{}
q={'u':(0,-1),'d':(0,1),'l':(-1,0),'r':d}
for c in input():m[x,y]=c;d=q.get(c.lower(),d);x,y=x+d[0],y+d[1]
X,Y=zip(*m)
O,P=min(X),min(Y)
r,p=0,print
exec("t=~~O;exec(\"p(m.get((t,r+P),' '),end='');t+=1;\"*-~abs(max(X)-O));r+=1;p();"*-~abs(max(Y)-P))
```
I tried running my program as input to my program with some interesting results. Hah, try interpreting that, Python!
Shaved 5 bytes - compliments to Jack Bates.
23 bytes whisked away by kundor
Note: I think there was some error of measurement with my bytes because of using different editors. However, I'm fairly certain the latest one is correct.
[Answer]
# PHP, ~~238 223 205~~ 204 bytes
12 bytes saved by Jörg (`stripos` instead of `preg_match`), 1 byte +braces by leading instead of trailing newline, 16+braces golfed from the direction change, 1 more with ternary instead of `if`.
```
for($m=$d=1;$o=ord($c=$argn[$i++]);$m=min($m,$x),$n=max($n,$x))stripos(_ulrd,$r[$y+=$e][$x+=$d]=$c)?$d=($e=[1,-1][$o&11])?0:$o%4-1:0;ksort($r);foreach($r as$s)for($i=$m-print"\n";$i++<$n;)echo$s[$i]??" ";
```
Run as pipe with `php -nR '<code>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/0cf5686ca09dbd714cfbdc40109a4dd8a91af78d).
**breakdown**
```
for($m=$d=1; # init max index and x-offset to 1
$o=ord($c=$argn[$i++]); # loop through characters
$m=min($m,$x),$n=max($n,$x)) # 3. adjust min and max x offset
stripos(_ulrd,
$r[$y+=$e][$x+=$d]=$c # 1. move cursor; add character to grid
)? # 2. if direction change
$d=(
$e=[1,-1][$o&11] # set y direction
)
?0:$o%4-1 # set x direction
:0;
ksort($r); # sort rows by index
foreach($r as$s) # loop through rows
for($i=$m-print"\n"; # print newline, reset $i
$i++<$n;) # loop $i from min index to max index
echo$s[$i]??" "; # print character, space if empty
```
[Answer]
# Java 10, ~~288~~ ~~286~~ ~~280~~ 263 bytes
```
s->{int l=s.length(),x=l,y=l,d=82,A=x,B=y;var r=new char[l+=l][l];for(var c:s.toCharArray()){A=x<A?x:A;B=y<B?y:B;r[x][y]=c;c&=~32;d="DLRU".contains(""+c)?c:d;x+=5-d/14;y+=3-(d^16)/23;}s="";for(x=A;x<l;x++,s+="\n")for(y=B;y<l;y++)s+=r[x][y]<1?32:r[x][y];return s;}
```
-17 bytes thanks to *@Grimy*.
**Explanation:**
[Try it here.](https://tio.run/##bVNbb9MwFH7frzhYCCVKmq0tINTUVOkuMNgG7MKtK8i13TabYwfbaZNN5a8XpwsPozw48vnO1d/5ckMWpHXDbtdUEGPglKTyfgcglZbrKaEczmoT4MLqVM6Aes3F@LHDVzvuYyyxKYUzkIDXpvX63iWDwCYSXM7s3PPDEouwcofhV50wwWU4xFW8IBo0lnwJdE70SARYjEdiHE@V9mof7ZnIqn3nS7Qmlef79y61nwzKXhK7Av3hoOoNYz0qx6NqjGlMn@Hf3U7MMDo4Ob9CEVXSuucYD6GA@gPaY3EZ4Bctttt@HlcB7rY89qP90t/tdOOVwQhtWpc4icu@cKFBaAKMriXya7zCw7hyeBUEvsObtv32oNvpNUasuS20BBOv1jU7eTERjpiGn4VKGWRuoIbC0RiI/0Cu5cZ6iEwo49PZPL25FZlU@S9tbLFYltVdMtw/ODx68/b43fuT07MPHz@dX1xeff7y9dt3tFnD3wrFY9MV3ALYNsK3oX8xqhifKTEFIhnkWs00ybJaBnlxdye4eRy9Gffk6MoN/NhxbCE1TluQVTAvsongoPJUpkqCnRNbMyUZ0cyFl5vQiaqZiuByzjV3W@BwXLfPleFAoNbOUqd2o8cmNYQlEbc1slSamSdoS6ebPWzmaaScyrywzSYuKmN5FqnCRrlzWiE9GVHvISTSPBfun0iE8JCXDfzraxM8RSFCfvPM/6Sjn6jO48R67b09vxlntf4D) (NOTE: I remove all trailing spaces/newlines to make the output a bit more compact. Feel free to remove the `.replaceAll("(m?)\\s+$","")` in the `test`-method to see the actual result.)
```
s->{ // Method with String as both parameter and return-type
int l=s.length(), // Length of input String
x=l,y=l, // x,y coordinates, starting at `l`,`l`
d=82, // Direction, starting towards the right
A=x,B=y; // Min x & y values to remove leading spaces at the end
var r=new char[l+=l][l]; // character-matrix, with size `l`+`l` by `l`+`l`
for(var c:s.toCharArray()){ // Loop over the characters of the input String:
A=x<A?x:A; // Adjust minimum x `A` if necessary
B=y<B?y:B; // Adjust minimum y `B` if necessary
r[x][y]=c; // Fill x,y with the current character
c&=~32; // Make character uppercase if it isn't yet
d="DLRU".contains(""+c)?c:d; // Change the direction if necessary
x+=5-d/14; // Set the next x coordinate based on the direction
y+=3-(d^16)/23;} // Set the next y coordinate based on the direction
s=""; // After the loop: create an empty result-String
for(x=A;x<l;x++, // Loop `x` in the range [`A`, `l`):
s+="\n") // And append a new-line after every iteration
for(y=B;y<l;y++) // Inner loop `y` in the range [`B`, `l`):
s+=r[x][y]<1? // If the cell at x,y is empty:
32 // Append a space to the result-String
:r[x][y]; // Else: append the character to the result-String
return s;} // After the nested loop: teturn result-String
```
[Answer]
# Perl, 204 + 3 = 207 bytes
+3 for `-F`
Whitespace is not part of the code and is provided for legibility.
```
%p=(d,1,l,2,u,3,r,$x=$y=0);
for(@F){
$m{"$x,$y"}=$_;
$g=$p{lc$_}if/[dlur]/i;
$g%2?($y+=2-$g):($x+=1-$g);
($a>$x?$a:$b<$x?$b:$x)=$x;
($c>$y?$c:$d<$y?$d:$y)=$y
}
for$k($c..$d){
print($m{"$_,$k"}||$")for$a..$b;
say""
}
```
Similar to my solution to the Fizz Buzz challenge, I create a hash with x,y coordinates for every step along the way, keeping the maximums and minimums of the x- and y- coordinates stored, then loop through and print everything out.
If I'm *desperate* I might be able to turn the last three lines of the first `for` loop into a single disgusting statement that may save a byte or two, but I'm not looking forward to the completely unreadable result.
[Answer]
## Excel VBA, 205 bytes
```
Sub t(a)
Z=1:x=70:y=x:For i=1 To Len(a)
s=Mid(a,i,1):Cells(y,x).Value=s:Select Case LCase(s)
Case "l":Z=-1:w=0
Case "d":Z=0:w=1
Case "r":Z=1:w=0
Case "u":Z=0:w=-1
End Select:x=x+Z:y=y+w:Next:End Sub
```
I'm kinda surprised at Excel's ability to compete with existing answers. It works because `w` and `z` keep track of the direction.
[Answer]
# SmileBASIC, ~~148~~ 146 bytes
```
DEF W M,S,T
WHILE""<M
A=INSTR(@DLURdlur,M[0])*PI()/2IF A>0THEN S=COS(A)T=SIN(A)
X=CSRX+S
Y=CSRY+T?SHIFT(M);
SCROLL-!X,-!Y
LOCATE!X+X,Y+!Y
WEND
END
```
Call the function with `W "text",vx,vy`, where vx and vy is the direction at the start (default is 1,0)
[Answer]
# Swift 3, 283 bytes
```
func w(a:String){var t=a.characters,d=t.count,c=Array(repeating:Array(repeating:" ",count:d*2),count:d*2),i=d,j=d,l=["d":(1,0),"u":(-1,0),"l":(0,-1),"r":(0,1)],e=(0,1)
t.map{c[i][j]="\($0)"
e=l["\($0)".lowercased()] ?? e
i+=e.0
j+=e.1}
c.map{$0.map{print($0,terminator:"")};print()}}
```
**Ungolfed**
```
func w(a:String){
var t=a.characters,d=t.count,c=Array(repeating:Array(repeating:" ",count:d*2),count:d*2),i=d,j=d,l=["d":(1,0),"u":(-1,0),"l":(0,-1),"r":(0,1)],e=(0,1)
t.map{
c[i][j]="\($0)"
e=l["\($0)".lowercased()] ?? e
i+=e.0
j+=e.1
}
c.map{
$0.map{
print($0,terminator:"")
};
print()
}
}
```
**Warning**
Longer input will requires bigger screen. Output has no treatment for "empty" row/columns as I understood that is acceptable by the rules of the challenge.
**Rant**
* Newline being the default terminator for `print` sux
* No simple way of creating an array of known length destroyed the score.
] |
[Question]
[
# Introduction
My grandpa is a fan of James Bond, but he is always unsure on how to rank his favourite actors. As such, he is always making lists, which is a lot of work. He asked me to produce a program that will make his life easier, but I do not have time for that, I have to work! So I will count on you guys.
# Challenge
The challenge is simple. The input will consist of a list, in the following format:
`<number> <space> <actor's name> <newline>`
Your task is to sort them based on the **number** at the beginning of the line, starting from the last, and ending with the first. All numbers should be removed.
However, my grandpa sometimes makes mistakes. As such, you will need to validate the data. If one of the names on the list doesn't refer to one of the actors who played Bond, you need to discard it. In case of repetitions, repeats should be removed, and the name should maintain the lowest weight it was associated with (example #3).
There is no limit to how many lines there may be.
The output only needs to be a list of some sort, whether it is an array, a comma separated string, just values separated by spaces, or something else entirely, i.e.
`Pierce Brosnan, Sean Connery, David Niven`
A trailing newline or space is allowed.
# Example Input and Output
Input:
>
> 1 Sean Connery
>
>
> 2 Emma Watson
>
>
> 5 Timothy Dalton
>
>
> 4 Roger Moore
>
>
> 3 Daniel Craig
>
>
>
Output:
>
> Timothy Dalton, Roger Moore, Daniel Craig, Sean Connery
>
>
>
Input:
>
> 2 Timothy Dalton
>
>
> 4 George Lazenby
>
>
> 5 George Lazenby
>
>
> 3 Bob Simmons
>
>
>
Output:
>
> George Lazenby, Bob Simmons, Timothy Dalton
>
>
>
Input:
>
> 3 Sean Connery
>
>
> 2 Pierce Brosnan
>
>
> 1 Sean Connery
>
>
>
Output:
>
> Pierce Brosnan, Sean Connery
>
>
>
As this is a code golf, shortest code (in bytes) wins!
# Appendix
List of actors who played the role of Bond:
* Barry Nelson
* Bob Simmons
* Sean Connery
* Roger Moore
* David Niven
* George Lazenby
* Timothy Dalton
* Pierce Brosnan
* Daniel Craig
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~201 197~~ 191
```
\d+
$0$*1
G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$
+`\b((1+)\D*)¶(\2.+)
$3¶$1
+s`1+(\D+)¶(.*\1)
$2
1+
```
[Try it online!](http://retina.tryitonline.net/#code=XGQrCiQwJCoxCkdgXjErIChCYXJyeSBOZWxzb258Qm9iIFNpbW1vbnN8U2VhbiBDb25uZXJ5fFJvZ2VyIE1vb3JlfERhdmlkIE5pdmVufEdlb3JnZSBMYXplbmJ5fFRpbW90aHkgRGFsdG9ufFBpZXJjZSBCcm9zbmFufERhbmllbCBDcmFpZykkCitgXGIoKDErKVxEKinCtihcMi4rKQokM8K2JDEKK3NgMSsoXEQrKcK2KC4qXDEpCiQyCjErIAo&input=MSBTZWFuIENvbm5lcnkKMiBFbW1hIFdhdHNvbgo4IFNlYW4gQ29ubmVyeQo1IFRpbW90aHkgRGFsdG9uCjE0IFJvZ2VyIE1vb3JlCjcgU2VhbiBEYWx0b24KNiBTZWFuIENvbm5lcnkKMyBEYW5pZWwgQ3JhaWc)
6 bytes saved thanks to Martin!
Whee, bubble sort with regex. Note that ten bytes are spent doing decimal to unary conversion at the beginning, if unary input is OK then that isn't needed. Also, if numbers can't be in people's names, then a couple more bytes can be saved by moving the line that removes non-Bond actors to the end and removing the `1+` (untested with `\D` version).
### Explanation:
A Retina program is made up of several stages, so I will explain each stage separately.
Stage 1:
```
\d+
$0$*1
```
Replaces the numbers in the input with unary. This uses Retina's special replacement token: `$*` which repeats the character after a number of times equal to the preceding token's base 10 value.
Stage 2:
```
G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$
```
The stuff before a ``` in a stage changes the mode being used. This turns on grep mode, which means that each line that doesn't match the regex is discarded. The anchors are necessary to prevent near matches from slipping by.
Stage 3:
```
+`\b((1+)\D*)¶(\2.+)
$3¶$1
```
This is the sorting stage. The `+` in the mode signifies that this stage should be repeated until the replacement makes no change when applied (i.e. we reach a fixed point). The regex finds a word boundry, followed by some number of `1`s and then all the rest of the line up to the newline. Then, if the next line has more `1`s than it, the regex will match and we swap the lines.
Stage 4:
```
+s`1+(\D+)¶(.*\1)
$2
```
This stage uses the `+` mode again, but also uses `s` to make the `.` meta-character also match newlines. This removes duplicate lines, by matching for exact duplicates after the `1`s and capturing the stuff after the first duplicate to replace the whole match with it. This will work without needing to consider the order of tie breaking, because the names are already sorted appropriately, with the larger numbers above, therefore we will always keep the smaller values.
Stage 5:
```
1+
```
Really simple one here, everything is in order, except we have a bunch of `1`s in front of our Bonds, so we replace them and the space after them with nothing.
[Answer]
## TSQL 426 bytes (includind data + input)
Golfed solution:
```
create table A(Name varchar(99))insert into A values('Barry Nelson'),('Bob Simmons'),('Sean Connery'),('Roger Moore'),('David Niven'),('George Lazenby'),('Timothy Dalton'),('Pierce Brosnan'),('Daniel Craig')declare @I as table (R int, N varchar(99))insert into @I values(3,'Sean Connery'),(2,'Pierce Brosnan'),(1,'Sean Connery')select N from(select N,min(R) R from @I where N in (select N from A) group by N) x order by R desc
```
[Try it here](http://sqlfiddle.com/#!3/e5375/1)
SQL excels (no pun intended) in this kind of task: relating sets, ordering, cutting off duplicates etc.
All you need is to create and populate a table of Actors like this:
```
create table Actor (Name varchar(99))
insert into Actor values
('Barry Nelson')
,('Bob Simmons')
,('Sean Connery')
,('Roger Moore')
,('David Niven')
,('George Lazenby')
,('Timothy Dalton')
,('Pierce Brosnan')
,('Daniel Craig')
```
Now if we use a table-variable as input we just need to get the intersection of both sets. Removing duplicates and ordering in SQL are really easy.
Example 1:
```
declare @Input as table (Rnk int, Name varchar(99))
insert into @Input values
(1,'Sean Connery')
,(2,'Emma Watson')
,(5,'Timothy Dalton')
,(4,'Roger Moore')
,(3,'Daniel Craig')
select Name
from
(
select Name, min(Rnk) as R
from @Input
where Name in (select Name from Actor)
group by Name
) x
order by R desc
```
Example 2:
```
declare @Input as table (Rnk int, Name varchar(99))
insert into @Input values
(2,'Timothy Dalton')
,(4,'George Lazenby')
,(5,'George Lazenby')
,(3,'Bob Simmons')
select Name
from
(
select Name, min(Rnk) as R
from @Input
where Name in (select Name from Actor)
group by Name
) x
order by R desc
```
The golfed version is just the full thing for example input 3
As a plus this SQL can work for older DBMS versions (even be rewrite to ANSI SQL) and run without problem in older computers than most languages.
[Answer]
# Perl, ~~242~~ ~~179~~ 217 bytes
```
print reverse grep{/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/&&!$s{$_}++}map{s/\d+ //;$_}sort{($a=~/(\d+)/)[0]<=>($b=~/(\d+)/)[0]}<>;
```
Nicer formatted version, with comments:
```
print
# reverse ranking order
reverse
# filter entries...
grep {
# only actual bonds
/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/
# only new bonds
&& !$s{$_}++
} map {s/\d+ //;$_} # remove leading digits+space
# sort according to embedded numbers
sort {($a=~/(\d+)/)[0] <=> ($b=~/(\d+)/)[0]}
<>; # slurp input as list (list context)
```
Most of the size is the list of Bonds; I can't find a nice way of compressing that regex without allowing false positives.
[Answer]
# Python 2, 250 bytes:
```
lambda I:zip(*sorted({k:v for v,k in[x.split(' ',1)for x in I.split('\n')]if k in'Barry Nelson,Bob Simmons,Sean Connery,Roger Moore,David Niven,George Lazenby,Timothy Dalton,Pierce Brosnan,Daniel Craig'.split(',')}.items(),key=lambda t:-int(t[1])))[0]
```
Demo:
```
>>> L = ["Barry Nelson",
... "Bob Simmons",
... "Sean Connery",
... "Roger Moore",
... "David Niven",
... "George Lazenby",
... "Timothy Dalton",
... "Pierce Brosnan",
... "Daniel Craig"]
>>> I="""2 Timothy Dalton
... 4 George Lazenby
... 5 George Lazenby
... 3 Bob Simmons"""
>>> F(I,L)
('George Lazenby', 'Bob Simmons', 'Timothy Dalton')
>>> I = """1 Sean Connery
... 2 Emma Watson
... 5 Timothy Dalton
... 4 Roger Moore
... 3 Daniel Craig"""
>>>
>>> F(I,L)
('Timothy Dalton', 'Roger Moore', 'Daniel Craig', 'Sean Connery')
```
[Answer]
# Pyth, ~~136~~ 132 bytes
```
_{mtcd\ f}stcTdc"BarryNelson BobSimmons SeanConnery RogerMoore DavidNiven GeorgeLazenby TimothyDalton PierceBrosnan DanielCraig"dS.z
```
[Try it here!](http://pyth.herokuapp.com/?code=_%7Bmtcd%5C+f%7DstcTdc%22BarryNelson+BobSimmons+SeanConnery+RogerMoore+DavidNiven+GeorgeLazenby+TimothyDalton+PierceBrosnan+DanielCraig%22dS.z&input=2+Timothy+Dalton%0A4+George+Lazenby%0A5+George+Lazenby%0A3+Bob+Simmons%0A6+Emma+Watson&debug=0)
### Explanation
```
_{mtcd\ f}stcTdc"BarryNelson BobSimmons ..."dS.z # .z=list of all input lines
S.z # Sort input ascending
f # filter sorted lines with T being the current line
cTd # Split a line on spaces
st # Dicard the number and join first and last name
c"BarryNelson BobSimmons ..."d # Split the bond actor list on spaces...
} # only keep the lines which are in the actor list
mtcd\ # remove the number from the filtered lines
_{ # Remove duplicates from the mapping result and reverse the result
```
[Answer]
## PowerShell v3+, ~~227~~ 219 bytes
```
$a=$args-split"`n"|sort|%{$c,$b=-split$_;$b-join' '}|?{$_-in('Barry Nelson,Bob Simmons,Sean Connery,Roger Moore,David Niven,George Lazenby,Timothy Dalton,Pierce Brosnan,Daniel Craig'-split',')}|select -u
$a[$a.count..0]
```
121 bytes of that is just the list of actors ...
Takes input `$args` and `-split`s it on newlines with ``n`. Pipe that to `sort`, which will sort the entries numerically ascending, which is OK for now. We pipe those to a foreach loop `|%{...}`, each iteration take the entry, `-split` it on spaces, then `-join` the second half back together with a space (i.e., stripping the numbers off the beginning). Those (ascending) sorted names are now left on the pipeline. We pipe those through a where with `?` that ensures they're `-in` the approved list of actors. Finally, we `select` only the `-u`nique entries, which for duplicates will select the first one it encounters (i.e., the lowest-weighted one) and discard the rest. We store the resultant array of names into `$a`.
So, now we've got a sorted ascending list of actors. Since the challenge requires descending, we do an in-place reversal operation on `$a` by indexing from `$a.count` down to `0`.
### Example
```
PS C:\Tools\Scripts\golfing> .\sort-these-james-bond-ratings.ps1 "1 Sean Connery`n2 Emma Watson`n5 Daniel Craig`n4 Roger Moore`n3 Daniel Craig"
Roger Moore
Daniel Craig
Sean Connery
```
Edit -- don't need to use [array]::Reverse() when indexing will do
[Answer]
# Python ~~309~~ 286 bytes
```
import sys
i='Barry Nelson.Bob Simmons.Sean Connery.Roger Moore.David Niven.George Lazenby.Timothy Dalton.Pierce Brosnan.Daniel Craig'.split('.')
print ', '.join(i.pop(i.index(x)) for x in zip(*sorted((x.strip().split(' ',1) for x in sys.stdin),None,lambda x:int(x[0]),1))[1] if x in i)
```
[Answer]
# JavaScript (ES6), 232 bytes
```
s=>s.split`
`.sort((a,b)=>(p=parseInt)(a)<p(b)).map(l=>l.replace(/\d+ /,"")).filter(l=>!p[l]&/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/.test(p[l]=l))
```
## Explanation
```
var solution =
s=>
s.split`
`
.sort((a,b)=> // sort the list by the number
(p=parseInt)(a)<p(b) // parseInt reads only the first number in a string
// the variable p also holds names that appeared in the
// list previously
)
.map(l=>l.replace(/\d+ /,"")) // remove the number at the beginning of each line
.filter(l=>
!p[l]& // remove duplicates
// Bond actor regex
/^(Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$/
.test(p[l]=l) // test for bondness and add the line to p
)
```
```
<textarea id="input" rows="6" cols="40">1 Sean Connery
2 Emma Watson
5 Timothy Dalton
4 Roger Moore
3 Daniel Craig</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
] |
[Question]
[
**A [Latin square](https://en.wikipedia.org/wiki/Latin_square) is a square that has no repeated symbols in the rows or columns:**.
```
13420
21304
32041
04213
40132
```
And as many Sudoku players know, you don't need all of the numbers to deduce the remaining numbers.
**Your challenge is to compress a Latin square into as few bytes as possible.** You need to provide one or two program(s) that compresses/decompresses.
Various info:
* The numbers used will always be `0..N-1`, where `N` is the length of the square's edge, and `N<=25`
* On decompression, the latin square must be identical to the input.
* Your program(s) should be able to (de)compress *any* latin square (within the maximum square size), not just the ones I've provided. Compression ratios should be similar as well.
* You must actually run the compression and decompressor to obtain your score (No end-of-universe runtimes)
The test cases can be found on [github](https://gist.github.com/nathanmerrill/934c5887d7c34d794cbfd737b1ef5aef). **Your score is total size of compressed test cases.**
**EDIT: As of 20:07 on July 7th, I updated the test cases (in order to fix a generation issue). Please rerun your program on the new test cases.** Thanks [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg).
[Answer]
# Python, ~~1281.375~~ 1268.625 bytes
We encode the Latin square one “decision” at a time, where each decision is of one of these three forms:
* which number goes in row *i*, column *j*;
* in row *i*, which column the number *k* goes in;
* in column *j*, which row the number *k* goes in.
At each step, we make all the logical inferences we can based on previous decisions, then pick the decision with the smallest number of possible choices, which therefore take the smallest number of bits to represent.
The choices are provided by a simple arithmetic decoder (div/mod by the number of choices). But that leaves some redundancy in the encoding: if *k* decodes to a square where the product of all the numbers of choices was *m*, then *k* + *m*, *k* + 2⋅*m*, *k* + 3⋅*m*, … decode to the same square with some leftover state at the end.
We take advantage of this redundancy to avoid explicitly encoding the size of the square. The decompressor starts by trying to decode a square of size 1. Whenever the decoder finishes with leftover state, it throws out that result, subtracts *m* from the original number, increases the size by 1, and tries again.
```
import numpy as np
class Latin(object):
def __init__(self, size):
self.size = size
self.possible = np.full((size, size, size), True, dtype=bool)
self.count = np.full((3, size, size), size, dtype=int)
self.chosen = np.full((3, size, size), -1, dtype=int)
def decision(self):
axis, u, v = np.unravel_index(np.where(self.chosen == -1, self.count, self.size).argmin(), self.count.shape)
if self.chosen[axis, u, v] == -1:
ws, = np.rollaxis(self.possible, axis)[:, u, v].nonzero()
return axis, u, v, list(ws)
else:
return None, None, None, None
def choose(self, axis, u, v, w):
t = [u, v]
t[axis:axis] = [w]
i, j, k = t
assert self.possible[i, j, k]
assert self.chosen[0, j, k] == self.chosen[1, i, k] == self.chosen[2, i, j] == -1
self.count[1, :, k] -= self.possible[:, j, k]
self.count[2, :, j] -= self.possible[:, j, k]
self.count[0, :, k] -= self.possible[i, :, k]
self.count[2, i, :] -= self.possible[i, :, k]
self.count[0, j, :] -= self.possible[i, j, :]
self.count[1, i, :] -= self.possible[i, j, :]
self.count[0, j, k] = self.count[1, i, k] = self.count[2, i, j] = 1
self.possible[i, j, :] = self.possible[i, :, k] = self.possible[:, j, k] = False
self.possible[i, j, k] = True
self.chosen[0, j, k] = i
self.chosen[1, i, k] = j
self.chosen[2, i, j] = k
def encode_sized(size, square):
square = np.array(square, dtype=int)
latin = Latin(size)
chosen = np.array([np.argmax(square[:, :, np.newaxis] == np.arange(size)[np.newaxis, np.newaxis, :], axis=axis) for axis in range(3)])
num, denom = 0, 1
while True:
axis, u, v, ws = latin.decision()
if axis is None:
break
w = chosen[axis, u, v]
num += ws.index(w)*denom
denom *= len(ws)
latin.choose(axis, u, v, w)
return num
def decode_sized(size, num):
latin = Latin(size)
denom = 1
while True:
axis, u, v, ws = latin.decision()
if axis is None:
break
if not ws:
return None, 0
latin.choose(axis, u, v, ws[num % len(ws)])
num //= len(ws)
denom *= len(ws)
return latin.chosen[2].tolist(), denom
def compress(square):
size = len(square)
assert size > 0
num = encode_sized(size, square)
while size > 1:
size -= 1
square, denom = decode_sized(size, num)
num += denom
return '{:b}'.format(num + 1)[1:]
def decompress(bits):
num = int('1' + bits, 2) - 1
size = 1
while True:
square, denom = decode_sized(size, num)
num -= denom
if num < 0:
return square
size += 1
total = 0
with open('latin_squares.txt') as f:
while True:
square = [list(map(int, l.split(','))) for l in iter(lambda: next(f), '\n')]
if not square:
break
bits = compress(square)
assert set(bits) <= {'0', '1'}
assert square == decompress(bits)
print('Square {}: {} bits'.format(len(square), len(bits)))
total += len(bits)
print('Total: {} bits = {} bytes'.format(total, total/8.0))
```
Output:
```
Square 1: 0 bits
Square 2: 1 bits
Square 3: 3 bits
Square 4: 8 bits
Square 5: 12 bits
Square 6: 29 bits
Square 7: 43 bits
Square 8: 66 bits
Square 9: 94 bits
Square 10: 122 bits
Square 11: 153 bits
Square 12: 198 bits
Square 13: 250 bits
Square 14: 305 bits
Square 15: 363 bits
Square 16: 436 bits
Square 17: 506 bits
Square 18: 584 bits
Square 19: 674 bits
Square 20: 763 bits
Square 21: 877 bits
Square 22: 978 bits
Square 23: 1097 bits
Square 24: 1230 bits
Square 25: 1357 bits
Total: 10149 bits = 1268.625 bytes
```
[Answer]
# Python 3, 10772 bits (1346.5 bytes)
```
def compress(rows):
columns = list(zip(*rows))
size = len(rows)
symbols = range(size)
output = size - 1
weight = 25
for i in symbols:
for j in symbols:
choices = set(rows[i][j:]) & set(columns[j][i:])
output += weight * sorted(choices).index(rows[i][j])
weight *= len(choices)
return bin(output + 1)[3:]
def decompress(bitstring):
number = int('1' + bitstring, 2) - 1
number, size = divmod(number, 25)
size += 1
symbols = range(size)
rows = [[None] * size for _ in symbols]
columns = [list(column) for column in zip(*rows)]
for i in symbols:
for j in symbols:
choices = set(symbols) - set(rows[i]) - set(columns[j])
number, index = divmod(number, len(choices))
rows[i][j] = columns[j][i] = sorted(choices)[index]
return rows
```
Takes 0.1 seconds to compress and decompress the combined test cases.
Verify the score on [Ideone](http://ideone.com/qouOu1#stdout).
[Answer]
# MATLAB, ~~3'062.5~~ 2'888.125 bytes
This approach just ditches the last row and the last column of the square, and converts each entry into words of a certain bit depth. The bit depth is chosen minimal for the given size square. (Suggestion by @KarlNapf) These words are just appended to each other. Decompression is just the reverse.
The sum for all the test cases is 23'105 bits or 2'888.125 bytes. (Still holds for the updated test cases, as the size of my outputs is only dependent of the size of the input.)
```
function bin=compress(a)
%get rid of last row and column:
s=a(1:end-1,1:end-1);
s = s(:)';
bin = [];
%choose bit depth:
bitDepth = ceil(log2(numel(a(:,1))));
for x=s;
bin = [bin, dec2bin(x,bitDepth)];
end
end
function a=decompress(bin)
%determine bit depth
N=0;
f=@(n)ceil(log2(n)).*(n-1).^2;
while f(N)~= numel(bin)
N=N+1;
end
bitDepth = ceil(log2(N));
%binary to decimal:
assert(mod(numel(bin),bitDepth)==0,'invalid input length')
a=[];
for k=1:numel(bin)/bitDepth;
number = bin2dec([bin(bitDepth*(k-1) + (1:bitDepth)),' ']);
a = [a,number];
end
n = sqrt(numel(a));
a = reshape(a,n,n);
disp(a)
%reconstruct last row/column:
n=size(a,1)+1;
a(n,n)=0;%resize
%complete rows:
v = 0:n-1;
for k=1:n
a(k,n) = setdiff(v,a(k,1:n-1));
a(n,k) = setdiff(v,a(1:n-1,k));
end
end
```
[Answer]
# [J](http://jsoftware.com), 2444 bytes
Relies on the builtin `A.` to convert to and from a permutation of integers [0, n) and a permutation index.
### Compress, 36 bytes
```
({:a.)joinstring<@(a.{~255&#.inv)@A.
```
The input is a 2d array representing the Latin square. Each row is converted to a permutation index, and that index is converted to a list of base 255 digits and replaced with an ASCII value. Each string is then joined using the ASCII character at 255.
### Decompress, 45 bytes
```
[:(A.i.@#)[:(_&,(255&#.&x:);._1~1,255&=)u:inv
```
Splits the input string at each ASCII value of 255, and parse each group as base 255 digits. Then using the number of groups, create a list of integers [0, length) and permute it according to each index and return it as a 2d array.
[Answer]
# Python, ~~6052~~ ~~4521~~ 3556 bytes
`compress` takes the square as a multiline string, just like the examples and returns a binary string, whereas `decompress` does the opposite.
```
import bz2
import math
def compress(L):
if L=="0":
C = []
else:
#split elements
elems=[l.split(',') for l in L.split('\n')]
n=len(elems)
#remove last row and col
cropd=[e[:-1] for e in elems][:-1]
C = [int(c) for d in cropd for c in d]
#turn to string
B=map(chr,C)
B=''.join(B)
#compress if needed
if len(B) > 36:
BZ=bz2.BZ2Compressor(9)
BZ.compress(B)
B=BZ.flush()
return B
def decompress(C):
#decompress if needed
if len(C) > 40:
BZ=bz2.BZ2Decompressor()
C=BZ.decompress(C)
#return to int and determine length
C = map(ord,C)
n = int(math.sqrt(len(C)))
if n==0: return "0"
#reshape to list of lists
elems = [C[i:i+n] for i in xrange(0, len(C), n)]
#determine target length
n = len(elems[0])+1
L = []
#restore last column
for i in xrange(n-1):
S = {j for j in range(n)}
L.append([])
for e in elems[i]:
L[i].append(e)
S.remove(e)
L[i].append(S.pop())
#restore last row
L.append([])
for col in xrange(n):
S = {j for j in range(n)}
for row in xrange(n-1):
S.remove(L[row][col])
L[-1].append(S.pop())
#merge elements
orig='\n'.join([','.join([str(e) for e in l]) for l in L])
return orig
```
Remove the last row+column and zip the rest.
* Edit1: well `base64` does not seem necessary
* Edit2: now converting the chopped table into a binary string and compress only if necessary
[Answer]
# Python 3, 1955 bytes
Yet another one that uses permutation indices...
```
from math import factorial
test_data_name = 'latin_squares.txt'
def grid_reader(fname):
''' Read CSV number grids; grids are separated by empty lines '''
grid = []
with open(fname) as f:
for line in f:
line = line.strip()
if line:
grid.append([int(u) for u in line.split(',') if u])
elif grid:
yield grid
grid = []
if grid:
yield grid
def show(grid):
a = [','.join([str(u) for u in row]) for row in grid]
print('\n'.join(a), end='\n\n')
def perm(seq, base, k):
''' Build kth ordered permutation of seq '''
seq = seq[:]
p = []
for j in range(len(seq) - 1, 0, -1):
q, k = divmod(k, base)
p.append(seq.pop(q))
base //= j
p.append(seq[0])
return p
def index(p):
''' Calculate index number of sequence p,
which is a permutation of range(len(p))
'''
#Generate factorial base code
fcode = [sum(u < v for u in p[i+1:]) for i, v in enumerate(p[:-1])]
#Convert factorial base code to integer
k, base = 0, 1
for j, v in enumerate(reversed(fcode), 2):
k += v * base
base *= j
return k
def encode_latin(grid):
num = len(grid)
fbase = factorial(num)
#Encode grid rows by their permutation index,
#in reverse order, starting from the 2nd-last row
codenum = 0
for row in grid[-2::-1]:
codenum = codenum * fbase + index(row)
return codenum
def decode_latin(num, codenum):
seq = list(range(num))
sbase = factorial(num - 1)
fbase = sbase * num
#Extract rows
grid = []
for i in range(num - 1):
codenum, k = divmod(codenum, fbase)
grid.append(perm(seq, sbase, k))
#Build the last row from the missing element of each column
allnums = set(seq)
grid.append([allnums.difference(t).pop() for t in zip(*grid)])
return grid
byteorder = 'little'
def compress(grid):
num = len(grid)
codenum = encode_latin(grid)
length = -(-codenum.bit_length() // 8)
numbytes = num.to_bytes(1, byteorder)
codebytes = codenum.to_bytes(length, byteorder)
return numbytes + codebytes
def decompress(codebytes):
numbytes, codebytes= codebytes[:1], codebytes[1:]
num = int.from_bytes(numbytes, byteorder)
if num == 1:
return [[0]]
else:
codenum = int.from_bytes(codebytes, byteorder)
return decode_latin(num, codenum)
total = 0
for i, grid in enumerate(grid_reader(test_data_name), 1):
#show(grid)
codebytes = compress(grid)
length = len(codebytes)
total += length
newgrid = decompress(codebytes)
ok = newgrid == grid
print('{:>2}: Length = {:>3}, {}'.format(i, length, ok))
#print('Code:', codebytes)
#show(newgrid)
print('Total bytes: {}'.format(total))
```
**output**
```
1: Length = 1, True
2: Length = 1, True
3: Length = 2, True
4: Length = 3, True
5: Length = 5, True
6: Length = 7, True
7: Length = 11, True
8: Length = 14, True
9: Length = 20, True
10: Length = 26, True
11: Length = 33, True
12: Length = 41, True
13: Length = 50, True
14: Length = 61, True
15: Length = 72, True
16: Length = 84, True
17: Length = 98, True
18: Length = 113, True
19: Length = 129, True
20: Length = 147, True
21: Length = 165, True
22: Length = 185, True
23: Length = 206, True
24: Length = 229, True
25: Length = 252, True
Total bytes: 1955
```
[Answer]
## Python3 - 3,572 3,581 bytes
```
from itertools import *
from math import *
def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
if isinstance(x,complex):
return (int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet))
if x<=0:
if x==0:return alphabet[0]
else:return '-' + int2base(-x,b,alphabet)
rets=''
while x>0:
x,idx = divmod(x,b)
rets = alphabet[idx] + rets
return rets
def lexicographic_index(p):
result = 0
for j in range(len(p)):
k = sum(1 for i in p[j + 1:] if i < p[j])
result += k * factorial(len(p) - j - 1)
return result
def getPermutationByindex(sequence, index):
S = list(sequence)
permutation = []
while S != []:
f = factorial(len(S) - 1)
i = int(floor(index / f))
x = S[i]
index %= f
permutation.append(x)
del S[i]
return tuple(permutation)
alphabet = "abcdefghijklmnopqrstuvwxyz"
def dataCompress(lst):
n = len(lst[0])
output = alphabet[n-1]+"|"
for line in lst:
output += "%s|" % int2base(lexicographic_index(line), 36)
return output[:len(output) - 1]
def dataDeCompress(data):
indexes = data.split("|")
n = alphabet.index(indexes[0]) + 1
del indexes[0]
lst = []
for index in indexes:
if index != '':
lst.append(getPermutationByindex(range(n), int(index, 36)))
return lst
```
`dataCompress` takes a list of integer tuples and returns a string.
`dateDeCompress` takes a string and returns a list of integer tuples.
In short, for each line, this program takes that lines permutation index and saves it in base 36. Decompressing takes a long time with big inputs but compression is really fast even on big inputs.
## Usage:
`dataCompress([(2,0,1),(1,2,0),(0,1,2)])`
result: `c|4|3|0`
`dataDeCompress("c|4|3|0")`
result: `[(2, 0, 1), (1, 2, 0), (0, 1, 2)]`
[Answer]
# Java, 2310 bytes
We convert each row of the square to a number representing which lexicographic permutation it is using factoradic numbers, also known as a [factorial number system](https://en.wikipedia.org/wiki/Factorial_number_system), which is useful for numbering permutations.
We write the square to a binary file where the first byte is the size of the square, and then each row has one byte for the number of bytes in the binary representation of a Java BigInteger, followed by the bytes of that BigInteger.
To reverse the process and decompress the square we read the size back and then each BigInteger, and use that number to generate each row of the square.
```
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Latin {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("java Latin {-c | -d} infile outfile");
} else if (args[0].equals("-c")) {
compress(args[1], args[2]);
} else if (args[0].equals("-d")) {
decompress(args[1], args[2]);
} else {
throw new IllegalArgumentException(
"Invalid mode: " + args[0] + ", not -c or -d");
}
}
public static void compress(String filename, String outname) {
try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
try (OutputStream os =
new BufferedOutputStream(new FileOutputStream(outname))) {
String line = br.readLine();
if (line == null) return;
int size = line.split(",").length;
if (size > 127) throw new ArithmeticException(
"Overflow: square too large");
Permutor perm = new Permutor(size);
os.write((byte) size); // write size of square
do {
List<Integer> nums = Arrays.stream(line.split(","))
.map(Integer::new)
.collect(Collectors.toList());
byte[] bits = perm.which(nums).toByteArray();
os.write((byte) bits.length); // write length of bigint
os.write(bits); // write bits of bigint
} while ((line = br.readLine()) != null);
}
} catch (IOException e) {
System.out.println("Error compressing " + filename);
e.printStackTrace();
}
}
public static void decompress(String filename, String outname) {
try (BufferedInputStream is =
new BufferedInputStream(new FileInputStream(filename))) {
try (BufferedWriter bw =
Files.newBufferedWriter(Paths.get(outname))) {
int size = is.read(); // size of latin square
Permutor perm = new Permutor(size);
for (int i = 0; i < size; ++i) {
int num = is.read(); // number of bytes in bigint
if (num == -1) {
throw new IOException(
"Unexpected end of file reading " + filename);
}
byte[] buf = new byte[num];
int read = is.read(buf); // read bits of bigint into buf
if (read != num) {
throw new IOException(
"Unexpected end of file reading " + filename);
}
String row = perm.nth(new BigInteger(buf)).stream()
.map(Object::toString)
.collect(Collectors.joining(","));
bw.write(row);
bw.newLine();
}
}
} catch (IOException e) {
System.out.println("Error reading " + filename);
e.printStackTrace();
}
}
}
```
Permutor is adapted from a class I wrote a few years ago to work with permutations:
```
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.math.BigInteger;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.ONE;
public class Permutor {
private final List<Integer> items;
public Permutor(int n) {
items = new ArrayList<>();
for (int i = 0; i < n; ++i) items.add(i);
}
public BigInteger size() {
return factorial(items.size());
}
private BigInteger factorial(int x) {
BigInteger f = ONE;
for (int i = 2; i <= x; ++i) {
f = f.multiply(BigInteger.valueOf(i));
}
return f;
}
public List<Integer> nth(long n) {
return nth(BigInteger.valueOf(n));
}
public List<Integer> nth(BigInteger n) {
if (n.compareTo(size()) > 0) {
throw new IllegalArgumentException("too high");
}
n = n.subtract(ONE);
List<Integer> perm = new ArrayList<>(items);
int offset = 0, size = perm.size() - 1;
while (n.compareTo(ZERO) > 0) {
BigInteger fact = factorial(size);
BigInteger mult = n.divide(fact);
n = n.subtract(mult.multiply(fact));
int pos = mult.intValue();
Integer t = perm.get(offset + pos);
perm.remove((int) (offset + pos));
perm.add(offset, t);
--size;
++offset;
}
return perm;
}
public BigInteger which(List<Integer> perm) {
BigInteger n = ONE;
List<Integer> copy = new ArrayList<>(items);
int size = copy.size() - 1;
for (Integer t : perm) {
int pos = copy.indexOf(t);
if (pos < 0) throw new IllegalArgumentException("invalid");
n = n.add(factorial(size).multiply(BigInteger.valueOf(pos)));
copy.remove((int) pos);
--size;
}
return n;
}
}
```
Usage:
With a Latin square in `latin.txt`, compress it:
```
java Latin -c latin.txt latin.compressed
```
And decompress it:
```
java Latin -d latin.compressed latin.decompressed
```
] |
[Question]
[
>
> **Note**: Anders Kaseorg warns me that this could be a duplicate of [another previous question](https://codegolf.stackexchange.com/q/53760/70347). It seems so, and I'm sorry I did not find that question before posting this one. Nonetheless, that question only received one answer and this one is simpler, just in case you all want to try this time. I'll understand if this question ends up being marked as duplicate, though.
>
>
>
### The challenge
Given an input like this:
```
8g 8Df 4cs 2C 1A
```
Write the shortest program/function that produces an output like this:
```
/\ -o-
| |
---|-|---------------------------------------------------|-|
|/ | |
---/|--------|\----b-*-----------------------------------|-|
/ | | | | o | |
-|--|--------|------|-----------------|------------------|-|
| (| \ | | | | | |
-|--|--)----*-------|/---------|------|------------------|-|
\ | / | | | |
-----|-------------------------|-------------------------|-|
| |
*_/ #-*-
```
### Rules
The output must consist of a five-line staff beginning with the drawing of a G-clef exactly as shown above, aligned to the left of the staff and leaving a single column after the starting of the staff.
```
/\
| |
---|-|--
|/
---/|---
/ |
-|--|---
| (| \
-|--|--)
\ | /
-----|--
|
*_/
^
Single column
```
The notes must begin with a `*` or a `o` character depending on its type.
There must be exactly eight columns of separation every `*` or a `o` character:
```
/\ -o-
| |
---|-|---------------------------------------------------|-|
|/ | |
---/|--------|\----b-*-----------------------------------|-|
/ | | | | o | |
-|--|--------|------|-----------------|------------------|-|
| (| \ | | | | | |
-|--|--)----*-------|/---------|------|------------------|-|
\ | / | | | |
-----|-------------------------|-------------------------|-|
| |
*_/ #-*-
↑ ↑ ↑ ↑ ↑ ↑ ↑
8 columns of separation
```
The staff must end with the terminator aligned to the right as shown in the example. The left bar of the terminator must be separated 8 columns from the last note.
The input will be a single string containing the notes (at least one, no empty inputs), each one separated by a whitespace (you can consider every note will be a proper one, so no need to check for errors). You can also take the input as an array of strings, with a note per element in the array. For each note, the first character will be the denominator of the note length (`1` for a [whole note/semibreve](https://en.wikipedia.org/wiki/Whole_note), starts with `o`; `2` for a [half note/minim](https://en.wikipedia.org/wiki/Half_note), starts with `o`; `4` for a [quarter note/crotchet](https://en.wikipedia.org/wiki/Quarter_note), starts with `*`; and `8` for an [eighth note/quaver](https://en.wikipedia.org/wiki/Eighth_note), starts with `*`). The second character will be the note (see next table), and the third, optional character will be `f` or `F` for flat notes and `s` or `S` for sharp notes.
```
--- A (ledger line)
G
-------- F
E
-------- D
C
-------- b
a
-------- g
f
-------- e
d
--- c (ledger line)
```
Obviously, the input must respect the case for the notes, but you can choose the case of the `f` and `s` modifiers.
Notes `c` and `A` must add two `-` (ledger lines), one at each side, as they must extend the staff. Notes `d` and `G` are out of the staff but do not need ledger lines.
Flatten or sharpened notes must add `b` or `#` two positions at the left of the note.
The stems (if any) must be drawn with 4 vertical bars. Notes from `b` and above must draw the stem downwards and at the left side of the note. Notes from `a` and below must draw the stem upwards and at the right side of the note. Quavers must add the flag, always rightwards and exactly as shown, and do not need to be beamed if there are several of them in a row.
```
--------------------------
-----|\----b-*------------
| | |
-----|------|-------------
| | |
----*-------|/---------|--
↑↑ |
----||------↑↑---------|--
|| || |
|| || #-*-
|\ |\ ↑↑
| Stem | Note | Stem
Note Stem Note
```
As usual, your program/function can directly draw the output or return a string, array of strings, matrix of characters or any other reasonable format.
### Useful links
* [List of musical symbols](https://en.wikipedia.org/wiki/List_of_musical_symbols).
* [Letter notation](https://en.wikipedia.org/wiki/Letter_notation).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win!
Bonus: try to write examples with famous melodies and let everyone try to guess which melody it is!
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~178~~ ~~175~~ ~~174~~ ~~173~~ ~~172~~ 171 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
l9*6«+@*@¶¹┐∑:@┌ŗ4Ο"γ;]∑«;‽ΗmzΖH+īN D‼,ΨU‛y‚_○¤└yΨšI‘7n2∆╬5;{" -o-”;l3=?Jζ2%Ƨ#bWGk+;}Jz7m««:U+;W7«κArBb3>?Ζo*ŗ}a2\?┌@ŗ}ē9*LI+a╬5b1>?4┐∙b8=?"■QD³‘┼}e9*5+a4-8a>?5+;2-;G↕№}╬5
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0I4bDkqNiVBQitAKkAlQjYlQjkldTI1MTAldTIyMTElM0FAJXUyNTBDJXUwMTU3NCV1MDM5RiUyMiV1MDNCMyUzQiU1RCV1MjIxMSVBQiUzQiV1MjAzRCV1MDM5N216JXUwMzk2SCsldTAxMkJOJTA5RCV1MjAzQyUyQyV1MDNBOFUldTIwMUJ5JXUyMDFBXyV1MjVDQiVBNCV1MjUxNHkldTAzQTgldTAxNjFJJXUyMDE4N24yJXUyMjA2JXUyNTZDNSUzQiU3QiUyMiUyMC1vLSV1MjAxRCUzQmwzJTNEJTNGSiV1MDNCNjIlMjUldTAxQTclMjNiV0drKyUzQiU3REp6N20lQUIlQUIlM0FVKyUzQlc3JUFCJXUwM0JBQXJCYjMlM0UlM0YldTAzOTZvKiV1MDE1NyU3RGEyJTVDJTNGJXUyNTBDQCV1MDE1NyU3RCV1MDExMzkqTEkrYSV1MjU2QzViMSUzRSUzRjQldTI1MTAldTIyMTliOCUzRCUzRiUyMiV1MjVBMFFEJUIzJXUyMDE4JXUyNTNDJTdEZTkqNSthNC04YSUzRSUzRjUrJTNCMi0lM0JHJXUyMTk1JXUyMTE2JTdEJXUyNTZDNQ__,inputs=OGclMjA4RGYlMjA0Y3MlMjAyQyUyMDFBJTIwMUclMjAyRmYlMjA0RXMlMjA4RCUyMDFDZiUyMDJicyUyMDRhJTIwOGdGJTIwMWZTJTIwMmUlMjA0ZGYlMjA4Y3M_) (θ added for ease of use; To run as 171 bytes it expects the input to be on the stack)
As far as I can tell this works, but if you find any problems, tell me.
## Explanation:
### first part: canvas creation
```
l get the length of that array
9* multiply by 9
6«+ add 12
@* get that many spaces
@¶ push a space and a newline
¹ put all the strings on the stack in an array
┐∑ join with vertical bars
: duplicate that string (which is a line with the ending barline but no staff)
@┌ŗ replace spaces with dashes (to make it a line with staff)
4Ο encase 4 copies of the space lines in lines with the dashes
"...‘ push the G-clef without newlines
7n split into an array of items of length 7
2∆╬5 at 1-indexed coordinates [2; -1] place the G-clef in the staff lines, extending the arrays size
; get the input split on spaces back on top of the stack
```
### second part: loop, note head placement
```
{ loop over the input split on spaces
" -o-” push a template for a note head and leger lines
; get the input optop
l3=? } if the length of the input is 3, then
J pop the last letter off from the input
ζ get its unicode point
2% modulo 2
Ƨ#bW get its index in "#b"
G get the template ontop
k remove its 1st letter
+ join the replaced input and the template
; get the input back ontop to be consisntent with how the if started
sidequest: parse the rest of the inputs
J pop the last letter off of the remaining input string (the note), leaving the note length as string on the stack below
z push the lowercase alphabet
7m get its first 7 letters
«« put the first 2 at the end
: duplicate it
U+ append it uppercased to the original
;W get the notes letter ontop and get its 1-indexed index in that just created string
7«κ subtract it from 14
A save on variable A
r convert the note length to a number
B save on variable B
b3>? } if b>3 (aka if note length is either 4 or 8)
Ζo*ŗ replace "o" with "*"
a2\? } if a divides by 2 (aka there isn't staff nor leger lines required)
┌@ŗ replace "-" with " "
ē push the value of variable E and after that increase it (default is user input number, which errors and defaults to 0)
9* multiply by 9
LI+ increase by 11
a push variable a
╬5 at those positions (e*9+11, a) insert the note head template in the canvas
```
### third part: flags and stems
```
b1>? if b (note length)>1 (aka if the stem is needed at all)
4┐∙ get an array of 4 vertical bars
b8=? } if b==8 (aka if the flag is needed)
"■QD³‘ push "\ |"
┼ add verically-down-then-horizontally-right
e9* push e*9 (now e starts with 1 as it's been increased) (the X coordinate for the flag)
5+ add 5 to it
a4- push a-4 (the Y coordinate, 4 less than the note head as arrays get inserted from the top-left corner)
8a>? } if 8>a (aka if the flag needs to be rotated)
5+ add 5 to the Y coordinate
;2-; subtract 2 from the X coordinate
G get the stem&flag or stem ontop
↕№ reverse it vertically and mirror characters
╬5 insert the array of the stem and maybe flag at those coordinates
```
[Answer]
## JavaScript(ES6), ~~616~~ 527 bytes
Thanks [@shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for removing almost 90 bytes
I had no idea about notes... until now, hope I got it right.
```
f=i=>i.map((v,p)=>(k[e=(w=q+12)*(l="AGFEDCbagfedc".search(v[1]))+p*9+12]="o*"[(s=v[0])>3|0],l<1|l>11&&(k[e-1]=k[e+1]="-"),(t=v[2])&&(k[e-2]="b#"[t>"f"|0]),--s&&[1,2,3,4].map(i=>(k[(b=l<8)?e+w*i-1:e-w*i+1]="|",s>6&&( b?k[e+w*4]="/":k[e-w*4+2]="\\",k[b?e+w*3+1:e-w*3+3]='|')))),k=[...` /\\ ${s=" ".repeat(q=i.length*9)}
| | ${s}
---|-|--${l="-".repeat(q)+"|-|"}
|/ ${t=s+"| |"}
---/|---${l}
/ | ${t}
-|--|---${l}
| (| \\ ${t}
-|--|--)${l}
\\ | / ${t}
-----|--${l}
| ${s}
*_/ ${s}`])&&k.join``
console.log(f(["8g","8Df","4cs","2C","1A"]))
```
```
.as-console-wrapper { max-height: 100% !important; top: 0 }
.as-console-row:after { display: none !important; }
```
**explanation**
```
f=i=>i.map((v,p)=>( // for each note
k[e=(w=q+12)*(l="AGFEDCbagfedc".search(v[1]))+p*9+12]= // position in 1D array to set the note to
"o*"[(s=v[0])>3|0], // note value (either o or *)
l<1|l>11&&(k[e-1]=k[e+1]="-"), // add leger line
(t=v[2])&&(k[e-2]="b#"[t>"f"|0]), // add sharp or flat
--s&&[1,2,3,4].map(i=> // add the 4 stem lines
(k[(b=l<8)?e+w*i-1:e-w*i+1]="|", // durration over eigth note => add stem
s>6&&( // if to add a flag
b?k[e+w*4]="/":k[e-w*4+2]="\\", // add flag either on left or the right side
k[b?e+w*3+1:e-w*3+3]='|') // add the line after the flag
)
)
),
// template, extended to the final length with lines
k=[...` /\\ ${s=" ".repeat(q=i.length*9)}
| | ${s}
---|-|--${l="-".repeat(q)+"|-|"}
|/ ${t=s+"| |"}
---/|---${l}
/ | ${t}
-|--|---${l}
| (| \\ ${t}
-|--|--)${l}
\\ | / ${t}
-----|--${l}
| ${s}
*_/ ${s}`])&&k.join``
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~180~~ ~~171~~ ~~168~~ 163 bytes
```
F⁵⁺⸿⸿×-⁺²⁷×⁸№θ ↑⁹←↙↓⁹J⁴¦⁹↑⁶↗¹↑²↖¹↓↙¹↓³↙²↓³ \M²↑(| ↘¹↙)↙¹↓²↙¹↑←_*F⪪θ «A⌕AGFEDCbagfedc§ι¹λJχλA⁺⁹χχ¿⁼³Lι§b#⁼§ι²s→P׳¬﹪λ²→P§o*›ι4¿›ι2¿›λ⁶«↗↑⁴¿›ι8«↘↘¹↓¹»»«↙↓⁴¿›ι8«↗↗¹↑¹
```
[Try it online!](https://tio.run/##jVNNT@MwFDw7v@LJXBzkHghdKOUUtYBY0RXi41YJhcRJLZm4xAmLxPa3Z@04aZzSSlRq1fcyb2bsN4lXURHLSNR1Kgsgv3y4L3hekjBJCF4WywJTeOJvTBE80n/vRaVIcN71JhRmstLwdwoYsN98Lj1LMX1eU7jQ5UJ@MDK9Y2m5Lebyb942WrDpWPjv6m39JMnYVg7XmVs@8GxVUjgZQgK3NAIW0YsOBXvEwMXpPlRwGIVhucSdTEBBa/fPyD/Aw9Hv1nsV7OMfWQwOoexRHQPTlvjl2DA3W35cC97vDL48FCrFs5xc81yvPby5vprPXqMsZUmslx6Wt3nCPgk3Cj4FoXlQu6W4LVuCJh8XFGLffHWfp0Cu3qtIKHJK4Y7lWbkiXKeky1nLjV@PtFKLdAQDTYSVSZaHmFAM7PmaKzT8i0qUfN1Q2UhqlT@yJAuZVEISYRiaTKLDg1sP8lh7uClYVLLCiOMxtrPmFG4/wMbPoC1MPpu7RKjbwVYMISejY9vZ5Zzgbhz1cXUY0P4E7TzZNjf6ZwPNlTmenPdud@6ntgbHQvveRzQ8r2vI29T1JIPJPIVxrCCYwUno1aOPeqTEfw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⁵⁺⸿⸿×-⁺²⁷×⁸№θ ↑⁹←↙↓⁹
```
Print the stave.
```
J⁴¦⁹↑⁶↗¹↑²↖¹↓↙¹↓³↙²↓³ \M²↑(| ↘¹↙)↙¹↓²↙¹↑←_*
```
Print the clef.
```
F⪪θ «
```
Loop through each note.
```
A⌕AGFEDCbagfedc§ι¹λ
```
Find the Y-coordinate of the note.
```
JχλA⁺⁹χχ
```
This is really sneaky: `χ` is a variable that is predefined to 10, which is exactly the X-coordinate of the first note's accidental, if it has one. After jumping to that position, 9 is added to it, representing the next note position.
```
¿⁼³Lι§b#⁼§ι²s→
```
Print the accidental, if there is one.
```
P׳¬﹪λ²→P§o*›ι4
```
Print the ledger lines if necessary and the note. In fact the line is printed on any even y-coordinate although printing it over the stave has no effect of course.
```
¿›ι2
```
Nothing more to do for semibreves.
```
¿›λ⁶«
```
For notes below the midpoint,
```
↗↑⁴
```
draw the stem upwards,
```
¿›ι8«↘↘¹↓¹
```
and the flag for quavers.
```
»»«
```
For notes above the midpoint,
```
↙↓⁴
```
draw the stem downwards,
```
¿›ι8«↗↗¹↑¹
```
and the flag for quavers.
] |
[Question]
[
N children, with no two sharing their exact size, are lined up in some order. Each can only compare heights with their immediate neighbours. When the teacher shouts "raise hands if you are the tallest", they do so if they are taller than both their neighbours, and they do so simultaneously. If only one raises their hand, he wins. If more than one raise their hands, they are all eliminated from the row (preserving the order of the rest of the children) and they repeat the process.
Write a program, which takes an array of distinct integers (you can assume they are strictly positive) and outputs the winner of this game. This is code-golf, so the shortest code wins.
Examples (with intermediate stages shown):
**5** 3 **9** 8 7 → 3 **8** 7 → 8
1 2 **9** 4 → 9
**9** 3 **8** 7 4 **12** 5 → 3 **7** 4 **5** → 3 **4** → 4
---
Current leaders:
1. Jelly: 17 bytes [by Dennis♦]
2. MATL: 20 bytes [by Luis Mendo]
3. APL: 28 bytes [voidhawk]
4. k: 40 bytes [by Paul Kerrigan]
There's also a battle of Pythons going on. Still waiting for more golfing languages to show up.
I currently accepted Dennis♦'s answer - if there are new winners, I'll update the selection.
[Answer]
# JavaScript (ES6), ~~78~~ ~~76~~ 72 bytes
*Thanks to @edc65 for -4 bytes*
```
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r
```
Takes in an array of integers and outputs an array containing only the winner.
### Test snippet
```
f=a=>a.map((c,i)=>(p>c|c<a[i+1]?q:r).push(p=c),p=q=[],r=[])&&r[1]?f(q):r
g=a=>a?console.log("Input:",`[${a}]`,"Output:",f(a.map(Number))+""):console.error("Invalid input")
g([5,3,9,8,7])
g([1,2,9,4])
g([9,3,8,7,4,12,5])
```
```
<input id=I value="9 1 8 2 7 3 6 4 5"><button onclick="g(I.value.match(/\d+/g))">Run</button>
```
Here are a few other attempts, using `.filter` and array comprhensions:
```
f=a=>(q=a.filter((c,i)=>p>(p=c)|c<a[i+1]||0*r.push(c),p=r=[]))&&r[1]?f(q):r
f=a=>(r=a.filter((c,i)=>p<(p=c)&c>~~a[i+1]||0*r.push(c),p=q=[]))[1]?f(q):r
f=a=>[for(c of(i=p=q=[],r=[],a))(p>c|c<a[++i]?q:r).push(p=c)]&&r[1]?f(q):r
f=a=>(q=[for(c of(i=p=r=[],a))if(p>(p=c)|c<a[++i]||0*r.push(c))c])&&r[1]?f(q):r
```
Or a double for-loop, horribly long:
```
a=>eval("for(r=[,1];r[1]&&(p=i=q=[],r=[]);a=q)for(c of a)(p>c|c<a[++i]?q:r).push(p=c));r")
```
### Explanation
The way this works is pretty simple: it builds an array of those who are relatively taller (`r`) and an array of those that aren't (`q`), then returns `r` if it only has one item; if not, it runs itself on `q` and returns the result of that.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 20 bytes
```
`tTYadZSd0<~&)nq}x2M
```
Input is a column vector, using `;` as separator.
[Try it online!](http://matl.tryitonline.net/#code=YHRUWWFkWlNkMDx-JilucX14Mk0&input=Wzk7IDM7IDg7IDc7IDQ7IDEyOyA1XQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YApgdFRZYWRaU2QwPH4mKW5xfXgyTQpEVA&input=WzU7IDM7IDk7IDg7IDddClsxOyAyOyA5OyA0XSAKWzk7IDM7IDg7IDc7IDQ7IDEyOyA1XQ).
### Explanation
This is a direct implementation of the procedure described in the challenge. A `do`...`while` loop keeps removing elements until only one has been removed; and that one is the output.
The elements to be removed are detected by taking differences, signum, then differences again. Those that give a negative value are the ones to be removed.
```
` % Do...while
t % Duplicate. Takes input (implicit) the first time
TYa % Append and prepend a zero
d % Consecutive differences
ZS % Signum
d % Consecutive differences
0<~ % Logical mask of non-negative values: these should be kept
&) % Split array into two: those that should kept, then those removed
nq % Size minus 1. This is used as loop condition. The loop will exit
% if this is 0, that is, if only one element was removed
} % Finally (i.e. execute at the end of the loop)
x % Delete array of remaining elements
2M % Push last element that was removed
% End (implicit)
% Display (implicit)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
j@N»3\=x@ḟ@ḢṖ?µ¬¿
```
Input is a comma-separated string of integers.
[Try it online!](https://tio.run/nexus/jelly#@5/l4Hdot3GMbYXDwx3zgXjRw53T7A9tPbTm0P7///9b6hjrWOiY65joGBrpmAIA "Jelly – TIO Nexus")
*Credits go to @Xanderhall, @Sherlock, and @ErikGolfer for laying the groundwork.*
### How it works
```
j@N»3\=x@ḟ@ḢṖ?µ¬¿ Main link: Argument: A (integer or list of integers)
¬¿ While the logical NOT of A (0 for a positive integer, a non-empty
array for a non-empty array) is truthy:
µ Execute the chain of links to the left.
N Negative; multiply all integers in A by -1.
j@ Join -A, separating by A. This prepends and appends a
negative to A and appends more integers that will be ignored.
»3\ Compute the maxima of all overlapping slices of length 3.
= Compare the maxima with the elements of A, yielding 1 or 0.
x@ Repeat the elements of A, 1 or 0 times.
This ignores Booleans without a counterpart in A.
Ṗ? If the popped result is truthy, i.e., if it has at least two
elements:
ḟ@ Filter/remove those elements from A.
Else:
Ḣ Head; extract the (only) element of the return value.
```
[Answer]
# Python3, ~~265~~ ~~260~~ ~~248~~ ~~243~~ ~~203~~ ~~121~~ ~~117~~ ~~112~~ 111 bytes
```
def T(I):
b=[0];q=[];J=b+I+b
for i,x in enumerate(I):[q,b][J[i]<x>J[i+2]]+=x,
return len(b)<3and b[1]or T(q)
```
Thank you @ZacharyT, @orion, and @mathmandan for saving ~~5~~ ~~45~~ a lot of bytes!
[Answer]
## Haskell, 85 bytes
```
import Data.List
f x=(#)=<<(x\\)$[b|a:b:c:_<-tails$0:x++[0],b<a||b<c]
[s]#_=s
_#i=f i
```
Usage example: `f [9,3,8,7,4,12,5]` -> `4`.
How it works:
```
f x = -- main function with parameter x
[b| ] -- make a list of all b
a:b:c:_ -- where b is the second element of all lists with
-- at least 3 elements
<- tails $ 0:x++[0] -- drawn from the tails of x with a 0 pre- and
-- appended (tails [1,2,3] -> [1,2,3],[2,3],[3],[])
,b<a||b<c -- and b is not greater than its neighbors
(#)=<<(x\\) -- feed the list difference of x and that list
-- and the list itself to the function #
[s]#_s -- if the list difference is a singleton list,
-- return the element
_#i=f i -- else start over with the list of b's
```
A variant, also 85 bytes:
```
import Data.List
f x|n<-[b|a:b:c:_<-tails$0:x++[0],b<a||b<c]=last$f n:[s|[s]<-[x\\n]]
```
Bind the list of `b` (see above) to n and return the element `s` if `x\\n` is a singleton list and `f n` otherwise.
[Answer]
## Mathematica, 107 108 bytes
```
(For[x=y=#,Length@y>1,x=DeleteCases[x,#|##&@@y],y=Intersection[Max@@@x~Split~Less,#&@@@Split[x,#>#2&]]];y)&
```
**Explanation**
First, set `x` and `y` equal to the input `List`. The loop continues until `Length@y==1`. `x~Split~Less` is the list of lists of consecutive, increasing elements, `Split[x,#>#2&]` is the list of lists of consecutive, decreasing elements. Taking the `Max` of all of the lists in the former gives the list of children taller than the child to their right (along with the right-most child). Taking the first argument (`#&`) of all of the lists in the latter gives the list of children taller than the child to their left (along with the left-most child). The intersection of these two will be the list of children who raised their hand. Set this equal to `y`. `x=DeleteCases[x,#|##&@@y]` removes from `x` any elements matching an element of `y` (`#|##&` is equivalent to `Alternatives`). Once the loop terminates, return `y`. If the output must be an integer (rather than a list containing a single integer), return `#&@@y` (+4 bytes).
Thanks to Martin Ender for saving 2 bytes and making me comply with the rules. Open to suggestions.
[Answer]
# [Perl 6](https://perl6.org), 111 bytes
```
{(@_,{(($/=(0,|@$_,0).rotor(3=>-2).classify({+so .[1]>.[0,2].all})){1}>1??$/{0}!!$/{1})».[1]}...*==1)[*-1][0]}
```
## Expanded:
```
{ # bare block lambda with implicit parameter list 「@_」
( # generate a sequence
@_, # starting with the input
{ # code block used to get the next value in the sequence
# which has implicit parameter 「$_」
(
(
$/ = # store in 「$/」 for later use
( 0, |@$_, 0 ) # the input with 0s before and after
.rotor( 3 => -2 ) # take 3 at a time, back up 2, repeat
.classify({
+ # Numify the following:
so # simplify the following Junction
.[1] > .[ 0, 2 ].all # is the middle larger than its neighbors
})
){1} # look at the values where it is true
> 1 # is there more than 1?
?? # if so
$/{ 0 } # look at the false ones instead
!! # otherwise
$/{ 1 } # look at the true ones
)».[1] # undo the transformation from 「.rotor」
}
... # keep doing that until
* == 1 # there is only one value
)\
[ * - 1 ] # the last value of the sequence
[ 0 ] # make it a singular value ( not a list )
}
```
[Answer]
## Python 2, ~~100~~ 98 bytes
```
def f(A):
t=[0];l=[];a=b=0
for c in A+[0]:[l,t][a<b>c]+=[b];a,b=b,c
return t[-2]and f(l)or t[1]
```
Uses the short-circuiting return as in Yodle's answer (by Zachary T)
[Answer]
# Mathematica, 101 bytes
```
If[Equal@@(a=Position[Max/@Partition[#,3,1,{2,2},0]-#,0]),#[[Last@a]],#0@Fold[Drop@##&,#,Reverse@a]]&
```
Unnamed recursive function taking a list of numbers as input, and returning a list with a single number (the winner) as output.
The core of the algorithm is `Max/@Partition[#,3,1,{2,2},0]`, which computes the array of (the-max-of-me-and-my-neighbors)s from the input list. `a=Position[...-#,0]` then subtracts the original list and returns where the 0s are; these are the hand-raising children.
`If[Equal@@a, #[[Last@a]], #0@Fold[Drop@##&,#,Reverse@a]]&` branches depending on whether all the elements of `a` are equal or not (in this case, they will be only if `a` is a singleton); if so, then this child is the winner and we output her number; if not, then we recursively call this function on the list with all elements at positions in `a` removed.
[Answer]
# Python 2, 99 Bytes
```
def f(l):k=[x[0]for x in zip(l,[0]+l,l[1:]+[0])if(max(x),)>x];return(len(k)+2>len(l))*max(l)or f(k)
```
[Answer]
# PHP, 131 bytes
```
$r=$a=$argv;for(;$r[1];$a=array_values(array_diff($a,$r))){$r=[];foreach($a as$i=>$x)if($x>$a[$i-1]&$x>$a[$i+1])$r[]=$x;}echo$r[0];
```
Takes numbers from command line arguments. Fails if filename starts with a positive number.
**breakdown**
```
// import (and init $r[1])
$r=$a=$argv;
// while more than 1 raised hand, remove them from data
for(;$r[1];$a=array_values(array_diff($a,$r)))
{
// reset hands
$r=[];
// raise hands
foreach($a as$i=>$x)
if($x>$a[$i-1]&$x>$a[$i+1])$r[]=$x;
}
// output
echo$r[0];
```
[Answer]
# k, 40 bytes
```
{$[1=+/B:(|>':|x)&>':x;x@&B;.z.s x@&~B]}
```
Explanation:
$ is an if-else.
The condition is whether 1 is the sum of B, which is defined as the minimum of two lists generated by checking if x is greater than the prior and post-positions (Pipe is reverse).
If this is true we return x where B is true.
Otherwise we recurse without the true positions.
[Answer]
# Scala 129 bytes
## Golfed
```
def x(a:List[Int]):Int={val (y,n)=(0+:a:+0).sliding(3).toList.partition(l=>l.max==l(1));if(y.length>1)x(n.map(_(1)))else y(0)(1)}
```
## Ungolfed
```
def whoIsTallest(a: List[Int]): Int = {
val (handUp, handDown) = (0 +: a :+ 0).sliding(3).toList.partition {
case x :: y :: z :: Nil => y > x && y > z
}
if (handUp.length > 1)
whoIsTallest(handDown.map(_(1)))
else
handUp.head(1)
}
```
By padding the list left and right with 0's, can then group in sets of 3 and partition the list for those where the hand is up, the left and right most elements compare to 0 on the outside so get the correct number (assuming nobodys height is negative!)
[Answer]
# C++14, 182 bytes
```
#define P .push_back(c[i]);
int f(auto c){decltype(c)t,s;int i=0;(c[0]>c[1]?t:s)P for(;++i<c.size()-1;)(c[i-1]<c[i]&&c[i]>c[i+1]?t:s)P(c[i-1]<c[i]?t:s)P return t.size()<2?t[0]:f(s);}
```
Learned that the ternary operator can be used with C++ objects. Requires the input to be a random access container with `push_back`, like `vector`, `deque` and `list`.
Creates two containers `t` and `s` of the same type and appends the local tallest to `t` and the rest to `s`. If there is only 1 element in `t` return that one, otherwise recursive call itself with `s`.
Ungolfed:
```
int f(auto c){
decltype(c)t,s;
int i=0;
(c[0]>c[1] ? t : s).push_back(c[i]);
for(;++i<c.size()-1;)
(c[i-1]<c[i]&&c[i]>c[i+1] ? t : s).push_back(c[i]);
(c[i-1]<c[i] ? t : s).push_back(c[i]);
return t.size()<2 ? t[0] : f(s);
}
```
[Answer]
**R, 83 bytes**
Two different versions:
This one takes a vector N:
```
while(T){Z=diff(sign(diff(c(0,N,0))))<0;if(sum(Z)>1)N=N[!Z]else{print(N[Z]);break}}
```
This one creates a function F defined recursively:
```
F=function(N){Z=diff(sign(diff(c(0,N,0))))<0;if(sum(Z)>1)F(N[!Z])else return(N[Z])}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
{1=≢⍸s←⍵=3⌈/∊0⍵0:s/⍵⋄∇⍵/⍨~s}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rQ9lHnoke9O4oftU141LvV1vhRT4f@o44uAyDHwKpYH0g96m551NEOZAA5K@qKa/@ngdX2Peqb6un/qKv50HrjR20TgbzgIGcgGeLhGfw/TcFUwVjBUsFCwZwrTcFQwQjINgGyLIGiQDEFEwVDIwVTAA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
## A Brainfuck derivative
Let's define a simple [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck)-like programming language.
It has a two-directional tape of cells, and each cell holds one bit.
All bits are initially 0.
There is a moving head on the tape, initially at position 0.
A program is a string over the characters `<>01!`, executed from left to right, with the following semantics:
* `<` moves the head one step to the left.
* `>` moves the head one step to the right.
* `0` puts 0 in the current cell.
* `1` puts 1 in the current cell.
* `!` flips the current cell.
There are no loops, so a program of **n** characters terminates after exactly **n** steps.
A program is *boring* if all cells contain 0 at the end of execution, and *exciting* if there is at least one 1.
Note that the size of the tape is not specified, so depending on the implementation, it may be two-way infinite or circular.
## An example program
Consider the program `1>>>!<<<<0>!>>>!`.
On an infinite tape, execution proceeds as follows:
```
v
00000000000000 Put 1
v
00000100000000 Move by >>>
v
00000100000000 Flip
v
00000100100000 Move by <<<<
v
00000100100000 Put 0
v
00000100100000 Move by >
v
00000100100000 Flip
v
00000000100000 Move by >>>
v
00000000100000 Flip
v
00000000000000
```
At the end, all cells are 0, so this program is boring.
Now, let's run the same program on a circular tape of length 4.
```
v
0000 Put 1
v
1000 Move by >>>
v
1000 Flip
v
1001 Move by <<<< (wrapping around at the edge)
v
1001 Put 0
v
1000 Move by > (wrapping back)
v
1000 Flip
v
0000 Move by >>>
v
0000 Flip
v
0001
```
This time, there is a cell with value 1, so the program is exciting!
We see that whether a program is boring or exciting depends on the size of the tape.
## The task
Your input is a non-empty string over `<>01!` that represents a program in the above programming language.
An array of characters is also an acceptable input format.
The program is guaranteed to be boring when run on an infinite tape.
Your output shall be the list of tape lengths on which the program is exciting.
Note that you only need to test the program on tapes that are shorter than the program length.
The solution with the lowest byte count in each language is the winner.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Test cases
```
> : []
110 : []
1>0<! : [1]
0>>1>0<<>! : [1]
1>>>!<<<<0>!>>>! : [2, 4]
!<!<><<0>!>!<><1!>>0 : [2]
>>!>><>001>0<1!<<!>< : [1, 2, 3]
1!><<!<<<!!100><>>>! : [1, 3]
!!1>!>11!1>>0<1!0<!<1><!0<!<0> : [3, 4]
<><<>>!<!!<<<!0!!!><<>0>>>>!>> : [1, 2, 4]
0>>><!<1><<<0>!>>!<<!!00>!<>!0 : [3]
0000!!!!><1<><>>0<1><<><<>>!<< : []
!>!>!>!>!>1>!>0<!<!<!<0<!<0<!<!<!<1>!>0<<! : [1, 2, 5, 7]
<!!>!!><<1<>>>!0>>>0!<!>1!<1!!><<>><0<<!>><<!<<!>< : [1, 2, 4, 5]
!>1<<11<1>!>!1!>>>0!!>!><!!00<><<<0<<>0<<!<<<>>!!> : [1, 2, 3, 5, 6]
```
[Answer]
## Haskell, 119 bytes
```
t#'<'=last t:init t
(h:t)#c|c<'#'=1-h:t|c>'='=t++[h]|1<2=read[c]:t
f p=[n|n<-[1..length p],sum(foldl(#)(0<$[1..n])p)>0]
```
[Try it online!](https://tio.run/##VYxLDoMwDET3nMKBSgHRVnGXyPFFUBaIT0FNUwTpjrtTw66S5bE9fjM266v3ft9jpklb36wRYjWFSSTJxyoWWbu1pDNt8Sbr1rK22sayrEe3IT3s0jdd3boqJgPMtg5boFuN97vvwzOOMLvr@n3nw8d3Ps@K3NDlcIMr5oKN29/NFMBC90kA5mUKES4wQEpKsRQREjMrI80oUoyK8LwzkyE5yKgOpfQ/QF4FRkKWIFQnLxNLsDEk1IGzOWkJEy9N9h8 "Haskell – Try It Online")
Function `#` is the interpreter for a single command `c`. The whole program `p` is run by `fold`ing `#` with the starting tape into `p`. `f` executes `p` for every tape and keeps those where the sum of the cells is at least 1.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~56~~ ~~54~~ ~~43~~ ~~38~~ 35 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437
```
è¥%►BΣ░ÜY⌂y(â&.═ªê►V½▲y▌)▀♫♂╣ª?√»!#
```
42 bytes when unpacked,
```
%fz(y{{|(}{|)}{B!s+}{0_]e&}4ls"><! "I@!F|a
```
[Run and debug online!](https://staxlang.xyz/#c=%C3%A8%C2%A5%25%E2%96%BAB%CE%A3%E2%96%91%C3%9CY%E2%8C%82y%28%C3%A2%26.%E2%95%90%C2%AA%C3%AA%E2%96%BAV%C2%BD%E2%96%B2y%E2%96%8C%29%E2%96%80%E2%99%AB%E2%99%82%E2%95%A3%C2%AA%3F%E2%88%9A%C2%BB%21%23&i=%3E%0A110%0A1%3E0%3C%21%0A0%3E%3E1%3E0%3C%3C%3E%21%0A1%3E%3E%3E%21%3C%3C%3C%3C0%3E%21%3E%3E%3E%21%0A%21%3C%21%3C%3E%3C%3C0%3E%21%3E%21%3C%3E%3C1%21%3E%3E0%0A%3E%3E%21%3E%3E%3C%3E001%3E0%3C1%21%3C%3C%21%3E%3C%0A1%21%3E%3C%3C%21%3C%3C%3C%21%21100%3E%3C%3E%3E%3E%21%0A%21%211%3E%21%3E11%211%3E%3E0%3C1%210%3C%21%3C1%3E%3C%210%3C%21%3C0%3E%0A%3C%3E%3C%3C%3E%3E%21%3C%21%21%3C%3C%3C%210%21%21%21%3E%3C%3C%3E0%3E%3E%3E%3E%21%3E%3E%0A0%3E%3E%3E%3C%21%3C1%3E%3C%3C%3C0%3E%21%3E%3E%21%3C%3C%21%2100%3E%21%3C%3E%210%0A0000%21%21%21%21%3E%3C1%3C%3E%3C%3E%3E0%3C1%3E%3C%3C%3E%3C%3C%3E%3E%21%3C%3C%0A%21%3E%21%3E%21%3E%21%3E%21%3E1%3E%21%3E0%3C%21%3C%21%3C%21%3C0%3C%21%3C0%3C%21%3C%21%3C%21%3C1%3E%21%3E0%3C%3C%21%0A%3C%21%21%3E%21%21%3E%3C%3C1%3C%3E%3E%3E%210%3E%3E%3E0%21%3C%21%3E1%21%3C1%21%21%3E%3C%3C%3E%3E%3C0%3C%3C%21%3E%3E%3C%3C%21%3C%3C%21%3E%3C%0A%21%3E1%3C%3C11%3C1%3E%21%3E%211%21%3E%3E%3E0%21%21%3E%21%3E%3C%21%2100%3C%3E%3C%3C%3C0%3C%3C%3E0%3C%3C%21%3C%3C%3C%3E%3E%21%21%3E&a=1&m=2)
-2 bytes per comment by @recursive
## Explanation
I will use the version with a prefix `i`(i.e. `i%fz(y{{|(}{|)}{B!s+}{0_]e&}4ls"><! "I@!F|a`) to explain and I will explain why the `i` can be removed
```
i Suppress implicit eval
This prevents the test case "110" from being interpreted as a number
However, this can be removed because a program containing only numbers cannot be exciting and the output will be empty anyway.
This is based on the fact that the program is boring on non-circular tapes
%f Filter range [1..n] with the rest of this program
Where n is the length of the input
Implicit output the array after filtering, one element per line
z( Initialize the tape
y{ F Run the program
|a Any cell is non-zero
```
Code for running the program:
```
{|(} Block to rotate left by one element
{|)} Block to rotate right by one element
{B!s+} Block to perform logical not on the element at index 0
{0_]e&} Block to obtain current instruction,
Convert it to a number
And assign to element at index 0
4l Pack the 4 blocks in an array
s"<>! "I Find the index of current instruction in string, if not found, the index will be -1
And when indexed with -1, it wraps around to the 4th element.
@! And execute the corresponding block.
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~57~~ ~~56~~ ~~49~~ 46 bytes
-7 thanks to @MartinEnder
```
{:T,({)0a*T{i23%")!+(+ W0tW1t)\+"3/=~}/:+},:)}
```
[Try it online!](https://tio.run/##NVDLasNADLzvV1SBQFwHLDU3o8wn5BTIpZfQUwuFFnIzzq@7M7K7i1l5NS/tx9f9e/m9DMs0Xo@HqfP763X6fDvtd531h/7l5o9bPLr3fncazs95GPv5OHbzsh9/FrSApzUHVCSMF4All8NUNktLrL8qgrfeoGbCXbQg3pCNLRakmoU720W3IDaCR0Fpl4Gs09EkLUMrnptJA8xTDgqGlbAFkpVRnFHMm3NZcSLl54XcJLMZ/rcyyFHbt89KWPd8AaqivKNiy9cJAGeLNRNSQKwjalw2CY/SMD0LGfKqgFmJNcr6JJD6Hw "CJam – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~83~~ ~~82~~ ~~79~~ 77 bytes
Includes `+3` for `-F`
Give instructions as one line on STDIN
```
#!/usr/bin/perl -F
1~~@$m&&say$m until++$m>map{*r=\$$m[($n+=/>/-/</)%$m];$r=/\d/?$&:$r^/!/}@F
```
[Try it online!](https://tio.run/##HYhBCsIwEEWv4sAY1BInWXRTp2NX3XkCq1DQRaFJS1oXIvboxig8/vu88R76PEa7LBU6pab2iW718HPXZxk6ce342oWyQXTnDfqsJCFNTNs1ussBQ0nNjY6oCgxXAnpXdYwMIAlmyyICJo0BBrHA9t9F2HAK6cLP/BnGuRv8FPUp3xtroq6/ "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) (`-F`), 101 bytes
```
map{$,=@a=(0)x$_;map{$,+=/>/-/</;$a[$,%@a]=$&if/0|1/;$a[$,%@a]=!$a[$,%@a]if/!/}@F;say if@a~~/1/}1..@F
```
[Try it online!](https://tio.run/##TcvBSgMxEAbge58i06ai2GySQ087O@S0N59ARIaS0i3qhk0WFNs@ujGxIJ3L//PNTPDT2zbndw7fctM57u7Nw6d8ba/w2GnSSqNuJT/LzdrxSyfvhr02J3tr8F/LDvTZ9W3kLzHsHV8u2uqzbRrX54pLpdSyFStxnGMSBz95kUYRfeCJU@m@6I6jF@OcwpxiRkIkAgRARDAAUMFQGSBaFKc/sliluinHZAHt9ZTQlMcSCDXxZwxpGD9iVk/bxliTVf8L "Perl 5 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 243 bytes
```
func[p][repeat n length? p[b: copy[]insert/dup b 0 n i: 1
parse p[any["<"(i: i - 1 if i < 1[i: n])|">"(i: i + 1 if i > n[i: 1])|"0"(b/(i): 0)|"1"(b/(i): 1)|"!"(b/(i): either b/(i) = 0[1][0])|
skip]]s: 0 foreach c b[s: s + c]if s > 0[print n]]]
```
[Try it online!](https://tio.run/##bVG7bsMwDNzzFaSnFEUQcg1U9h@6ChoSR26MFo5hp0OB/nt6lJMOjSwY4vvuqCkfr2/5SDFRt7t2X0MbxxSnPOb9hQb6zMP75fRKYzzsqD2P3zH1w5yny/b4NdKBBDX9jnQ17qc5o2w/fMcmNGsEe9qQUt/BCKQRkSE9/TR2Sz7fk0aDJ9WT0qwP23X/tCOBp3@ewuM/L/eXU56oePRCEjVFQftq/ujHlGZ0U3ee8r49UUuHiMAMvDYBbwaexHHqB@hLKV0Xs9lsNs2qIwK/1f@QmgR@DIuZZ4JxrcWMAz4xdvOxggMHW/JuKMrkscq8PZiIIykmsoUKGqLB4ZhVBPV1RFZMU8VVhkFUUAvllopsp@cquEwWZkcxqC6kqvuwZeRNttNl8IE@rmgTfFymanDOUlpvoBWVbPfjOpy1H7n9XKA9XnsrELHCX8tynKqgw7BSXXRZ8E5bFlndMqrRrwWF/b0wwtkUkaGo9v0sL2EO11x/AQ "Red – Try It Online")
Prety verbose and straightforward implementation. Red's 1-indexing doesn't allow me to reduce the byte count by using modular arithmetic for looping through the circular tapes.
Ungolfed
```
f: func[p][
repeat n length? p[
b: []
insert/dup b 0 n
i: 1
parse p[
some [
"<" (i: i - 1 if i < 1[i: n])
| ">" (i: i + 1 if i > n[i: 1])
| "0" (b/(i): 0)
| "1" (b/(i): 1)
| "!" (b/(i): either b/(i) = 0 [1][0])
| skip
]
]
s: 0
foreach c b[s: s + c]
if s > 0 [print n]
]
]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~139~~ ~~135~~ ~~133~~ ~~132~~ 131 bytes
-3 bytes thanks to Mr. Xcoder
```
def f(p):i=0;exec"i+=1;s=[0]*i\nfor c in p:c=ord(c)-61;s=c>-2and s[c:]+s[:c]or[[s.pop(0)^1,0,1][c%7]]+s\nif 1in s:print i\n"*len(p)
```
[Try it online!](https://tio.run/##VZL/aoNADMf/31NcBsO2cyNpuw7smRe53mBYZcJQUQfb03dJzu6HIt4luW8@yWX4mt/6bnu5nOvGNathXbQlHuvPurpt70s6TmXAuGlPXdOPrnJt54aiKvvxvKrWDwf1V/ywfe3ObgpVEe@nUFSxH0OYHod@WOH6hXLMKYbq7jmK@9S1jSORmYphbLvZifTt5r3uJPVlrqd5cqULIeMsdyHGPGTE6EF3ZFtkVovnPzZiZvDyIIMu1bPN3d6c4MFzcumCJAItwLysJzwjqiiJCLA34dyJwi7Ji82rPgAhSvSSgq4BYhcZIvmZigB7Ym9/tEp2VxpFUVgwPQRQbZaiDOQ38/5aLCetpTYFBGGQSsCqSAAoD5gWeeVDO7Kk8j@tBL6@yqt0@uLygWVSu4dfkKfcPSdykTdasgYoGsoRlqZRqoK9HuXUrH993IvOQkAiQJYH9CpEQ3msKm9lajtSu1nz/bkMgznEGG9udBp1WnI31tPH@6yDmaancGmudHdMyxRybFZqWydjduqyyzc "Python 2 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 121 bytes
```
.+
$.&*0¶$&
\G0
0$`¶
{ms`^.(?=.*¶¶(0|1))
$1
"¶¶!"&mT`d`10`^.
"¶¶>"&`(.)(.*)¶
$2$1¶
"¶¶<"&`(.*)(.)¶
$2$1¶
)`¶¶.
¶¶
G`1
%`.
```
[Try it online!](https://tio.run/##Tcs7DsIwDADQ3bdIZKIkSJbNXMLYC3REyEgwMJQBusG5coBcLE3Kggf/nv26L4/nVWqlPSC5yCWjg/PIwKglw2d@64X86Uix5JI9fyUEQAHbR2PdPOlNhdvRb5WsU0/BUwztHQ8orWwybBIb/UnQTgQ9w6gCO6VaJaVkhhacTG9X "Retina – Try It Online") Explanation:
```
.+
$.&*0¶$&
\G0
0$`¶
```
Create an array of tapes of each length up to the length of the input program.
```
{
```
Loop until the program is consumed.
```
ms`^.(?=.*¶¶(0|1))
$1
```
If the next character in the program is a 0 or 1, change the first character on each line to that character.
```
"¶¶!"&mT`d`10`^.
```
If it is a `!` then toggle the first character on each line.
```
"¶¶>"&`(.)(.*)¶
$2$1¶
"¶¶<"&`(.*)(.)¶
$2$1¶
```
If it is a `>` or `<` then rotate the line. (Easier than moving the head.)
```
)`¶¶.
¶¶
```
Delete the instruction and end the loop.
```
G`1
```
Keep only the exciting lines.
```
%`.
```
Count the length of each line.
[Answer]
# JavaScript (ES6), ~~126~~ 118 bytes
*Saved 3 bytes thanks to @user71546*
Takes input as an array of 1-character strings.
```
f=(s,l=0,p=0,t=[])=>s[l++]?s.map(c=>1/c?t[p%l]=+c:c>'='?p++:c>';'?p+=l-1:t[p%l]^=1)&&+t.join``?[l,...f(s,l)]:f(s,l):[]
```
[Try it online!](https://tio.run/##hZJhT4MwEIa/@yu4Dw4IjPXc1ATb44eQGhfczBYcRIh/H@/ajTgFhZA223t3z/u2x@3ntqs@Dm2/PDWvu2HYm6hLa6PSlr/elDY21JV1ktiiy963bVQZwlVV9GV7W1uTVHlFoQmLNklk9yQ7Uy8x94Jng/FikfTZsTmcXl6Ksk6zLNvLjNjmfs1LO1TNqWvqXVY3b9E@KlkTUmjjOFitSnsz8S@S0nBR4KREEYlK0z86JCLQ/CgC2V7Ud2mwmSwADZq8XDbIVWosmqwg6axJKQFCHgakR6g04EnraTTWaWEDQKW4wzc8nCtiLY9D5MVN46A0knarGlNdz7kTaxIIuLkKQBiIw3Qmrqk3c8GTn3nOVAwD83NaMCY1Da/4ATcTtfhVrs0ZSf95JYAur/gXt/Kq8weOSH7XcG3iPg0ep5NgDOceXfBiS3Eb4gNEnwppaUf@kH6d6YZ7z5AiN0XHA3J9uK9wu5S0i00i90dPwvDjsjjoBzt8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~79~~ ~~64~~ 54 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS))
```
⍸⊂{∨/⍎⍕(↓',',⍨5 3⍴'0@11@1~@1 1⌽¯1⌽')['01!<'⍳⌽⍺]⍵}¨0=,\
```
[Try it online!](https://tio.run/##rVCxSgRBDO39ik01CismiF0MV1toYakWB3I2B9qKaGFxiDiHIPcP21moIILNfUp@ZM3LrvgDzjCb2czLey@ZXs23z6@n88uLvvf66Y/3N/7Q7Xhdel1t@uKltKX12u01u17fC09EJnI3kUb86Xv9im/ZOikspMXrW/x6/Trz@nG77ni/Pe37WeOL5@b/uNs/8g1frg6Ojw7XXTOLU6w0RYyVIrIZrmqUSTPSWGyEa6RISW1I4CKR50gbAGrMKA5hJVMQRFAwEAlzAEYSksCLREh4SKuYZmS4gQSkKWuZCDwW3lJnsGlD0WgOkhQSYYpgiGNR1olClxM70sIa2e@GFyhj83goyZHPqQS3pQfJFqDOAbHoVAZvpoDa0O7QfDxHgSQPYVBRA700qukcTQ0DMvCXHw "APL (Dyalog Unicode) – Try It Online")
-15 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) (forgot about monadic `⍸`).
-10 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn).
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~46~~ 39 bytes
```
f"@:~G"@59>?@61-YS}@33=?t1)~}@U]1(]]a?@
```
[Try it online!](https://tio.run/##DckxCoAwEETRs2watRCyBAVlnGznAcTCIoWNlXZp9eoxxYcH/znzXcrlbP5WZ8PEaKP2x/ZaCEvM2n2v7UnblM5opTRCBVShFIoKSS9VhIj3IAAPsCaVZH3NDw) Or [verify all test cases](https://tio.run/##NVC7TgNBDOz5C6dZKE6yFYEEMnNbUKUFpFCcRBoq0qVNfv2Y8R67Otnyzct7Pl1@1@/jYf3Z9ZfbYdcfnzH3p5i@3q99v3@dL/Fwu/bPJe6X5TT3dVnaNLXj28fa0O5awNNYHVCbsBoCljwOU8uRpSXGQE1w7hxDgIS7yEGOISXAklIwC3cCNhEL4iNYCk7rDGRVVxpZyNqK62bSAbOVz4iJQdrCydJowVCmQM5jxYuUrxd2k1U0w/9VFjnr@vZZiWter0JtVIaoFeTuhICbxsiGFBRj3bE8f5MQpWN6KHLkV0Gzkmup8UCQfvsD).
### How it works
```
f % Push indices of nonzero chars of (implicit) input string: gives
% [1 2 ... n] where n is input length
" % For each k in [1 2 ... n]. These are the possible tape lengths
@:~ % Push array of k zeros. This is the tape, in its initial state
G % Push input string
" % For each char in the input string
@59>? % If code point of current char exceeds 59 (so it is '<' or '>')
@61- % Push code point minus 61: gives -1 for '<', or 1 for '>'
YS % Circularly shift the tape by that amount. Instead of moving
% the head, we shift the tape and keep the head at entry 1
} % Else
@33=? % If code point of current char is 33 (so it is '!')
t1) % Duplicate the array representing the tape, and get its
% first entry
~ % Logical negate
} % Else
@U % Push current char (it is '0' or '1') converted to number
] % End
1( % Write (either 0, 1 or old value negated) at entry 1
] % End
] % End
a? % If the tape contains at least a nonzero value
@ % Push tape length, k
% End (implicit)
% End (implicit)
% Display (implicit)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~192~~ 78 bytes
```
⊂{t/⍵⊣⍵{t[m]←('01!'⍳⍵)⊃0 1,e,⍨~e←t[m←⍺|i⊣i+←¯1 1 0⊃⍨'<>'⍳⍵]}¨⍺⊣i←⊃t←⍬⍳⍺}¨1+⍳∘≢
```
[Try it online! (non-flattened result)](https://tio.run/##NVC9SgNBEH6Vm2oTTOJMvw5ItBD8KaKFiEXEiwRiInqFErVQET05sRGstUkRsBCblHmUfZH4zd55x93Oznx/u92zQfP4qjsYnSxq4fV9uxOKab0VileHXXvfuYvuIHMuvDxg31lv7bW31rB9fDsaXSajXi9p9lZGw6SZrWTnaYpJ/pUOu0eDtLO6uWusYlqRN3bA4sUCPvndOFsOxS/A@I@zg9NDzGqOhVwoftCrh/yeE2mkjVBMblNMAcI/FLPrfsg/UfaX5t@SSMKAAuS8VtzDm/kEOIj3jZHfZ5E4jdMZhrJk5dNHeP6szyeN@cSpS5woe8LKqlZ6pdhUJY@HlaxEizx5LRtWCPqMthrAK7ORBRxSbwJYvCkQCTMAlQgJ8CJYIhzWXtTHlS2NWZg1RS4TmY4iW/QpY2pJqsKZJcECocgCMR6KPPHmyxFbyVo00v/XspizvVx9FMWtH28F2hozSDyCuTMgipNKmU29QbU8bnl4jEGQqEN2UeCYXwzqY3I7VHlBavruDw "APL (Dyalog Unicode) – Try It Online")
[Try it online! (flattened)](https://tio.run/##NVA7SwNBEP4rN9UmJNGZfh0QtRB8FNFCJEWCFwlEI3qF4qMwInpywUaw1iZFwEJsLPNT9o/Eb/bOO@52duZ77XbPhq2jq@5wdLyohcnbTjsUs/pSKCYOu7UD5y66w8y58PKAfXtjaX9tex3bx9fe6DIZ9ftJq78yOk1a2Up2nqaY5J/pabc3TNurW3vGKmYVeXMXLF4sFuEpr4X8/jpbDsUP8PhfZ4cnHYxrjoVcKL7Rq4d8zIk002YopncppgDhH4rfm0HIP1AOGvMvSSRhQAFyXitu53Y@BQ7iA2Pk4ywSZ3H6i6E0rHx6D88f9fm0OZ86dYkTZU9YWdVKrxSbquTxsJKVaJEnr2XDCkGf0VYDeGU2soBD6k0AizcFImEGoBIhAV4ES4TD2ov6uLKlMQuzpshlItNRZIs@ZUwtSVU4syRYIBRZIMZDkSfefDliK1mLRvr/WhZztperj6K49eOtQFtjBolHMHcGRHFSKbOpN6iWxy0PjzEIEnXILgoc84tBfUxuhyovSE3f/QE)
~~After some time spent banging my head against the wall, I decided to make a Tradfn instead of a Dfn. This is the result. Smarter people than me may be able to golf the heck out of this.~~
Surprise, surprise, someone smarter than me *did* golf the heck out of this. Thank you Adám for 114 bytes.
He said:
>
> Notice that it is your exact program, except using indexing instead of the inner :Ifs and collapsing :For-loops to {\_}¨ while giving a left argument to replace the global.
>
>
>
The function assumes `⎕IO←0`.
---
### How?
(This explanation uses an "ungolfed" version to facilitate reading)
```
⊂{ ⍝ Enclose
i←⊃t←⍬⍳⍺ ⍝ Assign a vector of 0s to t (the tape), then assign the first 0 to i.
t/⍵⊣⍵{ ⍝ Use ⍵ as left argument for the nested function, then compress the result into t. If there is a 1 anywhere in t, the result will be a vector of the result. If not, the result is an empty vector.
i+←¯1 1 0⊃⍨'<>'⍳⍵ ⍝ Map the string '<>' to the argument (which is the BF program). That yields 0 for <, 1 for >, and 2 for anything else.
⍝ The resulting vector will then be used as the argument for ⊃ to add -1 (index 0), 1 (index 1) or 0 (index 2) to the variable i.
e←t[m←⍺|i] ⍝ Assign i mod ⍺ (left arg) to m, and use it to index t. Then, assign the value to e.
t[m]←('01!'⍳⍵)⊃0 1,e,⍨~e ⍝ Map the string '01!' to ⍵. As before, this yields 0 for 0, 1 for 1, 2 for ! and 3 for anything else.
⍝ Then, concatenate (not e) with e, then concatenate that with the vector 0 1. This is used as argument to be picked from, and it is assigned to t[m].
}¨⍺ ⍝ Do that for each argument
}¨1+⍳∘≢ ⍝ And do that for each possible tape length from 1 to the length of the input.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes
```
JR0ṁð3“1⁺¦01¦¬1¦ṙ1 ṙ- ”s“10!<>”,yẎvЀ⁸Ẹ€T
```
[Try it online!](https://tio.run/##FckxCsJAEIXhq2R6AzPYDu8AluIVbCSdIKTL2tiJWClomypFyuyWu@QguxdZx@L9fPBOx67ra93tOXuX5m0ZPlJciCNLHONkyf4tjaVtyvA9/38mhXnT53C/pEe5TsUtOSyGQ0239Zn9q1aCqIqogEBCAJhMUCJmhaqyKmxkBOz7AQ "Jelly – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 171 bytes
```
l,i;f(S){for(char*p,t[l=strlen(S)];l;memchr(t,1,l)&&printf("%d ",l),l--)for(memset(t,i=0,l),p=S;*p;p++)*p==60?i=i?i-1:l-1:*p==62?i=i^l-1?i+1:0:*p^33?t[i]=*p-48:(t[i]^=1);}
```
[Try it online!](https://tio.run/##TZFhb4JADIY/y6@gJDMHQtJuy7LIUX@EH40mxqm7BB0Bti/Lfrtri6IQcr1e37fPlV2xq7fn4@VS56E8uGX6e/hq3e5z22ZN3q/qquvben@Wg3VZl6f9affZuj6nvE6n06YN5/7gkqePOJFEXhdFqnIp6/a9lIUKNd9UyzJrymY2S7Omqt5wEaqwCAXNa/ks9aypjWwXYUZzlOTm5WXRr8K6ypri9X3uNN5UlJZ/l5@v8BEfjTLOujT6jSYjShfP41WSx11aRpODs6X57juXrBOJ/6JICuPTNpydCY8uYT3QgAjHkNHDbYPMuvcM92Nm8PIgg4a3PHjwPGQ1IDkcLVlLPSOqF4ka2I9@Ens1BCBEqXr0BBIlkSwmFDBP7G3FkV3bKhOYCwKoIwu5tX24CQ/yK7pigHQUWhhJUR4wB/LKgia4NhiZgW@v8imNvnj9wNpo/j5HacXGRXZBhUGpYxkGDbzstZ6HYTzMR2pEReYIOlURameD93Ybve0wQ9Ym9rMv/w "C (clang) – Try It Online")
Had to use clang, since using `char*p,t[l=strlen(S)]` as the initialisation expression for some reason makes GCC think I want to declare `strlen` instead of calling it.
Pretty straight-forward: Runs the program on circular tapes of decreasing length, outputting any length that resulted in a 1 somewhere on the tape.
Tried shortening the tangle of the ternary operators, but ended up needing more parenthesis than was healthy.
] |
[Question]
[
(This is my first code-golf question)
When I was a child, my dad and I invented a game where the license plate we see on cars can give certain points based on some rather simple rules:
X amount of the same letter or number give X-1 points, examples:
```
22 = 1 point
aa = 1 point
5555 = 3 points
```
The numbers must be next to eachother, so `3353` only gives 1 point, as the 5 breaks the sequence of 3's.
A sequence of X numbers in ascending or descending order, at a minimum of 3, give X points, examples:
```
123 = 3 points
9753 = 4 points
147 = 3 points
```
The point system only works for 1-digit-numbers, so `1919` doesn't give points, and `14710` only give 3, (147).
Sequences can be combined to make more points, examples:
```
1135 = 4 points (1 point for 11 and 3 points for 135)
34543 = 6 points (3 points for 345 and 3 points for 543)
```
You are however not allowed to chop a larger sequence into 2 smaller sequences for extra points: `1234 = 123, 234 (6 points)` is not allowed.
Your task is, given a sequence, to determine the number of points the license plate gives.
In Denmark, the license plates are structured like this: CC II III, where C is character and I is integer, and thus my example inputs will reflect this structure. If you wish, you may make the sequence fit your own structure, or, if you feel really adventurous, let the program analyze the structure of the license plate and thus have it work on any type of license plate around the world. Explicitly state the structure you decide to use in your answer though.
You may take the input in any way you please, either a string or an array seem to make most sense to me.
Test input | output:
```
AA 11 111 | 5
AB 15 436 | 3
OJ 82 645 | 0
UI 65 456 | 6
HH 45 670 | 5
YH 00 244 | 5
AJ 00 754 | 1
```
Due to the nature of choosing your own structure, or even covering all structures, I dont necessarily see how a winner can be explicitly determined. I suppose the winner will be the shortest bytes on the structure one has decided. (And don't take an input like C I C I C, just to make it easy for yourself)
EDIT:
Due to comments asking, I have a few extra pieces of information to share: A sequence of ascending or descending numbers refers to an arithmetic sequence, so X +/- a \* 0, X +/- a \* 1, ... X +/- a \* *n* etc. So 3-5-7 for example is 3 + 2 \* 0, 3 + 2 \* 1, 3 + 2 \* 2. The sequence does not, however, need to start from 0 nor end in 0.
MORE EDIT:
You may give the input in any way you please, you dont need to input spaces, dashes or any other thing that makes a license plate more readable. If you can save bytes by only accepting capital letters or something like that, you may do that aswell. The only requirement is that your program can take a string/array/anything containing both characters and numbers, and output the correct amount of points according to the rules stated.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~22~~ ~~20~~ 18 bytes
Accepts a string of lower-case alphabetic chars and numbers with no spaces.
```
Ç¥0Kγ€gXK>OIγ€g<OO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cPuhpQbe5zY/alqTHuFt5@8JYdr4@///n5loCQIA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVvn/cPuhpQbe5zY/alqTHuFt518JYdr4@/@vVDq830rh8H4lnf@JiYYgwAXUZmpibMaVn2VhZGZiylWaaWZqYmrGlZEBJM0NuCozDAyMTEy4ErMMDMxNgXSmJQgAAA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ ~~16~~ 15 bytes
-1 byte thanks to @Zgarb
Takes input without spaces and in lower case.
```
ṁ??¬o→LεL←gẊ¤-c
```
[Try it online!](https://tio.run/##yygtzv6vkJtf/Kip8dC2/w93NtrbH1qT/6htks@5rT6P2iakP9zVdWiJbvL///8TEw1BgCsxydDUxNiMKz/LwsjMxJSrNNPM1MTUjCsjA0iaG3BVZhgYGJmYcCVmGRiYm5pwZSZaggAA "Husk – Try It Online")
### Explanation
```
Ẋ Map over all adjacent pairs
¤-c get the difference of their codepoints
g Split into groups of equal elements
ṁ Map then sum
? ← If the head of the list is truthy (not 0)
? ε If the length of the list is 1
¬ return 0
Else
o→L return the length + 1
Else
L return the length
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~193~~ 85 bytes
-3 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn)
Takes input as a byte-string with lowercase letters as: `b'aa11111'`.
```
def f(s):
d=l=L=p=0
for c in s:C=0!=d==c-l;p+=(c==l)+C*L;L=3>>C;d=c-l;l=c
return p
```
[Try it online!](https://tio.run/##TdDBboMwDAbgM3kKtxdgZVIoSehA7oXjkPYAUw80gKBCgAiV2qdnDmVSffzsP4o9Pudm6KNlKasaas/4CYMSO8xxRM6gHibQ0PZgkgz5DktE/dml4wE9jdj5h@wjT3OMzucsLddWh5rBVM33qYdxmTUg/DLHu7pFEdpyA5B@8JJrKEWkSKJNmkZIFfO3meF2OiohSfgm91ZJmiJRmzwbzo9CvL984zyWVsJNHo9TrFb5T7XFly0SQXJhzO5qAih6YxeedcIc2oP@b8/CnHFq@9mjATehDHUC2CPu1wC1C2OqaYY1gdYCMIy9Qu7P9871lz8 "Python 3 – Try It Online")
[Answer]
# Java 8, 195 bytes
```
a->{int r=a[0]==a[1]?1:0,i=3,j,p=a[2],x,y,z;for(;i<7;p=a[i++])for(r+=(x=a[i])==p?1:0,j=-4;++j<4;r+=j==0?0:i<6&&p+j==x&x+j==(y=a[i+1])?++i<6&&y+j==(z=a[i+1])?++i<6&&z+j==a[i+1]?5:4:3:0);return r;}
```
Can definitely be golfed some more by using another technique to check for sequences.
**Explanation:**
[Try it here.](https://tio.run/##dVPRbptAEHzPV6z8YB0CI7ABR2BiuVElJ1HSqlarpBYPV3xxoASj40iNLb7d3YPaMbTl4dDNzN7ODlxM3@hgk7E0Xv08hAnNc7inUbq/AIhSwfgzDRk8yG0NQEjCF8qXAVDFQ7C6wCUXVEQhPEAKPhzo4GovldynSyPwcTWDqekaWuSPtFjLEBgG2lYrtZ33vOHEiyZjT6KRqgaKRLjqk60EAsX3s7o29geWp6rxxPKQjX3fmBpuNHH6/UzF3ba/lS9S1seYgTJV1Zota3jXhXcSbrCp7VruyDUUjzNR8BS4Vx08OVZW/EhwrD/TvW2iFbxiNGQheJSu6wiaXGLMUC9ElOj3NJs0tAY3GN@a8SsQLBfXNGc5ppOyX2fyOc1fsIQo@@Yg2VOQ3mxmyqengV2H/E58MG1r5CAxahOfbi@HjmUjYbSJrzeObdmywmkT8znCY@PvHk9zwxha1j@a3xrG2JaE2SYeHy/HTk10ejx9H1no94yoqjpZAPmZW7HpH1PBy/@HB@57jjqT2gUTRFGOwTWFgB@MpSH7nFDBMO5jib5m4o6V5ORP/qBsm7FQsNUXlheJ6Ki/0aRgbT0NRUGTkzrVQ3LeTheba7waM84pNjpVLspcsFd9Uwg9Q4siSVtVoELPheXRiws9RDrOUBKAB8vGQCNpmakFDU66U/kt6dFXVd/d6vAb)
```
a->{ // Method with character-array parameter and integer return-type
int r= // Result-integer
a[0]==a[1]? // If the two letters are equal:
1 // Start this result-integer at 1
: // Else:
0, // Start the result-integer at 0 instead
i=3,j, // Index-integers
p=a[2],x,y,z; // Temp integers
for(;i<7; // Loop (1) from index 3 to 7 (exclusive)
p=a[i++]) // And after every iteration: Set `p` and raise `i` by 1
for(r+=(x=a[i])==p? // If the current digit (now `x`) equals the previous `p`:
1 // Raise the result-integer by 1
: // Else:
0, // Keep the result-integer the same
j=-4;++j<4; // Inner loop (2) from -3 to 3 (inclusive)
r+=j==0? // If `j` is 0:
0 // Skip it, so keep the result-integer the same
:i<6 // Else-if `i` is not 6,
&&p+j==x // and the previous digit `p` + `j` equals the current digit,
&x+j==(y=a[i+1])?
// and the current digit `x` + `j` equals the next digit `y`:
++ // Raise index `i` by 1 first,
i<6 // and check if `i` is not 6 again,
&&y+j==(z=a[i+1])?
// and if the new current digit `y` + `j` equals the next digit `z`:
++ // Raise index `i` by 1 first again,
i<6 // and check if `i` is not 6 again,
&&z+j==a[i+1]?
// and if the new current digit `z` + `j` equals the next digit:
5 // Raise the result-integer by 5
: // Else:
4 // Raise it by 4 instead
: // Else:
3 // Raise it by 3 instead
: // Else:
0 // Keep it the same
); // End of inner loop (2)
// End of loop (1) (implicit / single-line body)
return r; // Return the result-integer
} // End of method
```
[Answer]
# [R](https://www.r-project.org/), ~~153~~, ~~145~~, 143 bytes
```
function(x){p=0;s=sum;if(x[1]==x[2])p=1;a=diff(strtoi(x[3:7]));p=p+s(a==0);l=sort(table(a[a!=0]),T);(p=p+s(l[(l[((s(l)>0)&(l[1]>1))]+1)>2]+1))}
```
Anonymous function that takes a character vector and returns an integer.
Expected input `z(c("A", "A", "1", "1", "1", "1", "1"))`
[Try it online!](https://tio.run/##bdDPS8MwFMDxu39FnSDvsR2S/ljV8Ap62nbx4g5ScojTQqGupc2gTPzba9@C2aaD8qV9@aSkbYdhT8Vuu7FlvYUevxoSqqNu96nKAvpcaqI@DzU2JJWh97IooLOtrctxMXpINaJqqJl2YIgEqoq6urVgzVv1ASY31yQ0zl5QgVNVzheMN5gJvB0fpM4kop5KzEIufg972MDkcTILXOTFIAY3QXJ1tE9@MeHEnIgzdzZy9plHK84dJ3Tid0PirHB2zaOlF8kJO7537uyCR4u/YkzKEWfnffVW@IR@a/z/21bnNj05zcFKZ5f@n91fzMHGww8 "R – Try It Online")
Ungolfed version
```
function(x){
pnt <- 0; s <- sum
if(x[1] == x[2]) pnt <- 1
a <- diff(strtoi(x[3:7]))
pnt <- pnt + s(a == 0)
l <- sort(table(a[a!=0]), T)
(pnt <- pnt + s(l[(l[((s(l) > 0) & (l[1] > 1))] + 1) > 2] + 1))
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, ~~116~~ 89 bytes
```
$a.=($_=(ord$F[++$t])-ord)?chr$_+77:++$;for@F[0..@F-2];$_=$a=~s/(\S)\1+/$;+=length$&/ge+$
```
[Try it online!](https://tio.run/##RY1RS8MwFIXf@ysuLOhmXZO0TSuW4OpDmYL4ID7oNiRucS2UtiQZUxj@dOtdJwgX7vnO5ZzbaVOL3tKlpXSb4T4EF5Rms0LSAA0YzVWzqbUFV2qomm7nQFnYWb1BGsyute4SjEJt0FANlO0eRWXBrk3VOdirxlmonDeCp5Oj1m6n6vrr7/Tfva9c2eK2nVpre42JPOdhFAuPGMkykkmiJHmX5@cZcXLwRkZb7eCjNdDoTwfOVKruiQrkmLzJcWs2pFj4PnGryRRhcrMuDXnz0/QazQxjs2LBgmBWTMNVhgl88G3pePk0WXKfksyXtW62riRndKt90vd5DpzjcDiA8PJb4ALiKEGKvMd7uAohiQUS857vIMGbON4Sbz5HCUnKhtzLHBiDMI5PLfdHSsWR@LETVRT@fXgFHkI0dA7EOIScDZ0nikSKFP@0navaxvbTBxEwzvpp3RW/ "Perl 5 – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~51~~ 50 bytes (staggering)
```
+/|R0.+QZslM.MlZ+kfTsmm?&!-K.+sMkhK.AKkY.:>Q2d}3 5
```
**[Verify all test cases](https://pyth.herokuapp.com/?code=%2B%2F%7CR0.%2BQZslM.MlZ%2BkfTsmm%3F%26%21-K.%2BsMkhK.AKkY.%3A%3EQ2d%7D3+5&input=%22HH45670%22&test_suite=1&test_suite_input=%22AA11111%22%0A%22AB15436%22%0A%22OJ82645%22%0A%22UI65456%22%0A%22HH45670%22%0A%22YH00244%22%0A%22AJ00754%22&debug=0)** or **[Try it here.](https://pyth.herokuapp.com/?code=%2B%2F%7CR0.%2BQZslM.MlZ%2BkfTsmm%3F%26%21-K.%2BsMkhK.AKkY.%3A%3EQ2d%7D3+5&input=%22HH45670%22&test_suite_input=%22AA11111%22%0A%22AB15436%22%0A%22OJ82645%22%0A%22UI65456%22%0A%22HH45670%22%0A%22YH00244%22%0A%22AJ00754%22&debug=0)**
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 91 bytes
```
f(p,r,d,D,s,l)char*p;{for(r=D=0;d=p[1]-*p,*++p;D=d){s=d&&d==D;r+=!d+s*l;l=3-2*s;}return r;}
```
[Try it online!](https://tio.run/##LY9Nb4MwDIbP5Fd4TK0ChClQoJuy9MSx2m0nxoGRMlIxQAkcporfzsKHfbAf2Xr9uvR/ynKeK9wTRQRJiSaNU9aFcnv2qDqFFU85ZYL3WZD7bk9cz@tZyoXz0Fwcj4LzlCmPPwlPuw1r@MkPXc0mdRtG1YJi0/ws27IZxQ3e9SBk91JfEJLtAL@FbLEDD2Qt98DVWQ58QcsuimAJm6zwHcTRKdmgu7@GSRRvMMokjuJ9UtemPdMN/mpKwyjaBe6UnuMdZPEWmFzh4/N6RdbEkGU@BbyYksYCZaAzmTOQnrf6s3plZhW2Dxr8CxzEV2uTdYdAhZfqOEZkQtb@NmVoQvM/ "C (gcc) – Try It Online")
Idea stolen from [Felipe Nardi Batista's Python answer](https://codegolf.stackexchange.com/a/141659/9296).
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~48~~ 42 bytes
Direct port from my python answer. Takes input as a byte-string with lowercase letters as: b'aa11111'.
This is my first time coding in Pyth, so any tips are welcome :D
```
KJ=b0VQ=d&KqK-NJ=+b+qNJ*dZ=Z-3yd=K-NJ=JN;b
```
[Try it here](https://pyth.herokuapp.com/?code=KJ%3Db0VQ%3Dd%26KqK-NJ%3D%2Bb%2BqNJ*dZ%3DZ-3yd%3DK-NJ%3DJN%3Bb&input=b%27aa11111%27&debug=0)
[Answer]
# JavaScript, ~~216~~ ~~192~~ ~~186~~ ~~202~~ 201 bytes
```
function f(s){var a=s.split(" "),c=a[1],a=a[0],r,h=b=i=p=0;for(i=0;i<4;i++){if(i<2&(r=a[i+1]-a[i]==a[i+2]-a[i+1])){p++;b=2}if(i>0){if(a[i]==a[i-1]){p++;h++}if(i<3&c[i]==c[i-1])p++}}return h==4?p+b:p-b}
```
### Unminified
```
function f(s){
var a=s.split(" "),c=a[1],a=a[0],r,h=b=i=p=0;
for(i=0;i<4;i++){
if(i<2&(r=a[i+1]-a[i]==a[i+2]-a[i+1])){
p++;
b=2
}
if(i>0){
if(a[i]==a[i-1]){
p++;
h++;
}
if(i<3&c[i]==c[i-1])
p++;
}
}
return h==4?p+b:p-b
}
```
Edit history:
* Narrowed down the code to only work with `0000 XXX` format. (-24 bytes)
* Edits as suggested by @Titus. (-6 bytes)
* fixed a bug where four identical numbers gave a score of 7 instead of 3. (+16 bytes)
* Removed last semi-colon. (-1 byte)
* Fixed a typo in the code. (no byte change)
] |
[Question]
[
*In the spirit of [Patch the Image](https://codegolf.stackexchange.com/q/70483/42963), here's a similar challenge but with text.*
## Challenge
Bit rot has afflicted your precious text! Given a paragraph composed of ASCII characters, with a rectangular hole somewhere in it, your program should try to fill in the hole with appropriate text, so that the paragraph blends as best as possible.
## Further definitions
* The hole will always be rectangular, and it may span multiple lines.
* There will only ever be one hole.
* Note that the hole does not necessarily fall on word boundaries (in fact, it usually won't).
* The hole will be at most 25% of the input paragraph, but may overlap or extend past the "end" of the "normal" text (see the Euclid or Badger examples below).
* Since finding the hole is not the main point of this challenge, it will be composed solely of hash marks `#` to allow for easy identification.
* No other location in the input paragraph will have a hash mark.
* Your code cannot use the "normal" text in the examples below - it will only receive and process the text with the hole in it.
* The input can be as a single multi-line string, as an array of strings (one element per line), as a file, etc. -- your choice of what is most convenient for your language.
* If desired, an optional additional input detailing the coordinates of the hole can be taken (e.g., a tuple of coordinates or the like).
* Please describe your algorithm in your submission.
## Voting
Voters are asked to judge the entries based on how well the algorithm fills in the text hole. Some suggestions include the following:
* Does the filled in area match the approximate distribution of spaces and punctuation as the rest of the paragraph?
* Does the filled in area introduce faulty syntax? (e.g., two spaces in a row, a period followed by a question mark, an erroneous sequence like `, ,`, etc.)
* If you squint your eyes (so you're not actually reading the text), can you see where the hole used to be?
* If there aren't any CamelCase words outside the hole, does the hole contain any? If there aren't any Capitalized Letters outside the hole, does the hole contain any? If There Are A Lot Of Capitalized Letters Outside The Hole, does the hole contain a proportionate amount?
## Validity Criterion
In order for a submission to be considered valid, it must not alter any text of the paragraph outside of the hole (including trailing spaces). A single trailing newline at the very end is optional.
## Test Cases
Format is original paragraph in a code block, followed by the same paragraph with a hole. The paragraphs with the hole will be used for input.
1 (Patch the Image)
```
In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, based on the information outside of that patch. And it does a
quite good job, considering it is just a program. As a human, you can sometimes
see that something is wrong, but if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, #############information outside of that patch. And it does a
quite good job, co#############is just a program. As a human, you can sometimes
see that something#############t if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
```
2 (Gettysburg Address)
```
But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here have thus far so nobly advanced. It
is rather for us to be here dedicated to the great task remaining before us-
that from these honored dead we take increased devotion to that cause for which
they gave the last full measure of devotion-that we here highly resolve that
these dead shall not have died in vain-that this nation, under God, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.
But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h######################advanced. It
is rather for us to be here dedicated to the######################before us-
that from these honored dead we take increas######################use for which
they gave the last full measure of devotion-######################solve that
these dead shall not have died in vain-that ######################, shall have
a new birth of freedom-and that government of the people, by the people, for
the people, shall not perish from the earth.
```
3 (Lorem Ipsum)
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo conse################irure dolor in reprehenderit
in voluptate velit esse cil################giat nulla pariatur. Excepteur
sint occaecat cupidatat non################in culpa qui officia deserunt
mollit anim id est laborum.
```
4 (Jabberwocky)
```
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
'Twas brillig, and the slithy toves
Did gyre a######### in the wabe;
All mimsy #########borogoves,
And the mome raths outgrabe.
```
5 (Euclid's proof of the Pythagorean Theorem)
```
1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are collinear. Similarly for B, A, and H.
6.Angles CBD and FBA are both right angles; therefore angle ABD
equals angle FBC, since both are the sum of a right angle and angle ABC.
7.Since AB is equal to FB and BD is equal to BC, triangle ABD
must be congruent to triangle FBC.
8.Since A-K-L is a straight line, parallel to BD, then rectangle
BDLK has twice the area of triangle ABD because they share the base
BD and have the same altitude BK, i.e., a line normal to their common
base, connecting the parallel lines BD and AL. (lemma 2)
9.Since C is collinear with A and G, square BAGF must be twice in area
to triangle FBC.
10.Therefore, rectangle BDLK must have the same area as square BAGF = AB^2.
11.Similarly, it can be shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.
1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are #############milarly for B, A, and H.
6.Angles C#############e both right angles; therefore angle ABD
equals ang############# both are the sum of a right angle and angle ABC.
7.Since AB#############FB and BD is equal to BC, triangle ABD
must be co#############iangle FBC.
8.Since A-#############ight line, parallel to BD, then rectangle
BDLK has t############# of triangle ABD because they share the base
BD and hav#############titude BK, i.e., a line normal to their common
base, conn#############rallel lines BD and AL. (lemma 2)
9.Since C #############with A and G, square BAGF must be twice in area
to triangl#############
10.Therefo############# BDLK must have the same area as square BAGF = AB^2.
11.Similar############# shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.
```
6 (Badger, Badger, Badger by weebl)
```
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger##################badger, badger,
badger##################badger, badger
Mushro##################
Badger##################badger, badger,
badger##################badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
```
[Answer]
# Python 2
I know that [@atlasologist](https://codegolf.stackexchange.com/users/29961/atlasologist) already posted a solution in Python 2, but the way my works is a bit different. This works by going through all holes, from top to bottom, left to right, looking 5 characters back and at the character above, and finding a character where these matches. If multiple characters are found, it picks the most common one. In case there are no characters found, it removes the above-character restriction. If there are still no characters found, it decreases the amount of characters it looks back, and repeats.
```
def fix(paragraph, holeChar = "#"):
lines = paragraph.split("\n")
maxLineWidth = max(map(len, lines))
lines = [list(line + " " * (maxLineWidth - len(line))) for line in lines]
holes = filter(lambda pos: lines[pos[0]][pos[1]] == holeChar, [[y, x] for x in range(maxLineWidth) for y in range(len(lines))])
n = 0
for hole in holes:
for i in range(min(hole[1], 5), 0, -1):
currCh = lines[hole[0]][hole[1]]
over = lines[hole[0] - 1][hole[1]]
left = lines[hole[0]][hole[1] - i : hole[1]]
same = []
almost = []
for y, line in enumerate(lines):
for x, ch in enumerate(line):
if ch == holeChar:
continue
if ch == left[-1] == " ":
continue
chOver = lines[y - 1][x]
chLeft = lines[y][x - i : x]
if chOver == over and chLeft == left:
same.append(ch)
if chLeft == left:
almost.append(ch)
sortFunc = lambda x, lst: lst.count(x) / (paragraph.count(x) + 10) + lst.count(x)
if same:
newCh = sorted(same, key=lambda x: sortFunc(x, same))[-1]
elif almost:
newCh = sorted(almost, key=lambda x: sortFunc(x, almost))[-1]
else:
continue
lines[hole[0]][hole[1]] = newCh
break
return "\n".join(map("".join, lines))
```
Here's the result of Badger, Badger, Badger:
```
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a- b
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
```
Here's the result from the proof:
```
1.Let ACB be a right-angled triangle with right angle CAB.
2.On each of the sides BC, AB, and CA, squares are drawn,
CBDE, BAGF, and ACIH, in that order. The construction of
squares requires the immediately preceding theorems in Euclid,
and depends upon the parallel postulate. [footnote 14]
3.From A, draw a line parallel to BD and CE. It will
perpendicularly intersect BC and DE at K and L, respectively.
4.Join CF and AD, to form the triangles BCF and BDA.
5.Angles CAB and BAG are both right angles; therefore C, A,
and G are the same areamilarly for B, A, and H.
6.Angles CAB and CA, sqe both right angles; therefore angle ABD
equals angle ABD becaus both are the sum of a right angle and angle ABC.
7.Since ABD because theFB and BD is equal to BC, triangle ABD
must be construction ofiangle FBC.
8.Since A-angle ABD becight line, parallel to BD, then rectangle
BDLK has the same area of triangle ABD because they share the base
BD and have the base thtitude BK, i.e., a line normal to their common
base, conngle and G, sqrallel lines BD and AL. (lemma 2)
9.Since C = BD × BK + with A and G, square BAGF must be twice in area
to triangle FBC. (lemma
10.Therefore angle and BDLK must have the same area as square BAGF = AB^2.
11.Similarly for B, A, shown that rectangle CKLE must have the same
area as square ACIH = AC^2.
12.Adding these two results, AB^2 + AC^2 = BD × BK + KL × KC
13.Since BD = KL, BD × BK + KL × KC = BD(BK + KC) = BD × BC
14.Therefore, AB^2 + AC^2 = BC^2, since CBDE is a square.
```
And the result of Jabberwocky:
```
'Twas brillig, and the slithy toves
Did gyre and the mo in the wabe;
All mimsy toves, anborogoves,
And the mome raths outgrabe.
```
[Answer]
## Python 2
This is a pretty straight-forward solution. It creates a sample string composed of words that are between average word length `A`-(`A`/2) and `A`+(`A`/2), then it applies leading and trailing space trimmed chunks from the sample to the patch area. It doesn't handle capitalization, and I'm sure there's a curveball test case out there that would break it, but it does okay on the examples. See the link below to run all the tests.
I also put a patch in the code for good measure.
```
def patch(paragraph):
sample = [x.split() for x in paragraph if x.count('#') < 1]
length = max([x.count('#') for x in paragraph if x.find('#')])
s = sum(####################
sample,[####################
]) ####################
avg=sum(####################
len(w) ####################
for w in####################
s)//len(s)
avg_range = range(avg-(avg//2),avg+(avg//2))
sample = filter(lambda x:len(x) in avg_range, s)
height=0
for line in paragraph:
if line.find('#'):height+=1
print line.replace('#'*length,' '.join(sample)[(height-1)*length:height*length].strip())
print '\n'
```
Lorem Ipsum, original then patched:
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo conseore dolore magnairure dolor in reprehenderit
in voluptate velit esse cilenim minim quisgiat nulla pariatur. Excepteur
sint occaecat cupidatat nonnisi mollit aniin culpa qui officia deserunt
mollit anim id est laborum.
```
[Try it](https://repl.it/ChWV)
[Answer]
# Java Shakespeare
Who needs a grasp of standard english conventions? Just make your own! Just like the bard was allowed to make up his own words. This bot doesn't worry to much about correcting the cut off words, he really just inserts random words. The result is some beautiful Poetry. As a bonus feature the bard is of a higher caliber and can handle multiple holes provided they are the same size!
---
Sample Input
```
From fairest creatures we desire increase,
That thereby beauty's rose might never die,
But as the riper should by time decease,
His tender############bear his memory:
But thou c############ thine own bright eyes,
Feed'st th############ame with self-substantial fuel,
Making a famine where abundance lies,
Thy self thy foe, to thy sweet self too cruel:
Thou that art now the world's fresh ornament,
And only herald to the gaudy spring,
Within thine own bud buriest thy content,
And tender churl mak'st was############ding:
Pity the world, or else t############be,
To eat the world's due, b############and thee.
2
When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a tattered weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserved thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse'
Proving his beauty by succession thine.
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.
3
Look in thy glass and tell the face thou viewest,
Now is the time that face should form another,
Whose fresh repair if now thou not renewest,
Thou dost beguile the world, unbless some mother.
For where is she so fair whose uneared womb
Disdains the tillage of thy husbandry?
Or who is he so fond will be the tomb,
Of his self-love to stop posterity?
Thou art thy mother's glass and she in thee
Calls back the lovely April of her prime,
So thou through windows of thine age shalt see,
Despite of ############s thy golden time.
But if th############mbered not to be,
Die singl############image dies with thee.
```
Beautiful output
```
From fairest creatures we desire increase,
That thereby beauty's rose might never die,
But as the riper should by time decease,
His tender should of bear his memory:
But thou c all mbered thine own bright eyes,
Feed'st th Proving Or ame with self-substantial fuel,
Making a famine where abundance lies,
Thy self thy foe, to thy sweet self too cruel:
Thou that art now the world's fresh ornament,
And only herald to the gaudy spring,
Within thine own bud buriest thy content,
And tender churl mak'st was he Thou my ding:
Pity the world, or else t So the the be,
To eat the world's due, b t thine so and thee.
2
When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a tattered weed of small worth held:
Then being asked, where all thy beauty lies,
Where all the treasure of thy lusty days;
To say within thine own deep sunken eyes,
Were an all-eating shame, and thriftless praise.
How much more praise deserved thy beauty's use,
If thou couldst answer 'This fair child of mine
Shall sum my count, and make my old excuse'
Proving his beauty by succession thine.
This were to be new made when thou art old,
And see thy blood warm when thou feel'st it cold.
3
Look in thy glass and tell the face thou viewest,
Now is the time that face should form another,
Whose fresh repair if now thou not renewest,
Thou dost beguile the world, unbless some mother.
For where is she so fair whose uneared womb
Disdains the tillage of thy husbandry?
Or who is he so fond will be the tomb,
Of his self-love to stop posterity?
Thou art thy mother's glass and she in thee
Calls back the lovely April of her prime,
So thou through windows of thine age shalt see,
Despite of Look gazed s thy golden time.
But if th When be, mbered not to be,
Die singl repair the image dies with thee.
```
The last couple lines are deeply poetic if I do say so myself.
It performs suprisingly well on the gettysburg address as well.
```
But, in a larger sense, we can not dedicate, we can not consecrate, we can not
hallow this ground. The brave men, living and dead, who struggled here, have
consecrated it, far above our poor power to add or detract. The world will
little note, nor long remember what we say here, but it can never forget what
they did here. It is for us the living, rather, to be dedicated here to the
unfinished work which they who fought here h to of rather us of advanced. It
is rather for us to be here dedicated to the who be it, vain who before us
that from these honored dead we take increas be dead the the what use for which
they gave the last full measure of devotion dead government The solve that
these dead shall not have died in vain that the take nor world , shall have
a new birth of freedom and that government of the people, by the people, for
the people, shall not perish from the earth.
```
---
Lets see what makes Shakespeare tick. Here is the code. Essentially he strives to build a vocabulary base from the input. He then uses these words and randomly places them in the hole (ensuring that it fits nicely). He is deterministic as he uses a fixed seed for randomness.
```
package stuff;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
/**
*
* @author rohan
*/
public class PatchTheParagraph {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("File Name :");
String[] text = getWordsFromFile(in.nextLine());
System.out.println("==ORIGINAL==");
for(String s:text){
System.out.println(s);
}
int lengthOfHole= 0;
int rows = 0;
for(String s: text){
s = s.replaceAll("[^#]", "");
// System.out.println(s);
if(s.length()>0){
lengthOfHole = s.length();
rows++;
}
}
ArrayList<String> words = new ArrayList<>();
words.add("I");
for(String s:text){
String[] w = s.replaceAll("#", " ").split(" ");
for(String a :w){
words.add(a);
}
}
Iterator<String> j = words.iterator();
while(j.hasNext()){
String o;
if((o = j.next()).equals("")){
j.remove();
}
}
System.out.println(words);
Stack<String> out = new Stack<>();
String hashRow = "";
for(int i = 0;i<lengthOfHole;i++){
hashRow+="#";
}
for(int i = 0;i<rows;i++){
int length = lengthOfHole-1;
String outPut = " ";
while(length>2){
String wordAttempt = words.get(getRandom(words.size()-1));
while(wordAttempt.length()>length-1){
wordAttempt = words.get(getRandom(words.size()-1));
}
length -= wordAttempt.length()+1;
outPut+=wordAttempt;
outPut+=" ";
}
out.push(outPut);
}
System.out.println("==PATCHED==");
for(String s : text){
if(s.contains(hashRow)){
System.out.println(s.replaceAll(hashRow,out.pop()));
}else{
System.out.println(s);
}
}
}
public static final Random r = new Random(42);
public static int getRandom(int max){
return (int) (max*r.nextDouble());
}
/**
*
* @param fileName is the path to the file or just the name if it is local
* @return the number of lines in fileName
*/
public static int getLengthOfFile(String fileName) {
int length = 0;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
while (sc.hasNextLine()) {
sc.nextLine();
length++;
}
} catch (Exception e) {
System.err.println(e);
}
return length;
}
/**
*
* @param fileName is the path to the file or just the name if it is local
* @return an array of Strings where each string is one line from the file
* fileName.
*/
public static String[] getWordsFromFile(String fileName) {
int lengthOfFile = getLengthOfFile(fileName);
String[] wordBank = new String[lengthOfFile];
int i = 0;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
for (i = 0; i < lengthOfFile; i++) {
wordBank[i] = sc.nextLine();
}
return wordBank;
} catch (Exception e) {
System.err.println(e);
System.exit(55);
}
return null;
}
}
```
---
Most of Shakespeare's poetry is public domain.
[Answer]
## Python 2.7
Another Python solution with a different approach. My program sees the text as a [Markov chain](https://en.wikipedia.org/wiki/Markov_chain), where each letter is followed by another letter with a certain probability. So the first step is to build the table of probabilities. The next step is to apply that probabilities to the patch.
Full code, including one sample text is below. Because one example used unicode characters, I included an explicit codepage (utf-8) for compatibility with that example.
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
import numpy
texts = [
"""'Twas brillig, and the slithy toves
Did gyre a######### in the wabe;
All mimsy #########borogoves,
And the mome raths outgrabe."""
]
class Patcher:
def __init__(self):
self.mapper = defaultdict(lambda: defaultdict(int))
def add_mapping(self, from_value, to_value):
self.mapper[from_value][to_value] += 1
def get_patch(self, from_value):
if from_value in self.mapper:
sum_freq = sum(self.mapper[from_value].values())
return numpy.random.choice(
self.mapper[from_value].keys(),
p = numpy.array(
self.mapper[from_value].values(),dtype=numpy.float64) / sum_freq)
else:
return None
def add_text_mappings(text_string, patcher = Patcher(), ignore_characters = ''):
previous_letter = text_string[0]
for letter in text_string[1:]:
if not letter in ignore_characters:
patcher.add_mapping(previous_letter, letter)
previous_letter = letter
patcher.add_mapping(text_string[-1], '\n')
def patch_text(text_string, patcher, patch_characters = '#'):
result = previous_letter = text_string[0]
for letter in text_string[1:]:
if letter in patch_characters:
result += patcher.get_patch(previous_letter)
else:
result += letter
previous_letter = result[-1]
return result
def main():
for text in texts:
patcher = Patcher()
add_text_mappings(text, patcher, '#')
print patch_text(text, patcher, '#')
print "\n"
if __name__ == '__main__':
main()
```
Sample output for the Lorem Ipsum:
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo conse Exe eut ccadamairure dolor in reprehenderit
in voluptate velit esse cilore indipserexepgiat nulla pariatur. Excepteur
sint occaecat cupidatat non upir alostat adin culpa qui officia deserunt
mollit anim id est laborum.
```
An extra poetic line in the Jabberwocky:
```
'Twas brillig, and the slithy toves
Did gyre and me the in the wabe;
All mimsy was
An inborogoves,
And the mome raths outgrabe.
```
[Answer]
# C# 5 *massive as ever*
I threw this together, it's a bit of a mess, but it produces some OK results some of the time. It a mostly-deterministic algorithm, but with some (fixed-seed) randomness added to avoid it producing the same string for similar gaps. It goes to some effort to try to avoid just having columns of spaces either side of the gaps.
It works by tokenizing the input into words and punctuation (punctuation comes from a manually entered list, because I can't be bothered to work out if Unicode can do this for me), so that it can put spaces before words, and not before punctuation, because this is fairly typical. It splits on typical whitespace. In the vein of markov chains (I think), it counts how often each token follows each other token, and then *doesn't* compute probabilities for this (I figure that because the documents are so tiny, we would do better to bias toward things we see a lot where we can). Then we perform a breadth-first search, filling the space left by the hashes and the 'partial' words either side, with the cost being computed as `-fabness(last, cur) * len(cur_with_space)`, where `fabness` returns the number of times `cur` has followed `last` for each appended token in the generated string. Naturally, we try to minimise the cost. Because we can't always fill the gap with words and punctuation found in the document, it also considers a number of 'special' tokens from certain states, including the partial strings on either side, which we bias against with arbitrarily increased costs.
If the BFS fails to find a solution, then we naively try to pick a random adverb, or just insert spaces to fill the space.
## Results
All 6 can be found here: <https://gist.github.com/anonymous/5277db726d3f9bdd950b173b19fec82a>
The Euclid test-case did not go very well...
Patch the Image
```
In a popular image editing software there is a feature, that patches (The term
used in image processing is inpainting as @minxomat pointed out.) a selected
area of an image, that patches information outside of that patch. And it does a
quite good job, co the patch a is just a program. As a human, you can sometimes
see that something In a short it if you squeeze your eyes or just take a short
glance, the patch seems to fill in the gap quite well.
```
Jabberwocky
```
'Twas brillig, and the slithy toves
Did gyre and the in in the wabe;
All mimsy the mome borogoves,
And the mome raths outgrabe.
```
Badger
```
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, mushroom, a-
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mushroom, badger, badger
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Mush-mushroom, a
Badger, badger, badger, badger, badger,
badger, badger, badger, badger, badger
Argh! Snake, a snake!
Snaaake! A snaaaake, oooh its a snake!
```
\_I'm glad with how this one turned out... it's fortuate that "badger, badger," fits, or this one would not have done so well
## Code
Run it with
```
csc ParaPatch.cs
ParaPatch.exe infile outfile
```
There is quite a lot of it. The only remotely interesting bit is the `Fill` method. I include the heap implementation, because .NET doesn't have one (WHY MS WHY?!).
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace ParaPatch
{
class Program
{
private static string[] Filler = new string[] { "may", "will", "maybe", "rather", "perhaps", "reliably", "nineword?", "definitely", "elevenword?", "inexplicably" }; // adverbs
private static char[] Breaking = new char[] { ' ', '\n', '\r', '\t' };
private static char[] Punctuation = new char[] { ',', '.', '{', '}', '(', ')', '/', '?', ':', ';', '\'', '\\', '"', ',', '!', '-', '+', '[', ']', '£', '$', '%', '^', '—' };
private static IEnumerable<string> TokenizeStream(System.IO.StreamReader reader)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
HashSet<char> breaking = new HashSet<char>(Breaking);
HashSet<char> punctuation = new HashSet<char>(Punctuation);
while (!reader.EndOfStream)
{
int ci = reader.Read();
if (ci == -1) // sanity
break;
char c = (char)ci;
if (breaking.Contains(c))
{
if (sb.Length > 0)
yield return sb.ToString();
sb.Clear();
}
else if (punctuation.Contains(c))
{
if (sb.Length > 0)
yield return sb.ToString();
yield return ""+c;
sb.Clear();
}
else
{
sb.Append(c);
}
}
if (sb.Length > 0)
yield return sb.ToString();
}
private enum DocTokenTypes
{
Known,
LeftPartial,
RightPartial,
Unknown,
}
private class DocToken
{
public DocTokenTypes TokenType { get; private set; }
public string StringPart { get; private set; }
public int Length { get; private set; }
public DocToken(DocTokenTypes tokenType, string stringPart, int length)
{
TokenType = tokenType;
StringPart = stringPart;
Length = length;
}
}
private static IEnumerable<DocToken> DocumentTokens(IEnumerable<string> tokens)
{
foreach (string token in tokens)
{
if (token.Contains("#"))
{
int l = token.IndexOf("#");
int r = token.LastIndexOf("#");
if (l > 0)
yield return new DocToken(DocTokenTypes.LeftPartial, token.Substring(0, l), l);
yield return new DocToken(DocTokenTypes.Unknown, null, r - l + 1);
if (r < token.Length - 1)
yield return new DocToken(DocTokenTypes.RightPartial, token.Substring(r + 1), token.Length - r - 1);
}
else
yield return new DocToken(DocTokenTypes.Known, token, token.Length);
}
}
private class State : IComparable<State>
{
// missing readonly params already... maybe C#6 isn't so bad
public int Remaining { get; private set; }
public int Position { get; private set; }
public State Prev { get; private set; }
public string Token { get; private set; }
public double H { get; private set; }
public double Fabness { get; private set; }
public string FullFilling { get; private set; }
public State(int remaining, int position, Program.State prev, double fabness, double h, string token, string toAdd)
{
Remaining = remaining;
Position = position;
Prev = prev;
H = h;
Fabness = fabness;
Token = token;
FullFilling = prev != null ? prev.FullFilling + toAdd : toAdd;
}
public int CompareTo(State other)
{
return H.CompareTo(other.H);
}
}
public static void Main(string[] args)
{
if (args.Length < 2)
args = new string[] { "test.txt", "testout.txt" };
List<DocToken> document;
using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0], System.Text.Encoding.UTF8))
{
document = DocumentTokens(TokenizeStream(reader)).ToList();
}
foreach (DocToken cur in document)
{
Console.WriteLine(cur.StringPart + " " + cur.TokenType);
}
// these are small docs, don't bother with more than 1 ply
Dictionary<string, Dictionary<string, int>> FollowCounts = new Dictionary<string, Dictionary<string, int>>();
Dictionary<string, Dictionary<string, int>> PreceedCounts = new Dictionary<string, Dictionary<string, int>>(); // mirror (might be useful)
HashSet<string> knowns = new HashSet<string>(); // useful to have lying around
// build counts
DocToken last = null;
foreach (DocToken cur in document)
{
if (cur.TokenType == DocTokenTypes.Known)
{
knowns.Add(cur.StringPart);
}
if (last != null && last.TokenType == DocTokenTypes.Known && cur.TokenType == DocTokenTypes.Known)
{
{
Dictionary<string, int> ltable;
if (!FollowCounts.TryGetValue(last.StringPart, out ltable))
{
FollowCounts.Add(last.StringPart, ltable = new Dictionary<string, int>());
}
int count;
if (!ltable.TryGetValue(cur.StringPart, out count))
{
count = 0;
}
ltable[cur.StringPart] = count + 1;
}
{
Dictionary<string, int> ctable;
if (!PreceedCounts.TryGetValue(cur.StringPart, out ctable))
{
PreceedCounts.Add(cur.StringPart, ctable = new Dictionary<string, int>());
}
int count;
if (!ctable.TryGetValue(last.StringPart, out count))
{
count = 0;
}
ctable[last.StringPart] = count + 1;
}
}
last = cur;
}
// build probability grid (none of this efficient table filling dynamic programming nonsense, A* all the way!)
// hmm... can't be bothered
Dictionary<string, Dictionary<string, double>> fabTable = new Dictionary<string, Dictionary<string, double>>();
foreach (var k in FollowCounts)
{
Dictionary<string, double> t = new Dictionary<string, double>();
// very naive
foreach (var k2 in k.Value)
{
t.Add(k2.Key, (double)k2.Value);
}
fabTable.Add(k.Key, t);
}
string[] knarr = knowns.ToArray();
Random rnd = new Random("ParaPatch".GetHashCode());
List<string> fillings = new List<string>();
for (int i = 0; i < document.Count; i++)
{
if (document[i].TokenType == DocTokenTypes.Unknown)
{
// shuffle knarr
for (int j = 0; j < knarr.Length; j++)
{
string t = knarr[j];
int o = rnd.Next(knarr.Length);
knarr[j] = knarr[o];
knarr[o] = t;
}
fillings.Add(Fill(document, fabTable, knarr, i));
Console.WriteLine(fillings.Last());
}
}
string filling = string.Join("", fillings);
int fi = 0;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1]))
using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
{
while (!reader.EndOfStream)
{
int ci = reader.Read();
if (ci == -1)
break;
char c = (char)ci;
c = c == '#' ? filling[fi++] : c;
writer.Write(c);
Console.Write(c);
}
}
// using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[1], false, System.Text.Encoding.UTF8))
// using (System.IO.StreamReader reader = new System.IO.StreamReader(args[0]))
// {
// foreach (char cc in reader.ReadToEnd())
// {
// char c = cc;
// c = c == '#' ? filling[fi++] : c;
//
// writer.Write(c);
// Console.Write(c);
// }
// }
if (args[0] == "test.txt")
Console.ReadKey(true);
}
private static string Fill(List<DocToken> document, Dictionary<string, Dictionary<string, double>> fabTable, string[] knowns, int unknownIndex)
{
HashSet<char> breaking = new HashSet<char>(Breaking);
HashSet<char> punctuation = new HashSet<char>(Punctuation);
Heap<State> due = new Heap<Program.State>(knowns.Length);
Func<string, string, double> fabness = (prev, next) =>
{
Dictionary<string, double> table;
if (!fabTable.TryGetValue(prev, out table))
return 0; // not fab
double fab;
if (!table.TryGetValue(next, out fab))
return 0; // not fab
return fab; // yes fab
};
DocToken mostLeft = unknownIndex > 2 ? document[unknownIndex - 2] : null;
DocToken left = unknownIndex > 1 ? document[unknownIndex - 1] : null;
DocToken unknown = document[unknownIndex];
DocToken right = unknownIndex < document.Count - 2 ? document[unknownIndex + 1] : null;
DocToken mostRight = unknownIndex < document.Count - 3 ? document[unknownIndex + 2] : null;
// sum of empty space and partials' lengths
int spaceSize = document[unknownIndex].Length
+ (left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0)
+ (right != null && right.TokenType == DocTokenTypes.RightPartial ? right.Length : 0);
int l = left != null && left.TokenType == DocTokenTypes.LeftPartial ? left.Length : 0;
int r = l + unknown.Length;
string defaultPrev =
left != null && left.TokenType == DocTokenTypes.Known ? left.StringPart :
mostLeft != null && mostLeft.TokenType == DocTokenTypes.Known ? mostLeft.StringPart :
"";
string defaultLast =
right != null && right.TokenType == DocTokenTypes.Known ? right.StringPart :
mostRight != null && mostRight.TokenType == DocTokenTypes.Known ? mostRight.StringPart :
"";
Func<string, string> topAndTail = str =>
{
return str.Substring(l, r - l);
};
Func<State, string, double, bool> tryMove = (State prev, string token, double specialFabness) =>
{
bool isPunctionuation = token.Length == 1 && punctuation.Contains(token[0]);
string addStr = isPunctionuation || prev == null ? token : " " + token;
int addLen = addStr.Length;
int newRemaining = prev != null ? prev.Remaining - addLen : spaceSize - addLen;
int oldPosition = prev != null ? prev.Position : 0;
int newPosition = oldPosition + addLen;
// check length
if (newRemaining < 0)
return false;
// check start
if (oldPosition < l) // implies left is LeftPartial
{
int s = oldPosition;
int e = newPosition > l ? l : newPosition;
int len = e - s;
if (addStr.Substring(0, len) != left.StringPart.Substring(s, len))
return false; // doesn't match LeftPartial
}
// check end
if (newPosition > r) // implies right is RightPartial
{
int s = oldPosition > r ? oldPosition : r;
int e = newPosition;
int len = e - s;
if (addStr.Substring(s - oldPosition, len) != right.StringPart.Substring(s - r, len))
return false; // doesn't match RightPartial
}
if (newRemaining == 0)
{
// could try to do something here (need to change H)
}
string prevToken = prev != null ? prev.Token : defaultPrev;
bool isLastunctionuation = prevToken.Length == 1 && punctuation.Contains(prevToken[0]);
if (isLastunctionuation && isPunctionuation) // I hate this check, it's too aggresive to be realistic
specialFabness -= 50;
double fab = fabness(prevToken, token);
if (fab < 1 && (token == prevToken))
fab = -1; // bias against unrecognised repeats
double newFabness = (prev != null ? prev.Fabness : 0.0)
- specialFabness // ... whatever this is
- fab * addLen; // how probabilistic
double h = newFabness; // no h for now
State newState = new Program.State(newRemaining, newPosition, prev, newFabness, h, token, addStr);
// Console.WriteLine((prev != null ? prev.Fabness : 0) + "\t" + specialFabness);
// Console.WriteLine(newFabness + "\t" + h + "\t" + due.Count + "\t" + fab + "*" + addLen + "\t" + newState.FullFilling);
due.Add(newState);
return true;
};
// just try everything everything
foreach (string t in knowns)
tryMove(null, t, 0);
if (left != null && left.TokenType == DocTokenTypes.LeftPartial)
tryMove(null, left.StringPart, -1);
while (!due.Empty)
{
State next = due.RemoveMin();
if (next.Remaining == 0)
{
// we have a winner!!
return topAndTail(next.FullFilling);
}
// just try everything
foreach (string t in knowns)
tryMove(next, t, 0);
if (right != null && right.TokenType == DocTokenTypes.RightPartial)
tryMove(next, right.StringPart, -5); // big bias
}
// make this a tad less stupid, non?
return Filler.FirstOrDefault(f => f.Length == unknown.Length) ?? new String(' ', unknown.Length); // oh dear...
}
}
//
// Ultilities
//
public class Heap<T> : System.Collections.IEnumerable where T : IComparable<T>
{
// arr is treated as offset by 1, all idxes stored need to be -1'd to get index in arr
private T[] arr;
private int end = 0;
private void s(int idx, T val)
{
arr[idx - 1] = val;
}
private T g(int idx)
{
return arr[idx - 1];
}
public Heap(int isize)
{
if (isize < 1)
throw new ArgumentException("Cannot be less than 1", "isize");
arr = new T[isize];
}
private int up(int idx)
{
return idx / 2;
}
private int downLeft(int idx)
{
return idx * 2;
}
private int downRight(int idx)
{
return idx * 2 + 1;
}
private void swap(int a, int b)
{
T t = g(a);
s(a, g(b));
s(b, t);
}
private void moveUp(int idx, T t)
{
again:
if (idx == 1)
{
s(1, t);
return; // at end
}
int nextUp = up(idx);
T n = g(nextUp);
if (n.CompareTo(t) > 0)
{
s(idx, n);
idx = nextUp;
goto again;
}
else
{
s(idx, t);
}
}
private void moveDown(int idx, T t)
{
again:
int nextLeft = downLeft(idx);
int nextRight = downRight(idx);
if (nextLeft > end)
{
s(idx, t);
return; // at end
}
else if (nextLeft == end)
{ // only need to check left
T l = g(nextLeft);
if (l.CompareTo(t) < 0)
{
s(idx, l);
idx = nextLeft;
goto again;
}
else
{
s(idx, t);
}
}
else
{ // check both
T l = g(nextLeft);
T r = g(nextRight);
if (l.CompareTo(r) < 0)
{ // left smaller (favour going right if we can)
if (l.CompareTo(t) < 0)
{
s(idx, l);
idx = nextLeft;
goto again;
}
else
{
s(idx, t);
}
}
else
{ // right smaller or same
if (r.CompareTo(t) < 0)
{
s(idx, r);
idx = nextRight;
goto again;
}
else
{
s(idx, t);
}
}
}
}
public void Clear()
{
end = 0;
}
public void Trim()
{
if (end == 0)
arr = new T[1]; // don't /ever/ make arr len 0
else
{
T[] narr = new T[end];
for (int i = 0; i < end; i++)
narr[i] = arr[i];
arr = narr;
}
}
private void doubleSize()
{
T[] narr = new T[arr.Length * 2];
for (int i = 0; i < end; i++)
narr[i] = arr[i];
arr = narr;
}
public void Add(T item)
{
if (end == arr.Length)
{
// resize
doubleSize();
}
end++;
moveUp(end, item);
}
public T RemoveMin()
{
if (end < 1)
throw new Exception("No items, mate.");
T min = g(1);
end--;
if (end > 0)
moveDown(1, g(end + 1));
return min;
}
public bool Empty
{
get
{
return end == 0;
}
}
public int Count
{
get
{
return end;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return (IEnumerator<T>)arr.GetEnumerator();
}
}
}
```
] |
[Question]
[
# Sort the Textbooks
School is starting soon (if it hasn't already) and so it's time to get our textbooks in order. You need to sort your books in alphabetical order but that takes too long so you decide to write a program to do it.
### Examples
**Input:**
```
_
| | _
|F| | |
|o|_|P|
|o|B|P|
| |a|C|
| |r|G|
|_|_|_|
```
**Output:**
```
_
| |_
|F| |
_|o|P|
|B|o|P|
|a| |C|
|r| |G|
|_|_|_|
```
---
### Input
The input will be a set of books which need to rearranged alphabetically. It will contain only: `|`, `_`, , and `A-Za-z`. The titles of the books are read vertically, top-bottom.
You may choose to assume the input is padded with whitespace to fit a rectangle. If you choose to have your input padded with whitespace, please specify this in your answer.
The very maximum book height your program will need to handle is 5,120 lines tall without failing.
The books will always be 1-thick and their will always be at least one book in the input
### Output
The output will need to be the same set of books organized in alphabetical order. The height of the books must stay the same and the title must have the same spacing from the top when re-arranged.
Books should be sorted alphabetically. If your language sports a sort function you can use that. Otherwise you can use alphabetical sorting as described [here](https://en.wikipedia.org/wiki/Alphabetical_order).
**Book Title Examples**
```
_
| |
| |
|F|
|o|
|o|
| |
| |
|B|
|a|
|r|
| |
| |
|_|
```
This books title is:
```
"Foo Bar"
```
Book titles will *only* contain letters and spaces.
Trailing whitespace is allowed
---
# Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.
[Answer]
# Python 3, 231 bytes
```
def f(s):
*M,L=sorted(["".join(c).strip()for c in zip(*s.split("\n"))][1::2],key=lambda x:x[1:-1].strip()),;l=m=0
for r in L+[""]:n=len(r);M+="|"*~-max(n,l),r;m=max(n,m);l=n
for r in zip(*[x.rjust(m)for x in M]):print(*r,sep="")
```
Just a quick hack. Zip the books, sort, rezip, taking care of the columns of `|` while we're at it.
Input a multiline string, padded with trailing spaces to a rectangle. The output has one more trailing space on each line than necessary.
## Ungolfed
```
def f(s):
new_cols = []
# Zip columns, removing the spaces above each book
# [1::2] is to skip columns of |s, keeping only the books
books = ["".join(c).strip() for c in zip(*s.split("\n"))][1::2]
# Sort based on title, [1:-1] to remove the top and bottom _s
books.sort(key=lambda x:x[1:-1].strip())
last = 0
max_height = 0
for book in (books + [""]):
height = len(book)
# Append |s as necessary for the left edge of the current book
# The +[""] above is for the right edge of the last book
new_cols.extend(["|"*(max(height, last) - 1), book])
max_height = max(height, max_height)
last = height
# Rezip columns, add back spaces as necessary and print
for col in zip(*[x.rjust(max_height) for x in new_cols]):
print("".join(col))
```
[Answer]
## Ruby (~~209~~ ~~204~~ ~~200~~ 198 bytes)
```
a=n.tr(?|,' ').split$/
i=!p;t=a.map(&:chars).transpose.map(&:join).select{i^=a}.sort_by{|s|s[/[A-Z]/][0]}
x=0;t.map{|t|y=0;u=p;t.chars{|c|u&&a[y][x,3]=?|*3;a[y][x+1]=c;y+=1;u|=c=='_'};x+=2}
a.join$/
```
The `transpose` function in this solution requires that all lines are the same length, hence the input needs to be padded with whitespace.
### Explanation
```
def sort_books(n)
a = n.tr(?|,' ') # pre-emptively remove all the '|'.
.split $/ # and split into an array of lines
# ($/ is the INPUT_RECORD_SEPARATOR, typically "\n")
# we're going to write our answer into `a` later
i = !p # i = true; we'll use this as a flip-flop variable
# Kernel#p returns nil with no args
# we're now going to get a sorted array of book titles (t)
t = a.map(&:chars) # break array into nested array of every character
.transpose # and transpose the entire array
.map(&:join) # this gives us an array of "horizontal" book titles with dividers
.select { i ^= a } # select every second line
# (i.e. just titles without dividers)
# `i` starts off true
# `a` is truish (it's our original array)
# `^=` is the bitwise xor assignment,
# it will alternate true/false on each execution
.sort_by { |s| s[/[A-Z]/][0] } # sort by the first alphabetical char
# use counters for less chars than `each_with_index`
# x and y are cartesian coordinates in the final array
x = 0 # start in the left-hand column
# go through each title
t.map { |t|
y = 0 # each book title starts on the top row
u = p # `u` is "have we reached the book's spine yet?" (or are we above it?)
# `u` starts off false and we'll set it true when we see the first '_'
# after which we'll start writing the book's edges
# go through each character of each title, including leading spaces and '_'s
# this will "descend" down the array writing each letter of the title
# along with the "edges"
t.chars { |c|
u && # if we're on the spine
a[y][x,3] = ?|*3; # write ||| in the next 3 columns
# the middle | will be overwriten by the title char
a[y][x+1] = c; # write the current title char into the second (x+1) column
y+=1; # descend to the next row
u |= c == '_' # Since '_' is the top and bottom of the book,
# this toggles whether we're on the spine
}
x += 2 # jump to the right 2 columns and start on the next title
}
a.join $/ # hopefully this is obvious
end
```
[Answer]
# CJam, 60 bytes
```
qN/:Kz1>2%{_{" _"-}#>}$_{_'_#>,}%2,\*2ew{:e>('|*K,Se[}%.\zN*
```
I tried porting my Python answer, which is also similar to [@RetoKoradi's approach](https://codegolf.stackexchange.com/a/54307/21487).
[Try it online](http://cjam.aditsu.net/#code=qN%2F%3AKz1%3E2%25%7B_%7B%22%20_%22-%7D%23%3E%7D%24_%7B_%27_%23%3E%2C%7D%252%2C%5C*2ew%7B%3Ae%3E%28%27%7C*K%2CSe%5B%7D%25.%5CzN*&input=%20%20%20%20%20%20%20%20%20_%20_%20%0A%20%20%20%20%20%20%20%20%7C%20%7C%20%7C%0A%20%20%20_%20%20%20%20%7CA%7C%20%7C%0A%20%20%7C%20%7C_%20_%7CB%7C%20%7C%0A%20_%7C%20%7CB%7C%20%7CC%7C%20%7C%0A%7C%20%7CB%7Cc%7CB%7CD%7C%20%7C%0A%7CC%7C%20%7C%20%7Cb%7C%20%7CD%7C%0A%7C_%7C_%7C_%7C_%7C_%7C_%7C). The input should be padded with spaces to form a rectangle.
[Answer]
# Python 2 - 399 bytes
Expects the input to not have a trailing newline.
```
import sys;a=str.strip;L=list(sys.stdin);b=len(L[-1])/2;s=['']*b
for l in L:
i=0
for c in l[1:-1:2]:s[i]+=c;i+=1
s=sorted([a(a(x),'_')for x in s],key=a);y=map(len,s);m=[y[0]]+[max(y[i],y[i+1])for i in range(b-1)]
for i in range(max(y)+1):
h=max(y)-i;l='';j=0
for x in s:l+='|'if h<m[j]else' ';l+='_' if h==len(x)else' 'if h>len(x)else x[-h-1];j+=1
print l+('|'if h<y[-1]else' ')
print'|_'*b+'|'
```
[Answer]
# CJam, ~~75~~ ~~66~~ 65 bytes
```
qN/z(;2%{_{" _"#W=}#>}$es:P;_W>+{_'_#_Pe<)S*2$,'|*.e<@@:P;}%);zN*
```
This expects input padded with spaces to form a rectangle.
[Try it online](http://cjam.aditsu.net/#code=qN%2Fz(%3B2%25%7B_%7B%22%20_%22%23W%3D%7D%23%3E%7D%24es%3AP%3B_W%3E%2B%7B_'_%23_Pe%3C)S*2%24%2C'%7C*.e%3C%40%40%3AP%3B%7D%25)%3BzN*&input=%20_%20%20%20%20%20%0A%7C%20%7C%20%20_%20%0A%7CF%7C%20%7C%20%7C%0A%7Co%7C_%7CP%7C%0A%7Co%7CB%7CP%7C%0A%7C%20%7Ca%7CC%7C%0A%7C%20%7Cr%7CG%7C%0A%7C_%7C_%7C_%7C)
Thanks to @Sp3000 and @Dennis for suggestions on string trimming on chat, as well as clueing me in that the `$` operator can take a block as an argument.
I'm still not entirely happy with the second loop. But after trying a few other options without better success, I'm getting tired.
Explanation:
```
qN/ Read input and split at newlines.
z Transpose to turn columns into lines.
(; Drop first line...
2% ... and every second line after that, to keep only lines with titles.
{ Start block that maps lines for sort.
_ Copy.
{ Start block for matching first title letter.
" _"# Search for character in " _".
W= True if not found.
}# End match block. This gets position of first character not in " _".
> Trim leading spaces and '_.
}$ End of sort block. Lines are now sorted alphabetically by title.
es:P; Store large number in P. P holds previous position of '_ in following loop.
_W>+ Repeat last title line, so that final separator line is generated.
{ Loop over title lines.
_'_# Find position of '_.
_ Copy position. Will store it in P after the minimum has been determined.
P Get position of '_ in previous line.
e<) Take the smaller of the two '_ positions, and decrement.
S* Generate leading spaces from the count.
2$, Get length of title line.
'|* Generate full line length sequence of '|.
.e< Overlap spaces with '| to give the final separator.
@@ Get '_ position to top, and stack in order for next loop iteration.
:P; Store '_ position in P.
}% End of loop over lines.
); Remove last line, which was a repeat.
z Transpose to turn lines into columns again.
N* Join with newline characters.
```
[Answer]
# Scala ~~359~~ 341 bytes
expects all lines to be of the same length (i.e. padded with spaces)
```
(s:String)=>{def f(s:String)=(" "/:s)((r,c)=>if(r.last=='|'||c=='_')r+"|"else r+" ").init;val h=s.lines.toSeq.transpose.collect{case s if s.exists(_.isLetter)=>s.mkString}.sortBy(_.filter(!_.isWhitespace));((Seq(f(h(0)))/:h.sliding(2))((s,l)=>s:+l(0):+f(l.minBy(_.indexOf('_')))):+h.last:+f(h.last)).transpose.map(_.mkString).mkString("\n")}
```
ungolfed & commented:
```
//anonymous method that takes the books ascii-art string
(s: String) => {
//method to convert the middle to a border
def f(s: String) =
//fold (starting from non empty string since we use `.last`)
(" "/:s)((r,c) =>
if(r.last=='|'||c=='_')r+"|"
else r+" "
).init.tail
//h is a sequence of strings of the middle of the books
val h =
//transpose lines of input string, and take only the lines the contains letters (middle of the books)
s.lines.toSeq.transpose.collect{
case s if s.exists(_.isLetter) =>
s.mkString
}.sortBy(_.filter(!_.isWhitespace)) //sort the books by title (actually by "_$title" since we filter out just whitspaces)
//fold over pairs of books and add the last manually
(
(Seq(f(h(0)))/:h.sliding(2))((s,l) =>
s :+ l(0) :+ f(l.minBy(_.indexOf('_'))) //convert higher book to border and append to folded accumulator
) :+ h.last :+ f(h.last) //add last book manually
).transpose.map(_.mkString).mkString("\n") //transpose back and construct the output string
}
```
] |
[Question]
[
**Closed**. This question is [opinion-based](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it can be answered with facts and citations by [editing this post](/posts/2070/edit).
Closed 7 years ago.
[Improve this question](/posts/2070/edit)
What are some tips for choosing the right language to golf?
What factors affect the language to be chosen?
Here are some example problem types:
* Problems that require *I/O* solution, either console or file
* Problems that require *parsing*
* Problems that requires you to write your solution as a *function definition*
* Math problems
* Problem dealing with prime numbers
* Solving number puzzles
* Performing numerical methods
* String processing
* Array processing
* Tricky 2D array problems
* Computational geometry
* Recursion
* 2D graphics
* 3D graphics
* Audio
* Networking / web
* Parallel processing
Don't simply say things like "Use GolfScript|J" because you like them.
[Answer]
Putting my two cents in on *array programming languages*, **J** and **APL** in particular.
K/Kona, Q, and Nial fall in this category too, but they generally have the same benefits and criticisms. Use discretion. I will use J examples below, mostly because these are ASCII and thus easy to type--remember than APL characters count as single bytes, so don't let that be your problem with the language as choice for golfing.
* Math problems
* Solving number puzzles
* Performing numerical methods
* Tricky 2D array problems
These two are very good math and data-manipulation languages, because they toss arrays around a high level, and a lot of looping is done *implicitly*, by saying, e.g. add ten to each of 3, 4, and 5 (`10 + 3 4 5`) or sum each row of an array (`+/"1 arr`--the looping is in the `"1`).
* Problem dealing with prime numbers
With prime number problems in particular, J has fast and short builtin primitives, as do some dialects of APL. (Edit: I'm thinking of Nars2000, which is part dialect and part completely different implementation. APL has no builtin for primes.) N-th prime (`p:`), no. of primes up to (`_1&p:`), factoring (`q:`), GCD and LCM (`+.` and `*.`), and so on, there's a lot there. However, in practice, the question will often specify that you have to cook your own prime implementations, so these don't see too much use. There are still neat and fancy ways of getting the prime stuff you need, it just becomes a little less cut-and-paste.
* String processing
* Array processing
Array and string processing is a bit of a mixed bag: if it's something that APL/J is good at or has a primitive or common idiom for, it's nearly trivial; if it's something that's very sequential and not very parallelizable, you're going to have a bad time. Anything in between is up in the air, though usually they will respond favourably.
* Problems that require I/O solution, either console or file
* Problems that requires you to write your solution as a function definition
IO is weird. APL has a single-character input expression, but with J you have to spend at least 8 to read in a number: `".1!:1]1`. Output is a little less verbose, but you're still looking at 6 or 7 characters wasted, in practice. J in particular really likes it a lot if you can take in the input as arguments to a function, instead of having to muck around with IO itself.
In practice, with J and APL, usually the solution is written as a function that you invoke at the console. With APL, you can basically just put in variable names for your arguments and wrap the expression you were working with in curly braces and call it a day.
But with J, there's a bit of an overhead for defining functions explicitly--`3 :'...'`, and you have to escape any strings inside--so what is usually done is something called tacit programming: you program at the function level, combining primitives in a manner not unlike that of Haskell. This can be both a blessing and a curse, because you don't have to spend as many characters referring to your arguments, but it's easy to drown in parentheses and end up losing tens of characters trying to hack your otherwise short and clever solution into something that works.
* Problems that require parsing
* Computational geometry
I don't have experience with golfing these particular problems, but I will say this: in the end, array programming languages are very good at piping and transforming lots of data in the same way. If you can turn the problem into an exercise in number shuffling, you can make it an APL/J problem, no sweat.
That said, not everything is an APL/J problem. Unlike Golfscript, APL and J just happened to be good for golfing, alongside their other benefits ;)
[Answer]
Why hasn't Perl been praised yet? It's an excellent golfing language, for nearly every one of these, especially string related stuff (regex).
Burlesque is good for number-related programs, while Ruby is great for simpler text manipulation.
There's actually a list of languages and golfing scores over [here](http://golf.shinh.org/lranking.rb).
[Answer]
I like using obscure programming languages to (try to) get the job done.
Here are my favorites for the details you listed:
**Problems that require I/O solution, either console or file**
Languages like *TI-Basic* work well, but I prefer *Ruby* because of `puts`
**Problems that require parsing**
*GolfScript* will definitely aid you here
**Problems that requires you to write your solution as a function definition**
*TI-84 Table* - allows functions as `Y=` e.g. `Y=|X|` returns the absolute value of X
**Math problems**
*TI-Basic* - made for a calculator, so it includes math ;)
**Problem dealing with prime numbers**
Nothing special; *Mathematica* is probably the right tool for the job
**Solving number puzzles**
*TI-Basic* as it automatically loops through arrays
**Performing numerical methods**
*TI-Basic* or *Mathematica*
**String processing**
*Python* - has some great string functions.
No matter how good you think *TI-Basic* is, **don't use it** for strings...
**Array processing**
*TI-Basic* - **automatically loops through arrays**; e.g. increment all values in the array - `L1+1→L1`
*Ruby* - also has very powerful array features, and of course the `!` will help compress code also
**Tricky 2D array problems**
*Ruby* or *Python* works best here, as *TI-Basic* doesn't support 2D arrays
**Computational geometry**
*TI-Basic* has geometric features and can be used for most math up to Calculus and Linear Algebra
---
***BONUS***
**Looping**
Either [*Arduino*](http://www.arduino.cc/ "Arduino") or [*Quomplex*](http://timtechsoftware.com/?page_id=1264 "Quomplex"). *Arduino* has a built-in `void loop(){}` and *Quomplex* has the infinite loops contained by brackets (`[]`)
**Drawing/GUI**
[*Game Maker Language*](http://yoyogames.com/ "YoYo Games") has **very** powerful drawing features, and *TI-Basic* is also a generally useful tool because of the support for drawing on the graph.
**Quines**
Either *HQ9+* or *Quomplex* because *HQ9+* has the `Q` to output the program's source code and *Quomplex* will automatically print out its source code unless `*` (output) is specified or it produces no output, defined with `#`
[Answer]
If you're solving a math problem and you don't have Mathematica, try [Sage](http://www.sagemath.org/). It is based on Python, so if you already know Python you don't need much time to learn its syntax.
Examples:
* [Solving a system of linear equations](https://codegolf.stackexchange.com/a/22574/12205)
* [Primes](https://codegolf.stackexchange.com/a/22961/12205)
* [Base conversions](https://codegolf.stackexchange.com/a/22454/12205)
* [Drawing Platonic solids](https://codegolf.stackexchange.com/a/22764/12205)
It is also useful for graph plotting and equation solving (e.g. you can use the `solve()` function in Sage, or if that is forbidden by the rules, it allows an easy implementation of the Newton Raphson process because it has the `diff()` function that can perform symbolic differentiation).
Besides, if you are a Python2 programmer, using Sage may allow you to cheat by skipping the long `import` statements. For example, `math` and `sys` are already imported by default. (Note that this may not work if your Python2 program depends on integer division.)
[Answer]
I know three languages - Java, C++, and Python 3. I know none of these at a high level, but this is my experience with them.
## Java:
I would never use Java for golfing again. It takes over 80 characters just to write `Hello World!`. However, it does have its strengths:
>
> Input requires creation of a `Scanner` object. It is difficult to input a single character. It requires specification of what types you are inputting.
>
> Parsing is simple enough because of the `for` loop. The enhanced `for` loop is excellent for this.
>
> Java supports methods, but the method declaration is quite long.
>
> Java is excellent at math, as well as all other high-level languages.
>
> Java is difficult to use when the problem involves modifying strings. You cannot make modifications to an existing string.
>
> Java's arrays are simple to use.
>
> Java is good at recursion.
>
> Java includes built-in graphics. They are very easy to use.
>
>
>
## C++
C++ is a very strong language, but it is somewhat lengthily when trying to golf at 56 characters for `Hello world!`.
>
> Input and output are easy. You need not specify what types you are inputting - that is done automatically. However, you must include the iostream library.
>
> Parsing is very easy.
>
> Function declaration is simple, but eats a lot of important characters.
> C++ excels at math, but it does not include PI or E, as Java does.
>
> C++'s strings are easy to use and change as needed.
>
> I use `vector`s where possible instead of `array`s, but both are easy to use.
>
> C++ is good at recursion.
>
> C++ does not include built-in graphics.
>
>
>
## Python 3
Python 3 is similar to C++ and Java. It is much shorter as it is not strongly-typed - in other words, it just guesses at what the variables are.
>
> Input is easy, but everything is input as strings. You must manually convert all input to whatever values you want.
>
> Parsing and looping is very simple.
>
> Python function declarations are quite simple and short.
>
> Python is good at math.
>
> Python's strings are simple to use.
>
> Arrays are simple to use.
>
> Python is good at recursion.
>
> Python does not include built-in graphics.
>
>
>
[Answer]
Depends on what one needs, C/C++ is fast, but you have to code more of the work yourself.
Python and Ruby are slower but are a lot easier to code with built in methods that shortens a lot of work and they automatically handle infinitely large values (if one has the RAM).
Using a functional language like Haskell is great for purely mathematical functional use if one can frame the problem that way.
] |
[Question]
[
My parents-in-law have a fishpond in their yard, filled with koi. It didn't really cross my mind until I noticed the following extract from my code.
`',') & '_'`
... I had fish-faces looking back at me from my screen...
Which has given me a great idea...
My quest for you, my dear golfers is to create a one-line ASCII aquarium, with the following rules:
* The size of the aquarium from side of the tank to the other side of the tank should be no smaller than 60 characters and no bigger than 80 characters. Sides of the tank need to be indicated using the pipe/bar (`|`) character.
* Fish must be able to "swim" left to right between the sides of the tank. As they will be turning, a front view is required for the transition from one direction to the other.
* The fish must look like the following:
+ `}}< }} ',')` Fish swimming right
+ `(',' {{ >{{` Fish swimming left
+ `}}('_'){{` Fish facing the front
* When a fish turns to change direction (30% chance), it must start from one direction, face the front, then face the other direction... Make sure there is ample room for the fish to turn, i.e. requires six spaces before the edge of the tank minimum...
* Unless a fish is blowing a bubble or changing direction, it will continue in the direction it is facing, if it gets within six spaces of the side of the tank, it will change direction.
* The fish (facing left or right) can on occasion (10% chance) stop to blow bubbles in succession (`.oO*`), so the fish is required to have a space available next to them in order for the bubble to exist, so a fish can only swim as close to the sides, save one space. The bubble must disappear before the fish can move on...
A series of example lines of the fish's behavior, with `-` characters indicating the spaces, as the code display feature on here is a little strict... I will expect these dashes to be replaced with spaces when you code this...
Each line here could be considered a frame in time-lapse.
```
|-}}< }} ',')----------|
|--}}< }} ',')---------|
|---}}< }} ',')--------|
|----}}< }} ',')-------|
|-----}}< }} ',')------|
|-----}}< }} ',').-----|
|-----}}< }} ',')o-----|
|-----}}< }} ',')O-----|
|-----}}< }} ',')*-----|
|---------}}('_'){{----|
|-----------(',' {{ >{{|
|----------(',' {{ >{{-|
|---------(',' {{ >{{--|
|--------.(',' {{ >{{--|
|--------o(',' {{ >{{--|
|--------O(',' {{ >{{--|
|--------*(',' {{ >{{--|
|--------(',' {{ >{{---|
|-------(',' {{ >{{----|
|------(',' {{ >{{-----|
```
etc. The above example is, as I said, small, but you get the general idea...
Shortest code wins...
I am expecting the output on the same line (if possible), if not, displaying frame after frame in succession is fine... Whether you go one line or multiple lines is up to you. If you are doing multiple lines, they must be separated by a newline.
Also a timer is imposed between frames, 2000ms . This is **mandatory**.
Let's see what you've got!
[Answer]
# Python 3 (278)
Previously: 334, 332, 325, 302, 300, 299, 291, 286, 284, 281
```
import random,time
r=random.random
F="}}('_'){{%s","}}< }} ',')%s","%s(',' {{ >{{"
p,d=9,1
c=b=0
while 1:
if c:p-=c+c*3*(2*d+c==1);d=c-c*d*d;c-=d
elif b%5:b+=1
elif.3>r()or{p*d}<{-5,53}:c=-d
elif.1>r():b=1
else:p+=d
print('|%-70s|'%(' '*p+F[d])%' .oO*'[b%5]);time.sleep(2)
```
Golfing in Python is always difficult due to the indentation requirements of statements, but despite that, this went incredibly well!
Big thanks to Volatility and DSM for helping me golf this so much further.
### Clean version
```
from random import random as r
from time import sleep as s
F = { 1: "}}< }} ',')%s", 0: "}}('_'){{%s", -1: "%s(',' {{ >{{" }
# p: position (from left)
# d: direction (-1: left, +1: right)
# c: changing direction (0: not changing, +1: to right, -1: to left)
# b: bubble (0)
p, d, c, b = 9, 1, 0, 0
while 1:
if c:
p -= c*[1,4][2*d+c==1]
if d:
d = 0
else:
d, c = c, 0
elif b % 5:
b += 1
else:
# change direction
if r() < .3 or p * d in (-5,53):
c = -d
# start bubbling
elif r() < .1:
b = 1
# move forward
else:
p += d
# print fish and sleep
print('|{:<70}|'.format(' '*p+(F[d]%' .oO*'[b%5])))
s(2)
```
[Answer]
# Ruby, ~~291~~ 289
```
l="(',' {{ >{{";m=" }}('_'){{ ";r="}}< }} ',')";w=?\s;s=w*6;q="|#{r+s*9}|"
f=->*s{(puts q;sleep 2)if q.sub! *s}
loop{rand>0.1||(f[") ",")."]||f[" (",".("];f[?.,?o];f[?o,?O];f[?O,?*];f[?*,w])
q[7]==?(||q[-8]==?)||rand<0.3?f[s+l,m]&&f[m,r+s]||f[r+s,m]&&f[m,s+l]:f[w+l,l+w]||f[r+w,w+r]}
```
The fish is eleven characters long, making the aquarium 6\*9+11+2 = 67 characters wide, which fits neatly in the required tolerance.
The `f` lambda function does all the heavy lifting: it accepts a substitution as a pair of arguments, then attempts to apply the substitution on the aquarium. If it succeeds, it paints one frame of the animation. It then reports the success value as `2` (the delay taken) or `nil` (delay not executed).
Fish will not blow bubbles twice in succession. (Fix: `...while rand>0.1` - 4 characers)
Fish may blow bubbles even before a forced turn. (Fix: rearrange the branching structure)
There is a frame where the bubble is completely gone (including the `*`) but the fish has not moved into the resulting void. This follows the letter, but not the example. (Fix: replace `f[?*,w]` with `q[?*]=w` - free)
Does not clear the console. Fix: add ``clear`` (Unix) or `system 'cls'` (Windows console) before `puts q` to fix ([Ref.](https://stackoverflow.com/questions/116593/how-do-you-clear-the-irb-console)) or use `print` instead of `puts` and prepend `\r` to the aquarium ([suggested by @manatwork](https://codegolf.stackexchange.com/questions/18599/one-line-aquarium/18609?noredirect=1#comment36204_18609)).
**Readable version:**
```
# l - left fish; m - middle fish + space; r - right fish
# w - single space character; s - six spaces; q - the aquarium
l="(',' {{ >{{"; m=" }}('_'){{ "; r="}}< }} ',')";
w=" "; s=w*6; q="|#{r+s*9}|"
f = ->k,v do
if q.sub! k,v
puts q
sleep 2
return 2
else
return nil
end
end
loop do
if rand < 0.1
f[") ",")."] || f[" (",".("]
f[?.,?o]; f[?o,?O]; f[?O,?*]; f[?*,' ']
end
if q[7] == "(" || q[-8] == ")" || rand < 0.3
(f[s+l,m] && f[m,r+s]) || (f[r+s,m] && f[m,s+l])
else
f[w+l,l+w] || f[r+w,w+r]
end
end
```
[Answer]
### R, 451 characters
A first attempt:
```
f=function(j,p){cat("\r|",rep("-",j),p,rep("-",50-j),"|",sep="");Sys.sleep(2)};d=F;j=5;P=c("--}}(\'_\'){{--","-}}< }} \',\')-","-(\',\' {{ >{{-");B=c("-",".","o","O","*","-");g=Vectorize(gsub,v="replacement");b=list(g("-$",B,P[2]),g("^-",B,P[3]));repeat{if(j<5 & d){d=!d;j=j+1;f(j,P[1])};if(j>44 & !d){d=!d;f(j,P[1]);j=j-1};if(runif(1)<.1){for(i in b[[d+1]])f(j,i)}else{f(j,P[d+2])};if(runif(1)<.3){d=!d;f(j,P[1]);f(j,P[d+2])};if(d){j=j-1}else{j=j+1}}
```
Indented:
```
f=function(j,p){ #Printing function (depends of buffer and kind of fish)
cat("\r|",rep("-",j),p,rep("-",50-j),"|",sep="")
Sys.sleep(2)
}
d=F #Direction: if FALSE left to right, if TRUE right to left.
j=5 #Buffer from left side of tank
P=c("--}}(\'_\'){{--","-}}< }} \',\')-","-(\',\' {{ >{{-") #The fish
B=c("-",".","o","O","*","-") #The bubble sequence
g=Vectorize(gsub,v="replacement")
b=list(g("-$",B,P[2]),g("^-",B,P[3])) #Fish+bubble
repeat{
if(j<5 & d){ #What happens if too close from left side
d=!d
j=j+1
f(j,P[1])
}
if(j>44 & !d){ #What happens if too close from right side
d=!d
f(j,P[1])
j=j-1}
if(runif(1)<.1){ #If bubble sequence initiated
for(i in b[[d+1]])f(j,i)
}else{f(j,P[d+2])} #Otherwise
if(runif(1)<.3){ #If fish decide to turn
d=!d
f(j,P[1])
f(j,P[d+2])
}
if(d){j=j-1}else{j=j+1} #Increment or decrement j depending on direction
}
```
It prints the aquarium as stdout on a single line (then 2s break and carriage return before the aquarium at t+1 is printed).
[Answer]
## Perl, 281
```
@f=("s O(',' {{ >{{","s}}('_'){{s","}}< }} ',')O s");$d=1;@o=split//," *Oo. ";{$_="|".$"x$x.$f[$d+1].$"x(44-$x).'|
';s/O/$o[$b]/;s/s/ /g;print;if($b||$t){$b--if$b;if($t){$d+=$t;$t=0if$d}}else{$x+=$d;$t=($x<1)-($x>43);if(!$t){$b=5if.9<rand;if(.7<rand){$t=-$d;$b=0}}}sleep 2;redo}
```
or more clearly
```
@f = ( "s O(',' {{ >{{", "s}}('_'){{s", "}}< }} ',')O s" );
$d = 1;
@o = split //, " *Oo. ";
{
$_ = "|" . $" x $x . $f[ $d + 1 ] . $" x ( 44 - $x ) . '|
';
s/O/$o[$b]/;
s/s/ /g;
print;
if ( $b || $t ) {
$b-- if $b;
if ($t) { $d += $t; $t = 0 if $d }
}
else {
$x += $d;
$t = ( $x < 1 ) - ( $x > 43 );
if ( !$t ) {
$b = 5 if .9 < rand;
if ( .7 < rand ) { $t = -$d; $b = 0 }
}
}
sleep 2;
redo
}
```
Fish turning correctly. Bubbles blowing.
**285** - if you like the real aquarium feel and not the scrolling version:
```
$|=@f=("s O(',' {{ >{{","s}}('_'){{s","}}< }} ',')O s");$d=1;@o=split//," *Oo. ";{$_="\r|".$"x$x.$f[$d+1].$"x(44-$x).'|';s/O/$o[$b]/;s/s/ /g;print;if($b||$t){$b--if$b;if($t){$d+=$t;$t=0if$d}}else{$x+=$d;$t=($x<1)-($x>43);if(!$t){$b=5if.9<rand;if(.7<rand){$t=-$d;$b=0}}}sleep 2;redo}
```
[Answer]
## C, 400 394 373 characters
```
#define p printf
#define a(x) l[5]=r[11]=x;d();
char *l=" (',' {{ >{{",*f=" }}('_'){{ ",*r="}}< }} ',') ",*c,s=7,i,*T;d(){p("|");for(i=0;i<s;i++)p(" ");p(c);for(i=0;i<70-s;i++)p(" ");puts("|");sleep(2);}b(){a(46)a(111)a(79)a(42)a(32)}t(){T=c;c=f;d();c=T==r?l:r;d();}m(){c==l?s--:s++;d();s>69||s<1?t():0;}main(){c=r;for(d();;)i=rand()%10,i?i>6?t():m():b();}
```
With whitespace:
```
#define p printf
#define a(x) l[5]=r[11]=x;d();
char *l=" (',' {{ >{{",
*f=" }}('_'){{ ",
*r="}}< }} ',') ",
*c,
s=7,
i,
*T;
d(){
p("|");
for(i=0;i<s;i++)
p(" ");
p(c);
for(i=0;i<70-s;i++)
p(" ");
puts("|");
sleep(2);
}
b(){
a(46)
a(111)
a(79)
a(42)
a(32)
}
t(){
T=c;
c=f;
d();
c=T==r?l:r;
d();
}
m(){
c==l?s--:s++;
d();
s>69||s<1?t():0;
}
main(){
c=r;
for(d();;)
i=rand()%10,
i?i>6?t():m():b();
}
```
] |
[Question]
[
You are responsible for building a new freeway. However, it leads through
mountainous lands and therefore needs numerous bridges and tunnels. The
freeway itself should stay at a single level.
**Input**
You are given a rough ASCII description of how the mountains look like on
standard input, such as the following:
```
/\
/ \
/\ / \
/\ / \/ \
/ \ / \ /\
/ \/ \ / \
_ / \ /\ / \
\ / \ / \ / \ /\
\ / \ / \/ \/ \
\ / \ /
\/ \/
```
The `_` in the first column marks the beginning and the level of the road.
The mountain range is contiguous and if the last segment will be a bridge,
it has an even number of characters.
You may assume that a line of input is never longer than 100 characters
and that there are no more than 15 lines. Every line has the same length
which is possibly space-padded at the end. The road never starts within a
mountain or as a bridge. The first thing following the road tile in the
input is either a slope down or up.
**Output**
Output is the same mountain range, except that there is now a road where
previously was only its beginning. Output is given on standard output.
For this there are numerous rules:
1. The road must start at the place indicated in the input and remain the
same level throughout. To make it easier, we have prepared a number of
premade road tiles which look like this: `_`:
```
_______
\ /
\/\/
```
2. The road must extend to the far end of the mountain range (i.e. the
length of the input lines dictates how far the road goes).
3. Tunnels must be drilled whenever a mountain is where the road needs to
go. Tunnels go straight through the mountain and leave holes at the start
and the end (i.e. a tunnel replaces the slope of the mountain with a
closing parenthesis at its start and an opening parenthesis at its end).
4. Tunnels leave, well, a tunnel in the mountain which usually has a
ceiling. Our premade road tiles luckily can be used to reinforce the
ceiling so that the tunnel does not collapse (the line above the tunnel
has to use `_` to reinforce the tunnel):
```
/\
/ \
/____\
___)______(__
\/ \/
```
5. The tunnel does not need to be reinforced when the mountain isn't high
enough above it. It sounds weird to me as well but I have been told the
premade road tiles are strong enough to hold even when spaced out in that
case (no tunnel ceiling is drawn when there is a slope directly above the
tunnel):
```
/\
/\/__\
___)______(__
\/ \/
```
6. Bridges are needed whenever the road needs to cross a chasm. For short
bridges the premade road tiles are strong enough but still need a bit
support at the beginning and end of the bridge (the first downward slope
under the bridge and the last upward slope are replaced by `Y` so that
there is a support beam for the bridge):
```
_____
Y Y
\/
```
7. Longer bridges need additional support. A long bridge is one that has
more than six unsupported road tiles in a row. Long bridges need a pillar
in their center. Pillars are easily built with our prebuilt pillar beams
which look like this: `|`. Each pillar needs two of those and they extend
down to the bottom of the chasm:
```
_____________________________
Y || Y
\ /\ || /\ /\/
\ /\ / \||/ \ /\/
\/ \/ \/ \/
```
8. Since the input only represents a portion of the whole mountain range
the freeway needs to be built through, it may end abruptly in the middle
of a bridge or tunnel. The long bridge rule still applies for the final
segment and you can assume that the first part beyond the given input
supports the bridge again.
Following the above rules we get the following for our input:
```
/\
/ \
/\ / \
/\ / \/ \
/ \ / \ /\
/____\/______________\ /__\
_________)______________________(________)(____)____(______
Y Y Y Y Y Y Y YY
\ / \ / \/ \/ \
\ / \ /
\/ \/
```
Shortest code by character count wins. Trailing whitespace in the lines is
ignored for validation.
**Sample input 1**
```
_
\ /\
\ / \
\ / \
\ /\ / \ /\ /
\ /\ / \ / \ /\ /\/ \ /
\ / \ / \/ \ / \/ \/\ /
\/ \ / \ / \/
\ / \/
\/
```
**Sample output 1**
```
____________________________________________________________
Y || YY ||
\ || / \ ||
\ || / \ ||
\ || /\ / \ || /\ /
\ /\ || / \ / \ /\ |/\/ \ /
\ / \ || / \/ \ / \/ \/\ /
\/ \ || / \ / \/
\||/ \/
\/
```
**Sample input 2**
```
/\ /\
/ \/ \ /
/\ / \ /\ /
/\ / \ / \/ \ /
/ \ / \/\ / \ /\ /
/ \/ \ / \ / \ /
_/ \ / \/ \/
\ /
\ /\/
\ /\ /
\/ \ /
\ /
\/
```
**Sample output 2**
```
/\ /\
/ \/ \ /
/\ / \ /\ /
/\ / \ / \/ \ /
/ \ / \/\ / \ /\ /
/____\/________\ /__________________\ /__\ /____
_)________________(__________________)____________________()____()_____
Y || Y
\ || /\/
\ /\ || /
\/ \|| /
\| /
\/
```
**Note**
Trailing spaces in the output are ignored for comparison with the
reference solutions.
**Winning condition**
Shortest code wins, as is customary in golf. In case of a tie, the earlier
solution wins.
**Test cases**
There are two tests scripts, containing identical test cases:
* [bash](http://hypftier.de/dump/CG3179/test)
* [PowerShell](http://hypftier.de/dump/CG3179/test.ps1)
Invocation is in both cases: `<test script> <my program> [arguments]`,
e.g. `./test ruby bridges.rb` or `./test.ps1 ./bridges.exe`.
**Another note**
This task was part of a golf contest held at my university during
2011-W24. The scores and languages of our contestants were as follows:
* 304 – Perl
* 343 – C
* 375 – C
* 648 – Python
Our own solution (thanks to Ventero) was
* 262 – Ruby
[Answer]
## Perl, 210 195 194 193 chars
*update*
Same ideas, but applied very differently, for the most part.
Run with `perl -p0` (4 chars counted for the switches).
```
($o,$c,$r,$b)=/((.+\n)?(_.+\n)(.+\n)?)/;/\n/;$n=$-[0];$c=~s{/ }{/_}g;$r=~y{ /\\}{_)(};map{s{\\( +) \1(/|\n)}{\\$1||$1$2}g,y{\\/}{Y}}$b;s/\Q$o/$c$r$b/;1while(s/_ /__/||s/(\|.{$n}) /$1|/s)
```
This also requires a change to the bash test script, so as not to over-quote the args:
```
- got=$("$cmd" "$args")
+ got=$("$cmd" $args)
```
BTW, I really appreciate the test scripts, @Joey.
commented:
```
#-p : implicitly read input and print after transformations
#-0 : "slurp mode": don't break lines
# grab the roadway line, along with the lines above and below for ceiling and buttresses
# also grab the whole match in $o for replacing later
($o,$c,$r,$b)=/((.+\n)?(_.+\n)(.+\n)?)/;
# compute line length
/\n/;$n=$-[0];
# start ceilings
$c=~s{/ }{/_}g;
# build the road and tunnels
$r=~y{ /\\}{_)(};
# use map to avoid repeating $b =~
map{
# insert the pillar tops
s{\\( +) \1(/|\n)}{\\$1||$1$2}g,
# and the buttresses
y{\\/}{Y}
} $b;
# put those 3 (or 2) lines back into the original
s/\Q$o/$c$r$b/;
# extend ceiling tiles to the right and pillars downward
1while(s/_ /__/||s/(\|.{$n}) /$1|/s)
```
*edits*:
* replace "`{3,}`" with 3 literal spaces and the `+` quantifier, to
save another character
* use the `1while(...)` form, where I can omit
the semicolon at the end of the script
---
*original* (see history for commented version)
```
@a=map{($r=$n),y{ /\\}{_)(}if/_/;$n++;$_}<>;if($r){while($a[$r-1]=~s{(/[ _]*) }{$1_}){}}map{s{(^|\\)( {3,}) \2(/|$)}{$1$2||$2$3}g;y{\\/}{YY}}$a[$r+1];$_=join'',@a;/\n/;$n=$-[0];while(s/(\|.{$n}) /$1|/s){}print
```
I deliberately didn't look at @Howard's Perl solution until mine was working, but I was able to improve my golfing by looking afterward.
In particular, the regexps for tunnel ceilings and extending pillars helped. Nicely done, Howard.
Conversely, my alternative for getting line length, using the implicit $\_ for the print, leaving off the final semicolon, and removing newlines could shorten Howard's to 222 characters.
[Answer]
### Perl, 234 characters
```
$_=join'',<>;$l=index($_,"\n");
($w)=/(_[^\n]*)/;$w=~y/ \\\//_()/;s/_[^\n]*/$w/e;
while(s/(\/[ _]*) (?=[^\n]*\n_)/$1_/||s/(_.{$l})[\\\/]/$1Y/s){}while(s/(\n( |Y *Y)*)Y( {3,}) \3(Y| ?\n)/\1Y\3||\3\4/||s/(?<=\|.{$l}) /|/s){}
print $_;
```
This is a perl regex-only solution. It passes all given test cases.
The identical but more readable version shows the steps taken to obtain the result:
```
$_=join'',<>; # read the input
$l=index($_,"\n"); # determine length of line
($w)=/(_[^\n]*)/; # extract the line starting with _
$w=~y/ \\\//_()/; # and build road there (i.e. replace all chars in line)
s/_[^\n]*/$w/e; # put road back into string
while(s/(\/[ _]*) (?=[^\n]*\n_)/$1_/||s/(_.{$l})[\\\/]/$1Y/s){}
# build ceiling of tunnels
# build Y supports directly below the road
while(s/(\n( |Y *Y)*)Y( {3,}) \3(Y| ?\n)/\1Y\3||\3\4/||s/(?<=\|.{$l}) /|/s){}
# build center support in middle of bridges
# and extend them down to the ground
print $_; # print result
```
[Answer]
# C++, 662 622 598 chars, 4 lines
```
#include<iostream>
#include<string>
#define s for(
#define v g[t][f]
int t,f,r,q,m=-1,w,b,e,h,j,x,y,l,c=18;int main(){std::string g[19];s;r<19;h=c)getline(std::cin,g[r++]);s;c>=0;g[c--].push_back(0))(q=g[c].size())&&g[c][0]-95?0:r=c;s;c<q;y=0){x=g[r][++c];x==47?x=41,w=e=1:++y;x==92?x=40,w=0:++y;t=r-1;f=c;y>1?x=95,w?r&&v==32?v=95:0:++b:0;c-q?0:e=1;t++;s v=x;m<0;)g[h].find(47)<g[h--].npos?m=h:0;t=r+1;if(r<m){(y=v)==47?y=89,e=1:0;v=y-92?y:89;if(e){y=e=0;if((b/=2)>4){j=l=r+1;s;!y;t=j,f=c-b+1,v==32?v=124,++j:0)t=l,y=f=c-b,v==32?v=124,l++,y=0:0;}b=0;}}}s f=q,t=0;t<=m;std::cout<<g[t++]<<'\n')v=32;}
```
This should be it, I've tested this out with the powershell script so it should be ok...
**Edit 1**
Replaced all char constants with numbers, removed successive calls to std::cout + a few other minor changes.
**Edit 2**
last edit, just to get it less than 600. Took out g[t][f] as a #define and moved a few things around.
[Answer]
## Ruby, 382 356 353 characters
I thought to give a non-regex solution a shot.
```
m=$<.read;n,r,s,$e,t=(/\n/=~m)+1,/^_/=~m,m.size,(u,d=47,92),0;def j y;$e.member? y;end;(n-1).times{|i|x=r+i;c=m[x];j(c)||(m[x]=95;a,b=x-n,x+n;t<41||a<0||m[a]>32||m[a]=95;b>s||!j(m[b])||(m[b]<d||(p=(/\/|\n/=~m[b..s])/2+b;p-b<4||(w=[f=false,f];p.step(s,n){|p|2.times{|i|(w[i]||=j m[i=p+i])||m[i]='|'}}));m[b]='Y'));c!=u||t=m[x]=41;c!=d||t=m[x]=40};print m
```
The biggest space saver here is to use conditional `||` operator instead of `if - elsif - end`. So instead of writing `if(a) lorem_ipsum end` I've written `!a||lopem_ipsum`. Larger blocks can included using parenthesis `!a||(block)`. If the condition includes `&&` operators then they must negated by using parenthesis and a `!` or by using De Morgan's laws.
And here's the same with more words
```
# read the STDIN to string
mountains = $<.read
line_length,road_level,size,$slopes,in_tunnel =
(/\n/ =~ mountains) + 1, # Fint the first new line
/^_/ =~ mountains, # Find the index of the road
mountains.size,
(slope_up,slope_down=47,92),
0
def is_slope y;$slopes.member? y;end
# For each index in the road line
(line_length - 1).times { |i|
curindex = road_level + i
curchar = mountains[curindex]
# If not a slope then
(is_slope(curchar))|| (
# mark road as underscore
mountains[curindex] = 95
above, below = curindex - line_length, curindex + line_length
# add roof to tunnel if in tunnel and the mountain
# is high enough
in_tunnel<41||above<0||mountains[above]>32||mountains[above]=95
# If there's a slope character below the road
below>size||!is_slope(mountains[below])||(
# if there's a downward slop - start a bridge
mountains[below]<slope_down||(
# If bridge is longer than 6 characters
# Add support to the middle
support_pos = (/\/|\n/=~mountains[below..size])/2+below
support_pos-below<4||(
# Init collision detection
collision_detected=[f=false,f]
# Build supports as long as
# There is mountains below
support_pos.step(size,line_length) { |support_pos|
# Add two parallel suppports
2.times { |i|
# Add support if the bottom of the
# gap has not been reached
(collision_detected[i]||=is_slope(mountains[i=support_pos+i]))||mountains[i] = '|'
}
}
)
)
# Add support to the beginning and to the end
# of the bridge
mountains[below] = 'Y'
)
)
# Add tunnel entrance and exit
curchar!=slope_up||in_tunnel=mountains[curindex]=41
curchar!=slope_down||in_tunnel=mountains[curindex]=40
}
print mountains
```
[Answer]
## Scala, 462 characters
```
object B extends App{var r="""(?s)((?:.*\n)?)((?:.*?\n)?)(_.*?\n)(.*?\n)(.*)""".r
var r(a,b,c,d,e)=io.Source.stdin.mkString
var s=a+b.replaceAll("(?<=/ {0,99}) (?=.*\\\\)","_")+c.replaceAll("\\\\","(").replaceAll("/",")").replaceAll(" ","_")+d.replaceAll("\\\\( {3,99}) \\1/","Y$1||$1Y").replaceAll("\\\\( {3,99}) \\1\\n","Y$1||$1\n").replaceAll("\\\\( {0,9})/","Y$1Y")+e
for(i<-1 to 15)s=s.replaceAll("(?s)(?<=\\|.{"+s.split("\n")(0).size+"}) ","|")
print(s)}
```
Not particularly competitive, but I've learnt a lot about regular expressions today. :-)
[Answer]
# Erlang, 1182 characters
```
-module(b).
-export([t/0]).
t()->r([]).
r(R)->case io:get_line("")of eof->{_,Q}=lists:foldl(fun([$ |L],{$_,Q})->{$ ,[[$X|L]|Q]};([C|_]=L,{_,Q})->{C,[L|Q]}end,{$ ,[]},R),{_,P}=lists:foldl(fun s/2,{s,[]},lists:flatten(Q)),io:put_chars(lists:reverse(P));L->r([L|R])end.
s($X,{s,R})->{{r,s},[$ |R]};s($/,{{r,s},R})->{{r,r},[$/|R]};s($\\,{{r,r},R})->{{r,s},[$\\|R]};s($\n,{{r,_},R})->{u,[$\n|R]};s(_,{{r,r}=S,R})->{S,[$_|R]};s($_,{_,R})->{u,[$_|R]};s($\n,{u,R})->{{g,i,1,1,[]},[$\n|R]};s($\\,{u=S,R})->{S,[$(|R]};s($/,{u=S,R})->{S,[$)|R]};s(_,{u=S,R})->{S,[$_|R]};s($\\,{{g,i,X,_L,T},R})->{{g,o,X+1,X,[$Y|T]},R};s($/,{{g,o,X,L,T},R})->a(o,X,L),{{g,i,X+1,X,[$Y|T]},R};s($\n,{{g,S,X,L,T},R})->a(S,X,L),{{d,1},[$\n,f(T,X)|R]};s(C,{{g,S,X,L,T},R})->{{g,S,X+1,L,[C|T]},R};s($\n,{{d,_},R})->{{d,1},[$\n|R]};s($ ,{{d,X},R})->{{d,X+1},[case get(X)of y->$|;_->$ end|R]};s($/,{{d,X},R})->put(X,n),{{d,X+1},[$/|R]};s($\\,{{d,X},R})->put(X,n),{{d,X+1},[$\\|R]};s($\n=N,{S,R})->{S,[N|R]};s(X,{S,R})->{S,[X|R]}.
a(o,X,L)when X-L-1>6->Pos=round((X-L-1)/2+L),put(Pos,y),put(Pos+1,y);a(_,_,_)->v.
f(L,M)->{_,R}=lists:foldl(fun(C,{X,R})->case get(M-X)of y->{X+1,[$||R]};_->{X+1,[C|R]}end end,{1,[]},L),R.
```
Not competitive at all. To be honest, I was simply interested in producing some nice ascii art, not so much in the golfing. Note that this does not use regular expressions, instead, I wrote the state machine myself. This will also need the overquoting fix in the shell script, mentioned in the perl solution above.
[Answer]
# Powershell, ~~300~~ 295 287 bytes
*-8 bytes fix peeked from DCharness'es [answer](https://codegolf.stackexchange.com/a/3197/80745).*
```
param($s)filter e{$r,$e=$_-split'#';$e|%{$r=$r-replace($_-split';')};$r}
$x=$s-match'(.+
)?(_.+)(
.+)?'
$o,$c,$r,$b=$Matches[0..3]
for($s=$s|% *ce $o(("$c#/ ;/_"|e)+("$r# ;_#/;)#\\;("|e)+($b+'#\\( +) \1;\$1||$1#/|\\;Y'|e));$s-ne($x="$s#_ ;__#(?s)(?<=\|.{$($r|% Le*)}) ;|"|e)){$s=$x}$s
```
Ungolfed test script:
```
$f = {
param($s)
$x=$s-match'(.+
)?(_.+)(
.+)?'
$o,$c,$r,$b=$Matches[0..3]
$c=$c-replace'/ ','/_' # we assume that road does not start as a tunnel
$r=$r-replace' ','_'
$r=$r-replace'/',')'
$r=$r-replace'\\','('
$b=$b-replace'\\( +) \1','\$1||$1' # we assume that road does not start as a bridge under a chasm
$b=$b-replace'/|\\','Y'
$s=$s.replace($o,"$c$r$b") # string method replace (not operator) does not handle regexp
for(;$s-ne($x=$s-replace'_ ','__'-replace"(?s)(?<=\|.{$($r.Length)}) ",'|')){$s=$x}
$s
}
$pass = 0
$count = 0
@(
# Test 2
,(2,@'
/\ /\ /\
/ \ / \ / \
/____\ /____\ /____\
_)______(____________)______(____________)______(_____
Y || Y Y || Y Y
\ || / \ || / \
\ || / \ || / \
\ || / \ || / \
\||/ \||/ \
\/ \/
'@,@'
/\ /\ /\
/ \ / \ / \
/ \ / \ / \
_/ \ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\/ \/
'@)
# Test 1
,(1,@'
____________________________________________________________
Y || YY ||
\ || / \ ||
\ || / \ ||
\ || /\ / \ || /\ /
\ /\ || / \ / \ /\ |/\/ \ /
\ / \ || / \/ \ / \/ \/\ /
\/ \ || / \ / \/
\||/ \/
\/
'@,@'
_
\ /\
\ / \
\ / \
\ /\ / \ /\ /
\ /\ / \ / \ /\ /\/ \ /
\ / \ / \/ \ / \/ \/\ /
\/ \ / \ / \/
\ / \/
\/
'@)
# Test 3
,(3,@'
/\
/ \
/____\/\/\/\/\/\/\/\
_)____________________(
'@,@'
/\
/ \
/ \/\/\/\/\/\/\/\
_/ \
'@)
# Test 4
,(4,@'
___________________________________________________
Y || YY || Y
\ || / \ |/\ /
\ || / \ / \ /
\ /\ || /\ / \ / \ /
\ / \ || / \/ \ / \ /
\/ \|| / \ / \/
\| / \/
\/
'@,@'
_
\ /\ /
\ / \ /\ /
\ / \ / \ /
\ /\ /\ / \ / \ /
\ / \ / \/ \ / \ /
\/ \ / \ / \/
\ / \/
\/
'@)
# Test 5
,(5,@'
/
/
/__
___________________________________________________)___
Y || YY || Y
\ || / \ |/\ /
\ || / \ / \ /
\ /\ || /\ / \ / \ /
\ / \ || / \/ \ / \ /
\/ \|| / \ / \/
\| / \/
\/
'@,@'
/
/
/
_ /
\ /\ /
\ / \ /\ /
\ / \ / \ /
\ /\ /\ / \ / \ /
\ / \ / \/ \ / \ /
\/ \ / \ / \/
\ / \/
\/
'@)
# Test 6
,(6,@'
_______________________________)
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
'@,@'
_ /
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
'@)
# Test 7
,(7,@'
_________________________________)
Y || Y
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
'@,@'
_ /
\ /
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
'@)
# Test 8
,(8,@'
/\ /\ /\ /\ /\ /\
_)(__)__(__)__(__)__(__)__(__)__(__)__(
YY YY YY YY YY YY
'@,@'
/\ /\ /\ /\ /\ /\
_/\ / \ / \ / \ / \ / \ / \
\/ \/ \/ \/ \/ \/
'@)
# Test 9
,(9,@'
/\/\/\/\/\/\/\/\
_)________________(
'@,@'
/\/\/\/\/\/\/\/\
_/ \
'@)
# Test 10
,(10,@'
/\ /\
/ \ / \
/ \ / \
/ \ / \
/________\ /________\/\/\/\/\
_)__________(__________________________________________________)__________________(______)(_________
Y || Y Y Y Y ||
\ || /\ / \ / \ || /
\ /\ || / \ / \/ \ || /
\ / \ || / \ / \||/
\/ \ || / \ / \/
\ /\ ||/ \ /
\ / \ |/ \ /
\ / \/ \ /
\/\/ \/\/
'@,@'
/\ /\
/ \ / \
/ \ / \
/ \ / \
/ \ / \/\/\/\/\
_/ \ / \ /\
\ / \ / \
\ /\ / \ / \ /
\ /\ / \ / \/ \ /
\ / \ / \ / \ /
\/ \ / \ / \/
\ /\ / \ /
\ / \ / \ /
\ / \/ \ /
\/\/ \/\/
'@)
# Test 11
,(11,@'
__________________________________________________
Y || YY || YY ||
\ || / \ || / \ /\
\ || / \ || / \ / \ /\
\ || / \ || / \ / \ / \/
\ || / \ || / \ / \/
\||/ \||/ \/
\/ \/
'@,@'
_
\ /\ /\
\ / \ / \ /\
\ / \ / \ / \ /\
\ / \ / \ / \ / \/
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 12
,(12,@'
/\ /\
/ \/ \ /
/\ / \ /\ /
/\ / \ / \/ \ /
/ \ / \/\ / \ /\ /
/____\/________\ /__________________\ /__\ /____
_)________________(__________________)____________________()____()_____
Y || Y
\ || /\/
\ /\ || /
\/ \|| /
\| /
\/
'@,@'
/\ /\
/ \/ \ /
/\ / \ /\ /
/\ / \ / \/ \ /
/ \ / \/\ / \ /\ /
/ \/ \ / \ / \ /
_/ \ / \/ \/
\ /
\ /\/
\ /\ /
\/ \ /
\ /
\/
'@)
# Test 13
,(13,@'
_____________)(____________)(_____________________
Y || Y Y || Y Y || YY ||
\ || / \ || / \ || / \ |/\ /
\ || / \ || / \ || / \ / \/
\ || / \ || / \||/ \/
\||/ \||/ \/
\/ \/
'@,@'
_ /\ /\
\ / \ / \ /\
\ / \ / \ / \ /\ /
\ / \ / \ / \ / \/
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 14
,(14,@'
/\ /\
___________)__(__________)__(________)(_________
Y || Y Y || Y Y Y Y YY
\ || / \ || / \ / \ / \/
\ || / \ || / \ / \/
\||/ \||/ \/
\/ \/
'@,@'
/\ /\
_ / \ / \ /\
\ / \ / \ / \ /\
\ / \ / \ / \ / \/
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 15
,(15,@'
/\ /\
/__\ /__\ /\
_________)____(________)____(______)__(____)(__
Y Y Y Y Y Y Y Y YY
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@,@'
/\ /\
/ \ / \ /\
_ / \ / \ / \ /\
\ / \ / \ / \ / \/
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 16
,(16,@'
/\ /\
/ \ / \ /\
/____\ /____\ /__\ /\
_______)______(______)______(____)____(__)__()
Y Y Y Y Y Y YY
\ / \ / \/
\/ \/
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
_ / \ / \ / \ / \/
\ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 17
,(17,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/______\ /______\ /____\ /__\/
_____)________(____)________(__)______()_____
Y Y Y Y YY
\/ \/
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
_ / \ / \ / \/
\ / \ / \/
\/ \/
'@)
# Test 18
,(18,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/________\ /________\ /______\/_____
___)__________(__)__________()______________
YY YY
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/ \ / \ / \/
_ / \ / \/
\/ \/
'@)
# Test 19
,(19,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/ \ / \ / \/
/__________\ /__________\/______________
_)____________()___________________________
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/ \ / \ / \/
/ \ / \/
_/ \/
'@)
# Test 20
,(20,@'
__________________________________________________
Y || YY || YY ||
\ || / \ || / \ /\
\ || / \ || / \ / \ /\
\ || / \ || / \ / \ / \
\ || / \ || / \ / \/ \
\||/ \||/ \/
\/ \/
'@,@'
_
\ /\ /\
\ / \ / \ /\
\ / \ / \ / \ /\
\ / \ / \ / \ / \
\ / \ / \ / \/ \
\ / \ / \/
\/ \/
'@)
# Test 21
,(21,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/________\ /________\ /______\/_____
_)__________(__)__________()______________
YY
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
/ \ / \ / \/
_/ \ / \/
\/
'@)
# Test 22
,(22,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/______\ /______\ /____\ /__\/
_)________(____)________(__)______()_____
Y Y YY
\/
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
/ \ / \ / \ / \/
_/ \ / \ / \/
\ / \/
\/
'@)
# Test 23
,(23,@'
/\
/ \
/\ / \
/\ / \/ \
/ \ / \ /\
/____\/______________\ /__\
_________)______________________(________)(____)____(_______
Y Y Y Y Y Y Y YY
\ / \ / \/ \/ \/
\ / \ /
\/ \/
'@,@'
/\
/ \
/\ / \
/\ / \/ \
/ \ / \ /\
/ \/ \ / \
_ / \ /\ / \
\ / \ / \ / \ /\
\ / \ / \/ \/ \/
\ / \ /
\/ \/
'@)
# Test 24
,(24,@'
/\ /\
/ \ / \ /\
/____\ /____\ /__\ /\
_)______(______)______(____)____(__)__()
Y Y Y Y YY
\ / \/
\/
'@,@'
/\ /\
/ \ / \ /\
/ \ / \ / \ /\
_/ \ / \ / \ / \/
\ / \ / \/
\ / \/
\/
'@)
# Test 25
,(25,@'
/\ /\
/__\ /__\ /\
_)____(________)____(______)__(____)(__
Y Y Y Y Y Y YY
\ / \ / \/
\ / \/
\/
'@,@'
/\ /\
/ \ / \ /\
_/ \ / \ / \ /\
\ / \ / \ / \/
\ / \ / \/
\ / \/
\/
'@)
# Test 26
,(26,@'
/\ /\
_)__(__________)__(________)(_________
Y || Y Y Y Y YY
\ || / \ / \ / \/
\ || / \ / \/
\||/ \/
\/
'@,@'
/\ /\
_/ \ / \ /\
\ / \ / \ /\
\ / \ / \ / \/
\ / \ / \/
\ / \/
\/
'@)
# Test 27
,(27,@'
_)(____________)(_____________________
Y || Y Y || YY ||
\ || / \ || / \ |/\ /
\ || / \ || / \ / \/
\ || / \||/ \/
\||/ \/
\/
'@,@'
_/\ /\
\ / \ /\
\ / \ / \ /\ /
\ / \ / \ / \/
\ / \ / \/
\ / \/
\/
'@)
# Test 28
,(28,@'
____________________________________
Y || YY ||
\ || / \ /\
\ || / \ / \ /\
\ || / \ / \ / \/
\ || / \ / \/
\||/ \/
\/
'@,@'
_
\ /\
\ / \ /\
\ / \ / \ /\
\ / \ / \ / \/
\ / \ / \/
\ / \/
\/
'@)
# Test 29
,(29,@'
_____________________________
Y || Y
\ /\ || /\ /\/
\ /\ / \||/ \ /\/
\/ \/ \/ \/
'@,@'
_
\ /
\ /\ /\ /\/
\ /\ / \ / \ /\/
\/ \/ \/ \/
'@)
# Test 30
,(30,@'
_____
Y Y
\/
'@,@'
_
\ /
\/
'@)
# Test 31
,(31,@'
/\
/\/__\
___)______(__
YY YY
'@,@'
/\
/\/ \
_ / \
\/ \/
'@)
# Test 32
,(32,@'
/\
/ \
/____\
___)______(__
YY YY
'@,@'
/\
/ \
/ \
_ / \
\/ \/
'@)
# Test 33
,(33,@'
_______
Y Y
\/\/
'@,@'
_
\ /
\/\/
'@)
# Test 34
,(34,@'
_)()()()()()()()()()()()()()()()()()(
'@,@'
_/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
'@)
) | % {
$num, $expected, $s = $_
$result = &$f $s
$passed=$result-eq$expected
"$num : $passed"
# $result # uncomment this line to display results
$pass+=$passed
$count+=1
}
"$pass/$count passed."
```
Output:
```
2 : True
1 : True
3 : True
4 : True
5 : True
6 : True
7 : True
8 : True
9 : True
10 : True
11 : True
12 : True
13 : True
14 : True
15 : True
16 : True
17 : True
18 : True
19 : True
20 : True
21 : True
22 : True
23 : True
24 : True
25 : True
26 : True
27 : True
28 : True
29 : True
30 : True
31 : True
32 : True
33 : True
34 : True
34/34 passed.
```
Explanation comics:
```
Start here:
/\ /\ /\
/ \ / \ / \
/ \ / \ / \
_/ \ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\/ \/
Match and zoom it!
/ \ / \ / \ $ceiling \
_/ \ / \ / \ $road | $outline
\ / \ / \ $bottom /
Start ceiling:
/_ \ /_ \ /_ \ $ceiling \
_/ \ / \ / \ $road | $outline
\ / \ / \ $bottom /
Dig tunnels, build a road:
/_ \ /_ \ /_ \ $ceiling \
_)______(____________)______(____________)______(_____$road | $outline
\ / \ / \ $bottom /
Attach to the road the top parts of pillars:
/_ \ /_ \ /_ \ $ceiling \
_)______(____________)______(____________)______(_____$road | $outline
\ || / \ || / \ $bottom /
The road need support:
/____\ /____\ /____\ $ceiling \
_)______(____________)______(____________)______(_____$road | $outline
Y || Y Y || Y Y $bottom /
Put the road back into mountainous lands:
/\ /\ /\
/ \ / \ / \
/_ \ /_ \ /_ \ $ceiling \
_)______(____________)______(____________)______(_____$road | $outline
Y || Y Y || Y Y $bottom /
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\/ \/
Build ceilings and build down pillars:
/\ /\ /\
/ \ / \ / \
/__ \ /__ \ /__ \
_)______(____________)______(____________)______(_____
Y || Y Y || Y Y
\ || / \ || / \
\ / \ / \
\ / \ / \
\ / \ / \
\/ \/
A few iterations later...
/\ /\ /\
/ \ / \ / \
/____\ /____\ /____\
_)______(____________)______(____________)______(_____
Y || Y Y || Y Y
\ || / \ || / \
\ || / \ || / \
\ || / \ || / \
\||/ \||/ \
\/ \/
Thanks. But our princess is in another castle!
```
] |
[Question]
[
The trees we are growing have some rules that define how they grow:
## Growth Rules:
1. Trees consist only of branches.
2. Branches are made up of a combination of the following symbols: `_`, `\`, `|`, `/`, & `_`
3. A tree starts as a single vertical branch/trunk (`|`) on the ground (`_`):
`__________________|___________________`
4. The food for branch growth comes from light.
* Light starts at an intensity of 2 at each point in the sky and travels straight down.
* Each branch is able to eat half the light available to it and the rest passes through to lower branches.
* Thus, a branch with no other branches above it will get 1 unit of light-food each season, a branch with 1 branch above it will get .5 units of food each season, and in general a branch with n branches over it will get 1/(2^n) units of food each season.
5. At the end of each season, the food is totaled starting with the trunk and moving up and converted into new branches and fruit (apply the following rules until the branch turns into fruit or has less than 1 unit of food remaining):
* If a branch has less than 1 unit of food at the end of a season, all the food for that branch is stored in that branch until the next season.
* If a branch has greater than or equal to 1 unit of food and has room to grow, it randomly grows a new branch using the available growth patterns (see below) and stores the remaining food for the next season.
* If a branch has >= 1 unit of food, nowhere to grow, and has offshoot branches, it evenly distributes the food to its offshoot branches
* If a branch has >= 1 unit of food, nowhere to grow, and no offshoot branches, it becomes fruit (represented by `O`)
6. Here are the possible growth configurations
Growth Configurations:
```
_ \ | / _ _ \ | / \ | / _
| | | | | \ \ \ \ / / / / __ \_ |_ _| _/ __
--- Vertical Branches --- --- Diagonal Branches --- --- Horizontal Branches ---
```
## Example potential tree:
```
\
/ /
\/O |___//
\_/ \//O\_/
\__/|\|_/
\|/
__________________|__________________
```
## Input:
Your program should be able to take as input a list of which snapshots of the tree you would like to see. For example [10,20,50] would mean you'd like to see the tree after 10 seasons, 20 seasons, and 50 seasons.
## Output:
For each input season, your program should output the season and then a picture of the tree in that season. If it helps, you can define a maximum age for the tree, such as 60, so that the maximum height for a tree would be 61, and the maximum width would be 121, and then always show the tree on that scale. Otherwise, feel free to scale your image to any sized tree. For example, if the input was [0,1,2,3], your output might be:
```
Season 0:
_|_
Season 1:
\
__|__
Season 2:
_
\|
___|___
Season 3:
|_/ _
\|
____|___
```
## Winner
Each solution must post the output of the coder's favorite run of their program with input of `[10,40]`, along with their source code. Also, ALL the above criteria must be met in order to qualify.
**The winner will be the qualifier with the highest number of votes.**
Good luck and merry planting!!!
[Answer]
**Python**
I took a little liberty with this:
1. I allow multiple trees
2. Fruit is preceded by flower -- once a flower has 1 food, it turns into a fruit.
3. Fruit turns ripe when it has 3 food. It then falls off of the tree, and turns back into a flower.
4. If fruit falls at least 4 places from any given trunk, it buds into a new tree. Since it doesn't get much light, I seed it with as much food as was in the fruit.
**Sample Output, 2 trees**
```
/
\/\_ | / |
_ _/\|\|_\/ /|/
|/ \/|/|O/ \|/
\_/O|@|/ /|_
\_|_| \|
_______|___________________|__
_ \
_/ _ \/\___/\|/ \
/|\|\O@|/\/|__\/ \__/_\|/\\| _ |/| _||/\\ /
\|_|@|\|@/O|@@/O_/@O|@/ \//\ \|\||@||@///
\_ \_|\|/@\\O|@||/OO//O\\O/ \@|@\||/@|\/\/|/ | / _
___/ |/|/O//O|O||\\/|/O// \_O\|__| \O|/\/O| _/\\|
/ \_O@@_\/\O\\@|/O|/O\@\O\\@/OO/|O_@O/O|\/\/ \//|/__
_|/|_| \\|O\\/O/O||_@|\O|\/O//|O|@\|/O_O\@|/O/\_@O__//_||
| \\|____// |O|\O\O|/\@|/ |/O/ \|O|OO|\/@_/O|_O\/O//O_//O/
|_O\\@O\/\\OO\|/|/\O\O\|__@\|O@/|/O|O|/\OO\/|_O/ \\|OO\/
/ \\||_|\|||_O|\|@/OO\//OOO/|/@\|OO|\|\@|O \|\|O@O// \/\
_/\_/@\|\@|/ \_||/ \\@|/\\\||/ \//O|O|/|/@|\@/|/O/OO\\__/ \||/
\||/ |_|O\__@ |O\O/O||\///@|O_//|/OO|@|OO|/O\|O/OO|// /|\|/\|
||___O@|_/ |__\/||_||/|\\/OO/|@|O|/ \|_O||_/O/O/O|/_|\/\|_/
\_OO\\_O\@_|/|_\|_O|/\|//\/|/@|O\|@_O|O_O\/||\/O/|/_|/|O|
\_|\@\@|_|\|OO|O|/\//O\/\O\@|_/|_@\|/\O/\||/\|/|@@|@|/
/|//|\|O|_|O\O\O\/|O\/|@|/_|\OO@\/ \/|O/_|O//@|@/\_|
\O\\|/|_OO|OO\O|/\|@@\|O|/ @//|_@\_/\|//O_/|O/ \/
\O\|O_/|/ \|O|O\/|/OO|O|O_/ \| \/|/|/@ |/\__/
|O|_O\|\O/|_|O/\|\//|/ \_/ /\@\| \_/\/
\OO\O|/ \ _|@\/O||@|\___/ \/|/ \/
|__|O\__|OO\/\@||/\/ \|O____/
|____|/@/\|\|O\/ _/|/O
|/ \/|/|@/ \|/
\_/O|@|/ |/|__
\|/ \_|_| \|_ \|/ \| \|/ _|_
_____________|__________|_____|________|____|_____|____|__________
```
**Source**
```
from random import choice, shuffle
format = '_\|/_@O'
directions = [(-1,0),(-1,1),(0,1),(1,1),(1,0)]
placement = [[[],[0,1,2],[]],[[],[0,1,2],[3]],[[0,1],[2],[3,4]],[[1],[2,3,4],[]],[[],[2,3,4],[]]]
def shine():
for x in ymax:
light = 2.
for y in range(ymax[x],-1,-1):
if (x,y) in tree:
tree[x,y][1] += light/2
light /= 2
def grow((x,y)=(0,0),flow=0):
type,store,children = tree[x,y]
food = store + flow
if type == 5:
if food > 1:
tree[x,y][0] = 6
tree[x,y][1] = food-1
return
elif type == 6:
if food > 3:
tree[x,y]=[5,0,[]]
if min(abs(x-xi) for xi in roots) > 4:
tree[x,0] = [2,food,[]]
roots.append(x)
else:
tree[x,y][1]=food
return
if food < 1:
shuffle(children)
for c in children:
grow(c)
return
sites = []
x0 = x+directions[type][0]-1
y0 = y+directions[type][1]
for i,t in enumerate(placement[type]):
if t and (x0+i,y0) not in tree:
sites.append((t,x0+i,y0))
if sites:
t,x1,y1 = choice(sites)
t1 = choice(t)
children.append((x1,y1))
tree[x,y][1]=food-1
tree[x1,y1]= [t1,0,[]]
ymax[x1] = max(ymax.get(x1,0),y1)
elif children:
shuffle(children)
for c in children:
grow(c,food/len(children))
tree[x,y][1]=0
else:
tree[x,y][0]=5
def output():
X = range(min(ymax.keys())-1,max(ymax.keys())+2)
for y in range(max(ymax.values()),-1,-1):
s = ''
for x in X:
s += format[tree[x,y][0]] if (x,y) in tree else '_ '[y>0]
print s
roots = [0,20]
seasons = [10,40]
tree = {}
ymax = {}
for r in roots:
tree[r,0] = [2,0,[]]
ymax[r]=0
for season in range(max(seasons)):
shine()
shuffle(roots)
for r in roots:
grow((r,0))
if season+1 in seasons:
output()
print
```
I'm curious to see a golfed solution.
[Answer]
## Python, 673 chars
Here's a golfed version:
```
import random
Z='|_\/O'
T={60:0}
F={60:0}
C={60:[]}
B=[((1j-1,1),(1j-1,2),(1j,0),(1j+1,3),(1j+1,1)),((-1,1),(-1,2),(-1,0),(1,0),(1,3),(1,1)),((1j-1,1),(1j-1,2),(1\
j-1,0),(1j,3)),((1j,2),(1j+1,0),(1j+1,3),(1j+1,1)),()]
S=input()
for s in range(61):
if s in S:
for y in range(60,0,-1):print''.join(Z[T[x+y*1j]]if x+y*1j in T else' 'for x in range(121))
print'_'*60+'|'+'_'*60
for p in T:F[p]+=.5**sum(q.real==p.real and q.imag>p.imag and T[q]<4for q in T)
for p in[q for q in T if F[q]>=1]:
D=[p+d,c for d,c in B[T[p]]if p+d not in T]
if D:q,c=random.choice(D);F[p]-=1;T[q]=c;F[q]=0;C[q]=[];C[p]+=[q]
elif C[p]:
for q in C[p]:F[q]+=F[p]/len(C[p])
else:T[p]=4
```
sample @10 (truncated to the interesting part):
```
| |_
|_|/\_\ \|
| \\/\|\/__|/
|/ \\O|O\__|
\___/O|/\/
\/O\/
\|/
________|__________
```
sample @40:
```
_ _ \_ _ / _|
// _|/\|_\||_\___/ \_|_|/|/|_ | _ //
/ _|\\|_/\/|\/_/\/O|O\OO\|\|OO\| \\/ |/|/|_/|
\/\|OOO|//OO\O\|//OO/O_|O||\O|/|/|/OOO/ \OOO\/\| \||_| |
\_|/|_O\\|\O\/|/O/O\_O|/ \\|O|O|/OO\\_/\O\|\/OO/\|O_|\|
|_|OO/O|/O/\|\/\O|O||_OOO|\\|/ \/O_|O\/OO|/O_|\/|OO|/
|/|\O|\|\/OO\O\|_|OO\|||// \OO\_O|O/ |||/_O/O|__|
\|O\O\|/\O\/\O|O|O\/O||/O_/|OO/\| \OO/\|/ \_|
|_/ O|\/O/\/\O\|\|\O|/\/OO|/ \/OO/\O\O\\__/
\_/O/\||/\O|\|O|O\\\/O_| \O/|/ \/O/_//
\O\/ \O\|_|O/\// \/OOOO|\|OO/|/|_|
|/\OO/O/ |O\/|\O/\O\|\O\|_|\|_|
\/OO\_\O__\|\|O|\/OO|/OO|___|
\|OOO\|O \\\|O|/|OO|OO\|
|/ \O|\_O\\|O|\|OO|O|/
\_/O|/O_//|O|/OO\|\|
\_|OO \\O\|\/O_|/
|/ \\O|O\__|
\___/O|/\/
\/O\/
\|/
___________________________|______________________________
```
[Answer]
## Javascript
**UPD:** Added some new rules:
1. if branch can grow it become leaf at first, when leaf have >= 1 food it became a branch with food = leaf food
2. if branch have nowhere to grow and have food >= 1 food its turn into flower
3. if flower have more than 1.5 food it become a froot with flower food / 2
4. if froot have more than 1 food it drops on the ground and grows into new tree
5. each season have 10% chance to have rain which gives additional food to the branches on the ground which distributing food to the others.
Here is not the most beautiful code on javascript. May be later would be some improvements.
Code on [JSFiddle](http://jsfiddle.net/atheo/7mhc7/)
```
var leaf = function(food, branchDirection){
this.food = food || 0;
this.branchDirection = branchDirection;
this.char = 'o';
this.getHtml = function(){
var color = "#00FF00";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var branch = function(food, direction){
var directionChars = ["_", "\\", "|", "/"];
this.food = food || 0;
this.char = directionChars[direction];
this.direction = direction;
this.child_branches = [];
this.getPossibleDirections = function(){
if(this.direction === 0)
{
return [
[-1, 0, [0,1,2]],
[+1, 0, [2,3,0]]
];
}
if(this.direction == 1)
{
return [
[-1, +1, [0,1,2]],
[0, +1, [3]]
];
}
if(this.direction == 2){
return [
[-1, +1, [0,1]],
[0, +1, [2]],
[+1, +1, [3,0]]
];
}
if(this.direction == 3){
return [
[+1 ,+1 , [0,2,3]],
[0 ,+1 , [1]]
];
}
};
this.getHtml = function(){
var color = "brown";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var froot = function(food){
this.char = "O";
this.food = food || 0;
this.getHtml = function(){
var color = "#FF0000";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var flower = function(food){
this.char = "@";
this.food = food || 0;
this.getHtml = function(){
var color = "#FFFF00";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var ground = function(){
this.char = "_";
this.getHtml = function(){
var color = "black";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var air = function(){
this.char = " ";
this.getHtml = function(){
var color = "blue";
var bgColor = "#00BBEE";
return "<span style=\"color: " + color + "; background-color: " + bgColor + "\">" + this.char + "</span>";
};
};
var tree = function(){
var me = this;
var treeSpace = 5;
this.treeMatrix = [];
this.calculateFood = function(isRainy){
//console.log(this.treeMatrix);
var width = this.treeMatrix[0].length;
isRainy = isRainy || false;
for(var i in this.treeMatrix[0]){
var food = 2;
for(var j in this.treeMatrix){
if(this.treeMatrix[this.treeMatrix.length - 1 - j][i] instanceof branch
|| this.treeMatrix[this.treeMatrix.length - 1 - j][i] instanceof leaf){
this.treeMatrix[this.treeMatrix.length -1 - j][i].food += food;
food /= 2;
}
}
if(isRainy){
var rainFood = 5;
for(var j in this.treeMatrix){
if(j == 0 && !(this.treeMatrix[j][i] instanceof branch))
continue;
if((this.treeMatrix[j][i] instanceof branch
|| this.treeMatrix[j][i] instanceof leaf)
&&
(j == 0 || this.treeMatrix[j-1][i] instanceof branch)){
this.treeMatrix[j][i].food += food;
rainFood /= 2;
}
}
}
}
};
this.expandMatrix = function(){
var expandLeft = false;
var expandRight = false;
var expandTop = false;
this.treeMatrix[this.treeMatrix.length - 1].forEach(function(el){
if(el instanceof branch)
expandTop = true;
});
if(expandTop)
this.treeMatrix.push(this.treeMatrix[0].map(function(){return new air();}));
for(var i in this.treeMatrix){
if(this.treeMatrix[i][0] instanceof branch){
expandLeft = true;
}
if(this.treeMatrix[i][this.treeMatrix.length - 1] instanceof branch){
expandRight = true;
}
}
this.treeMatrix = this.treeMatrix.map(function(row){
if(expandLeft)
row.unshift((row[0] instanceof ground ? new ground() : new air()));
if(expandRight)
row.push((row[0] instanceof ground ? new ground() : new air()));
return row;
});
};
this.calculateNewMatrix = function(){
if(this.treeMatrix.length === 0){
this.treeMatrix.push([new ground(), new branch(0,2), new ground()]);
}
var rainySeason = Math.random() > 0.9;
this.expandMatrix();
this.calculateFood(rainySeason);
for(var i in this.treeMatrix){
for(var j in this.treeMatrix[i]){
var element = this.treeMatrix[i][j];
// grow a branch/distribute food/set froot or just store food of not(do nothing)
if(element instanceof branch
&& element.food >= 1
){
//console.log("branch coordinates", i, j);
var directions = element.getPossibleDirections();
var tm = this.treeMatrix;
var freeDirections = directions.filter(function(directionArr){
if(tm[parseInt(i) + directionArr[1]][parseInt(j) + directionArr[0]] instanceof branch)
return false;
else
return true;
});
if(freeDirections.length){
var newCell = freeDirections.length > 1
? freeDirections[Math.floor(Math.random() * freeDirections.length)]
: freeDirections[0];
this.treeMatrix[parseInt(i) + newCell[1]][parseInt(j) + newCell[0]] = new leaf(element.food/2, newCell[2][Math.floor(Math.random() * newCell[2].length)]);
element.child_branches.push(this.treeMatrix[parseInt(i) + newCell[1]][parseInt(j) + newCell[0]]);
}
else if(!freeDirections.length && !element.child_branches.length){
this.treeMatrix[i][j] = new flower(element.food/2);
}
else if(!freeDirections.length && element.child_branches.length){
element.child_branches.forEach(function(child){
child.food += element.food/element.child_branches.length;
});
element.food = 0;
}
}
if(element instanceof flower
&& element.food >= 1.5
){
this.treeMatrix[i][j] = new froot(element.food/2);
}
if(element instanceof froot
&& element.food >= 1
){
this.plantNewTree(j, element.food);
this.treeMatrix[i][j] = new air();
}
if(element instanceof leaf
&& element.food >= 1
){
this.treeMatrix[i][j] = new branch(element.food, element.branchDirection);
}
}
}
};
this.plantNewTree = function(coord, food){
var canGrow = true;
for(var i = 0; i <= treeSpace; i++){
if(!(this.treeMatrix[0][coord + i] instanceof ground)
|| !(this.treeMatrix[0][coord - i] instanceof ground))
canGrow = false;
}
if(canGrow)
this.treeMatrix[0][coord] = new branch(food*10, 2);
};
this.getTreeString = function(){
return this.treeMatrix.reduceRight(function(prev, next){
return (
typeof prev == "string"
? prev
: prev.map(function(el){ return el.char}).join('')
) + "\n" + next.map(function(el){ return el.char}).join('');
})
};
this.getTreeHtml = function(){
return "<pre>" + this.treeMatrix.reduceRight(function(prev, next){
return (
typeof prev == "string"
? prev
: prev.map(function(el){ return el.getHtml()}).join('')
) + "<br/>" + next.map(function(el){ return el.getHtml()}).join('');
}) + "</pre>";
};
};
var seasonsTotal = 300;
var seasonsCounter = 0;
var showAt = [1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,300];
var pageTree = new tree();
var season = function(){
pageTree.calculateNewMatrix();
seasonsCounter++;
if(showAt.indexOf(seasonsCounter) >= 0){console.log(pageTree.getTreeString()); document.body.innerHTML = pageTree.getTreeHtml();}
};
window.onload = function(){
var intervalId = setInterval(function(){
season();
if(seasonsCounter >= seasonsTotal)
clearInterval(intervalId);
}, 100);
};
```
Some examples(10,40,100):
```
\/
\ |/\_/_
| \/\/|/0/_ _
|/ \/0||/|_//
/ \0_/0/\|0|_|
\_/00\0\/|_|
\_|/00\|
|__|/
________|__________
/
_ \_
|/\o_| /
o_/ \/ @|/\|
_@\o__\_/|o/
\|\|\/ \|/
|/ \_//
\__/_|
______|__________
\ \/\
\ |/\/\_|/ | | /
\ \@\/ \/\/\/ |/ \_/ \||_
_ _\\/@/\/@\/\/ \_//\__/|/\_
\ /\|\/|/|_o\/ __/o|\/_|_/\/__|
|@|\_|/_o\|/\|\__o/\\|/\_|\|//|/\__|
|_||/|_@|\/|\|_/|/|| \/ |\//\/o\\\\_@\|| |_|
|/|/\|_||/\o\|/_/\/\_/\o|/ \/|_//// \/ \\|
__@\|\||/\|@/|/o\/\/\/_@_\|\_/\_/|/ \_/__//
__\/|/_@\O|o\|@|@\/\/\_|o/|/|\|\/|_//_||_/
\ \ \|\|_/\|\|//|/\|_\/\//_@\/\|/|/\||//|\|o
/ |/ _|_|@|/|/ \\|__|_o\/o\\|o\||\|\/O|/O|/o_|_|
\_/\|___|_| \_/_|\/ \\/@|\\|\/||/|/\_|__|@|\|___/ /
|_||/|_@_\@\o_/o|o|/@_/\\/_//o \|/\|\/@|_o__|_|__/|/
|@\| /|/\_\|\|/\||_/\_|\@|\\_/|\/@/|/|__/O|_/_/_|/
\||@\|_@_\|/|\@|//o\||//o\||\|/\/||||o___|/ @|_| _
|o\/ \|@@|/ /\O\\/\|o\\|/o|/ \/|/\/\/|\@/\_/|/\_/
\|\o/ \/ \ \/o_|\/|\//|\/o\_/_|O/\//o_|\/@//\/
\\|\_@\_/_o\_/|o\|/|_|_\|/O|/|/\|||__|/o \\/
\|/_|@\\/\\_\|/\|\|@\|\|\_|\|O//O/o_/ \_//
|_@|_/@\/_/\|@_|//o/_/o//@\|/|\//||____|
o_______\\/\\|@\/\/__@\\\/|_o/|__|\\|/|/O|
\|\/ |_o\/\o|_////_/|\|_|@/@|_|\/
|_\_o\\/\/\o\|/|/ O|/ O|/\/\|\/
\||/@\/\O\_|\|@_/ \_/|O/@_|/
|_\|_\O|/o|/ oo\_/@/ \__|
\|_\|\\_|\_/_|/\|___/
|/\| \||/ |_|\/|/
\ |_/@ \/ o|/\|
|_o\\_@\_/|@/
\|\|\/ \|/
|/ \_//
\__/_|
______|__________________|________________________________________
|
\ /\_ \/ | _ \
|/ |\/_/\ |_\/\|_/\ _\ / \ |\/\ |
/ /_\_|/|__/\/|_|\/_/\/\_|\|\ \ \\|/_/|/\ \ _
_|_//|/ |/__|\/\@\\/|/o/|//\/_/_/@/@|\|\@\/\/_ \/ __
\ \|\|o\\|\o/\/O /\|\/|\O\|_|/_///|@\|\\|/|/@|\/\_|@\|/\\|
_ \/\_o_\_/|/ \\\|/|\/ \O\/_@\/\|/|/|_/\\\|_/ \\|\|o_|_\|\|\/|\/\|_|\ /
\o_\|\|\_|||\/\_/o\|o|/\_/__\/\/\/\\|o_@\/// \o/o|/|__|\o|/||||/\/|O|/|@\/
\|@/|/@\|\/\/o/@\|\|_o\/_/||/\/\o\/O|/|@_\\\__/ \/|\__/|//|\/\|/\/o||@\/\/__|
|O\O\|\|/o//o\//|//\|/|o/|O\|\|\|\_|@|/ \\|||\_/\|///O|// @\/O\/|/\\\/\\\/\__|
\||/@/|\/\\/|\\o\\ |/|/\|@\|O|/|/ |_|__//_||O\|o|//o_|\\_//\_|\|\/_||//|\/@\|\
| \__@|/\/\|/_/|\|_\|/\\/\/\/| \|_@\/\_|o|/\|_o||o/\\|/@/_o//\@\/\|/|/\o\|\\|/ \/|/
o_\|/ \|||\/\||_/\|/|@\|\/\\/\/\|_/|o_|\/o/\o\/|_|/\o\/ \\/|_|/\/_@\/| |__|/|//O\_///\o_
\|\|o_/@|\\\||/\|\|o|_@|/o/O\/\_|_/_o_|O\|_/\@\||/ |/\ /|\_/|O/o/|/\|o|/|/\| \|/@/|_/|_|\ _
/ /\__/|/o__\_|_|\|/\/\/|/|/|_\|\/ \/\|/\@|__o||\|/o_|/\__/\/ \|/@/||o/| \/|_@\|_/___|O|_|@/|_@/|//
\/\o_/\| o__|\|@|/\\o\/\|\|_@/\|/_o/o/o\/\\/\\||/|\__|\/|/_/__/ \/\|@\\|\/ @/\/ \|o_/\_|\/o\| \|/\\
o_/\/|@\/ _/o|\|\/\/O\/\//\| \\/o\\|\/o_|\/@\o\||\|/O\|\\o\_|@|\_/\_|_/||/@_/_/\_/_/__/@@/|\/\__/|o//
\o\|_@\___|/\\|_\/\o|\//\/o_/@\|/@|/ \|/o\|\/\@\|\o\|//@/@|/\/o\/o/OO|/\_/\o\//|o/|/|_/\|/O__o\|/ \__\
\ |\|__/ \/\/\|_||/\|/|\/ \|/|o_|\__/O\\_|/_/o/|/\/ \\|\\/\/o\/\/\\_|\/ \/_|\\| \|_| \/|// \/|_o/\__\__
| |/ o_o\| o\\_/|@\/ o|/\_|\|@\_o_/|\|/@\/\\_@|\\|/o_/||_/\o//|_|\/__|\/\/ /|/O_/\/\//__/|___/_|@\_o/O|o/@/ \/|_
\|/o_@\_/|\||_//@_\|_/@__|\/o|/_/\||/| \|_/_\//@\|//o\_o\||/\//\\|_ //_|o/\/\o\|_o\\|\/// @_|\_||@_|/@|\/_/\/\_/_| /
|\_/|/_|\\|@ \\|o\|o\_o_|@\\|/O_//\\|_o|/\_||_|/| \\/o\/|O\/\\//_/|o\O\/\/|/|/@||//|//@\__/\|__|/\/ \|/|_|/__/||\|
/_/\|\/\||/ |__@\|/o|_/_|_|\@\|\/ \/ |/_|\/_||o|/|_//\_|\|_|\/O\\/\|o/o/@|\|_|_/o_\\o\\|/_@__|_||\|\_/ \|@|\@|//\\||
\|\@|/\/\_\_o\|o|\\\|_|o|/\O\_|/\o_/| |_/|/ o\|_|\|o/\/_o/o|\/o_\|\/ |_/\_|/|_||\_O\||/\|\_|@_|__o\|/_@_/__|/\|/\// |//
o_\|@\|_@\//|\_/_|\\|\|\_@\\/_//\\|\|\|_@_\|\o/o|\|o|/\/O\|/@|O\_/\|/\_@\|/_|\|O||/@_/@/\/o//o__||O\/@\|\/\_||\/o\/ \_|/ _
_\|_/|\|/\\ \|\O|/o\\|\||/o\/|oo\|/|@|_|_/o/ \\|/|_|\/|/O|\||\@\|/ \/||/|/o\/o_| \o_\|_/O|/@/_@/|_/_|_|/\/o\|/|_/\\/@|\_|
o__|\o\|_|\@||/|@|/\|/@|/o|\_|\_\|/|/ \@\|/\/\o|\|\|/|/\|\/|_| \\|\\_/\||_|_|/\@\\_//@_\|\||_/|_|O/\|O|\/|/ \| \_||_|/\
|/_||o|_||\\|_|\/|\|o\/_/ |/ \|_|__/_//\o\/_|\|/|@ \/_/\||__/ |/_|\/|/\|o|_||//@/\_o\|/@|/@|/@/\/_/_o\|__o/o___/|_|_|o_|
_ \oo\/\/\|o||\||/|@\|/_/ \o\_@\_/|/|/\|/|\@\|\_|\|/|_o/\_|_|| \__|\||o\|\/_/|_/|/_/_/_@_|@/|\/|_/\//@/o\/ \\/\/ o__|_| @/__o
/\/@|\\/oo|/@|_|\\|\\|\\\_/\|\|/\\o\\\/o\|/\/|///\|\/\|o/\/ |_@_\\/|O\/|/|///|\|@_|\\@|/\/_|/\|o_//o/\|\\_//\/\_/O|/o__/\_|
\/\_|/o\/\\\/|O\/||_||//@_\_|/o\/@|/@\\//\\/|o\\\/@_\/_/\|\_/|_|_//\|\/\|\|\\\|/||\_//o|\//|O\/O|\||O\/_//O|o/\/O|_|o_|@\/
\O_|\_|\/\|\|_o\|_/|@\\|__|\\|/\/_\|/|\\o|\|\/@|\__|\/\/ \|\|o|//\/o \O\\|//_|\||/o_\/|/\\|//\_|_||_/\_|\||O\/\_|@/|_|_/
|_|/_|@\_|_||_O||\|\\||@||/@|\/_|\|\|_|\|/|o\/|/o/|/|/O/o|/ \||\/\\_/_//|/@|\/O|o__|\o\//| \/|/__|o_/\_//@|/ /@@|\__|
o |\_|_|_|O|/o/|o\|/ \\\|\\/|/_/\||o|o\\\\o\/\|_/\O\\\/ o|\_//O/\/|\|@|_o\_|/\_|/\\_/\/\\|_/O||/\_||@/_@\/|o|/\_||\/
|_@\||o|_/\|\/\|\/ \_||\|\|\\\O\o||/o\/ \|\|\//@_/O_\|\_/|/o|_o\ \|/|_|o//_o\/_@\_|||/O//|/|\||_/ \|// |/O|//|/|/|/
o\_|/\\@\/| \/|@\__|\o\|_|/ ||/o|o\/\\_o|/\@\\_/\_o\|/ \|/_| \|\//\|/|/o\_|/|@|o|\|o\|/\|/|/o|/\_/|\\_|/O|@\|\/\|
o|o|o@\|o\|oo\|\/ \\/|_|_|\_@\\/__|\/_|\|_/_/|\_//\\|\_/\\/|_/ \\/|\|/\/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|_\| @__/@_|/oo
/||@\\ _|\@|/ \_||_\/|||o/@\/_|/\ \ \|_o/|\o_|\||_|o__| |/@_\\/__||_/\\\|\__|\//\|_|/\\_/@|_/\/||/\||_|_/__/ \__|o/
\/\\/ |@|_| \ _/@_| \\|/\/\_|\\\\/\_|O|_/\|/_@|/o__|//__/|/|_//|_|_| \o\||/o/|/@\\|/|_///@/|/\/_||_//_||@|_@___/@__|
\_|\_/\oo|_/_@\_@\_@\|@/ /o\/@\|\_ \\||_/|o|\@\_/|/ \|\_|_@_\\/\|@__/\/_o\|/|O//_|\|@/||/|@\/\/|/\||@/@/|__|_@//|/
|__\|\|_o\/\/_|\|\O|/\o\_|\|_|_/| \|o|\|o|/\_o\|\__|/o/_|_o\\/_/|\| \ |//o|/ \|\/|//\|@\\|\/_|\/_|/\/\|/o@/|/_|
\|_||/ \/\_|_|/o|\/|/ \\|o|_||_/o/ |/ \/ |_|//o|\/_@\/\// \|_|_/o||/\|\_/@_\|\\_|_/_|/|o\//O///\_|/ \|/
|_\|\_o\/O|o|_\|@\o\_o\|/|_|_@\|\@_/\_/___o|\\_| \/\o\/ \_@_|@|/ \||_/|/@__O\|//O|_||O\|_||\/ \\/o \__/|
\|/|\|\|/\\\||\/||\|_|\_O|__/|/ |\__\@|\_o\|\\_/_/_/o_/\/\|_@\_@|/\_|__|\|@|/|_|| |_/|_@|/\_//o\_/ O/
\\|/ |_// |/\\||O|_|o_|\\o\|\o|/__\||o\|\|/o\\||/\_/\/\_|_|\\|||/@|_o/\|/|_||/_o/\_|@\/\/_||\_@\_/
\|o___o|_o_\//o|_/\\_||\||@|/|\\_@\|/\/@/|\/|||o\/o//\//|o_///O|\/|/o\o|/|_||__|\/|__|\/|/o|/ \/
|\|@_\O \|\\\/_@\/_\\|_|/\o\|_|\_/@\o\/ \\| \\/\|\\/ \|/\|\\_|/_|_/_||/|O/|/o|/\|_||/\| \/\_/
\|/ \__|_||\/\/O|\\|_|o/\/|/@\_\|/|/\_o/ |o_|\/|/ \_/o\_|/|\|__|@_/\|/O/_o\/ \o|__|\/ o\/
|_____o|_|@\\/_o\\|\@\|\/\|\// \|\|\/_|\_/\|\/\ \_/@_|/o|/ \|____/\//\/|o_/ \|/|_/o__//
oooo|_/|@|\\||\||/|/|\\//|\\_o|/|/\/\/\|o|/o/o/@_|||o\|\o/ \|O/o/\\|\|_o\___/|O|oo/ \|
o__|/\|o\|/|_||/\|/\|_@\|\\|/@\\|\|\|\/o/|_|\/\/\|\_|\\\|/ \_/ \|\/O|/|_|/|_//|/_//__/oo
|_// |_|\//@/ \ |__@|O||\//@|_|/|/\/\|o|/\/\_|/||/ \|o_/Oo__/_/\/|\|/|\|/ \|@_|/ooo|
|_____|//@|\_/\|O|_/\||/ \/ \\\/\O\/o\/\/\/ |/ o\_/ \||_/ \| \@\|\|\|/|__/___|/|_/
ooo|/ \|@\\_|o_@\/_|@_/__/_\\/o/\/o\/\/o \_//\__/|/\__/__/_o|/|_|_|__|oooo\|
o__|/o\__|_//@|/\\o\o\_o\|\\O\|\/|/|_|\/|___/@|\/_|_/\/__|o_@_||\|_|@/ oo\\/\/
|_|\\||@|\|@\/|\\|o|\\|o|\_|/_o\|/\|\__@/\\|/\_|\|//O/|__|/_|/|__|oo \/ \/
|/ ||_|/|_@\|/\|\|_||/|_@|\/|\|_/|/|| \/o|\//\/o\\\\_o\||o|_|oo_|__@\_/
\_o\\|@|_|_|O/ |/|@\|_||/\o\|/_/\/\_/\o|/ \/|_//// \/ O\| oo\/|/@|/oo
\_||@|__@| \__@\|\O|/_|@/|/o\/\/\/_@_\|\_/\_/|/o\_/__// oo|/\|\_|@|_oo
|/\\_\_|_@_|\/|/_@\\|o\|@|@\/\/\_|o/|/|\|\/|_//_||_/ooo\|\_|/o_/|_|
\@|@|\\|\|\|\|_/\|\|//|/\|_\/\//_@\/\|/|/\||//|\|@|_|//|/O|o_/\|
\|\|/ |/|@|_|@|_|/ \\|__|_o\/o\\|o\||\|\/O|/O|/@_|_| \/\/_o_\/
|_|\_/\|O__|_| \_/_|\/ \\/@|\\|\/||/|/\_|__|@|\|___/\/|\|_/
|_||/|_@_\@\o_/o|o|/@_/\\/_//o \|/\|\/@|_o__|_|__/|/||/|/
|o\| /|/\_\|\|/\||_/\_|\@|\\_/|\/@/|/|__/O|_/_/_|// \|
\||@\|_@_\|/|\@|//o\||//o\||\|/\/||||o___|/o_|@| \_/
|o\/ \|@@|/ /\O\\/\|o\\|/o|/ \/|/\/\/|_o/\_/|/\_/
\|\o/ \/ \ \/o_|\/|\//|\/o\_/_|O/\//o_|\/@//\/
\\|\_@\_/_o\_/|o\|/|_|_\|/O|/|/\|||__|/o \\/
\|/_|@\\/\\_\|/\|\|@\|\|\_|\|O//O/o_/ \_//
|_@|_/@\/_/\|@_|//o/_/o//@\|/|\//||____|
o________\\/\\|@\/\/__@\\\/|_o/|__|\\|/|/O|
\|\/ |_o\/\o|_////_/|\|_|@/@|_|\/
|_\_o\\/\/\o\|/|/ O|/ O|/\/\|\/
\||/@\/\O\_|\|@_/ \_/|O/@_|/
|_\|_\O|/o|/ oo\_/@/ \__|
\|_\|\\_|\_/_|/\|___/
|/\| \||/ |_|\/|/
\ |_/@ \/ o|/\|
oooooooo ooo oo |_o\\_@\_/|@/
oo|_o\|/oo__|_oo o_\_o_oo \|\|\/ \|/
|/\|/| \/\|/|_o |\|_/ |/ \_//
\_|/ \_|_| \|/ \__/_|
__________________|_______|_______________|__________________|____________________________________________________________________________________________________
```
] |
[Question]
[
The purpose of this challenge is to determine if a collection of one-dimensonal pieces can be tiled to form a finite continuous chunk.
A **piece** is a non-empty, finite sequence of zeros and ones that starts and ends with a one. Some possible pieces are `1`, `101`, `1111`, `1100101`.
**Tiling** means arranging the pieces so that a single contiguous block of ones is formed. A one from one piece can occupy the place of a zero, but not of a one, from another piece.
Equivalently, if we view a one as being "solid material" and a zero as a "hole", the pieces should fit so as to form a single stretch, without leaving any holes.
To form a tiling, pieces can only be **shifted** along their one-dimensional space. (They cannot be split, or reflected). Each piece is used exactly once.
# Examples
The three pieces `101`, `11`, `101` can be tiled as shown in the following, where each piece is represented with the required shift:
```
101
11
101
```
so the obtained tiling is
```
111111
```
As a second example, the pieces `11011` and `1001101` cannot be tiled. In particular, the shift
```
11011
1001101
```
is not valid because there are two ones that collide; and
```
11011
1001101
```
is not valid because the result would contain a zero.
# Additional rules
The **input** is a collection of one or more pieces. Any reasonable format is allowed; for example:
* A list of strings, where each string can contain two different, consistent characters;
* Several arrays, where each array contains the positions of ones for a piece;
* A list of (odd) integers such the binary representation of each number defines a piece.
The **output** should be a truthy value if a tiling is possible, and a falsy value otherwise. Output values need not be consistent; that is, they can be different for different inputs.
[Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
Shortest code in bytes wins.
# Test cases
Each input is on a different line
### Truthy
```
1
111
1, 1
11, 111, 1111
101, 11, 1
101, 11, 101
10001, 11001, 10001
100001, 1001, 1011
10010001, 1001, 1001, 101
10110101, 11001, 100001, 1
110111, 100001, 11, 101
1001101, 110111, 1, 11, 1
```
### Falsy
```
101
101, 11
1, 1001
1011, 1011
11011, 1001101
1001, 11011, 1000001
1001, 11011, 1000001, 10101
```
[Answer]
# JavaScript (ES6), ~~74~~ ~~73~~ 70 bytes
Takes input as an array of 32-bit integers. Returns a boolean.
```
f=([n,...a],x)=>n?[...f+''].some(_=>n&&!(x&n)&f(a,x|n,n<<=1)):!(x&-~x)
```
Or **66 bytes** with inverted truthy/falsy values:
```
f=([n,...a],x)=>n?[...Array(32)].every(_=>x&n|f(a,x|n,n*=2)):x&-~x
```
### Test cases
```
f=([n,...a],x)=>n?[...f+''].some(_=>n&&!(x&n)&f(a,x|n,n<<=1)):!(x&-~x)
console.log('[Truthy]')
console.log(f([0b1]))
console.log(f([0b111]))
console.log(f([0b1,0b1]))
console.log(f([0b11,0b111,0b1111]))
console.log(f([0b101,0b11,0b1]))
console.log(f([0b101,0b11,0b101]))
console.log(f([0b10001,0b11001,0b10001]))
console.log(f([0b100001,0b1001,0b1011]))
console.log(f([0b10010001,0b1001,0b1001,0b101]))
console.log(f([0b10110101,0b11001,0b100001,0b1]))
console.log(f([0b110111,0b100001,0b11,0b101]))
console.log(f([0b1001101,0b110111,0b1,0b11,0b1]))
console.log('[Falsy]')
console.log(f([0b101]))
console.log(f([0b101,0b11]))
console.log(f([0b1,0b1001]))
console.log(f([0b1011,0b1011]))
console.log(f([0b11011,0b1001101]))
console.log(f([0b1001,0b11011,0b1000001]))
console.log(f([0b1001,0b11011,0b1000001,0b10101]))
```
### How?
```
f = ( // f = recursive function taking:
[n, ...a], // n = next integer, a = array of remaining integers
x // x = solution bitmask, initially undefined
) => //
n ? // if n is defined:
[... f + ''].some(_ => // iterate 32+ times:
n && // if n is not zero:
!(x & n) // if x and n have some bits in common,
& // force invalidation of the following result
f( // do a recursive call with:
a, // the remaining integers
x | n, // the updated bitmask
n <<= 1 // and update n for the next iteration
) // end of recursive call
) // end of some()
: // else (all integers have been processed):
!(x & -~x) // check that x is a continuous chunk of 1's
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
+"FṢIP
FSṗLç€ċ1
```
Takes a list of indices and returns a positive integer (truthy) or **0** (falsy).
[Try it online!](https://tio.run/##y0rNyan8/19bye3hzkWeAVxuwQ93Tvc5vPxR05oj3Yb///@PjjbUUTCO1VEA0UZgOjZWQRlIGQAFDEE4FgA "Jelly – Try It Online") or [verify most test cases](https://tio.run/##y0rNyan8/19bye3hzkWeAVxuwQ93Tvc5vPxR05oj3Yb/XUKADAg63A6h3f//j46ONozV4VJQiDY0hDF0FOBCQCaUgAkZgLkIJXC@AVzEACIGoUA8hARUCKLeMBYkER2NpBWsEeEMJL2GMD1Ql0EFDAyRLYbYC5UB2xwbCwA "Jelly – Try It Online").
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
V§=OŀF×+ṠṀṪ+oŀṁ▲
```
Takes a list of lists of 1-based indices.
[Try it online!](https://tio.run/##yygtzv6vkHtiffGjpsaiQ9v@hx1abut/tMHt8HTthzsXPNzZ8HDnKu38o0Cq8dG0Tf///4@ONoyN5QKSOkY6xhBWrA5CDMQGy0BpHROoDFQESS2SCMwkHVOoPghtChU1A/NMICrhJproWCCJm6CYA1SlYwaVh5lmhuxOoLwp1FwzLO4AyZpDdcNVYvEBqk/goYHwNYarweZB1IDtgNqHsAvMwi0OMQ0YMgA "Husk – Try It Online")
## Explanation
```
V§=OŀF×+ṠṀṪ+oŀṁ▲ Implicit input, say x=[[1,3],[1]]
ṁ▲ Sum of maxima: 4
oŀ Lowered range: r=[0,1,2,3]
ṠṀ For each list in x,
Ṫ+ create addition table with r: [[[1,3],[2,4],[3,5],[4,6]],
[[1],[2],[3],[4]]]
F×+ Reduce by concatenating all combinations: [[1,3,1],[1,3,2],...,[4,6,4]]
V 1-based index of first list y
ŀ whose list of 1-based indices [1,2,...,length(y)]
§= is equal to
O y sorted: 2
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
FLḶ0ẋ;þ⁸ŒpS€P€1e
```
A monadic link taking a list of lists of ones and zeros returning either `1` (truthy) or `0` (falsey).
**[Try it online!](https://tio.run/##y0rNyan8/9/N5@GObQYPd3VbH973qHHH0UkFwY@a1gQAsWHq////o6MNdQx0DGN1kGjD2FgA "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8/9/N5@GObQYPd3VbH973qHHH0UkFwY@a1gQAsWHqf5fD7UDG///R0YYGhrE6XAogWkfBEMoGsgwQ4mAuTArGNzBE6IRohUkYwLVCdSAMhQqAVEMIFLvhCuBchA1QKwygViDEoSIwN8YCAA "Jelly – Try It Online") (shortened - first 6 falseys followed by first eight truthys since the length four ones take too long to include due to the use of the Cartesian product).
### How?
```
FLḶ0ẋ;þ⁸ŒpS€P€1e - Link: list of lists, tiles
F - flatten (the list of tiles into a single list)
L - length (gets the total number of 1s and zeros in the tiles)
Ḷ - lowered range = [0,1,2,...,that-1] (how many zeros to try to prepend)
0 - literal zero
ẋ - repeat = [[],[0],[0,0],...[0,0,...,0]] (the zeros to prepend)
⁸ - chain's left argument, tiles
þ - outer product with:
; - concatenation (make a list of all of the zero-prepended versions)
Œp - Cartesian product (all ways that could be chosen, including man
- redundant ones like prepending n-1 zeros to every tile)
S€ - sum €ach (good yielding list of only ones)
P€ - product of €ach (good yielding 1, others yielding 0 or >1)
1 - literal one
e - exists in that? (1 if so 0 if not)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 159 bytes
```
lambda x:g([0]*sum(map(sum,x)),x)
g=lambda z,x:x and any(g([a|x[0][j-l]if-1<j-l<len(x[0])else a for j,a in enumerate(z)],x[1:])for l in range(len(z)))or all(z)
```
[Try it online!](https://tio.run/##VUxLCoMwEN17iixnSgTTpehJ0iymGK0So/iBKL17mqAtlmF@7zduy2uwd1@XD2@of1bEXN6AzNRtXnvoaYSwuUMMnTTlqdm5yx0jW4XeIOjp7YJHdqlRbZ2KIhyF0RYiitrMmhGrh4l1nFhrmbZrrydaNOyouJMiVxhpE8mJbKMhundEDCgZE04/Tq1doAYpBRc843EKxZmMz1Hn@0OFUojJ1XhVHRn/CdnF/A3wHw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
FLḶ0ẋ;þµŒpSP$€1e
```
[Try it online!](https://tio.run/##y0rNyan8/9/N5@GObQYPd3VbH953aOvRSQXBASqPmtYYpv53Odx@dNLDnTNA3Mj//6OjDQ0MY3W4FEC0joIhlA1kGSDEwVyYFIxvYIjQCdEKkzCAa4XqQBgKFQCphhAodsMVwLkIG6BWGECtQIhDRWBujAUA "Jelly – Try It Online")
-1 byte thanks to Mr. Xcoder
I developed this completely independently of Jonathan Allan but now looking at his is exactly the same:
[Answer]
# [J](http://jsoftware.com/), 74 bytes
```
f=:3 :'*+/1=*/"1+/"2(l{."1 b)|.~"1 0"_ 1>,{($,y)#<i.l=:+/+/b=:>,.&.":&.>y'
```
I might try to make it tacit later, but for now it's an explicit verb. I'll explain the ungolfed version. It takes a list of boxed integers and returns `1` (truthy) or `0` (falsy).
```
This will be my test case, a list of boxed integers:
]a=:100001; 1001; 1011
┌──────┬────┬────┐
│100001│1001│1011│
└──────┴────┴────┘
b is the rectangular array from the input, binary digits. Shorter numbers are padded
with trailing zeroes:
]b =: > ,. &. ": &.> a NB. Unbox each number, convert it to a list of digits
1 0 0 0 0 1
1 0 0 1 0 0
1 0 1 1 0 0
l is the total number of 1s in the array:
]l=: +/ +/ b NB. add up all rows, find the sum of the resulting row)
7
r contains all possible offsets needed for rotations of each row:
r=: > , { ($,a) # < i.l NB. a catalogue of all triplets (in this case, the list
has 3 items) containing the offsets from 0 to l:
0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
...
6 6 3
6 6 4
6 6 5
6 6 6
m is the array after all possible rotations of the rows of b by the offsets in r.
But I first extend each row of b to the total length l:
m=: r |."0 1"1 _ (l {."1 b) NB. rotate the extended rows of b with offsets in r,
ranks adjusted
For example 14-th row of the offsets array applied to b:
13{r
0 1 6
13{m
1 0 0 0 0 1 0
0 0 1 0 0 0 1
0 1 0 1 1 0 0
Finally I add the rows for each permutation, take the product to check if it's all 1, and
check if there is any 1 in each permuted array.
* +/ 1= */"1 +/"2 m
1
```
[Try it online!](https://tio.run/##ZVBJDsIwDLzziiigppsSG27pcuQF3BFFoIIqIbEcoiK@HtqmS5peYnvGnox91/qayR2RLIwEZqGgGAm69auaUyRF8OW/JgI9Eszj2t/EKlinN15lMhKRKDKZx9zjVHo8V0xfzuWDsMPz8y4VW3XVlaQ4ZTjmmJApb4v@mUDoALttRMDCwKAmtJVN9aCZsRmcc@CqNoLoCMPcMhjHA7GwhcO86Zvtwvan6qUYmQ4D7pb2nWDuzFlmgLofbQOJxTmHWXCdJqD@Aw "J – Try It Online")
] |
[Question]
[
# Where is the Arrow Pointing?
In this challenge, your goal is to follow an arrow and output the character it is pointing to.
## Examples
**Input:**
```
d S------+ b
|
|
c +--->a
```
**Output:** `a`
---
**Input:**
```
S-----+---a->c
|
V
b
```
**Output:** `b`
The arrow is not pointing at `c` because it is divided by the `a`, meaning this path never leads to an arrow head.
---
**Input:**
```
a S s
| |
V V
b c
```
**Output:** `b`
---
**Input:**
```
d s<+S+--V
||| Q
-++
```
**Output:** `Q`
This path starts at the `S`, goes down, to the right, goes up, to the right, then points down at the Q. Note that the path does not go straight from `S` to `+`.
---
**Input:**
```
d s-+ +-S +--+
+-->b | | |
| | +--+ |
+--+ A<----+
```
**Output:** `A`
---
**Input:**
```
S-----+
| +-^
+---+->B
+---^
```
**Output:** `B`
Because the valid line will never lead to a whitespace character. The only line that doesn't lead to a whitespace character leads to a `B`
# Challenge
The input will be a multi-line string in which you need to find the character the arrow is pointing at. **There will only be one valid arrow.** The valid arrow will *only* point to alphanumeric characters excluding `S`. A line will never overlap itself. e.g. `-|-`
* `S` (capital) represents where the arrow starts.
* `-` represents a horizontal line
* `+` represents a possible change in axis. A valid arrow will never start with a `+`.
* `|` represents a vertical line
* `> < V ^` any of these represent the arrow head. These will never connect to a `+`.
There will only be one `S` in the string. The input will also be padded to be a rectangle (not necessarily a square).
[Answer]
# JavaScript (ES6), 195 ~~245 231 242 246 250~~
**Edit4** Now, a single recursive function. Probably can't be golfed more
**Edit3** Test for straight line and test for arrowhead merged in T function, S and H functions removed.
**Edit2** Revised and longer :( after [this](https://codegolf.stackexchange.com/questions/57952/where-is-the-arrow-pointing?noredirect=1#comment140764_57952) this clarification
**Edit** Small improvements, cutting some char here and there, waiting for CJammers to step in
Test running the snippet below in an EcmaScript 6 compliant browser. (works on Firefox. Chrome still missing the spread operator `...`)
```
f=(s,p=s[I='indexOf']`S`,w=m=[o=~s[I]`
`,1,-o,-1],q,v,r)=>m.some((d,i)=>{for(v=w,q=p;r=s[q+=d],r=='|-'[i&1];)v='+';return r=r==v?f(s,q,v):/\w/.test(r=s[q+m['^>V<'[I](r)]])&&r},s=[...s],s[p]=0)&&r
// Less golfed
// U: recursive scan function
U = (s, // input string or array
p = s.indexOf`S`, // current position, defult to position of S into string (at first call)
w = // char to compare looking for a '+', at first call default to garbage as you can't follow '+' near 'S'
m = [// m, global, offset array form movements.
o = ~s.indexOf`\n`, // o, global, row line +1 (negated)
1, -o, -1], // complete the values of m array
// m and o are assigned again and again at each recursive call, but that is harmless
// params working as local variables as the function is recursive
q,v,r) =>
{
s = [...s]; //convert to array, as I have to modify it while scanning
//the conversion is done again and again at each recursive call, but that is harmless
s[p] = 0; // make s[p] invalid to avoid bouncing back and forth
m.some( // for each direction, stop if endpoint found
(d,i ) => {
q = p; // start at current position, then will add the offset relative to current direction
v = w; // for each direction, assign the starting value that can be '+' or garbage at first call
// compare char at next position with the expected char based on direction (- for horiz, | for vertical)
// in m array, values at even positon are vertical movements, odds are horizontal
while (s[q+=d] == '|-'[i&1]) // while straight direction, follow it until it ends
v = '+'; // from now on '+' is allowed
r = s[q];
if (r == v) // check if found a '+'
r = U(s, q, v) // recursive call to check all directions from current position
else
{
r = s[q + m['^>V<'.indexOf(r)]], // pointed char in p (if arrowhead, else will return undefined)
r = /\w/.test(r) && r // if alphanumeric, then we found our result - else r = false
}
return r; // returning r to .some; if r is truthy, the .some function will stop
}
)
return r; // result if found, else undefined or null
}
// TEST
out=x=>O.innerHTML+=x.replace(/</g,'<')+'\n'
// Using explicit newlines '\n' to ensure the padding to a rectangle
;[
['z<+S-+->a','a']
,['a<-+S>b','b']
,['S-+\n |\n V\n a','a']
,['a S s\n | |\n V V\n b c ','b']
,['S-----+ \n| +-^ \n+---+->B \n +---^','B']
,['d s<+S+--V\n ||| Q\n -++ ','Q']
,['d s-+ +-S +--+\n +-->b | | |\n | | +--+ |\n +--+ A<----+ ','A']
,['S-----+ \n| +-^ \n+---+->B \n +---^ ','B']
].forEach(t=>{
r=f(t[0])
k=t[1]
out('Test '+(r==k?'OK':'Fail')+'\n'+t[0]+'\nResult: '+ r +'\nCheck: '+k+'\n')
})
```
```
<pre id=O></pre>
```
[Answer]
## JavaScript 2016, ~~264 263 249 240 235~~ 234 bytes
Run it in Firefox:
```
m=l=>{o=(q,e)=>q.indexOf(e)
s=[-1,1,c=~o(l,`
`),-c]
f=i=>!o[i]&(!(r=l[i+s[o(a="<>^V",o[i]=c=l[i])]])|r<"0"|r>"z"|r=="S"||alert(s=r))&&c&&[for(j of (c!='+'?a:"")+"-|+")for(k of s)l[i+k]!=j|~o(l[i]+j,k*k>1?"-":"|")||f(i+k)]
f(o(l,'S'))}
```
---
```
m(`d s-+ +-S +--+
+-->b | | |
| | +--+ |
+--+ A<----+`)
```
---
Scattered in some of my notes:
```
m=l=>{o=(q,e)=>q.indexOf(e) //shorthand for indexOf
s=[-1,1,c=o(l,`
`)+1,-c] // get all possible moves in 1d
w=[] // to keep track of the already-visited indexes
f=i=>{c=l[i] // current character
if(!w[i]&&c) // only continue if the index wasn't already visited and we aren't out of bounds
{r=l[i+s[o(a="<>^V",w[i]=c)]] // sets w[i] to a truthy value and maps the arrows to their corresponding moves in s. If c is an arrow, r is the character it's pointing to.
if(!r||r<"0"||r>"z"||r=="S"||alert(r)) // if r is an alphanumeric character that isn't r, show it and return. If not, continue.
for(j of (c!='+'?a:"")+"-|+") // iterate over all characters to make sure plusses are checked out last, which is necessary at the start.
for(k of s) // check out all possible moves
l[i+k]!=j|| // check if the move leads to the character we're looking for
~o(l[i]+j,k*k>1?"-":"|")|| // make sure the current nor that character goes against the direction of the move
f(i+k)}} // make the move, end of f
f(o(l,'S'))} // start at S
```
[Answer]
**VBA Excel 2007, 894 bytes**
Well this started out a lot better then it ended. I have a feeling my logic is flawed and i could have saved a tonne of bytes if i reordered some of my logic, But Too much time has been sunk into this already =P
The input for this is Column A of whatever sheet you are on. This method uses the fact that Excel has this nice grid and Breaks everything out so you can see what it is doing more clearly.
`Sub m()` is just taking the Copy pasted data from Column A and Breaking it out by char. If We allow a Modified input then if you preformat the maze into 1 char per cell you can save a few bytes by removing `sub m()`
Paste a Maze into Excel any size upto 99 rows by 27 char across. If you want bigger mazes its only 2 extra Bytes to increase the scope to 999 rows and ZZ columns
Also might need a judges call on whether a Excel Sheet is Valid "Standard Input" for a VBA answer. If not, Its pretty much impossible to give VBA Multi-line input VIA the Immediate window
To run this code just paste this code into a Excel module, Paste a maze into A1 and run `sub j()`
```
Sub m()
For k=1 To 99
u=Cells(k,1).Value
For i=1 To Len(u)
Cells(k,i+1).Value=Mid(u,i,1)
Next
Next
Columns(1).Delete
End Sub
Sub j()
m
With Range("A:Z").Find("S",,,,,,1)
h .row,.Column,0
End With
End Sub
Sub h(r,c,t)
If t<>1 Then l r-1,c,1,0,r
If t<>-1 Then l r+1,c,-1,0,r
If t<>2 Then l r,c-1,2,0,r
If t<>-2 Then l r,c+1,-2,0,r
End Sub
Sub l(r,c,y,p,i)
On Error GoTo w
q=Cells(r,c).Text
If q="V" Or q="^" Or q="<" Or q=">" Then
p=1
End If
f="[^V<>]"
If p=1 And q Like "[0-9A-UW-Za-z]" Then
MsgBox q: End
Else
If q="^" Then p=1: GoTo t
If q="V" Then p=1: GoTo g
If q="<" Then p=1: GoTo b
If q=">" Then p=1: GoTo n
Select Case y
Case 1
t:If q="|" Or q Like f Then l r-1,c,y,p,q
Case -1
g:If q="|" Or q Like f Then l r+1,c,y,p,q
Case 2
b:If q="-" Or q Like f Then l r,c-1,y,p,q
Case -2
n:If q="-" Or q Like f Then l r,c+1,y,p,q
End Select
If q="+" And i<>"S" Then h r,c,y*-1
p=0
End If
w:
End Sub
```
[Answer]
# Python 3, 349 bytes
Ugh, so many bytes.
```
S=input().split('\n')
Q=[[S[0].find('S'),0]]
D=[[1,0],[0,1],[-1,0],[0,-1]]
A='-S--++-'
B='|S||++|'
P='>V<^'
i=0
while D:
a,b=Q[i];i+=1
j=S[b][a]
for x,y in D:
try:
c,d=a+x,b+y;k=S[d][c]
if k in P:
z=P.index(k);print(S[d+D[z][1]][c+D[z][0]]);D=[]
if (j+k in A and x)+(j+k in B and y)*~([c,d]in Q):Q+=[[c,d]]
except IndexError: pass
```
Essentially a breadth-first search. Bonus: this actually exits gracefully instead of using `exit()`, which is longer anyway.
[Answer]
# Perl 5
The solution turned out longer than other solutions.
Even after golfing it. So this is the ungolfed version.
It prints the map so that you can follow the cursor.
The way it works? At each step it puts possible moves on the stack.
And it keeps on running till there's nothing left on the stack, or a solution is found.
It can be easily modified to find all solutions and choose the nearest --> while(@\_){...
```
while(<>){
chomp;
@R=split//;
$j++;$i=0;
for(@R){$nr++;$i++;$A[$i][$j]=$_;if('S'eq$_){$x=$i;$y=$j}}
$xm=$i,if$xm<$i;$ym=$j;
}
push(@_,[($x,$y,'S',0)]);
$cr='';
while(@_&&''eq$cr){
@C=pop@_;
($x,$y,$d,$n)=($C[0]->[0],$C[0]->[1],$C[0]->[2],$C[0]->[3]);
$c=$A[$x][$y];
$A[$x][$y]='.';
if($c=~m/[S+]/){
if('L'ne$d&&$A[$x+1][$y]=~m/[+-]/){push(@_,[($x+1,$y,'R',$n+1)])}
if('D'ne$d&&$A[$x][$y-1]=~m/[+|]/){push(@_,[($x,$y-1,'U',$n+1)])}
if('R'ne$d&&$A[$x-1][$y]=~m/[+-]/){push(@_,[($x-1,$y,'L',$n+1)])}
if('U'ne$d&&$A[$x][$y+1]=~m/[+|]/){push(@_,[($x,$y+1,'D',$n+1)])}
}
if($c eq'|'){
if($d ne'U'&&$A[$x][$y+1]=~m/[+|<>^V]/){push(@_,[($x,$y+1,'D',$n+1)])}
if($d ne'D'&&$A[$x][$y-1]=~m/[+|<>^V]/){push(@_,[($x,$y-1,'U',$n+1)])}
}
if($c eq'-'){
if($d ne'L'&&$A[$x+1][$y]=~m/[+-<>^V]/){push(@_,[($x+1,$y,'R',$n+1)])}
if($d ne'R'&&$A[$x-1][$y]=~m/[+-<>^V]/){push(@_,[($x-1,$y,'L',$n+1)])}
}
if($c=~m/[<>^V]/&&$n<$nr){
if($c eq'>'&&$A[$x+1][$y]=~m/\w/){$cr=$A[$x+1][$y];$nr=$n}
if($c eq'<'&&$A[$x-1][$y]=~m/\w/){$cr=$A[$x-1][$y];$nr=$n}
if($c eq'V'&&$A[$x][$y+1]=~m/\w/){$cr=$A[$x][$y+1];$nr=$n}
if($c eq'^'&&$A[$x][$y-1]=~m/\w/){$cr=$A[$x][$y-1];$nr=$n}
}
print_map()
}
print "$cr\n";
sub print_map {
print "\033[2J"; #clearscreen
print "\033[0;0H"; #cursor at 0,0
for$j(1..$ym){for$i(1..$xm){print (($x==$i&&$y==$j)?'X':$A[$i][$j])}print"\n"}
sleep 1;
}
```
### Test
```
$ cat test_arrows6.txt
S-----+
| +-^
+---+->B
+---^
$ perl arrows.pl < test_arrows6.txt
.-----+
. +-^
......XB
.....
B
```
[Answer]
PHP version (comments are french, sorry)
```
<?php
/*
* By Gnieark https://blog-du-grouik.tinad.fr oct 2015
* Anwser to "code golf" http://codegolf.stackexchange.com/questions/57952/where-is-the-arrow-pointing in PHP
*/
//ouvrir le fichier contenant la "carte et l'envoyer dans un array 2 dimmension
$mapLines=explode("\n",file_get_contents('./input.txt'));
$i=0;
foreach($mapLines as $ligne){
$map[$i]=str_split($ligne,1);
if((!isset($y)) && in_array('S',$map[$i])){
//tant qu'à parcourir la carte, on cherche le "S" s'il n'a pas déjà été trouvé.
$y=$i;
$x=array_search('S',$map[$i]);
}
$i++;
}
if(!isset($y)){
echo "Il n'y a pas de départ S dans ce parcours";
die;
}
echo "\n".file_get_contents('./input.txt')."\nLe départ est aux positions ".$map[$y][$x]." [".$x.",".$y."]. Démarrage du script...\n";
$previousX=-1; // Contiendra l'ordonnée de la position précédente. (pour le moment, une valeur incohérente)
$previousY=-1; // Contiendra l'absycede la position précédente. (pour le moment, une valeur incohérente)
$xMax=count($map[0]) -1;
$yMax=count($map) -1;
$previousCrosses=array(); //On ne gardera en mémoire que les croisements, pas l'ensemble du chemin.
while(1==1){ // C'est un défi de codagee, pas un script qui sera en prod. j'assume.
switch($map[$y][$x]){
case "S":
//même fonction que "+"
case "+":
//on peut aller dans les 4 directions
$target=whereToGoAfterCross($x,$y,$previousX,$previousY);
if($target){
go($target[0],$target[1]);
}else{
goToPreviousCross();
}
break;
case "s":
goToPreviousCross();
break;
case "-":
//déplacement horizontal
if($previousX < $x){
//vers la droite
$targetX=$x+1;
if(in_array($map[$y][$targetX],array('-','+','S','>','^','V'))){
go($targetX,$y);
}else{
//On est dans un cul de sac
goToPreviousCross();
}
}else{
//vers la gauche
$targetX=$x-1;
if(in_array($map[$y][$targetX],array('-','+','S','<','^','V'))){
go($targetX,$y);
}else{
//On est dans un cul de sac
goToPreviousCross();
}
}
break;
case "|":
//déplacement vertical
if($previousY < $y){
//on descend (/!\ y augmente vers le bas de la carte)
$targetY=$y+1;
if(in_array($map[$targetY][$x],array('|','+','S','>','<','V'))){
go ($x,$targetY);
}else{
goToPreviousCross();
}
}else{
//on Monte (/!\ y augmente vers le bas de la carte)
$targetY=$y - 1;
if(in_array($map[$targetY][$x],array('|','+','S','>','<','V'))){
go ($x,$targetY);
}else{
goToPreviousCross();
}
}
break;
case "^":
case "V":
case ">":
case "<":
wheAreOnAnArrow($map[$y][$x]);
break;
}
}
function wheAreOnAnArrow($arrow){
global $x,$y,$xMax,$yMax,$map;
switch($arrow){
case "^":
$targetX=$x;
$targetY=$y -1;
$charsOfTheLoose=array(" ","V","-","s");
break;
case "V":
$targetX=$x;
$targetY=$y + 1;
$charsOfTheLoose=array(" ","^","-","s");
break;
case ">":
$targetX=$x + 1;
$targetY=$y;
$charsOfTheLoose=array(" ","<","|","s");
break;
case "<":
$targetX=$x - 1;
$targetY=$y;
$charsOfTheLoose=array(" ",">","|","s");
break;
default:
break;
}
if(($targetX <0) OR ($targetY<0) OR ($targetX>$xMax) OR ($targetY>$yMax) OR (in_array($map[$targetY][$targetX],$charsOfTheLoose))){
//on sort du cadre ou on tombe sur un caractere inadapté
goToPreviousCross();
}else{
if(preg_match("/^[a-z]$/",strtolower($map[$targetY][$targetX]))){
//WIN
echo "WIN: ".$map[$targetY][$targetX]."\n";
die;
}else{
//on va sur la cible
go($targetX,$targetY);
}
}
}
function whereToGoAfterCross($xCross,$yCross,$previousX,$previousY){
//haut
if(canGoAfterCross($xCross,$yCross +1 ,$xCross,$yCross,$previousX,$previousY)){
return array($xCross,$yCross +1);
}elseif(canGoAfterCross($xCross,$yCross -1 ,$xCross,$yCross,$previousX,$previousY)){
//bas
return array($xCross,$yCross -1);
}elseif(canGoAfterCross($xCross-1,$yCross,$xCross,$yCross,$previousX,$previousY)){
//gauche
return array($xCross-1,$yCross);
}elseif(canGoAfterCross($xCross+1,$yCross,$xCross,$yCross,$previousX,$previousY)){
//droite
return array($xCross+1,$yCross);
}else{
//pas de direction possible
return false;
}
}
function canGoAfterCross($xTo,$yTo,$xNow,$yNow,$xPrevious,$yPrevious){
global $previousCrosses,$xMax,$yMax,$map;
if(($xTo < 0) OR ($yTo < 0) OR ($xTo >= $xMax) OR ($yTo >= $yMax)){return false;}// ça sort des limites de la carte
if(
($map[$yTo][$xTo]==" ") // on ne va pas sur un caractere vide
OR (($xTo==$xPrevious)&&($yTo==$yPrevious)) //on ne peut pas revenir sur nos pas (enfin, ça ne servirait à rien dans cet algo)
OR (($xTo==$xNow)&&($map[$yTo][$xTo]=="-")) //Déplacement vertical, le caractere suivant ne peut etre "-"
OR (($yTo==$yNow)&&($map[$yTo][$xTo]=="|")) // Déplacement horizontal, le caractère suivant ne peut être "|"
OR ((isset($previousCrosses[$xNow."-".$yNow])) && (in_array($xTo."-".$yTo,$previousCrosses[$xNow."-".$yNow]))) //croisement, ne pas prendre une direction déjà prise
){
return false;
}
return true;
}
function go($targetX,$targetY){
global $previousX,$previousY,$x,$y,$previousCrosses,$map;
if(($map[$y][$x]=='S')OR ($map[$y][$x]=='+')){
//on enregistre le croisement dans lequel on renseigne la direction prise et la direction d'origine
$previousCrosses[$x."-".$y][]=$previousX."-".$previousY;
$previousCrosses[$x."-".$y][]=$targetX."-".$targetY;
}
$previousX=$x;
$previousY=$y;
$x=$targetX;
$y=$targetY;
//debug
echo "deplacement en ".$x.";".$y."\n";
}
function goToPreviousCross(){
global $x,$y,$previousX,$previousY,$xMax,$yMax,$previousCrosses;
/*
* On va remonter aux précédents croisements jusqu'à ce
* qu'un nouveau chemin soit exploitable
*/
foreach($previousCrosses as $key => $croisement){
list($crossX,$crossY)=explode("-",$key);
$cross=whereToGoAfterCross($crossX,$crossY,-1,-1);
if($cross){
go($crossX,$crossY);
return true;
}
}
//si on arrive là c'est qu'on est bloqués
echo "Aucun chemin n'est possible\n";
die;
}
```
[Answer]
# Haskell, 268 bytes
Congratulations to the Javascripters! Gave up the bounty, but here is what I got. May/Might not work in all cases, but actually handles arrows starting in and arrowheads conncting to `+`es, as far as I know. Didn't even include searching for the `S`, is just `(0,0)` for now.
```
import Data.List
x%m=length m<=x||x<0
a s(x,y)z|y%s||x%(head s)=[]|0<1=b s(x,y)z$s!!y!!x
b s(x,y)z c|g c>[]=filter(>' ')$concat[a s(x+i k,y+i(3-k))k|k<-g c,k-z`mod`4/=2]|0<1=[c]
i=([0,-1,0,1]!!)
g c=findIndices(c`elem`)$words$"V|+S <-+S ^|+S >-+S"
f s=a(lines s)(0,0)0
```
[Answer]
I would like to see an APL version in spirit of <https://www.youtube.com/watch?v=a9xAKttWgP4>
As a start, a vectorized Julia solution which I think can be translated 1:0.3 to APL or J. It takes a string R representing a L x K arrowgram. It first translates the matrix of symbols into a matrix of small 3x3 matrices whose patterns are the binary expansions of the letters of the string "\0\x18\fH\t]]\x1cI". For example '+' is encoded as reshape([0,digits(int(']'),2,8)],3,3)
```
0 2 0
2 2 2
0 2 0
```
In this representation, the path consists of 2's and gets flooded by 3's from the starting point.
```
A=zeros(Int,L*3+3,K*3+3)
s(i,j=i,n=2)=A[i:end+i-n,j:end+j-n]
Q=Int['A':'Z';'a':'z']
for k=0:K-1,l=0:L-1
r=R[K*l+k+1]
q=search(b"V^><+S|-",r)
d=reverse(digits(b"\0\x18\fH\t]]\x1cI"[q+1],2,8))
A[1+3l:3l+3,1+3k:3k+3]=2*[d;0]
A[3l+2,3k+2]+=r*(r in Q&&r!='V'&&r!='^')+(1-r)*(r=='S')+3(5>q>0)
end
m=0
while sum(A)>m
m=sum(A)
for i=0:1,j=1:2,(f,t)=[(3,6),(11,15)]
A[j:end+j-2,j:end+j-2]=max(s(j),f*(s(j).*s(2-i,1+i).==t))
end
end
for i=[1,4],k=Q
any(s(1,1,5).*s(5-i,i,5).==11*k)&&println(Char(k))
end
```
To test,
```
R=b"""
d S------+ b
|
|
c +--->a
""";
K=search(R,'\n') # dimensions
L=div(endof(R),K)
include("arrow.jl")
a
```
By the way, I think the clause "Another + may be adjacent but the arrow should prioritize going on a - or | first." puts a vector approach at a disadvantage. Anyway, I just ignored it.
] |
[Question]
[
A move sequence is a sequence of moves (turns) on a Rubik's Cube (for the notation look down below). Beside the empty move sequence, there are many other other move sequences, that have no effect on the cube at all. We call these move sequences identity sequences.
Some of these identity sequences are obvious to determine, like `U2 R R' U2` or `U D2 U' D2`. In the first one, two random moves are done `U2 R` and afterwards immediately undone `R' U2`. The second one is similar. First two random moves `U D2` and afterwards they are undone, but in reversed order `U' D2`. This only works, because the move `U` effects only the pieces of the upper layer and the move `D2` only effects pieces of the lower layer. You can see a visualization of these two move sequences.
![U2 R R' U2](https://i.stack.imgur.com/9NxNf.gif) ![U D2 U' D2](https://i.stack.imgur.com/g4SbI.gif)
Other identity sequences may be not obvious at all. For instance the sequence `R' U' R' F' U F U' R' F R F' U' R U2 R`. It pretty long, but also has no effect at the cube at all.
![enter image description here](https://i.stack.imgur.com/5doGQ.gif)
## Move Notation
A move describes the turn of one layer of one of the six faces of the cube. A move consist of one letter representing the face followed by an optional suffix representing the turn angle.
The letters and their corresponding faces are **U** (Up - the side facing upwards), **D** (Down - the side facing downwards), **R** (Right - the side facing to the right), **L** (Left - the side facing to the left), **F** (Front - the side facing you) and **B** (Back - the side facing away from you).
If there is no suffix, the face is turned 90-degree clockwise, the suffix **`'`** means, the face is turned 90-degree counterclockwise, and the suffix **`2`** means, the face is turned 180-degree clockwise.
It you have any problems with the notation, just use [http://alg.cubing.net](http://alg.cubing.net/), where you can visualize such move sequences.
## The Challenge
Your task is to write a program, that determines if a move sequences is an identity or not.
You may write a full program or a function. It should receive a string containing a move sequence (moves are separate by spaces) as input (via STDIN, command-line argument, prompt or function argument), and output (via return value or STDOUT) a Boolean value or a corresponding integer (True - 1 - identity sequence/ False - 0 - not identity sequence).
If you suffix `'` creates problems in your programming language, you may use a different symbol, but not at digit. `R F2 U3` is not allowed.
This is codegolf, therefore the shortest code (in bytes) wins.
## Test Cases
```
"" -> True
"U2 R R' U2" -> True
"U D2 U' D2" -> True
"U2 R U2 R'" -> False
"R' U' R' F' U F U' R' F R F' U' R U2 R" -> True
"L'" -> False
"B B2 B' B2" -> True
"D D2 D'" -> False
"R F' D2 U B' F2 B' U2 D2 F2 B2 U F R'" -> True
"D2 U' R2 U F2 D2 U' R2 U' B' L2 R' B' D2 U B2 L' D' R2" -> False
"R U R' U' R' F R2 U' R' U' R U R' F' R2 U R2 U' R2 U' D R2 U' R2 U R2 D'" -> True
"R U R' U' R' F R2 U' R' U' R U R' F' R2 U' R2 U R2 U' D R2 U' R2 U R2 D'" -> False
"B2 F2 U' F2 U R2 F2 U2 B D' R' D' R2 D' F2 U' F U R2 U R B D B D2 L2 D' F2 U D' R' D B R2 D2 F2 R' F2 D2" -> True
"R U2 R' U R' U2 R U2 R U R' U' R' U R U2" -> False
"U F B' R' U F' R U' F' B L U' F L'" -> False
"R2 U' R' U' R U R U R U' R" -> False
"R' F R' B2 R F' R' B2 R2" -> False
```
[Answer]
# Haskell, ~~263~~ ~~261~~ ~~247~~ 243 characters
```
c[x]=[x]
c(x:"2")=[x,x]
c(x:_)=[x,x,x]
s!a@[x,y,z]=case s of
'R'|x>0->[x,-z,y]
'B'|y>0->[z,y,-x]
'U'|z>0->[-y,x,z]
'L'|x<0->[x,z,-y]
'F'|y<0->[-z,y,x]
'D'|z<0->[y,-x,z]
_->a
r=[-2..2]
i=mapM id[r,r,r]
f w=i==foldr(map.(!))i(c=<<words w)
```
Rather straightworward algorithm; each cubelet is made out of 1,2,4 or 8 chunks encoding its position and orientation; 4 chunks per edge cubelet, 8 per corner cubelet, 7 cubelets are stationary.
`c` **c**homps each word of the input into a sequence of CW turns, and `!` sends each chunk according to a turn. `i` is the **i**dentity position. `f` is the main **f**unction.
I'm not too happy with the `c`homp function, but I can't seem to find a way to shorten it either (@Nimi did, however)
[Answer]
# [Cubically](//git.io/Cubically), ~~6~~ 4 bytes
```
¶=8%
```
I win :P
```
¶=8%
¶ read a string, evaluate as Cubically code
=8 set notepad to (notepad == 8th face)
% print notepad
```
The notepad is initialized to zero. The 8th "face" contains 1 if the cube is unsolved and 0 otherwise.
[Try it online!](https://tio.run/##Sy5NykxOzMmp/P//0DZbC9X//0ONFIIUgtQVQo0A)
[Answer]
## J - 232, 220, 381, 315 296 bytes
This solution encodes all operations as face permutations and works based on the fact that all face twists are actually the same, under a rotation of the entire cube.
*Edit*: some more golfing
```
f=:+/~6&*
r=:4 :'y f&.>(]{^:x~)&.C.;/i.2 4'"0
t=:((r~0),_4<\44#.inv 1478253772705907911x)&C.&.
Y=:(C.(,0 2 r 4 5),;/4 f&i.8)&{^:t
X=:((,1 1 0 2 r 2 4 3 1)C.C.;/0 4 2 5 f i.8)&{^:t
61".@A."1'=: ',"#~6 3$'D0XR1YF1XU2YB3XL3Y'
T=:[:(_2".@}.'(i.48)-:'&(,,[))[:(,'^:',])/&.>@|.&.;:[:''''&=@{.`]},:&'3'
```
Other than the previous tries, this *does* take corner rotation into account.
`f` is just a helper function. `r` does the rotation of one face. a face is encoded as follows:
1. all corners in steps of 6
2. all edges in steps of six
this order facilitates the encoding of rotations and twists.
`t` is an adverb that twists the face under a certain cube rotation, selecting the face.
`X` and `Y` are adverbs which take as left argument the number of in that direction of the entire cube.
The next line defines all rotations: 3 characters per rotation: the name, the number of rotations and the direction.
The last line defines the test verb `T`, converting 3 and `'` to Power notation, flipping the order of operation appending the test vector andfinally excuting the entire thing.
More details upon request.
```
tests =: (] ;. _2) 0 : 0
U2 R R' U2
U D2 U' D2
U2 R2 R'
R' U' R' F' U F U' R' F R F' U' R U2 R
L'
B B2 B' B2
D D2 D'
R F' D2 U B' F2 B' U2 D2 F2 B2 U F R'
D2 U' R2 U F2 D2 U' R2 U' B' L2 R' B' D2 U B2 L' D' R2
R U R' U' R' F R2 U' R' U' R U R' F' R2 U R2 U' R2 U' D R2 U' R2 U R2 D'
R U R' U' R' F R2 U' R' U' R U R' F' R2 U' R2 U R2 U' D R2 U' R2 U R2 D'
B2 F2 U' F2 U R2 F2 U2 B D' R' D' R2 D' F2 U' F U R2 U R B D B D2 L2 D' F2 U D' R' D B R2 D2 F2 R' F2 D2
R U2 R' U R' U2 R U2 R U R' U' R' U R U2
U F B' R' U F' R U' F' B L U' F L'
R2 U' R' U' R U R U R U' R
R' F R' B2 R F' R' B2 R2
)
res =: 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0
res ([,],:=) T"1 tests NB. passes all tests.
1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0
1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
NB. some handy display methods:
dispOrig=: (". ;._2) 0 :0
_ _ _ 5 29 11 _ _ _ _ _ _
_ _ _ 47 _1 35 _ _ _ _ _ _
_ _ _ 23 41 17 _ _ _ _ _ _
3 27 9 0 24 6 1 25 7 2 26 8
45 _3 33 42 _6 30 43 _5 31 44 _4 32
21 39 15 18 36 12 19 37 13 20 38 14
_ _ _ 4 28 10 _ _ _ _ _ _
_ _ _ 46 _2 34 _ _ _ _ _ _
_ _ _ 22 40 16 _ _ _ _ _ _
)
ind =: dispOrig i.&, i. 48 NB. indices of i.48 in the original display
disp =: (9 12$(,dispOrig) ind}~ ])
changed =: 1 : '(u ~:&disp ]) i.48' NB. use to debug permutation verbs: L ch
vch =: 1 :'disp ((]+_*=) u)'
NB. viewmat integration RGB
cm =: 255 * 1 0 0 , 1 1 1, 0 1 0, 1 1 0, 1 0.5 0, 0 0 1,: 0 0 0 NB. colormap
NB. use as: "cube i. 48" for seeing a nice folded out cube.
cube =: cm viewmat (>&7 + >&15 + >&23 + >&31 + >& 39 + >&47)@|@disp@]
```
[Answer]
# Python 3: 280 chars
This is not a participant in the challenge. Firstly because I asked the challenge myself and secondly because it's not my code. All credits belong to [Stefan Pochmann](http://www.stefan-pochmann.info/), who discovered this awesome way of simulating a Rubik's Cube. I only did some golfing and some minor changes in respect of the challenge.
```
def f(a):
s=t="UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR".split()
for m in a.split():q="FLBR FRBL FDBU FUBD URDL ULDR".split()['UDLRFB'.index(m[0])];n=2+"2'".find(m[-1]);s=[[p,p.translate(str.maketrans(q,q[n:]+q[:n]))][m[0]in p]for p in s]
return s==t
```
The idea behind this is the following. `s` represents the location of the pieces of `UF`, `UR`, and so on. For instance: `s = ['DF', 'BL', ...]` means, that the piece `UF` is at the position `DF`, the piece `UR` is at the position `BL`, ...
How does the position of a piece change, when doing a move. If you do a `U`-move, all stickers (colors) of the `U`-layer, which faced the front face, move to the left face. The stickers of the left face move to the back, these to the right and these to the front face. Encoded by `FLBR`. Some examples: `UF` moves to `UL`, `UFR` moves to `ULF` and so on. Therefore, applying a move is simply translating the faces of pieces in the corresponding layer.
] |
[Question]
[
[Nontransitive dice](http://en.wikipedia.org/wiki/Nontransitive_dice) are nice little toys that defy our intuition in probability theory. We'll need a few definitions for this challenge:
Consider two dice *A* and *B* which are thrown at the same time. We say that *A* **beats** *B* if the probability of *A* showing a larger number than *B* is strictly greater than the probability of *B* showing a larger number than *A*.
Now consider a set of three dice, with labels *A*, *B*, *C*. Such a set of dice is called **nontransitive** if
* either *A* beats *B*, *B* beats *C* and *C* beats *A*
* or *C* beats *B*, *B* beats *A* and *A* beats *C*.
As one of my favourite examples, consider the [Grime dice](http://singingbanana.com/dice/article.htm), which have the following sides:
```
A: 3 3 3 3 3 6
B: 2 2 2 5 5 5
C: 1 4 4 4 4 4
```
Interestingly, the mean of each die is 3.5, just like a regular die.
One can show that:
* *A* beats *B* with a probability of 7/12.
* *B* beats *C* with a probability of 7/12.
* *C* beats *A* with a probability of 25/36.
Now these particular dice are even weirder. If we roll each die twice and add up the results, the order of which beats which gets reversed:
* *B* beats *A* with a probability of 85/144.
* *C* beats *B* with a probability of 85/144.
* *A* beats *C* with a probability of 671/1296.
Let's call a set of dice with this property **Grime-nontransitive**.
On the other hand, if the dice retain their original cycle when using two throws, we call them **strongly nontransitive**. (If there is no cycle at all for two throws, we simply call them *nontransitive*.)
## The Challenge
Given three six-sided dice, determine which of the above properties this set has, and output one of the following strings: `none`, `nontransitive`, `Grime-nontransitive`, `strongly nontransitive`.
You may write a program or function, take input via STDIN, command-line argument, prompt or function argument, and write the result to STDOUT or return it as a string.
You may assume that all sides are non-negative integers. You cannot assume that the sides or the dice are in any particular order. You can take input in any convenient list or string format.
This is code golf, so the shortest answer (in bytes) wins.
## Test Cases
```
none
1 2 3 4 5 6, 6 5 4 3 2 1, 1 3 5 2 4 6
1 1 1 6 6 6, 4 4 4 5 5 5, 5 5 5 5 5 5
1 1 2 5 6 6, 2 2 3 4 4 6, 2 3 3 4 4 5
0 1 2 3 4 5, 1 1 2 3 3 5, 1 2 2 2 3 5
3 13 5 7 13 7, 5 7 11 5 7 13, 5 9 13 5 7 9
nontransitive
1 2 2 4 6 6, 1 2 3 5 5 5, 2 3 4 4 4 4
1 4 4 4 4 4, 2 2 2 4 5 6, 2 3 3 3 5 5
1 2 1 6 5 6, 3 1 3 6 2 6, 2 4 2 4 4 5
3 4 6 6 7 7, 4 4 4 7 7 7, 5 5 5 5 6 7
2 5 11 11 14 14, 5 5 5 14 14 14, 8 8 8 8 8 17
Grime-nontransitive
3 3 3 3 3 6, 2 2 2 5 5 5, 1 4 4 4 4 4
1 1 4 5 5 5, 2 2 2 3 6 6, 3 3 3 4 4 4
2 1 4 6 4 4, 2 4 5 2 3 5, 3 3 6 3 3 3
11 11 13 15 15 16, 12 12 12 13 16 16, 13 13 13 14 14 14
4 4 7 16 19 19, 4 7 13 13 13 19, 4 10 10 10 16 19
strongly nontransitive
2 2 2 5 5 5, 2 3 3 3 5 5, 1 1 4 5 5 5
2 2 2 3 6 6, 2 2 2 5 5 5, 2 2 4 4 4 5
1 5 1 3 6 5, 6 6 4 2 2 1, 5 3 4 3 4 2
0 0 2 4 4 5, 0 1 1 3 5 5, 1 1 2 3 4 4
1 1 9 17 17 21, 1 5 5 13 21 21, 5 5 13 13 13 17
```
If you want to test your code even more thoroughly, Peter Taylor was kind enough to write a reference implementation, which classified all ~5000 sets of dice with sides 1 to 6 and a mean of 3.5. **[Pastebin link](http://pastebin.com/raw.php?i=ZzSUrpp1)**
[Answer]
# Python 2, 269
Here's a nice little expression that evaluates to a function. It accepts three lists of integers. Passes all test cases.
```
lambda A,B,C,w=lambda A,B:cmp(sum(cmp(a,b)for a in A for b in B),0),x=lambda A,B:cmp(sum(cmp(a+c,b+d)for a in A for b in B for c in A for d in B),0): (w(A,B)==w(B,C)==w(C,A)!=0)*((x(A,B)==x(B,C)==x(C,A))*["","strongly ","Grime-"][x(A,B)*w(A,B)]+"nontransitive")or"none"
```
[Answer]
# Dyalog APL, ~~107~~ 100 bytes
~~[`{({+/×+/¨,¨×⍵∘.-¨1⌽⍵}{3≠|a←⍺⍺⍵:1⋄a=b←⍺⍺∘.+⍨¨⍵:2⋄3+a=-b}⍵)⊃(⊂'none'),'strongly '⍬'Grime-',¨⊂'nontransitive'}`](http://tryapl.org/?a=%7B%28%7B+/%D7+/%A8%2C%A8%D7%u2375%u2218.-%A81%u233D%u2375%7D%7B3%u2260%7Ca%u2190%u237A%u237A%u2375%3A1%u22C4a%3Db%u2190%u237A%u237A%u2218.+%u2368%A8%u2375%3A2%u22C43+a%3D-b%7D%u2375%29%u2283%28%u2282%27none%27%29%2C%27strongly%20%27%u236C%27Grime-%27%2C%A8%u2282%27nontransitive%27%7D%20%A8%20%28%281%202%203%204%205%206%29%286%205%204%203%202%201%29%281%203%205%202%204%206%29%29%20%28%281%201%201%206%206%206%29%284%204%204%205%205%205%29%285%205%205%205%205%205%29%29%20%28%281%201%202%205%206%206%29%282%202%203%204%204%206%29%282%203%203%204%204%205%29%29%20%28%280%201%202%203%204%205%29%281%201%202%203%203%205%29%281%202%202%202%203%205%29%29%20%28%283%2013%205%207%2013%207%29%285%207%2011%205%207%2013%29%285%209%2013%205%207%209%29%29%20%28%281%202%202%204%206%206%29%281%202%203%205%205%205%29%282%203%204%204%204%204%29%29%20%28%281%204%204%204%204%204%29%282%202%202%204%205%206%29%282%203%203%203%205%205%29%29%20%28%281%202%201%206%205%206%29%283%201%203%206%202%206%29%282%204%202%204%204%205%29%29%20%28%283%204%206%206%207%207%29%284%204%204%207%207%207%29%285%205%205%205%206%207%29%29%20%28%282%205%2011%2011%2014%2014%29%285%205%205%2014%2014%2014%29%288%208%208%208%208%2017%29%29%20%28%283%203%203%203%203%206%29%282%202%202%205%205%205%29%281%204%204%204%204%204%29%29%20%28%281%201%204%205%205%205%29%282%202%202%203%206%206%29%283%203%203%204%204%204%29%29%20%28%282%201%204%206%204%204%29%282%204%205%202%203%205%29%283%203%206%203%203%203%29%29%20%28%2811%2011%2013%2015%2015%2016%29%2812%2012%2012%2013%2016%2016%29%2813%2013%2013%2014%2014%2014%29%29%20%28%284%204%207%2016%2019%2019%29%284%207%2013%2013%2013%2019%29%284%2010%2010%2010%2016%2019%29%29%20%28%282%202%202%205%205%205%29%282%203%203%203%205%205%29%281%201%204%205%205%205%29%29%20%28%282%202%202%203%206%206%29%282%202%202%205%205%205%29%282%202%204%204%204%205%29%29%20%28%281%205%201%203%206%205%29%286%206%204%202%202%201%29%285%203%204%203%204%202%29%29%20%28%280%200%202%204%204%205%29%280%201%201%203%205%205%29%281%201%202%203%204%204%29%29%20%28%281%201%209%2017%2017%2021%29%281%205%205%2013%2021%2021%29%285%205%2013%2013%2013%2017%29%29&run)~~
[`{T←{+/×+/¨∊¨×⍵∘.-¨1⌽⍵}⋄3≠|S←T⍵:'none'⋄N←'nontransitive'⋄S=D←T∘.+⍨¨⍵:'strongly ',N⋄S=-D:'Grime-',N⋄N}`](http://tryapl.org/?a=%7BT%u2190%7B+/%D7+/%A8%u220A%A8%D7%u2375%u2218.-%A81%u233D%u2375%7D%u22C43%u2260%7CS%u2190T%u2375%3A%27none%27%u22C4N%u2190%27nontransitive%27%u22C4S%3DD%u2190T%u2218.+%u2368%A8%u2375%3A%27strongly%20%27%2CN%u22C4S%3D-D%3A%27Grime-%27%2CN%u22C4N%7D%20%A8%20%28%281%202%203%204%205%206%29%286%205%204%203%202%201%29%281%203%205%202%204%206%29%29%20%28%281%201%201%206%206%206%29%284%204%204%205%205%205%29%285%205%205%205%205%205%29%29%20%28%281%201%202%205%206%206%29%282%202%203%204%204%206%29%282%203%203%204%204%205%29%29%20%28%280%201%202%203%204%205%29%281%201%202%203%203%205%29%281%202%202%202%203%205%29%29%20%28%283%2013%205%207%2013%207%29%285%207%2011%205%207%2013%29%285%209%2013%205%207%209%29%29%20%28%281%202%202%204%206%206%29%281%202%203%205%205%205%29%282%203%204%204%204%204%29%29%20%28%281%204%204%204%204%204%29%282%202%202%204%205%206%29%282%203%203%203%205%205%29%29%20%28%281%202%201%206%205%206%29%283%201%203%206%202%206%29%282%204%202%204%204%205%29%29%20%28%283%204%206%206%207%207%29%284%204%204%207%207%207%29%285%205%205%205%206%207%29%29%20%28%282%205%2011%2011%2014%2014%29%285%205%205%2014%2014%2014%29%288%208%208%208%208%2017%29%29%20%28%283%203%203%203%203%206%29%282%202%202%205%205%205%29%281%204%204%204%204%204%29%29%20%28%281%201%204%205%205%205%29%282%202%202%203%206%206%29%283%203%203%204%204%204%29%29%20%28%282%201%204%206%204%204%29%282%204%205%202%203%205%29%283%203%206%203%203%203%29%29%20%28%2811%2011%2013%2015%2015%2016%29%2812%2012%2012%2013%2016%2016%29%2813%2013%2013%2014%2014%2014%29%29%20%28%284%204%207%2016%2019%2019%29%284%207%2013%2013%2013%2019%29%284%2010%2010%2010%2016%2019%29%29%20%28%282%202%202%205%205%205%29%282%203%203%203%205%205%29%281%201%204%205%205%205%29%29%20%28%282%202%202%203%206%206%29%282%202%202%205%205%205%29%282%202%204%204%204%205%29%29%20%28%281%205%201%203%206%205%29%286%206%204%202%202%201%29%285%203%204%203%204%202%29%29%20%28%280%200%202%204%204%205%29%280%201%201%203%205%205%29%281%201%202%203%204%204%29%29%20%28%281%201%209%2017%2017%2021%29%281%205%205%2013%2021%2021%29%285%205%2013%2013%2013%2017%29%29&run)
(Thanks @Tobia for this simpler, shorter, better solution)
Basics:
* `←` assignment
* `⋄` statement separator
* `{}` lambda form
* `⍺⍵` left and right argument
* `A:B` guard ("if `A` then return `B`")
`T` is a function that returns 3 if A beats B, B beats C, and C beats A; -3 if the exact opposite is the case; and something inbetween otherwise. In detail:
* `1⌽⍵` is the one-rotation of `⍵`. If `⍵` is ABC, the rotation is BCA.
* `∘.-` computes a subtraction table between two vectors (`1 2...10 ∘.× 1 2...10` would be the multiplication table we know from school). We apply this between each (`¨`) item of `⍵` and its corresponding item in `1⌽⍵`.
* `×` signum of all numbers in the subtraction tables
* `∊¨` flatten each table
* `+/¨` and sum it. We now have three numbers that represent balances: number of winning minus losing cases for each of A vs B, B vs C, C vs A.
* `×` signum of those
* `+/` sum
Then handle the cases in turn:
* `3≠|S←T⍵:'none'` if `T⍵`'s absolute value isn't 3, return 'none'
* `N←'nontransitive'` we'll need this word a lot
* `S=D←T∘.+⍨¨⍵:'strongly ',N` compute `T` for pairs of dice (`∘.+⍨¨⍵` ←→ `⍵((∘.+)¨)⍵`) and return "strongly..." if the same relationships among ABC still hold
* `S=-D:'Grime-',N` ⍝ "Grime" if the relationships are in the opposite directions
* `N` if all else fails, just "nontransitive"
[Answer]
# J - 311 257 bytes
Update (13 Jan 2015):
```
g=:4 :'(+/,x>/y)>+/,y>/x'
h=:4 :'(,+/~x)g,+/~y'
f=: 3 :0
'a b c'=:y
if. (b g a)*(c g b)*a g c do.
a=.2{y
c=.0{y
end.
'none'([`]@.((a g b)*(b g c)*c g a))((''([`]@.((b h a)*(c h b)*a h c))'Grime-')([`]@.((a h b)*(b h c)*c h a))'strongly '),'nontransitive'
)
```
Explanation: Using Gerunds, simplify the `if.`s to `@.`s.
## Older version:
First try at both coding in J as well as golfing.
```
g=:4 :'(+/,x>/y)>+/,y>/x'
h=:4 :'(,+/~x)g,+/~y'
f=: 3 :0
'a b c'=:y
if. (b g a)*(c g b)*a g c do.
a=.2{y
c=.0{y
end.
if. (a g b)*(b g c)*c g a do.
if. (a h b)*(b h c)*c h a do.
'strongly nontransitive'
elseif. (b h a)*(c h b)*a h c do.
'Grime-nontransitive'
elseif. do.
'nontransitive'
end.
else.
'none'
end.
)
```
Run it using a syntax similar to following (extra spaces for clarity):
```
f 3 6 $ 1 1 9 17 17 21, 1 5 5 13 21 21, 5 5 13 13 13 17
```
Explanation:
`g` is defined as a diad taking two arrays that tells if first dice beats second dice
`h` is defined as a diad taking two arrays that tells if throwing twice and summing, does first dice beat second
`f` is a monad that takes a table and returns a string with the right answer
Edit: Fix a mistake in Grime-nontransitive condition (replacing `,` with `*`)
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) 129 ~~133~~
```
Lmsd^b2Msmsm>bkGHDPNK-ghNeNgeNhNR?^tZ<KZKZAGHmsdCm,PkP,yhkyekm,@Qb@QhbUQ?"none"|!G%G3s[*!+GH"Grime-"*qGH"strongly ""nontransitive
```
[Try it here](https://pyth.herokuapp.com/), or at least you could, but the online `eval` doesn't seem to like lists of lists :( If you want to try it there, manually store a list of 3 dice into a variable not used by the program and then replace all instances of `Q` with that variable. A sample initialization:
```
J[[3 3 3 3 3 6)[2 2 2 5 5 5)[1 4 4 4 4 4))
```
This passes all of Martin's test cases, I haven't the heart go through all of Peter's cases :P
Explanation (this is gonna be a doozy)
```
Lmsd^b2
```
Pretty simple, makes a function `y` that returns the sum of each Cartesian pair of values in an iterable. Equivalent to: `def y(b):return map(lambda d:sum(d),product(b,repeats=2))`. This is used to create many-sided dies that simulate throwing the regular dies twice.
```
Msmsm>bkGH
```
Defines a function `g` of 2 arguments that returns how many times a die beats another. Equivalent to `def g(G,H):return sum(map(lambda k:sum(map(lambda b:b>k,G)),H)`.
```
DPNK-ghNeNgeNhNR?^tZ<KZKZ
```
Defines a funtion `P` that takes a list of two dice as its argument. This returns -1 if the first die 'loses', 0 for a tie and 1 if the first die 'wins'. Equivalent to:
```
def P(N):
K=g(N[0],N[-1]) - g(N[-1],N[0])
return -1**(K<0) if K else 0
```
The `AGH` assigns acts like a python 2-tuple assignment. Essentially `G,H=(result)`
```
msdCm,PkP,yhkyekm,@Qb@QhbUQ
```
Going to explain backwards through the maps. `m,@Qb@QhbUQ` iterates over b=0..2 and generates 2-tuples of dice with index b and index b+1. This gives us dice (A,B),(B,C),(C,A) (pyth automatically mods indexes by the length of the list).
Next, `m,PkP,yhkyek` iterates over the result of the previous map, with each dice pair being stored in k over each run. Returns `tuple(P(k),P(tuple(y(k[0]),y(k[-1]))))` for each value. That boils down to `((A beats B?, 2\*A beats 2\*B), (B beats C?, 2\*B beats..)).
Finally, `msdC` sums the values of the previous map after it has been zipped. The zip causes all of the single dice 'beats' values in the first tuple, and the double dice values in the second.
```
?"none"|!G%G3s[*!+GH"Grime-"*qGH"strongly ""nontransitive
```
A gross thing that prints out the results. If G is 0 or not divisible by 3, this catches bot +/- 3, (`|!G%G3`), prints `none`, otherwise prints the sum of the follwing list: `[not(G+H)*"Grime",(G==H)*"strongly ","nontransitive"]`. I think the booleans are fairly self-explanatory with regard to the definitions in the question. Do note that G cannot be zero here, as that is caught by the previous check.
[Answer]
# J (204)
Way too long, could probably be golfed a lot by having a more efficient system for picking the right string.
```
f=:3 :'(<,>)/"1+/"2>"1,"2(<,>)/L:0{(,.(1&|.))y'
n=:'nontransitive'
d=:3 :0
if.+/*/a=.f y do.+/*/b=.f<"1>,"2+/L:0{,.~y if.a-:b do.'strongly ',n elseif.a-:-.b do.'Grime-',n elseif.do.n end.else.'none'end.
)
```
[Answer]
# Matlab (427)
It is not that short and I am sure it can be golfed a lot more, I just tried to solve this challenge because I thought it was a very fun task, so thanks **@MartinBüttner** for creating this challenge!
```
a=input();b=input();c=input();
m = 'non';l=@(a)ones(numel(a),1)*a;n=@(a,b)sum(sum(l(a)>l(b)'));g=@(a,b)n(a,b)>n(b,a);s=@(a,b,c)sum([g(a,b),g(b,c),g(c,a)]);
x=s(a,b,c);y=s(a,c,b);if x~=3 && y~=3;m=[m,'e'];else m=[m,'transitive'];o=ones(6,1);a=o*a;a=a+a';a=a(:)';b=o*b;b=b+b';b=b(:)';c=o*c;c=c+c';c=c(:)';u=s(a,b,c);
v=s(a,c,b);if u==3|| v==3;if x==3&&u==3 || y==3&&v==3 m=['strongly ',m];else m=['Grime-',m];end;end;end;disp(m);
```
Here the full length code with some comments if you want to try to understand what's going on. I included some test cases hare and excluced the input commands:
```
%nontransitive
% a = [1 2 2 4 6 6];
% b = [1 2 3 5 5 5];
% c = [2 3 4 4 4 4];
%none
% a = [1 2 3 4 5 6];
% b = [6 5 4 3 2 1];
% c = [1 3 5 2 4 6];
%grime nontransitive
% a = [3 3 3 3 3 6];
% b = [2 2 2 5 5 5];
% c = [1 4 4 4 4 4];
%strongly nontransitive
% a = [2 2 2 5 5 5];
% b = [2 3 3 3 5 5];
% c = [1 1 4 5 5 5];
m = 'non';
l=@(a)ones(numel(a),1)*a;
n=@(a,b)sum(sum(l(a)>l(b)'));
%input as row vector, tests whether the left one beats the right one:
g=@(a,b)n(a,b)>n(b,a);
s=@(a,b,c)sum([g(a,b),g(b,c),g(c,a)]);
%if one of those x,y has the value 3, we'll have intransitivity
x=s(a,b,c);
y=s(a,c,b);
if x~=3 && y~=3 %nontransitive
m=[m,'e'];
else %transitive
m=[m,'transitive'];
o=ones(6,1);
a=o*a;a=a+a';a=a(:)'; %all possible sums of two elements of a
b=o*b;b=b+b';b=b(:)';
c=o*c;c=c+c';c=c(:)';
u=s(a,b,c);
v=s(a,c,b);
%again: is u or v equal to 3 then we have transitivity
if u==3 || v==3 %grime OR strongly
% if e.g. x==3 and u==3 then the 'intransitivity' is in the same
% 'order', that means stronlgy transitive
if x==3 && u==3 || y==3 && v==3%strongly
m=['strongly ',m];
else %grime
m=['Grime-',m];
end
end
end
disp(m);
```
[Answer]
## JavaScript - 276 bytes
```
function(l){r=function(i){return l[i][Math.random()*6|0]};p=q=0;for(i=0;j=(i+1)%3,i<3;++i)for(k=0;k<1e5;++k){p+=(r(i)>r(j))-(r(i)<r(j));q+=(r(i)+r(i)>r(j)+r(j))-(r(i)+r(i)<r(j)+r(j))}alert((a=Math.abs)(p)>5e3?((a(q)>5e3?p*q>0?'strongly ':'Grime-':'')+'nontransitive'):'none')}
```
I'm not really good in probability, so to be sure of my results, I prefer to just throw the dice hundreds of thousands times.
The expression evaluates to a function, that should be called with only one argument: an array of three arrays of integers. [Check the Fiddle](http://jsfiddle.net/Blackhole/gg90hxxv/) to be able to run the code by yourself.
Here is the ungolfed version:
```
function (diceList) {
var getRandomValue = function (idDie) {
return diceList[idDie][Math.floor(Math.random() * 6)];
};
var probabilitySimpleThrow = 0;
var probabilityDoubleThrow = 0;
for (var idDieA = 0; idDieA < 3; ++idDieA)
{
var idDieB = (idDieA + 1) % 3;
for (var idThrow = 0; idThrow < 1e5; ++idThrow)
{
probabilitySimpleThrow += getRandomValue(idDieA) > getRandomValue(idDieB);
probabilitySimpleThrow -= getRandomValue(idDieA) < getRandomValue(idDieB);
probabilityDoubleThrow += getRandomValue(idDieA) + getRandomValue(idDieA) > getRandomValue(idDieB) + getRandomValue(idDieB);
probabilityDoubleThrow -= getRandomValue(idDieA) + getRandomValue(idDieA) < getRandomValue(idDieB) + getRandomValue(idDieB);
}
}
if (Math.abs(probabilitySimpleThrow) > 5e3) {
if (Math.abs(probabilityDoubleThrow) > 5e3) {
if (probabilitySimpleThrow * probabilityDoubleThrow > 0) {
var result = 'strongly ';
}
else {
var result = 'Grime-';
}
}
else {
var result = '';
}
result += 'nontransitive';
}
else {
var result = 'none';
}
alert(result);
}
```
] |
[Question]
[
(I'm not a chemist! I might be wrong at some stuff, I'm writing what I've learned in high-school)
Carbon atoms have a special attribute: They can bind to 4 other atoms (which is not that special) and they stay stable even in long chains, which is very unique. Because they can be chained and combined in a lot of different ways, we need some kind of naming convention to name them.
This is the smallest molecule we can make:
```
CH4
```
It's called methane. It consists of only one carbon and 4 hydrogen atoms. The next one is:
```
CH3 - CH3
```
This is called ethane. It's made up of 2 carbon and 6 hydrogen atoms.
The next 2 are:
```
CH3 - CH2 - CH3
CH3 - CH2 - CH2 - CH3
```
They are propane and butane. The problems start with the chains with 4 carbon atoms, as it can be built in 2 different ways. One is shown above and the other is:
```
CH3 - CH - CH3
|
CH3
```
This is obviously not the same as the other. The number of atoms and the bindings are different. Of course just folding bindings and rotating the molecule won't make it a different one! So this:
```
CH3 - CH2 - CH2 - CH3
```
And this:
```
CH3 - CH2
|
CH3 - CH2
```
Are the same (If you are into graph theory, you may say that if there is isomorphism between 2 molecules; they are the same). From now on I won't write out hydrogen atoms as they are not essential for this challenge.
As you hate organic chemistry and you have a lot of different carbon atoms to name, you decide to write a program that does this for you. You don't have too much space on your hard-drive tho, so the program must be as small as possible.
# The challenge
Write a program that takes in a multi-line text as input (a carbon chain) and outputs the name of the carbon chain. The input will only contain spaces, uppercase 'c' characters and '|' and '-' which represents a binding. The input chain will never contain cycles! Example:
Input:
```
C-C-C-C-C-C
| |
C C-C
```
Output:
>
> 4-ethyl-2-methylhexane
>
>
>
Any output is acceptable as long as it's human-readable and essentially the same (so you can use different separators for example if you wish).
**The naming convention:**
(See: [IUPAC rules](http://www.chem.uiuc.edu/GenChemReferences/nomenclature_rules.html))
1. Identify the longest carbon chain. This chain is called the parent chain.
2. Identify all of the substituents (groups appending from the parent chain).
3. Number the carbons of the parent chain from the end that gives the substituents the lowest numbers. When comparing a series of numbers, the series that is the "lowest" is the one which contains the lowest number at the occasion of the first difference. If two or more side chains are in equivalent positions, assign the lowest number to the one which will come first in the name.
4. If the same substituent occurs more than once, the location of each point on which the substituent occurs is given. In addition, the number of times the substituent group occurs is indicated by a prefix (di, tri, tetra, etc.).
5. If there are two or more different substituents they are listed in alphabetical order using the base name (ignore the prefixes). The only prefix which is used when putting the substituents in alphabetical order is iso as in isopropyl or isobutyl. The prefixes sec- and tert- are not used in determining alphabetical order except when compared with each other.
6. If chains of equal length are competing for selection as the parent chain, then the choice goes in series to:
* the chain which has the greatest number of side chains.
* the chain whose substituents have the lowest- numbers.
* the chain having the greatest number of carbon atoms in the smallest side chain.
* the chain having the least branched side chains (a graph having the least number of leaves).
For the parent chain, the naming is:
```
Number of carbons Name
1 methane
2 ethane
3 propane
4 butane
5 pentane
6 hexane
7 heptane
8 octane
9 nonane
10 decane
11 undecane
12 dodecane
```
No chains will be longer than 12, so this will be enough. For the sub-chains it's the same but instead of 'ane' at the end we have 'yl'.
You can assume that the `C`s are in the odd columns and the bindings (`|` and `-` characters) are 1 long between carbon atoms.
# Test cases:
Input:
```
C-C-C-C
```
Output:
>
> butane
>
>
>
Input:
```
C-C-C
|
C
```
Output:
>
> 2-methylpropane
>
>
>
Input:
```
C-C-C-C
|
C
|
C-C
```
Output:
>
> 3-methylhexane
>
>
>
Input:
```
C-C-C-C-C
|
C
|
C
```
Output:
>
> 3-methylhexane
>
>
>
Input:
```
C
|
C
|
C-C-C-C
|
C-C-C
|
C-C
```
Output:
>
> 3,4-dimethyl-5-ethylheptane
>
>
>
Edit: Sorry for the wrong examples. I wasn't a good student :( . They should be fixed now.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~1876~~ ~~1871~~ ~~1870~~ ~~1859~~ ~~1846~~ ~~1830~~ ~~1826~~ ~~1900~~ ~~1932~~ ~~1913~~ ~~1847~~ ~~1833~~ ~~1635~~ ~~1613~~ 1596 bytes
```
s=input().split('\n')
W=enumerate
J=len
Y=sorted
l=J(s[0])
s=''.join(s)
S=set
M=max
A=min
p=map
f=lambda k:[(x/l,x%l)for x,V in W(s)if V==k]
g=lambda x,i,h=lambda x,i,j:x[:i]+(x[i]+j,)+x[i+1:]:[(h(q,i,-1),h(q,i,1))for q in x]
v=f('C');e=g(f('-'),1)+g(f('|'),0)
E=[V for V in v if sum(e,()).count(V)==1]
o=lambda v:[E[~E.index(v)]for E in e if v in E]
T=lambda a:lambda b:z((a,b))
Z=lambda a:p(T(a[0]),a[1])
n=lambda R:'mepbphhondudetrueeeco nothotnxptn ddh p t t'[R-1::12].strip()+(R>9)*'ec'
G=lambda K:[H[i]for i,V in W(K)if V==A(K)]
q=lambda x:[`k[0]`for k in H if k[1]==x]
B='-'.join
def z(n,c=[]):k=[x for x in S(o(n[0]))-S(c)];p=[z((j,n[1]),c+k)for j in k];return 1-~-(n[0]==n[1])*(p and A(p)or J(v))
C=[(a,b)for a in E for b in E]
a=p(z,C)
s=[(k,[E for E in v if~-z((k[0],E))+z((k[1],E))==z((k[0],k[1]))])for k in[C[x]for x,V in W(a)if V==M(a)]]
H=[]
R=0
for k,_ in s:R=M(J(_),R);_.sort(key=T(k[0]));a=sum([list(S(o(k))-S(_))for k in _],[]);H+=zip(p(lambda a:Z((a,_)).index(2),a),p(Z,[(O,[x for x in S(v)-S(_)if z((x,O),_)<J(v)])for O in a])),
X=n(R)
U=any(H)
if U:H=G([[h[0]for h in Q]for Q in H if J(Q)==M(p(J,H))]);K=[[J(Q[1])for Q in j]for j in H];H=[H[i]for i,V in W(K)if A(V)==A(sum(K,[]))];K=[J([Q[1]for Q in j if J(S(Q[1]))-J(Q[1])])for j in H];H=[[p[0]+1,n(M(p[1]))+[['isopropyl','butyl-tert','butyl-sec','isobutyl'][J(p[1])+p[1].count(3)-3],'yl'][Y(p[1])==range(1,1+M(p[1]))]]for p in G(K)[0]]
print(U and B([','.join(q(x))+'-'+'dttphhondireeeecoe itnxptnc rtataaa aa a '[J(q(x))-2::9].strip()+B(x.split('-')[::-1])for x in Y(list(S(zip(*H)[1])))])+X or[X,'meth']['t'==X])+'ane'
```
[Try it online!](https://tio.run/##bVRdT@M6EH33r/DLlccbp5ewT5teXwmqiqpohSgfC3gtNm0NTT@ckLhVQIi/zo7dplyutlGjiX1m5vjMeMpnNyvs4ft7LXNbrh3wTl0ucwfsp2Wc/JDGrlemypwhQ7k0ltzKuqicmZKlHEKtDjQntWSsMy9yCzUnF7I2jnyXq6whR3KVW1KiXZIHucxW42lGF6mC5u@laP5a8oeioo24prmlP9A5f6DXUi40eWzBjcjF7L8f87RRaa4jaBS@54JHaERJqjHqDJ4QESdcbK2EhwRPPnyjyUY@AOsx3jXyEdCMGUdIFOxXtA846Ut1Tb1PoLShSKher8AI4LwzKdbWwTWXMtGkaEltUtVXb/1ObqemgQ3X3r3v3Y1333irr8lli8/SnTFOXwAyMeac3H1slnAJmVdVZCpBbW27NUrZypTjcoblmq6nxlVrY8ykoLbACjrblM7S6XRGS@qoY2oUJ2maHOpO7aq8BB7B6N9v/AszE0ZO2qCnqRqgjp5y3pbhdFeGI7Q0edqLn6pfCyT2y4MXHjrw51sgSylR3WOJgoYuIFPzQF/AiolUmqcLqZqgaeOdLqAA68/H4wuYcN0tpUId5sL644pJtAg1m3vsQncr49aVpUn8Fgc3KQPuC5Q0s1N6BCVH9BB156QnVdDT@2dB9pB2vKtAJkt4ET3frgoWQm13@22h32Kk4Q8o@pxHwU6CLWW74Vc417xVQPVUoz@1cLbT7jtaWpMBCkBG8oAED3HvQXU6wu0h3HMx4t37jr9NsDDP8jIk4bybSd9zapnXDrxci6DVPd/npfdaoLLdQSRfsLQl7LvnzncUInfdeIhdxEUJd0LBmfhchs02aO5LBY044@j3jxdye74zj8qQjiA30sKIkyuZ2WcYcIIuV@lAnoBSM2Ts0TOPPg/m@b41hnDOvRQlDMXA69Y9lUrhqpdxD53rfb0HuouK/bkhj8LFOwIvzak/PbYOhhuC8uE@om0TX2yT8HiXTfP/JVElMo8SYQH5BWikFMvroqyK8nnJBBuv3fMydqZy@48a747woPDJNGYPvpF/78bDVx5/1YKF7dvttpRVZh8NJCKJ2mw6UC49oRM8IJLRpKxyDHAVGvsYFKbaDtUnaJAe3q6ITZ3bDoC8MuH244zZXv0JpZXLXJZllOI/owzZBc/4ME2/fYyBY2jaCY8DUKVpvKtG6Itb2LWdb6wvAx7IonzRDS0qdSNwBrkZHo05JuUNrrPMGvb@zjr463U6P603Xlvj80ovDo9fefWL3vjjSqfDfgM "Python 2 – Try It Online")
Well there you go. Certainly not the golfiest but it works (I hope) :D
Took me about 10 hours, maybe? Probably my longest golf in both size and time, and that's saying something considering I used to use Java D:
Logic:
1. Convert from the ASCII representation to graph representation with each carbon atom as a node and each bond as an edge represented in adjacency form.
2. Find all leaves; that is, nodes with only one bond. The longest chain is guaranteed to be from one of these to another.
3. Find the dyadic product of the leaves; that is, all pairs of edge nodes. Then, take the length of all of these chains.
4. For each chain, find its subchains.
5. Do stuff to pick the right chain. If there are ties, then it doesn't really matter. Fun fact: There will always be a tie because each chain is counted twice, once in reverse.
6. Print it properly.
**EDIT**: Fixed bug where it used to cause errors if there were no side chains.
**EDIT**: Thanks to MD XF for noticing a few extra spaces (indentation for the for loop).
**EDIT**: I completely forgot about the prefix for having the same substituent.
**NOTE**: Each line needs to be the same width for this to work. That is, trailing spaces are required.
Fun fact: most cyclic hydrocarbons will be determined as "methane"
Fun fact: If you do `C-C-...-C-C` with 13 Cs, it will give `ethane`, then `thane` for 14, `ropane` for 15, etc.
-79 bytes thanks to Jonathan Frech
-119 bytes thanks to NieDzejkob
-17 bytes thanks to ovs
] |
[Question]
[
# The puzzle:
Consider a console/hand-held game with a d-pad where you are required to enter a name of sorts. This appeared in many older games before the use of QWERTY was popularised in consoles (e.g. I believe the Wii uses a QWERTY keyboard layout for input). Typically, the on-screen keyboard looks to the effect of\*:
Default:
```
0 1 2 3 4 5 6 7 8 9
A B C D E F G H I J
K L M N O P Q R S T
U V W X Y Z _ + ^ =
```
With the case switched:
```
0 1 2 3 4 5 6 7 8 9
a b c d e f g h i j
k l m n o p q r s t
u v w x y z - + ^ =
```
That is, all alphanumeric keys and the following:
`_`: A single space
`-`: A hyphen
`+`: Switch case for the next letter only
`^`: Toggle caps lock (that is, switch the case of all letters)
`=`: Enter, complete
\*Obviously I replaced keys like "BKSP" and "ENTER" with shorter versions
And then the hardware would include a d-pad (or some form of control where you could go `up`, `down`, `left` and `right`)
The screen also typically let you move from one side directly to the other. That is, if you were focussed on the letter `J`, pressing `right` would allow you to move to the letter `A`.
Whenever I was entering my name, I'd always try to work out the quickest way to do so.
# Goal:
Your program will take string input which may include any alphanumeric character including a space and hyphen, and your goal is to **output the shortest amount of *key presses*** on the d-pad to output the required string.
# Considerations:
You do not need to include the key pressed for *pressing* the actual character.
Focus always starts at the `A`
Enter `=` must be *pressed* at the end
# Example:
`input: Code Golf`
`output: 43`
**Explained:**
`A` -> `C` = 2
`C` -> `^` = 6 (moving to the left)
`^` -> `o` = 5
`o` -> `d` = 2
`d` -> `e` = 1
`e` -> `+` = 5
`+` -> `_` = 1
`_` -> `+` = 1
`+` -> `G` = 3
`G` -> `o` = 3
`o` -> `l` = 3
`l` -> `f` = 5
`f` -> `=` = 6
Note that it is quicker to hit the `+` twice for a `_` and a `G` than it is to hit `^` once, then swap back.
The winning submission (I'll allow at least 1w) will be the shortest solution (in bytes). As this is my first question, I hope this is clear and not too hard.
[Answer]
# Swift 1.2, ~~812~~ ~~588~~ 670 bytes
Edit: Removed 224 bytes by replacing the large arrays of numbers with a Range and converting it to an Array instead.
Edit2: Added looping vertically
```
typealias S=String
typealias I=Int
var A:(I)->S={S(UnicodeScalar($0))},B:(I)->(I,I)={a in(a%10,a/10)},a=Array(48...57).map{A($0)},b=[a+(Array(65...90)+[32,43,94,61]).map{A($0)},a+(Array(97...122)+[45,43,94,61]).map{A($0)}],z=Process.arguments
z.removeAtIndex(0)
func C(e:I,f:I)->I{let(a,b)=B(e),(c,d)=B(f)
return min(abs(d-b), abs(4-(d-b)))+min(abs(c-a),abs(10-(c-a)))}
func D(c:S,_ e:I=10,_ f:Bool=false,_ g:Bool=false)->I{if count(c)==0{return C(e,39)}
let h=c.startIndex,i=c.endIndex,j=S(c[h])
if let k=find(b[f ?1:0],j){return C(e,k)+D(c[advance(h,1)..<i],k,(g ?(!f):f),false)}else{return min(C(e,37)+D(c,37,!f,true),C(e,38)+D(c,38,!f,false))}}
print(D(" ".join(z)))
```
To run, put the code in a `.swift` file and run it with `swift <filename> <your name>`
---
This uses the simple approach where the two 'keyboards' are stored as arrays.
`B:(I)->(I,I)={a in(a%10,a/10)}`
Converts an index from the array to an x,y position on the virtual keyboard.
`func C(e:I,f:I)->I{let(a,b)=B(e),(c,d)=B(f)
return abs(d-b)+min(abs(c-a),abs(10-(c-a)))}` Takes a start/end index and returns the minimum number of moves to get from once to the other (accounting for horizontal wrap)
`func D(c:S,_ e:I=10,_ f:Bool=false,_ g:Bool=false)->I` Is the main recursive function that does most of the calculations. It calculates the distance from the current position to the target character, unless the case should change, then it calculates **both** the *shift* **and** the *caps lock* methods and takes the smallest.
Running `swift codegolf.swift Code Golf` prints `43`
[Answer]
# Ruby (369 bytes)
Takes input from command line.
```
K="0123456789"+('A'..'Z').to_a.join+" +^="
Q=K.downcase.sub' ','-'
def d x,y
t,s=(x/10-y/10).abs,(x%10-y%10).abs
[t,4-t].min+[s,10-s].min
end
def v s,i,l,a
return l if s.empty?
c,r=s[0],s[1..-1]
j=K.index(c.upcase)||36
return v(r,j,l+d(i,j),a)if a.include?c
s,p=d(i,37)+d(37,j),d(i,38)+d(38,j)
[v(r,j,l+s,a),v(r,j,l+p,a==K ? Q : K)].min
end
puts v("#{ARGV[0]}=",10,0,K)
```
Saved a bunch of bytes thanks to @Charlie :)
[Answer]
# Python ~~679~~ ~~661~~ ~~619~~ ~~602~~ ~~589~~ ~~576~~ ~~539~~ ~~520~~ ~~496~~ 482 Bytes
Run this and it will ask for a input (without prompt text). For the input `Code Golf` it prints `43`.
```
a=input()+'=';b=0;c="0123456789abcdefghijklmnopqrstuvwxyz-+^=";d=0;e=[0,1];f='+';g='^';h=[i.isupper()or i==' 'for i in a];i=abs;p=lambda z:all([i==b for i in z]);q=0
def l(z):global s;k=c.index(z.lower().replace(' ','-'));s=[k%10,int(k/10)];m,n=s;return sum([min(i(m-e[0]),i(10-(m-e[0]))),min(i(n-e[1]),i(4-(n-e[1])))])
def o(z):global d,e;d+=l(z);e=s
for r in a:
if p(h[q:q+3]):o(g);b^=1
if p(h[q:q+2]):
if l(f)<l(g):o(f)
else:o(g);b^=1
if p([h[q]]):o(f)
o(r);q+=1
print(d)
```
---
Full program:
```
input = input() + '='
capsOn = False
keys = "0123456789abcdefghijklmnopqrstuvwxyz-+^="
totalKeys = 0
caret = [0, 1]
shiftKey = '+'
capsKey = '^'
cases = [char.isupper() or char == ' ' for char in input]
def locate(char):
"""
Find the location of the char on the keyboard
regardless of case
"""
location = keys.find(char.replace(' ', '-').lower())
return [location % 10, int(location / 10)]
def dist(key):
"""
Calculate the min dist to a char
"""
nx, ny = locate(key)
return sum([min(abs(nx - caret[0]), abs(10 - (nx - caret[0]))), min(abs(ny - caret[1]), abs(4 - (ny - caret[1])))])
def moveTo(char):
"""
Move the caret to the char, ignoring case and
adds the dist to the tally
"""
global totalKeys, caret
totalKeys = totalKeys + dist(char)
print(keys[caret[0] + caret[1] * 10], '->', char, '=', dist(char))
caret = locate(char)
diffCase = lambda case: all([i == capsOn for i in case])
for ind, ch in enumerate(input):
if diffCase(cases[ind:ind + 3]): # use caps
moveTo(capsKey)
capsOn ^= 1
elif diffCase(cases[ind:ind + 2]): # use closest
if dist(shiftKey) < dist(capsKey):
moveTo(shiftKey)
else:
moveTo(capsKey)
capsOn ^= 1
elif diffCase([cases[ind]]): # use shift
moveTo(shiftKey)
moveTo(ch) # apply the move
print('Total:', totalKeys)
```
---
[Answer]
# C 675 Bytes
Takes input from command line argument. Uses recursive main:
```
#define Y(_) (!isdigit(_)?!isalpha(_)?3:1+(toupper(_)-65)/10:0)
#define X(_) (!isdigit(_)?!isalpha(_)?_-32&&_-45?_-43?9-(_==94):7:6:(toupper(_)-5)%10:_-48)
x,y,z;char*s;main(a,_,p,q,r){a<2?s[_]?!isdigit(s[_])&&((s[_]-32&&!isupper(s[_]))||!a)&&((s[_]-45&&!islower(s[_]))||a)?q=x,r=y,main(3,43),p=z,x=X(43),y=Y(43),main(3,s[_]),p+=z,x=X(s[_]),y=Y(s[_]),main(a,_+1),p+=z,x=q,y=r,main(3,94),q=z,x=X(94),y=Y(94),main(3,s[_]),q+=z,x=X(s[_]),y=Y(s[_]),main(!a,_+1),q+=z,z=(q<p?q:p):(main(3,s[_]),q=z,x=X(s[_]),y=Y(s[_]),main(a,_+1),z+=q):(main(3,61)):(a<3?s=((char**)_)[1],x=0,y=1,main(1,0),printf("%d",z):(x=X(_)-x,y=Y(_)-y,x+=10*(x<0),y+=4*(y<0),z=(x>5?10-x:x)+(y>2?4-y:y)));}
```
] |
[Question]
[
Your task is to assemble the integers from `1` to `N` (given as input) into a rectangle of width `W` and height `H` (also given as input). Individual numbers may be rotated by any multiple of 90 degrees, but they must appear as contiguous blocks in the rectangle. That is, you cannot break one of the numbers into multiple digits and place the digits in the rectangle individually, neither can you bend three digits of a number around a corner. You could consider each number a brick from which you're building a wall.
Here is an example. Say your input is `(N, W, H) = (12, 5, 3)`. One possible solution is:
```
18627
21901
53114
```
For clarity, here are two copies of this grid, one with the one-digit numbers hidden and one with the two-digit numbers hidden:
```
1#### #8627
2##01 #19##
##11# 53##4
```
It's fine if the rectangle cannot be disassembled again in a unique way. For instance, in the above example, the `12` could also have been placed like this:
```
##### 18627
21#01 ##9##
##11# 53##4
```
## Rules
You may assume that `N` is positive and that `W*H` matches the number of digits in the integers from `1` to `N` inclusive, and that a tiling of the rectangle into the given numbers exists. I don't currently have a proof whether this is always possible, but I'd be interested in one if you do.
Output may either be a single linefeed-separated string or a list of strings (one for each line) or a list of lists of single-digit integers (one for each cell).
The results of your submission must be determinstic and you should be able to handle all test cases in less than a minute on reasonable desktop machine.
You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
Except for the first one, none of these are unique. Each test case is `N W H` followed by a possible output. Make sure that your answer works when the rectangle is too narrow to write the larger numbers horizontally.
```
1 1 1
1
6 6 1
536142
6 2 3
16
25
34
10 1 11
1
0
8
9
2
6
7
3
1
5
4
11 13 1
1234567891011
27 9 5
213112117
192422581
144136119
082512671
205263272
183 21 21
183116214112099785736
182516114011998775635
181116013911897765534
180415913811796755433
179115813711695745332
178315713611594735231
177115613511493725130
176215513411392715029
175115413311291704928
174115313211190694827
173115213111089684726
172015113010988674625
171915012910887664524
170814912810786654423
169714812710685644322
168614712610584634221
167514612510483624120
166414512410382614019
165314412310281603918
164214312210180593817
163114212110079583716
200 41 12
81711132917193661114105533118936111184136
50592924448815915414562967609909953662491
89529721161671582389717813151113658811817
41418184511110119010183423720433017331118
35171183614003547461181197275184300111711
41874381132041861871718311415915921116264
11914245014112711011594492626831219331845
17125112629222085166344707736090956375181
94507611291431121128817413566319161275711
11011540021119913511011169939551729880780
92725141607727665632702567369893534277304
78118311405621148296417218591118562161856
```
[Answer]
# Python 2, ~~210~~ 200 bytes
**Edit:** Works now!
Fills from top to bottom, left to right, starting with the largest numbers. Then, transpose and do it again. Then transpose and print. I had to pad with spaces for the transposition to work, since the lines aren't to their full length yet.
I had trouble getting a nested `exec` working (to do `exec'exec"..."*w\n;...'*2`. If someone can figure it out, let me know.
```
n,w,h=input()
s=[""]*h
for x in 1,2:
exec"for i in range(h):l=len(s[i]+`n`)<=w;s[i]+=`n`*l;n-=l\n"*w;s=[r.replace(" ","")for r in map(lambda x:`x`[2::5],zip(*[r.ljust(w)for r in s]))];w,h=h,w
print s
```
[**Try it online**](http://ideone.com/NgUF2x) - Uses a modified function so it can run multiple test cases more easily (and it couldn't use `exec`). Uncomment the other version and modify stdin to see it run.
**Less golfed:**
```
def f(n,w,h):
s=[""]*h
for x in 1,2:
for j in[0]*w:
for i in range(h):
l=len(s[i]+`n`)<=w
s[i]+=`n`*l
n-=l
s=[r.ljust(w)for r in s]
s=map(lambda x:`x`[2::5],zip(*s))
s=[r.replace(' ','')for r in s]
w,h=h,w
print"\n".join(s)
```
[Answer]
## JavaScript, ~~284~~ ~~259~~ ~~245~~ ~~241~~ ~~240~~ ~~223~~ ~~209~~ 205 bytes
```
// Golfed
let f = (N,W,H)=>eval('a=Array(H).fill("");while(N)g:{s=""+N--;d=s[L="length"];for(i in a)if(a[i][L]+d<=W){a[i]+=s;break g}for(p=0;d;++p){l=a[p][L];for(k=p+d;k>p;)l=a[--k][L]-l?W:l;while(l<W&&d)a[p+--d]+=s[d]}}a');
// Ungolfed
(N,W,H) => {
a = Array(H).fill(""); // Create `H` empty rows.
while (N) g : {
s = "" + N--; // Convert the number to a string.
d = s[L="length"]; // Count the digits in the number.
// Loop through the rows trying to fit the number in horizontally.
for (i in a) {
if (a[i][L] + d <= W) { // If it fits.
a[i] += s; // Append the number to the row.
break g; // This is what a goto statement looks like in JavaScript.
}
}
// Loop through the rows trying to fit the number in vertically.
for (p = 0; d; ++p) {
l = a[p][L]; // Get the length of the row.
// Find `d` adjacent rows of the same length.
for (k = p + d; k > p; ) {
// If `a[--k][L] == l`, continue.
// Else set `l` to `W` so the next loop doesn't run.
l = a[--k][L] - l ? W : l;
}
// Put the characters in position.
while (l < W && d)
a[p+--d] += s[d];
}
}
return a;
}
let test_data = [[1,1,1],
[6,6,1],
[6,2,3],
[10,1,11],
[10,11,1],
[11,13,1],
[27,9,5],
[183,21,21],
[184,2,222],
[200,41,12],
[1003,83,35]];
for (let test of test_data)
console.log(f(test[0],test[1],test[2]));
```
[Answer]
# Pyth, 35 bytes
```
juum+WghHl+dQd~tQN<+.TGmkeHeH)_BvzY
```
Credits to mbomb007. I used his algorithm.
Originally I only wanted to help Steven H., but then I really wanted to see a short version.
Takes `N` on the first line, and `W,H` on the second line: Try it online: [Demonstration](http://pyth.herokuapp.com/?code=juum%2BWghHl%2BdQd~tQN%3C%2B.TGmkeHeH%29_BvzY&input=10%0A1%2C%2011&test_suite_input=6%0A1%2C%206%0A6%0A6%2C%201&debug=0&input_size=2)
Found a nasty bug in the Pyth implementation of `.[` (my own fault, since I implemented it). Gotta fix it tomorrow. This resulted in +3 bytes.
### Explanation:
```
juum+WghHl+dQd~tQN<+.TGmkeHeH)_BvzY
Y start with the empty list []
I'll perform all operations on this list.
Sometimes it is called G, sometimes N.
vz read the second line and evaluate it: [W, H]
_B bifurcate it with reverse: [[W, H], [H, W]]
u for each pair H in ^:
.TG transpose G
+ mkeH append H[1] empty strings
< eH use only the first H[1] strings
lets call this result N
u ) modify N, until it doesn't change anymore:
m N map each d in N to:
WghHl+dQ if H[0] >= len(d+Q):
+ d Q d + Q
~t and decrement Q by 1
d else:
d
j at the end print every row on a separate line
```
[Answer]
# Pyth, ~~79 50~~ 48 Bytes
~~Noncompeting until I work out bugs (for example, [6,6,1] returns the same as [6,1,6]). It's my first time trying to use Pyth, so I'm probably missing a lot of features.~~
*Thanks to Jakube, saved 29 bytes and made my code actually work!*
Saved another two byte by realizing that the `repr()` calls were unnecessary.
It's basically just a translation of mbomb007's Python 2 answer.
```
AEJmkHFb2VHVGIgGl+@JNQ XNJ~tQ)))=.[.TJkGA,HG)jJ
```
Takes input in the form of
`n`
`w,h`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é!L↑?∞S░♠╔)¥¼/ÿµ◄÷│♦╫Δò6√√╣
```
[Run and debug it](https://staxlang.xyz/#p=82214c183fec53b006c9299dac2f98e611f6b304d7ff9536fbfbb9&i=12+3+5%0A1+1+1%0A6+1+6%0A6+3+2%0A10+11+1%0A11+1+13%0A27+5+9%0A183+21+21%0A200+12+41&a=1&m=2)
It takes input on one line in the for `{N} {H} {W}`.
This program starts with a grid of spaces of the specified size. For each number from `N` .. `1`, it attempts to do a single string replacement from a string of spaces of the appropriate size to the formatted number. If no replacement can be performed, then it tries again with a transposed grid.
```
z)A+* create "grid" of spaces and newlines of specified size
,Rr create range [n ... 1]
F for each number execute the indented section; it will fit the value into the grid
$%z( make a string out of spaces the same length as the number; e.g. 245 => " "
Y store the space string in register Y; this will be used as a search substring
[# count the number of occurrences of y in the grid; the grid is still on the stack
X store the count in register X; this will be used as a condition
G jump to routine at closing curly brace
y_$|e replace the first instance of y (the spaces) with the current number
xG push x; then jump to routine at closing curly brace
end program
} called routine jump target
C pop top of stack; if it's truthy terminate routine
|jM|J split on newlines; transpose; join with newlines
```
[Run this one](https://staxlang.xyz/#c=z%29A%2B*++%09create+%22grid%22+of+spaces+and+newlines+of+specified+size%0A,Rr++++%09create+range+[n+...+1]%0AF++++++%09for+each+number+execute+the+indented+section%3B+it+will+fit+the+value+into+the+grid%0A++%24%25z%28+%09make+a+string+out+of+spaces+the+same+length+as+the+number%3B+e.g.+245+%3D%3E+%22+++%22%0A++Y++++%09store+the+space+string+in+register+Y%3B+this+will+be+used+as+a+search+substring%0A++[%23+++%09count+the+number+of+occurrences+of+y+in+the+grid%3B+the+grid+is+still+on+the+stack%0A++X++++%09store+the+count+in+register+X%3B+this+will+be+used+as+a+condition%0A++G++++%09jump+to+routine+at+closing+curly+brace%0A++y_%24%7Ce%09replace+the+first+instance+of+y+%28the+spaces%29+with+the+current+number%0A++xG+++%09push+x%3B+then+jump+to+routine+at+closing+curly+brace%0A+++++++%09end+program%0A%7D++++++%09called+routine+jump+target%0AC++++++%09pop+top+of+stack%3B+if+it%27s+truthy+terminate+routine%0A%7CjM%7CJ++%09split+on+newlines%3B+transpose%3B+join+with+newlines&i=12+3+5%0A1+1+1%0A6+1+6%0A6+3+2%0A10+11+1%0A11+1+13%0A27+5+9%0A183+21+21%0A200+12+41&a=1&m=2)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 59 bytes
Oy, Pip can be verbose for a golfing language sometimes...
```
YsXbRLcJnWa{T` `X#a~yx:Y(t:{J*Z:a^n}Jny)Y$`.a.$'--a}x?(ty)y
```
[Try it online!](https://tio.run/##K8gs@P8/sjgiKcgn2SsvPLE6JEEhIUI5sa6ywipSo8Sq2ksryioxLq/WK69SM1IlQS9RT0VdVzextsJeo6RSs/L///@Wlv8t/xsZAgA "Pip – Try It Online")
### Ungolfed
Approach: store the grid as a newline-separated string, using regex to replace a run of spaces with the current number, and transposing if there isn't a run of spaces long enough.
```
; Command-line arguments are: a (the number), b (the width), c (the height)
; x is "", a falsey value
; Set up the initial string:
; sXb String of b spaces
; RLc Make a list of c of those
; Jn Join on newline
Y sXb RL c J n
; Define a function t that transposes a newline-separated string:
; a^n Split argument on newlines
; Z Zip (transposes, but results in a list of lists of characters)
; J* Join each of the sublists into a string
; Jn Join those strings on newline
t: {(J* Z (a^n)) J n}
; Loop while a is nonzero:
W a {
; Loop till a regex made of len(a) spaces matches in y:
T y ~ ` `X#a
; Transpose y and set x to a truthy value to indicate that we've transposed it:
; (t y) Call the t function on y
; Y Assign the result back to y
; x: Assign it to x also
x: Y (ty)
; When we break out of the loop, we have matched the first run of len(a) spaces
; in y; now we want to replace that with the number a:
; $` The part of the string before the match
; .a Concatenated to a
; .$' Concatenated to the part of the string after the match
; Y Assign that to y
Y $`.a.$'
; Decrement a
--a
}
; After the main loop, we need to transpose y back if we transposed it:
; x? Is x truthy?
; (t y) If so, transpose y
; y If not, return y as-is
x ? (ty) y
; The result is autoprinted.
```
] |
[Question]
[
>
> Holy wars have been fought over spaces vs. tabs. (And of course spaces, being
> objectively superior, won.) —[Alex A.](http://chat.stackexchange.com/transcript/message/23907461#23907461)
>
>
>
**S**ome peo**p**le [still refuse](https://codegolf.stackexchange.com/questions/57963/overcoming-cluster-size#comment139453_57963) to **a**ccept that
[whi**c**h is cl**e**arly](https://codegolf.stackexchange.com/questions/56001/my-god-its-full-of-spaces#comment137150_56001) **s**upreme. You've just received
**a** file using the incor**re**ct, **b**ad, and inf**e**rior form
of whi**t**espace, and now **t**he cont**e**nts of the file a**r**e
tainted and ruined.
You decide you might as well show the person who sent the file to you just how
wrong they are—violently.
## Description
As the title suggests, your challenge is to take a file that contains one or
more tabs:
```
this is an evil tab onoes
```
and ruthlessly shatter them into pieces:
```
this is an evil tab
o
n
o
e
s
```
Note that the Stack Exchange software turns literal tabs into four spaces
(because it's right), so tabs within this post will be displayed as four
spaces. The input to your program, however, will contain actual tabs.
## Challenge
The solution should take a single string as input, which may contain printable
ASCII, newlines, and tabs. There will always be at least a single tab in the
input.
The output should be the same string, with the following rules applied:
* Start the cursor at coordinates (0,0) and with a direction of right. The
coordinates are (column,row), zero-indexed, and the direction is which way
you should move the cursor after printing a character.
* For each character in the string:
+ If it's a newline, move to coordinates (0,n), where n is the number of
newlines in the string so far (including this one), and reset the
direction to right.
+ If it's a tab, output two spaces, *rotate the cursor direction 90 degrees
clockwise*, and output two more spaces, effectively "breaking" the tab in
half. Here's a visual example, where a tab is represented as `--->` and
spaces as `·`:
```
foo--->bar--->baz
```
becomes
```
foo···
·
b
a
r
·
·
zab··
```
+ Otherwise, simply output the character at the cursor and move the cursor
one step in the current direction.
Since you are reading the string from start to end, it is possible that you
will have to write "on top" of existing characters—this is okay. For example,
the input
```
foo--->bar
spaces are superior
```
should result in an output of
```
foo
b
spaces are superior
r
```
You may choose whether "broken tabs" should overwrite other characters—the original intention was that they do not, but the spec was ambiguous, so this is your decision.
Furthermore, after applying these rules, you may also
* add or remove as many trailing spaces as you would like.
* add a maximum of a single trailing newline.
The input will *never* contain trailing spaces; it will also never contain
leading or trailing newlines. You may also always assume that you will never
need to write to a column or a row less than 0 (i.e. off the screen).
## Test case
Tabs in this test case are represented as `--->` because otherwise SE gobbles
them up.
Input:
```
Test case. Here's a tab--->there's a tab--->everywhere a tab--->tab--->this is some more text
blah
blah
blah blah blah blah blah blah--->blaah--->blaah--->blah--->blaaaaah--->blah--->blah--->blah--->blah--->blah
```
Output:
```
Test case. Here's a tab
blah
blah t
blah blah blah blah blah blah
blaablah
r b
e l b
h 'h a l
a sa a a
l l h h
this is some mobe tbxt
haalhalb
b a
a b
t
bat a erehwyreve
```
Fancy animation:
![](https://i.stack.imgur.com/EeW21.gif)
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win!
[Answer]
# MATLAB, 144 bytes
The weapon of choice for dealing with strings is of course a language designed for manipulating numbers [citation needed]. Kidding aside, the great thing about Matlab is that it doesn't care if you assign to an array 'out of bounds': it will simply make a larger matrix. Furthermore, the default matrix element, `0`, is rendered as a space instead of a `null` character the ASCII spec prescribes.
Tabs are simply a jump in coordinates, so no spaces are outputted for a tab.
```
function o=q(t)
u=2;v=0;x=1;y=1;n=1;for s=t
if s==9 x=x+u-v;y=y+v+u;a=v;v=u;u=-a;elseif s<11
n=n+1;x=1;y=n;else
o(y,x)=s;x=x+u/2;y=y+v/2;end
end
```
I started out with 209 bytes, but some more careful golfing got rid of most of that; there's a lot of repetition in this code, so I did some trial-and-error which alternatives worked best. I don't think there's much space for more optimization with this code, but I'm always happy to be proven wrong. **Edit:** Tom Carpenter managed to prove me wrong; he managed to save 9 bytes which I optimized to save a whopping 29 bytes. Last byte saved by assuming there are no control characters (ASCII < 9) in the input - MATLAB strings aren't `null`-terminated.
[Answer]
# Python 3, ~~272~~ ~~270~~ ~~266~~ ~~262~~ ~~255~~ ~~253~~ 244 bytes
```
I=[]
try:
while 1:I+=[input()]
except:r=m=0
M=sum(map(len,I))
O=[M*[' ']for _ in[0]*M]
for l in I:
x=b=0;y=r;a=1;r+=1
for c in l:
if'\t'==c:a,b=-b,a;x+=a+2*b;y+=b-2*a
else:O[y][x]=c
x+=a;y+=b;m=max(m,y)
for l in O[:m+1]:print(*l,sep='')
```
The `\t` should be an actual tab character.
The code works somewhat like Zach Gates' answer, first generating a `M` by `M` grid where `M` is the sum of the lengths of the lines. (That's a huge amount of excess, but makes the code shorter.) It then loops through the characters, placing them in the correct spots, keeping track of the bottommost visited row. Finally, it prints all the lines up to that row.
The output contains (usually a huge amount of) trailing spaces and 1 trailing newline.
[Answer]
# Javascript (ES6), ~~264~~ 245 bytes
Tried the "create a giant grid of spaces, fill and trim" approach, which ended up 19 bytes shorter than the other.
```
a=t=>(o=`${' '.repeat(l=t.length)}
`.repeat(l).split`
`.map(q=>q.split``),d=x=y=z=0,s=c=>o[d>2?y--:d==1?y++:y][d?d==2?x--:x:x++]=c,[...t].map(c=>c=='\t'?(s` `,s` `,++d,d%=4,s` `,s` `):c==`
`?(x=d=0,y=++z):s(c)),o.map(p=>p.join``).join`
`.trim())
```
By modifying the second-to-last line like so, you can remove the large amount of trailing spaces on every line:
```
...o.map(p=>p.join``.trimRight())...
```
Try it here:
```
a=t=>(o=`${' '.repeat(l=t.length)}
`.repeat(l).split`
`.map(q=>q.split``),d=x=y=z=0,s=c=>o[d>2?y--:d==1?y++:y][d?d==2?x--:x:x++]=c,[...t].map(c=>c=='\t'?(s` `,s` `,++d,d%=4,s` `,s` `):c==`
`?(x=d=0,y=++z):s(c)),o.map(p=>p.join``.trimRight()).join`
`.trim())
function submit(){ O.innerHTML = a(P.value.replace(/\\t|-+>/g,'\t')); }
```
```
<p>Input: (Use <code>\t</code> or <code>---></code> for a tab.)</p>
<textarea id=P rows="10" cols="40">this is an evil tab\tonoes</textarea>
<br><button onclick="submit()">Try it!</button>
<p>Output: (Looks best in full-page mode.)</p>
<pre id=O>
```
Explanation coming soon; suggestions welcome!
[Answer]
# JavaScript (ES6), 180 ~~183~~
Using template strings, there are some newlines that are significant and counted.
That's a function returning the requested output (padded with tons of trailing spaces)
There is little to explain: the rows are builded as neeeded. There is not a direction variable, just the 2 offset for x and y, as in clockwise rotation they are easily managed: `dx <= -dy, dy <= dx`
Test running the snippet below in Firefox
```
f=s=>[...s].map(c=>c<`
`?(x+=2*(d-e),y+=2*(e+d),[d,e]=[-e,d]):c<' '?(y=++r,e=x=0,d=1):(t=[...(o[y]||'')+' '.repeat(x)],t[x]=c,o[y]=t.join``,x+=d,y+=e),o=[r=x=y=e=0],d=1)&&o.join`
`
// TEST
// Avoid evil tabs even in this source
O.innerHTML = f(`Test case. Here's a tab--->there's a tab--->everywhere a tab--->tab--->this is some more text
blah
blah
blah blah blah blah blah blah--->blaah--->blaah--->blah--->blaaaaah--->blah--->blah--->blah--->blah--->blah`
.replace(/--->/g,'\t'))
```
```
<pre id=O></pre>
```
[Answer]
# Python 2, ~~370~~ ~~369~~ 368 bytes
Thanks to [@sanchises](https://codegolf.stackexchange.com/users/32352/sanchises) and [@edc65](https://codegolf.stackexchange.com/users/21348/edc65) for saving me a byte each.
```
J=''.join
u=raw_input().replace('\t',' \t ')
w=u[:]
G=range(len(u))
d,r=0,[[' 'for _ in G]for _ in G]
u=u.split('\n')
for t in G:
x,y=0,0+t
for c in u[t]:
if c=='\t':d=(d+1)%4
if c!='\t':
if c.strip():r[y][x]=c
if d<1:x+=1
if d==1:y+=1
if d==2:x-=1
if d>2:y-=1
r=r[:max(i for i,n in enumerate(r)if J(n).strip())+1]
for i in r:print J(i).rstrip()
```
It generates the largest grid possible and then loops around, character by character, switching direction at each tab.
] |
[Question]
[
A [comment I made in chat](http://chat.stackexchange.com/transcript/message/20243968#20243968) and the ensuing conversation inspired me to make this challenge.
>
> *Am I the only one referred to by initials around here? We are all about golfing things down. We can have MB and D-nob and ... O.*
>
>
>
If I'm known as "CH" then I think everyone else ought to have an initial-based nickname as well.
Here's a list of the top 100 Programming Puzzles & Code Golf users by reputation to play with:
```
Martin Büttner
Doorknob
Peter Taylor
Howard
marinus
Dennis
DigitalTrauma
David Carraher
primo
squeamish ossifrage
Keith Randall
Ilmari Karonen
Quincunx
Optimizer
grc
Calvin's Hobbies
ugoren
Mig
gnibbler
Sp3000
aditsu
histocrat
Ventero
xnor
mniip
Geobits
J B
Joe Z.
Gareth
Jan Dvorak
isaacg
edc65
Victor
steveverrill
feersum
ace
Danko Durbić
xfix
PhiNotPi
user23013
manatwork
es1024
Joey
daniero
boothby
nneonneo
Joey Adams
Timwi
FireFly
dansalmo
grovesNL
breadbox
Timtech
Flonk
algorithmshark
Johannes Kuhn
Yimin Rong
copy
belisarius
professorfish
Ypnypn
trichoplax
Darren Stone
Riot
ProgramFOX
TheDoctor
swish
minitech
Jason C
Tobia
Falko
PleaseStand
VisioN
leftaroundabout
alephalpha
FUZxxl
Peter Olson
Eelvex
marcog
MichaelT
w0lf
Ell
Kyle Kanos
qwr
flawr
James_pic
MtnViewMark
cjfaure
hammar
bitpwner
Heiko Oberdiek
proud haskeller
dan04
plannapus
Mr Lister
randomra
AShelly
ɐɔıʇǝɥʇuʎs
Alexandru
user unknown
```
([this is how I got it](https://api.stackexchange.com/docs/users#pagesize=100&order=desc&sort=reputation&filter=!KWFow8qjaaRs*&site=codegolf&run=true))
# Challenge
Write a program or function that takes in a list of strings and outputs another list of strings of their minimal, unique, initial-based nicknames, giving preference to those closer to the start of the list.
Apply this method to each string S in the list in the order given to create the nicknames:
1. Split S up into words separated by spaces, removing all spaces in the process.
2. List the nonempty prefixes of the string of the first letters of the words in S, from shortest to longest.
e.g. `Just Some Name` → `J`, `JS`, `JSN`
3. Choose the first item in this list that is not identical to an already chosen nickname as the nickname for S. Stop if a nickname was chosen, continue to step 4 otherwise.
e.g. if `Just Some Name` was the first string then `J` is guaranteed to be the nickname.
4. List the prefixes again, but this time include the second letter of the first word in it's natural place.
e.g. `Just Some Name` → `Ju`, `JuS`, `JuSN`
5. Do the same as in step 3 for this list, stopping if a unique nickname is found.
6. Repeat this process with the remaining letters of the first word, eventually inserting letters into the second word, then the third, and so on, until a unique nickname is found.
e.g. The first unique string listed here will be the nickname:
`Jus`, `JusS`, `JusSN`
`Just`, `JustS`, `JustSN`
`Just`, `JustSo`, `JustSoN` (note that `o` was not added after `Just`)
`Just`, `JustSom`, `JustSomN`
`Just`, `JustSome`, `JustSomeN`
`Just`, `JustSome`, `JustSomeNa`
`Just`, `JustSome`, `JustSomeNam`
`Just`, `JustSome`, `JustSomeName`
In the end all the input strings should end up with a unique nickname (potentially identical to the string). **You may assume that none of the input strings will map to the same nickname using this method.**
# Example
**Updated to fix my mistake!**
For the input
```
Martin Buttner
Doorknob
Peter Taylor
Howard
marinus
Dennis
DigitalTrauma
David Carraher
Martin Bitter
Martin Butter
Martin Battle
Martini Beer
Mart Beer
Mars Bar
Mars Barn
```
the nicknames would be
```
M
D
P
H
m
De
Di
DC
MB
Ma
MaB
Mar
MarB
Mars
MarsB
```
# Details
* Input can be from a file (one name per line), or one name at a time via stdin/command line, or as a function argument of a list of strings, or as a function arg of a single string with newlines between names.
* Output should be printed to stdout (one nickname per line) or returned by the function as a list of strings, or as one string with newlines between nicknames.
* Ideally programs will work for names that contain any characters except [line terminators](http://en.wikipedia.org/wiki/Newline#Unicode). However, you may assume that all the names only contain [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). (The PPCG names don't.)
* Only the [regular space character](http://www.fileformat.info/info/unicode/char/0020/index.htm) counts as a word separator. Leading and trailing spaces can be ignored.
# Scoring
The shortest submission [in bytes](https://mothereff.in/byte-counter) wins. Tiebreaker goes to the answer posted earliest.
[Answer]
# JavaScript (ES6) 159
Following the specs and not the example.
I generate the candidate nicknames having a current middle word (at the beginning, the first word). The words before the current are used 'as is'. The words after the current contribute with no - or just the first - character. The current word contributes with 1 more character for each loop.
Example 'Just Some Name' => 'Just','Some','Name'
Cw `Just`, position `1`, try `J`, `JS`, `JSN`
Cw `Just`, position `2`, try `Ju`, `JuS`, `JuSN`
Cw `Just`, position `3`, try `Jus`, `JusS`, `JusSN`
Cw `Just`, position `4`, try `Just`, `JustS`, `JustSN`
Now `Just` is exhausted, `Some` becomes Cw, position restarted to 2 (for position 1, all already tried)
Cw `Some`, position `2`, try `Just`, `JustSo`, `JustSoN`
Cw `Some`, position `3`, try `Just`, `JustSom`, `JustSomN`
Cw `Some`, position `4`, try `Just`, `JustSome`, `JustSomeN`
Now `Some` is exhausted, `Name` becomes Cw, position restarted to 2
Cw `Name`, position `2`, try `Just`, `JustSome`, `JustSomeNa`
Cw `Name`, position `3`, try `Just`, `JustSome`, `JustSomeNam`
Cw `Name`, position `4`, try `Just`, `JustSome`, `JustSomeName`
That's all folks!
**The code**
(q is current word position, p is slicing position)
```
F=l=>
l.map(w=>{
for(w=w.match(/[^ ]+/g),q=p=0;
w.every((w,i)=>~o.indexOf(t+=i<q?w:i>q?w[0]:w.slice(0,p+1)),t='')
&&(w[q][p++]||(p=1,w[++q]));
);
o.push(t)
},o=[])&&o
```
**Test** In Firefox/FireBug console
```
F(['Martin Buttner','Doorknob','Peter Taylor','Howard','marinus'
,'Dennis','DigitalTrauma','David Carraher'
,'Martin Bitter','Martin Butter','Martin Battle','Martini Beer','Mart Beer'])
```
>
> ["M", "D", "P", "H", "m", "De", "Di", "DC", "MB", "Ma", "MaB", "Mar", "MarB"]
>
>
>
[Answer]
# CJam, ~~58~~ 53 bytes
This can be golfed a lot.. But for starters:
```
LqN/{:Q1<aQ,,:)QS/f{{1$<_,@-z1e>}%W<s}+{a1$&!}=a+}/N*
```
**Code Expansion**:
```
L "Put an empty array on stack. This is the final nickname array";
qN/{ ... }/ "Read the input and split it on new lines. Run the block for each";
:Q1<a "Store each name in Q and get its first char. Wrap it in an array";
Q,,:) "Get an array of 1 to length(name) integers";
QS/ "Split the name on spaces";
f{{ }% } "for each of the integer in the array, run the code block";
"and then for each of the name part, run the inner code block";
1$< "Copy the integer, take first that many characters from the";
"first part of the name";
_,@-z1e> "Get the actual length of the part and the number of characters";
"to be taken from the next name part, minimum being 1";
W< "Get rid of the last integer which equals 1";
s "Concat all name parts in the array";
+ "Add the list of nick names as per spec with the first character";
{ }= "Get the first nick name that matches the criteria";
a1$& "Wrap the nick name in an array and do set intersection with";
"the copy of existing nick names";
! "Choose this nick name if the intersection is empty";
N* "After the { ... }/ for loop, the stack contains the final";
"nick names array. Print it separated with new lines";
```
[Try it online here](http://cjam.aditsu.net/#code=LqN%2F%7B%3AQ1%3CaQ%2C%2C%3A)QS%2Ff%7B%7B1%24%3C_%2C%40-z1e%3E%7D%25W%3Cs%7D%2B%7Ba1%24%26!%7D%3Da%2B%7D%2FN*&input=Martin%20Buttner%0ADoorknob%0APeter%20Taylor%0AHoward%0Amarinus%0ADennis%0ADigitalTrauma%0ADavid%20Carraher%0AMartin%20Bitter%0AMartin%20Butter%0AMartin%20Battle%0AMartini%20Beer%0AMart%20Beer)
[Answer]
# PHP, ~~327~~ ~~289~~ ~~275~~ ~~274~~ 270
There may still be a little golfing potential.
```
while($n=fgets(STDIN)){$c=count($w=preg_split('/\s+/',trim($n)));$p=[];for($k=0;$k<$c;$p[$k]++){for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1);for($j=1;$j<=strlen($t);$j++)if(!in_array($v=substr($t,0,$j),$u))break 2;$k+=$p[$k]==strlen($w[$k]);}echo$u[]=$v,'
';}
```
* Program operates on stdin/stdout, works on ASCII, buggy on UTF
* usage: `php -d error_reporting=0 golfnicks.php < nicknames.txt`
* or `cat <<EOF | php -d error_reporting=0 golfnicks.php` + list of names + `EOF`
* To test as function in web browser: fetch the breakdown, uncomment all lines marked with `// FUNC` and comment the one marked with `//PROG`.
Try `f(array_fill(0,21,'Just Some Name'));`
**breakdown**
```
#error_reporting(0);function f($a){echo'<pre>'; // FUNC
#foreach($a as$n) // FUNC
while($n=fgets(STDIN)) // PROG
{
$c=count($w=preg_split('/\s+/',trim($n))); // split name to words, count them
$p=[]; // initialize cursors
for($k=0;$k<$c;$p[$k]++)
{
for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1); // concatenate prefixes
for($j=1;$j<=strlen($t);$j++) // loop through possible nicks
if(!in_array($v=substr($t,0,$j),$u)) // unused nick found
break 2; // -> break cursor loop
$k+=$p[$k]==strlen($w[$k]); // if Cw exhausted -> next word
// strlen()-1 would be correct; but this works too)
}
echo$u[]=$v,'
';
}
#echo '</pre>';} // FUNC
```
] |
[Question]
[
Many languages allow strings to be "added" with `+`. However this is really concatenation, a *true* addition would follow the group axioms:
* It is closed (the addition of any two strings is always a string)
* It is associative ( \$\forall a b . (a + b) + c = a + (b + c)\$)
* There is an identity (\$\exists e . \forall a . a + e = a\$)
* Every element has an inverse (\$\forall a . ∃b . a + b = e\$)
*(concatenation violates the 4th group axiom)*
So my task to you is to implement a true string addition, that is a function that takes two sequences of bytes representing strings and returns a third such that your function satisfies all the group axioms on sequences of bytes.
It must work on all sequence of bytes representing strings including those with null bytes.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~177~~ ~~170~~ ~~163~~ 130 bytes
```
lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
while n:n-=1;s+=chr(n%256);n>>=8
return s
def d(n,c=0):
while s(c)!=n:c+=1
return c
```
[Try it online!](https://tio.run/##VYtBCsIwEEX3OUUMSGdohFZRJGW69hAitElLC3UsSUU9fbRdKG7@4v33xtfU3XgXWzrHobrWrpKVrk0ABxVeHNSIwjWtDMD6SZkOlCRohHx0/dBINryhvAgp2c4Dr7f7AxZclnQU0jfT3bMMS@4@uaXsVwawuCI2NqX869o4@p4naEGdeqXnQSKlUPzzhc5nfAM "Python 3 – Try It Online")
-14 bytes thanks to notjagan
-33 bytes thanks to Leaky Nun (and switched endianness)
I have no business trying to golf anything in Python, but I didn't want to use Lua since this method needs large exact integers to work on reasonable length stings. (Note: the algorithm is still Really Slow when ramping up the string length.) This is mostly just to provide an answer ;)
Each string is self-inverse, and the empty string is the identity. This simply performs xor under a simple bijection between strings and non-negative integers. `s` is a helper function that computes the bijection (one way only), and `d` is the inverse.
Non-slow version (148 bytes, courtesy of Leaky Nun):
```
lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
while n:n-=1;s=chr(n%256)+s;n>>=8
return s
def d(n,c=0):
while n:c=c*256+ord(n[0])+1;n=n[1:]
return c
```
[Try it online!](https://tio.run/##XcvBCoJAEAbgu0@xCeFObqBFEcp47g06WIHurihso@wa1dPb4qGi2/zz/9/wGtuetlOD58lUt1pVrBJ15rjiFVwVrwECpRvmOIknJsJhFEEWsEfbGc0oozWmuUPZWk7LzW4PscupKPAQMKvHuyXmZq@8l5j8Uoly5UXcW1@WyQXiNCekMs0uHyynwXY08oaHR21ML9ipt0YtQvGXATEMIfiuOz@Zv/6C6Q0 "Python 3 – Try It Online")
I'm going to hijack this for a group-theory primer as well.
Any right inverse is **a** left inverse: **inv(a) + a = (inv(a) + a) + e = (inv(a) + a) + (inv(a) + inv(inv(a))) = inv(a) + (a + inv(a)) + inv(inv(a)) = (inv(a) + e) + inv(inv(a)) = inv(a) + inv(inv(a)) = e**
This also means that **a** is an inverse of **inv(a)**.
Any right identity is a left identity: **e + a = (a + inv(a)) + a = a + (inv(a) + a) = a**
The identity is unique, given other identity **f**: **e = e + f = f**
If **a + x = a** then **x = e**: **x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + a = e**
Inverses are unique, if **a + x = e** then: **x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + e = inv(a)**
Following the proofs should make it fairly easy to construct counterexamples for proposed solutions that don't satisfy these propositions.
Here's a more natural algorithm I implemented (but didn't golf) in [Lua](https://www.lua.org). Maybe it will give someone an idea.
```
function string_to_list(s)
local list_val = {}
local pow2 = 2 ^ (math.log(#s, 2) // 1) -- // 1 to round down
local offset = 0
list_val.p = pow2
while pow2 > 0 do
list_val[pow2] = 0
if pow2 & #s ~= 0 then
for k = 1, pow2 do
list_val[pow2] = 256 * list_val[pow2] + s:byte(offset + k)
end
list_val[pow2] = list_val[pow2] + 1
offset = offset + pow2
end
pow2 = pow2 // 2
end
return list_val
end
function list_to_string(list_val)
local s = ""
local pow2 = list_val.p
while pow2 > 0 do
if list_val[pow2] then
local x = list_val[pow2] % (256 ^ pow2 + 1)
if x ~= 0 then
x = x - 1
local part = ""
for k = 1, pow2 do
part = string.char(x % 256) .. part
x = x // 256
end
s = s .. part
end
end
pow2 = pow2 // 2
end
return s
end
function list_add(list_val1, list_val2)
local result = {}
local pow2 = math.max(list_val1.p, list_val2.p)
result.p = pow2
while pow2 > 0 do
result[pow2] = (list_val1[pow2] or 0) + (list_val2[pow2] or 0)
pow2 = pow2 // 2
end
return result
end
function string_add(s1, s2)
return list_to_string(list_add(string_to_list(s1), string_to_list(s2)))
end
```
The idea is basically to split the string based on the power-of-two components of its length, and then treat these as fields with a missing component representing zero, and each non-missing component representing numbers from 1 up to 256^n, so 256^n+1 values total. Then these representations can be added component-wise modulo 256^n+1.
Note: This Lua implementation will have numeric overflow problems for strings of sizes greater than 7. But the set of strings of length 7 or less is closed under this addition.
[Try it online!](https://tio.run/##jVTLbtswELzrKxYMWpCNrNgCnEMB90eKxmD0iAUrokBStYKi/XV3@RDpSDaSk@mZ3VlyhmI78PO5HrpCN6IDpWXTvey12LeN0lSxBKAVBW/B/N//xsUO/vwNaC9OOSI5PAF95fqQteKF3qkUcgYPD7BhsFrZBWgBUgxdCaU4daFf1LWqNCqsDeRHZD0CRhmx06FpKzfmB6yxGbFY@dMQv3w7QFO7yq9wp@AfoqAPVWcpgFpIOGLpJnVFXuqqXL59hG9z@B7U9@c3XVG/6Xs4Mi9RdWVyQ2ohsvGV4ehBzh85ynl37Q@aaEhHyUoPsgvaiUGTEKKFMUIXJp2qYpYKRQmZhxjtv@k7Gjw7z4XBTmxcnvkLUGPok5NDBybbUG5c5ARWYoRVcCrsk0s97fzDTGEqdy5kxYFLOuJecCsMsszSF9VuqHF5@xjgmCtY09SsceI/G5i6lhQvy5ARHmRa5jEvWamh1Ve/PPvRvfIxKmT9hUbWMzvd9H/8Wbm6cHWjpofQ7TXDAAORXxKfcsCNmNngXx1jhEIHVM5md3x2mW3h7KXasHTxeuWMMTPqXO/iiCThSlVS05oS/lyQlBC229kle0chU1ylTA/St7re3bh8u135//btIJywdAGiGDNyqNUjrCkRR/5G2Pk/ "Lua – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 93 bytes
```
f=lambda a,b,L=len:f(c:=a.rstrip(x:=a[-1]),x*(L(a)-L(c)^L(b)-L(d:=b.lstrip(x)))+d)if a else b
```
[Try it online!](https://tio.run/##vZLRasMgFIbvfYqDV7qmgbKbLeAb5A3KBsdoNtNURd1o9/KZLg0rXXdRGDsgMcdz/v8zJ/6YXp29f/Bhmnox4l4qBKxk1YpR26ZnXSOwDjEF49kh77frzROvDnesZcjXLev4c8tk2alGyHo8VXLOV4qbHhD0GDXIyey9CwlM0iE5N0ZCUCkQ0BOjtE0mHfMLpcTYdx1yh4CFpgHcNk32JaR3AQwYCwHti2aPvCGQo6SxpPfoGaX14Iytvq1qH5x66xKjh@MHrSBorzEJw0/tJTDGXA2ZiWFuPSFxEALwH33ny@dP@@W8YMwA8TrAGVeEFWzOxP@Ab5EZLlxgDeairMQuzy2Ws7yGH6dFSN7MM/ArRotcd7Pc7je5y3HMI5G8gm7@D@ZEeciS44T4YGzWdzvKp08 "Python 3.8 (pre-release) – Try It Online")
This doesn’t use base conversion or character codes at all. It works on strings over any alphabet \$\mathcal A\$.
We define addition by concatenation \$a + b = ab\$ except when \$a\$ ends with the same character \$\mathtt x\$ that starts \$b\$, in which case we use
$$\underbrace{\mathtt{xx\cdots x}}\_{\text{$i$ times}} + \underbrace{\mathtt{xx\cdots x}}\_{\text{$j$ times}} = \underbrace{\mathtt{xx\cdots x}}\_{\text{$i \oplus j$ times}},$$
where \$\oplus\$ is bitwise XOR, perhaps repeatedly if \$i = j\$. For example,
$$\mathtt{uuzzzzzyxx} + \mathtt{xxyzzzv} = \mathtt{uuzzzzzzv},$$
because \$2 \oplus 2 = 0\$, \$1 \oplus 1 = 0\$, and \$5 \oplus 3 = 6\$. The identity is the empty string, and the inverse of a string is its reversal.
This describes the [free product](https://en.wikipedia.org/wiki/Free_product) of \$|\mathcal A|\$ copies of the group \$(\mathbb N, \oplus)\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
‘ḅ⁹^/ḃ⁹’
```
This uses a bijective mapping **φ** from byte arrays to the non-negative integers, XORs the result of applying **φ** to two input strings, then applies **φ-1** to the result.
The empty array is the neutral element and every byte arrays is its own inverse.
[Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO1ofNe6M03@4oxlIP2qY@f///2hDHQUjHQVjHQWTWB0FhWhTHQUzHQXzWAA "Jelly – Try It Online")
### How it works
```
‘ḅ⁹^/ḃ⁹’ Main link. Argument: [A, B] (pair of byte arrays)
‘ Increment all integers in A and B.
ḅ⁹ Convert from base 256 to integer.
^/ XOR the resulting integers.
ḃ⁹ Convert from integer to bijective base 256.
’ Subtract 1.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 114 bytes
```
lambda a,b:s(d(a)^d(b))
d=lambda s:s and d(s[1:])*256+ord(s[0])+1or 0
s=lambda d:d and chr(~-d%256)+s(~-d/256)or''
```
[Try it online!](https://tio.run/##XcxNC4JAEAbgu79iGQh30uiLOggdOvYbymBt1hRqN3YWQQ/9dVP7pNO8M@/D3GpfWLNo882hvahrRkqoOEtYklR4JJkhBrR5NZywUIYESd7PkxTHi9U6sq5fZylGc@vELOC3poQGfSqcvE9o1GGMuI/TPloXhu3NlcYL2DLbU6l8WWkInrdc5hKWEAvwmj1gF9h3zZkBP2QA3RjIr8DgZWBH2vjS19@/0PQUfoiptGP9LxrA9gE "Python 2 – Try It Online") Works by XORing the strings interpreted as little-endian bijective base 256.
[Answer]
# [Python 2](https://docs.python.org/2/), 197 bytes
```
def n(s):
n=s and ord(s[0])+1 or 0
for c in s[1:]:n=n*256+ord(c)
return(-1)**n*n/2
def f(l,r,s=""):
i=n(l)+n(r)
i=abs(i*2+(i<=0))
while i>257:s=chr(i%256)+s;i/=256
return["",chr(i-1)+s][i>0]
```
[Try it online!](https://tio.run/##bZDBToQwEIbvPMWkibEF3GUxqwnKJsaTN28ekAPQEiaSYdPprq4vjwVxjYmn@dv5Zr6m@5PrBkrHUZsWSLLKAqCcoSINg9WSi6RU0cZnSAJofWkACbjYZGVGOYXp9iaawEYFYI07WJJXGxWGFNI6DaatrexjG3MuxLQcc5K9ikhaNR2qmiWGaSTxPk@Uv3rvsDeAu3R7m3HedFbihXeoiO9wnfv0oymEiOe210VcFrhLynFvkZx47Ac2WgTfpxfT96vVClxXuUuGNyRdwVAfcTgwZM8iWLgH5qHByuHRLKP@6a0UnyIGUbFu21YoH1lXLNSZmPu@LMQZUMteEE/akEN3En9n/H/8InQ0lv/xNrOyPvus2Vs5t18/kmQifE1nyIdrrx2/AA "Python 2 – Try It Online")
Turns the string into a number (reducing by charcode), negates if odd, then halves. Not as golfy as the other one, but faster :P
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 119 bytes
```
a=>b=>q(p(a)^p(b));p=x=>Buffer(x,h=0).map(c=>h=h*256-~c)|h;q=(n,i=0)=>n<2**i?i?q(n>>8,i-8)+Buffer([n]):'':q(n-2**i,i+8)
```
[Try it online!](https://tio.run/##fY7LasMwEEX3/QrvNBPbwo8mmKRSoL/QZZwSR7VjBVfyQy6CPn7dVUICDbTd3ZlzuNxj8VYMopetCZV@KaeKTQXje8Y7aKHA5xb2iKuWWcYfx6oqe7BBzSKkr0ULgvGa1bNkvgi/BH7Uq46BCqTDjKuHZDaTa7nuQHGeBTLM0L9UbNQWl4QsHQpPViD9DKdqVMJIrTw9mnY0YNF794RWg25K2ugDbCil1xG4PS8wjJM8t8QH47sZSI1@Mr1UB4jdMTRSlBAj0qOWardD7/PuUl4ByW2S5vZ@TvCU08zliCD@acQit9HiP@OafxjOiU8wcV8g6a8sPbPkttmdNwJO3w "JavaScript (Node.js) – Try It Online")
xor of id of string
] |
[Question]
[
# Challenge description
**Dominoes** is a game played with tiles with two values on it - one on the left, one on the right, for example `[2|4]` or `[4|5]`. Two tiles can be joined together if they contain a common value. The two tiles above can be joined like this:
`[2|4][4|5]`
We'll call a sequence of `n` joined tiles a **chain** of length n. Of course, tiles can be rotated, so tiles `[1|2]`, `[1|3]` and `[5|3]` can be rearranged into a chain `[2|1][1|3][3|5]` of length 3.
Given a list of pairs of integers, determine the length of the longest chain that can be formed using these tiles. If the list is empty, the correct answer is `0` (note that you can always form a chain of length `1` from a non-empty list of tiles).
# Sample input / output
```
[(0, -1), (1, -1), (0, 3), (3, 0), (3, 1), (-2, -1), (0, -1), (2, -2), (-1, 2), (3, -3)] -> 10
([-1|0][0|-1][-1|2][2|-2][-2|-1][-1|1][1|3][3|0][0|3][3|-3])
[(17, -7), (4, -9), (12, -3), (-17, -17), (14, -10), (-6, 17), (-16, 5), (-3, -16), (-16, 19), (12, -8)] -> 4
([5|-16][-16|-3][-3|12][12|-8])
[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] -> 7
([1|1][1|1][1|1][1|1][1|1][1|1][1|1])
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] -> 1
(any chain of length 1)
[] -> 0
(no chain can be formed)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes
```
s:papcb~k~c:{#=l2}al|,0
```
[Try it online!](https://tio.run/nexus/brachylog#@19sVZBYkJxUl12XbFWtbJtjVJuYU6Nj8P9/dLShlVGsVbSxlQmQNLEyBJKGVqaxsf@jAA "Brachylog – TIO Nexus")
## Explanation
```
s:papcb~k~c:{#=l2}al|,0
s Check subsets of the input (longest first).
:pa Check all permutations inside the input's elements
p and all permutations /of/ the input's elements.
c Flatten the result;
b delete the first element;
~k find something that can be appended to the end so that
~c the result can be unflattened into
:{ }a a list whose elements each have the property:
#= all the elements are equal
l2 and the list has two elements.
l If you can, return that list's length.
|,0 If all else fails, return 0.
```
So in other words, for input like `[[1:2]:[1:3]:[5:3]]`, we try to rearrange it into a valid chain `[[2:1]:[1:3]:[3:5]]`, then flatten/behead/unkknife to produce `[1:1:3:3:5:_]` (where `_` represents an unknown). The combination of `~c` and `:{…l2}a` effectively splits this into groups of 2 elements, and we ensure that all the groups are equal. As we flattened (doubling the length), removed one element from the start and added one at the end (no change), and grouped into pairs (halving the length), this will have the same length as the original chain of dominoes.
The "behead" instruction will fail if there are no dominoes in the input (actually, IIRC the `:pa` will also fail; `a` dislikes empty lists), so we need a special case for 0. (One big reason we have the asymmetry between `b` and `~k` is so that we don't also need a special case for 1.)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 29 bytes
```
v0|sp:{|r}aLcbk@b:{l:2%0}a,Ll
```
[Try it online!](https://tio.run/nexus/brachylog#@19mUFNcYFVdU1Sb6JOclO2QZFWdY2WkalCbqOOT8/9/dLShlVGsFZA0BpKmQDL2fxQA "Brachylog – TIO Nexus")
Pretty sure this is awfully long, but whatever. This is also awfully slow.
### Explanation
```
v0 Input = [], Output = 0
| Or
sp:{|r}aL L (a correct chain) must be a permutation of a subset of the
Input with each tile being left as-is or reversed
Lcbk Concatenate L into a single list and remove the first and
last elements (the two end values don't matter)
@b Create a list of sublists which when concatenated results in
L, and where each sublist's elements are identical
:{ }a, Apply this to each sublist:
l:2%0 It has even length
Ll Output = length(L)
```
The reason this will find the biggest one is because `s - subset` generates choice points from the biggest to the smallest subset.
[Answer]
# Mathematica, 191 bytes
```
If[#=={},0,Max[Length/@Select[Flatten[Rest@Permutations[#,∞]&/@Flatten[#,Depth[#]-4]&@Outer[List,##,1]&@@({#,Reverse@#}&/@#),1],MatchQ[Differences/@Partition[Rest@Flatten@#,2],{{0}...}]&]]]&
```
Can be golfed a fair bit, I'm sure. But basically the same algorithm as in [Fatalize's Brachylog answer](https://codegolf.stackexchange.com/a/105501/56178), with a slightly different test at the end.
[Answer]
## JavaScript (Firefox 30-57), 92 bytes
```
(a,l)=>Math.max(0,...(for(d of a)for(n of d)if(!(l-n))1+f(a.filter(e=>e!=d),d[0]+d[1]-n)))
```
* `l` is the last value, or `undefined` for the initial invocation. `l-n` is therefore a falsy value if the domino can be played.
* `d` is the domino under consideration.
* `n` is the end of the domino under consideration for chaining to the previous domino. The other end may readily be calculated as `d[0]+d[1]-n`.
* `0,` simply handles the base case of no playable dominoes.
[Answer]
# [Haskell](https://www.haskell.org/), ~~180 134~~ ~~131~~ 117 bytes
```
p d=maximum$0:(f[]0d=<<d)
f u n[]c=[n]
f u n(e@(c,d):r)a@(_,b)=f(e:u)n r a++(f[](n+1)(r++u)=<<[e|b==c]++[(d,c)|b==d])
```
[Try it online!](https://tio.run/##lVBBbsMgELz7FXvIgRW4MnYbp1aQ8oceEaqIsZUogVhOrPTQv7uASdprTzs7OzuzcNDXU3c@z1YfHQgYptvHbYQXuB4ud1iB1QMMIDOQpGCQc2RA@AN4pgq1YlCkGvm8/KNYQGDKOPPbZRLnFSoGwZvXvqsD/erBe0wpoyCuhCmPYx7mPKblax9XLwIP3yIKrnz9JPmv1eaZla78V1UsfcHjNVU6Nsb6pHjIhsESGIRpSWWg5gGMsPrraCe7KhrSS1UYsd0azHqYwEnVCunU0pBuR1pmsBlR78gn26PoSddM6GAETWnYJo5yJCOlE3ob2X3vhWgVpZIY1mLojMJ5/gE "Haskell – TIO Nexus") New approach turned out to be both shorter and more efficient. Instead of all possible permutations only all valid chains are build.
*Edit:* The 117 byte version is much slower again, but still faster than the brute-force.
---
Old brute-force method:
```
p(t@(a,b):r)=[i[]t,i[](b,a)]>>=(=<<p r)
p e=[e]
i h x[]=[h++[x]]
i h x(y:t)=(h++x:y:t):i(h++[y])x t
c%[]=[0]
c%((_,a):r@((b,_):_))|a/=b=1%r|c<-c+1=c:c%r
c%e=[c]
maximum.(>>=(1%)).p
```
This is a brute-force implementation which tries all possible permutations (The number of possible permutations seems to be given by [A000165](http://oeis.org/A000165), the "***double** factorial of even numbers*"). [Try it online](https://tio.run/nexus/haskell#LY3LasQwDEX3@QotGpCImybtPMBEw/xDl8YExwzEi7TG9VAPzL@nSujmcDlI9y4ufAFDvOfPnKCFn/n7F15gcSUs96XFy4Wxr4naKNZgr95J4cfOgzoKT@osPO75sPtOdWTXiPmKTk2kE7EJxmYlwEk5slspD0OERFWEG5ubrQLMUIxlMzeNKfZf4ENnYhRX9BZ12LJ5WCqQK19vD52VgDhKs05XlImR9Ej0dG88cV@npx9efdOz175OciuD3q7rHw "Haskell – TIO Nexus") barely manages inputs up to length 7 (which is kind of impressive as 7 corresponds to *645120* permutations).
**Usage:**
```
Prelude> maximum.(>>=(1%)).p $ [(1,2),(3,2),(4,5),(6,7),(5,5),(4,2),(0,0)]
4
```
[Answer]
# Python 2, 279 bytes
Golfed:
```
l=input()
m=0
def f(a,b):
global m
l=len(b)
if l>m:m=l
for i in a:
k=a.index(i)
d=a[:k]+a[k+1:]
e=[i[::-1]]
if not b:f(d,[i])
elif i[0]==b[-1][1]:f(d,b+[i])
elif i[0]==b[0][0]:f(d,e+b)
elif i[1]==b[0][0]:f(d,[i]+b)
elif i[1]==b[-1][1]:f(d,b+e)
f(l,[])
print m
```
[Try it online!](https://tio.run/nexus/python2#bY3BisQgDIbvPkWOltpF25vgvEjwoFSHULXD0IV9@27anYWZYUBI8n9f4l4ctdv3JjtRnRZzypBlULGzAq5ljaFAFVBcSU3GTgBlKJdqqysC8noHAmoQWIbFhS9qc/qRxB7MLqBdfB9w6Y31nCSHhNYOxh8TH2rrBtFmOSskf@ykwimh9s5FZA@NP3HsPwna8zt56uMTNW@Udz/wl/OpE1kWhfzJ7U5tg7rviFoBWwrQ/DecTEedFOhHPfNhfDL@miMZT8bb40MeJu9/AQ)
Same thing with some comments:
```
l=input()
m=0
def f(a,b):
global m
l=len(b)
if l>m:m=l # if there is a larger chain
for i in a:
k=a.index(i)
d=a[:k]+a[k+1:] # list excluding i
e=[i[::-1]] # reverse i
if not b:f(d,[i]) # if b is empty
# ways the domino can be placed:
elif i[0]==b[-1][1]:f(d,b+[i]) # left side on the right
elif i[0]==b[0][0]:f(d,e+b) # (reversed) left side on the left
elif i[1]==b[0][0]:f(d,[i]+b) # right side on left
elif i[1]==b[-1][1]:f(d,b+e) # (reversed) right side on the right
f(l,[])
print m
```
I'm posting because I didn't see any python answers...someone will see my answer and, in disgust, be forced to post something much shorter and efficient.
[Answer]
## Clojure, ~~198~~ 183 bytes
Update: Better handling of "maximum of possibly empty sequence"
```
(defn F[a C](remove(fn[i](identical? i a))C))(defn M[C](apply max 0 C))(defn L([P](M(for[p P l p](L l(F p P)))))([l R](+(M(for[r R[i j][[0 1][1 0]]:when(=(r i)l)](L(r j)(F r R))))1)))
```
Earlier version:
```
(defn F[a C](remove(fn[i](identical? i a))C))(defn M[C](apply max 1 C))(defn L([P](if(empty? P)0(M(for[p P l p](L l(F p P))))))([l R](M(for[r R[i j][[0 1][1 0]]:when(=(r i)l)](+(L(r j)(F r R))1)))))
```
Calling convention and test cases:
```
(L [])
(L [[2 4] [3 2] [1 4]])
(L [[3, 1] [0, 3], [1, 1]])
(L [[17 -7] [4 -9] [12 -3] [-17 -17] [14 -10] [-6 17] [-16 5] [-3 -16] [-16 19] [12 -8]])
(L [[0 -1] [1 -1] [0 3] [3 0] [3 1] [-2 -1] [0 -1] [2 -2] [-1 2] [3 -3]])
(L [[1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1]])
```
`F` returns elements of list `C` without the element `a`, `M` returns the max of input ingerers or 1.
`L` is the main function, when called with a single argument it generates all possible starting pieces and finds the max length for each of them. When called with two arguments the `l` is the first element of the sequence to which the next piece must match and `R` is rest of the pieces.
Generating permutations and "choose one element and split to rest" were quite tricky to implement succinctly.
] |
[Question]
[
[*Super Mario Galaxy*](https://www.mariowiki.com/Super_Mario_Galaxy) features two [rhombicuboctahedron](https://en.wikipedia.org/wiki/Rhombicuboctahedron)-shaped\* planets tiled with platforms that shrink as Mario runs across. Should Mario fall into a triangular hole or a gap left by a tile he previously touched, he will be consumed by the black hole at the core. (Watch: [Hurry-Scurry Galaxy](https://youtu.be/xfFBi7z_8cQ?t=1m12s), [Sea Slide Galaxy](https://youtu.be/xOl7au63XNg?t=1m30s))
[![Image: MarioWiki.com](https://i.stack.imgur.com/oQAwF.png)](https://i.stack.imgur.com/oQAwF.png)
Image: [MarioWiki.com](https://www.mariowiki.com/Hurry-Scurry_Galaxy)
(You can think of the planet as a 2x2x2 cube whose faces have been detached and connected to each other by 2x3 "bridges".)
Unfortunately, since my controller is very broken, Mario cannot jump and is limited to the four cardinal directions. Additionally, Mario moves very slowly and cannot retrace even one step without first having the platform behind him disappear.
Let's assume the camera is always above Mario's head and he starts at the bottom right of a 2x2 face:
```
■ ■
■ ■
■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ M ■ ■ ■
■ ■
■ ■
■ ■
```
Your program will take a list or string of directions, `U` `D` `L` `R` (up, down, left, right), representing Mario's walk around the planet so far as a series of steps. The program can output one of two distinct outputs: one representing that Mario is still alive and walking, and the other representing that somewhere along his walk, Mario has fallen into the Shrinking Satellite.
```
RR: ■ ■ RRD: ■ ■ RRL: ■ ■
■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ □ □ M ■ ■ ■ ■ ■ □ □ □ ■ ■ ■ ■ ■ □ M □ ■
■ ■ \ ■ ■ M ■ ■ \
■ ■ Let's-a go! ■ ■ \ ■ ■ W-aaaaaaaaaahh!
■ ■ ■ ■ W-aaaaaaaaaahh! ■ ■
```
Of course, unlike the above diagrams, you'll have to take the 3D into account. Here's a diagram that might help you visualize the scenario better:
```
Top 2x2 face
<- clockwise anticlockwise ->
- ■ - ■ - ■ - ■ -
/ \ / \ / \ / \
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ Left and right
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ M ■ ■ ■ ■ ■ ■ ■ ■ ■ edges wrap around.
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
\ / \ / \ / \ /
- ■ - ■ - ■ - ■ -
<- anticlockwise clockwise ->
Bottom 2x2 face
```
So according to this diagram, `UUUUURRRR` might look like this:
```
- ■ - ■ - □ - ■ -
/ \ / \ / \ / \
■ ■ ■ ■ □ □ ■ ■
■ ■ ■ ■ □ □ ■ ■
■ ■ ■ ■ □ □ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ □ ■ ■ ■ M ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ □ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
\ / \ / \ / \ /
- ■ - ■ - ■ - ■ -
```
And `UUUUUUUUULURRRRRR` might look like this:
```
- ■ - ■ - □ - □ -
/ \ / \ / \ / \
■ ■ ■ ■ □ ■ ■ □
■ ■ ■ ■ □ ■ ■ □
-> □ ■ ■ ■ □ ■ ■ □ ->
<- □ ■ ■ ■ ■ ■ ■ ■ ■ ■ □ ■ ■ ■ M □ □ □ □ □ <-
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ □ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■
\ / \ / \ / \ /
- ■ - ■ - ■ - ■ -
```
May the shortest program in bytes w-aaaaaaaaaahh!
## Test Cases
### Output 1: Still Alive
`DDDDDLUUUUU` - Mario walks across a bridge and back.
`RRRRDDDDLLL` - Mario walks in a triangle.
`LLLLLLUUUUUURRRRR` - Mario walks in a bigger triangle.
`ULLDRDDDRU` - Mario puts himself in peril.
`RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRR` - Mario takes an unconventional route... and puts himself in peril.
Mario crosses every tile exactly once.
`DDDDLUUUULLLLDDDLUUULLLLDDDDLUUUULLLLDDDLUUULLLURRRUUURDDDRRRRUUURDDDRRRRUUURDDDRRRRUUUUURDDDDD`
`DLDRDLDLLLDRRRDDDDLLLLLLLLLDRRRRRRRRRDDDDLLLDRRRDDDRUUURRRRULLLLUUUURRRULLLUUUUURDRURDRUURULURU`
### Output 2: W-aaaaaaaaaahh!
`LLR` - Mario attempts to retrace a step and falls off.
`UULDR` - Mario attempts to cross a tile twice and steps into air.
`RRDDDDD` - Mario walks off a bridge at the first D (ignore any following steps).
`RRRRDDDDLLLL` - Mario walks in a triangle and falls through the starting tile.
`LLLLLLUUUUUURRRRRR` - Mario walks in a bigger triangle and falls through the starting tile.
`UUUUUUUUUUUUUUUUUUUU` - Mario walks all the way around the planet and falls through the starting tile.
`RURDRURDRDLDRDLDLDLULDLLUU` - Mario takes an unconventional route and becomes disoriented.
Mario, realizing the peril he is in, is left with no choice.
`ULLDRDDDRUUU` `ULLDRDDDRUUL` `ULLDRDDDRUUR` `ULLDRDDDRUUD` `RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRRR` `RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRRU` `RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRRL` `RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRRD`
Finally, copy any test case from "Mario crosses every tile exactly once" and change or add one step at random. Mario should fall. (If you add a step to the end, Mario falls to grab the Power Star!)
\*[Cantellated cube](https://en.wikipedia.org/wiki/Cantellation_(geometry)) would be a more correct term as some faces aren't square, but you've got to admit - "rhombicuboctahedron" flows nicer.
[Answer]
# APL (Dyalog), ~~457~~ 441 bytes ([Classic Dyalog Character Set](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each))
```
r←'RULD'
S←{(r⍳⍵)⌷4 4⍴2 3 4 1 4 3 1 2 4,(⍳3),3 4 2 1}
C←{(⊂⍺)⌷⍵}
P←,⍉0 1 2 3∘.{2 4 1 3(C⍨⍣⍺)⍵}(⊂⍳4),C\S¨'LUULU'
v←6 6⍴(3⍴0),2(⊥⍣¯1)4512674568
a←1 4 4
N←{s y x←⍵+0,(r⍳⍺)⌷4 2⍴0 1 ¯1 0 0 ¯1 1 0
t Y X←⊃(1+(7<y+x)(0<y-x))⌷2 2⍴('U'5 0)('L'0 5)('R'0 ¯5)('D'¯5 0)
⊃(1+(1+y x)⌷(¯2⊖¯2⌽8 8↑4 4⍴1)∨¯1⊖¯1⌽8 8↑v)⌷((P⍳⊂(⊃s⌷P)C(S t)),(Y X+y x))(s y x)}
M←{T←24 6 6⍴0
~∨/,0>(6 6 6⍴v)-+/[2]6 4 6 6⍴↑(24⍴⍳4){{⊖⍉⍵}⍣⍺⊢⍵}¨⊂[2 3]T⊣{T[⊂⍵]+←1}¨(⊂a),{⊃N/(⌽⍵),⊂a}¨,\⍵}
```
*Thanks, Bubbler, for helping me shave off several bytes!*
[Try it online!](https://tio.run/##nVLBahsxEL3rK9STJHZd72rXGx9CL96jEsw6S1scHxZamoChJTHGxriHGEK6ZEt7aOm5oeBbDmkoBHrxp@hH3BlJdus05OBZpB3NzBu9mVHxrl97NS76b98slyf6/BPLcpUy0gF1wk90daOrW6Evf8U01tVPSSMa0xBWBLuksc8hJBI@miUNp6RlgLo809Ud4gA@JW0w@rr6EBhQpC@@PZ1IkyjiLV3NdXVlwiHWQm9i4bcOO4s5U3muckaGkCGhCVDgEWyB8CVE/gDg4joUcSOUyU7cSJqkgEDkF5N9ZHJKx3QECqT2At8VdGcLkpgIOEAGGsCHf9DIgL6kLxBTznjo8Z3dsTcSPNgd10YCkdIgOctZgwaCM8UC2oB/xjAHaimDP/iISxF6wAKhfHEtdfkV98vfTdrU559tY0OhL@ZAwDjDtXNoQLyNtMszqHh2Coa2aPEOHQjhc2BqcgtuKhVTsodlH8AmY2o7FpD3kLzuB8944kxDUfPqXdlL6CoILuMSmZjmTyZABAaGE7HD0eV3PCzmwKMLM@wd6PJqctA147rtedh28OL4CuEDfLZf51AHPh8fjeD0DzHFUn/8gg@tMzju92nRPx6@ZsTa9hZzylIUGDsIoywDMQal4KSMGF@OngxsuVIphmQmPM9Ss1JlFnzwntU9sdi1MHupyYtupzv1ITsmQAp47WOqPaQp3uAIIdt1SVbSNRNndhGZqzJfFe10l9jWmoMJFiOuh@x5rVjL0dGTjd4qZToGLclMb1fk/rn7wTZb1P/ySMeN8@9s7h/V5nFzkHm67SizbYFbPx61LTBlyz8)
To see how this works, let's learn some group theory! First, observe that the entire cuboid structure can be realized as the following shape, tessellated onto the six faces of a cube.
```
.
. .
. . . . .
. . . . .
. .
.
```
Now, in our case, I won't be using just six faces. Because Mario's position doesn't just depend on which face he's on; it also depends on his current orientation (i.e. the direction he's facing). So I'll be using 24 states to represent his current state (24 = 6 faces × 4 orientations). Since this is APL, we'll do the calculation in a massive array. Specifically, we'll use a 24×6×6 array to store every position Mario steps on, and how many times he's been there. So Mario's position at a given moment with be a 3-vector `s y x`, where `s` is the cuboid state (face times orientation) and `y`, `x` are the coordinates within that face.
Now, if Mario is in the middle of a face, then when he moves we simply update the position vector accordingly. So a movement `U` (up) would add `0 ¯1 0` to his position. A movement `R` (right) would add `0 0 1`, etc., etc.
The tricky case comes into play when Mario is at an edge. So if we're here
```
M
. .
. . . . .
. . . . .
. .
.
```
and we move up, what do we do? We end up moving four down (effectively wrapping around) and to some other cuboid state. So if we started as `s y x`, our new position will be `t (y + 4) x`. But what is `t`? To figure that out, we need to look at rotations of a cube.
As I already mentioned, there are 24 rotations of a cube. Let's try to represent the vertices of a cube numerically.
```
5--6
/| /|
1--2 |
| 7|-8
|/ |/
3--4
```
Okay, neat. But that's not all of the information we have. In particular, any rotation of a cube will take opposite vertices to opposite vertices. So, in the above diagram, 1 and 8 are at opposite sides. No matter which way I rotate this cube, 1 and 8 will still be opposites. So we really only have four points we care about, as the other four can be calculates from those.
```
4--3
/| /|
1--2 |
| 2|-1
|/ |/
3--4
```
As it turns out, this is all of the information we need. If we look at the cube head-on so that the above cube looks like
```
1--2
| |
| |
3--4
```
Then every permutation of those four points is a rotation of the cube, and every rotation of the cube can be represented as a permutation of those four points. You can read more about that [on Wikipedia](https://en.wikipedia.org/wiki/Octahedral_symmetry), but the basic idea is that rotations of the cube can be represented using the symmetric group S4, which has 24 elements. We'll represent it this way, since APL has some nice built-in functions to apply permutations.
Now, how does this help us? Well, we wanted to know, given a state `s` and a side of the screen we went off (say, to the right, for this example), what is our new state `t`? If we can enumerate the 24 elements of S4 in a nice order, then `s` is simply some element of that enumeration. Then we figure out what the permutation for "go off the screen to the right" is, and compose the two to get `t`. So, if our cube is
```
5--6
/| /|
1--2 |
| 7|-8
|/ |/
3--4
```
Then, if we go off the screen to the right, we rotate the cube so the face Mario is now on is facing frontward. We get
```
1--5
/| /|
2--6 |
| 3|-7
|/ |/
4--8
```
Remember that we're identifying opposite vertices, so
```
1--4
/| /|
2--3 |
| 3|-2
|/ |/
4--1
```
Looking from the front, we turned a `1 2 3 4` cube into a `2 3 4 1` cube. So our permutation group element is `2 3 4 1`. This works whenever we move right. If we take our current cuboid state (which is an element of S4), and compose it with `2 3 4 1`, we get the new state. A pencil and a bit of effort, and we can calculate the element of S4 representing right, up, left, and down movements.
```
Right 2 3 4 1
Up 4 3 1 2
Left 4 1 2 3
Down 3 4 2 1
* 2 4 1 3
```
That last one (with the `*`) is a rotation of the current face that doesn't change which face Mario is on. So it corresponds to Mario just facing a different direction without walking. In the problem statement, it's not possible for Mario to do that, but we'll need that permutation later for our calculations.
Alright, that should be all the background we need. Let's dig into the code.
```
r←'RULD'
```
Nothing to see here. We use the string `'RULD'` a few times, so it saves us a couple characters to store it.
```
S←{(r⍳⍵)⌷4 4⍴2 3 4 1 4 3 1 2 4,(⍳3),3 4 2 1}
```
`S` is the function which takes R, U, L, or D and converts it to the corresponding permutation we found above.
```
C←{(⊂⍺)⌷⍵}
```
Like I mentioned earlier, APL has nice built-ins for applying permutations. `C` composes two elements of S4. This is how we model multiple steps, like "go right, then go right again".
```
P←,⍉0 1 2 3∘.{2 4 1 3(C⍨⍣⍺)⍵}(⊂⍳4),C\S¨'LUULU'
```
`P` consists of all permutations of `1 2 3 4`, i.e. all elements of the group S4. Let's break it down.
```
(⊂⍳4),C\S¨'LUULU'
```
From the starting orientation, `LUULU` will visit each face of the cube exactly once. So the above expression consists of one permutation representing each face of the cube, ignoring rotations for the moment. We manually tack on the identity `1 2 3 4`, which is our starting state.
```
{2 4 1 3(C⍨⍣⍺)⍵}
```
I mentioned earlier that `2 4 1 3` corresponds to Mario turning his head 90 degrees. We have each face, so we'll want to rotate the faces to get every possible state. This function rotates a face once.
```
0 1 2 3∘.{2 4 1 3(C⍨⍣⍺)⍵}(⊂⍳4),C\S¨'LUULU'
```
Now we rotate every face zero times, once, twice, and thrice, to get every possible permutation.
```
,⍉0 1 2 3∘.{2 4 1 3(C⍨⍣⍺)⍵}(⊂⍳4),C\S¨'LUULU'
```
`⍉` will transpose the result, which gives us the permutations in a nice order (namely, every cube is represented contiguously, by its four rotations in a sequence in the array). Then we ravel `,` the array to get one nice, flat vector of vectors.
```
v←6 6⍴(3⍴0),2(⊥⍣¯1)4512674568
```
`v` is a representation of the below valid positions grid, encoded in base 10 for compactness.
```
0 0 0 1 0 0
0 0 1 1 0 0
1 1 1 1 1 0
0 1 1 1 1 1
0 0 1 1 0 0
0 0 1 0 0 0
```
```
a←1 4 4
```
Mario's starting state. Again, we use this twice, so it's just barely shorter to assign it to a variable.
```
N←{...}
```
`N` is a big one. Given a direction `⍺` (one of the letter RULD) and a position `⍵`, this moves Mario in that direction. Remember, our position is a 3-vector `s y x`, so we'll be moving in 3-dimensional space, where the third dimension is our state space.
```
s y x←⍵+0,(r⍳⍺)⌷4 2⍴0 1 ¯1 0 0 ¯1 1 0
```
In the easy case, we simply shift `y` and `x` and leave `s` alone. This is fine as long as we don't run off the edge. If we don't, then `s y x`, as declared above, is the correct answer. If we do, then we need to do some more work.
```
2 2⍴('U'5 0)('L'0 5)('R'0 ¯5)('D'¯5 0)
```
On the other hand, if we do run off the edge, this tells us what we have to do. In the first case, we shift the cube up and move Mario down 5. In the second case, we shift the cube left and shift Mario to the right 5, and so on.
```
t Y X←⊃(1+(7<y+x)(0<y-x))⌷...
```
To figure out which case we're in, we draw two diagonal lines along the grid as follows
```
\ . /
\ . . /
. . \ / .
. / \ . .
/ . . \
/ . \
```
This partitions our grid space into four sections. The lines are determined by `7<y+x` and `0<y-x`. Then we look up our cases in the previous 2×2 array. Note that if we're in the easy case, then this calculation is pointless but ultimately harmless. We'll determine which case we're in next.
```
(¯2⊖¯2⌽8 8↑4 4⍴1)∨¯1⊖¯1⌽8 8↑v
```
This expression uses `v` above and produces the array below
```
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 1 1 1 1 0 0
0 1 1 1 1 1 0 0
0 0 1 1 1 1 1 0
0 0 1 1 1 1 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0
```
Then, if Mario ends up on a `0`, we need to change cuboid state. If not, then we're good. Note that I include a few "out of bounds" points here where there aren't platforms. This prevents Mario from warping to out of the array bounds if he walks off the edge.
```
(1+y x)⌷(...)
```
Look at Mario's position and see if it's a zero in the above array.
```
⊃(1+(1+y x)⌷(¯2⊖¯2⌽8 8↑4 4⍴1)∨¯1⊖¯1⌽8 8↑v)⌷(...)(s y x)
```
We use the above `0` or `1` to index into our two cases. If it's a `1`, simply return `s y x`. If not, then we have more work to do.
```
(P⍳⊂(⊃s⌷P)C(S t)),(Y X+y x)
```
The Y and X coordinates are simply `y x` added to our shift amount we calculated earlier. As for the new cuboid state, we have our direction `t`. Then `S t` is the permutation, which we compose with our permutation for our current state `⊃s⌷P`, then we convert the permutation back to an index in state space `P⍳⊂`.
```
M←{...}
```
Now, `M` is the final piece. It's the function that, given a sequence of inputs, actually determines whether or not Mario falls. It will return `1` on success and `0` if he falls off.
```
T←24 6 6⍴0
```
Our initial state is a 24×6×6 state space, consisting of all zeroes, since Mario hasn't been anywhere yet.
```
(⊂a),{⊃N/(⌽⍵),⊂a}¨,\⍵
```
Now we take all of the prefixes of our input (`,\⍵`) and we move Mario along those paths (`{⊃N/(⌽⍵),⊂a}¨`). Then we tack on the initial state (`(⊂a),`), since Mario clearly starts off by visiting the initial position. Now we have a vector of all of Mario's positions at every moment.
```
{T[⊂⍵]+←1}¨...
```
For each position Mario ever visits, go to that place in the array `T` and add one to it.
```
(24⍴⍳4){{⊖⍉⍵}⍣⍺⊢⍵}¨⊂[2 3]T
```
We have 24 faces on our "cube". In reality, our cube only has 6 faces. So it's time to account for which faces are rotations of which others. Remember, we enumerated our permutations earlier so that the first four states are rotations of one another, then the next four are rotations of one another, and so on. So we'll take `T` (a 24×6×6 array) and, along the first axis (state space), we rotate. We'll rotate the first 6×6 once, the second twice, the third three times, then four times, then once, then twice, and so on. The actual rotation is done by `{⊖⍉⍵}`, which is a transpose followed by a flip. This corresponds to a 90 degree rotation. Now everything is oriented correctly.
```
+/[2]6 4 6 6⍴↑...
```
Now that everything has the right orientation, we want to add together the faces that are actually the same. So reshape the array to a 6×4×6×6 (where the dimensions are, respectively: face, orientation, y, x). Then we sum along the second axis, which represents orientation, giving us a 6×6×6 array of all of the actual positions on the grid.
```
(6 6 6⍴v)-...
```
`v` tells us which positions Mario is allowed to visit. So we subtract the ones we actually visited from this. If we ever end up with a negative number, that means Mario either went somewhere he shouldn't have or he revisited the same space twice.
```
R←~∨/,0>...
```
See if any positions are less than zero. Then invert the result (since success means they're all greater than zero, and failure means there is one which is less).
And that's all there is to it. If you actually read this dissertation of mine, then congratulations! This is my first APL golf, so I'm sure there's room for improvement. But I enjoyed the opportunity to use a bit of math in my answer as well.
[Answer]
# Ruby, golfed, ~~244~~ 230 bytes
Seems to work fine, will test a bit more.
```
->s{a=[8**8/5]*8
v=[-1,x=d=0,1,0]
y=m=4
s.chars{|c|a[y]&=~(1<<x)
y+=v[e="URDL".index(c)+d&3]
x+=v[e-1]
r= ~0**q=x/4
i=q+x&1
j=q+y&1
y%9>7&&(y=4-i;x+=4-j*11-x%2;d+=r)
x&2>0&&-y/2==-2&&(y=i*7;x+=6-x%2*9+j;d-=r)
m*=1&a[y]>>x%=24}
m}
```
# Ruby, first working version, 260 bytes
[Try it online](https://tio.run/##pVRNb@IwEL37V4xARHyFAou2XbXmlGP2klVOiINJnGARHHAMJOrHX2dtJ9C0ha66HZQwtvPmjd@MLXaL4niMsD3NHgmeDfMfxubdO7RXw7496g/7oznKcYiHqMBrPEHZIFgSkT0@BU9kVswt/NIePTzkHUAUN3zPcRsDxkOat4NOL0R5D@9ntDWZo0J79ovxNzi37DHa4vxm0hqjovVremtZ7dDG2@7YHt0X/RxP7Pa2l3da43570zODQg26o5F6Tzoot8bToWXZxc0YY3us0BpUQbq3GvTTzpV716ugGncf9kqKDlp3sc5/Os2t0TNaPx@bfyRLEiAJ29M@CCp3gsOeJDsKE7TZyQyiWcPR5vraGnNowm8iWAoHkqwyIIFIM/UHC8HCmALhISxIsBqc0Z4yE8B1P6AZV0gpGOFxQl8hrjFD6Gu4dxm4YHFMxQW877qO5vTq@ZrFJVtnNIk0fkMFS2ppqjKax3HNo36@67jvrEznZLXokqyokoHDjgcp31MuWcpJAiLdSToYDIww/0jhLLNmqvzKvTSvc9EC6Y1@5pYDx1HZvlJVm9RCnctTmnPeXjVdfeFVxfBPtan8iqHUz1dTvpYdoaZDSfiup4aoVuNSvko/IiVdb9SSTDVEkED1EmSSboxyEUmSDNIoqhVZledqiFNXqu6mIA8sKDtTx9PNo74gTNR79KTQOVrZZ4qx1tsS5JJCxEQmwYE2i3kqdOACojRJ0gPjcUnRudj@7sf4bw5AbadyqRonXhq@TBIhdWi9mU8OiXcl/Ltj8jUW/4J95FHRTJADKYComIpBDzcJ4VR@jfDaOaxo0YVDbpYuzbtX5r0r82@OyP9cCGUNJM0lBCSjWv8tsAwOIuXxAFJOYa1bxgMShjTUnbpWF4fRY6Uu4u9dR/5303e/G0AJePwL)
Lambda function taking a string argument. Returns 4 for alive, 0 for dead.
```
->s{a=[0x333333]*8
v=[0,-1,0,1]
x=d=0
y=m=4
s.chars{|c|a[y]&=~(1<<x)
e="URDL".index(c)+d
x+=v[e%4]
y+=v[-~e%4]
p=x&-2
q=x/4%2
y%9>7&&(d-=q*2-1;y,x=4-(q+x)%2,(p+4-(q+y)%2*11)%24)
x&2>0&&-y/2==-2&&(y,x=(q+x)%2*7,(p+6-x%2*8+(q+y)%2)%24;d+=q*2-1)
m*=a[y]>>x&1}
m}
```
**Explanation**
The board is unfolded into 6 strips of size 2x8, represented by the `/\` and `O` characters below. These are mapped onto a 24\*8 2D map, where x=(strip number)\*4+(horizontal position on strip) and y=vertical position on strip.
```
Map 4 2 0 Initial state of array a
/ / /
/ / / / / / 1100110011001100110011
/ / / / / / 1100110011001100110011
O / O / O / 1100110011001100110011
O O O O O O 1100110011001100110011
\ / O \ / O \ / X 110011001100110011001X
\ \ / / \ \ / / \ \ / / 1100110011001100110011
\ \ / / \ \ / / \ \ / / 1100110011001100110011
\ O / \ O / \ O / 1100110011001100110011
O O O O O O
O \ O \ O \ X=Mario's start point
\ \ \ \ \ \
\ \ \ \ \ \
\ \ \
5 3 1
```
These are stored in an array of 8 binary numbers, so x increases going left and y increases going down.
The array is intialized with 8 copies of the number `0x33333333`. This forms the squares Mario is allowed to step on. As Mario moves around the square he is on is set to zero, and the square he is moving to is tested - he lives it contains a 1, and dies if it contains a 0.
If Mario walks off the top or bottom of the strip he is on, he moves to another strip. If he walks off the side of the strip he is on, if he is on a square with y=3 or y=4 he moves to another strip. If y is not 3 or 4, he does not move to another strip and ends up on a square which had 0 in it from the outset of the game, so he dies.
Because the camera is always above Mario's head, whenever Mario changes strip, the reference for the directions must be rotated by 90 degrees.
**Ungolfed in test program**
```
f=->s{ #Move sequence is taken as string argument s.
a=[0x333333]*8 #Setup board as an array of 8 copies of 1100110011001100110011.
v=[0,-1,0,1] #Displacements for moving.
x=d=0 #Mario starts at 0,4.
y=m=4 #d=offset for directions. m=4 when Mario is alive (value chosen for golfing reasons) 0 when dead.
s.chars{|c| #For each character c in s
a[y]&=~(1<<x) #Set the square where Mario is to 0.
e="URDL".index(c)+d #Decode the letter and add the offset
x+=v[e%4] #x movement direction is v[e%4]
y+=v[-~e%4] #y movement direction is v[(e+1)%4]
p=x&-2 #p is a copy of x with the last bit set to zero (righthand edge of strip).
q=x/4%2 #q is 0 for an even number strip, 1 for an odd number strip.
y%9>7&&( #If y out of bounds (8 or -1)
d-=q*2-1; #Adjust d so directions will be interpreted correctly on the next move.
y,x=
4-(q+x)%2, #y becomes 3 or 4 depending on the values of q and x.
(p+4-(q+y)%2*11)%24 #If q+y is even, move 1 strip left. if even, move 2 strips right. Take x%24.
)
x&2>0&&-y/2==-2&&( #If x&2>0 Mario has walked sideways off a strip. If y is 3 or 4, move him to a different strip.
y,x=
(q+x)%2*7, #y becomes 0 or 7, depending on the values of q and x.
(p+6-x%2*8+(q+y)%2)%24; #If x%2 is even, move 2 strips left. If odd, move 1 strip right*. Pick the left or right column of the strip depending on (q+y)%2. Take x%24
d+=q*2-1 #Adjust d so directions will be interpreted correctly on the next move.
)
m*=a[y]>>x&1 #Multiply m by the value (0 or 1) of the current square. Mario is either alive (4) or dead (0).
#puts x,y,m,a.map{|i|"%022b"%i}#Uncomment this line for diagnostics.
}
m} #Return value of m.
#Still alive, return value 4
puts f["DDDDDLUUUUU"] # Mario walks across a bridge and back.
puts f["RRRRDDDDLLL"] # Mario walks in a triangle.
puts f["LLLLLLUUUUUURRRRR"] # Mario walks in a bigger triangle.
puts f["ULLDRDDDRU"] # Mario puts himself in peril.
puts f["RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRR"] # Mario takes an unconventional route... and puts himself in peril.
puts f["DDDDLUUUULLLLDDDLUUULLLLDDDDLUUUULLLLDDDLUUULLLURRRUUURDDDRRRRUUURDDDRRRRUUURDDDRRRRUUUUURDDDDD"]
puts f["DLDRDLDLLLDRRRDDDDLLLLLLLLLDRRRRRRRRRDDDDLLLDRRRDDDRUUURRRRULLLLUUUURRRULLLUUUUURDRURDRUURULURU"]
#Dead, return value 0
puts f["LLR"] # Mario attempts to retrace a step and falls off.
puts f["UULDR"] # Mario attempts to cross a tile twice and steps into air.
puts f["RRDDDDD"] # Mario walks off a bridge at the first D (ignore any following steps).
puts f["RRRRDDDDLLLL"] # Mario walks in a triangle and falls through the starting tile.
puts f["LLLLLLUUUUUURRRRRR"] # Mario walks in a bigger triangle and falls through the starting tile.
puts f["UUUUUUUUUUUUUUUUUUUU"] # Mario walks all the way around the planet and falls through the starting tile.
puts f["RURDRURDRDLDRDLDLDLULDLLUU"] #
puts f["ULLDRDDDRUUU"]
puts f["ULLDRDDDRUUL"]
puts f["ULLDRDDDRUUR"]
puts f["ULLDRDDDRUUD"]
puts f["RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRRR"] #text case in q is wrong. one more R added to make the kill.
puts f["RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRU"]
puts f["RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRL"]
puts f["RURDRURDRDLDRDLDLDLULDLLLLLLLLLLLLLLLLURRRRRRRRRRRRRD"]
```
] |
[Question]
[
While bored in high-school (when I was half my current age...), I found that \$f(x) = x^{x^{-1}}\$ had some interesting properties, including e.g. that the maximum \$f\$ for \$0 ≤ x\$ is \$f(e)\$, and that the [binding energy per nucleon](https://commons.wikimedia.org/wiki/File:Binding_energy_curve_-_common_isotopes.svg) of an isotope can be approximated as [\$6 × f(x ÷ 21)\$](http://www.wolframalpha.com/input/?i=Plot%5B6%20(x%2F21)%5E(x%2F21)%5E(-1),%20%7Bx,%200,%20140%7D%5D)...
Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.
## Examples cases
### [For all languages](https://www.wolframalpha.com/input/?i=x%5Ex%5E-1+for+x+from+0+to+5)
```
-1 > -1
¯0.2 > -3125
¯0.5 > 4
0.5 > 0.25
1 > 1
2 > 1.414
e > 1.444
3 > 1.442
100 > 1.047
10000 > 1.001
```
### [For languages that handle complex numbers](https://www.wolframalpha.com/input/?i=x%5Ex%5E-1+for+x+from+-5+to+5)
```
-2 > -0.7071i
i > 4.81
2i > 2.063-0.745i
1+2i > 1.820-0.1834i
2+2i > 1.575-0.1003i
```
### For languages that handle infinities
```
-1/‚àû > 0 (or ‚àû or ÃÉ‚àû)
0 > 0 (or 1 or ‚àû)
1/‚àû > 0
‚àû > 1
-‚àû > 1
```
### For languages that handle both infinities and complex numbers
```
-‚àû-2i > 1 (or ÃÉ‚àû)
```
---
`ÃÉ‚àû` denotes [directed infinity](https://en.wikipedia.org/wiki/Directed_infinity).
[Answer]
# TI-BASIC, 3 bytes
```
Ans√ó‚àöAns
```
TI-BASIC uses tokens, so `Ans` and `√ó‚àö` are both one byte.
### Explanation
`Ans` is the easiest way to give input; it is the result of the last expression. `√ó‚àö` is a function for the x'th root of x, so for example `5√ó‚àö32` is 2.
[Answer]
# Jelly, 2 bytes
```
*İ
```
[Try it online!](http://jelly.tryitonline.net/#code=KsSw&input=&args=Mg)
### How it works
```
*İ Main link. Input: n
İ Inverse; yield 1÷n.
* Power (fork); compute n ** (1√∑n).
```
[Answer]
# Javascript (ES2016), 11 bytes
```
x=>x**(1/x)
```
I rarely ever use ES7 over ES6.
[Answer]
## Python 3, 17 bytes
```
lambda x:x**(1/x)
```
Self-explanatory
[Answer]
# Haskell, ~~12~~ 11 bytes
Thanks @LambdaFairy for doing some magic:
```
(**)<*>(1/)
```
My old version:
```
\x->x**(1/x)
```
[Answer]
# J, 2 bytes
```
^%
```
[Try it online!](https://tio.run/nexus/j#@5@mYGulEKf6PzU5I18hTUEj3lAh3kDPCESYKoCwoYKRgpGeuaGFkYWCsYKhgQEIGxhocsF1GCkYZBkCsZGCIRAbZRlp/gcA).
### How it works
```
^% Monadic verb. Argument: y
% Inverse; yield 1√∑y.
^ Power (hook); compute y ** (1√∑y).
```
[Answer]
## Pyth, 3 bytes
```
@QQ
```
Trivial challenge, trivial solution...
### (noncompeting, 1 byte)
```
@
```
This uses the implicit input feature present in a version of Pyth that postdates this challenge.
[Answer]
# JavaScript ES6, 18 bytes
```
n=>Math.pow(n,1/n)
```
[Answer]
## Java 8, 18 bytes
```
n->Math.pow(n,1/n)
```
Java isn't in last place?!?!
Test with the following:
```
import java.lang.Math;
public class Main {
public static void main (String[] args) {
Test test = n->Math.pow(n,1/n);
System.out.println(test.xthRoot(6.0));
}
}
interface Test {
double xthRoot(double x);
}
```
[Answer]
# R, ~~19~~ 17 bytes
```
function(x)x^x^-1
```
-2 bytes thanks to @Flounderer
[Answer]
# Java, 41 bytes
```
float f(float n){return Math.pow(n,1/n);}
```
Not exactly competitive because Java, but why not?
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 5 bytes
```
t-1^^
```
[**Try it online!**](http://matl.tryitonline.net/#code=dC0xXl4&input=Mmo)
```
t % implicit input x, duplicate
-1 % push -1
^ % power (raise x to -1): gives 1/x
^ % power (raise x to 1/x). Implicit display
```
[Answer]
# Mathematica, ~~8~~ ~~7~~ ~~4~~ 7 bytes
```
#^#^-1&
```
~~More [builtin-only](https://codegolf.stackexchange.com/questions/6228/arithmetic-sequences/74826#74826) answers, and now even shorter!~~ Nope.
~~By definition, the next answer should be 13 bytes. (Fibonacci!)~~ The pattern is still broken. :(
[Answer]
# Perl 5, 10 bytes
9 bytes plus 1 for `-p`
```
$_**=1/$_
```
[Answer]
# Ruby, 15 Bytes
```
a=->n{n**n**-1}
```
Ungolfed:
`->` is the *stabby* lambda operator where `a=->n` is equivalent to `a = lambda {|n|}`
[Answer]
# NARS APL, 2 bytes
```
‚àö‚ç®
```
NARS supports the `‚àö` function, which gives the ‚ç∫-th root of ‚çµ. Applying commute (‚ç®) gives a function that, when used monadically, applies its argument to both sides of the given function. Therefore `‚àö‚ç® x` ‚Üî `x ‚àö x`.
### Other APLs, 3 bytes
```
⊢*÷
```
This is a function train, i.e. `(F G H) x` ↔ `(F x) G H x`. Monadic `⊢` is identity, dyadic `*` is power, and monadic `÷` is inverse. Therefore, `⊢*÷` is *x* raised to 1/*x*.
[Answer]
# Python 2 - 56 bytes
The first actual answer, if I'm correct. Uses Newton's method.
```
n=x=input();exec"x-=(x**n-n)/(1.*n*x**-~n);"*999;print x
```
[Answer]
# CJam, 6 bytes
```
rd_W##
```
[Try it online!](http://cjam.tryitonline.net/#code=cmRfVyMj&input=Mg)
### How it works
```
rd e# Read a double D from STDIN and push it on the stack.
_ e# Push a copy of D.
W e# Push -1.
# e# Compute D ** -1.
# e# Compute D ** (D ** -1).
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 125 bytes
```
15k?ddsk1-A 5^*sw1sn0[A 5^ln+_1^+ln1+dsnlw!<y]syr1<y1lk/*sz[si1[li*li1-dsi0<p]spli0<p]so0dsw[lzlw^lwlox/+lw1+dswA 2^!<b]dsbxp
```
Unlike the other dc answer, this works for *all* real \$x\$ greater than or equal to \$1 (\$1 ≤ x$). Accurate to 4-5 places after the decimal.
I would have included a TIO link here, but for some reason this throws a segmentation fault with the version there (`dc 1.3`) whereas it does *not* with my local version (`dc 1.3.95`).
### Explanation
As **dc** does not support raising numbers to non-integer exponents to calculate \$x^\frac1x\$, this takes advantage of the fact that:
$$x^\frac1x = e^\frac{\ln x}x$$
So, to calculate \$\ln(x)\$, this also takes advantage of the fact that:
$$\int \frac1x dx = \ln(x) + c$$
whose definite integral from \$1\$ to \$b = x\$ is numerically-approximated in increments of \$10^{-5}\$ using the following summation formula:
$$\int\_1^b \frac1x dx = \sum\_{i=1}^{10^{5}(b-1)} \frac 1 {10^5 + i}$$
The resulting sum is then multiplied by \$\frac1x\$ to get \$\frac{\ln(x)}x\$. \$e^{\frac{\ln(x)}x}\$ is then finally calculated using the \$e^x\$ Maclaurin Series to 100 terms as follows:
$$e^x=\sum^{10^2}\_{n=0}\frac{x^n}{n!}$$
This results in our relatively accurate output of \$x^\frac1x\$.
[Answer]
## Seriously, 5 bytes
```
,;ì@^
```
[Try it online!](http://seriously.tryitonline.net/#code=LDvDrEBe&input=NQ)
Explanation:
```
,;ì@^
,; input, dupe
ì@ 1/x, swap
^ pow
```
[Answer]
# [Pylons](https://github.com/morganthrapp/Pylons-lang), 5 bytes.
```
ideAe
```
How it works.
```
i # Get command line input.
d # Duplicate the top of the stack.
e # Raise the top of the stack to the power of the second to the top element of the stack.
A # Push -1 to the stack (pre initialized variable).
e # Raise the top of the stack to the power of the second to the top element of the stack.
# Implicitly print the stack.
```
[Answer]
# Japt, 3 bytes
```
UqU
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VXFV&input=NA==)
Very simple: `U` is the input integer, and `q` is the root function on numbers.
[Answer]
## C++, 48 bytes
```
#include<math.h>
[](auto x){return pow(x,1./x);}
```
The second line defines an anonymous lambda function. It can be used by assigning it to a function pointer and calling it, or just calling it directly.
[Try it online](http://ideone.com/fork/apfznO)
[Answer]
# [Milky Way 1.6.5](https://github.com/zachgates7/Milky-Way), 5 bytes
```
'1'/h
```
---
### Explanation
```
' ` Push input
1 ` Push the integer literal
' ` Push input
/ ` Divide the STOS by the TOS
h ` Push the STOS to the power of the TOS
```
>
> x\*\*(1/x)
>
>
>
---
### Usage
```
$ ./mw <path-to-code> -i <input-integer>
```
[Answer]
## [O](https://github.com/phase/o), 6 bytes
```
j.1\/^
```
No online link because the online IDE doesn't work (specifically, exponentiation is broken)
Explanation:
```
j.1\/^
j. push two copies of input
1\/ push 1/input (always float division)
^ push pow(input, 1/input)
```
[Answer]
# ùîºùïäùïÑùïöùïü, 5 chars / 7 bytes
```
Мű⁽ïï
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=100&code=%D0%9C%C5%B1%E2%81%BD%C3%AF%C3%AF)`
Trivial.
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE/commit/9e0140f09cee5922e3931615c31216eb387738ce) (commit 29), 6 bytes
```
D1_R^^
```
Explanation:
```
D - duplicate top
1_ - load -1
R - rotate
^ - ^**^
^ - ^**^
```
[Answer]
# C# - ~~18~~ ~~43~~ 41 bytes
```
float a(float x){return Math.Pow(x,1/x);}
```
-2 byes thanks to @VoteToClose
[Try it out](https://repl.it/Bp8C/9)
Note:
>
> First actual attempt at golfing - I know I could do this better.
>
>
>
[Answer]
## C, 23 bytes
```
#define p(a)pow(a,1./a)
```
This defines a macro function `p` which evaluates to the `a`th root of `a`.
Thanks to Dennis for reminding me that `gcc` doesn't require `math.h` to be included.
Thanks to @E Ä…™·¥ã·¥õ ú·¥áG·¥è ü“ì·¥á Ä for reminding me that the space after the first `)` is not needed.
[Try it online](http://ideone.com/fork/8FHRht)
[Answer]
# PHP 5.6, ~~32~~ ~~30~~ 29 bytes
```
function($x){echo$x**(1/$x);}
```
or
```
function($x){echo$x**$x**-1;}
```
30->29, thank you Dennis!
] |
[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/2823/edit).
Closed 2 years ago.
[Improve this question](/posts/2823/edit)
Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.
For example given 76543 return 34567
[Answer]
# HTML 21 7 chars (1 char if I'm cheeky...)
```
‮n
```
replace `n` with your number
[Answer]
Python
`int(str(76543)[::-1])`
**EDIT:**
Shorter solution as suggested by @gnibbler:
```
int(`76543`[::-1])
```
or, if above is unclear:
```
x=76543
int(`x`[::-1])
```
[Answer]
**Universal (language *agnostic/independent*)**
If you want to use **only numbers** (avoid converting the number to string) and **don't** want to use some **specific** library (to be universal for any language):
```
x = 76543 # or whatever is your number
y = 0
while x > 0:
y *= 10
y += ( x %10 )
x /= 10 # int division
```
This is python, but it could be done in any language, because it's just a math method.
[Answer]
## Perl 6
```
+$n.flip
```
or:
```
$n.flip
```
for dynamically typed code.
Numbers got string methods due to language design.
[Answer]
# J - 6 characters + variable
```
".|.":y
```
Where y is your value.
[Answer]
## APL (3)
```
⍎⌽⍕
```
Usage:
```
⍎⌽⍕12345 => 54321
```
[Answer]
# Vim
17 chars
```
:se ri<CR>C<C-R>"
```
[Answer]
# PHP, 9 chars
```
(int)strrev(123);
```
To do it short where `N` is a constant:
```
strrev(N)
```
[Answer]
# Befunge (3 characters)
Complete runnable program:
```
N.@
```
Where `N` is your number. Rules say "accept *a single integer* valued argument"; In Befunge you can only enter integers from 0 to 9.
[Answer]
### Language-independent/mathematics
Inspired by Kiril Kirov's answer above. I got curious about the mathematical properties of reversing a number, so I decided to investigate a bit.
Turns out if you plot the difference `n - rev(n)` for natural numbers `n` in some base `r`, you get patterns like this (`(n - rev(n)) / (r - 1)`, for `r=10`, wrapped at `r` columns, red denotes negative number):
![table of differences](https://i.stack.imgur.com/vra3X.png)
This sequence could be generated as such (pseudocode):
```
for i=1 to r:
output 0
for m=0, 1, …
for k=1 to (r-1):
for d=1 to r^m:
for i=0 to (r-1):
output (r-1) * (r+1)^m * (k - i)
```
If you store these values in a list/array, then `n - arr[n]` would get you the reversed form of `n`. Now, to "mathematically golf" this, we'd ideally want a closed-form expression that gives us the n:th value in the sequence, so that we could have a closed-form expression for solving the entire task. Unfortunately, I haven't been able to find such an expression... but it *looks* like it should be possible. :(
So yeah, not so much a code-golf as a mathematical curiosity, but if there is a closed-form expression of the above sequence it might actually be useful in proper PL golf submissions.
[Answer]
# Haskell, ~~28~~ 24 characters
```
f=read.reverse.show.(+0)
```
[Answer]
**Scala - 33 Chars**
```
def r(a:Int)=(a+"").reverse.toInt
```
[Answer]
## Python 3+
### Function form: 28 characters
```
r=lambda i:int(str(i)[::-1])
```
### (Sub)program form: 25 characters
```
print(input()[::-1])
```
I consider some of the other Python examples to be cheating, or at least cheap, due to using hardcoded input and/or not fully satisfying the requirements.
[Answer]
# Ruby (14)
```
x = 13456
x.to_s.reverse
```
[Answer]
It is possible to convert a number a string, then reverse the string and then convert that string back to number. This kind of feature is probably available in all language. If you are looking for a more mathematical method then this might help:
```
int n = 76543;
int r = 0;
while (n > 0) {
r *= 10;
r += n % 10;
n /= 10;
}
```
[Answer]
## Golfscript, 5 chars
```
`-1%~
```
This takes an argument on the stack and leaves the result on the stack. I'm exploiting the "subprogram" option in the spec: if you insist on a function, that's four chars more leaving it on the stack:
```
{`-1%~}:r
```
[Answer]
In shell scripting :
```
echo "your number"|rev
```
Hope this was useful :)
[Answer]
Kinda late but
## APL, 3
```
⍎⌽⍞
```
If you insists on a function
```
⍎∘⌽∘⍕
```
[Answer]
# Mathematica, 14 bytes
```
IntegerReverse
```
This is not competing, because this function was only added in last week's 10.3 release, but for completeness I thought I'd add the only ever (I think?) built-in for this task.
[Answer]
You could do the following in Java. Note that this converts to String and back and is not a mathematical solution.
```
public class test {
public static int reverseInt(int i) {
return Integer.valueOf((new StringBuffer(String.valueOf(i))).reverse().toString());
}
public static void main(String[] args) {
int i = 1234;
System.out.println("reverse("+i+") -> " + reverseInt(i));
}
}
```
[Answer]
Depends on what you mean by short (javascript):
```
alert(String(123).split('').reverse().join('')),
```
[Answer]
# Lua
Numbers and strings are interchangeable, so this is trivial
```
string.reverse(12345)
```
[Answer]
This one *ACTUALLY* takes an input, unlike some of the rest:
```
print`input()`[::-1]
```
Python btw.
[Answer]
## Actionscript
43 characters. num as the parameter to the function:
```
num.toString().split('').reverse().join('')
```
[Answer]
# Groovy
```
r={"$it".reverse() as BigDecimal}
assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543
```
[Answer]
# Perl, 11 chars
The `p` flag is needed for this to work, included in the count.
Usage:
```
$ echo 76543 | perl -pE '$_=reverse'
```
[Answer]
# Clojure (42 chars)
```
#(->> % str reverse(apply str)read-string)
```
Example usage:
```
(#(->> % str reverse(apply str)read-string) 98321)
```
returns 12389
[Answer]
# Common Lisp - 60 chars
```
(first(list(parse-integer(reverse(write-to-string '4279)))))
```
will get you 9724.
[Answer]
# K, 3 bytes:
```
.|$
```
Evaluate (`.`) the reverse (`|`) of casting to a string (`$`).
Usage example:
```
.|$76543
34567
```
[Answer]
# [rs](https://github.com/kirbyfan64/rs), 20 bytes
```
#
+#(.*)(.)/\2#\1
#/
```
Technically, this doesn't count (rs was created earlier this year), but I didn't see any other regex-based answers, and I thought this was neat.
[Live demo.](http://kirbyfan64.github.io/rs/index.html?script=%23%0A%2B%23(.*)(.)%2F%5C2%23%5C1%0A%23%2F&input=34567)
## Explanation:
```
#
```
Insert a pound character at the beginning of the string. This is used as a marker.
```
+#(.*)(.)/\2#\1
```
Continuously prepend the last character of the main string to the area before the marker until there are no characters left.
```
#/
```
Remove the marker.
] |
[Question]
[
# Task
Given one non-whitespace printable character, make a 3x3 square representation of that input. For example, if the input is `#`, then the output is:
```
###
# #
###
```
# Rules
* The output format is strict, although a trailing newline is allowed. It means that the space in the middle is required, and also that the two newline characters separating the three lines are required.
# Testcases
Input: `#`
Output:
```
###
# #
###
```
Input: `A`
Output:
```
AAA
A A
AAA
```
Input: `0`
Output:
```
000
0 0
000
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins.
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 120052; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [Carrot](https://github.com/kritixilithos/Carrot/), 11 bytes
```
###
# #
###
```
[Try it online!](http://kritixilithos.github.io/Carrot/)
The program is in caret-mode, where `#`s are replaced with the input.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~5~~ 3 bytes
```
B³S
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z6JDm9/v2fz/vzIA "Charcoal – TIO Nexus") Edit: Saved 40% thanks to @carusocomputing. Explanation:
```
B Draw a box
³ 3×3 (second dimension is implicit if omitted)
S Using the input character
```
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
lambda s:s+s.join(s+'\n \n'+s)+s
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbFWsXayXlZ@Zp1GsrR6TpxCTp65drKld/L@gKDOvRCFNQ11ZXfM/AA "Python 2 – TIO Nexus")
For `s='a'` : the middle `s+'\n \n'+s` generates `a\n \na` and `s.join` turns it in `a**a**\n**a** **a**\n**a**a` (bold `a`s are the ones that `.join` adds), because `.join` accepts a string as an iterable, then it is surrounded with the two missing characters
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
3Y6*c
```
[Try it online!](https://tio.run/nexus/matl#@28caaaV/P@/uqM6AA "MATL – TIO Nexus")
### Explanation
```
3Y6 % Push predefined literal: [true true true; true false true; true true true]
* % Implicitly input a character. Multiply element-wise by its code point
c % Convert to char. Implicitly display. Char 0 is displayed as space
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
4×ð«û3ô»
```
[Try it online!](https://tio.run/nexus/05ab1e#ARcA6P//MzBiw7tUScOwwqvigKEzw7TCu///WA "05AB1E – TIO Nexus")
```
INPUT # ['R'] | Implicit Input: 'R'
---------#-----------------------+-------------------------------
4× # ['RRRR'] | Repeat string 4 times.
ð # ['RRRR',' '] | Push space onto top of stack.
« # ['RRRR '] | Concatenate last 2 items.
û # ['RRRR RRRR'] | Palindromize.
3ô # [['RRR','R R','RRR']] | Split into 3 pieces.
» # ['RRR\nR R\nRRR'] | Join with newlines
---------#-----------------------+-------------------------------
OUTPUT # RRR | Implicitly print the top
# R R | of the stack on exit.
# RRR |
```
---
Original idea using 30 as a binary number (unfinished, someone else try this in another lang):
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
30bûTIð«‡3ô»
```
[Try it online!](https://tio.run/nexus/05ab1e#ARcA6P//MzBiw7tUScOwwqvigKEzw7TCu///WA "05AB1E – TIO Nexus")
[Answer]
# [Python 3.6](https://docs.python.org/3.6/), 33 bytes
```
lambda c:f'{3*c}\n{c} {c}\n{3*c}'
```
[Try it online!](https://repl.it/HwJ4/2)
[Answer]
## [RPL (Reverse Polish Lisp)](https://en.wikipedia.org/wiki/Reverse_Polish_Lisp "RPL (Reverse Polish Lisp)"), 60 characters
```
→STR 1 4 START DUP NEXT " " + SWAP + 4 ROLLD + + SWAP 2 PICK
```
(Note that "→" is a single character on the HP48 and compatible calculators)
Would visually represent what you want by having three items on the stack:
```
3.: "###"
2.: "# #"
1.: "###"
```
If you insist to return it as one string, one has to add the newline characters as well and combine the strings, left as exercise to the next tester.
[![Input (can be anything, does not need to be a string)](https://i.stack.imgur.com/diYxx.png)](https://i.stack.imgur.com/diYxx.png) [![Entered code](https://i.stack.imgur.com/RTEYY.png)](https://i.stack.imgur.com/RTEYY.png) [![Result](https://i.stack.imgur.com/cz2Zc.png)](https://i.stack.imgur.com/cz2Zc.png)
Explanation:
* `→STR`: Make the last object in the stack into a string. (So the input can be anything, e.g. a number.)
* `1` `4`: Push the number `1` and `4` to the stack.
* `START [...] NEXT`: Like a for loop but without access to the counter variable. Takes two numbers from the stack (here, we just have pushed `1` and `4`) and executes the code `[...]` the corresponding times (here, four times).
* `DUP`: Duplicate the last entry in the stack.
* `" "`: Push the string (i.e. the string with one whitespace) to the stack.
* `+`: Take two objects from the stack and return them added together, for strings: Concatenated.
* `4`: Push the number `4` to the stack.
* `ROLLD`: Takes the last element (here: `4` that we just have pushed) from the stack and rolls the next element as far down the stack as the number we just took from the stack specifies.
* `SWAP`: Swaps the two last stack elements.
* `2`: Push `2` to the stack.
* `PICK`: Takes an element (here: The `2` we just pushed to the stack), interprets it as a number n, and copies the nth element from the stack.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
1 byte thanks to Erik the Outgolfer.
```
x4,`Ks3Y
```
[Try it online!](https://tio.run/nexus/jelly#@19hopPgXWwc@f//f3VldQA "Jelly – TIO Nexus")
[Answer]
# JavaScript, 28 bytes
```
c=>c+c+c+`
${c} ${c}
`+c+c+c
```
---
## Try it
```
f=
c=>c+c+c+`
${c} ${c}
`+c+c+c
o.innerText=f(i.value="#")
i.oninput=_=>o.innerText=f(i.value)
```
```
<input id=i maxlength=1><pre id=o>
```
[Answer]
# Java 7, ~~56~~ 55 bytes
-1 Thanks to Leaky Nun for pointing out the space I missed
```
String a(char s){return"...\n. .\n...".replace('.',s);}
```
Simply replaces the periods with the given character, for input #:
```
... ###
. . => # #
... ###
```
[Try it online!](https://tio.run/nexus/java-openjdk#JYzBCsMgEETP8SuW9KBC2R/IN/SUY5vD1koqGCPuWigh355acpmBeTOT6zMGBy4SM9wopE11@cxYSJp91vCCpREzSglpvk9AZWYLrdmNXxa/4FoFc4NiyOiLtnZQ3a7Og@OcARn3pgJst@KlltQj4iMh/AWxx@JzJOeNRn1lO@zHfvwA)
[Answer]
# PHP, 32 Bytes
```
<?=strtr("000
0 0
000",0,$argn);
```
[Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVJWsuayt/tvY29bXFJUUqShZGBgwGWgAMQGBko6BjpgZZrW//8DAA "PHP – TIO Nexus")
[Answer]
# sed, ~~28~~ 18 bytes
```
s:.:&&&\n& &\n&&&:
```
[Try it online!](https://tio.run/nexus/sed#@19spWelpqYWk6emACLU1Kz@/0/i@pdfUJKZn1f8X7cIAA "sed – TIO Nexus")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~76~~ 70 + 1 = 71 bytes
*Requires the `-c` flag*
```
(((((((({})))<((([])[]{}<>)<>)>)<(<>({})({}){}()()<>)>)<([]()()())>)))
```
[Try it online!](https://tio.run/nexus/brain-flak#@68BBdW1mpqaNkBGdKxmdGx1rY2dJhABCQ0bO5AkCFfXamhqwISjY0EcDU0gR1Pz/3/V/7rJAA "Brain-Flak – TIO Nexus")
[Answer]
# Pyth, 7 bytes
```
jc3.[9d
```
[Try this online.](http://pyth.herokuapp.com/?code=jc3.%5B9d&test_suite=1&test_suite_input=%27%23%27%0A%27A%27%0A%270%27&debug=0)
Explanation:
```
jc3.[9d Expects quoted input.
3 3
9 9
d ' '
Q (eval'd input) as implicit argument
.[ Pad B on both sides with C until its length is a multiple of A
c Split B to chunks of length A, last chunk may be shorter
j Join A on newlines
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
*-1 byte thanks to carusocomputing.*
```
ж¹ðJû
```
Explanation:
```
# Implicit input # ['R']
Ð # Repeat string three times # ['R', 'R', 'R']
¶ # Push newline character # ['R', 'R', 'R', '\n']
¹ # Push first input # ['R', 'R', 'R', '\n', 'R']
ð # Push space # ['R', 'R', 'R', '\n', 'R', ' ']
J # Join stack # ['RRR\nR ']
û # Palindromize ("abc" -> "abcba") # ['RRR\nR R\nRRR']
# Implicit output # []
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f@PD0Q9sO7Ty8wevw7v//EwE "05AB1E – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~61~~, 59 bytes
```
(((((((({})))<([][][]())>)<(([][][]()){})>)<([]()()())>)))
```
[Try it online!](https://tio.run/nexus/brain-flak#@68BBdW1mpqaNhrRsSCooalpB@QgeEBZO7CshiYIAjmamv//q/zXTQYA "Brain-Flak – TIO Nexus")
This is 58 bytes of code `+1` byte for the `-c` flag which enables ASCII input and output.
Explanation:
```
(((
(
(
(
#Duplicate the input 3 times
((({})))
#Push 10 (newline)
<([][][]())>
#Push the input again
)
#Push 32 (space)
<(([][][]()){})>
#Push the input again
)
#Push 10 (newline)
<([]()()())>)
#Push input 3 times
)))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~49~~ 47 bytes
*Saved 2 bytes thanks to 2501!*
```
j;f(i){for(j=12;j;)putchar(--j%4?j-6?i:32:10);}
```
[Try it online!](https://tio.run/nexus/c-gcc#@59lnaaRqVmdll@kkWVraGSdZa1ZUFqSnJFYpKGrm6VqYp@la2afaWVsZGVooGld@z8zr0QhNzEzT0OzmktBQSFNQ91RXdMaynRCMJURTD0Qs/Y/AA "C (gcc) – TIO Nexus") has a trailing newline
[Answer]
# [Python 3](https://docs.python.org/3/), 34 bytes
```
lambda s:s*3+"\n"+s+" "+s+"\n"+s*3
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQbFWsZaytFJOnpF2sraQAJsEcLeP/BUWZeSUaaRrqyuqamlwQHowGijoCRf8DAA "Python 3 – TIO Nexus")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 36 bytes
```
x=repmat(input(0),3);x(5)=32;disp(x)
```
[Try it online!](https://tio.run/nexus/octave#@19hW5RakJtYopGZV1BaomGgqWOsaV2hYappa2xknZJZXKBRofn/v7qDOgA "Octave – TIO Nexus")
### Explanation
This creates a 3x3 char matrix with the input char repeated, and sets its 5th entry in column-major order (i.e. its center) to `32` (ASCII for space).
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 5 bytes
```
dQA.X
```
[Try it online!](https://tio.run/nexus/pyke#@58S6KgX8f9/IAA "Pyke – TIO Nexus")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~27~~ 25 bytes
Saved 2 bytes thanks to Level River St
```
->x{[s=x*3,x+" "+x,s]*$/}
```
[Try it online!](https://tio.run/nexus/ruby#S7T9r2tXUR1dbFuhZaxToa2koKRdoVMcq6WiX/u/KDUxJSczL7VYLzexoLqmuIZLoaC0pFghMbpYr7ikKLMglqv2vzKXI5cBFwA "Ruby – TIO Nexus")
[Answer]
# Brainfuck, 40 bytes
```
+++++[->++<<++++++>],...>.<.<++.>.>.<...
```
[Try it online!](https://tio.run/nexus/brainfuck#@68NAtG6dtraNjZgtrZdrI6enp6dno0eUABIg1h6ev//KwMA "brainfuck – TIO Nexus") *Requires an implementation that can access left of the starting position.*
Also see: [Graviton's brainfuck answer](https://codegolf.stackexchange.com/a/120124/66421) which takes a different approach (but is longer).
---
## Explanation:
Brainfuck can do a lot of cool tricks with its limited instruction set. Unfortunately, this answer doesn't use any of them, because it's cheaper (in terms of bytes) to just hardcode everything.
```
+++++[->++<<++++++>] Sets the cells to |5*6|>0<|5*2|
, Takes input character into the middle cell | 30|>#<| 10|
... Print the top of the square | 30|>#<| 10| ###
>. Print a newline character | 30| # |>10| \n
<. Print another input character | 30|>#<| 10| #
<++. Add 30+2 for a space character and print |>32| # | 10| _
>. And just print the 5 remaining characters | 32|>#<| 10| #
>. | 32| # |>10| \n
<... | 32|>#<| 10| ###
```
# = input character, \_ = space (ASCII 32), \n = newline (ASCII 10)
---
Results in this beautiful box (for input '+'):
```
+++
+ +
+++
```
[Answer]
# Vim, 9 keystrokes
Assuming the input char is present in a buffer, vim makes this straightforward
```
x3pY2plr<space>
```
There is probably some magic vim commands of use here (there always seem to be some) so improvement suggestions are welcome. Only one keystroke behind V!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
jc++K*z4dK3
```
[Try it online!](https://tio.run/##K6gsyfj/PytZW9tbq8okxdv4/38A "Pyth – Try It Online")
**Explanation:**
```
jc++K*z4dK3 expects a single char as input
j joins on new line
c 3 chops array into 3 sized pieces
+ joins +K*z4d and K
+ joins K*z4 and d
K initialize variable K as *z4
*z4 duplicate the input 4 times
d variable initialized to string " "
K calls variable K, in this case *z4
```
[Answer]
# AWK, ~~28~~ ~~26~~ 25 bytes
```
$0=$0$0$0RS$0FS$0RS$0$0$0
```
[Try it online!](https://tio.run/##SyzP/v9fxcBWxQAEg4JVDNyCITQI/v@vDAA "AWK – Try It Online")
[Answer]
# [StupidStackLanguage](https://esolangs.org/wiki/StupidStackLanguage), 28 bytes
```
jfffavvflflqvvvviifblflflfff
```
[Try it online!](https://lebster.xyz/projects/stustala#5f741f9d65b18913fc56acfc "StupidStackLanguage - Try It Online")
## Explanation
```
j # Get the input (x)
fff # first 3
avv # new line
fl # print new line
fl # first x
qvvvviifb # space
lf # second x
lf # new line
lfff # last 3 x's
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~24~~ 23 bytes
```
i:o:o:oao:o84*o:a0!.<o$
```
[Try it online!](https://tio.run/nexus/fish#@59plQ@CiUBsYaKVb5VooKhnk6/y/38gAA "><> – TIO Nexus")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 8 bytes
```
x3p2Ùlr
```
[Try it online!](https://tio.run/nexus/v#@19hXGB0eGZOkcL//8oA "V – TIO Nexus")
[Answer]
# C#,50 bytes
```
a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);
```
Test Case:
```
var f = new Action<string>(
a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);
);
f("#");
```
[Answer]
# Z80 or 8080 Assembly, 21 bytes machine code
Assume a memory mapped I/O device:
```
Z80 8080
3A xx xx ld a, (input) lda input ; get input character
11 0A 20 ld de, 200ah lxi d, 200ah ; space & newline
21 yy yy ld hl, output lxi h, output ; get output address
77 ld (hl), a mov m, a ; output character * 3
77 ld (hl), a mov m, a
77 ld (hl), a mov m, a
73 ld (hl), e mov m, e ; output newline
77 ld (hl), a mov m, a ; output character
72 ld (hl), d mov m, d ; output space
77 ld (hl), a mov m, a ; output character
73 ld (hl), e mov m, e ; output newline
77 ld (hl), a mov m, a ; output character * 3
77 ld (hl), a mov m, a
77 ld (hl), a mov m, a
76 halt hlt ; or C9 ret
```
No interpreter needed!
Hexdump:
```
0000: 3A 00 FF 11 0A 20 21 01 FF 77 77 77 73 77 72 77
0010: 73 77 77 77 76
```
where the input address is at FF00h and the output address is mapped at FF01h. The actual addresses will depend on the actual hardware. Of course this assumes the I/O is memory mapped. If it is I/O mapped, it would take several extra bytes because Z80 & 8080 I/O instructions are two bytes each. This also assumes the output device interprets 0Ah as a newline and doesn't require a CR (0Dh) which would add an extra 4 bytes to the program.
] |